@aviaratech/ai-delivery 0.3.34 → 0.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -477
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,1875 +1,2506 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync } from 'node:child_process';
3
- import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join, resolve } from 'node:path';
6
- import { afterEach, describe, it, vi } from 'vitest';
7
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
- import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
9
- import * as settings from './config/deliveryConfig.js';
10
- import * as github from './github/client.js';
11
- import { digestValue } from './delivery/common.js';
12
- import { DeliveryError, setMachineRequestDiagnostics } from './errors.js';
13
- import { executeTool } from './dispatch.js';
14
- import * as issues from './issue.js';
15
- import { createAiDeliveryMcpServer } from './mcp/index.js';
16
- import { preflightReviewRoute, prInfo, publishPr, startIssueBranch, submitFormalReview } from './pr.js';
17
- const repo = 'example/widget';
18
- const head = 'a'.repeat(40);
19
- const base = 'b'.repeat(40);
20
- const tree = 'c'.repeat(40);
1
+ import { syntheticDiscoveryClients, syntheticDiscoveryConfig } from "./fixtures/discovery.js";
2
+ import { issueProjectItemsResponse } from "./fixtures/issueProjectItems.js";
3
+ import { quietReadViewResponse } from "./fixtures/readView.js";
4
+ import assert from "node:assert/strict";
5
+ import { execFileSync } from "node:child_process";
6
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join, resolve } from "node:path";
9
+ import { afterEach, describe, expect, it, vi } from "vitest";
10
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
12
+ import * as settings from "./config/deliveryConfig.js";
13
+ import * as github from "./github/client.js";
14
+ import { digestValue } from "./delivery/common.js";
15
+ import { DeliveryError, setMachineRequestDiagnostics } from "./errors.js";
16
+ import { executeTool } from "./dispatch.js";
17
+ import * as issues from "./issue.js";
18
+ import { createAiDeliveryMcpServer } from "./mcp/index.js";
19
+ import { preflightReviewRoute, prInfo, publishPr, startIssueBranch, submitFormalReview } from "./pr.js";
20
+ const repo = "example/widget";
21
+ const head = "a".repeat(40);
22
+ const base = "b".repeat(40);
23
+ const tree = "c".repeat(40);
21
24
  const pageInfo = { hasNextPage: false, endCursor: null };
25
+ const nonClosingCreation = {
26
+ issueNumber: 17,
27
+ nonClosing: true,
28
+ reconcileNonClosingReference: true,
29
+ expectedHeadSha: head,
30
+ expectedBaseSha: base,
31
+ body: `References ${repo}#17
32
+
33
+ Improve widget.`
34
+ };
22
35
  function fixture(published = true, nonClosing = false) {
23
- const state = {
24
- published,
25
- nonClosing,
26
- body: nonClosing ? `References ${repo}#17\n\nImprove widget.` : 'Closes #17',
27
- title: 'Improve widget',
28
- issueBody: 'Four retained criteria',
29
- issueState: 'open',
30
- referenceReadback: undefined,
31
- referencePages: [],
32
- referencePageIndex: 0,
33
- commitReadback: undefined,
34
- comparisonReadback: undefined,
35
- commitMessage: 'Improve widget',
36
- referenceActor: 'author',
37
- referenceCloses: false,
38
- updates: 0,
39
- failCreateAck: false,
40
- failUpdateAck: false,
41
- linked: false,
42
- remoteHead: published ? head : base,
43
- headSha: head,
44
- headRef: 'issue/17',
45
- headRepo: repo,
46
- baseRepo: repo,
47
- baseSha: base,
48
- baseRef: 'main',
49
- nodeId: 'PR23',
50
- prAuthor: 'author',
51
- prState: 'open',
52
- merged: false,
53
- draft: true,
54
- remoteRef: 'refs/heads/issue/17',
55
- remoteType: 'commit',
56
- issueNumber: 17,
57
- associationRepo: repo,
58
- associationPr: 23,
59
- closingReadback: undefined,
60
- closingPages: [],
61
- closingPageIndex: 0,
62
- branchReadback: undefined,
63
- reviewerActor: 'reviewer[bot]',
64
- movedOnRead: 0,
65
- reads: 0,
66
- readHook: undefined,
67
- matchReadback: undefined,
68
- promotionReadback: undefined,
69
- keepDraftOnPromotion: false,
70
- promotions: 0,
71
- creations: 0,
72
- expectedCreationDraft: true,
73
- events: [],
74
- reviews: [],
75
- submissions: 0,
76
- };
77
- const pr = () => ({
78
- number: 23,
79
- node_id: state.nodeId,
80
- changed_files: 1,
81
- title: state.title,
82
- body: state.body,
83
- html_url: `https://github.com/${repo}/pull/23`,
84
- state: state.prState,
85
- draft: state.draft,
86
- merged: state.merged,
87
- head: { sha: state.headSha, ref: state.headRef, repo: { full_name: state.headRepo } },
88
- base: { sha: state.baseSha, ref: state.baseRef, repo: { full_name: state.baseRepo } },
89
- user: { login: state.prAuthor },
90
- });
91
- const rest = {
92
- request: async () => ({ data: [] }),
93
- repos: {
94
- get: async () => ({ data: { node_id: 'REPO', full_name: repo, default_branch: 'main' } }),
95
- compareCommitsWithBasehead: async () => ({
96
- data: state.comparisonReadback ?? {
97
- base_commit: { sha: base },
98
- merge_base_commit: { sha: base },
99
- status: 'ahead',
100
- total_commits: 1,
101
- commits: [{ sha: head, commit: { message: state.commitMessage }, parents: [{ sha: base }] }],
102
- },
103
- }),
104
- },
105
- issues: {
106
- get: async () => ({
107
- data: {
108
- node_id: 'ISSUE17',
36
+ const state = {
37
+ published,
38
+ nonClosing,
39
+ body: nonClosing ? `References ${repo}#17
40
+
41
+ Improve widget.` : "Closes #17",
42
+ title: "Improve widget",
43
+ issueBody: "Four retained criteria",
44
+ issueState: "open",
45
+ referenceReadback: void 0,
46
+ referencePages: [],
47
+ referencePageIndex: 0,
48
+ commitReadback: void 0,
49
+ comparisonReadback: void 0,
50
+ commitMessage: "Improve widget",
51
+ referenceActor: "author",
52
+ referenceCloses: false,
53
+ updates: 0,
54
+ failCreateAck: false,
55
+ failUpdateAck: false,
56
+ linked: false,
57
+ remoteHead: published ? head : base,
58
+ headSha: head,
59
+ headRef: "issue/17",
60
+ headRepo: repo,
61
+ baseRepo: repo,
62
+ baseSha: base,
63
+ baseRef: "main",
64
+ remoteBase: { ref: "refs/heads/main", object: { type: "commit", sha: base } },
65
+ nodeId: "PR23",
66
+ prAuthor: "author",
67
+ prState: "open",
68
+ merged: false,
69
+ draft: true,
70
+ remoteRef: "refs/heads/issue/17",
71
+ remoteType: "commit",
72
+ issueNumber: 17,
73
+ associationRepo: repo,
74
+ associationPr: 23,
75
+ closingReadback: void 0,
76
+ closingPages: [],
77
+ closingPageIndex: 0,
78
+ closingOnCreate: false,
79
+ manualClosing: false,
80
+ manualReadback: void 0,
81
+ manualPages: [],
82
+ manualPageIndex: 0,
83
+ removals: 0,
84
+ failRemovalAck: false,
85
+ removalReadback: void 0,
86
+ keepClosingOnRemoval: false,
87
+ removalHook: void 0,
88
+ branchReadback: void 0,
89
+ reviewerActor: "reviewer[bot]",
90
+ movedOnRead: 0,
91
+ reads: 0,
92
+ readHook: void 0,
93
+ matchReadback: void 0,
94
+ promotionReadback: void 0,
95
+ keepDraftOnPromotion: false,
96
+ promotions: 0,
97
+ creations: 0,
98
+ expectedCreationDraft: true,
99
+ events: [],
100
+ reviews: [],
101
+ submissions: 0
102
+ };
103
+ const pr = () => ({
104
+ number: 23,
105
+ node_id: state.nodeId,
106
+ changed_files: 1,
107
+ title: state.title,
108
+ body: state.body,
109
+ html_url: `https://github.com/${repo}/pull/23`,
110
+ state: state.prState,
111
+ draft: state.draft,
112
+ merged: state.merged,
113
+ head: { sha: state.headSha, ref: state.headRef, repo: { full_name: state.headRepo } },
114
+ base: { sha: state.baseSha, ref: state.baseRef, repo: { full_name: state.baseRepo } },
115
+ user: { login: state.prAuthor }
116
+ });
117
+ const rest = {
118
+ request: async () => ({ data: [] }),
119
+ repos: {
120
+ get: async () => ({ data: { node_id: "REPO", full_name: repo, default_branch: "main" } }),
121
+ compareCommitsWithBasehead: async () => ({
122
+ data: state.comparisonReadback ?? {
123
+ base_commit: { sha: base },
124
+ merge_base_commit: { sha: base },
125
+ status: "ahead",
126
+ total_commits: 1,
127
+ commits: [{ sha: head, commit: { message: state.commitMessage }, parents: [{ sha: base }] }]
128
+ }
129
+ })
130
+ },
131
+ issues: {
132
+ get: async () => ({
133
+ data: {
134
+ node_id: "ISSUE17",
135
+ number: 17,
136
+ state: state.issueState,
137
+ title: "Improve widget",
138
+ body: state.issueBody,
139
+ html_url: `https://github.com/${repo}/issues/17`
140
+ }
141
+ })
142
+ },
143
+ git: {
144
+ getRef: async (input) => {
145
+ assert.equal(`${input.owner}/${input.repo}`, repo);
146
+ return {
147
+ data: input.ref === "heads/main" ? state.remoteBase : { ref: state.remoteRef, object: { type: state.remoteType, sha: state.remoteHead } }
148
+ };
149
+ },
150
+ getCommit: async () => ({ data: { sha: head, tree: { sha: tree } } })
151
+ },
152
+ pulls: {
153
+ get: async () => {
154
+ state.reads++;
155
+ state.readHook?.(state.reads);
156
+ if (state.movedOnRead && state.reads >= state.movedOnRead) state.headSha = "d".repeat(40);
157
+ return { data: pr() };
158
+ },
159
+ list: async () => ({ data: state.matchReadback ?? (state.published ? [{ number: 23 }] : []) }),
160
+ create: async (input) => {
161
+ assert.equal(input.draft, state.expectedCreationDraft);
162
+ assert.equal(input.head, "issue/17");
163
+ state.creations++;
164
+ state.body = input.body;
165
+ if (state.closingOnCreate) {
166
+ state.manualClosing = true;
167
+ state.referenceCloses = true;
168
+ }
169
+ if (state.failCreateAck) {
170
+ state.published = true;
171
+ throw new Error("Transport lost after creation");
172
+ }
173
+ state.draft = input.draft;
174
+ state.published = true;
175
+ state.linked = false;
176
+ state.events.push("draft-publication-replaces-branch-link");
177
+ return { data: pr() };
178
+ },
179
+ update: async (input) => {
180
+ state.updates++;
181
+ state.body = input.body;
182
+ state.nonClosing = input.body.startsWith("References ");
183
+ if (state.failUpdateAck) throw new Error("Transport lost after body update");
184
+ return { data: pr() };
185
+ },
186
+ listFiles: async () => ({ data: [{ filename: "change.ts" }] }),
187
+ listReviews: async () => ({ data: state.reviews }),
188
+ getReview: async (input) => ({
189
+ data: state.reviews.find((review) => review.id === input.review_id)
190
+ }),
191
+ createReview: async (input) => {
192
+ assert.equal(input.commit_id, head);
193
+ assert.equal(input.event, "APPROVE");
194
+ state.submissions++;
195
+ const review = {
196
+ id: 98 + state.submissions,
197
+ body: input.body,
198
+ user: { login: state.reviewerActor },
199
+ state: "APPROVED",
200
+ commit_id: head,
201
+ html_url: `https://github.com/${repo}/pull/23#pullrequestreview-${98 + state.submissions}`
202
+ };
203
+ state.reviews.push(review);
204
+ return { data: review };
205
+ }
206
+ }
207
+ };
208
+ const graphql = async (query, variables = {}) => {
209
+ if (query.includes("DeliveryRemoveClosingReference")) {
210
+ assert.deepEqual(variables.issueId, "ISSUE17");
211
+ assert.deepEqual(variables.pullRequestIds, ["PR23"]);
212
+ assert.equal(typeof variables.clientMutationId, "string");
213
+ state.removals++;
214
+ state.events.push("remove-exact-closing-pair");
215
+ if (!state.keepClosingOnRemoval) {
216
+ state.manualClosing = false;
217
+ state.referenceCloses = false;
218
+ }
219
+ state.removalHook?.();
220
+ if (state.failRemovalAck) throw new Error("Lost reference-removal acknowledgement");
221
+ return state.removalReadback ?? { removeCloseIssueReferences: { issue: { id: "ISSUE17" } } };
222
+ }
223
+ if (query.includes("DeliveryNonClosingReferences")) {
224
+ if (state.referencePages.length) return state.referencePages[state.referencePageIndex++];
225
+ return state.referenceReadback ?? {
226
+ repository: {
227
+ id: "REPO",
228
+ nameWithOwner: repo,
229
+ issue: {
230
+ id: "ISSUE17",
231
+ number: 17,
232
+ state: "OPEN",
233
+ timelineItems: {
234
+ nodes: [
235
+ {
236
+ id: "REFERENCE",
237
+ actor: { login: state.referenceActor },
238
+ isCrossRepository: false,
239
+ willCloseTarget: state.referenceCloses,
240
+ source: {
241
+ __typename: "PullRequest",
242
+ id: "PR23",
243
+ number: 23,
244
+ repository: { id: "REPO", nameWithOwner: repo }
245
+ },
246
+ target: {
247
+ __typename: "Issue",
248
+ id: "ISSUE17",
109
249
  number: 17,
110
- state: state.issueState,
111
- title: 'Improve widget',
112
- body: state.issueBody,
113
- html_url: `https://github.com/${repo}/issues/17`,
114
- },
115
- }),
116
- },
117
- git: {
118
- getRef: async (input) => {
119
- assert.equal(`${input.owner}/${input.repo}`, repo);
120
- return {
121
- data: {
122
- ref: input.ref === 'heads/main' ? 'refs/heads/main' : state.remoteRef,
123
- object: { type: state.remoteType, sha: input.ref === 'heads/main' ? base : state.remoteHead },
124
- },
125
- };
126
- },
127
- getCommit: async () => ({ data: { sha: head, tree: { sha: tree } } }),
128
- },
129
- pulls: {
130
- get: async () => {
131
- state.reads++;
132
- state.readHook?.(state.reads);
133
- if (state.movedOnRead && state.reads >= state.movedOnRead)
134
- state.headSha = 'd'.repeat(40);
135
- return { data: pr() };
136
- },
137
- list: async () => ({ data: state.matchReadback ?? (state.published ? [{ number: 23 }] : []) }),
138
- create: async (input) => {
139
- assert.equal(input.draft, state.expectedCreationDraft);
140
- assert.equal(input.head, 'issue/17');
141
- state.creations++;
142
- state.body = input.body;
143
- if (state.failCreateAck) {
144
- state.published = true;
145
- throw new Error('Transport lost after creation');
250
+ repository: { id: "REPO", nameWithOwner: repo }
251
+ }
146
252
  }
147
- state.draft = input.draft;
148
- state.published = true;
149
- state.linked = false;
150
- state.events.push('draft-publication-replaces-branch-link');
151
- return { data: pr() };
152
- },
153
- update: async (input) => {
154
- state.updates++;
155
- state.body = input.body;
156
- state.nonClosing = true;
157
- if (state.failUpdateAck)
158
- throw new Error('Transport lost after body update');
159
- return { data: pr() };
160
- },
161
- listFiles: async () => ({ data: [{ filename: 'change.ts' }] }),
162
- listReviews: async () => ({ data: state.reviews }),
163
- getReview: async (input) => ({
164
- data: state.reviews.find((review) => review.id === input.review_id),
165
- }),
166
- createReview: async (input) => {
167
- assert.equal(input.commit_id, head);
168
- assert.equal(input.event, 'APPROVE');
169
- state.submissions++;
170
- const review = {
171
- id: 98 + state.submissions,
172
- body: input.body,
173
- user: { login: state.reviewerActor },
174
- state: 'APPROVED',
175
- commit_id: head,
176
- html_url: `https://github.com/${repo}/pull/23#pullrequestreview-${98 + state.submissions}`,
177
- };
178
- state.reviews.push(review);
179
- return { data: review };
180
- },
181
- },
182
- };
183
- const graphql = async (query) => {
184
- if (query.includes('DeliveryNonClosingReferences')) {
185
- if (state.referencePages.length)
186
- return state.referencePages[state.referencePageIndex++];
187
- return (state.referenceReadback ?? {
188
- repository: {
189
- id: 'REPO',
190
- nameWithOwner: repo,
191
- issue: {
192
- id: 'ISSUE17',
193
- number: 17,
194
- state: 'OPEN',
195
- timelineItems: {
196
- nodes: [
197
- {
198
- id: 'REFERENCE',
199
- actor: { login: state.referenceActor },
200
- isCrossRepository: false,
201
- willCloseTarget: state.referenceCloses,
202
- source: {
203
- __typename: 'PullRequest',
204
- id: 'PR23',
205
- number: 23,
206
- repository: { id: 'REPO', nameWithOwner: repo },
207
- },
208
- target: {
209
- __typename: 'Issue',
210
- id: 'ISSUE17',
211
- number: 17,
212
- repository: { id: 'REPO', nameWithOwner: repo },
213
- },
214
- },
215
- ],
216
- pageInfo,
217
- },
218
- },
219
- },
220
- });
253
+ ],
254
+ pageInfo
255
+ }
256
+ }
221
257
  }
222
- if (query.includes('DeliveryNonClosingCommits'))
223
- return (state.commitReadback ?? {
224
- repository: {
225
- nameWithOwner: repo,
226
- pullRequest: {
227
- id: 'PR23',
228
- number: 23,
229
- headRefOid: head,
230
- baseRefOid: base,
231
- baseRefName: 'main',
232
- commits: {
233
- totalCount: 1,
234
- nodes: [
235
- {
236
- commit: {
237
- oid: head,
238
- message: state.commitMessage,
239
- parents: { totalCount: 1, nodes: [{ oid: base }], pageInfo },
240
- },
241
- },
242
- ],
243
- pageInfo,
244
- },
245
- },
246
- },
247
- });
248
- if (query.includes('DeliveryStartBranch')) {
249
- state.linked = true;
250
- state.events.push('native-start');
251
- return { createLinkedBranch: { linkedBranch: { ref: { name: 'issue/17', target: { oid: base } } } } };
258
+ };
259
+ }
260
+ if (query.includes("DeliveryNonClosingCommits"))
261
+ return state.commitReadback ?? {
262
+ repository: {
263
+ nameWithOwner: repo,
264
+ pullRequest: {
265
+ id: "PR23",
266
+ number: 23,
267
+ headRefOid: head,
268
+ baseRefOid: base,
269
+ baseRefName: "main",
270
+ commits: {
271
+ totalCount: 1,
272
+ nodes: [
273
+ {
274
+ commit: {
275
+ oid: head,
276
+ message: state.commitMessage,
277
+ parents: { totalCount: 1, nodes: [{ oid: base }], pageInfo }
278
+ }
279
+ }
280
+ ],
281
+ pageInfo
282
+ }
283
+ }
252
284
  }
253
- if (query.includes('DeliveryIssueBranches'))
254
- return (state.branchReadback ?? {
255
- repository: {
256
- issue: {
257
- linkedBranches: {
258
- nodes: state.linked
259
- ? [
260
- {
261
- ref: {
262
- name: 'issue/17',
263
- target: { oid: state.remoteHead },
264
- repository: { nameWithOwner: repo },
265
- },
266
- },
267
- ]
268
- : [],
269
- pageInfo,
270
- },
271
- },
272
- },
273
- });
274
- if (query.includes('DeliveryClosingIssues') && state.closingPages.length > 0)
275
- return state.closingPages[state.closingPageIndex++];
276
- if (query.includes('DeliveryClosingIssues'))
277
- return (state.closingReadback ?? {
278
- repository: {
279
- nameWithOwner: state.associationRepo,
280
- pullRequest: {
281
- id: state.nodeId,
282
- number: state.associationPr,
283
- closingIssuesReferences: {
284
- nodes: state.nonClosing
285
- ? []
286
- : [
287
- {
288
- __typename: 'Issue',
289
- id: 'ISSUE17',
290
- number: state.issueNumber,
291
- repository: { id: 'REPO', nameWithOwner: repo },
292
- },
293
- ],
294
- pageInfo,
295
- },
296
- },
297
- },
298
- });
299
- if (query.includes('DeliveryReadyPr')) {
300
- state.promotions++;
301
- if (!state.keepDraftOnPromotion)
302
- state.draft = false;
303
- return (state.promotionReadback ?? { markPullRequestReadyForReview: { pullRequest: { id: 'PR23', isDraft: false } } });
285
+ };
286
+ if (query.includes("DeliveryStartBranch")) {
287
+ state.linked = true;
288
+ state.events.push("native-start");
289
+ return { createLinkedBranch: { linkedBranch: { ref: { name: "issue/17", target: { oid: base } } } } };
290
+ }
291
+ if (query.includes("DeliveryIssueBranches"))
292
+ return state.branchReadback ?? {
293
+ repository: {
294
+ issue: {
295
+ linkedBranches: {
296
+ nodes: state.linked ? [
297
+ {
298
+ ref: {
299
+ name: "issue/17",
300
+ target: { oid: state.remoteHead },
301
+ repository: { nameWithOwner: repo }
302
+ }
303
+ }
304
+ ] : [],
305
+ pageInfo
306
+ }
307
+ }
304
308
  }
305
- throw new Error(`Unexpected synthetic query: ${query}`);
306
- };
307
- const reviewer = {
308
- role: 'reviewer',
309
- authSource: 'app',
310
- effectiveContentsPermission: 'write',
311
- appActorLogin: async () => state.reviewerActor,
312
- rest,
313
- graphql,
314
- };
315
- const context = {
316
- root: '/nonexistent-launch-directory',
317
- repo: { owner: 'example', repo: 'widget' },
318
- config: {
319
- schemaVersion: 'ai-delivery.github@1',
320
- repository: repo,
321
- roles: { author: { authSource: 'personal', identity: 'author' }, reviewer: { identity: 'reviewer' } },
322
- },
323
- clients: {
324
- role: 'author',
325
- authSource: 'personal',
326
- authenticatedAuthor: async () => ({ actorLogin: 'author', credentialIdentity: 'synthetic-author' }),
327
- rest,
328
- graphql,
329
- },
330
- reviewerClients: reviewer,
331
- };
332
- const content = {
333
- schemaVersion: 'ai-delivery.review-artifact@1',
334
- authorIdentity: 'author',
335
- reviewerIdentity: 'reviewer',
336
- checks: ['Synthetic exact-head checks'],
337
- diffScopeHash: digestValue(['change.ts']),
338
- elapsedMs: 1,
339
- findings: [],
340
- head: { sha: head, tree },
341
- issueNumber: 17,
342
- prNumber: 23,
343
- readOnly: true,
344
- requestedEffort: 'xhigh',
345
- requestedModel: 'gpt-6-astra',
346
- effectiveEffort: 'unknown',
347
- effectiveModel: 'unknown',
348
- summary: 'Synthetic independent review.',
349
- verdict: 'approve',
350
- };
351
- const artifact = JSON.stringify({ ...content, artifactId: digestValue(content) });
352
- return { state, context, reviewerContext: { ...context, clients: reviewer }, artifact };
309
+ };
310
+ const manual = query.includes("userLinkedOnly");
311
+ if (query.includes("DeliveryClosingIssues") && manual && state.manualPages.length > 0)
312
+ return state.manualPages[state.manualPageIndex++ % state.manualPages.length];
313
+ if (query.includes("DeliveryClosingIssues") && manual && state.manualReadback !== void 0)
314
+ return state.manualReadback;
315
+ if (query.includes("DeliveryClosingIssues") && !manual && state.closingPages.length > 0)
316
+ return state.closingPages[state.closingPageIndex++];
317
+ if (query.includes("DeliveryClosingIssues"))
318
+ return (manual ? void 0 : state.closingReadback) ?? {
319
+ repository: {
320
+ nameWithOwner: state.associationRepo,
321
+ pullRequest: {
322
+ id: state.nodeId,
323
+ number: state.associationPr,
324
+ closingIssuesReferences: {
325
+ nodes: (manual ? !state.manualClosing : state.nonClosing && !state.manualClosing) ? [] : [
326
+ {
327
+ __typename: "Issue",
328
+ id: "ISSUE17",
329
+ number: state.issueNumber,
330
+ repository: { id: "REPO", nameWithOwner: repo }
331
+ }
332
+ ],
333
+ pageInfo
334
+ }
335
+ }
336
+ }
337
+ };
338
+ if (query.includes("DeliveryReadyPr")) {
339
+ state.promotions++;
340
+ if (!state.keepDraftOnPromotion) state.draft = false;
341
+ return state.promotionReadback ?? { markPullRequestReadyForReview: { pullRequest: { id: "PR23", isDraft: false } } };
342
+ }
343
+ if (query.includes("ProjectDeliveryIssueItems")) return issueProjectItemsResponse(variables, []);
344
+ if (query.includes("ProjectDeliveryConfiguration")) return syntheticDiscoveryClients().graphql(query, variables);
345
+ const quiet = quietReadViewResponse(query, variables);
346
+ if (quiet !== void 0) return quiet;
347
+ throw new Error(`Unexpected synthetic query: ${query}`);
348
+ };
349
+ const reviewer = {
350
+ role: "reviewer",
351
+ authSource: "app",
352
+ effectiveContentsPermission: "write",
353
+ appActorLogin: async () => state.reviewerActor,
354
+ rest,
355
+ graphql
356
+ };
357
+ const context = {
358
+ root: "/nonexistent-launch-directory",
359
+ repo: { owner: "example", repo: "widget" },
360
+ config: {
361
+ schemaVersion: "ai-delivery.github@1",
362
+ repository: repo,
363
+ roles: { author: { authSource: "personal", identity: "author" }, reviewer: { identity: "reviewer" } },
364
+ native: syntheticDiscoveryConfig.native
365
+ },
366
+ clients: {
367
+ role: "author",
368
+ authSource: "personal",
369
+ authenticatedAuthor: async () => ({ actorLogin: "author", credentialIdentity: "synthetic-author" }),
370
+ rest,
371
+ graphql
372
+ },
373
+ reviewerClients: reviewer
374
+ };
375
+ const content = {
376
+ schemaVersion: "ai-delivery.review-artifact@1",
377
+ authorIdentity: "author",
378
+ reviewerIdentity: "reviewer",
379
+ checks: ["Synthetic exact-head checks"],
380
+ diffScopeHash: digestValue(["change.ts"]),
381
+ elapsedMs: 1,
382
+ findings: [],
383
+ head: { sha: head, tree },
384
+ issueNumber: 17,
385
+ prNumber: 23,
386
+ readOnly: true,
387
+ requestedEffort: "xhigh",
388
+ requestedModel: "gpt-6-astra",
389
+ effectiveEffort: "unknown",
390
+ effectiveModel: "unknown",
391
+ summary: "Synthetic independent review.",
392
+ verdict: "approve"
393
+ };
394
+ const artifact = JSON.stringify({ ...content, artifactId: digestValue(content) });
395
+ return { state, context, reviewerContext: { ...context, clients: reviewer }, artifact };
353
396
  }
354
397
  afterEach(() => vi.restoreAllMocks());
398
+ it("publishes a pushed canonical branch without native creation and preserves the open issue", async () => {
399
+ const { context, state } = fixture(false, true);
400
+ state.remoteHead = head;
401
+ await publishPr(context, nonClosingCreation);
402
+ assert.equal(state.creations, 1);
403
+ assert.equal(state.issueState, "open");
404
+ state.issueState = "closed";
405
+ await assert.rejects(issues.issueBranch(context, 17), /open|OPEN/u);
406
+ await assert.rejects(issues.issueBranch(context, 17, "issue/18"), /Branch issue\/18 is not linked/u);
407
+ });
408
+ it("accepts a hyphenated close mention while refusing an actual closing directive", async () => {
409
+ const { context, state } = fixture(true, true);
410
+ state.title = "absent-close (#3777)";
411
+ await publishPr(context, { issueNumber: 17, nonClosing: true, prNumber: 23, draft: false });
412
+ state.title = "closes #3777";
413
+ await assert.rejects(
414
+ publishPr(context, { issueNumber: 17, nonClosing: true, prNumber: 23, draft: false }),
415
+ /closing directives/u
416
+ );
417
+ });
418
+ describe("remote closing PR creation", () => {
419
+ it("replays a plain-git head from a temporary non-git directory through the public tool", async () => {
420
+ const { context, state } = fixture(false);
421
+ state.remoteHead = head;
422
+ state.issueBody = "## Outcome\n\nWidgets improve.\n\n## Acceptance criteria\n\n- [ ] Reject invalid widgets.\n Verified by: A synthetic widget test.";
423
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "delivery-pr-open-")));
424
+ vi.spyOn(settings, "loadDeliverySettings").mockResolvedValue(
425
+ context.config
426
+ );
427
+ vi.spyOn(issues, "loadDeliveryContext").mockImplementation(async (input) => {
428
+ assert.equal(input.repository, repo);
429
+ assert.equal(input.repoRoot, root);
430
+ return { ...context, root };
431
+ });
432
+ const branchLinks = vi.spyOn(issues, "linkedIssueBranches").mockRejectedValue(new Error("No ai-delivery branch lifecycle"));
433
+ try {
434
+ const result = await executeTool(
435
+ "issue_pr_create",
436
+ { repo, issueNumber: 17, head: "issue/17", base: "main" },
437
+ { repoRoot: root }
438
+ );
439
+ assert.equal(state.creations, 1);
440
+ assert.equal(branchLinks.mock.calls.length, 0);
441
+ assert.equal(
442
+ state.body,
443
+ "Closes #17\n\n## Outcome\n\nWidgets improve.\n\n## Acceptance criteria\n\n- [ ] Reject invalid widgets.\n Verified by: A synthetic widget test.\n\n<!-- ai-delivery:pr@1 -->"
444
+ );
445
+ assert.deepEqual(result, {
446
+ prNumber: 23,
447
+ url: "https://github.com/example/widget/pull/23",
448
+ headSha: head,
449
+ state: "draft"
450
+ });
451
+ expect(JSON.stringify(result)).toMatchInlineSnapshot(
452
+ '"{"prNumber":23,"url":"https://github.com/example/widget/pull/23","headSha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","state":"draft"}"'
453
+ );
454
+ assert.ok(JSON.stringify(result).length < 1e3);
455
+ } finally {
456
+ rmSync(root, { recursive: true });
457
+ }
458
+ });
459
+ it("reuses an open PR for an unlinked remote head without changing its body", async () => {
460
+ const { context, state } = fixture();
461
+ state.body = "Closes #17\n\nRetain the author explanation.";
462
+ const result = await publishPr(context, { issueNumber: 17, headBranch: "issue/17" });
463
+ assert.equal(result.prNumber, 23);
464
+ assert.equal(state.creations + state.updates, 0);
465
+ assert.equal(state.body, "Closes #17\n\nRetain the author explanation.");
466
+ });
467
+ it("restores a lost closing link once and reports the repair without replacing user content", async () => {
468
+ const { context, state } = fixture();
469
+ state.body = "Retain the author explanation.";
470
+ state.nonClosing = true;
471
+ const input = { issueNumber: 17, headBranch: "issue/17" };
472
+ assert.deepEqual(await publishPr(context, input), {
473
+ prNumber: 23,
474
+ url: "https://github.com/example/widget/pull/23",
475
+ headSha: head,
476
+ state: "draft",
477
+ closingLinkAdded: true
478
+ });
479
+ assert.equal(state.body, "Closes #17\n\nRetain the author explanation.");
480
+ await publishPr(context, input);
481
+ assert.equal(state.creations, 0);
482
+ assert.equal(state.updates, 1);
483
+ });
484
+ it("previews a closing-link repair without a mutation", async () => {
485
+ const { context, state } = fixture();
486
+ state.body = "Retain explanation";
487
+ state.nonClosing = true;
488
+ await publishPr(context, { issueNumber: 17, headBranch: "issue/17", dryRun: true });
489
+ assert.equal(state.updates + state.creations, 0);
490
+ });
491
+ it("refuses a conflicting association without rewriting the existing body", async () => {
492
+ const { context, state } = fixture();
493
+ state.body = "Closes #18";
494
+ state.issueNumber = 18;
495
+ await assert.rejects(publishPr(context, { issueNumber: 17, headBranch: "issue/17" }), /conflicting/u);
496
+ assert.equal(state.updates + state.creations, 0);
497
+ });
498
+ it("refuses body drift during the final association read before repair", async () => {
499
+ const { context, state } = fixture();
500
+ state.body = "Retain explanation";
501
+ state.nonClosing = true;
502
+ const graphql = context.clients.graphql;
503
+ let associationReads = 0;
504
+ vi.spyOn(context.clients, "graphql").mockImplementation(async (query, variables) => {
505
+ const result = await graphql(query, variables);
506
+ if (String(query).includes("DeliveryClosingIssues") && ++associationReads === 2)
507
+ state.body = "Concurrent author edit";
508
+ return result;
509
+ });
510
+ await assert.rejects(publishPr(context, { issueNumber: 17, headBranch: "issue/17" }), /drifted/u);
511
+ assert.equal(state.updates, 0);
512
+ assert.equal(state.body, "Concurrent author edit");
513
+ });
514
+ it("reconciles a lost repair acknowledgement without repeating the applied update", async () => {
515
+ const { context, state } = fixture();
516
+ state.body = "Retain explanation";
517
+ state.nonClosing = true;
518
+ state.failUpdateAck = true;
519
+ const input = { issueNumber: 17, headBranch: "issue/17" };
520
+ await assert.rejects(publishPr(context, input), /repair acknowledgement is uncertain/u);
521
+ state.failUpdateAck = false;
522
+ await publishPr(context, input);
523
+ assert.equal(state.creations, 0);
524
+ assert.equal(state.updates, 1);
525
+ });
526
+ it("names the missing closing line and exact repair call before independent review", async () => {
527
+ const { reviewerContext, state, artifact } = fixture();
528
+ state.body = "Lost closing link";
529
+ state.nonClosing = true;
530
+ await assert.rejects(
531
+ submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }),
532
+ (error) => {
533
+ assert.ok(error instanceof Error);
534
+ assert.match(error.message, /Missing `Closes #17`/u);
535
+ assert.ok(
536
+ error.message.includes('issue_pr_create({"repo":"example/widget","issueNumber":17,"head":"issue/17"})')
537
+ );
538
+ assert.doesNotMatch(error.message, /association does not identify/u);
539
+ return true;
540
+ }
541
+ );
542
+ assert.equal(state.submissions + state.updates, 0);
543
+ });
544
+ });
355
545
  function rulesetOnlyFixture(published = true) {
356
- const current = fixture(published, true);
357
- const evidence = {
358
- deniedRoute: '',
359
- protectionError: { status: 404, response: { status: 404, data: { message: 'Branch not protected' } } },
360
- protection: undefined,
361
- rules: {
362
- status: 200,
363
- headers: {},
364
- data: [
365
- {
366
- type: 'required_status_checks',
367
- ruleset_id: 41,
368
- ruleset_source_type: 'Repository',
369
- ruleset_source: repo,
370
- parameters: {
371
- strict_required_status_checks_policy: true,
372
- required_status_checks: [{ context: 'local-verify' }],
373
- },
374
- },
375
- {
376
- type: 'pull_request',
377
- ruleset_id: 42,
378
- ruleset_source_type: 'Organization',
379
- ruleset_source: 'example',
380
- parameters: { required_approving_review_count: 1, dismiss_stale_reviews_on_push: true },
381
- },
382
- ],
383
- },
384
- rulesets: {
385
- status: 200,
386
- headers: {},
387
- data: [
388
- { id: 41, source_type: 'Repository', source: repo, enforcement: 'active' },
389
- { id: 42, source_type: 'Organization', source: 'example', enforcement: 'active' },
390
- ],
546
+ const current = fixture(published, true);
547
+ const evidence = {
548
+ deniedRoute: "",
549
+ protectionError: { status: 404, response: { status: 404, data: { message: "Branch not protected" } } },
550
+ protection: void 0,
551
+ rules: {
552
+ status: 200,
553
+ headers: {},
554
+ data: [
555
+ {
556
+ type: "required_status_checks",
557
+ ruleset_id: 41,
558
+ ruleset_source_type: "Repository",
559
+ ruleset_source: repo,
560
+ parameters: {
561
+ strict_required_status_checks_policy: true,
562
+ required_status_checks: [{ context: "local-verify" }]
563
+ }
391
564
  },
392
- branch: { status: 200, data: { name: 'main', protected: true, protection: { enabled: true } } },
393
- repository: { status: 200, data: { full_name: repo, permissions: { push: true } } },
394
- };
395
- current.context.clients.rest.request = (async (route, input) => {
396
- assert.equal(input.owner, 'example');
397
- assert.equal(input.repo, 'widget');
398
- if (route === evidence.deniedRoute)
399
- throw { status: 403 };
400
- if (route.endsWith('/protection')) {
401
- if (evidence.protection !== undefined)
402
- return evidence.protection;
403
- throw evidence.protectionError;
565
+ {
566
+ type: "pull_request",
567
+ ruleset_id: 42,
568
+ ruleset_source_type: "Organization",
569
+ ruleset_source: "example",
570
+ parameters: { required_approving_review_count: 1, dismiss_stale_reviews_on_push: true }
404
571
  }
405
- if (route.endsWith('/rules/branches/{branch}'))
406
- return evidence.rules;
407
- if (route.endsWith('/rulesets')) {
408
- assert.equal(input.includes_parents, true);
409
- assert.equal(input.page, 1);
410
- assert.equal(input.per_page, 100);
411
- return evidence.rulesets;
412
- }
413
- if (route.endsWith('/branches/{branch}')) {
414
- assert.equal(input.branch, 'main');
415
- return evidence.branch;
416
- }
417
- if (route === 'GET /repos/{owner}/{repo}')
418
- return evidence.repository;
419
- throw new Error(`Unexpected fictional route ${route}`);
420
- });
421
- return { ...current, evidence };
572
+ ]
573
+ },
574
+ rulesets: {
575
+ status: 200,
576
+ headers: {},
577
+ data: [
578
+ { id: 41, source_type: "Repository", source: repo, enforcement: "active" },
579
+ { id: 42, source_type: "Organization", source: "example", enforcement: "active" }
580
+ ]
581
+ },
582
+ branch: { status: 200, data: { name: "main", protected: true, protection: { enabled: true } } },
583
+ repository: { status: 200, data: { full_name: repo, permissions: { push: true } } }
584
+ };
585
+ current.context.clients.rest.request = (async (route, input) => {
586
+ assert.equal(input.owner, "example");
587
+ assert.equal(input.repo, "widget");
588
+ if (route === evidence.deniedRoute) throw { status: 403 };
589
+ if (route.endsWith("/protection")) {
590
+ if (evidence.protection !== void 0) return evidence.protection;
591
+ throw evidence.protectionError;
592
+ }
593
+ if (route.endsWith("/rules/branches/{branch}")) return evidence.rules;
594
+ if (route.endsWith("/rulesets")) {
595
+ assert.equal(input.includes_parents, true);
596
+ assert.equal(input.page, 1);
597
+ assert.equal(input.per_page, 100);
598
+ return evidence.rulesets;
599
+ }
600
+ if (route.endsWith("/branches/{branch}")) {
601
+ assert.equal(input.branch, "main");
602
+ return evidence.branch;
603
+ }
604
+ if (route === "GET /repos/{owner}/{repo}") return evidence.repository;
605
+ throw new Error(`Unexpected fictional route ${route}`);
606
+ });
607
+ return { ...current, evidence };
422
608
  }
423
609
  async function machineRulesetOnlyFixture(published = true) {
424
- const current = rulesetOnlyFixture(published);
425
- const { context, evidence } = current;
426
- const rest = context.clients.rest;
427
- const graphql = context.clients.graphql;
428
- const home = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-machine-protection-')));
429
- const bin = join(home, 'bin');
430
- mkdirSync(bin);
431
- const token = 'fictional_machine_protection_token';
432
- writeFileSync(join(bin, 'gh'), `#!${process.execPath}
610
+ const current = rulesetOnlyFixture(published);
611
+ const { context, evidence } = current;
612
+ const rest = context.clients.rest;
613
+ const graphql = context.clients.graphql;
614
+ const home = realpathSync(mkdtempSync(join(tmpdir(), "ai-delivery-machine-protection-")));
615
+ const bin = join(home, "bin");
616
+ mkdirSync(bin);
617
+ const token = "fictional_machine_protection_token";
618
+ writeFileSync(
619
+ join(bin, "gh"),
620
+ `#!${process.execPath}
433
621
  const args=process.argv.slice(2);
434
622
  if(JSON.stringify(args)===JSON.stringify(['auth','status','--hostname','github.com','--active','--json','hosts']))
435
623
  process.stdout.write(JSON.stringify({hosts:{'github.com':[{host:'github.com',active:true,state:'success',login:'author'}]}}));
436
624
  else if(JSON.stringify(args)===JSON.stringify(['auth','token','--hostname','github.com','--user','author']))
437
625
  process.stdout.write(${JSON.stringify(token)}+'\\n');
438
626
  else process.exit(91);
439
- `, { mode: 0o755 });
440
- const originalEnv = process.env;
441
- const restore = () => {
442
- process.env = originalEnv;
443
- vi.unstubAllGlobals();
444
- rmSync(home, { recursive: true });
445
- };
446
- process.env = { HOME: home, PATH: bin };
447
- context.config.roles.author.credentialEnv = { token: 'GH_TOKEN' };
448
- vi.stubGlobal('fetch', async (input, init) => {
449
- const url = new URL(input instanceof Request ? input.url : String(input));
450
- assert.equal(url.origin, 'https://api.github.com');
451
- const path = url.pathname;
452
- const method = init?.method ?? 'GET';
453
- const body = (typeof init?.body === 'string' ? JSON.parse(init.body) : {});
454
- let result;
455
- if (path === '/user')
456
- result = { data: { id: 42, login: 'author', type: 'User' } };
457
- else if (path === '/graphql') {
458
- assert.ok(typeof body.query === 'string');
459
- result = { data: { data: await graphql(body.query) } };
460
- }
627
+ `,
628
+ { mode: 493 }
629
+ );
630
+ const originalEnv = process.env;
631
+ const restore = () => {
632
+ process.env = originalEnv;
633
+ vi.unstubAllGlobals();
634
+ rmSync(home, { recursive: true });
635
+ };
636
+ process.env = { HOME: home, PATH: bin };
637
+ context.config.roles.author = {
638
+ authSource: "personal",
639
+ identity: context.config.roles.author.identity,
640
+ credentialEnv: { token: "GH_TOKEN" }
641
+ };
642
+ vi.stubGlobal("fetch", async (input, init) => {
643
+ const url = new URL(input instanceof Request ? input.url : String(input));
644
+ assert.equal(url.origin, "https://api.github.com");
645
+ const path = url.pathname;
646
+ const method = init?.method ?? "GET";
647
+ const body = typeof init?.body === "string" ? JSON.parse(init.body) : {};
648
+ let result;
649
+ if (path === "/user") result = { data: { id: 42, login: "author", type: "User" } };
650
+ else if (path === "/graphql") {
651
+ assert.ok(typeof body.query === "string");
652
+ result = { data: { data: await graphql(body.query) } };
653
+ } else {
654
+ const prefix = "/repos/example/widget";
655
+ assert.ok(path.startsWith(prefix));
656
+ const suffix = path.slice(prefix.length);
657
+ if (suffix === "") {
658
+ const native = await rest.repos.get({ owner: "example", repo: "widget" });
659
+ const visible = evidence.repository;
660
+ result = { status: visible.status, data: { ...native.data, ...visible.data } };
661
+ } else if (suffix === "/branches/main/protection") {
662
+ if (evidence.protection !== void 0) result = evidence.protection;
461
663
  else {
462
- const prefix = '/repos/example/widget';
463
- assert.ok(path.startsWith(prefix));
464
- const suffix = path.slice(prefix.length);
465
- if (suffix === '') {
466
- const native = await rest.repos.get({ owner: 'example', repo: 'widget' });
467
- const visible = evidence.repository;
468
- result = { status: visible.status, data: { ...native.data, ...visible.data } };
469
- }
470
- else if (suffix === '/branches/main/protection') {
471
- if (evidence.protection !== undefined)
472
- result = evidence.protection;
473
- else {
474
- const error = evidence.protectionError;
475
- result = {
476
- status: error.status,
477
- data: { ...error.response.data, private: token },
478
- headers: { 'x-private': token },
479
- };
480
- }
481
- }
482
- else if (suffix === '/rules/branches/main')
483
- result = evidence.rules;
484
- else if (suffix === '/branches/main')
485
- result = evidence.branch;
486
- else if (suffix === '/rulesets') {
487
- assert.equal(url.searchParams.get('includes_parents'), 'true');
488
- assert.equal(url.searchParams.get('per_page'), '100');
489
- assert.equal(url.searchParams.get('page'), '1');
490
- result = evidence.rulesets;
491
- }
492
- else if (suffix === '/issues/17')
493
- result = await rest.issues.get({ owner: 'example', repo: 'widget', issue_number: 17 });
494
- else if (suffix.startsWith('/git/ref/'))
495
- result = await rest.git.getRef({
496
- owner: 'example',
497
- repo: 'widget',
498
- ref: decodeURIComponent(suffix.slice('/git/ref/'.length)),
499
- });
500
- else if (suffix.startsWith('/git/commits/'))
501
- result = await rest.git.getCommit({ owner: 'example', repo: 'widget', commit_sha: head });
502
- else if (suffix.startsWith('/compare/'))
503
- result = await rest.repos.compareCommitsWithBasehead({
504
- owner: 'example',
505
- repo: 'widget',
506
- basehead: `${base}...${head}`,
507
- });
508
- else if (suffix === '/pulls' && method === 'POST') {
509
- assert.ok(typeof body.draft === 'boolean' && typeof body.head === 'string' && typeof body.body === 'string');
510
- result = await rest.pulls.create({
511
- owner: 'example',
512
- repo: 'widget',
513
- title: 'Improve widget',
514
- base: 'main',
515
- draft: body.draft,
516
- head: body.head,
517
- body: body.body,
518
- });
519
- }
520
- else if (suffix === '/pulls')
521
- result = await rest.pulls.list({ owner: 'example', repo: 'widget' });
522
- else if (suffix === '/pulls/23')
523
- result = await rest.pulls.get({ owner: 'example', repo: 'widget', pull_number: 23 });
524
- else if (suffix === '/pulls/23/files')
525
- result = await rest.pulls.listFiles({ owner: 'example', repo: 'widget', pull_number: 23 });
526
- else if (suffix === '/pulls/23/reviews')
527
- result = await rest.pulls.listReviews({ owner: 'example', repo: 'widget', pull_number: 23 });
528
- else
529
- throw new Error(`Unexpected fictional machine route ${method} ${suffix}`);
530
- if (evidence.deniedRoute && suffix === evidence.deniedRoute)
531
- result = { status: 403, data: { message: token } };
664
+ const error = evidence.protectionError;
665
+ result = {
666
+ status: error.status,
667
+ data: { ...error.response.data, private: token },
668
+ headers: { "x-private": token }
669
+ };
532
670
  }
533
- const response = new Response(JSON.stringify(result.data), {
534
- status: result.status ?? 200,
535
- headers: {
536
- 'content-type': 'application/json',
537
- ...Object.fromEntries(Object.entries(result.headers ?? {}).filter((entry) => typeof entry[1] === 'string')),
538
- },
539
- });
540
- Object.defineProperty(response, 'url', { value: url.href });
541
- return response;
542
- });
543
- try {
544
- context.clients = await github.createDeliveryGitHubClients({
545
- config: context.config,
546
- role: 'author',
547
- identity: 'author',
548
- env: process.env,
549
- });
550
- github.retainMachineAuthorForConfiguration(context.config, context.clients);
551
- return { ...current, restore, token };
552
- }
553
- catch (error) {
554
- restore();
555
- throw error;
556
- }
557
- }
558
- describe('native exact PR association after publication', () => {
559
- it('replays native start, push, draft publication, empty branch links, author inspection and distinct App review', async () => {
560
- const { context, reviewerContext, state, artifact } = fixture(false);
561
- const started = await startIssueBranch(context, 17);
562
- assert.equal(started.reused, false);
563
- assert.equal(started.headSha, base);
564
- state.remoteHead = head;
565
- state.events.push('push');
566
- await publishPr(context, { issueNumber: 17, body: 'Improve widget', draft: true });
567
- assert.deepEqual(state.events, ['native-start', 'push', 'draft-publication-replaces-branch-link']);
568
- assert.equal(state.linked, false);
569
- assert.equal((await prInfo(context, { issueNumber: 17, prNumber: 23 })).headSha, head);
570
- assert.equal((await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact, dryRun: true })).headSha, head);
571
- assert.equal(state.submissions, 0);
572
- const submitted = await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
573
- const reused = await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
574
- assert.deepEqual(reused, submitted);
575
- assert.equal(state.submissions, 1);
576
- });
577
- it('gives an exact-PR next action for issue-only lookup with empty branch links', async () => {
578
- const { context } = fixture();
579
- await assert.rejects(prInfo(context, { issueNumber: 17 }), (error) => {
580
- assert.ok(error instanceof Error);
581
- assert.match(error.message, /exact issue and PR numbers.*--issue and --pr/u);
582
- assert.doesNotMatch(error.message, /zero or multiple PRs|start again|repeat.*start/u);
583
- return true;
671
+ } else if (suffix === "/rules/branches/main") result = evidence.rules;
672
+ else if (suffix === "/branches/main") result = evidence.branch;
673
+ else if (suffix === "/rulesets") {
674
+ assert.equal(url.searchParams.get("includes_parents"), "true");
675
+ assert.equal(url.searchParams.get("per_page"), "100");
676
+ assert.equal(url.searchParams.get("page"), "1");
677
+ result = evidence.rulesets;
678
+ } else if (suffix === "/issues/17")
679
+ result = await rest.issues.get({ owner: "example", repo: "widget", issue_number: 17 });
680
+ else if (suffix.startsWith("/git/ref/"))
681
+ result = await rest.git.getRef({
682
+ owner: "example",
683
+ repo: "widget",
684
+ ref: decodeURIComponent(suffix.slice("/git/ref/".length))
584
685
  });
585
- assert.equal((await prInfo(context, { prNumber: 23 })).prNumber, 23);
586
- });
587
- it('verifies native association when issue-only lookup still has a linked branch', async () => {
588
- const { context, state } = fixture();
589
- state.linked = true;
590
- assert.equal((await prInfo(context, { issueNumber: 17 })).prNumber, 23);
591
- state.issueNumber = 18;
592
- await assert.rejects(prInfo(context, { issueNumber: 17 }), /association/u);
593
- });
594
- for (const [name, change] of [
595
- ['wrong closing issue', { issueNumber: 18 }],
596
- ['wrong PR repository', { headRepo: 'other/widget' }],
597
- ['wrong base repository', { baseRepo: 'other/widget' }],
598
- ['wrong native repository', { associationRepo: 'other/widget' }],
599
- ['wrong native PR', { associationPr: 24 }],
600
- ['remote head drift', { remoteHead: 'd'.repeat(40) }],
601
- ['remote ref mismatch', { remoteRef: 'refs/heads/other' }],
602
- ['incomplete remote ref', { remoteType: '' }],
603
- ['invalid head branch', { headRef: '../other' }],
604
- ['invalid PR head', { headSha: 'missing' }],
605
- ['incomplete PR state', { prState: '' }],
606
- ['incomplete merged state', { merged: undefined }],
607
- ['incomplete draft state', { draft: undefined }],
608
- ['conflicting merged state', { merged: true }],
609
- ]) {
610
- it(`refuses ${name} before inspection or review mutation`, async () => {
611
- const { context, reviewerContext, state, artifact } = fixture();
612
- Object.assign(state, change);
613
- await assert.rejects(prInfo(context, { issueNumber: 17, prNumber: 23 }));
614
- await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }));
615
- assert.equal(state.submissions, 0);
686
+ else if (suffix.startsWith("/git/commits/"))
687
+ result = await rest.git.getCommit({ owner: "example", repo: "widget", commit_sha: head });
688
+ else if (suffix.startsWith("/compare/"))
689
+ result = await rest.repos.compareCommitsWithBasehead({
690
+ owner: "example",
691
+ repo: "widget",
692
+ basehead: `${base}...${head}`
616
693
  });
617
- }
618
- for (const [name, response] of [
619
- ['missing connection', { repository: { nameWithOwner: repo, pullRequest: { number: 23 } } }],
620
- [
621
- 'empty closing issues',
622
- {
623
- repository: {
624
- nameWithOwner: repo,
625
- pullRequest: { number: 23, closingIssuesReferences: { nodes: [], pageInfo } },
626
- },
627
- },
628
- ],
629
- [
630
- 'foreign closing issue',
631
- {
632
- repository: {
633
- nameWithOwner: repo,
634
- pullRequest: {
635
- number: 23,
636
- closingIssuesReferences: {
637
- nodes: [{ number: 17, repository: { nameWithOwner: 'other/widget' } }],
638
- pageInfo,
639
- },
640
- },
641
- },
642
- },
643
- ],
644
- [
645
- 'incomplete closing issue',
646
- {
647
- repository: {
648
- nameWithOwner: repo,
649
- pullRequest: { number: 23, closingIssuesReferences: { nodes: [null], pageInfo } },
650
- },
651
- },
652
- ],
653
- [
654
- 'duplicate closing issue',
655
- {
656
- repository: {
657
- nameWithOwner: repo,
658
- pullRequest: {
659
- number: 23,
660
- closingIssuesReferences: {
661
- nodes: Array.from({ length: 2 }, () => ({ number: 17, repository: { nameWithOwner: repo } })),
662
- pageInfo,
663
- },
664
- },
665
- },
666
- },
667
- ],
668
- [
669
- 'missing pagination',
670
- { repository: { nameWithOwner: repo, pullRequest: { number: 23, closingIssuesReferences: { nodes: [] } } } },
671
- ],
672
- [
673
- 'nonadvancing pagination',
674
- {
675
- repository: {
676
- nameWithOwner: repo,
677
- pullRequest: {
678
- number: 23,
679
- closingIssuesReferences: { nodes: [], pageInfo: { hasNextPage: true, endCursor: null } },
680
- },
681
- },
682
- },
683
- ],
684
- ]) {
685
- it(`refuses ${name} before App submission`, async () => {
686
- const { reviewerContext, state, artifact } = fixture();
687
- state.closingReadback = response;
688
- await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }), /association|identity|pagination/u);
689
- assert.equal(state.submissions, 0);
694
+ else if (suffix === "/pulls" && method === "POST") {
695
+ assert.ok(typeof body.draft === "boolean" && typeof body.head === "string" && typeof body.body === "string");
696
+ result = await rest.pulls.create({
697
+ owner: "example",
698
+ repo: "widget",
699
+ title: "Improve widget",
700
+ base: "main",
701
+ draft: body.draft,
702
+ head: body.head,
703
+ body: body.body
690
704
  });
705
+ } else if (suffix === "/pulls") result = await rest.pulls.list({ owner: "example", repo: "widget" });
706
+ else if (suffix === "/pulls/23")
707
+ result = await rest.pulls.get({ owner: "example", repo: "widget", pull_number: 23 });
708
+ else if (suffix === "/pulls/23/files")
709
+ result = await rest.pulls.listFiles({ owner: "example", repo: "widget", pull_number: 23 });
710
+ else if (suffix === "/pulls/23/reviews")
711
+ result = await rest.pulls.listReviews({ owner: "example", repo: "widget", pull_number: 23 });
712
+ else throw new Error(`Unexpected fictional machine route ${method} ${suffix}`);
713
+ if (evidence.deniedRoute && suffix === evidence.deniedRoute) result = { status: 403, data: { message: token } };
691
714
  }
692
- for (const [name, response] of [
693
- ['incomplete linked branches', { repository: { issue: { linkedBranches: { nodes: [], pageInfo: {} } } } }],
694
- [
695
- 'conflicting linked branch',
696
- {
697
- repository: {
698
- issue: {
699
- linkedBranches: {
700
- nodes: [{ ref: { name: 'other', target: { oid: head }, repository: { nameWithOwner: repo } } }],
701
- pageInfo,
702
- },
703
- },
704
- },
705
- },
706
- ],
707
- [
708
- 'stale linked head',
709
- {
710
- repository: {
711
- issue: {
712
- linkedBranches: {
713
- nodes: [{ ref: { name: 'issue/17', target: { oid: base }, repository: { nameWithOwner: repo } } }],
714
- pageInfo,
715
- },
716
- },
717
- },
718
- },
719
- ],
720
- ]) {
721
- it(`accepts ${name} when the native PR closing association and head are current`, async () => {
722
- const { reviewerContext, state, artifact } = fixture();
723
- state.branchReadback = response;
724
- await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
725
- assert.equal(state.submissions, 1);
726
- });
727
- }
728
- it('refuses configured/selected repository disagreement', async () => {
729
- const { context } = fixture();
730
- context.repo = { owner: 'other', repo: 'widget' };
731
- await assert.rejects(prInfo(context, { issueNumber: 17, prNumber: 23 }), /repository identities/u);
732
- });
733
- it('reads the complete closing-issue connection before accepting a later-page association', async () => {
734
- const { context, state } = fixture();
735
- state.closingPages = [
736
- {
737
- repository: {
738
- nameWithOwner: repo,
739
- pullRequest: {
740
- number: 23,
741
- closingIssuesReferences: {
742
- nodes: [{ number: 18, repository: { nameWithOwner: repo } }],
743
- pageInfo: { hasNextPage: true, endCursor: 'NEXT' },
744
- },
745
- },
746
- },
747
- },
748
- {
749
- repository: {
750
- nameWithOwner: repo,
751
- pullRequest: {
752
- number: 23,
753
- closingIssuesReferences: {
754
- nodes: [{ number: 17, repository: { nameWithOwner: repo } }],
755
- pageInfo,
756
- },
757
- },
758
- },
759
- },
760
- ];
761
- assert.equal((await prInfo(context, { issueNumber: 17, prNumber: 23 })).headSha, head);
762
- assert.equal(state.closingPageIndex, 2);
715
+ const response = new Response(JSON.stringify(result.data), {
716
+ status: result.status ?? 200,
717
+ headers: {
718
+ "content-type": "application/json",
719
+ ...Object.fromEntries(
720
+ Object.entries(result.headers ?? {}).filter(
721
+ (entry) => typeof entry[1] === "string"
722
+ )
723
+ )
724
+ }
763
725
  });
764
- it('refuses an incomplete later page even after finding the intended closing issue', async () => {
765
- const { reviewerContext, state, artifact } = fixture();
766
- state.closingPages = [
767
- {
768
- repository: {
769
- nameWithOwner: repo,
770
- pullRequest: {
771
- number: 23,
772
- closingIssuesReferences: {
773
- nodes: [{ number: 17, repository: { nameWithOwner: repo } }],
774
- pageInfo: { hasNextPage: true, endCursor: 'NEXT' },
775
- },
776
- },
777
- },
778
- },
779
- { repository: null },
780
- ];
781
- await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }), /association/u);
782
- assert.equal(state.closingPageIndex, 2);
783
- assert.equal(state.submissions, 0);
726
+ Object.defineProperty(response, "url", { value: url.href });
727
+ return response;
728
+ });
729
+ try {
730
+ context.clients = await github.createDeliveryGitHubClients({
731
+ config: context.config,
732
+ role: "author",
733
+ identity: "author",
734
+ env: process.env
784
735
  });
785
- it('preserves configured reviewer separation and stale artifact/head refusals', async () => {
786
- const { context, reviewerContext, state, artifact } = fixture();
787
- await assert.rejects(submitFormalReview(context, { issueNumber: 17, prNumber: 23, artifact }), /reviewer.*role/u);
788
- state.reviewerActor = 'author';
789
- await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }), /differ/u);
790
- state.reviewerActor = 'reviewer[bot]';
791
- state.movedOnRead = state.reads + 2;
792
- await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }), /head|moved/u);
793
- assert.equal(state.submissions, 0);
794
- });
795
- it('submits a fresh valid artifact despite an older remapped App review', async () => {
796
- const { reviewerContext, state, artifact } = fixture();
797
- await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
798
- state.reviews[0].body = `<!-- ai-delivery-review-artifact: sha256:${'f'.repeat(64)} -->`;
799
- await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
800
- assert.equal(state.submissions, 2);
736
+ github.retainMachineAuthorForConfiguration(context.config, context.clients);
737
+ return { ...current, restore, token };
738
+ } catch (error) {
739
+ restore();
740
+ throw error;
741
+ }
742
+ }
743
+ describe("native exact PR association after publication", () => {
744
+ it("replays native start, push, draft publication, empty branch links, author inspection and distinct App review", async () => {
745
+ const { context, reviewerContext, state, artifact } = fixture(false);
746
+ const started = await startIssueBranch(context, 17);
747
+ assert.equal(started.reused, false);
748
+ assert.equal(started.headSha, base);
749
+ state.remoteHead = head;
750
+ state.events.push("push");
751
+ await publishPr(context, { issueNumber: 17, body: "Improve widget", draft: true });
752
+ assert.deepEqual(state.events, ["native-start", "push", "draft-publication-replaces-branch-link"]);
753
+ assert.equal(state.linked, false);
754
+ assert.equal((await prInfo(context, { issueNumber: 17, prNumber: 23 })).headSha, head);
755
+ assert.equal(
756
+ (await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact, dryRun: true })).headSha,
757
+ head
758
+ );
759
+ assert.equal(state.submissions, 0);
760
+ const submitted = await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
761
+ const reused = await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
762
+ assert.deepEqual(reused, submitted);
763
+ assert.equal(state.submissions, 1);
764
+ });
765
+ it("gives an exact-PR next action for issue-only lookup with empty branch links", async () => {
766
+ const { context } = fixture();
767
+ await assert.rejects(prInfo(context, { issueNumber: 17 }), (error) => {
768
+ assert.ok(error instanceof Error);
769
+ assert.match(error.message, /exact issue and PR numbers.*--issue and --pr/u);
770
+ assert.doesNotMatch(error.message, /zero or multiple PRs|start again|repeat.*start/u);
771
+ return true;
801
772
  });
802
- });
803
- describe('authoritative existing PR promotion', () => {
804
- const input = { issueNumber: 17, headBranch: 'issue/17', draft: false };
805
- it('promotes after publication and exact-head review, then reuses authoritative ready readback', async () => {
806
- const { context, reviewerContext, state, artifact } = fixture();
807
- await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
808
- const preview = await publishPr(context, { ...input, dryRun: true });
809
- assert.equal(preview.prNumber, 23);
810
- assert.equal(preview.draft, true);
811
- assert.equal(state.promotions, 0);
812
- const promoted = await publishPr(context, input);
813
- const reused = await publishPr(context, input);
814
- assert.equal(promoted.prNumber, 23);
815
- assert.equal(promoted.draft, false);
816
- assert.deepEqual(reused, promoted);
817
- assert.equal(state.promotions, 1);
818
- assert.equal(state.creations, 0);
819
- assert.equal(state.submissions, 1);
820
- assert.equal(state.linked, false);
821
- assert.deepEqual(state.events, []);
773
+ assert.equal((await prInfo(context, { prNumber: 23 })).prNumber, 23);
774
+ });
775
+ it("verifies native association when issue-only lookup still has a linked branch", async () => {
776
+ const { context, state } = fixture();
777
+ state.linked = true;
778
+ assert.equal((await prInfo(context, { issueNumber: 17 })).prNumber, 23);
779
+ state.issueNumber = 18;
780
+ await assert.rejects(prInfo(context, { issueNumber: 17 }), /association/u);
781
+ });
782
+ for (const [name, change] of [
783
+ ["wrong closing issue", { issueNumber: 18 }],
784
+ ["wrong PR repository", { headRepo: "other/widget" }],
785
+ ["wrong base repository", { baseRepo: "other/widget" }],
786
+ ["wrong native repository", { associationRepo: "other/widget" }],
787
+ ["wrong native PR", { associationPr: 24 }],
788
+ ["remote head drift", { remoteHead: "d".repeat(40) }],
789
+ ["remote ref mismatch", { remoteRef: "refs/heads/other" }],
790
+ ["incomplete remote ref", { remoteType: "" }],
791
+ ["invalid head branch", { headRef: "../other" }],
792
+ ["invalid PR head", { headSha: "missing" }],
793
+ ["incomplete PR state", { prState: "" }],
794
+ ["incomplete merged state", { merged: void 0 }],
795
+ ["incomplete draft state", { draft: void 0 }],
796
+ ["conflicting merged state", { merged: true }]
797
+ ]) {
798
+ it(`refuses ${name} before inspection or review mutation`, async () => {
799
+ const { context, reviewerContext, state, artifact } = fixture();
800
+ Object.assign(state, change);
801
+ await assert.rejects(prInfo(context, { issueNumber: 17, prNumber: 23 }));
802
+ await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }));
803
+ assert.equal(state.submissions, 0);
822
804
  });
823
- for (const [name, change] of [
824
- ['wrong issue', { issueNumber: 18 }],
825
- ['foreign PR head repository', { headRepo: 'other/widget' }],
826
- ['foreign PR base repository', { baseRepo: 'other/widget' }],
827
- ['foreign native repository', { associationRepo: 'other/widget' }],
828
- ['wrong native PR', { associationPr: 24 }],
829
- ['wrong author', { prAuthor: 'collaborator' }],
830
- ['wrong head', { headSha: 'd'.repeat(40) }],
831
- ['moved remote head', { remoteHead: 'd'.repeat(40) }],
832
- ['wrong ref', { headRef: 'other' }],
833
- ['wrong base', { baseRef: 'release' }],
834
- ['closed PR', { prState: 'closed' }],
835
- ['missing node identity', { nodeId: '' }],
836
- ['incomplete draft state', { draft: undefined }],
837
- ['ambiguous matches', { matchReadback: [{ number: 23 }, { number: 24 }] }],
838
- ['incomplete match identity', { matchReadback: [{}] }],
839
- ['incomplete match connection', { matchReadback: {} }],
840
- ['incomplete association', { closingReadback: { repository: null } }],
841
- ]) {
842
- it(`refuses ${name} before promotion, including already-ready reuse`, async () => {
843
- for (const draft of [true, false]) {
844
- const { context, state } = fixture();
845
- state.draft = draft;
846
- Object.assign(state, change);
847
- await assert.rejects(publishPr(context, input));
848
- assert.equal(state.promotions, 0);
849
- assert.equal(state.creations, 0);
850
- assert.deepEqual(state.events, []);
805
+ }
806
+ for (const [name, response] of [
807
+ ["missing connection", { repository: { nameWithOwner: repo, pullRequest: { number: 23 } } }],
808
+ [
809
+ "empty closing issues",
810
+ {
811
+ repository: {
812
+ nameWithOwner: repo,
813
+ pullRequest: { number: 23, closingIssuesReferences: { nodes: [], pageInfo } }
814
+ }
815
+ }
816
+ ],
817
+ [
818
+ "foreign closing issue",
819
+ {
820
+ repository: {
821
+ nameWithOwner: repo,
822
+ pullRequest: {
823
+ number: 23,
824
+ closingIssuesReferences: {
825
+ nodes: [{ number: 17, repository: { nameWithOwner: "other/widget" } }],
826
+ pageInfo
851
827
  }
852
- });
853
- }
854
- for (const read of [2, 3]) {
855
- it(`refuses head drift on authoritative PR read ${read} before mutation`, async () => {
856
- const { context, state } = fixture();
857
- state.readHook = (count) => {
858
- if (count === read)
859
- state.headSha = state.remoteHead = 'd'.repeat(40);
860
- };
861
- await assert.rejects(publishPr(context, input), /drift/u);
862
- assert.equal(state.promotions, 0);
863
- });
864
- }
865
- it('refuses author and native node drift immediately before mutation', async () => {
866
- for (const field of ['prAuthor', 'nodeId']) {
867
- const { context, state } = fixture();
868
- state.readHook = (count) => {
869
- if (count === 3)
870
- state[field] = 'changed';
871
- };
872
- await assert.rejects(publishPr(context, input), /drift/u);
873
- assert.equal(state.promotions, 0);
828
+ }
874
829
  }
875
- });
876
- for (const response of [
877
- {},
878
- { markPullRequestReadyForReview: null },
879
- { markPullRequestReadyForReview: { pullRequest: { id: 'PR24', isDraft: false } } },
880
- { markPullRequestReadyForReview: { pullRequest: { id: 'PR23' } } },
881
- ]) {
882
- it('refuses incomplete or conflicting mutation acknowledgement without retrying it', async () => {
883
- const { context, state } = fixture();
884
- state.promotionReadback = response;
885
- await assert.rejects(publishPr(context, input), /mutation readback/u);
886
- assert.equal(state.promotions, 1);
887
- assert.equal(state.creations, 0);
888
- });
889
- }
890
- it('refuses a still-draft authoritative readback after a ready acknowledgement', async () => {
891
- const { context, state } = fixture();
892
- state.keepDraftOnPromotion = true;
893
- await assert.rejects(publishPr(context, input), /still draft/u);
894
- assert.equal(state.promotions, 1);
895
- });
896
- it('refuses post-mutation head or association drift without another mutation', async () => {
897
- for (const kind of ['head', 'association']) {
898
- const { context, state } = fixture();
899
- state.readHook = (count) => {
900
- if (count === 4) {
901
- if (kind === 'head')
902
- state.headSha = state.remoteHead = 'd'.repeat(40);
903
- else
904
- state.closingReadback = { repository: null };
905
- }
906
- };
907
- await assert.rejects(publishPr(context, input), /drift|association/u);
908
- assert.equal(state.promotions, 1);
830
+ }
831
+ ],
832
+ [
833
+ "incomplete closing issue",
834
+ {
835
+ repository: {
836
+ nameWithOwner: repo,
837
+ pullRequest: { number: 23, closingIssuesReferences: { nodes: [null], pageInfo } }
909
838
  }
910
- });
911
- it('requires explicit head and ready intent rather than guessing a post-publication branch', async () => {
912
- const { context, state } = fixture();
913
- await assert.rejects(publishPr(context, { issueNumber: 17, draft: false }), /linked/u);
914
- await assert.rejects(publishPr(context, { ...input, draft: true }), /linked/u);
915
- assert.equal(state.promotions, 0);
916
- });
917
- it('keeps new ready-PR creation behind native linked-branch authority', async () => {
918
- const { context, state } = fixture(false);
919
- await assert.rejects(publishPr(context, input), /linked/u);
920
- assert.equal(state.creations, 0);
921
- const started = await startIssueBranch(context, 17);
922
- assert.equal(started.headSha, base);
923
- state.remoteHead = head;
924
- state.expectedCreationDraft = false;
925
- const created = await publishPr(context, input);
926
- assert.equal(created.draft, false);
927
- assert.equal(state.creations, 1);
928
- assert.equal(state.promotions, 0);
929
- });
930
- it('keeps incomplete native branch readback behind the unchanged start gate', async () => {
931
- const { context, state } = fixture(false);
932
- state.branchReadback = { repository: null };
933
- await assert.rejects(startIssueBranch(context, 17), /Incomplete/u);
934
- assert.deepEqual(state.events, []);
935
- });
936
- it('retains configured author role and distinct App preflight before promotion', async () => {
937
- const { context, reviewerContext, state } = fixture();
938
- await assert.rejects(publishPr(reviewerContext, input), /author/u);
939
- state.reviewerActor = 'author';
940
- await assert.rejects(publishPr(context, input), /distinct/u);
941
- assert.equal(state.promotions, 0);
942
- });
943
- });
944
- describe('directory-independent exact-PR contract', () => {
945
- it('uses the existing MCP selector for author dry-run, promotion and ready reuse outside a checkout', async () => {
946
- const root = mkdtempSync(join(tmpdir(), 'delivery-pr-promotion-'));
947
- const { context, state } = fixture();
948
- vi.spyOn(settings, 'loadDeliverySettings').mockResolvedValue(context.config);
949
- vi.spyOn(issues, 'loadDeliveryContext').mockImplementation(async (input) => {
950
- assert.equal(input.repository, repo);
951
- assert.equal(input.repoRoot, root);
952
- assert.equal(input.role, 'author');
953
- return context;
954
- });
955
- const server = createAiDeliveryMcpServer({ repoRoot: root });
956
- const client = new Client({ name: 'promotion-fixture', version: '1' });
957
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
958
- const input = { repo, issueNumber: 17, headBranch: 'issue/17', draft: false };
959
- try {
960
- await server.connect(serverTransport);
961
- await client.connect(clientTransport);
962
- const preview = await client.callTool({ name: 'issue_pr_create', arguments: { ...input, dryRun: true } });
963
- assert.equal(preview.isError, undefined);
964
- assert.equal(state.promotions, 0);
965
- for (let call = 0; call < 2; call++) {
966
- const result = await client.callTool({ name: 'issue_pr_create', arguments: input });
967
- assert.equal(result.isError, undefined);
839
+ }
840
+ ],
841
+ [
842
+ "duplicate closing issue",
843
+ {
844
+ repository: {
845
+ nameWithOwner: repo,
846
+ pullRequest: {
847
+ number: 23,
848
+ closingIssuesReferences: {
849
+ nodes: Array.from({ length: 2 }, () => ({ number: 17, repository: { nameWithOwner: repo } })),
850
+ pageInfo
968
851
  }
969
- assert.equal(state.promotions, 1);
970
- assert.equal(state.creations, 0);
971
- assert.equal(state.draft, false);
972
- assert.equal(state.linked, false);
852
+ }
973
853
  }
974
- finally {
975
- await client.close();
976
- await server.close();
977
- rmSync(root, { recursive: true, force: true });
854
+ }
855
+ ],
856
+ [
857
+ "missing pagination",
858
+ { repository: { nameWithOwner: repo, pullRequest: { number: 23, closingIssuesReferences: { nodes: [] } } } }
859
+ ],
860
+ [
861
+ "nonadvancing pagination",
862
+ {
863
+ repository: {
864
+ nameWithOwner: repo,
865
+ pullRequest: {
866
+ number: 23,
867
+ closingIssuesReferences: { nodes: [], pageInfo: { hasNextPage: true, endCursor: null } }
868
+ }
978
869
  }
870
+ }
871
+ ]
872
+ ]) {
873
+ it(`refuses ${name} before App submission`, async () => {
874
+ const { reviewerContext, state, artifact } = fixture();
875
+ state.closingReadback = response;
876
+ await assert.rejects(
877
+ submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }),
878
+ /association|identity|pagination/u
879
+ );
880
+ assert.equal(state.submissions, 0);
979
881
  });
980
- it('dispatches native inspection and App dry-run through MCP from a non-Git directory', async () => {
981
- const root = mkdtempSync(join(tmpdir(), 'delivery-pr-association-'));
982
- const { context, reviewerContext, state, artifact } = fixture();
983
- vi.spyOn(settings, 'loadDeliverySettings').mockResolvedValue(context.config);
984
- const loader = vi.spyOn(issues, 'loadDeliveryContext').mockImplementation(async (input) => {
985
- assert.equal(input.repository, repo);
986
- assert.equal(input.repoRoot, root);
987
- return input.role === 'reviewer' ? reviewerContext : context;
988
- });
989
- const server = createAiDeliveryMcpServer({ repoRoot: root });
990
- const client = new Client({ name: 'exact-pr-fixture', version: '1' });
991
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
992
- try {
993
- await server.connect(serverTransport);
994
- await client.connect(clientTransport);
995
- const info = await client.callTool({ name: 'issue_pr_info', arguments: { repo, issueNumber: 17, prNumber: 23 } });
996
- assert.equal(info.isError, undefined);
997
- const review = await client.callTool({
998
- name: 'issue_pr_review',
999
- arguments: { repo, issueNumber: 17, prNumber: 23, artifact, dryRun: true },
1000
- });
1001
- assert.equal(review.isError, undefined);
1002
- state.issueNumber = 18;
1003
- await assert.rejects(executeTool('issue_pr_info', { repo, issueNumber: 17, prNumber: 23 }, { repoRoot: root }), /association/u);
1004
- assert.deepEqual(loader.mock.calls.map(([input]) => input.role), ['author', 'reviewer', 'author']);
1005
- assert.equal(state.submissions, 0);
882
+ }
883
+ for (const [name, response] of [
884
+ ["incomplete linked branches", { repository: { issue: { linkedBranches: { nodes: [], pageInfo: {} } } } }],
885
+ [
886
+ "conflicting linked branch",
887
+ {
888
+ repository: {
889
+ issue: {
890
+ linkedBranches: {
891
+ nodes: [{ ref: { name: "other", target: { oid: head }, repository: { nameWithOwner: repo } } }],
892
+ pageInfo
893
+ }
894
+ }
1006
895
  }
1007
- finally {
1008
- await client.close();
1009
- await server.close();
1010
- rmSync(root, { recursive: true, force: true });
896
+ }
897
+ ],
898
+ [
899
+ "stale linked head",
900
+ {
901
+ repository: {
902
+ issue: {
903
+ linkedBranches: {
904
+ nodes: [{ ref: { name: "issue/17", target: { oid: base }, repository: { nameWithOwner: repo } } }],
905
+ pageInfo
906
+ }
907
+ }
1011
908
  }
909
+ }
910
+ ]
911
+ ]) {
912
+ it(`accepts ${name} when the native PR closing association and head are current`, async () => {
913
+ const { reviewerContext, state, artifact } = fixture();
914
+ state.branchReadback = response;
915
+ await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
916
+ assert.equal(state.submissions, 1);
1012
917
  });
1013
- it('documents explicit issue/PR selection in actual CLI help without credentials or a checkout', () => {
1014
- const root = mkdtempSync(join(tmpdir(), 'delivery-pr-help-'));
1015
- try {
1016
- const help = execFileSync(process.execPath, [resolve('dist/cli.js'), 'pr:info', '--help'], {
1017
- cwd: root,
1018
- env: { HOME: root, PATH: process.env.PATH },
1019
- encoding: 'utf8',
1020
- });
1021
- assert.match(help, /combine --issue and --pr/u);
1022
- assert.match(help, /issue-only lookup requires a GitHub-linked\s+branch/u);
1023
- const creationHelp = execFileSync(process.execPath, [resolve('dist/cli.js'), 'pr:create', '--help'], {
1024
- cwd: root,
1025
- env: { HOME: root, PATH: process.env.PATH },
1026
- encoding: 'utf8',
1027
- }).replace(/\s+/gu, ' ');
1028
- assert.match(creationHelp, /promote an existing associated PR with --head and --ready/u);
1029
- assert.match(creationHelp, /Explicit remote head/u);
1030
- assert.match(creationHelp, /--pr <number>/u);
1031
- for (const command of ['pr:create', 'pr:info', 'pr:review', 'pr:merge', 'finish']) {
1032
- const modeHelp = execFileSync(process.execPath, [resolve('dist/cli.js'), command, '--help'], {
1033
- cwd: root,
1034
- env: { HOME: root, PATH: process.env.PATH },
1035
- encoding: 'utf8',
1036
- });
1037
- assert.match(modeHelp, /--non-closing/u);
918
+ }
919
+ it("refuses configured/selected repository disagreement", async () => {
920
+ const { context } = fixture();
921
+ context.repo = { owner: "other", repo: "widget" };
922
+ await assert.rejects(prInfo(context, { issueNumber: 17, prNumber: 23 }), /repository identities/u);
923
+ });
924
+ it("reads the complete closing-issue connection before accepting a later-page association", async () => {
925
+ const { context, state } = fixture();
926
+ state.closingPages = [
927
+ {
928
+ repository: {
929
+ nameWithOwner: repo,
930
+ pullRequest: {
931
+ number: 23,
932
+ closingIssuesReferences: {
933
+ nodes: [{ number: 18, repository: { nameWithOwner: repo } }],
934
+ pageInfo: { hasNextPage: true, endCursor: "NEXT" }
1038
935
  }
936
+ }
1039
937
  }
1040
- finally {
1041
- rmSync(root, { recursive: true, force: true });
938
+ },
939
+ {
940
+ repository: {
941
+ nameWithOwner: repo,
942
+ pullRequest: {
943
+ number: 23,
944
+ closingIssuesReferences: {
945
+ nodes: [{ number: 17, repository: { nameWithOwner: repo } }],
946
+ pageInfo
947
+ }
948
+ }
1042
949
  }
1043
- });
1044
- });
1045
- describe('explicit native non-closing reference delivery', () => {
1046
- const input = { issueNumber: 17, prNumber: 23, nonClosing: true };
1047
- it.each(['ruleset-only', 'ruleset-only with disabled protection summary', 'confirmed-unprotected'])('creates and reviews %s protection through the real machine client and sanitizer', async (mode) => {
1048
- const { context, reviewerContext, state, artifact, evidence, restore, token } = await machineRulesetOnlyFixture(false);
1049
- try {
1050
- if (mode === 'ruleset-only with disabled protection summary')
1051
- evidence.branch = { status: 200, data: { name: 'main', protected: true, protection: { enabled: false } } };
1052
- if (mode === 'confirmed-unprotected') {
1053
- evidence.rules = { status: 200, headers: {}, data: [] };
1054
- evidence.rulesets = { status: 200, headers: {}, data: [] };
1055
- evidence.branch = { status: 200, data: { name: 'main', protected: false, protection: { enabled: false } } };
950
+ }
951
+ ];
952
+ assert.equal((await prInfo(context, { issueNumber: 17, prNumber: 23 })).headSha, head);
953
+ assert.equal(state.closingPageIndex, 2);
954
+ });
955
+ it("refuses an incomplete later page even after finding the intended closing issue", async () => {
956
+ const { reviewerContext, state, artifact } = fixture();
957
+ state.closingPages = [
958
+ {
959
+ repository: {
960
+ nameWithOwner: repo,
961
+ pullRequest: {
962
+ number: 23,
963
+ closingIssuesReferences: {
964
+ nodes: [{ number: 17, repository: { nameWithOwner: repo } }],
965
+ pageInfo: { hasNextPage: true, endCursor: "NEXT" }
1056
966
  }
1057
- await startIssueBranch(context, 17);
1058
- state.remoteHead = head;
1059
- const preview = await publishPr(context, { issueNumber: 17, nonClosing: true, dryRun: true });
1060
- assert.equal(state.creations, 0);
1061
- const created = await publishPr(context, { issueNumber: 17, nonClosing: true });
1062
- assert.equal(state.creations, 1);
1063
- const route = await preflightReviewRoute(context, 'main');
1064
- assert.equal(route.rules.visibility, 'complete');
1065
- assert.equal(route.rules.observedRequiredApprovals, mode === 'confirmed-unprotected' ? 0 : 1);
1066
- const reviewPreview = await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1067
- assert.equal(state.submissions, 0);
1068
- const reviewed = await submitFormalReview(reviewerContext, { ...input, artifact });
1069
- assert.equal(state.submissions, 1);
1070
- assert.equal(state.reviews[0]?.commit_id, head);
1071
- assert.equal(state.reviews[0]?.user.login, 'reviewer[bot]');
1072
- assert.equal(state.issueState, 'open');
1073
- assert.equal(state.issueBody, 'Four retained criteria');
1074
- assert.equal(state.updates, 0);
1075
- assert.equal(JSON.stringify([preview, created, reviewPreview, reviewed]).includes(token), false);
967
+ }
1076
968
  }
1077
- finally {
1078
- restore();
969
+ },
970
+ { repository: null }
971
+ ];
972
+ await assert.rejects(
973
+ submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }),
974
+ /association/u
975
+ );
976
+ assert.equal(state.closingPageIndex, 2);
977
+ assert.equal(state.submissions, 0);
978
+ });
979
+ it("preserves configured reviewer separation and stale artifact/head refusals", async () => {
980
+ const { context, reviewerContext, state, artifact } = fixture();
981
+ await assert.rejects(submitFormalReview(context, { issueNumber: 17, prNumber: 23, artifact }), /reviewer.*role/u);
982
+ state.reviewerActor = "author";
983
+ await assert.rejects(submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }), /differ/u);
984
+ state.reviewerActor = "reviewer[bot]";
985
+ state.movedOnRead = state.reads + 2;
986
+ await assert.rejects(
987
+ submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact }),
988
+ /head|moved/u
989
+ );
990
+ assert.equal(state.submissions, 0);
991
+ });
992
+ it("submits a fresh valid artifact despite an older remapped App review", async () => {
993
+ const { reviewerContext, state, artifact } = fixture();
994
+ await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
995
+ state.reviews[0].body = `<!-- ai-delivery-review-artifact: sha256:${"f".repeat(64)} -->`;
996
+ await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
997
+ assert.equal(state.submissions, 2);
998
+ });
999
+ });
1000
+ describe("authoritative existing PR promotion", () => {
1001
+ const input = { issueNumber: 17, headBranch: "issue/17", draft: false };
1002
+ it("promotes after publication and exact-head review, then reuses authoritative ready readback", async () => {
1003
+ const { context, reviewerContext, state, artifact } = fixture();
1004
+ await submitFormalReview(reviewerContext, { issueNumber: 17, prNumber: 23, artifact });
1005
+ const preview = await publishPr(context, { ...input, dryRun: true });
1006
+ assert.equal(preview.prNumber, 23);
1007
+ assert.ok("dryRun" in preview);
1008
+ assert.equal(preview.draft, true);
1009
+ assert.equal(state.promotions, 0);
1010
+ const promoted = await publishPr(context, input);
1011
+ const reused = await publishPr(context, input);
1012
+ assert.equal(promoted.prNumber, 23);
1013
+ assert.ok("state" in promoted);
1014
+ assert.equal(promoted.state, "open");
1015
+ assert.deepEqual(reused, promoted);
1016
+ assert.equal(state.promotions, 1);
1017
+ assert.equal(state.creations, 0);
1018
+ assert.equal(state.submissions, 1);
1019
+ assert.equal(state.linked, false);
1020
+ assert.deepEqual(state.events, []);
1021
+ });
1022
+ for (const [name, change] of [
1023
+ ["wrong issue", { issueNumber: 18 }],
1024
+ ["foreign PR head repository", { headRepo: "other/widget" }],
1025
+ ["foreign PR base repository", { baseRepo: "other/widget" }],
1026
+ ["foreign native repository", { associationRepo: "other/widget" }],
1027
+ ["wrong native PR", { associationPr: 24 }],
1028
+ ["wrong author", { prAuthor: "collaborator" }],
1029
+ ["wrong head", { headSha: "d".repeat(40) }],
1030
+ ["moved remote head", { remoteHead: "d".repeat(40) }],
1031
+ ["wrong ref", { headRef: "other" }],
1032
+ ["wrong base", { baseRef: "release" }],
1033
+ ["closed PR", { prState: "closed" }],
1034
+ ["missing node identity", { nodeId: "" }],
1035
+ ["incomplete draft state", { draft: void 0 }],
1036
+ ["ambiguous matches", { matchReadback: [{ number: 23 }, { number: 24 }] }],
1037
+ ["incomplete match identity", { matchReadback: [{}] }],
1038
+ ["incomplete match connection", { matchReadback: {} }],
1039
+ ["incomplete association", { closingReadback: { repository: null } }]
1040
+ ]) {
1041
+ it(`refuses ${name} before promotion, including already-ready reuse`, async () => {
1042
+ for (const draft of [true, false]) {
1043
+ const { context, state } = fixture();
1044
+ state.draft = draft;
1045
+ Object.assign(state, change);
1046
+ await assert.rejects(publishPr(context, input));
1047
+ assert.equal(state.promotions, 0);
1048
+ assert.equal(state.creations, 0);
1049
+ assert.deepEqual(state.events, []);
1050
+ }
1051
+ });
1052
+ }
1053
+ for (const read of [2, 3]) {
1054
+ it(`refuses head drift on authoritative PR read ${read} before mutation`, async () => {
1055
+ const { context, state } = fixture();
1056
+ state.readHook = (count) => {
1057
+ if (count === read) state.headSha = state.remoteHead = "d".repeat(40);
1058
+ };
1059
+ await assert.rejects(publishPr(context, input), /drift/u);
1060
+ assert.equal(state.promotions, 0);
1061
+ });
1062
+ }
1063
+ it("refuses author and native node drift immediately before mutation", async () => {
1064
+ for (const field of ["prAuthor", "nodeId"]) {
1065
+ const { context, state } = fixture();
1066
+ state.readHook = (count) => {
1067
+ if (count === 3) state[field] = "changed";
1068
+ };
1069
+ await assert.rejects(publishPr(context, input), /drift/u);
1070
+ assert.equal(state.promotions, 0);
1071
+ }
1072
+ });
1073
+ for (const response of [
1074
+ {},
1075
+ { markPullRequestReadyForReview: null },
1076
+ { markPullRequestReadyForReview: { pullRequest: { id: "PR24", isDraft: false } } },
1077
+ { markPullRequestReadyForReview: { pullRequest: { id: "PR23" } } }
1078
+ ]) {
1079
+ it("refuses incomplete or conflicting mutation acknowledgement without retrying it", async () => {
1080
+ const { context, state } = fixture();
1081
+ state.promotionReadback = response;
1082
+ await assert.rejects(publishPr(context, input), /mutation readback/u);
1083
+ assert.equal(state.promotions, 1);
1084
+ assert.equal(state.creations, 0);
1085
+ });
1086
+ }
1087
+ it("refuses a still-draft authoritative readback after a ready acknowledgement", async () => {
1088
+ const { context, state } = fixture();
1089
+ state.keepDraftOnPromotion = true;
1090
+ await assert.rejects(publishPr(context, input), /still draft/u);
1091
+ assert.equal(state.promotions, 1);
1092
+ });
1093
+ it("refuses post-mutation head or association drift without another mutation", async () => {
1094
+ for (const kind of ["head", "association"]) {
1095
+ const { context, state } = fixture();
1096
+ state.readHook = (count) => {
1097
+ if (count === 4) {
1098
+ if (kind === "head") state.headSha = state.remoteHead = "d".repeat(40);
1099
+ else state.closingReadback = { repository: null };
1079
1100
  }
1101
+ };
1102
+ await assert.rejects(publishPr(context, input), /drift|association/u);
1103
+ assert.equal(state.promotions, 1);
1104
+ }
1105
+ });
1106
+ it("requires an explicit head after branch links disappear and preserves draft on reuse", async () => {
1107
+ const { context, state } = fixture();
1108
+ await assert.rejects(publishPr(context, { issueNumber: 17, draft: false }), /linked/u);
1109
+ await publishPr(context, { ...input, draft: true });
1110
+ assert.equal(state.promotions, 0);
1111
+ });
1112
+ it("creates a ready PR directly from a pushed remote head without native branch setup", async () => {
1113
+ const { context, state } = fixture(false);
1114
+ state.remoteHead = head;
1115
+ state.expectedCreationDraft = false;
1116
+ const created = await publishPr(context, input);
1117
+ assert.ok("state" in created);
1118
+ assert.equal(created.state, "open");
1119
+ assert.equal(state.creations, 1);
1120
+ assert.equal(state.promotions, 0);
1121
+ assert.equal(state.events.includes("native-start"), false);
1122
+ });
1123
+ it("keeps incomplete native branch readback behind the unchanged start gate", async () => {
1124
+ const { context, state } = fixture(false);
1125
+ state.branchReadback = { repository: null };
1126
+ await assert.rejects(startIssueBranch(context, 17), /Incomplete/u);
1127
+ assert.deepEqual(state.events, []);
1128
+ });
1129
+ it("retains the configured author role before promotion", async () => {
1130
+ const { reviewerContext, state } = fixture();
1131
+ await assert.rejects(publishPr(reviewerContext, input), /author/u);
1132
+ assert.equal(state.promotions, 0);
1133
+ });
1134
+ });
1135
+ describe("canonical publication footer and exact-body recovery", () => {
1136
+ const footer = "\n\n<!-- ai-delivery:pr@1 -->";
1137
+ const substantive = "Original intent.\r\nKeep trailing spaces. \n\n";
1138
+ for (const ready of [false, true]) {
1139
+ it(`marks new closing publication once and reuses original unmarked input (${ready ? "ready" : "draft"})`, async () => {
1140
+ const { context, state } = fixture(false);
1141
+ state.linked = true;
1142
+ state.remoteHead = head;
1143
+ state.expectedCreationDraft = !ready;
1144
+ const input = { issueNumber: 17, headBranch: "issue/17", body: substantive, draft: !ready };
1145
+ const expected = `Closes #17
1146
+
1147
+ ${substantive}${footer}`;
1148
+ const preview = await publishPr(context, { ...input, dryRun: true });
1149
+ assert.equal(Reflect.get(preview, "body"), expected);
1150
+ assert.equal(state.creations + state.updates + state.promotions, 0);
1151
+ await publishPr(context, input);
1152
+ assert.equal(state.body, expected);
1153
+ await publishPr(context, input);
1154
+ await publishPr(context, { ...input, draft: false });
1155
+ await publishPr(context, { ...input, body: expected, draft: false });
1156
+ assert.equal(state.body, expected);
1157
+ assert.equal(state.creations, 1);
1158
+ assert.equal(state.updates, 0);
1159
+ assert.equal(state.promotions, ready ? 0 : 1);
1080
1160
  });
1081
- for (const [name, change] of [
1082
- ['generic protection 404', { protectionError: { status: 404, response: { data: { message: 'Not Found' } } } }],
1083
- [
1084
- 'denied protection',
1085
- { protectionError: { status: 403, response: { data: { message: 'Branch not protected' } } } },
1086
- ],
1087
- ['denied applicable rules', { deniedRoute: '/rules/branches/main' }],
1088
- [
1089
- 'denied repository',
1090
- { deniedRoute: '', repository: { status: 403, data: { full_name: repo, permissions: { push: true } } } },
1091
- ],
1092
- ['denied parent rulesets', { deniedRoute: '/rulesets' }],
1093
- [
1094
- 'incomplete rules',
1095
- { rules: { status: 200, headers: { link: '<https://api.github.com/next>; rel="next"' }, data: [] } },
1096
- ],
1097
- ]) {
1098
- it(`refuses ${name} through real machine sanitization before publication or review`, async () => {
1099
- const { context, reviewerContext, state, artifact, evidence, restore, token } = await machineRulesetOnlyFixture(false);
1100
- try {
1101
- evidence.branch = { status: 200, data: { name: 'main', protected: true, protection: { enabled: false } } };
1102
- await startIssueBranch(context, 17);
1103
- state.remoteHead = head;
1104
- Object.assign(evidence, change);
1105
- for (const operation of [
1106
- () => publishPr(context, { issueNumber: 17, nonClosing: true }),
1107
- () => {
1108
- state.published = true;
1109
- return submitFormalReview(reviewerContext, { ...input, artifact });
1110
- },
1111
- ])
1112
- await assert.rejects(operation(), (error) => {
1113
- assert.ok(error instanceof DeliveryError);
1114
- assert.equal(JSON.stringify(error).includes(token), false);
1115
- return true;
1116
- });
1117
- assert.equal(state.creations, 0);
1118
- assert.equal(state.submissions, 0);
1119
- assert.equal(state.updates, 0);
1120
- }
1121
- finally {
1122
- restore();
1123
- }
1161
+ }
1162
+ it("marks admitted non-closing creation and continues with original unmarked intent", async () => {
1163
+ const { context, state } = fixture(false, true);
1164
+ state.linked = true;
1165
+ state.remoteHead = head;
1166
+ const input = { ...nonClosingCreation, body: `References ${repo}#17
1167
+
1168
+ ${substantive}` };
1169
+ const preview = await publishPr(context, { ...input, dryRun: true });
1170
+ assert.equal(Reflect.get(preview, "body"), input.body + footer);
1171
+ await publishPr(context, input);
1172
+ await publishPr(context, { ...input, prNumber: 23 });
1173
+ await publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, body: input.body, draft: false });
1174
+ assert.equal(state.body, input.body + footer);
1175
+ assert.equal(state.creations, 1);
1176
+ assert.equal(state.updates, 0);
1177
+ assert.equal(state.promotions, 1);
1178
+ assert.equal(state.issueState, "open");
1179
+ });
1180
+ for (const nonClosing of [false, true]) {
1181
+ it(`reconciles lost creation acknowledgement with original body without another mutation (${nonClosing})`, async () => {
1182
+ const { context, state } = fixture(false, nonClosing);
1183
+ state.linked = true;
1184
+ state.remoteHead = head;
1185
+ state.failCreateAck = true;
1186
+ const input = nonClosing ? nonClosingCreation : { issueNumber: 17, body: substantive };
1187
+ await assert.rejects(publishPr(context, input), /acknowledgement is uncertain/u);
1188
+ const expected = nonClosing ? nonClosingCreation.body : `Closes #17
1189
+
1190
+ ${substantive}`;
1191
+ assert.equal(state.body, expected + footer);
1192
+ state.failCreateAck = false;
1193
+ await publishPr(context, { ...input, prNumber: 23 });
1194
+ assert.equal(state.creations, 1);
1195
+ assert.equal(state.updates, 0);
1196
+ assert.equal(state.body, expected + footer);
1197
+ });
1198
+ it(`does not backfill a historical unmarked PR or permit a marker-only transition (${nonClosing})`, async () => {
1199
+ const { context, state } = fixture(true, nonClosing);
1200
+ const original = state.body;
1201
+ const input = { issueNumber: 17, prNumber: 23, nonClosing, body: original };
1202
+ await publishPr(context, input);
1203
+ assert.equal(state.body, original);
1204
+ await assert.rejects(publishPr(context, { ...input, body: original + footer }), /marker|footer|conflict/iu);
1205
+ assert.equal(state.body, original);
1206
+ assert.equal(state.creations + state.updates + state.promotions, 0);
1207
+ });
1208
+ }
1209
+ for (const malformed of [
1210
+ "Closes #17\n\n<!-- ai-delivery:pr@2 -->",
1211
+ `Closes #17${footer}
1212
+ `,
1213
+ `Closes #17${footer}${footer}`,
1214
+ `Closes #17${footer}
1215
+
1216
+ Later text.`,
1217
+ `Closes #17
1218
+
1219
+ <div>
1220
+ ${footer}
1221
+ </div>`
1222
+ ]) {
1223
+ for (const published of [false, true]) {
1224
+ it(`refuses malformed or ambiguous publication markers without repair (${published}, ${JSON.stringify(malformed)})`, async () => {
1225
+ const { context, state } = fixture(published);
1226
+ state.linked = true;
1227
+ state.remoteHead = head;
1228
+ if (published) state.body = malformed;
1229
+ await assert.rejects(publishPr(context, { issueNumber: 17, body: malformed }), /marker|footer|conflict/iu);
1230
+ assert.equal(state.creations + state.updates + state.promotions, 0);
1231
+ });
1232
+ }
1233
+ }
1234
+ it("preserves quoted marker examples and substantive bytes while adding one active footer", async () => {
1235
+ const { context, state } = fixture(false);
1236
+ state.linked = true;
1237
+ state.remoteHead = head;
1238
+ const body = "Closes #17\n\nExample:\n\n```md\n<!-- ai-delivery:pr@1 -->\n```\n\nText. \r\n";
1239
+ await publishPr(context, { issueNumber: 17, body });
1240
+ await publishPr(context, { issueNumber: 17, prNumber: 23, body });
1241
+ assert.equal(state.body, body + footer);
1242
+ assert.equal(state.creations, 1);
1243
+ assert.equal(state.updates, 0);
1244
+ });
1245
+ });
1246
+ describe("directory-independent exact-PR contract", () => {
1247
+ it("uses the existing MCP selector for author dry-run, promotion and ready reuse outside a checkout", async () => {
1248
+ const root = mkdtempSync(join(tmpdir(), "delivery-pr-promotion-"));
1249
+ const { context, state } = fixture();
1250
+ vi.spyOn(settings, "loadDeliverySettings").mockResolvedValue(
1251
+ context.config
1252
+ );
1253
+ vi.spyOn(issues, "loadDeliveryContext").mockImplementation(async (input2) => {
1254
+ assert.equal(input2.repository, repo);
1255
+ assert.equal(input2.repoRoot, root);
1256
+ assert.equal(input2.role, "author");
1257
+ return context;
1258
+ });
1259
+ const server = createAiDeliveryMcpServer({ repoRoot: root });
1260
+ const client = new Client({ name: "promotion-fixture", version: "1" });
1261
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
1262
+ const input = { repo, issueNumber: 17, headBranch: "issue/17", draft: false };
1263
+ try {
1264
+ await server.connect(serverTransport);
1265
+ await client.connect(clientTransport);
1266
+ const preview = await client.callTool({ name: "issue_pr_create", arguments: { ...input, dryRun: true } });
1267
+ assert.equal(preview.isError, void 0);
1268
+ assert.equal(state.promotions, 0);
1269
+ for (let call = 0; call < 2; call++) {
1270
+ const result = await client.callTool({ name: "issue_pr_create", arguments: input });
1271
+ assert.equal(result.isError, void 0);
1272
+ }
1273
+ assert.equal(state.promotions, 1);
1274
+ assert.equal(state.creations, 0);
1275
+ assert.equal(state.draft, false);
1276
+ assert.equal(state.linked, false);
1277
+ } finally {
1278
+ await client.close();
1279
+ await server.close();
1280
+ rmSync(root, { recursive: true, force: true });
1281
+ }
1282
+ });
1283
+ it("dispatches native inspection and App dry-run through MCP from a non-Git directory", async () => {
1284
+ const root = mkdtempSync(join(tmpdir(), "delivery-pr-association-"));
1285
+ const { context, reviewerContext, state, artifact } = fixture();
1286
+ vi.spyOn(settings, "loadDeliverySettings").mockResolvedValue(
1287
+ context.config
1288
+ );
1289
+ const loader = vi.spyOn(issues, "loadDeliveryContext").mockImplementation(async (input) => {
1290
+ assert.equal(input.repository, repo);
1291
+ assert.equal(input.repoRoot, root);
1292
+ return input.role === "reviewer" ? reviewerContext : context;
1293
+ });
1294
+ const server = createAiDeliveryMcpServer({ repoRoot: root });
1295
+ const client = new Client({ name: "exact-pr-fixture", version: "1" });
1296
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
1297
+ try {
1298
+ await server.connect(serverTransport);
1299
+ await client.connect(clientTransport);
1300
+ const info = await client.callTool({ name: "issue_pr_info", arguments: { repo, issueNumber: 17, prNumber: 23 } });
1301
+ assert.equal(info.isError, void 0, JSON.stringify(info.content));
1302
+ const review = await client.callTool({
1303
+ name: "issue_pr_review",
1304
+ arguments: { repo, issueNumber: 17, prNumber: 23, artifact, dryRun: true }
1305
+ });
1306
+ assert.equal(review.isError, void 0);
1307
+ state.issueNumber = 18;
1308
+ await assert.rejects(
1309
+ executeTool("issue_pr_info", { repo, issueNumber: 17, prNumber: 23 }, { repoRoot: root }),
1310
+ /association/u
1311
+ );
1312
+ assert.deepEqual(
1313
+ loader.mock.calls.map(([input]) => input.role),
1314
+ ["author", "reviewer", "author"]
1315
+ );
1316
+ assert.equal(state.submissions, 0);
1317
+ } finally {
1318
+ await client.close();
1319
+ await server.close();
1320
+ rmSync(root, { recursive: true, force: true });
1321
+ }
1322
+ });
1323
+ it(
1324
+ "documents explicit issue/PR selection in actual CLI help without credentials or a checkout",
1325
+ { tags: ["release"] },
1326
+ () => {
1327
+ const root = mkdtempSync(join(tmpdir(), "delivery-pr-help-"));
1328
+ try {
1329
+ const help = execFileSync(process.execPath, [resolve("dist/cli.js"), "pr:info", "--help"], {
1330
+ cwd: root,
1331
+ env: { HOME: root, PATH: process.env.PATH },
1332
+ encoding: "utf8"
1124
1333
  });
1334
+ assert.match(help, /combine --issue and --pr/u);
1335
+ assert.match(help, /issue-only lookup requires a GitHub-linked\s+branch/u);
1336
+ const creationHelp = execFileSync(process.execPath, [resolve("dist/cli.js"), "pr:create", "--help"], {
1337
+ cwd: root,
1338
+ env: { HOME: root, PATH: process.env.PATH },
1339
+ encoding: "utf8"
1340
+ }).replace(/\s+/gu, " ");
1341
+ assert.match(creationHelp, /Create or reuse an issue-closing PR from a pushed --head, from any directory/u);
1342
+ assert.match(creationHelp, /--base <branch>/u);
1343
+ assert.match(creationHelp, /Pushed remote head/u);
1344
+ assert.match(creationHelp, /--pr <number>/u);
1345
+ assert.match(creationHelp, /--reconcile-non-closing-reference/u);
1346
+ assert.match(creationHelp, /--expected-head <sha>/u);
1347
+ assert.match(creationHelp, /--expected-base <sha>/u);
1348
+ for (const command of ["pr:create", "pr:info", "pr:review", "pr:merge", "finish"]) {
1349
+ const modeHelp = execFileSync(process.execPath, [resolve("dist/cli.js"), command, "--help"], {
1350
+ cwd: root,
1351
+ env: { HOME: root, PATH: process.env.PATH },
1352
+ encoding: "utf8"
1353
+ });
1354
+ assert.match(modeHelp, /--non-closing/u);
1355
+ }
1356
+ } finally {
1357
+ rmSync(root, { recursive: true, force: true });
1358
+ }
1125
1359
  }
1126
- it.each([true, false])('creates and independently reviews a non-closing PR with corroborated rulesets and protection summary %s', async (enabled) => {
1127
- const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture(false);
1128
- evidence.branch = { status: 200, data: { name: 'main', protected: true, protection: { enabled } } };
1129
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1360
+ );
1361
+ });
1362
+ describe("explicit native non-closing reference delivery", () => {
1363
+ const input = { issueNumber: 17, prNumber: 23, nonClosing: true };
1364
+ it.each(["ruleset-only", "ruleset-only with disabled protection summary", "confirmed-unprotected"])(
1365
+ "creates and reviews %s protection through the real machine client and sanitizer",
1366
+ async (mode) => {
1367
+ const { context, reviewerContext, state, artifact, evidence, restore, token } = await machineRulesetOnlyFixture(false);
1368
+ try {
1369
+ if (mode === "ruleset-only with disabled protection summary")
1370
+ evidence.branch = { status: 200, data: { name: "main", protected: true, protection: { enabled: false } } };
1371
+ if (mode === "confirmed-unprotected") {
1372
+ evidence.rules = { status: 200, headers: {}, data: [] };
1373
+ evidence.rulesets = { status: 200, headers: {}, data: [] };
1374
+ evidence.branch = { status: 200, data: { name: "main", protected: false, protection: { enabled: false } } };
1375
+ }
1130
1376
  await startIssueBranch(context, 17);
1131
1377
  state.remoteHead = head;
1132
- const preview = await publishPr(context, { issueNumber: 17, nonClosing: true, dryRun: true });
1133
- assert.equal(preview.nonClosing, true);
1378
+ const preview = await publishPr(context, { ...nonClosingCreation, dryRun: true });
1134
1379
  assert.equal(state.creations, 0);
1135
- await publishPr(context, { issueNumber: 17, nonClosing: true });
1380
+ const created = await publishPr(context, nonClosingCreation);
1136
1381
  assert.equal(state.creations, 1);
1137
- assert.equal(state.issueState, 'open');
1138
- assert.equal(state.issueBody, 'Four retained criteria');
1139
- await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1382
+ const route = await preflightReviewRoute(context, "main");
1383
+ assert.equal(route.rules.visibility, "complete");
1384
+ assert.equal(route.rules.observedRequiredApprovals, mode === "confirmed-unprotected" ? 0 : 1);
1385
+ const reviewPreview = await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1140
1386
  assert.equal(state.submissions, 0);
1141
- await submitFormalReview(reviewerContext, { ...input, artifact });
1387
+ const reviewed = await submitFormalReview(reviewerContext, { ...input, artifact });
1142
1388
  assert.equal(state.submissions, 1);
1143
1389
  assert.equal(state.reviews[0]?.commit_id, head);
1144
- assert.equal(state.reviews[0]?.user.login, 'reviewer[bot]');
1390
+ assert.equal(state.reviews[0]?.user.login, "reviewer[bot]");
1391
+ assert.equal(state.issueState, "open");
1392
+ assert.equal(state.issueBody, "Four retained criteria");
1145
1393
  assert.equal(state.updates, 0);
1146
- });
1147
- for (const [name, change] of [
1148
- ['generic 404', { protectionError: { status: 404, response: { status: 404, data: { message: 'Not Found' } } } }],
1149
- [
1150
- 'permission 404',
1151
- { protectionError: { status: 404, response: { status: 403, data: { message: 'Branch not protected' } } } },
1152
- ],
1153
- ['denied protection', { deniedRoute: 'GET /repos/{owner}/{repo}/branches/{branch}/protection' }],
1154
- ['denied applicable rules', { deniedRoute: 'GET /repos/{owner}/{repo}/rules/branches/{branch}' }],
1155
- ['denied repository', { deniedRoute: 'GET /repos/{owner}/{repo}' }],
1156
- ['denied branch', { deniedRoute: 'GET /repos/{owner}/{repo}/branches/{branch}' }],
1157
- ['denied parent rulesets', { deniedRoute: 'GET /repos/{owner}/{repo}/rulesets' }],
1158
- [
1159
- 'foreign repository',
1160
- { repository: { status: 200, data: { full_name: 'other/widget', permissions: { push: true } } } },
1161
- ],
1162
- ['unknown author write access', { repository: { status: 200, data: { full_name: repo, permissions: {} } } }],
1163
- [
1164
- 'foreign branch',
1165
- { branch: { status: 200, data: { name: 'other', protected: true, protection: { enabled: true } } } },
1166
- ],
1167
- [
1168
- 'conflicting branch protection',
1169
- { branch: { status: 200, data: { name: 'main', protected: false, protection: { enabled: true } } } },
1170
- ],
1171
- [
1172
- 'unprotected branch with active rulesets',
1173
- { branch: { status: 200, data: { name: 'main', protected: false, protection: { enabled: false } } } },
1174
- ],
1175
- ['missing protected branch summary', { branch: { status: 200, data: { name: 'main', protected: true } } }],
1176
- ['missing enabled summary', { branch: { status: 200, data: { name: 'main', protected: true, protection: {} } } }],
1177
- [
1178
- 'null enabled summary',
1179
- { branch: { status: 200, data: { name: 'main', protected: true, protection: { enabled: null } } } },
1180
- ],
1181
- [
1182
- 'string enabled summary',
1183
- { branch: { status: 200, data: { name: 'main', protected: true, protection: { enabled: 'false' } } } },
1184
- ],
1185
- [
1186
- 'numeric enabled summary',
1187
- { branch: { status: 200, data: { name: 'main', protected: true, protection: { enabled: 0 } } } },
1188
- ],
1189
- ['missing ruleset page headers', { rulesets: { status: 200, data: [] } }],
1190
- [
1191
- 'incomplete parent ruleset page',
1192
- { rulesets: { status: 200, headers: { link: '<https://api.github.com/next>; rel="next"' }, data: [] } },
1193
- ],
1194
- ['malformed parent rulesets', { rulesets: { status: 200, headers: {}, data: null } }],
1195
- ['uncorroborated rulesets', { rulesets: { status: 200, headers: {}, data: [] } }],
1196
- [
1197
- 'inactive applicable ruleset',
1198
- {
1199
- rulesets: {
1200
- status: 200,
1201
- headers: {},
1202
- data: [
1203
- { id: 41, source_type: 'Repository', source: repo, enforcement: 'evaluate' },
1204
- { id: 42, source_type: 'Organization', source: 'example', enforcement: 'active' },
1205
- ],
1206
- },
1207
- },
1208
- ],
1209
- [
1210
- 'conflicting source identity',
1211
- {
1212
- rulesets: {
1213
- status: 200,
1214
- headers: {},
1215
- data: [
1216
- { id: 41, source_type: 'Repository', source: 'other/widget', enforcement: 'active' },
1217
- { id: 42, source_type: 'Organization', source: 'example', enforcement: 'active' },
1218
- ],
1219
- },
1220
- },
1221
- ],
1222
- ]) {
1223
- it(`refuses non-closing creation and review with ruleset-only ${name} without mutation`, async () => {
1224
- const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture(false);
1225
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1226
- Object.assign(evidence, change);
1227
- await startIssueBranch(context, 17);
1228
- state.remoteHead = head;
1229
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }), /complete native rule visibility/u);
1230
- assert.equal(state.creations, 0);
1231
- state.published = true;
1232
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /complete native rule visibility/u);
1233
- assert.equal(state.submissions, 0);
1234
- assert.equal(state.promotions, 0);
1235
- assert.equal(state.updates, 0);
1236
- assert.equal(state.issueState, 'open');
1237
- });
1394
+ assert.equal(JSON.stringify([preview, created, reviewPreview, reviewed]).includes(token), false);
1395
+ } finally {
1396
+ restore();
1397
+ }
1238
1398
  }
1239
- it('keeps reviewer permission, distinct-actor and exact-head guards with complete ruleset-only protection', async () => {
1240
- const { context, reviewerContext, state, artifact } = rulesetOnlyFixture();
1241
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1242
- context.reviewerClients.effectiveContentsPermission = 'read';
1243
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /complete native rule visibility/u);
1244
- context.reviewerClients.effectiveContentsPermission = 'write';
1245
- state.reviewerActor = 'author';
1246
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /differ|same GitHub actor/u);
1247
- state.reviewerActor = 'reviewer[bot]';
1248
- state.headSha = 'd'.repeat(40);
1249
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /head|artifact/u);
1250
- assert.equal(state.submissions, 0);
1399
+ );
1400
+ for (const [name, change] of [
1401
+ ["generic protection 404", { protectionError: { status: 404, response: { data: { message: "Not Found" } } } }],
1402
+ [
1403
+ "denied protection",
1404
+ { protectionError: { status: 403, response: { data: { message: "Branch not protected" } } } }
1405
+ ],
1406
+ ["denied applicable rules", { deniedRoute: "/rules/branches/main" }],
1407
+ [
1408
+ "denied repository",
1409
+ { deniedRoute: "", repository: { status: 403, data: { full_name: repo, permissions: { push: true } } } }
1410
+ ],
1411
+ ["denied parent rulesets", { deniedRoute: "/rulesets" }],
1412
+ [
1413
+ "incomplete rules",
1414
+ { rules: { status: 200, headers: { link: '<https://api.github.com/next>; rel="next"' }, data: [] } }
1415
+ ]
1416
+ ]) {
1417
+ it(`refuses ${name} through real machine sanitization before publication or review`, async () => {
1418
+ const { context, reviewerContext, state, artifact, evidence, restore, token } = await machineRulesetOnlyFixture(false);
1419
+ try {
1420
+ evidence.branch = { status: 200, data: { name: "main", protected: true, protection: { enabled: false } } };
1421
+ await startIssueBranch(context, 17);
1422
+ state.remoteHead = head;
1423
+ Object.assign(evidence, change);
1424
+ for (const operation of [
1425
+ () => publishPr(context, nonClosingCreation),
1426
+ () => {
1427
+ state.published = true;
1428
+ return submitFormalReview(reviewerContext, { ...input, artifact });
1429
+ }
1430
+ ])
1431
+ await assert.rejects(operation(), (error) => {
1432
+ assert.ok(error instanceof DeliveryError);
1433
+ assert.equal(JSON.stringify(error).includes(token), false);
1434
+ return true;
1435
+ });
1251
1436
  assert.equal(state.creations, 0);
1252
- assert.equal(state.updates, 0);
1253
- });
1254
- it('does not treat a sanitized machine-session 404 as proof of absent classic protection', async () => {
1255
- const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture();
1256
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1257
- const error = Object.assign(new DeliveryError('Machine GitHub session cannot access the selected operation.'), {
1258
- status: 404,
1259
- });
1260
- setMachineRequestDiagnostics(error, {
1261
- phase: 'rest.request',
1262
- endpoint: 'UNKNOWN',
1263
- status: 404,
1264
- code: undefined,
1265
- requestId: undefined,
1266
- });
1267
- evidence.protectionError = error;
1268
- await assert.rejects(publishPr(context, { ...input, draft: false }), /complete native rule visibility/u);
1269
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /complete native rule visibility/u);
1270
- assert.equal(state.promotions, 0);
1271
1437
  assert.equal(state.submissions, 0);
1272
1438
  assert.equal(state.updates, 0);
1439
+ } finally {
1440
+ restore();
1441
+ }
1273
1442
  });
1274
- for (const name of [
1275
- 'incomplete applicable page',
1276
- 'incomplete parent page',
1277
- 'missing applicable headers',
1278
- 'non-success applicable response',
1279
- 'malformed applicable rules',
1280
- 'missing applicable ruleset identity',
1281
- 'malformed approval count',
1282
- 'duplicate corroborating ruleset',
1283
- 'protected branch with empty rules',
1284
- ]) {
1285
- it(`refuses ${name} despite observed ruleset-only protection without mutation`, async () => {
1286
- const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture();
1287
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1288
- const rules = evidence.rules;
1289
- const rulesets = evidence.rulesets;
1290
- switch (name) {
1291
- case 'incomplete applicable page':
1292
- rules.headers = { link: '<https://api.github.com/next>; rel="next"' };
1293
- break;
1294
- case 'incomplete parent page':
1295
- rulesets.headers = { link: '<https://api.github.com/next>; rel="next"' };
1296
- break;
1297
- case 'missing applicable headers':
1298
- delete rules.headers;
1299
- break;
1300
- case 'non-success applicable response':
1301
- rules.status = 206;
1302
- break;
1303
- case 'malformed applicable rules':
1304
- rules.data = [null];
1305
- break;
1306
- case 'missing applicable ruleset identity':
1307
- rules.data = [{ type: 'pull_request', parameters: { required_approving_review_count: 1 } }];
1308
- break;
1309
- case 'malformed approval count':
1310
- rules.data = [
1311
- {
1312
- type: 'pull_request',
1313
- ruleset_id: 42,
1314
- ruleset_source_type: 'Organization',
1315
- ruleset_source: 'example',
1316
- parameters: { required_approving_review_count: '1' },
1317
- },
1318
- ];
1319
- break;
1320
- case 'duplicate corroborating ruleset':
1321
- rulesets.data.push(rulesets.data[0]);
1322
- break;
1323
- case 'protected branch with empty rules':
1324
- rules.data = [];
1325
- rulesets.data = [];
1326
- break;
1327
- }
1328
- await assert.rejects(publishPr(context, { ...input, draft: false }), /complete native rule visibility/u);
1329
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /complete native rule visibility/u);
1330
- assert.equal(state.creations, 0);
1331
- assert.equal(state.submissions, 0);
1332
- assert.equal(state.promotions, 0);
1333
- assert.equal(state.updates, 0);
1334
- });
1443
+ }
1444
+ it.each([true, false])(
1445
+ "creates and independently reviews a non-closing PR with corroborated rulesets and protection summary %s",
1446
+ async (enabled) => {
1447
+ const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture(false);
1448
+ evidence.branch = { status: 200, data: { name: "main", protected: true, protection: { enabled } } };
1449
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1450
+ await startIssueBranch(context, 17);
1451
+ state.remoteHead = head;
1452
+ const preview = await publishPr(context, { ...nonClosingCreation, dryRun: true });
1453
+ assert.equal(preview.nonClosing, true);
1454
+ assert.equal(state.creations, 0);
1455
+ await publishPr(context, nonClosingCreation);
1456
+ assert.equal(state.creations, 1);
1457
+ assert.equal(state.issueState, "open");
1458
+ assert.equal(state.issueBody, "Four retained criteria");
1459
+ await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1460
+ assert.equal(state.submissions, 0);
1461
+ await submitFormalReview(reviewerContext, { ...input, artifact });
1462
+ assert.equal(state.submissions, 1);
1463
+ assert.equal(state.reviews[0]?.commit_id, head);
1464
+ assert.equal(state.reviews[0]?.user.login, "reviewer[bot]");
1465
+ assert.equal(state.updates, 0);
1335
1466
  }
1336
- it('preserves non-closing publication and exact-head review with readable classic protection', async () => {
1337
- const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture();
1338
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1339
- evidence.protection = {
1340
- status: 200,
1341
- data: { required_pull_request_reviews: { required_approving_review_count: 2 } },
1342
- };
1343
- await publishPr(context, { ...input, draft: false });
1344
- await submitFormalReview(reviewerContext, { ...input, artifact });
1345
- assert.equal(state.promotions, 1);
1346
- assert.equal(state.submissions, 1);
1347
- assert.equal(state.reviews[0]?.commit_id, head);
1348
- assert.equal(state.issueState, 'open');
1349
- });
1350
- it('submits confirmed-unprotected exact-head review while preserving distinct reviewer and stale-head guards', async () => {
1351
- const { context, reviewerContext, state, artifact } = fixture(true, true);
1352
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1353
- let protectionMessage = 'Branch not protected';
1354
- const request = async (route) => {
1355
- if (route.endsWith('/protection'))
1356
- throw { status: 404, response: { status: 404, data: { message: protectionMessage } } };
1357
- if (route.endsWith('/rules/branches/{branch}') || route.endsWith('/rulesets'))
1358
- return { status: 200, headers: {}, data: [] };
1359
- if (route.endsWith('/branches/{branch}'))
1360
- return { status: 200, data: { name: 'main', protected: false, protection: { enabled: false } } };
1361
- if (route === 'GET /repos/{owner}/{repo}')
1362
- return { status: 200, data: { full_name: repo, permissions: { push: true } } };
1363
- throw new Error(`Unexpected fictional route ${route}`);
1364
- };
1365
- context.clients.rest.request = request;
1366
- await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1367
- assert.equal(state.submissions, 0);
1368
- protectionMessage = 'Not Found';
1369
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /complete native rule visibility/u);
1370
- protectionMessage = 'Branch not protected';
1371
- state.reviewerActor = 'author';
1372
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /differ|same GitHub actor/u);
1373
- state.reviewerActor = 'reviewer[bot]';
1374
- state.headSha = 'd'.repeat(40);
1375
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /head|artifact/u);
1376
- state.headSha = head;
1377
- await submitFormalReview(reviewerContext, { ...input, artifact });
1378
- assert.equal(state.submissions, 1);
1379
- assert.equal(state.reviews[0]?.commit_id, head);
1380
- });
1381
- it('accepts the exact native historical reference with empty branch/closing connections', async () => {
1382
- const { context, state } = fixture(true, true);
1383
- assert.equal((await prInfo(context, input)).headSha, head);
1384
- const preview = await publishPr(context, { ...input, draft: false, dryRun: true });
1385
- assert.equal(preview.prNumber, 23);
1386
- assert.equal(preview.nonClosing, true);
1387
- await publishPr(context, { ...input, draft: false });
1388
- await publishPr(context, { ...input, draft: false });
1389
- assert.equal(state.promotions, 1);
1390
- assert.equal(state.updates, 0);
1391
- assert.equal(state.creations, 0);
1392
- assert.equal(state.issueState, 'open');
1393
- assert.equal(state.issueBody, 'Four retained criteria');
1467
+ );
1468
+ for (const [name, change] of [
1469
+ ["generic 404", { protectionError: { status: 404, response: { status: 404, data: { message: "Not Found" } } } }],
1470
+ [
1471
+ "permission 404",
1472
+ { protectionError: { status: 404, response: { status: 403, data: { message: "Branch not protected" } } } }
1473
+ ],
1474
+ ["denied protection", { deniedRoute: "GET /repos/{owner}/{repo}/branches/{branch}/protection" }],
1475
+ ["denied applicable rules", { deniedRoute: "GET /repos/{owner}/{repo}/rules/branches/{branch}" }],
1476
+ ["denied repository", { deniedRoute: "GET /repos/{owner}/{repo}" }],
1477
+ ["denied branch", { deniedRoute: "GET /repos/{owner}/{repo}/branches/{branch}" }],
1478
+ ["denied parent rulesets", { deniedRoute: "GET /repos/{owner}/{repo}/rulesets" }],
1479
+ [
1480
+ "foreign repository",
1481
+ { repository: { status: 200, data: { full_name: "other/widget", permissions: { push: true } } } }
1482
+ ],
1483
+ ["unknown author write access", { repository: { status: 200, data: { full_name: repo, permissions: {} } } }],
1484
+ [
1485
+ "foreign branch",
1486
+ { branch: { status: 200, data: { name: "other", protected: true, protection: { enabled: true } } } }
1487
+ ],
1488
+ [
1489
+ "conflicting branch protection",
1490
+ { branch: { status: 200, data: { name: "main", protected: false, protection: { enabled: true } } } }
1491
+ ],
1492
+ [
1493
+ "unprotected branch with active rulesets",
1494
+ { branch: { status: 200, data: { name: "main", protected: false, protection: { enabled: false } } } }
1495
+ ],
1496
+ ["missing protected branch summary", { branch: { status: 200, data: { name: "main", protected: true } } }],
1497
+ ["missing enabled summary", { branch: { status: 200, data: { name: "main", protected: true, protection: {} } } }],
1498
+ [
1499
+ "null enabled summary",
1500
+ { branch: { status: 200, data: { name: "main", protected: true, protection: { enabled: null } } } }
1501
+ ],
1502
+ [
1503
+ "string enabled summary",
1504
+ { branch: { status: 200, data: { name: "main", protected: true, protection: { enabled: "false" } } } }
1505
+ ],
1506
+ [
1507
+ "numeric enabled summary",
1508
+ { branch: { status: 200, data: { name: "main", protected: true, protection: { enabled: 0 } } } }
1509
+ ],
1510
+ ["missing ruleset page headers", { rulesets: { status: 200, data: [] } }],
1511
+ [
1512
+ "incomplete parent ruleset page",
1513
+ { rulesets: { status: 200, headers: { link: '<https://api.github.com/next>; rel="next"' }, data: [] } }
1514
+ ],
1515
+ ["malformed parent rulesets", { rulesets: { status: 200, headers: {}, data: null } }],
1516
+ ["uncorroborated rulesets", { rulesets: { status: 200, headers: {}, data: [] } }],
1517
+ [
1518
+ "inactive applicable ruleset",
1519
+ {
1520
+ rulesets: {
1521
+ status: 200,
1522
+ headers: {},
1523
+ data: [
1524
+ { id: 41, source_type: "Repository", source: repo, enforcement: "evaluate" },
1525
+ { id: 42, source_type: "Organization", source: "example", enforcement: "active" }
1526
+ ]
1527
+ }
1528
+ }
1529
+ ],
1530
+ [
1531
+ "conflicting source identity",
1532
+ {
1533
+ rulesets: {
1534
+ status: 200,
1535
+ headers: {},
1536
+ data: [
1537
+ { id: 41, source_type: "Repository", source: "other/widget", enforcement: "active" },
1538
+ { id: 42, source_type: "Organization", source: "example", enforcement: "active" }
1539
+ ]
1540
+ }
1541
+ }
1542
+ ]
1543
+ ]) {
1544
+ it(`refuses non-closing creation and review with ruleset-only ${name} without mutation`, async () => {
1545
+ const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture(false);
1546
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1547
+ Object.assign(evidence, change);
1548
+ await startIssueBranch(context, 17);
1549
+ state.remoteHead = head;
1550
+ await assert.rejects(publishPr(context, nonClosingCreation), /complete native rule visibility/u);
1551
+ assert.equal(state.creations, 0);
1552
+ state.published = true;
1553
+ await assert.rejects(
1554
+ submitFormalReview(reviewerContext, { ...input, artifact }),
1555
+ /complete native rule visibility/u
1556
+ );
1557
+ assert.equal(state.submissions, 0);
1558
+ assert.equal(state.promotions, 0);
1559
+ assert.equal(state.updates, 0);
1560
+ assert.equal(state.issueState, "open");
1394
1561
  });
1395
- it('transitions only an exact selected author PR, then reuses the verified body without another update', async () => {
1396
- const { context, state } = fixture();
1397
- const transition = { ...input, body: 'Deliver widget while retaining its issue.' };
1398
- const preview = await publishPr(context, { ...transition, dryRun: true });
1399
- assert.ok('bodyTransition' in preview);
1400
- assert.equal(preview.bodyTransition, true);
1401
- assert.equal(state.updates, 0);
1402
- await publishPr(context, transition);
1403
- await publishPr(context, transition);
1404
- assert.equal(state.body, `References ${repo}#17\n\nDeliver widget while retaining its issue.`);
1405
- assert.equal(state.updates, 1);
1406
- assert.equal(state.creations, 0);
1562
+ }
1563
+ it("keeps reviewer permission, distinct-actor and exact-head guards with complete ruleset-only protection", async () => {
1564
+ const { context, reviewerContext, state, artifact } = rulesetOnlyFixture();
1565
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1566
+ context.reviewerClients.effectiveContentsPermission = "read";
1567
+ await assert.rejects(
1568
+ submitFormalReview(reviewerContext, { ...input, artifact }),
1569
+ /complete native rule visibility/u
1570
+ );
1571
+ context.reviewerClients.effectiveContentsPermission = "write";
1572
+ state.reviewerActor = "author";
1573
+ await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /differ|same GitHub actor/u);
1574
+ state.reviewerActor = "reviewer[bot]";
1575
+ state.headSha = "d".repeat(40);
1576
+ await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /head|artifact/u);
1577
+ assert.equal(state.submissions, 0);
1578
+ assert.equal(state.creations, 0);
1579
+ assert.equal(state.updates, 0);
1580
+ });
1581
+ it("does not treat a sanitized machine-session 404 as proof of absent classic protection", async () => {
1582
+ const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture();
1583
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1584
+ const error = Object.assign(new DeliveryError("Machine GitHub session cannot access the selected operation."), {
1585
+ status: 404
1407
1586
  });
1408
- it('keeps new PR publication behind native start/branch linkage and checks introduced messages first', async () => {
1409
- const { context, state } = fixture(false, true);
1410
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }), /branch/u);
1411
- state.linked = true;
1412
- state.remoteHead = head;
1413
- state.commitMessage = 'Fixes: example/widget#99';
1414
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }), /closing directives/u);
1415
- assert.equal(state.creations, 0);
1416
- state.commitMessage = 'Improve widget';
1417
- await publishPr(context, { issueNumber: 17, nonClosing: true });
1418
- assert.equal(state.creations, 1);
1419
- assert.equal(state.linked, false);
1420
- assert.equal(state.issueState, 'open');
1587
+ setMachineRequestDiagnostics(error, {
1588
+ phase: "rest.request",
1589
+ endpoint: "UNKNOWN",
1590
+ status: 404,
1591
+ code: void 0,
1592
+ requestId: void 0
1421
1593
  });
1422
- it('uses the independent reviewer route for dry-run, submission and authoritative idempotence', async () => {
1423
- const { context, reviewerContext, state, artifact } = fixture(true, true);
1424
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1425
- await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1426
- assert.equal(state.submissions, 0);
1427
- await submitFormalReview(reviewerContext, { ...input, artifact });
1428
- await submitFormalReview(reviewerContext, { ...input, artifact });
1429
- assert.equal(state.submissions, 1);
1430
- assert.equal(state.issueState, 'open');
1594
+ evidence.protectionError = error;
1595
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /complete native rule visibility/u);
1596
+ await assert.rejects(
1597
+ submitFormalReview(reviewerContext, { ...input, artifact }),
1598
+ /complete native rule visibility/u
1599
+ );
1600
+ assert.equal(state.promotions, 0);
1601
+ assert.equal(state.submissions, 0);
1602
+ assert.equal(state.updates, 0);
1603
+ });
1604
+ for (const name of [
1605
+ "incomplete applicable page",
1606
+ "incomplete parent page",
1607
+ "missing applicable headers",
1608
+ "non-success applicable response",
1609
+ "malformed applicable rules",
1610
+ "missing applicable ruleset identity",
1611
+ "malformed approval count",
1612
+ "duplicate corroborating ruleset",
1613
+ "protected branch with empty rules"
1614
+ ]) {
1615
+ it(`refuses ${name} despite observed ruleset-only protection without mutation`, async () => {
1616
+ const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture();
1617
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1618
+ const rules = evidence.rules;
1619
+ const rulesets = evidence.rulesets;
1620
+ switch (name) {
1621
+ case "incomplete applicable page":
1622
+ rules.headers = { link: '<https://api.github.com/next>; rel="next"' };
1623
+ break;
1624
+ case "incomplete parent page":
1625
+ rulesets.headers = { link: '<https://api.github.com/next>; rel="next"' };
1626
+ break;
1627
+ case "missing applicable headers":
1628
+ delete rules.headers;
1629
+ break;
1630
+ case "non-success applicable response":
1631
+ rules.status = 206;
1632
+ break;
1633
+ case "malformed applicable rules":
1634
+ rules.data = [null];
1635
+ break;
1636
+ case "missing applicable ruleset identity":
1637
+ rules.data = [{ type: "pull_request", parameters: { required_approving_review_count: 1 } }];
1638
+ break;
1639
+ case "malformed approval count":
1640
+ rules.data = [
1641
+ {
1642
+ type: "pull_request",
1643
+ ruleset_id: 42,
1644
+ ruleset_source_type: "Organization",
1645
+ ruleset_source: "example",
1646
+ parameters: { required_approving_review_count: "1" }
1647
+ }
1648
+ ];
1649
+ break;
1650
+ case "duplicate corroborating ruleset":
1651
+ rulesets.data.push(rulesets.data[0]);
1652
+ break;
1653
+ case "protected branch with empty rules":
1654
+ rules.data = [];
1655
+ rulesets.data = [];
1656
+ break;
1657
+ }
1658
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /complete native rule visibility/u);
1659
+ await assert.rejects(
1660
+ submitFormalReview(reviewerContext, { ...input, artifact }),
1661
+ /complete native rule visibility/u
1662
+ );
1663
+ assert.equal(state.creations, 0);
1664
+ assert.equal(state.submissions, 0);
1665
+ assert.equal(state.promotions, 0);
1666
+ assert.equal(state.updates, 0);
1431
1667
  });
1432
- for (const directive of [
1433
- 'Closes #17',
1434
- 'CLOSE: #17, #18',
1435
- 'closed example/widget#17',
1436
- 'Fixes: other_owner/other_repo#9',
1437
- 'fixed https://github.com/example/widget/issues/17',
1438
- 'Resolves: https://github.com/example/widget/pull/23',
1439
- 'Resolved **#17**',
1440
- 'Fixes [the issue](https://github.com/example/widget/issues/17)',
1441
- 'Closes \\#17',
1442
- ]) {
1443
- it(`refuses closure syntax in introduced messages: ${directive}`, async () => {
1444
- const { context, state } = fixture(true, true);
1445
- state.commitMessage = directive;
1446
- await assert.rejects(publishPr(context, { ...input, draft: false }), /closing directives/u);
1447
- assert.equal(state.promotions, 0);
1448
- assert.equal(state.updates, 0);
1449
- });
1450
- }
1451
- for (const [name, change] of [
1452
- [
1453
- 'removed current intent',
1454
- (state) => {
1455
- state.body = 'Improve widget';
1456
- },
1457
- ],
1458
- [
1459
- 'changed intended issue',
1460
- (state) => {
1461
- state.body = `References ${repo}#18`;
1462
- },
1463
- ],
1464
- [
1465
- 'conflicting intent declarations',
1466
- (state) => {
1467
- state.body += `\nReferences ${repo}#18`;
1468
- },
1469
- ],
1470
- [
1471
- 'body closure',
1472
- (state) => {
1473
- state.body += '\nFixes #18';
1474
- },
1475
- ],
1476
- [
1477
- 'title closure',
1478
- (state) => {
1479
- state.title = 'Fixes #17';
1480
- },
1481
- ],
1482
- [
1483
- 'closing native event',
1484
- (state) => {
1485
- state.referenceCloses = true;
1486
- },
1487
- ],
1488
- [
1489
- 'unknown native event intent',
1490
- (state) => {
1491
- state.referenceCloses = null;
1492
- },
1493
- ],
1494
- [
1495
- 'unauthorized reference actor',
1496
- (state) => {
1497
- state.referenceActor = 'collaborator';
1498
- },
1499
- ],
1500
- [
1501
- 'wrong PR author',
1502
- (state) => {
1503
- state.prAuthor = 'collaborator';
1504
- },
1505
- ],
1506
- [
1507
- 'closed issue',
1508
- (state) => {
1509
- state.issueState = 'closed';
1510
- },
1511
- ],
1512
- [
1513
- 'foreign PR repository',
1514
- (state) => {
1515
- state.headRepo = 'other/widget';
1516
- },
1517
- ],
1518
- [
1519
- 'moved default base',
1520
- (state) => {
1521
- state.baseSha = 'd'.repeat(40);
1522
- },
1523
- ],
1524
- [
1525
- 'incomplete commits',
1526
- (state) => {
1527
- state.commitReadback = { repository: null };
1528
- },
1529
- ],
1530
- [
1531
- 'missing native reference',
1532
- (state) => {
1533
- state.referenceReadback = {
1534
- repository: {
1535
- id: 'REPO',
1536
- nameWithOwner: repo,
1537
- issue: { id: 'ISSUE17', number: 17, state: 'OPEN', timelineItems: { nodes: [], pageInfo } },
1538
- },
1539
- };
1540
- },
1541
- ],
1668
+ }
1669
+ it("preserves non-closing publication and exact-head review with readable classic protection", async () => {
1670
+ const { context, reviewerContext, state, artifact, evidence } = rulesetOnlyFixture();
1671
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1672
+ evidence.protection = {
1673
+ status: 200,
1674
+ data: { required_pull_request_reviews: { required_approving_review_count: 2 } }
1675
+ };
1676
+ await publishPr(context, { ...input, draft: false });
1677
+ await submitFormalReview(reviewerContext, { ...input, artifact });
1678
+ assert.equal(state.promotions, 1);
1679
+ assert.equal(state.submissions, 1);
1680
+ assert.equal(state.reviews[0]?.commit_id, head);
1681
+ assert.equal(state.issueState, "open");
1682
+ });
1683
+ it("submits confirmed-unprotected exact-head review while preserving distinct reviewer and stale-head guards", async () => {
1684
+ const { context, reviewerContext, state, artifact } = fixture(true, true);
1685
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1686
+ let protectionMessage = "Branch not protected";
1687
+ const request = async (route) => {
1688
+ if (route.endsWith("/protection"))
1689
+ throw { status: 404, response: { status: 404, data: { message: protectionMessage } } };
1690
+ if (route.endsWith("/rules/branches/{branch}") || route.endsWith("/rulesets"))
1691
+ return { status: 200, headers: {}, data: [] };
1692
+ if (route.endsWith("/branches/{branch}"))
1693
+ return { status: 200, data: { name: "main", protected: false, protection: { enabled: false } } };
1694
+ if (route === "GET /repos/{owner}/{repo}")
1695
+ return { status: 200, data: { full_name: repo, permissions: { push: true } } };
1696
+ throw new Error(`Unexpected fictional route ${route}`);
1697
+ };
1698
+ context.clients.rest.request = request;
1699
+ await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1700
+ assert.equal(state.submissions, 0);
1701
+ protectionMessage = "Not Found";
1702
+ await assert.rejects(
1703
+ submitFormalReview(reviewerContext, { ...input, artifact }),
1704
+ /complete native rule visibility/u
1705
+ );
1706
+ protectionMessage = "Branch not protected";
1707
+ state.reviewerActor = "author";
1708
+ await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /differ|same GitHub actor/u);
1709
+ state.reviewerActor = "reviewer[bot]";
1710
+ state.headSha = "d".repeat(40);
1711
+ await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /head|artifact/u);
1712
+ state.headSha = head;
1713
+ await submitFormalReview(reviewerContext, { ...input, artifact });
1714
+ assert.equal(state.submissions, 1);
1715
+ assert.equal(state.reviews[0]?.commit_id, head);
1716
+ });
1717
+ it("accepts the exact native historical reference with empty branch/closing connections", async () => {
1718
+ const { context, state } = fixture(true, true);
1719
+ assert.equal((await prInfo(context, input)).headSha, head);
1720
+ const preview = await publishPr(context, { ...input, draft: false, dryRun: true });
1721
+ assert.equal(preview.prNumber, 23);
1722
+ assert.equal(preview.nonClosing, true);
1723
+ await publishPr(context, { ...input, draft: false });
1724
+ await publishPr(context, { ...input, draft: false });
1725
+ assert.equal(state.promotions, 1);
1726
+ assert.equal(state.updates, 0);
1727
+ assert.equal(state.creations, 0);
1728
+ assert.equal(state.issueState, "open");
1729
+ assert.equal(state.issueBody, "Four retained criteria");
1730
+ });
1731
+ it("transitions only an exact selected author PR, then reuses the verified body without another update", async () => {
1732
+ const { context, state } = fixture();
1733
+ const transition = { ...input, body: "Deliver widget while retaining its issue." };
1734
+ const preview = await publishPr(context, { ...transition, dryRun: true });
1735
+ assert.ok("bodyTransition" in preview);
1736
+ assert.equal(preview.bodyTransition, true);
1737
+ assert.equal(state.updates, 0);
1738
+ await publishPr(context, transition);
1739
+ await publishPr(context, transition);
1740
+ assert.equal(state.body, `References ${repo}#17
1741
+
1742
+ Deliver widget while retaining its issue.`);
1743
+ assert.equal(state.updates, 1);
1744
+ assert.equal(state.creations, 0);
1745
+ });
1746
+ it("keeps new PR publication behind the exact pushed head and checks introduced messages first", async () => {
1747
+ const { context, state } = fixture(false, true);
1748
+ await assert.rejects(publishPr(context, nonClosingCreation), /expected head/u);
1749
+ state.linked = true;
1750
+ state.remoteHead = head;
1751
+ state.commitMessage = "Fixes: example/widget#99";
1752
+ await assert.rejects(publishPr(context, nonClosingCreation), /closing directives/u);
1753
+ assert.equal(state.creations, 0);
1754
+ state.commitMessage = "Improve widget";
1755
+ await publishPr(context, nonClosingCreation);
1756
+ assert.equal(state.creations, 1);
1757
+ assert.equal(state.linked, false);
1758
+ assert.equal(state.issueState, "open");
1759
+ });
1760
+ it("submits exact non-closing review after the default base advances and refuses invalid refs", async () => {
1761
+ const { context, reviewerContext, state, artifact } = fixture(true, true);
1762
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
1763
+ state.remoteBase.object.sha = "d".repeat(40);
1764
+ await submitFormalReview(reviewerContext, { ...input, artifact, dryRun: true });
1765
+ assert.equal(state.submissions, 0);
1766
+ await submitFormalReview(reviewerContext, { ...input, artifact });
1767
+ await submitFormalReview(reviewerContext, { ...input, artifact });
1768
+ assert.equal(state.submissions, 1);
1769
+ assert.equal(state.issueState, "open");
1770
+ for (const ref of [
1771
+ { ref: "", object: { type: "commit", sha: base } },
1772
+ { ref: "refs/heads/other", object: { type: "commit", sha: base } },
1773
+ { ref: "refs/heads/main", object: { type: "tag", sha: base } },
1774
+ { ref: "refs/heads/main", object: { type: "commit", sha: "" } },
1775
+ { ref: "refs/heads/main", object: { type: "commit", sha: "not-a-sha" } }
1542
1776
  ]) {
1543
- it(`refuses ${name} without mutation`, async () => {
1544
- const { context, state } = fixture(true, true);
1545
- change(state);
1546
- await assert.rejects(publishPr(context, { ...input, draft: false }));
1547
- assert.equal(state.promotions + state.creations + state.updates, 0);
1548
- });
1777
+ state.remoteBase = ref;
1778
+ await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }));
1779
+ assert.equal(state.submissions, 1);
1549
1780
  }
1550
- it('requires complete empty closing associations including later pages', async () => {
1551
- const { context, state } = fixture(true, true);
1552
- state.closingPages = [
1553
- {
1554
- repository: {
1555
- nameWithOwner: repo,
1556
- pullRequest: {
1557
- id: 'PR23',
1558
- number: 23,
1559
- closingIssuesReferences: { nodes: [], pageInfo: { hasNextPage: true, endCursor: 'NEXT' } },
1560
- },
1561
- },
1562
- },
1563
- {
1564
- repository: {
1565
- nameWithOwner: repo,
1566
- pullRequest: {
1567
- id: 'PR23',
1568
- number: 23,
1569
- closingIssuesReferences: { nodes: [{ number: 99, repository: { nameWithOwner: repo } }], pageInfo },
1570
- },
1571
- },
1572
- },
1573
- ];
1574
- await assert.rejects(publishPr(context, { ...input, draft: false }), /closing association/u);
1575
- assert.equal(state.promotions, 0);
1781
+ });
1782
+ for (const directive of [
1783
+ "Closes #17",
1784
+ "CLOSE: #17, #18",
1785
+ "closed example/widget#17",
1786
+ "Fixes: other_owner/other_repo#9",
1787
+ "fixed https://github.com/example/widget/issues/17",
1788
+ "Resolves: https://github.com/example/widget/pull/23",
1789
+ "Resolved **#17**",
1790
+ "Fixes [the issue](https://github.com/example/widget/issues/17)",
1791
+ "Closes \\#17"
1792
+ ]) {
1793
+ it(`refuses closure syntax in introduced messages: ${directive}`, async () => {
1794
+ const { context, state } = fixture(true, true);
1795
+ state.commitMessage = directive;
1796
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /closing directives/u);
1797
+ assert.equal(state.promotions, 0);
1798
+ assert.equal(state.updates, 0);
1576
1799
  });
1577
- it('accepts equivalent duplicate native events without duplicating authority, but refuses conflicts', async () => {
1578
- const { context, state } = fixture(true, true);
1579
- const native = (await context.clients.graphql('DeliveryNonClosingReferences', {}));
1580
- const event = native.repository.issue.timelineItems.nodes[0];
1581
- native.repository.issue.timelineItems.nodes.push({ ...event });
1582
- state.referenceReadback = native;
1583
- await prInfo(context, input);
1584
- native.repository.issue.timelineItems.nodes[1].willCloseTarget = true;
1585
- await assert.rejects(prInfo(context, input), /Conflicting/u);
1800
+ }
1801
+ for (const [name, change] of [
1802
+ [
1803
+ "removed current intent",
1804
+ (state) => {
1805
+ state.body = "Improve widget";
1806
+ }
1807
+ ],
1808
+ [
1809
+ "changed intended issue",
1810
+ (state) => {
1811
+ state.body = `References ${repo}#18`;
1812
+ }
1813
+ ],
1814
+ [
1815
+ "conflicting intent declarations",
1816
+ (state) => {
1817
+ state.body += `
1818
+ References ${repo}#18`;
1819
+ }
1820
+ ],
1821
+ [
1822
+ "body closure",
1823
+ (state) => {
1824
+ state.body += "\nFixes #18";
1825
+ }
1826
+ ],
1827
+ [
1828
+ "title closure",
1829
+ (state) => {
1830
+ state.title = "Fixes #17";
1831
+ }
1832
+ ],
1833
+ [
1834
+ "closing native event",
1835
+ (state) => {
1836
+ state.referenceCloses = true;
1837
+ }
1838
+ ],
1839
+ [
1840
+ "unknown native event intent",
1841
+ (state) => {
1842
+ state.referenceCloses = null;
1843
+ }
1844
+ ],
1845
+ [
1846
+ "unauthorized reference actor",
1847
+ (state) => {
1848
+ state.referenceActor = "collaborator";
1849
+ }
1850
+ ],
1851
+ [
1852
+ "wrong PR author",
1853
+ (state) => {
1854
+ state.prAuthor = "collaborator";
1855
+ }
1856
+ ],
1857
+ [
1858
+ "closed issue",
1859
+ (state) => {
1860
+ state.issueState = "closed";
1861
+ }
1862
+ ],
1863
+ [
1864
+ "foreign PR repository",
1865
+ (state) => {
1866
+ state.headRepo = "other/widget";
1867
+ }
1868
+ ],
1869
+ [
1870
+ "moved default base",
1871
+ (state) => {
1872
+ state.baseSha = "d".repeat(40);
1873
+ }
1874
+ ],
1875
+ [
1876
+ "incomplete commits",
1877
+ (state) => {
1878
+ state.commitReadback = { repository: null };
1879
+ }
1880
+ ],
1881
+ [
1882
+ "missing native reference",
1883
+ (state) => {
1884
+ state.referenceReadback = {
1885
+ repository: {
1886
+ id: "REPO",
1887
+ nameWithOwner: repo,
1888
+ issue: { id: "ISSUE17", number: 17, state: "OPEN", timelineItems: { nodes: [], pageInfo } }
1889
+ }
1890
+ };
1891
+ }
1892
+ ]
1893
+ ]) {
1894
+ it(`refuses ${name} without mutation`, async () => {
1895
+ const { context, state } = fixture(true, true);
1896
+ change(state);
1897
+ await assert.rejects(publishPr(context, { ...input, draft: false }));
1898
+ assert.equal(state.promotions + state.creations + state.updates, 0);
1586
1899
  });
1587
- it('refuses incomplete reference pagination after a matching observation', async () => {
1588
- const { context, state } = fixture(true, true);
1589
- const native = (await context.clients.graphql('DeliveryNonClosingReferences', {}));
1590
- native.repository.issue.timelineItems.pageInfo = { hasNextPage: true, endCursor: 'NEXT' };
1591
- state.referencePages = [native, { repository: null }];
1592
- await assert.rejects(publishPr(context, { ...input, draft: false }), /Incomplete/u);
1593
- assert.equal(state.promotions, 0);
1900
+ }
1901
+ it("requires complete empty closing associations including later pages", async () => {
1902
+ const { context, state } = fixture(true, true);
1903
+ state.closingPages = [
1904
+ {
1905
+ repository: {
1906
+ nameWithOwner: repo,
1907
+ pullRequest: {
1908
+ id: "PR23",
1909
+ number: 23,
1910
+ closingIssuesReferences: { nodes: [], pageInfo: { hasNextPage: true, endCursor: "NEXT" } }
1911
+ }
1912
+ }
1913
+ },
1914
+ {
1915
+ repository: {
1916
+ nameWithOwner: repo,
1917
+ pullRequest: {
1918
+ id: "PR23",
1919
+ number: 23,
1920
+ closingIssuesReferences: { nodes: [{ number: 99, repository: { nameWithOwner: repo } }], pageInfo }
1921
+ }
1922
+ }
1923
+ }
1924
+ ];
1925
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /closing association/u);
1926
+ assert.equal(state.promotions, 0);
1927
+ });
1928
+ it("accepts equivalent duplicate native events without duplicating authority, but refuses conflicts", async () => {
1929
+ const { context, state } = fixture(true, true);
1930
+ const native = await context.clients.graphql("DeliveryNonClosingReferences", {});
1931
+ const event = native.repository.issue.timelineItems.nodes[0];
1932
+ native.repository.issue.timelineItems.nodes.push({ ...event });
1933
+ state.referenceReadback = native;
1934
+ await prInfo(context, input);
1935
+ native.repository.issue.timelineItems.nodes[1].willCloseTarget = true;
1936
+ await assert.rejects(prInfo(context, input), /Conflicting/u);
1937
+ });
1938
+ it("refuses incomplete reference pagination after a matching observation", async () => {
1939
+ const { context, state } = fixture(true, true);
1940
+ const native = await context.clients.graphql("DeliveryNonClosingReferences", {});
1941
+ native.repository.issue.timelineItems.pageInfo = { hasNextPage: true, endCursor: "NEXT" };
1942
+ state.referencePages = [native, { repository: null }];
1943
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /Incomplete/u);
1944
+ assert.equal(state.promotions, 0);
1945
+ });
1946
+ it("does not create again after a server-created draft fails association verification", async () => {
1947
+ const { context, state } = fixture(false);
1948
+ state.linked = true;
1949
+ state.remoteHead = head;
1950
+ state.closingReadback = { repository: null };
1951
+ await assert.rejects(
1952
+ publishPr(context, { issueNumber: 17 }),
1953
+ /created PR #23.*post-publication association\/identity verification is unresolved/u
1954
+ );
1955
+ assert.equal((await prInfo(context, { prNumber: 23 })).prNumber, 23);
1956
+ await assert.rejects(publishPr(context, { issueNumber: 17 }));
1957
+ assert.equal(state.creations, 1);
1958
+ assert.equal(state.published, true);
1959
+ });
1960
+ it("preserves uncertain create/update acknowledgements and reconciles without another mutation", async () => {
1961
+ const { context, state } = fixture(false);
1962
+ state.linked = true;
1963
+ state.remoteHead = head;
1964
+ state.failCreateAck = true;
1965
+ await assert.rejects(publishPr(context, { issueNumber: 17 }), /acknowledgement is uncertain/u);
1966
+ assert.equal((await prInfo(context, { prNumber: 23 })).prNumber, 23);
1967
+ state.failCreateAck = false;
1968
+ await publishPr(context, { issueNumber: 17, prNumber: 23 });
1969
+ assert.equal(state.creations, 1);
1970
+ state.failUpdateAck = true;
1971
+ const transition = { ...input, body: "Keep the issue open." };
1972
+ await assert.rejects(publishPr(context, transition), /Transport lost after body update/u);
1973
+ state.failUpdateAck = false;
1974
+ await publishPr(context, transition);
1975
+ assert.equal(state.updates, 1);
1976
+ });
1977
+ it("refuses explicit ambiguity and requires exact numbers for non-closing inspection", async () => {
1978
+ const { context, state } = fixture(true, true);
1979
+ await assert.rejects(prInfo(context, { issueNumber: 17, nonClosing: true }), /explicit/u);
1980
+ state.matchReadback = [{ number: 23 }, { number: 24 }];
1981
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /conflicting/u);
1982
+ assert.equal(state.promotions, 0);
1983
+ });
1984
+ });
1985
+ describe("non-closing complete native graph and mutation drift", () => {
1986
+ const input = { issueNumber: 17, prNumber: 23, nonClosing: true };
1987
+ it("checks earlier introduced commits rather than only the safe head message", async () => {
1988
+ const { context, state } = fixture(true, true);
1989
+ const graph = await context.clients.graphql("DeliveryNonClosingCommits", {});
1990
+ graph.repository.pullRequest.commits.totalCount = 2;
1991
+ graph.repository.pullRequest.commits.nodes.unshift({
1992
+ commit: {
1993
+ oid: "e".repeat(40),
1994
+ message: "Closes: #999",
1995
+ parents: { totalCount: 1, nodes: [{ oid: base }], pageInfo }
1996
+ }
1594
1997
  });
1595
- it('does not create again after a server-created draft fails association verification', async () => {
1596
- const { context, state } = fixture(false);
1597
- state.linked = true;
1598
- state.remoteHead = head;
1599
- state.closingReadback = { repository: null };
1600
- await assert.rejects(publishPr(context, { issueNumber: 17 }), /created PR #23.*post-publication association\/identity verification is unresolved/u);
1601
- assert.equal((await prInfo(context, { prNumber: 23 })).prNumber, 23);
1602
- await assert.rejects(publishPr(context, { issueNumber: 17 }));
1603
- assert.equal(state.creations, 1);
1604
- assert.equal(state.published, true);
1998
+ state.commitReadback = graph;
1999
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /closing directives/u);
2000
+ assert.equal(state.promotions, 0);
2001
+ graph.repository.pullRequest.commits.nodes[0].commit.message = "Earlier improvement";
2002
+ await prInfo(context, input);
2003
+ graph.repository.pullRequest.commits.totalCount = 3;
2004
+ await assert.rejects(prInfo(context, input), /count\/head is incomplete/u);
2005
+ });
2006
+ for (const kind of [
2007
+ "source-node",
2008
+ "source-number",
2009
+ "source-repository",
2010
+ "source-type",
2011
+ "target-node",
2012
+ "target-number",
2013
+ "target-repository",
2014
+ "cross-repository",
2015
+ "missing-actor",
2016
+ "wrong-pr-node"
2017
+ ]) {
2018
+ it(`refuses conflicting native identity ${kind}`, async () => {
2019
+ const { context, state } = fixture(true, true);
2020
+ const native = await context.clients.graphql("DeliveryNonClosingReferences", {});
2021
+ const event = native.repository.issue.timelineItems.nodes[0];
2022
+ if (kind === "source-node") event.source.id = "PROTHER";
2023
+ if (kind === "source-number") event.source.number = 24;
2024
+ if (kind === "source-repository") event.source.repository.nameWithOwner = "other/widget";
2025
+ if (kind === "source-type") event.source.__typename = "Issue";
2026
+ if (kind === "target-node") event.target.id = "ISSUEOTHER";
2027
+ if (kind === "target-number") event.target.number = 18;
2028
+ if (kind === "target-repository") event.target.repository.id = "OTHER";
2029
+ if (kind === "cross-repository") event.isCrossRepository = true;
2030
+ if (kind === "missing-actor") event.actor = null;
2031
+ if (kind === "wrong-pr-node") state.nodeId = "OTHER";
2032
+ state.referenceReadback = native;
2033
+ await assert.rejects(publishPr(context, { ...input, draft: false }));
2034
+ assert.equal(state.promotions + state.creations + state.updates, 0);
1605
2035
  });
1606
- it('preserves uncertain create/update acknowledgements and reconciles without another mutation', async () => {
1607
- const { context, state } = fixture(false);
1608
- state.linked = true;
1609
- state.remoteHead = head;
1610
- state.failCreateAck = true;
1611
- await assert.rejects(publishPr(context, { issueNumber: 17 }), /acknowledgement is uncertain/u);
1612
- assert.equal((await prInfo(context, { prNumber: 23 })).prNumber, 23);
1613
- state.failCreateAck = false;
1614
- await publishPr(context, { issueNumber: 17, prNumber: 23 });
1615
- assert.equal(state.creations, 1);
1616
- state.failUpdateAck = true;
1617
- const transition = { ...input, body: 'Keep the issue open.' };
1618
- await assert.rejects(publishPr(context, transition), /Transport lost after body update/u);
1619
- state.failUpdateAck = false;
1620
- await publishPr(context, transition);
1621
- assert.equal(state.updates, 1);
2036
+ }
2037
+ it("refuses changed issue criteria on promotion readback without another ready mutation", async () => {
2038
+ const { context, state } = fixture(true, true);
2039
+ state.readHook = () => {
2040
+ if (state.promotions) state.issueBody = "External changed criteria";
2041
+ };
2042
+ await assert.rejects(publishPr(context, { ...input, draft: false }), /criteria drifted/u);
2043
+ assert.equal(state.promotions, 1);
2044
+ assert.equal(state.issueState, "open");
2045
+ });
2046
+ it("refuses changed body during formal review readback without a duplicate review", async () => {
2047
+ const { context, reviewerContext, state, artifact } = fixture(true, true);
2048
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
2049
+ state.readHook = () => {
2050
+ if (state.submissions) state.body = "External removed reference";
2051
+ };
2052
+ await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /References line/u);
2053
+ assert.equal(state.submissions, 1);
2054
+ assert.equal(state.issueState, "open");
2055
+ });
2056
+ });
2057
+ describe("exact created intent and native reader bounds", () => {
2058
+ for (const drift of ["body", "title", "draft", "closed", "base"]) {
2059
+ it(`reports created identity but refuses post-publication ${drift} drift without a replacement`, async () => {
2060
+ const { context, state } = fixture(false, true);
2061
+ state.linked = true;
2062
+ state.remoteHead = head;
2063
+ state.readHook = () => {
2064
+ if (!state.creations) return;
2065
+ if (drift === "body") state.body = `References ${repo}#17
2066
+
2067
+ Other safe intent`;
2068
+ if (drift === "title") state.title = "Other safe title";
2069
+ if (drift === "draft") state.draft = false;
2070
+ if (drift === "closed") state.prState = "closed";
2071
+ if (drift === "base") state.baseSha = "d".repeat(40);
2072
+ };
2073
+ await assert.rejects(publishPr(context, nonClosingCreation), /created PR #23.*differs from publication intent/u);
2074
+ assert.equal(state.creations, 1);
2075
+ await assert.rejects(publishPr(context, nonClosingCreation));
2076
+ assert.equal(state.creations, 1);
1622
2077
  });
1623
- it('refuses explicit ambiguity and requires exact numbers for non-closing inspection', async () => {
1624
- const { context, state } = fixture(true, true);
1625
- await assert.rejects(prInfo(context, { issueNumber: 17, nonClosing: true }), /explicit/u);
1626
- state.matchReadback = [{ number: 23 }, { number: 24 }];
1627
- await assert.rejects(publishPr(context, { ...input, draft: false }), /conflicting/u);
1628
- assert.equal(state.promotions, 0);
2078
+ }
2079
+ for (const id of [1, true, {}, null, "", " "]) {
2080
+ it(`refuses malformed native event ID ${JSON.stringify(id)} before ready`, async () => {
2081
+ const { context, state } = fixture(true, true);
2082
+ const native = await context.clients.graphql("DeliveryNonClosingReferences", {});
2083
+ native.repository.issue.timelineItems.nodes[0].id = id;
2084
+ state.referenceReadback = native;
2085
+ await assert.rejects(
2086
+ publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, draft: false }),
2087
+ /event identity/u
2088
+ );
2089
+ assert.equal(state.promotions + state.updates + state.creations, 0);
1629
2090
  });
2091
+ }
2092
+ it("refuses an oversized reference page despite equivalent observations", async () => {
2093
+ const { context, state } = fixture(true, true);
2094
+ const native = await context.clients.graphql("DeliveryNonClosingReferences", {});
2095
+ native.repository.issue.timelineItems.nodes = Array.from(
2096
+ { length: 101 },
2097
+ () => native.repository.issue.timelineItems.nodes[0]
2098
+ );
2099
+ state.referenceReadback = native;
2100
+ await assert.rejects(
2101
+ publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, draft: false }),
2102
+ /Incomplete/u
2103
+ );
2104
+ assert.equal(state.promotions, 0);
2105
+ });
2106
+ it("refuses oversized introduced commit and parent pages", async () => {
2107
+ for (const kind of ["commits", "parents"]) {
2108
+ const { context, state } = fixture(true, true);
2109
+ const native = await context.clients.graphql("DeliveryNonClosingCommits", {});
2110
+ const commits = native.repository.pullRequest.commits;
2111
+ if (kind === "commits") {
2112
+ commits.nodes = Array.from({ length: 101 }, () => commits.nodes[0]);
2113
+ commits.totalCount = 101;
2114
+ } else {
2115
+ commits.nodes[0].commit.parents.nodes = Array.from({ length: 101 }, () => ({ oid: base }));
2116
+ commits.nodes[0].commit.parents.totalCount = 101;
2117
+ }
2118
+ state.commitReadback = native;
2119
+ await assert.rejects(
2120
+ publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, draft: false }),
2121
+ /Incomplete/u
2122
+ );
2123
+ assert.equal(state.promotions, 0);
2124
+ }
2125
+ });
2126
+ it("refuses body-transition draft drift before promotion, with no second body mutation", async () => {
2127
+ const { context, state } = fixture();
2128
+ state.readHook = () => {
2129
+ if (state.updates) state.draft = false;
2130
+ };
2131
+ await assert.rejects(
2132
+ publishPr(context, {
2133
+ issueNumber: 17,
2134
+ prNumber: 23,
2135
+ nonClosing: true,
2136
+ body: "Safe partial intent",
2137
+ draft: false
2138
+ }),
2139
+ /drifted/u
2140
+ );
2141
+ assert.equal(state.updates, 1);
2142
+ assert.equal(state.promotions, 0);
2143
+ assert.equal(state.creations, 0);
2144
+ });
2145
+ it("does not use the closing-transition exception for stale body with empty closing associations", async () => {
2146
+ const { context, state } = fixture(true, true);
2147
+ state.body = "Stale intent with removed References line";
2148
+ await assert.rejects(
2149
+ publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, body: "New safe intent" }),
2150
+ /closing-issue association/u
2151
+ );
2152
+ assert.equal(state.updates + state.creations + state.promotions, 0);
2153
+ });
1630
2154
  });
1631
- describe('non-closing complete native graph and mutation drift', () => {
1632
- const input = { issueNumber: 17, prNumber: 23, nonClosing: true };
1633
- it('checks earlier introduced commits rather than only the safe head message', async () => {
1634
- const { context, state } = fixture(true, true);
1635
- const graph = (await context.clients.graphql('DeliveryNonClosingCommits', {}));
1636
- graph.repository.pullRequest.commits.totalCount = 2;
1637
- graph.repository.pullRequest.commits.nodes.unshift({
1638
- commit: {
1639
- oid: 'e'.repeat(40),
1640
- message: 'Closes: #999',
1641
- parents: { totalCount: 1, nodes: [{ oid: base }], pageInfo },
1642
- },
1643
- });
1644
- state.commitReadback = graph;
1645
- await assert.rejects(publishPr(context, { ...input, draft: false }), /closing directives/u);
1646
- assert.equal(state.promotions, 0);
1647
- graph.repository.pullRequest.commits.nodes[0].commit.message = 'Earlier improvement';
1648
- await prInfo(context, input);
1649
- graph.repository.pullRequest.commits.totalCount = 3;
1650
- await assert.rejects(prInfo(context, input), /count\/head is incomplete/u);
2155
+ describe("explicit metadata transition typed authority", () => {
2156
+ for (const closing of [
2157
+ { number: 17, repository: { nameWithOwner: repo } },
2158
+ { __typename: "PullRequest", id: "ISSUE17", number: 17, repository: { id: "REPO", nameWithOwner: repo } },
2159
+ { __typename: "Issue", id: "OTHER", number: 17, repository: { id: "REPO", nameWithOwner: repo } },
2160
+ { __typename: "Issue", id: "ISSUE17", number: 17, repository: { id: "OTHER", nameWithOwner: repo } }
2161
+ ]) {
2162
+ it(`refuses incomplete/foreign typed closing identity ${JSON.stringify(closing)}`, async () => {
2163
+ const { context, state } = fixture();
2164
+ state.closingReadback = {
2165
+ repository: {
2166
+ nameWithOwner: repo,
2167
+ pullRequest: { id: "PR23", number: 23, closingIssuesReferences: { nodes: [closing], pageInfo } }
2168
+ }
2169
+ };
2170
+ await assert.rejects(
2171
+ publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, body: "Safe partial intent" }),
2172
+ /typed closing/u
2173
+ );
2174
+ assert.equal(state.updates + state.creations + state.promotions, 0);
1651
2175
  });
1652
- for (const kind of [
1653
- 'source-node',
1654
- 'source-number',
1655
- 'source-repository',
1656
- 'source-type',
1657
- 'target-node',
1658
- 'target-number',
1659
- 'target-repository',
1660
- 'cross-repository',
1661
- 'missing-actor',
1662
- 'wrong-pr-node',
1663
- ]) {
1664
- it(`refuses conflicting native identity ${kind}`, async () => {
1665
- const { context, state } = fixture(true, true);
1666
- const native = (await context.clients.graphql('DeliveryNonClosingReferences', {}));
1667
- const event = native.repository.issue.timelineItems.nodes[0];
1668
- if (kind === 'source-node')
1669
- event.source.id = 'PROTHER';
1670
- if (kind === 'source-number')
1671
- event.source.number = 24;
1672
- if (kind === 'source-repository')
1673
- event.source.repository.nameWithOwner = 'other/widget';
1674
- if (kind === 'source-type')
1675
- event.source.__typename = 'Issue';
1676
- if (kind === 'target-node')
1677
- event.target.id = 'ISSUEOTHER';
1678
- if (kind === 'target-number')
1679
- event.target.number = 18;
1680
- if (kind === 'target-repository')
1681
- event.target.repository.id = 'OTHER';
1682
- if (kind === 'cross-repository')
1683
- event.isCrossRepository = true;
1684
- if (kind === 'missing-actor')
1685
- event.actor = null;
1686
- if (kind === 'wrong-pr-node')
1687
- state.nodeId = 'OTHER';
1688
- state.referenceReadback = native;
1689
- await assert.rejects(publishPr(context, { ...input, draft: false }));
1690
- assert.equal(state.promotions + state.creations + state.updates, 0);
1691
- });
2176
+ }
2177
+ });
2178
+ describe("explicit closing-reference reconciliation", () => {
2179
+ function pending(published = false) {
2180
+ const f = fixture(published, true);
2181
+ f.state.linked = !published;
2182
+ f.state.remoteHead = head;
2183
+ f.state.closingOnCreate = true;
2184
+ if (published) {
2185
+ f.state.manualClosing = true;
2186
+ f.state.referenceCloses = true;
1692
2187
  }
1693
- it('refuses changed issue criteria on promotion readback without another ready mutation', async () => {
1694
- const { context, state } = fixture(true, true);
1695
- state.readHook = () => {
1696
- if (state.promotions)
1697
- state.issueBody = 'External changed criteria';
1698
- };
1699
- await assert.rejects(publishPr(context, { ...input, draft: false }), /criteria drifted/u);
1700
- assert.equal(state.promotions, 1);
1701
- assert.equal(state.issueState, 'open');
2188
+ return f;
2189
+ }
2190
+ for (const published of [false, true]) {
2191
+ it(`refuses a reviewer-context library mutation before publication/removal; existing PR ${published}`, async () => {
2192
+ const { context, reviewerContext, state } = pending(published);
2193
+ vi.spyOn(github, "createDeliveryGitHubClients").mockResolvedValue(context.clients);
2194
+ await assert.rejects(
2195
+ publishPr(reviewerContext, { ...nonClosingCreation, ...published ? { prNumber: 23 } : {} }),
2196
+ /configured authenticated author/u
2197
+ );
2198
+ assert.equal(state.creations + state.removals + state.promotions + state.updates, 0);
1702
2199
  });
1703
- it('refuses changed body during formal review readback without a duplicate review', async () => {
1704
- const { context, reviewerContext, state, artifact } = fixture(true, true);
1705
- vi.spyOn(github, 'createDeliveryGitHubClients').mockResolvedValue(context.clients);
1706
- state.readHook = () => {
1707
- if (state.submissions)
1708
- state.body = 'External removed reference';
1709
- };
1710
- await assert.rejects(submitFormalReview(reviewerContext, { ...input, artifact }), /References line/u);
1711
- assert.equal(state.submissions, 1);
1712
- assert.equal(state.issueState, 'open');
2200
+ }
2201
+ it("refuses the wrong credential source on the direct library mutation", async () => {
2202
+ const { context, state } = pending(true);
2203
+ const wrongSource = { ...context, clients: { ...context.clients, authSource: "app" } };
2204
+ await assert.rejects(publishPr(wrongSource, { ...nonClosingCreation, prNumber: 23 }), /configured.*author/u);
2205
+ assert.equal(state.creations + state.removals + state.promotions + state.updates, 0);
2206
+ });
2207
+ it("refuses bare nonClosing before creating the linked-branch PR with supported prerequisites", async () => {
2208
+ const { context, state } = pending();
2209
+ await assert.rejects(
2210
+ publishPr(context, { issueNumber: 17, nonClosing: true }),
2211
+ /reconcile-non-closing-reference.*expected-head.*expected-base/u
2212
+ );
2213
+ assert.equal(state.creations + state.removals, 0);
2214
+ });
2215
+ it("creates one draft and removes only the exact manual closing pair before strict success", async () => {
2216
+ const { context, state } = pending();
2217
+ const preview = await publishPr(context, { ...nonClosingCreation, dryRun: true });
2218
+ assert.ok("nonClosingVerified" in preview);
2219
+ assert.equal(preview.nonClosingVerified, false);
2220
+ assert.equal(state.creations + state.removals, 0);
2221
+ const result = await publishPr(context, nonClosingCreation);
2222
+ assert.equal(result.prNumber, 23);
2223
+ assert.ok("nonClosingVerified" in result);
2224
+ assert.equal(result.nonClosingVerified, true);
2225
+ assert.deepEqual(state.events, ["draft-publication-replaces-branch-link", "remove-exact-closing-pair"]);
2226
+ assert.equal(state.creations, 1);
2227
+ assert.equal(state.removals, 1);
2228
+ assert.equal(state.updates + state.promotions + state.submissions, 0);
2229
+ assert.equal(state.issueState, "open");
2230
+ assert.equal(state.issueBody, "Four retained criteria");
2231
+ await prInfo(context, { issueNumber: 17, prNumber: 23, nonClosing: true });
2232
+ });
2233
+ it("skips removal when the new draft already satisfies the complete non-closing graph", async () => {
2234
+ const { context, state } = pending();
2235
+ state.closingOnCreate = false;
2236
+ await publishPr(context, nonClosingCreation);
2237
+ assert.equal(state.creations, 1);
2238
+ assert.equal(state.removals, 0);
2239
+ });
2240
+ for (const change of [
2241
+ { nonClosing: false },
2242
+ { draft: false },
2243
+ { body: void 0 },
2244
+ { expectedHeadSha: void 0 },
2245
+ { expectedBaseSha: void 0 },
2246
+ { expectedHeadSha: "d".repeat(40) },
2247
+ { expectedBaseSha: "d".repeat(40) },
2248
+ { expectedHeadSha: "bad" },
2249
+ { body: "Closes #17" }
2250
+ ]) {
2251
+ it(`refuses incompatible action ${JSON.stringify(change)} before publication`, async () => {
2252
+ const { context, state } = pending();
2253
+ await assert.rejects(publishPr(context, Object.assign({ ...nonClosingCreation }, change)));
2254
+ assert.equal(state.creations + state.removals + state.updates + state.promotions, 0);
1713
2255
  });
1714
- });
1715
- describe('exact created intent and native reader bounds', () => {
1716
- for (const drift of ['body', 'title', 'draft', 'closed', 'base']) {
1717
- it(`reports created identity but refuses post-publication ${drift} drift without a replacement`, async () => {
1718
- const { context, state } = fixture(false, true);
1719
- state.linked = true;
1720
- state.remoteHead = head;
1721
- state.readHook = () => {
1722
- if (!state.creations)
1723
- return;
1724
- if (drift === 'body')
1725
- state.body = `References ${repo}#17\n\nOther safe intent`;
1726
- if (drift === 'title')
1727
- state.title = 'Other safe title';
1728
- if (drift === 'draft')
1729
- state.draft = false;
1730
- if (drift === 'closed')
1731
- state.prState = 'closed';
1732
- if (drift === 'base')
1733
- state.baseSha = 'd'.repeat(40);
1734
- };
1735
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }), /created PR #23.*differs from publication intent/u);
1736
- assert.equal(state.creations, 1);
1737
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }));
1738
- assert.equal(state.creations, 1);
1739
- });
1740
- }
1741
- for (const id of [1, true, {}, null, '', ' ']) {
1742
- it(`refuses malformed native event ID ${JSON.stringify(id)} before ready`, async () => {
1743
- const { context, state } = fixture(true, true);
1744
- const native = (await context.clients.graphql('DeliveryNonClosingReferences', {}));
1745
- native.repository.issue.timelineItems.nodes[0].id = id;
1746
- state.referenceReadback = native;
1747
- await assert.rejects(publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, draft: false }), /event identity/u);
1748
- assert.equal(state.promotions + state.updates + state.creations, 0);
1749
- });
1750
- }
1751
- it('refuses an oversized reference page despite equivalent observations', async () => {
1752
- const { context, state } = fixture(true, true);
1753
- const native = (await context.clients.graphql('DeliveryNonClosingReferences', {}));
1754
- native.repository.issue.timelineItems.nodes = Array.from({ length: 101 }, () => native.repository.issue.timelineItems.nodes[0]);
1755
- state.referenceReadback = native;
1756
- await assert.rejects(publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, draft: false }), /Incomplete/u);
1757
- assert.equal(state.promotions, 0);
2256
+ }
2257
+ it("does not infer removal authority from an implicitly matched existing PR", async () => {
2258
+ const { context, state } = pending(true);
2259
+ state.linked = true;
2260
+ await assert.rejects(publishPr(context, nonClosingCreation), /explicit.*PR|--pr/u);
2261
+ assert.equal(state.creations + state.removals, 0);
2262
+ });
2263
+ it("continues a caller-admitted exact pending PR without creating another", async () => {
2264
+ const { context, state } = pending(true);
2265
+ await publishPr(context, { ...nonClosingCreation, prNumber: 23 });
2266
+ assert.equal(state.creations, 0);
2267
+ assert.equal(state.removals, 1);
2268
+ });
2269
+ it("reads the complete manual connection before acting and checks both connections afterward", async () => {
2270
+ const { context, state } = pending(true);
2271
+ const first = structuredClone(await context.clients.graphql("DeliveryClosingIssues", {}));
2272
+ const last = structuredClone(first);
2273
+ first.repository.pullRequest.closingIssuesReferences.nodes = [];
2274
+ first.repository.pullRequest.closingIssuesReferences.pageInfo = { hasNextPage: true, endCursor: "manual-next" };
2275
+ state.manualPages = [first, last];
2276
+ state.removalHook = () => {
2277
+ state.manualPages = [];
2278
+ };
2279
+ await publishPr(context, { ...nonClosingCreation, prNumber: 23 });
2280
+ assert.ok(state.manualPageIndex >= 4);
2281
+ assert.equal(state.removals, 1);
2282
+ assert.equal(state.creations, 0);
2283
+ await prInfo(context, { issueNumber: 17, prNumber: 23, nonClosing: true });
2284
+ });
2285
+ for (const kind of [
2286
+ "foreign-later",
2287
+ "duplicate-later",
2288
+ "missing-node",
2289
+ "wrong-pr",
2290
+ "wrong-repo",
2291
+ "incomplete-page"
2292
+ ]) {
2293
+ it(`refuses manual graph ${kind} before removal`, async () => {
2294
+ const { context, state } = pending(true);
2295
+ const graph = structuredClone(await context.clients.graphql("DeliveryClosingIssues", {}));
2296
+ if (kind === "missing-node") graph.repository.pullRequest.closingIssuesReferences.nodes[0].id = "";
2297
+ if (kind === "wrong-pr") graph.repository.pullRequest.id = "FOREIGN";
2298
+ if (kind === "wrong-repo") graph.repository.nameWithOwner = "other/widget";
2299
+ if (kind === "incomplete-page") delete graph.repository.pullRequest.closingIssuesReferences.pageInfo;
2300
+ state.manualReadback = graph;
2301
+ if (kind.endsWith("-later")) {
2302
+ const next = structuredClone(graph);
2303
+ if (kind === "foreign-later") next.repository.pullRequest.closingIssuesReferences.nodes[0].number = 18;
2304
+ graph.repository.pullRequest.closingIssuesReferences.pageInfo = { hasNextPage: true, endCursor: "next" };
2305
+ state.manualReadback = void 0;
2306
+ state.manualPages = [graph, next];
2307
+ }
2308
+ await assert.rejects(publishPr(context, { ...nonClosingCreation, prNumber: 23 }));
2309
+ assert.equal(state.removals + state.creations, 0);
1758
2310
  });
1759
- it('refuses oversized introduced commit and parent pages', async () => {
1760
- for (const kind of ['commits', 'parents']) {
1761
- const { context, state } = fixture(true, true);
1762
- const native = (await context.clients.graphql('DeliveryNonClosingCommits', {}));
1763
- const commits = native.repository.pullRequest.commits;
1764
- if (kind === 'commits') {
1765
- commits.nodes = Array.from({ length: 101 }, () => commits.nodes[0]);
1766
- commits.totalCount = 101;
1767
- }
1768
- else {
1769
- commits.nodes[0].commit.parents.nodes = Array.from({ length: 101 }, () => ({ oid: base }));
1770
- commits.nodes[0].commit.parents.totalCount = 101;
1771
- }
1772
- state.commitReadback = native;
1773
- await assert.rejects(publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, draft: false }), /Incomplete/u);
1774
- assert.equal(state.promotions, 0);
1775
- }
2311
+ }
2312
+ it("treats malformed removal acknowledgement as uncertain and does not retry even after the edge disappeared", async () => {
2313
+ const { context, state } = pending();
2314
+ state.removalReadback = { removeCloseIssueReferences: { issue: { id: "OTHER" } } };
2315
+ await assert.rejects(publishPr(context, nonClosingCreation), /removal.*uncertain/u);
2316
+ await publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true });
2317
+ assert.equal(state.removals, 1);
2318
+ assert.equal(state.creations, 1);
2319
+ });
2320
+ for (const kind of [
2321
+ "auto-only",
2322
+ "foreign",
2323
+ "duplicate",
2324
+ "truncated",
2325
+ "cursor",
2326
+ "actor",
2327
+ "crossref",
2328
+ "keyword"
2329
+ ]) {
2330
+ it(`refuses ${kind} graph without removing any pair`, async () => {
2331
+ const { context, state } = pending(true);
2332
+ const graph = structuredClone(await context.clients.graphql("DeliveryClosingIssues", {}));
2333
+ if (kind === "auto-only") {
2334
+ state.closingReadback = graph;
2335
+ state.manualClosing = false;
2336
+ }
2337
+ if (kind === "foreign")
2338
+ graph.repository.pullRequest.closingIssuesReferences.nodes.push({
2339
+ __typename: "Issue",
2340
+ id: "OTHER",
2341
+ number: 18,
2342
+ repository: { id: "REPO", nameWithOwner: repo }
2343
+ });
2344
+ if (kind === "duplicate")
2345
+ graph.repository.pullRequest.closingIssuesReferences.nodes.push(
2346
+ graph.repository.pullRequest.closingIssuesReferences.nodes[0]
2347
+ );
2348
+ if (kind === "truncated") graph.repository.pullRequest.closingIssuesReferences.pageInfo.hasNextPage = true;
2349
+ if (kind === "cursor")
2350
+ graph.repository.pullRequest.closingIssuesReferences.pageInfo = { hasNextPage: true, endCursor: "same" };
2351
+ if (["foreign", "duplicate", "truncated", "cursor"].includes(kind)) state.closingReadback = graph;
2352
+ if (kind === "actor") state.referenceActor = "other";
2353
+ if (kind === "crossref") state.referenceCloses = false;
2354
+ if (kind === "keyword") state.commitMessage = "Fixes #18";
2355
+ await assert.rejects(publishPr(context, { ...nonClosingCreation, prNumber: 23 }));
2356
+ assert.equal(state.creations + state.removals + state.promotions + state.updates, 0);
1776
2357
  });
1777
- it('refuses body-transition draft drift before promotion, with no second body mutation', async () => {
1778
- const { context, state } = fixture();
1779
- state.readHook = () => {
1780
- if (state.updates)
1781
- state.draft = false;
1782
- };
1783
- await assert.rejects(publishPr(context, {
1784
- issueNumber: 17,
1785
- prNumber: 23,
1786
- nonClosing: true,
1787
- body: 'Safe partial intent',
1788
- draft: false,
1789
- }), /drifted/u);
1790
- assert.equal(state.updates, 1);
1791
- assert.equal(state.promotions, 0);
1792
- assert.equal(state.creations, 0);
2358
+ }
2359
+ for (const remains of [false, true]) {
2360
+ it(`reports uncertain removal once and permits only read-only reconciliation; edge remains ${remains}`, async () => {
2361
+ const { context, state } = pending();
2362
+ state.failRemovalAck = true;
2363
+ state.keepClosingOnRemoval = remains;
2364
+ await assert.rejects(publishPr(context, nonClosingCreation), /PR #23.*removal.*uncertain/u);
2365
+ assert.equal(state.removals, 1);
2366
+ assert.equal(state.creations, 1);
2367
+ if (remains) await assert.rejects(prInfo(context, { issueNumber: 17, prNumber: 23, nonClosing: true }));
2368
+ else await publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true });
2369
+ assert.equal(state.removals, 1);
2370
+ assert.equal(state.creations, 1);
1793
2371
  });
1794
- it('does not use the closing-transition exception for stale body with empty closing associations', async () => {
1795
- const { context, state } = fixture(true, true);
1796
- state.body = 'Stale intent with removed References line';
1797
- await assert.rejects(publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, body: 'New safe intent' }), /closing-issue association/u);
1798
- assert.equal(state.updates + state.creations + state.promotions, 0);
2372
+ }
2373
+ it("recovers a proven pre-action non-attempt with caller-admitted continuation on the same PR", async () => {
2374
+ const { context, state } = pending();
2375
+ state.referenceActor = "other";
2376
+ await assert.rejects(publishPr(context, nonClosingCreation), /removal not attempted/u);
2377
+ assert.equal(state.removals, 0);
2378
+ state.referenceActor = "author";
2379
+ await publishPr(context, { ...nonClosingCreation, prNumber: 23 });
2380
+ assert.equal(state.creations, 1);
2381
+ assert.equal(state.removals, 1);
2382
+ });
2383
+ it("does not remove anything after uncertain create acknowledgement or create again on read-only inspection", async () => {
2384
+ const { context, state } = pending();
2385
+ state.failCreateAck = true;
2386
+ await assert.rejects(publishPr(context, nonClosingCreation), /acknowledgement is uncertain/u);
2387
+ await assert.rejects(prInfo(context, { issueNumber: 17, prNumber: 23, nonClosing: true }));
2388
+ assert.equal(state.creations, 1);
2389
+ assert.equal(state.removals, 0);
2390
+ });
2391
+ it("refuses post-removal drift without rollback, promotion or another attempt", async () => {
2392
+ const { context, state } = pending();
2393
+ state.removalHook = () => {
2394
+ state.draft = false;
2395
+ };
2396
+ await assert.rejects(publishPr(context, nonClosingCreation), /unresolved/u);
2397
+ assert.equal(state.removals, 1);
2398
+ assert.equal(state.creations, 1);
2399
+ assert.equal(state.updates + state.promotions, 0);
2400
+ });
2401
+ });
2402
+ describe("later-read publication and pre-creation parent bound", () => {
2403
+ for (const drift of ["body", "title", "draft", "closed", "merged", "base"]) {
2404
+ it(`refuses later ${drift} drift after the first correct created PR read`, async () => {
2405
+ const { context, state } = fixture(false, true);
2406
+ state.linked = true;
2407
+ state.remoteHead = head;
2408
+ state.readHook = (count) => {
2409
+ if (!state.creations || count < 2) return;
2410
+ if (drift === "body") state.body = `References ${repo}#17
2411
+
2412
+ Other safe intent`;
2413
+ if (drift === "title") state.title = "Other safe title";
2414
+ if (drift === "draft") state.draft = false;
2415
+ if (drift === "closed") state.prState = "closed";
2416
+ if (drift === "merged") {
2417
+ state.prState = "closed";
2418
+ state.merged = true;
2419
+ }
2420
+ if (drift === "base") state.baseSha = "d".repeat(40);
2421
+ };
2422
+ await assert.rejects(publishPr(context, nonClosingCreation), /created PR #23.*unresolved/u);
2423
+ assert.equal(state.creations, 1);
1799
2424
  });
2425
+ }
2426
+ it("rejects state drift observed only by the verifier final internal PR read", async () => {
2427
+ const { context, state } = fixture(true, true);
2428
+ state.readHook = (count) => {
2429
+ if (count === 3) state.draft = false;
2430
+ };
2431
+ await assert.rejects(
2432
+ publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true }),
2433
+ /state\/draft\/merged/u
2434
+ );
2435
+ assert.equal(state.updates + state.promotions + state.creations, 0);
2436
+ });
2437
+ it("refuses oversized REST parent arrays before creating any PR", async () => {
2438
+ const { context, state } = fixture(false, true);
2439
+ state.linked = true;
2440
+ state.remoteHead = head;
2441
+ state.comparisonReadback = {
2442
+ base_commit: { sha: base },
2443
+ merge_base_commit: { sha: base },
2444
+ status: "ahead",
2445
+ total_commits: 1,
2446
+ commits: [
2447
+ { sha: head, commit: { message: "Safe message" }, parents: Array.from({ length: 101 }, () => ({ sha: base })) }
2448
+ ]
2449
+ };
2450
+ await assert.rejects(publishPr(context, nonClosingCreation), /Incomplete/u);
2451
+ assert.equal(state.creations, 0);
2452
+ });
1800
2453
  });
1801
- describe('explicit metadata transition typed authority', () => {
1802
- for (const closing of [
1803
- { number: 17, repository: { nameWithOwner: repo } },
1804
- { __typename: 'PullRequest', id: 'ISSUE17', number: 17, repository: { id: 'REPO', nameWithOwner: repo } },
1805
- { __typename: 'Issue', id: 'OTHER', number: 17, repository: { id: 'REPO', nameWithOwner: repo } },
1806
- { __typename: 'Issue', id: 'ISSUE17', number: 17, repository: { id: 'OTHER', nameWithOwner: repo } },
1807
- ]) {
1808
- it(`refuses incomplete/foreign typed closing identity ${JSON.stringify(closing)}`, async () => {
1809
- const { context, state } = fixture();
1810
- state.closingReadback = {
1811
- repository: {
1812
- nameWithOwner: repo,
1813
- pullRequest: { id: 'PR23', number: 23, closingIssuesReferences: { nodes: [closing], pageInfo } },
1814
- },
1815
- };
1816
- await assert.rejects(publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true, body: 'Safe partial intent' }), /typed closing/u);
1817
- assert.equal(state.updates + state.creations + state.promotions, 0);
1818
- });
1819
- }
2454
+ describe("first-call PR creation", () => {
2455
+ const recorded = { issueNumber: 17, headBranch: "issue/17" };
2456
+ it("opens a closing PR with only the author identity configured", async () => {
2457
+ const { context, state } = fixture(false);
2458
+ Reflect.deleteProperty(context, "reviewerClients");
2459
+ vi.spyOn(github, "createDeliveryGitHubClients").mockRejectedValue(
2460
+ new DeliveryError("Missing GitHub App credentials for reviewer role. Set GH_APP_ID_GPT_REVIEWER.")
2461
+ );
2462
+ state.remoteHead = head;
2463
+ assert.equal((await publishPr(context, recorded)).prNumber, 23);
2464
+ assert.equal(state.creations, 1);
2465
+ });
2466
+ it("returns the created PR with a warning while GitHub has not yet listed its closing link", async () => {
2467
+ const { context, state } = fixture(false);
2468
+ state.remoteHead = head;
2469
+ state.closingReadback = {
2470
+ repository: {
2471
+ nameWithOwner: repo,
2472
+ pullRequest: { id: "PR23", number: 23, closingIssuesReferences: { nodes: [], pageInfo } }
2473
+ }
2474
+ };
2475
+ const created = await publishPr(context, recorded);
2476
+ assert.equal(created.prNumber, 23);
2477
+ assert.match(String(Reflect.get(created, "warnings")), /not yet listed PR #23 as closing #17/u);
2478
+ state.closingReadback = void 0;
2479
+ assert.equal((await publishPr(context, recorded)).prNumber, 23);
2480
+ assert.equal(state.creations, 1);
2481
+ });
2482
+ it("names an unlinked worktree branch and the step that publishes it", async () => {
2483
+ const { context, state } = fixture(false, true);
2484
+ await assert.rejects(
2485
+ publishPr(context, { ...nonClosingCreation, headBranch: "claude/17-widget" }),
2486
+ /Branch claude\/17-widget is not linked to issue #17 \(GitHub-linked: none\); push the work as issue\/17\./u
2487
+ );
2488
+ assert.equal(state.creations, 0);
2489
+ });
1820
2490
  });
1821
- describe('later-read publication and pre-creation parent bound', () => {
1822
- for (const drift of ['body', 'title', 'draft', 'closed', 'merged', 'base']) {
1823
- it(`refuses later ${drift} drift after the first correct created PR read`, async () => {
1824
- const { context, state } = fixture(false, true);
1825
- state.linked = true;
1826
- state.remoteHead = head;
1827
- state.readHook = (count) => {
1828
- if (!state.creations || count < 2)
1829
- return;
1830
- if (drift === 'body')
1831
- state.body = `References ${repo}#17\n\nOther safe intent`;
1832
- if (drift === 'title')
1833
- state.title = 'Other safe title';
1834
- if (drift === 'draft')
1835
- state.draft = false;
1836
- if (drift === 'closed')
1837
- state.prState = 'closed';
1838
- if (drift === 'merged') {
1839
- state.prState = 'closed';
1840
- state.merged = true;
1841
- }
1842
- if (drift === 'base')
1843
- state.baseSha = 'd'.repeat(40);
1844
- };
1845
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }), /created PR #23.*unresolved/u);
1846
- assert.equal(state.creations, 1);
1847
- });
1848
- }
1849
- it('rejects state drift observed only by the verifier final internal PR read', async () => {
1850
- const { context, state } = fixture(true, true);
1851
- state.readHook = (count) => {
1852
- if (count === 3)
1853
- state.draft = false;
1854
- };
1855
- await assert.rejects(publishPr(context, { issueNumber: 17, prNumber: 23, nonClosing: true }), /state\/draft\/merged/u);
1856
- assert.equal(state.updates + state.promotions + state.creations, 0);
1857
- });
1858
- it('refuses oversized REST parent arrays before creating any PR', async () => {
1859
- const { context, state } = fixture(false, true);
1860
- state.linked = true;
1861
- state.remoteHead = head;
1862
- state.comparisonReadback = {
1863
- base_commit: { sha: base },
1864
- merge_base_commit: { sha: base },
1865
- status: 'ahead',
1866
- total_commits: 1,
1867
- commits: [
1868
- { sha: head, commit: { message: 'Safe message' }, parents: Array.from({ length: 101 }, () => ({ sha: base })) },
1869
- ],
1870
- };
1871
- await assert.rejects(publishPr(context, { issueNumber: 17, nonClosing: true }), /Incomplete/u);
1872
- assert.equal(state.creations, 0);
1873
- });
2491
+ describe("non-closing body update", () => {
2492
+ it("updates an already non-closing PR body and keeps its issue open", async () => {
2493
+ const { context, state } = fixture(true, true);
2494
+ const update = { issueNumber: 17, prNumber: 23, nonClosing: true, body: "Revised widget scope." };
2495
+ await publishPr(context, update);
2496
+ assert.equal(state.body, `References ${repo}#17
2497
+
2498
+ Revised widget scope.`);
2499
+ await publishPr(context, update);
2500
+ assert.equal(state.updates, 1);
2501
+ assert.equal(state.issueState, "open");
2502
+ await assert.rejects(publishPr(context, { ...update, body: "Closes #17" }), /closing directives/u);
2503
+ assert.equal(state.updates, 1);
2504
+ });
1874
2505
  });
1875
- //# sourceMappingURL=prAssociation.test.js.map
2506
+ //# sourceMappingURL=prAssociation.test.js.map