@aviaratech/ai-delivery 0.3.35 → 0.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +56 -554
  3. package/dist/agent.d.ts +1 -3
  4. package/dist/agent.js +74 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +91 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +389 -517
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +316 -354
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +63 -23
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.d.ts +0 -3
  95. package/dist/git.js +59 -76
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +42 -52
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +1 -0
  106. package/dist/github/discovery.js +197 -215
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +18 -2
  121. package/dist/github/projectDelivery.js +615 -557
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.js +433 -389
  124. package/dist/github/relationships.js.map +7 -1
  125. package/dist/github/repo.d.ts +1 -0
  126. package/dist/github/repo.js +123 -96
  127. package/dist/github/repo.js.map +7 -1
  128. package/dist/index.js +3 -3
  129. package/dist/index.js.map +7 -1
  130. package/dist/issue.d.ts +40 -9
  131. package/dist/issue.js +2102 -1742
  132. package/dist/issue.js.map +7 -1
  133. package/dist/issue63History.test.js +40 -42
  134. package/dist/issue63History.test.js.map +7 -1
  135. package/dist/issue63Routes.test.js +154 -143
  136. package/dist/issue63Routes.test.js.map +7 -1
  137. package/dist/issueBatchUpdate.test.js +989 -885
  138. package/dist/issueBatchUpdate.test.js.map +7 -1
  139. package/dist/issueBlockerGuard.test.js +262 -226
  140. package/dist/issueBlockerGuard.test.js.map +7 -1
  141. package/dist/issueContract.d.ts +23 -4
  142. package/dist/issueContract.js +416 -395
  143. package/dist/issueContract.js.map +7 -1
  144. package/dist/issueContract.test.d.ts +4 -3
  145. package/dist/issueContract.test.js +358 -321
  146. package/dist/issueContract.test.js.map +7 -1
  147. package/dist/issueDates.test.js +235 -233
  148. package/dist/issueDates.test.js.map +7 -1
  149. package/dist/issueInfoReadback.test.js +304 -190
  150. package/dist/issueInfoReadback.test.js.map +7 -1
  151. package/dist/issueIntake.test.js +1938 -1732
  152. package/dist/issueIntake.test.js.map +7 -1
  153. package/dist/issueJournal.d.ts +40 -19
  154. package/dist/issueJournal.js +229 -138
  155. package/dist/issueJournal.js.map +7 -1
  156. package/dist/issueJournal.test.js +605 -422
  157. package/dist/issueJournal.test.js.map +7 -1
  158. package/dist/issueRollup.test.d.ts +1 -0
  159. package/dist/issueRollup.test.js +476 -0
  160. package/dist/issueRollup.test.js.map +7 -0
  161. package/dist/issueTracking.test.js +1059 -989
  162. package/dist/issueTracking.test.js.map +7 -1
  163. package/dist/issueWriteRecovery.test.d.ts +1 -0
  164. package/dist/issueWriteRecovery.test.js +260 -0
  165. package/dist/issueWriteRecovery.test.js.map +7 -0
  166. package/dist/lifecycle.test.js +112 -441
  167. package/dist/lifecycle.test.js.map +7 -1
  168. package/dist/logger.js +80 -74
  169. package/dist/logger.js.map +7 -1
  170. package/dist/mcp/index.js +116 -94
  171. package/dist/mcp/index.js.map +7 -1
  172. package/dist/mcp/tools.d.ts +252 -310
  173. package/dist/mcp/tools.js +235 -342
  174. package/dist/mcp/tools.js.map +7 -1
  175. package/dist/pluginAuthProbe.js +63 -52
  176. package/dist/pluginAuthProbe.js.map +7 -1
  177. package/dist/pluginAuthProbe.test.js +85 -62
  178. package/dist/pluginAuthProbe.test.js.map +7 -1
  179. package/dist/pluginCredentials.test.js +282 -259
  180. package/dist/pluginCredentials.test.js.map +7 -1
  181. package/dist/pluginDoctor.test.js +653 -588
  182. package/dist/pluginDoctor.test.js.map +7 -1
  183. package/dist/pluginInstaller.d.ts +7 -5
  184. package/dist/pluginInstaller.js +1173 -1229
  185. package/dist/pluginInstaller.js.map +7 -1
  186. package/dist/pluginInstaller.test.js +1842 -1423
  187. package/dist/pluginInstaller.test.js.map +7 -1
  188. package/dist/pluginPackaging.test.js +417 -413
  189. package/dist/pluginPackaging.test.js.map +7 -1
  190. package/dist/pr.d.ts +114 -131
  191. package/dist/pr.js +1314 -1327
  192. package/dist/pr.js.map +7 -1
  193. package/dist/pr.test.js +967 -653
  194. package/dist/pr.test.js.map +7 -1
  195. package/dist/prAssociation.test.js +2419 -1788
  196. package/dist/prAssociation.test.js.map +7 -1
  197. package/dist/prDispatch.test.js +123 -89
  198. package/dist/prDispatch.test.js.map +7 -1
  199. package/dist/readView.d.ts +184 -0
  200. package/dist/readView.js +218 -0
  201. package/dist/readView.js.map +7 -0
  202. package/dist/readView.test.d.ts +1 -0
  203. package/dist/readView.test.js +146 -0
  204. package/dist/readView.test.js.map +7 -0
  205. package/dist/releaseReconciliation.test.js +267 -288
  206. package/dist/releaseReconciliation.test.js.map +7 -1
  207. package/dist/releaseWorkflow.test.js +2493 -422
  208. package/dist/releaseWorkflow.test.js.map +7 -1
  209. package/dist/review.d.ts +738 -2
  210. package/dist/review.js +601 -348
  211. package/dist/review.js.map +7 -1
  212. package/dist/review.test.js +1218 -812
  213. package/dist/review.test.js.map +7 -1
  214. package/dist/reviewSubmit.test.d.ts +1 -0
  215. package/dist/reviewSubmit.test.js +747 -0
  216. package/dist/reviewSubmit.test.js.map +7 -0
  217. package/dist/services/agentReadinessService.js +42 -37
  218. package/dist/services/agentReadinessService.js.map +7 -1
  219. package/dist/services/blockerGuardService.js +188 -188
  220. package/dist/services/blockerGuardService.js.map +7 -1
  221. package/dist/services/boardReconcileService.d.ts +125 -125
  222. package/dist/services/boardReconcileService.js +1295 -1421
  223. package/dist/services/boardReconcileService.js.map +7 -1
  224. package/dist/services/deliveryHealthService.js +197 -199
  225. package/dist/services/deliveryHealthService.js.map +7 -1
  226. package/dist/services/legacyIssueMigration.js +263 -277
  227. package/dist/services/legacyIssueMigration.js.map +7 -1
  228. package/dist/stagedChecks.test.js +396 -194
  229. package/dist/stagedChecks.test.js.map +7 -1
  230. package/dist/start.test.js +99 -95
  231. package/dist/start.test.js.map +7 -1
  232. package/dist/stdoutRegression.test.js +321 -358
  233. package/dist/stdoutRegression.test.js.map +7 -1
  234. package/dist/targetPolicyDiscovery.test.js +141 -143
  235. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  236. package/dist/targetPolicyEntrypoints.test.js +308 -269
  237. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  238. package/dist/targetPolicyLocal.test.js +580 -1051
  239. package/dist/targetPolicyLocal.test.js.map +7 -1
  240. package/dist/targetPolicyRoutes.test.js +274 -281
  241. package/dist/targetPolicyRoutes.test.js.map +7 -1
  242. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  243. package/dist/targetRepositoryExecution.test.js +451 -0
  244. package/dist/targetRepositoryExecution.test.js.map +7 -0
  245. package/dist/terminalMessages.js +41 -35
  246. package/dist/terminalMessages.js.map +7 -1
  247. package/dist/toolOutput.d.ts +2 -0
  248. package/dist/toolOutput.js +36 -0
  249. package/dist/toolOutput.js.map +7 -0
  250. package/dist/toolOutput.test.d.ts +1 -0
  251. package/dist/toolOutput.test.js +240 -0
  252. package/dist/toolOutput.test.js.map +7 -0
  253. package/dist/utils/atomicJson.d.ts +0 -2
  254. package/dist/utils/atomicJson.js +81 -77
  255. package/dist/utils/atomicJson.js.map +7 -1
  256. package/dist/utils/filesystem.d.ts +0 -8
  257. package/dist/utils/filesystem.js +5 -19
  258. package/dist/utils/filesystem.js.map +7 -1
  259. package/dist/utils/lockfile.js +68 -71
  260. package/dist/utils/lockfile.js.map +7 -1
  261. package/dist/verification.d.ts +1 -54
  262. package/dist/verification.js +976 -1941
  263. package/dist/verification.js.map +7 -1
  264. package/dist/verificationGate.test.js +127 -117
  265. package/dist/verificationGate.test.js.map +7 -1
  266. package/dist/version.js +45 -24
  267. package/dist/version.js.map +7 -1
  268. package/package.json +9 -8
  269. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  270. package/plugins/ai-delivery/README.md +47 -156
  271. package/plugins/ai-delivery/plugin.json +1 -1
  272. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  273. package/plugins/ai-delivery/runtime/dist/cli.js +351 -115
  274. package/plugins/ai-delivery/runtime/package.json +1 -1
  275. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  276. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  277. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  278. package/dist/investigationCompletion.test.js +0 -728
  279. package/dist/investigationCompletion.test.js.map +0 -1
  280. package/dist/services/deliveryAdmission.d.ts +0 -49
  281. package/dist/services/deliveryAdmission.js +0 -165
  282. package/dist/services/deliveryAdmission.js.map +0 -1
  283. package/dist/services/worktreeRegistry.d.ts +0 -434
  284. package/dist/services/worktreeRegistry.js +0 -1248
  285. package/dist/services/worktreeRegistry.js.map +0 -1
  286. package/dist/setup.d.ts +0 -60
  287. package/dist/setup.js +0 -585
  288. package/dist/setup.js.map +0 -1
  289. package/dist/setup.test.js +0 -3329
  290. package/dist/setup.test.js.map +0 -1
  291. package/dist/worktree.d.ts +0 -28
  292. package/dist/worktree.js +0 -188
  293. package/dist/worktree.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
package/dist/pr.js CHANGED
@@ -1,1410 +1,1397 @@
1
- import { z } from 'zod';
2
- import { DeliveryError } from './errors.js';
3
- import * as githubClients from './github/client.js';
4
- import { getNativeBlockerRelationships } from './github/relationships.js';
5
- import { commentIssue, issueBranch, linkedIssueBranches, readIssueClosure, startIssueBranch, } from './issue.js';
6
- import { existsSync, lstatSync, realpathSync } from 'node:fs';
7
- import { isAbsolute, join, relative, resolve, sep } from 'node:path';
8
- import { assertPrivateFile, digestBytes, digestValue, stableJson } from './delivery/common.js';
9
- import { gitCommonDir, primaryGitRoot } from './git.js';
10
- import { ensurePrivateDirectoryDurably } from './utils/atomicJson.js';
11
- import { resolveRepoFromRemote } from './github/repo.js';
12
- import { authenticatedWorktreeActors, assertNativeWorktreeAcceptance } from './worktreeTransition.js';
13
- import { withWorktreeTransitionWriterAbsent } from './verification.js';
14
- import { assertInvestigationSource, investigationSourceIdentity, removeInvestigationSource } from './worktree.js';
15
- import { InvestigationPreparationSchema, completeInvestigationCustody, readInvestigationAcknowledgement, readInvestigationPreparation, registerInvestigationCustody, } from './services/worktreeRegistry.js';
16
- import { parseReviewArtifact, readRequiredReviewState, submitReview } from './review.js';
1
+ import { z } from "zod";
2
+ import { randomUUID } from "node:crypto";
3
+ import { DeliveryError } from "./errors.js";
4
+ import * as githubClients from "./github/client.js";
5
+ import { issueBranch, linkedIssueBranches, startIssueBranch } from "./issue.js";
6
+ import {
7
+ parseReviewArtifact,
8
+ readRequiredReviewState,
9
+ ReviewSubmissionError,
10
+ submitReview
11
+ } from "./review.js";
12
+ import { parseIssueBody } from "./issueContract.js";
17
13
  const Sha = /^[a-f0-9]{40}$/u;
18
14
  const Branch = /^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;
19
- // Conservative refusals also cover Markdown decoration/escaped references.
20
- // This is a closure safety check, never authority for an issue association.
15
+ const DeliveryPrFooter = "\n\n<!-- ai-delivery:pr@1 -->";
16
+ function activeMarkerPositions(text, pattern) {
17
+ const ignored = [];
18
+ const uncertain = [];
19
+ const inline = [];
20
+ let paragraph = null;
21
+ let fence = null;
22
+ let comment = false;
23
+ let htmlEnd = null;
24
+ let container = false;
25
+ let quoted = false;
26
+ let blank = true;
27
+ const flush = (end) => {
28
+ if (paragraph !== null) inline.push([paragraph, end]);
29
+ paragraph = null;
30
+ };
31
+ for (const line of text.matchAll(/[^\n]*(?:\n|$)/gu)) {
32
+ if (!line[0]) continue;
33
+ const start = line.index;
34
+ const end = start + line[0].length;
35
+ const content = line[0].replace(/\r?\n$/u, "");
36
+ if (comment) {
37
+ const closing = content.indexOf("-->");
38
+ ignored.push([start, closing < 0 ? end : start + closing + 3]);
39
+ if (closing >= 0) comment = false;
40
+ continue;
41
+ }
42
+ if (htmlEnd !== null) {
43
+ if (htmlEnd === "blank" && !content.trim()) htmlEnd = null;
44
+ else {
45
+ uncertain.push([start, end]);
46
+ if (htmlEnd !== "blank" && htmlEnd.test(content)) htmlEnd = null;
47
+ continue;
48
+ }
49
+ }
50
+ const edge = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(content);
51
+ if (fence !== null) {
52
+ ignored.push([start, end]);
53
+ if (edge && edge[1][0] === fence[0] && edge[1].length >= fence.length && !edge[2].trim()) fence = null;
54
+ continue;
55
+ }
56
+ if (!content.trim()) {
57
+ flush(start);
58
+ quoted = false;
59
+ blank = true;
60
+ continue;
61
+ }
62
+ if (/^ {0,3}>/u.test(content)) {
63
+ flush(start);
64
+ ignored.push([start, end]);
65
+ quoted = true;
66
+ blank = false;
67
+ continue;
68
+ }
69
+ if (blank && /^\S/u.test(content) && !/^[-+*\d]/u.test(content)) container = false;
70
+ const indented = /^(?: {4}| {0,3}\t)/u.test(content);
71
+ if (indented && paragraph === null) {
72
+ (container || quoted ? uncertain : ignored).push([start, end]);
73
+ continue;
74
+ }
75
+ if (edge && (edge[1][0] !== "`" || !edge[2].includes("`"))) {
76
+ flush(start);
77
+ if (container || quoted) uncertain.push([start, text.length]);
78
+ ignored.push([start, end]);
79
+ fence = edge[1];
80
+ } else if (/^ {0,3}<!--/u.test(content)) {
81
+ flush(start);
82
+ const opening = content.indexOf("<!--");
83
+ const closing = content.indexOf("-->", opening + 4);
84
+ ignored.push([start + opening + 4, closing < 0 ? end : start + closing + 3]);
85
+ if (closing < 0) comment = true;
86
+ } else if (/^ {0,3}<\/?[A-Za-z!?]/u.test(content)) {
87
+ flush(start);
88
+ uncertain.push([start, end]);
89
+ const closing = /^ {0,3}<\?/u.test(content) ? /\?>/u : /^ {0,3}<!\[CDATA\[/u.test(content) ? /\]\]>/u : /^ {0,3}<!/u.test(content) ? />/u : /^ {0,3}<(?:pre|script|style|textarea)(?:[ \t>]|$)/iu.test(content) ? /<\/(?:pre|script|style|textarea)>/iu : null;
90
+ htmlEnd = closing === null ? "blank" : closing.test(content) ? null : closing;
91
+ } else if (/^ {0,3}(?:#{1,6}(?:[ \t]|$)|(?:[-+*]|\d+[.)])[ \t])/u.test(content) || /^ {0,3}(?:=+|-+)[ \t]*$/u.test(content) || /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:_[ \t]*){3,}|(?:-[ \t]*){3,})$/u.test(content)) {
92
+ flush(start);
93
+ inline.push([start, end]);
94
+ container = /^ {0,3}(?:[-+*]|\d+[.)])[ \t]/u.test(content);
95
+ } else {
96
+ if (quoted || container) uncertain.push([start, end]);
97
+ paragraph ??= start;
98
+ }
99
+ blank = false;
100
+ }
101
+ flush(text.length);
102
+ for (const [start, end] of inline) {
103
+ const unit = text.slice(start, end);
104
+ const tokens = /\\[\\`<]|`+|<!--/gu;
105
+ for (let token = tokens.exec(unit); token; token = tokens.exec(unit)) {
106
+ if (token[0].startsWith("\\")) {
107
+ ignored.push([start + token.index + 1, start + tokens.lastIndex]);
108
+ } else if (token[0] === "<!--") {
109
+ const closing = unit.indexOf("-->", tokens.lastIndex);
110
+ if (closing < 0) uncertain.push([start + token.index, end]);
111
+ else {
112
+ ignored.push([start + tokens.lastIndex, start + closing + 3]);
113
+ tokens.lastIndex = closing + 3;
114
+ }
115
+ } else {
116
+ const ticks = /`+/gu;
117
+ ticks.lastIndex = tokens.lastIndex;
118
+ for (let closing = ticks.exec(unit); closing; closing = ticks.exec(unit)) {
119
+ if (closing[0].length !== token[0].length) continue;
120
+ ignored.push([start + token.index, start + ticks.lastIndex]);
121
+ tokens.lastIndex = ticks.lastIndex;
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ }
127
+ const candidates = [...text.matchAll(pattern)].map((match) => match.index);
128
+ if (candidates.some((position) => uncertain.some(([start, end]) => position >= start && position < end))) return null;
129
+ return candidates.filter((position) => !ignored.some(([start, end]) => position >= start && position < end));
130
+ }
131
+ function hasDeliveryPrMarker(body) {
132
+ if (!body.endsWith(DeliveryPrFooter)) return false;
133
+ const prefix = body.slice(0, -DeliveryPrFooter.length);
134
+ const active = activeMarkerPositions(body, /<!--\s*ai-delivery:pr@[^\n]*?(?:-->|$)/gmu);
135
+ return Boolean(prefix.trim()) && active?.length === 1 && active[0] === prefix.length + 2;
136
+ }
137
+ function hasDeliveryMergeTrailer(message) {
138
+ const trailer = /\n\nDelivered-by: ai-delivery\n?$/u.exec(message);
139
+ if (!trailer || !message.slice(0, trailer.index).trim()) return false;
140
+ const active = activeMarkerPositions(message, /^Delivered-by: ai-delivery[ \t]*$/gmu);
141
+ return active?.length === 1 && active[0] === trailer.index + 2;
142
+ }
143
+ function publicationBody(body, previous) {
144
+ function marked(value) {
145
+ const active = activeMarkerPositions(value, /<!--\s*ai-delivery:pr@[^\n]*?(?:-->|$)/gmu);
146
+ if (active === null || active.length > 0 && !hasDeliveryPrMarker(value))
147
+ throw new DeliveryError("PR marker footer is malformed, misplaced or ambiguous; reconcile without repair.");
148
+ return active.length === 1;
149
+ }
150
+ const previousMarked = typeof previous === "string" && marked(previous);
151
+ const requestedMarked = marked(body);
152
+ if (previous !== void 0 && !previousMarked) {
153
+ if (requestedMarked) throw new DeliveryError("Historical unmarked PRs cannot receive a marker footer backfill.");
154
+ return body;
155
+ }
156
+ if (requestedMarked) return body;
157
+ const decorated = body + DeliveryPrFooter;
158
+ if (!hasDeliveryPrMarker(decorated))
159
+ throw new DeliveryError("PR marker footer would be ambiguous; retain the original body without repair.");
160
+ return decorated;
161
+ }
162
+ function hasClosingLink(body, issueNumber) {
163
+ const line = `Closes #${issueNumber}`;
164
+ return body === line || body?.startsWith(`${line}
165
+ `) === true || body?.startsWith(`${line}\r
166
+ `) === true;
167
+ }
168
+ function closingBody(issue, requested) {
169
+ const line = `Closes #${issue.number}`;
170
+ if (requested !== void 0)
171
+ return requested.startsWith(`${line}
172
+ `) || requested === line ? requested : `${line}
173
+
174
+ ${requested}`;
175
+ const { outcome, acceptanceCriteria } = parseIssueBody(issue.body ?? "", { title: issue.title }).issue;
176
+ return [
177
+ line,
178
+ ...outcome ? [`## Outcome
179
+
180
+ ${outcome}`] : [],
181
+ ...acceptanceCriteria.length ? [
182
+ `## Acceptance criteria
183
+
184
+ ${acceptanceCriteria.map((ac) => `- [ ] ${ac.behavior}
185
+ Verified by: ${ac.verifiedBy}`).join("\n")}`
186
+ ] : []
187
+ ].join("\n\n");
188
+ }
21
189
  function refuseClosingDirective(text) {
22
- if (typeof text !== 'string')
23
- throw new DeliveryError('Incomplete non-closing message readback.');
24
- const normalized = text.replace(/[*_~`\\<>[\]]/gu, '');
25
- if (/\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\b(?:\s*:\s*|\s+)[^\n]*?(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(normalized))
26
- throw new DeliveryError('Non-closing delivery refuses closing directives in body, title or commit messages.');
190
+ if (typeof text !== "string") throw new DeliveryError("Incomplete non-closing message readback.");
191
+ const normalized = text.replace(/\[[^\]\r\n]*\]\(([^()\s]+)\)/gu, "$1").replace(/[*_~`\\<>[\]]/gu, "");
192
+ if (/(?<![\p{L}\p{N}_-])(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)(?:\s*:\s*|\s+)(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(
193
+ normalized
194
+ ))
195
+ throw new DeliveryError("Non-closing delivery refuses closing directives in body, title or commit messages.");
27
196
  }
28
197
  function referenceLine(context, issueNumber) {
29
- return `References ${context.config.repository}#${issueNumber}`;
198
+ return `References ${context.config.repository}#${issueNumber}`;
30
199
  }
31
200
  function nonClosingBody(context, issueNumber, requested) {
32
- refuseClosingDirective(requested);
33
- const line = referenceLine(context, issueNumber);
34
- const body = requested.startsWith(`${line}\n`) || requested === line ? requested : `${line}\n\n${requested}`;
201
+ refuseClosingDirective(requested);
202
+ const line = referenceLine(context, issueNumber);
203
+ const body = requested.startsWith(`${line}
204
+ `) || requested === line ? requested : `${line}
205
+
206
+ ${requested}`;
207
+ verifyReferenceBody(context, issueNumber, body);
208
+ return body;
209
+ }
210
+ function hasReferenceBody(context, issueNumber, body) {
211
+ try {
35
212
  verifyReferenceBody(context, issueNumber, body);
36
- return body;
213
+ return true;
214
+ } catch {
215
+ return false;
216
+ }
37
217
  }
38
218
  function verifyReferenceBody(context, issueNumber, body) {
39
- refuseClosingDirective(body);
40
- const lines = body.split(/\r?\n/u);
41
- if (lines[0] !== referenceLine(context, issueNumber) ||
42
- lines.filter((line) => /^References\s/iu.test(line)).length !== 1)
43
- throw new DeliveryError('Non-closing PR body must retain one leading canonical References line.');
219
+ refuseClosingDirective(body);
220
+ const lines = body.split(/\r?\n/u);
221
+ if (lines[0] !== referenceLine(context, issueNumber) || lines.filter((line) => /^References\s/iu.test(line)).length !== 1)
222
+ throw new DeliveryError("Non-closing PR body must retain one leading canonical References line.");
44
223
  }
45
224
  function pageCursor(connection, seen) {
46
- const info = connection.pageInfo;
47
- if (!info ||
48
- typeof info.hasNextPage !== 'boolean' ||
49
- !(info.endCursor === null || typeof info.endCursor === 'string'))
50
- throw new DeliveryError('Incomplete non-closing native pagination.');
51
- if (!info.hasNextPage)
52
- return null;
53
- if (!info.endCursor || seen.has(info.endCursor))
54
- throw new DeliveryError('Non-closing native pagination did not advance.');
55
- seen.add(info.endCursor);
56
- return info.endCursor;
225
+ const info = connection.pageInfo;
226
+ if (!info || typeof info.hasNextPage !== "boolean" || !(info.endCursor === null || typeof info.endCursor === "string"))
227
+ throw new DeliveryError("Incomplete non-closing native pagination.");
228
+ if (!info.hasNextPage) return null;
229
+ if (!info.endCursor || seen.has(info.endCursor))
230
+ throw new DeliveryError("Non-closing native pagination did not advance.");
231
+ seen.add(info.endCursor);
232
+ return info.endCursor;
57
233
  }
58
234
  async function openReferenceIssue(context, issueNumber) {
59
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
60
- if (issue.number !== issueNumber ||
61
- 'pull_request' in issue ||
62
- issue.state !== 'open' ||
63
- typeof issue.node_id !== 'string' ||
64
- !issue.node_id ||
65
- typeof issue.title !== 'string' ||
66
- typeof issue.body !== 'string' ||
67
- issue.html_url?.toLowerCase() !==
68
- `https://github.com/${context.config.repository}/issues/${issueNumber}`.toLowerCase())
69
- throw new DeliveryError('Non-closing delivery requires the exact canonical OPEN issue and complete title/body.');
70
- return issue;
235
+ const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
236
+ if (issue.number !== issueNumber || "pull_request" in issue || issue.state !== "open" || typeof issue.node_id !== "string" || !issue.node_id || typeof issue.title !== "string" || typeof issue.body !== "string" || issue.html_url?.toLowerCase() !== `https://github.com/${context.config.repository}/issues/${issueNumber}`.toLowerCase())
237
+ throw new DeliveryError("Non-closing delivery requires the exact canonical OPEN issue and complete title/body.");
238
+ return issue;
71
239
  }
72
240
  function sameReferencePr(before, after, expectedMerge = false) {
73
- if (expectedMerge
74
- ? before.state !== 'open' ||
75
- before.draft ||
76
- before.merged ||
77
- after.state !== 'closed' ||
78
- after.draft ||
79
- !after.merged
80
- : before.state !== after.state || before.draft !== after.draft || before.merged !== after.merged)
81
- throw new DeliveryError('Non-closing PR state/draft/merged readback drifted; reconcile read-only.');
82
- if (before.node_id !== after.node_id ||
83
- before.head.sha !== after.head.sha ||
84
- before.head.ref !== after.head.ref ||
85
- before.base.sha !== after.base.sha ||
86
- before.base.ref !== after.base.ref ||
87
- before.body !== after.body ||
88
- before.title !== after.title ||
89
- before.user.login.toLowerCase() !== after.user.login.toLowerCase())
90
- throw new DeliveryError('Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.');
241
+ if (expectedMerge ? before.state !== "open" || before.draft || before.merged || after.state !== "closed" || after.draft || !after.merged : before.state !== after.state || before.draft !== after.draft || before.merged !== after.merged)
242
+ throw new DeliveryError("Non-closing PR state/draft/merged readback drifted; reconcile read-only.");
243
+ if (before.node_id !== after.node_id || before.head.sha !== after.head.sha || before.head.ref !== after.head.ref || before.base.sha !== after.base.sha || before.base.ref !== after.base.ref || before.body !== after.body || before.title !== after.title || before.user.login.toLowerCase() !== after.user.login.toLowerCase())
244
+ throw new DeliveryError("Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.");
91
245
  }
92
246
  function sameReferenceIssue(before, after) {
93
- if (before.node_id !== after.node_id || before.title !== after.title || before.body !== after.body)
94
- throw new DeliveryError('Non-closing issue identity/title/criteria drifted; reconcile read-only.');
247
+ if (before.node_id !== after.node_id || before.title !== after.title || before.body !== after.body)
248
+ throw new DeliveryError("Non-closing issue identity/title/criteria drifted; reconcile read-only.");
95
249
  }
96
250
  function nonClosingMode(value) {
97
- if (value !== undefined && typeof value !== 'boolean')
98
- throw new DeliveryError('nonClosing must be a boolean.');
99
- return value === true;
251
+ if (value !== void 0 && typeof value !== "boolean") throw new DeliveryError("nonClosing must be a boolean.");
252
+ return value === true;
100
253
  }
101
254
  async function nonClosingRoute(context, base) {
102
- const authorContext = context.clients.role === 'author'
103
- ? context
104
- : {
105
- ...context,
106
- clients: await githubClients.createDeliveryGitHubClients({
107
- config: context.config,
108
- identity: context.config.roles.author.identity,
109
- role: 'author',
110
- }),
111
- reviewerClients: context.clients,
112
- };
113
- const route = await preflightReviewRoute(authorContext, base);
114
- if (route.rules.visibility !== 'complete' || route.approvalEligibility === 'insufficient-permission')
115
- throw new DeliveryError('Non-closing delivery requires complete native rule visibility and an independent reviewer route.');
116
- return route;
255
+ const authorContext = context.clients.role === "author" ? context : {
256
+ ...context,
257
+ clients: await githubClients.createDeliveryGitHubClients({
258
+ config: context.config,
259
+ ...context.credentialEnvironment === void 0 ? {} : { env: context.credentialEnvironment },
260
+ identity: context.config.roles.author.identity,
261
+ role: "author"
262
+ }),
263
+ reviewerClients: context.clients
264
+ };
265
+ const route = await preflightReviewRoute(authorContext, base);
266
+ if (route.rules.visibility !== "complete" || route.approvalEligibility === "insufficient-permission")
267
+ throw new DeliveryError(
268
+ "Non-closing delivery requires complete native rule visibility and an independent reviewer route."
269
+ );
270
+ return route;
117
271
  }
118
272
  async function verifyNonClosingCommits(context, pr) {
119
- let cursor = null;
120
- const cursors = new Set();
121
- const commits = new Map();
122
- let total;
123
- for (let page = 0; page < 20; page++) {
124
- const data = await context.clients.graphql('query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}', { ...context.repo, number: pr.number, cursor });
125
- const live = data.repository?.pullRequest;
126
- const connection = live?.commits;
127
- if (data.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||
128
- live?.id !== pr.node_id ||
129
- live.number !== pr.number ||
130
- live.headRefOid !== pr.head.sha ||
131
- live.baseRefOid !== pr.base.sha ||
132
- live.baseRefName !== pr.base.ref ||
133
- !connection ||
134
- !Array.isArray(connection.nodes) ||
135
- connection.nodes.length > 100 ||
136
- !Number.isSafeInteger(connection.totalCount) ||
137
- connection.totalCount < 1 ||
138
- connection.totalCount > 2000 ||
139
- (total !== undefined && total !== connection.totalCount))
140
- throw new DeliveryError('Incomplete or moved introduced commit graph at the non-closing head/base.');
141
- total = connection.totalCount;
142
- for (const node of connection.nodes) {
143
- const commit = node?.commit;
144
- if (!commit ||
145
- !validSha(commit.oid) ||
146
- commits.has(commit.oid) ||
147
- !commit.parents ||
148
- !Array.isArray(commit.parents.nodes) ||
149
- commit.parents.nodes.length > 100 ||
150
- !Number.isSafeInteger(commit.parents.totalCount) ||
151
- commit.parents.totalCount < 1 ||
152
- commit.parents.totalCount !== commit.parents.nodes.length ||
153
- commit.parents.pageInfo?.hasNextPage !== false ||
154
- commit.parents.nodes.some((parent) => !validSha(parent?.oid)))
155
- throw new DeliveryError('Incomplete, duplicate or truncated introduced commit identity/parents.');
156
- refuseClosingDirective(commit.message);
157
- commits.set(commit.oid, commit.message);
158
- }
159
- cursor = pageCursor(connection, cursors);
160
- if (cursor === null) {
161
- if (commits.size !== total || !commits.has(pr.head.sha))
162
- throw new DeliveryError('Introduced commit count/head is incomplete.');
163
- return;
164
- }
273
+ let cursor = null;
274
+ const cursors = /* @__PURE__ */ new Set();
275
+ const commits = /* @__PURE__ */ new Map();
276
+ let total;
277
+ for (let page = 0; page < 20; page++) {
278
+ const data = await context.clients.graphql(
279
+ "query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}",
280
+ { ...context.repo, number: pr.number, cursor }
281
+ );
282
+ const live = data.repository?.pullRequest;
283
+ const connection = live?.commits;
284
+ if (data.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() || live?.id !== pr.node_id || live.number !== pr.number || live.headRefOid !== pr.head.sha || live.baseRefOid !== pr.base.sha || live.baseRefName !== pr.base.ref || !connection || !Array.isArray(connection.nodes) || connection.nodes.length > 100 || !Number.isSafeInteger(connection.totalCount) || connection.totalCount < 1 || connection.totalCount > 2e3 || total !== void 0 && total !== connection.totalCount)
285
+ throw new DeliveryError("Incomplete or moved introduced commit graph at the non-closing head/base.");
286
+ total = connection.totalCount;
287
+ for (const node of connection.nodes) {
288
+ const commit = node?.commit;
289
+ if (!commit || !validSha(commit.oid) || commits.has(commit.oid) || !commit.parents || !Array.isArray(commit.parents.nodes) || commit.parents.nodes.length > 100 || !Number.isSafeInteger(commit.parents.totalCount) || commit.parents.totalCount < 1 || commit.parents.totalCount !== commit.parents.nodes.length || commit.parents.pageInfo?.hasNextPage !== false || commit.parents.nodes.some((parent) => !validSha(parent?.oid)))
290
+ throw new DeliveryError("Incomplete, duplicate or truncated introduced commit identity/parents.");
291
+ refuseClosingDirective(commit.message);
292
+ commits.set(commit.oid, commit.message);
293
+ }
294
+ cursor = pageCursor(connection, cursors);
295
+ if (cursor === null) {
296
+ if (commits.size !== total || !commits.has(pr.head.sha))
297
+ throw new DeliveryError("Introduced commit count/head is incomplete.");
298
+ return;
165
299
  }
166
- throw new DeliveryError('Non-closing commit graph exceeds the bounded readback window.');
300
+ }
301
+ throw new DeliveryError("Non-closing commit graph exceeds the bounded readback window.");
167
302
  }
168
303
  async function verifyUnpublishedCommits(context, baseSha, headSha) {
169
- const commits = new Set();
170
- let total;
171
- for (let page = 1; page <= 20; page++) {
172
- const comparison = (await context.clients.rest.repos.compareCommitsWithBasehead({
173
- ...context.repo,
174
- basehead: `${baseSha}...${headSha}`,
175
- per_page: 100,
176
- page,
177
- })).data;
178
- if (comparison.base_commit?.sha !== baseSha ||
179
- !validSha(comparison.merge_base_commit?.sha) ||
180
- !['ahead', 'diverged'].includes(comparison.status) ||
181
- !Number.isSafeInteger(comparison.total_commits) ||
182
- comparison.total_commits < 1 ||
183
- comparison.total_commits > 2000 ||
184
- (total !== undefined && total !== comparison.total_commits) ||
185
- !Array.isArray(comparison.commits) ||
186
- comparison.commits.length > 100)
187
- throw new DeliveryError('Incomplete introduced commit range before non-closing publication.');
188
- total = comparison.total_commits;
189
- for (const commit of comparison.commits) {
190
- if (!validSha(commit.sha) ||
191
- commits.has(commit.sha) ||
192
- !Array.isArray(commit.parents) ||
193
- commit.parents.length < 1 ||
194
- commit.parents.length > 100 ||
195
- commit.parents.some((parent) => !validSha(parent.sha)))
196
- throw new DeliveryError('Incomplete or duplicate introduced commit identity.');
197
- refuseClosingDirective(commit.commit?.message);
198
- commits.add(commit.sha);
199
- }
200
- if (commits.size === total && commits.has(headSha))
201
- return;
202
- if (comparison.commits.length < 100)
203
- throw new DeliveryError('Truncated introduced commit range before publication.');
304
+ const commits = /* @__PURE__ */ new Set();
305
+ let total;
306
+ for (let page = 1; page <= 20; page++) {
307
+ const comparison = (await context.clients.rest.repos.compareCommitsWithBasehead({
308
+ ...context.repo,
309
+ basehead: `${baseSha}...${headSha}`,
310
+ per_page: 100,
311
+ page
312
+ })).data;
313
+ if (comparison.base_commit?.sha !== baseSha || !validSha(comparison.merge_base_commit?.sha) || !["ahead", "diverged"].includes(comparison.status) || !Number.isSafeInteger(comparison.total_commits) || comparison.total_commits < 1 || comparison.total_commits > 2e3 || total !== void 0 && total !== comparison.total_commits || !Array.isArray(comparison.commits) || comparison.commits.length > 100)
314
+ throw new DeliveryError("Incomplete introduced commit range before non-closing publication.");
315
+ total = comparison.total_commits;
316
+ for (const commit of comparison.commits) {
317
+ if (!validSha(commit.sha) || commits.has(commit.sha) || !Array.isArray(commit.parents) || commit.parents.length < 1 || commit.parents.length > 100 || commit.parents.some((parent) => !validSha(parent.sha)))
318
+ throw new DeliveryError("Incomplete or duplicate introduced commit identity.");
319
+ refuseClosingDirective(commit.commit?.message);
320
+ commits.add(commit.sha);
204
321
  }
205
- throw new DeliveryError('Introduced commit range exceeds the bounded readback window.');
322
+ if (commits.size === total && commits.has(headSha)) return;
323
+ if (comparison.commits.length < 100)
324
+ throw new DeliveryError("Truncated introduced commit range before publication.");
325
+ }
326
+ throw new DeliveryError("Introduced commit range exceeds the bounded readback window.");
206
327
  }
207
- async function verifyNonClosingReference(context, issueNumber, pr) {
208
- if (typeof pr.node_id !== 'string' ||
209
- !pr.node_id ||
210
- pr.html_url?.toLowerCase() !== `https://github.com/${context.config.repository}/pull/${pr.number}`.toLowerCase())
211
- throw new DeliveryError('Incomplete non-closing PR node identity.');
212
- verifyReferenceBody(context, issueNumber, pr.body);
213
- refuseClosingDirective(pr.title);
214
- const issue = await openReferenceIssue(context, issueNumber);
215
- const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
216
- if (repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() ||
217
- pr.base.ref !== repository.default_branch ||
218
- typeof repository.node_id !== 'string' ||
219
- !repository.node_id)
220
- throw new DeliveryError('Non-closing PR must target the canonical default repository/base.');
221
- const route = await nonClosingRoute(context, pr.base.ref);
222
- if (pr.user.login.toLowerCase() !== route.author.actorLogin.toLowerCase())
223
- throw new DeliveryError('Non-closing PR author differs from the configured author.');
224
- let cursor = null;
225
- const cursors = new Set();
226
- const events = new Map();
227
- let matched = false;
228
- for (let page = 0; page < 20; page++) {
229
- const data = await context.clients.graphql('query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}', { ...context.repo, number: issueNumber, cursor });
230
- const target = data.repository?.issue;
231
- const connection = target?.timelineItems;
232
- if (data.repository?.id !== repository.node_id ||
233
- data.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||
234
- target?.id !== issue.node_id ||
235
- target.number !== issueNumber ||
236
- target.state !== 'OPEN' ||
237
- !connection ||
238
- !Array.isArray(connection.nodes) ||
239
- connection.nodes.length > 100)
240
- throw new DeliveryError('Incomplete or conflicting native non-closing issue identity.');
241
- for (const event of connection.nodes) {
242
- const source = event?.source;
243
- const referenced = event?.target;
244
- if (!event ||
245
- !nativeId(event.id) ||
246
- !source ||
247
- !referenced ||
248
- !['Issue', 'PullRequest'].includes(source.__typename) ||
249
- !nativeId(source.id) ||
250
- !Number.isSafeInteger(source.number) ||
251
- source.number <= 0 ||
252
- !nativeId(source.repository?.id) ||
253
- typeof source.repository.nameWithOwner !== 'string' ||
254
- referenced.__typename !== 'Issue' ||
255
- referenced.id !== issue.node_id ||
256
- referenced.number !== issueNumber ||
257
- referenced.repository?.id !== repository.node_id ||
258
- referenced.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||
259
- typeof event.isCrossRepository !== 'boolean' ||
260
- typeof event.willCloseTarget !== 'boolean' ||
261
- !nativeId(event.actor?.login))
262
- throw new DeliveryError('Incomplete native cross-reference event identity/actor.');
263
- const signature = JSON.stringify([
264
- source.__typename,
265
- source.id,
266
- source.number,
267
- source.repository.id,
268
- source.repository.nameWithOwner.toLowerCase(),
269
- referenced.id,
270
- referenced.number,
271
- referenced.repository.id,
272
- referenced.repository.nameWithOwner.toLowerCase(),
273
- event.actor.login.toLowerCase(),
274
- event.isCrossRepository,
275
- event.willCloseTarget,
276
- ]);
277
- if (events.has(event.id) && events.get(event.id) !== signature)
278
- throw new DeliveryError('Conflicting duplicate native reference event.');
279
- events.set(event.id, signature);
280
- if (source.id === pr.node_id ||
281
- (source.__typename === 'PullRequest' &&
282
- source.number === pr.number &&
283
- source.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())) {
284
- if (source.__typename !== 'PullRequest' ||
285
- source.id !== pr.node_id ||
286
- source.number !== pr.number ||
287
- source.repository.id !== repository.node_id ||
288
- source.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() ||
289
- event.isCrossRepository ||
290
- event.willCloseTarget !== false ||
291
- event.actor.login.toLowerCase() !== route.author.actorLogin.toLowerCase())
292
- throw new DeliveryError('Conflicting, closing or unauthorized native PR reference.');
293
- matched = true;
294
- }
295
- }
296
- cursor = pageCursor(connection, cursors);
297
- if (cursor === null)
298
- break;
299
- if (page === 19)
300
- throw new DeliveryError('Native non-closing references exceed the bounded readback window.');
328
+ async function readNonClosingReference(context, issueNumber, pr, forReview = false) {
329
+ if (typeof pr.node_id !== "string" || !pr.node_id || pr.html_url?.toLowerCase() !== `https://github.com/${context.config.repository}/pull/${pr.number}`.toLowerCase())
330
+ throw new DeliveryError("Incomplete non-closing PR node identity.");
331
+ verifyReferenceBody(context, issueNumber, pr.body);
332
+ refuseClosingDirective(pr.title);
333
+ const issue = await openReferenceIssue(context, issueNumber);
334
+ const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
335
+ if (repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() || pr.base.ref !== repository.default_branch || typeof repository.node_id !== "string" || !repository.node_id)
336
+ throw new DeliveryError("Non-closing PR must target the canonical default repository/base.");
337
+ const route = await nonClosingRoute(context, pr.base.ref);
338
+ if (pr.user.login.toLowerCase() !== route.author.actorLogin.toLowerCase())
339
+ throw new DeliveryError("Non-closing PR author differs from the configured author.");
340
+ let cursor = null;
341
+ const cursors = /* @__PURE__ */ new Set();
342
+ const events = /* @__PURE__ */ new Map();
343
+ let matched = false;
344
+ let closesTarget;
345
+ for (let page = 0; page < 20; page++) {
346
+ const data = await context.clients.graphql(
347
+ "query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}",
348
+ { ...context.repo, number: issueNumber, cursor }
349
+ );
350
+ const target = data.repository?.issue;
351
+ const connection = target?.timelineItems;
352
+ if (data.repository?.id !== repository.node_id || data.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() || target?.id !== issue.node_id || target.number !== issueNumber || target.state !== "OPEN" || !connection || !Array.isArray(connection.nodes) || connection.nodes.length > 100)
353
+ throw new DeliveryError("Incomplete or conflicting native non-closing issue identity.");
354
+ for (const event of connection.nodes) {
355
+ const source = event?.source;
356
+ const referenced = event?.target;
357
+ if (!event || !nativeId(event.id) || !source || !referenced || !["Issue", "PullRequest"].includes(source.__typename) || !nativeId(source.id) || !Number.isSafeInteger(source.number) || source.number <= 0 || !nativeId(source.repository?.id) || typeof source.repository.nameWithOwner !== "string" || referenced.__typename !== "Issue" || referenced.id !== issue.node_id || referenced.number !== issueNumber || referenced.repository?.id !== repository.node_id || referenced.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() || typeof event.isCrossRepository !== "boolean" || typeof event.willCloseTarget !== "boolean" || !nativeId(event.actor?.login))
358
+ throw new DeliveryError("Incomplete native cross-reference event identity/actor.");
359
+ const signature = JSON.stringify([
360
+ source.__typename,
361
+ source.id,
362
+ source.number,
363
+ source.repository.id,
364
+ source.repository.nameWithOwner.toLowerCase(),
365
+ referenced.id,
366
+ referenced.number,
367
+ referenced.repository.id,
368
+ referenced.repository.nameWithOwner.toLowerCase(),
369
+ event.actor.login.toLowerCase(),
370
+ event.isCrossRepository,
371
+ event.willCloseTarget
372
+ ]);
373
+ if (events.has(event.id) && events.get(event.id) !== signature)
374
+ throw new DeliveryError("Conflicting duplicate native reference event.");
375
+ events.set(event.id, signature);
376
+ if (source.id === pr.node_id || source.__typename === "PullRequest" && source.number === pr.number && source.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase()) {
377
+ if (source.__typename !== "PullRequest" || source.id !== pr.node_id || source.number !== pr.number || source.repository.id !== repository.node_id || source.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() || event.isCrossRepository || event.actor.login.toLowerCase() !== route.author.actorLogin.toLowerCase())
378
+ throw new DeliveryError("Conflicting, closing or unauthorized native PR reference.");
379
+ if (closesTarget !== void 0 && closesTarget !== event.willCloseTarget)
380
+ throw new DeliveryError("Conflicting native PR closing-reference semantics.");
381
+ closesTarget = event.willCloseTarget;
382
+ matched = true;
383
+ }
301
384
  }
302
- if (!matched)
303
- throw new DeliveryError('Missing authorized native non-closing PR-to-issue reference.');
304
- await verifyPrIssueAssociation(context, pr.number, issueNumber, true, pr.node_id);
305
- await verifyNonClosingCommits(context, pr);
306
- if (!pr.merged) {
307
- const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data;
308
- if (ref.ref !== `refs/heads/${pr.base.ref}` || ref.object.type !== 'commit' || ref.object.sha !== pr.base.sha)
309
- throw new DeliveryError('Non-closing default base has moved or is incomplete.');
385
+ cursor = pageCursor(connection, cursors);
386
+ if (cursor === null) break;
387
+ if (page === 19) throw new DeliveryError("Native non-closing references exceed the bounded readback window.");
388
+ }
389
+ if (!matched) throw new DeliveryError("Missing authorized native non-closing PR-to-issue reference.");
390
+ const allClosing = await readClosingReferenceIds(context, issueNumber, issue.node_id, repository.node_id, pr);
391
+ const manualClosing = await readClosingReferenceIds(
392
+ context,
393
+ issueNumber,
394
+ issue.node_id,
395
+ repository.node_id,
396
+ pr,
397
+ true
398
+ );
399
+ await verifyNonClosingCommits(context, pr);
400
+ if (!pr.merged) {
401
+ const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data;
402
+ if (ref.ref !== `refs/heads/${pr.base.ref}` || ref.object.type !== "commit" || !validSha(ref.object.sha) || !forReview && ref.object.sha !== pr.base.sha)
403
+ throw new DeliveryError("Non-closing default base has moved or is incomplete.");
404
+ }
405
+ const after = await openReferenceIssue(context, issueNumber);
406
+ sameReferenceIssue(issue, after);
407
+ sameReferencePr(pr, await getPr(context, pr.number));
408
+ return { issue, closesTarget, allClosing, manualClosing };
409
+ }
410
+ async function readClosingReferenceIds(context, issueNumber, issueId, repositoryId, pr, manual = false) {
411
+ let cursor = null;
412
+ const cursors = /* @__PURE__ */ new Set();
413
+ const ids = /* @__PURE__ */ new Set();
414
+ for (let page = 0; page < 20; page++) {
415
+ const result = await context.clients.graphql(
416
+ `query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor${manual ? ",userLinkedOnly:true" : ""}){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,
417
+ { ...context.repo, number: pr.number, cursor }
418
+ );
419
+ const connection = result.repository?.pullRequest?.closingIssuesReferences;
420
+ if (result.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() || result.repository.pullRequest?.id !== pr.node_id || result.repository.pullRequest.number !== pr.number || !connection || !Array.isArray(connection.nodes) || connection.nodes.length > 100)
421
+ throw new DeliveryError("Incomplete or conflicting native closing-reference graph.");
422
+ for (const issue of connection.nodes) {
423
+ if (!issue || issue.__typename !== "Issue" || issue.id !== issueId || issue.number !== issueNumber || issue.repository?.id !== repositoryId || issue.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() || ids.has(issue.id))
424
+ throw new DeliveryError(
425
+ "Non-closing PR has an unintended, duplicate or incomplete native closing association."
426
+ );
427
+ ids.add(issue.id);
310
428
  }
311
- const after = await openReferenceIssue(context, issueNumber);
312
- sameReferenceIssue(issue, after);
313
- sameReferencePr(pr, await getPr(context, pr.number));
314
- return issue;
429
+ cursor = pageCursor(connection, cursors);
430
+ if (cursor === null) return [...ids];
431
+ }
432
+ throw new DeliveryError("Native closing-reference graph exceeds the bounded readback window.");
433
+ }
434
+ async function verifyNonClosingReference(context, issueNumber, pr, forReview = false) {
435
+ const graph = await readNonClosingReference(context, issueNumber, pr, forReview);
436
+ if (graph.closesTarget || graph.allClosing.length || graph.manualClosing.length)
437
+ throw new DeliveryError("Non-closing PR has a closing native PR reference/association.");
438
+ return graph.issue;
315
439
  }
316
440
  function nativeId(value) {
317
- return typeof value === 'string' && value.trim().length > 0;
441
+ return typeof value === "string" && value.trim().length > 0;
318
442
  }
319
443
  function validSha(value) {
320
- return typeof value === 'string' && Sha.test(value);
444
+ return typeof value === "string" && Sha.test(value);
321
445
  }
322
446
  function validBranch(value) {
323
- if (typeof value !== 'string' ||
324
- !Branch.test(value) ||
325
- value.startsWith('/') ||
326
- value.endsWith('/') ||
327
- value.endsWith('.lock'))
328
- throw new DeliveryError('Invalid GitHub branch name.');
447
+ if (typeof value !== "string" || !Branch.test(value) || value.startsWith("/") || value.endsWith("/") || value.endsWith(".lock"))
448
+ throw new DeliveryError("Invalid GitHub branch name.");
329
449
  }
330
450
  async function getPr(context, prNumber) {
331
- if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
332
- throw new DeliveryError('Configured and selected GitHub repository identities disagree.');
333
- const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;
334
- if (pr.number !== prNumber ||
335
- typeof pr.base.repo?.full_name !== 'string' ||
336
- typeof pr.head.repo?.full_name !== 'string' ||
337
- pr.base.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() ||
338
- pr.head.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() ||
339
- !validSha(pr.head.sha) ||
340
- !validSha(pr.base.sha) ||
341
- (pr.state !== 'open' && pr.state !== 'closed') ||
342
- typeof pr.merged !== 'boolean' ||
343
- typeof pr.draft !== 'boolean' ||
344
- (pr.merged && pr.state !== 'closed'))
345
- throw new DeliveryError('GitHub PR identity or exact head readback is invalid.');
346
- validBranch(pr.head.ref);
347
- validBranch(pr.base.ref);
348
- return pr;
451
+ if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
452
+ throw new DeliveryError("Configured and selected GitHub repository identities disagree.");
453
+ const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;
454
+ if (pr.number !== prNumber || typeof pr.base.repo?.full_name !== "string" || typeof pr.head.repo?.full_name !== "string" || pr.base.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() || pr.head.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() || !validSha(pr.head.sha) || !validSha(pr.base.sha) || pr.state !== "open" && pr.state !== "closed" || typeof pr.merged !== "boolean" || typeof pr.draft !== "boolean" || pr.merged && pr.state !== "closed")
455
+ throw new DeliveryError("GitHub PR identity or exact head readback is invalid.");
456
+ validBranch(pr.head.ref);
457
+ validBranch(pr.base.ref);
458
+ return pr;
349
459
  }
350
- async function verifyPrIssueAssociation(context, prNumber, issueNumber, nonClosing = false, expectedPrId, onlyIntended = false, expectedIssueId, expectedRepositoryId) {
351
- let cursor = null;
352
- const cursors = new Set();
353
- let matches = 0;
354
- for (let page = 0; page < 20; page++) {
355
- const result = await context.clients.graphql('query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}', { ...context.repo, number: prNumber, cursor });
356
- const connection = result.repository?.pullRequest?.closingIssuesReferences;
357
- if (typeof result.repository?.nameWithOwner !== 'string' ||
358
- result.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() ||
359
- result.repository?.pullRequest?.number !== prNumber ||
360
- (expectedPrId !== undefined && result.repository?.pullRequest?.id !== expectedPrId) ||
361
- !connection ||
362
- !Array.isArray(connection.nodes) ||
363
- connection.nodes.length > 100 ||
364
- typeof connection.pageInfo?.hasNextPage !== 'boolean' ||
365
- !(connection.pageInfo.endCursor === null || typeof connection.pageInfo.endCursor === 'string'))
366
- throw new DeliveryError('Incomplete or conflicting native GitHub PR issue association readback.');
367
- for (const issue of connection.nodes) {
368
- if (onlyIntended &&
369
- (!issue ||
370
- issue.__typename !== 'Issue' ||
371
- !nativeId(expectedIssueId) ||
372
- issue.id !== expectedIssueId ||
373
- !nativeId(expectedRepositoryId) ||
374
- issue.repository?.id !== expectedRepositoryId))
375
- throw new DeliveryError('Incomplete or conflicting typed closing issue/repository identity before body transition.');
376
- if (nonClosing)
377
- throw new DeliveryError('Non-closing PR has an unintended native closing association.');
378
- if (!issue ||
379
- !Number.isSafeInteger(issue.number) ||
380
- issue.number <= 0 ||
381
- typeof issue.repository?.nameWithOwner !== 'string' ||
382
- !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner))
383
- throw new DeliveryError('Incomplete native PR closing-issue identity.');
384
- if (issue.number === issueNumber &&
385
- issue.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())
386
- matches++;
387
- else if (onlyIntended)
388
- throw new DeliveryError('Existing PR has conflicting closing associations; body transition refused.');
389
- }
390
- if (!connection.pageInfo.hasNextPage) {
391
- if (!nonClosing && matches !== 1)
392
- throw new DeliveryError('Native GitHub PR closing-issue association does not identify the intended issue.');
393
- return;
394
- }
395
- const next = connection.pageInfo.endCursor;
396
- if (!next || cursors.has(next))
397
- throw new DeliveryError('Native PR issue pagination did not advance.');
398
- cursors.add(next);
399
- cursor = next;
460
+ async function verifyPrIssueAssociation(context, prNumber, issueNumber, expectedPrId, onlyIntended = false, expectedIssueId, expectedRepositoryId, options = {}) {
461
+ let cursor = null;
462
+ const cursors = /* @__PURE__ */ new Set();
463
+ let matches = 0;
464
+ for (let page = 0; page < 20; page++) {
465
+ const result = await context.clients.graphql(
466
+ "query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}",
467
+ { ...context.repo, number: prNumber, cursor }
468
+ );
469
+ const connection = result.repository?.pullRequest?.closingIssuesReferences;
470
+ if (typeof result.repository?.nameWithOwner !== "string" || result.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() || result.repository?.pullRequest?.number !== prNumber || expectedPrId !== void 0 && result.repository?.pullRequest?.id !== expectedPrId || !connection || !Array.isArray(connection.nodes) || connection.nodes.length > 100 || typeof connection.pageInfo?.hasNextPage !== "boolean" || !(connection.pageInfo.endCursor === null || typeof connection.pageInfo.endCursor === "string"))
471
+ throw new DeliveryError("Incomplete or conflicting native GitHub PR issue association readback.");
472
+ for (const issue of connection.nodes) {
473
+ if (onlyIntended && (!issue || issue.__typename !== "Issue" || !nativeId(expectedIssueId) || issue.id !== expectedIssueId || !nativeId(expectedRepositoryId) || issue.repository?.id !== expectedRepositoryId))
474
+ throw new DeliveryError(
475
+ "Incomplete or conflicting typed closing issue/repository identity before body transition."
476
+ );
477
+ if (!issue || !Number.isSafeInteger(issue.number) || issue.number <= 0 || typeof issue.repository?.nameWithOwner !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner))
478
+ throw new DeliveryError("Incomplete native PR closing-issue identity.");
479
+ if (issue.number === issueNumber && issue.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())
480
+ matches++;
481
+ else if (onlyIntended)
482
+ throw new DeliveryError("Existing PR has conflicting closing associations; body transition refused.");
400
483
  }
401
- throw new DeliveryError('Native PR issue association exceeds the bounded readback window.');
402
- }
403
- async function matchingPrs(context, branch, base) {
404
- const matches = [];
405
- for (let page = 1; page <= 20; page++) {
406
- const batch = (await context.clients.rest.pulls.list({
407
- ...context.repo,
408
- head: `${context.repo.owner}:${branch}`,
409
- ...(base === undefined ? {} : { base }),
410
- state: 'all',
411
- page,
412
- per_page: 100,
413
- })).data;
414
- if (!Array.isArray(batch) || batch.some((pr) => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0))
415
- throw new DeliveryError('Incomplete GitHub PR match readback.');
416
- matches.push(...batch);
417
- if (batch.length < 100)
418
- return matches;
484
+ if (!connection.pageInfo.hasNextPage) {
485
+ if (matches !== 1 && !(matches === 0 && options.allowMissing))
486
+ throw new DeliveryError(
487
+ matches === 0 && options.missingMessage ? options.missingMessage : "Native GitHub PR closing-issue association does not identify the intended issue."
488
+ );
489
+ return matches;
419
490
  }
420
- throw new DeliveryError('GitHub PR match history exceeds the bounded readback window.');
491
+ const next = connection.pageInfo.endCursor;
492
+ if (!next || cursors.has(next)) throw new DeliveryError("Native PR issue pagination did not advance.");
493
+ cursors.add(next);
494
+ cursor = next;
495
+ }
496
+ throw new DeliveryError("Native PR issue association exceeds the bounded readback window.");
421
497
  }
422
- async function verifyIssuePr(context, issueNumber, prNumber, nonClosing = false) {
423
- const pr = await getPr(context, prNumber);
424
- if (nonClosing)
425
- await verifyNonClosingReference(context, issueNumber, pr);
426
- else
427
- await verifyPrIssueAssociation(context, prNumber, issueNumber);
428
- if (!pr.merged) {
429
- const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.head.ref}` })).data;
430
- if (ref.ref !== `refs/heads/${pr.head.ref}` || ref.object.type !== 'commit' || ref.object.sha !== pr.head.sha)
431
- throw new DeliveryError('Current remote PR head/ref readback is incomplete or has moved.');
432
- }
433
- return pr;
498
+ async function matchingPrs(context, branch, base, state = "all") {
499
+ const matches = [];
500
+ for (let page = 1; page <= 20; page++) {
501
+ const batch = (await context.clients.rest.pulls.list({
502
+ ...context.repo,
503
+ head: `${context.repo.owner}:${branch}`,
504
+ ...base === void 0 ? {} : { base },
505
+ state,
506
+ page,
507
+ per_page: 100
508
+ })).data;
509
+ if (!Array.isArray(batch) || batch.some((pr) => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0))
510
+ throw new DeliveryError("Incomplete GitHub PR match readback.");
511
+ matches.push(...batch);
512
+ if (batch.length < 100) return matches;
513
+ }
514
+ throw new DeliveryError("GitHub PR match history exceeds the bounded readback window.");
434
515
  }
435
- export async function prInfo(context, input) {
436
- const nonClosing = nonClosingMode(input.nonClosing);
437
- if (nonClosing && (input.issueNumber === undefined || input.prNumber === undefined))
438
- throw new DeliveryError('Non-closing inspection requires explicit canonical issue and PR numbers.');
439
- let number = input.prNumber;
440
- if (number === undefined) {
441
- if (input.issueNumber === undefined)
442
- throw new DeliveryError('prNumber or issueNumber is required.');
443
- const branches = await linkedIssueBranches(context, input.issueNumber);
444
- if (branches.length !== 1)
445
- throw new DeliveryError('Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.');
446
- const branch = branches[0].name;
447
- const matches = await matchingPrs(context, branch);
448
- if (matches.length !== 1)
449
- throw new DeliveryError('Select an explicit PR number when the remote issue branch has zero or multiple PRs.');
450
- number = matches[0].number;
451
- }
452
- const pr = input.issueNumber === undefined
453
- ? await getPr(context, number)
454
- : await verifyIssuePr(context, input.issueNumber, number, nonClosing);
455
- return {
456
- prNumber: pr.number,
457
- url: pr.html_url,
458
- state: pr.state,
459
- draft: pr.draft,
460
- headSha: pr.head.sha,
461
- headBranch: pr.head.ref,
462
- baseBranch: pr.base.ref,
463
- merged: pr.merged,
464
- };
516
+ async function verifyIssuePr(context, issueNumber, prNumber, nonClosing = false, forReview = false) {
517
+ const pr = await getPr(context, prNumber);
518
+ if (nonClosing) await verifyNonClosingReference(context, issueNumber, pr, forReview);
519
+ else
520
+ await verifyPrIssueAssociation(
521
+ context,
522
+ prNumber,
523
+ issueNumber,
524
+ void 0,
525
+ false,
526
+ void 0,
527
+ void 0,
528
+ forReview && !hasClosingLink(pr.body, issueNumber) ? {
529
+ missingMessage: `Missing \`Closes #${issueNumber}\` in PR #${prNumber}. Restore it with issue_pr_create(${JSON.stringify({ repo: context.config.repository, issueNumber, head: pr.head.ref })}).`
530
+ } : {}
531
+ );
532
+ if (!pr.merged) {
533
+ const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.head.ref}` })).data;
534
+ if (ref.ref !== `refs/heads/${pr.head.ref}` || ref.object.type !== "commit" || ref.object.sha !== pr.head.sha)
535
+ throw new DeliveryError("Current remote PR head/ref readback is incomplete or has moved.");
536
+ }
537
+ return pr;
465
538
  }
466
- export async function listPrs(context, state = 'open') {
467
- const prs = await context.clients.rest.paginate(context.clients.rest.pulls.list, {
468
- ...context.repo,
469
- state,
470
- per_page: 100,
471
- });
472
- return {
473
- schemaVersion: 'ai-delivery.pr-list@1',
474
- pullRequests: prs.map((pr) => ({
475
- number: pr.number,
476
- state: pr.state,
477
- draft: pr.draft ?? false,
478
- headSha: pr.head.sha,
479
- baseSha: pr.base.sha,
480
- url: pr.html_url,
481
- })),
482
- };
539
+ async function prInfo(context, input) {
540
+ const nonClosing = nonClosingMode(input.nonClosing);
541
+ if (nonClosing && (input.issueNumber === void 0 || input.prNumber === void 0))
542
+ throw new DeliveryError("Non-closing inspection requires explicit canonical issue and PR numbers.");
543
+ let number = input.prNumber;
544
+ if (number === void 0) {
545
+ if (input.issueNumber === void 0) throw new DeliveryError("prNumber or issueNumber is required.");
546
+ const branches = await linkedIssueBranches(context, input.issueNumber);
547
+ if (branches.length !== 1)
548
+ throw new DeliveryError(
549
+ "Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association."
550
+ );
551
+ const branch = branches[0].name;
552
+ const matches = await matchingPrs(context, branch);
553
+ if (matches.length !== 1)
554
+ throw new DeliveryError("Select an explicit PR number when the remote issue branch has zero or multiple PRs.");
555
+ number = matches[0].number;
556
+ }
557
+ const pr = input.issueNumber === void 0 ? await getPr(context, number) : await verifyIssuePr(context, input.issueNumber, number, nonClosing);
558
+ return {
559
+ prNumber: pr.number,
560
+ url: pr.html_url,
561
+ state: pr.state,
562
+ draft: pr.draft,
563
+ headSha: pr.head.sha,
564
+ headBranch: pr.head.ref,
565
+ baseBranch: pr.base.ref,
566
+ merged: pr.merged
567
+ };
568
+ }
569
+ async function listPrs(context, state = "open") {
570
+ const prs = await context.clients.rest.paginate(context.clients.rest.pulls.list, {
571
+ ...context.repo,
572
+ state,
573
+ per_page: 100
574
+ });
575
+ return {
576
+ schemaVersion: "ai-delivery.pr-list@1",
577
+ pullRequests: prs.map((pr) => ({
578
+ number: pr.number,
579
+ state: pr.state,
580
+ draft: pr.draft ?? false,
581
+ headSha: pr.head.sha,
582
+ baseSha: pr.base.sha,
583
+ url: pr.html_url
584
+ }))
585
+ };
483
586
  }
484
- /** Enumerate configured requirements even when a check has never reported. */
485
587
  async function readRequiredCheckNames(context, base) {
486
- const sources = await branchRuleSources(context, base);
487
- const names = new Set();
488
- let complete = true;
489
- for (const [index, result] of sources.entries()) {
490
- if (result.status !== 'fulfilled' ||
491
- result.value.status !== 200 ||
492
- !result.value.headers ||
493
- result.value.headers.link) {
494
- complete = false;
495
- continue;
496
- }
497
- const data = result.value.data;
498
- const lists = [];
499
- if (index === 0) {
500
- if (!Array.isArray(data)) {
501
- complete = false;
502
- continue;
503
- }
504
- for (const rule of data) {
505
- if (typeof rule?.type !== 'string')
506
- complete = false;
507
- if (rule?.type === 'required_status_checks')
508
- lists.push(rule.parameters?.required_status_checks);
509
- }
510
- }
511
- else if (Array.isArray(data) || !data || typeof data !== 'object')
512
- complete = false;
513
- else if (data.required_status_checks === null)
514
- lists.push([]);
515
- else {
516
- const checks = data?.required_status_checks;
517
- if (Array.isArray(checks?.checks))
518
- lists.push(checks.checks);
519
- if (Array.isArray(checks?.contexts))
520
- lists.push(checks.contexts.map((context) => ({ context })));
521
- if (!Array.isArray(checks?.checks) && !Array.isArray(checks?.contexts))
522
- complete = false;
523
- }
524
- for (const list of lists) {
525
- const parsed = z.array(z.object({ context: z.string().min(1) })).safeParse(list);
526
- if (!parsed.success)
527
- complete = false;
528
- else
529
- for (const check of parsed.data)
530
- names.add(check.context);
588
+ const sources = await branchRuleSources(context, base);
589
+ const { confirmedUnprotected, confirmedRulesetOnly } = await corroborateClassicProtectionAbsence(
590
+ context,
591
+ base,
592
+ sources
593
+ );
594
+ const names = /* @__PURE__ */ new Set();
595
+ const required = /* @__PURE__ */ new Map();
596
+ let complete = true;
597
+ for (const [index, result] of sources.entries()) {
598
+ if (index === 1 && (confirmedUnprotected || confirmedRulesetOnly)) continue;
599
+ if (result.status !== "fulfilled" || result.value.status !== 200 || !result.value.headers || result.value.headers.link) {
600
+ complete = false;
601
+ continue;
602
+ }
603
+ const data = result.value.data;
604
+ const lists = [];
605
+ if (index === 0) {
606
+ if (!Array.isArray(data)) {
607
+ complete = false;
608
+ continue;
609
+ }
610
+ for (const rule of data) {
611
+ if (typeof rule?.type !== "string") complete = false;
612
+ if (rule?.type === "required_status_checks") lists.push(rule.parameters?.required_status_checks);
613
+ }
614
+ } else if (Array.isArray(data) || !data || typeof data !== "object") complete = false;
615
+ else if (data.required_status_checks === null) lists.push([]);
616
+ else {
617
+ const checks = data?.required_status_checks;
618
+ if (Array.isArray(checks?.checks)) lists.push(checks.checks);
619
+ if (Array.isArray(checks?.contexts))
620
+ lists.push(
621
+ checks.contexts.filter(
622
+ (context2) => !Array.isArray(checks?.checks) || !checks.checks.some((check) => check?.context === context2)
623
+ ).map((context2) => ({ context: context2 }))
624
+ );
625
+ if (!Array.isArray(checks?.checks) && !Array.isArray(checks?.contexts)) complete = false;
626
+ }
627
+ for (const list of lists) {
628
+ const parsed = z.array(
629
+ z.object({
630
+ context: z.string().min(1),
631
+ app_id: z.number().int().nullable().optional(),
632
+ integration_id: z.number().int().nullable().optional()
633
+ })
634
+ ).safeParse(list);
635
+ if (!parsed.success) complete = false;
636
+ else
637
+ for (const check of parsed.data) {
638
+ names.add(check.context);
639
+ const selected = index === 0 ? check.integration_id : check.app_id;
640
+ if (selected !== void 0 && selected !== null && selected !== -1 && selected <= 0) complete = false;
641
+ const appId = selected === void 0 || selected === null || selected === -1 ? null : selected;
642
+ required.set(JSON.stringify([check.context, appId]), { name: check.context, appId });
531
643
  }
532
644
  }
533
- return { names: [...names].sort(), complete };
645
+ }
646
+ return { names: [...names].sort(), complete, required: [...required.values()] };
534
647
  }
535
- export async function prChecks(context, prNumber) {
536
- const pr = await getPr(context, prNumber);
537
- const requirements = await readRequiredCheckNames(context, pr.base.ref);
538
- const [checks, status, reviewState] = await Promise.all([
539
- context.clients.rest.checks.listForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),
540
- context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),
541
- readRequiredReviewState(context, prNumber, pr.head.sha),
542
- ]);
543
- const headChecksComplete = checks.data.total_count === checks.data.check_runs.length &&
544
- status.data.total_count === status.data.statuses.length;
545
- return {
546
- schemaVersion: 'ai-delivery.pr-checks@1',
547
- prNumber: pr.number,
548
- headSha: pr.head.sha,
549
- combinedStatus: status.data.state,
550
- mergeStateStatus: pr.mergeable_state ?? 'unknown',
551
- requiredCheckDiscovery: requirements.complete ? 'complete' : 'partial',
552
- headChecksComplete,
553
- requiredChecks: requirements.names.map((name) => {
554
- const states = [
555
- ...checks.data.check_runs
556
- .filter((check) => check.name === name)
557
- .map((check) => `check: ${check.status}/${check.conclusion ?? 'pending'}`),
558
- ...status.data.statuses.filter((check) => check.context === name).map((check) => `status: ${check.state}`),
559
- ];
560
- return { name, headState: states.join('; ') || (headChecksComplete ? 'not-reported' : 'unknown') };
561
- }),
562
- reviewState,
563
- checkRuns: checks.data.check_runs.map((check) => ({
564
- name: check.name,
565
- status: check.status,
566
- conclusion: check.conclusion,
567
- })),
568
- };
648
+ async function queueChecks(context, base, sha) {
649
+ return readRequiredCheckProof(context, base, sha, false);
650
+ }
651
+ async function readRequiredCheckProof(context, base, sha, allowEmpty) {
652
+ const requirements = await readRequiredCheckNames(context, base);
653
+ if (!requirements.complete || !allowEmpty && requirements.required.length === 0)
654
+ return { state: "waiting", reason: "Required queue checks are absent or incompletely discovered." };
655
+ if (requirements.required.length === 0)
656
+ return { state: "passed", reason: "Native requirements are completely observed and empty.", proof: [] };
657
+ const [runs, statuses] = await Promise.all([
658
+ context.clients.rest.checks.listForRef({ ...context.repo, ref: sha, filter: "latest", per_page: 100 }),
659
+ context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: sha, per_page: 100 })
660
+ ]);
661
+ if (runs.status !== 200 || statuses.status !== 200 || !runs.headers || !statuses.headers || runs.headers?.link || statuses.headers?.link || runs.data.total_count !== runs.data.check_runs.length || statuses.data.total_count !== statuses.data.statuses.length || statuses.data.sha !== sha || runs.data.check_runs.some((run) => run.head_sha !== sha))
662
+ return { state: "waiting", reason: "Queue SHA check/status pagination or identity is incomplete." };
663
+ const proof = [];
664
+ for (const required of requirements.required) {
665
+ const status = statuses.data.statuses.filter((s) => s.context === required.name).sort((a, b) => b.id - a.id)[0];
666
+ let waiting;
667
+ if (status) {
668
+ if (required.appId !== null) waiting = `Queue status ${required.name} required App source cannot be established.`;
669
+ else if (!Number.isSafeInteger(status.id) || status.id <= 0)
670
+ waiting = `Queue status ${required.name} attempt is unknown.`;
671
+ else if (status.state === "failure" || status.state === "error")
672
+ return { state: "failed", reason: `Queue status ${required.name} is ${status.state}.` };
673
+ else if (status.state !== "success")
674
+ waiting = `Queue status ${required.name} is ${status.state === "pending" ? "pending" : "unknown"}.`;
675
+ else proof.push({ ...required, id: status.id });
676
+ }
677
+ const candidates = runs.data.check_runs.filter((run2) => run2.name === required.name && (required.appId === null || run2.app?.id === required.appId)).sort((a, b) => b.id - a.id);
678
+ const run = candidates[0];
679
+ if (run) {
680
+ if (!Number.isSafeInteger(run.id) || run.id <= 0 || !run.app?.id)
681
+ return { state: "waiting", reason: `Queue check ${required.name} producer/attempt is unknown.` };
682
+ if (run.status !== "completed")
683
+ return { state: "waiting", reason: `Queue check ${required.name} is pending.` };
684
+ if (run.conclusion !== "success" && !["failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale"].includes(
685
+ run.conclusion ?? ""
686
+ ))
687
+ return {
688
+ state: "waiting",
689
+ reason: `Queue check ${required.name} conclusion is unknown or not successful.`
690
+ };
691
+ if (run.conclusion !== "success")
692
+ return {
693
+ state: "failed",
694
+ reason: `Queue check ${required.name} concluded ${run.conclusion ?? "unknown"}.`
695
+ };
696
+ proof.push({ ...required, id: run.id });
697
+ } else if (!status) waiting = `Queue check ${required.name} has not reported from its required source.`;
698
+ if (waiting) return { state: "waiting", reason: waiting };
699
+ }
700
+ return { state: "passed", reason: "Current required queue SHA checks passed.", proof };
701
+ }
702
+ async function readPrBoardFacts(context, prNumber) {
703
+ const repository = `${context.repo.owner}/${context.repo.repo}`;
704
+ const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;
705
+ const baseRepo = pr.base.repo;
706
+ const headRepo = pr.head.repo;
707
+ if (pr.number !== prNumber || !nativeId(pr.node_id) || pr.html_url?.toLowerCase() !== `https://github.com/${repository}/pull/${prNumber}`.toLowerCase() || typeof pr.title !== "string" || pr.body !== null && typeof pr.body !== "string" || pr.state !== "open" && pr.state !== "closed" || typeof pr.draft !== "boolean" || typeof pr.merged !== "boolean" || !baseRepo || !headRepo || !nativeId(baseRepo.node_id) || !nativeId(headRepo.node_id) || typeof baseRepo.full_name !== "string" || typeof headRepo.full_name !== "string" || baseRepo.full_name.toLowerCase() !== repository.toLowerCase() || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(headRepo.full_name) || typeof pr.head.ref !== "string" || !pr.head.ref || typeof pr.base.ref !== "string" || !pr.base.ref || !validSha(pr.head.sha) || !validSha(pr.base.sha))
708
+ throw new DeliveryError("Incomplete native PR identity for board display.");
709
+ const baseRepository = { id: baseRepo.node_id, name: baseRepo.full_name };
710
+ const headRepository = { id: headRepo.node_id, name: headRepo.full_name };
711
+ const closingLinks = { complete: false, issues: [] };
712
+ let native = null;
713
+ try {
714
+ let cursor = null;
715
+ const cursors = /* @__PURE__ */ new Set();
716
+ const issues = /* @__PURE__ */ new Set();
717
+ const issueNumbers = /* @__PURE__ */ new Set();
718
+ for (let page = 0; page < 20; page++) {
719
+ const data = await context.clients.graphql(
720
+ "query DeliveryBoardPr($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner pullRequest(number:$number){id number state isDraft headRefOid baseRefOid headRefName baseRefName baseRepository{id nameWithOwner} headRepository{id nameWithOwner} mergeable mergeStateStatus closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}",
721
+ { ...context.repo, number: prNumber, cursor }
722
+ );
723
+ const live = data.repository?.pullRequest;
724
+ const links = live?.closingIssuesReferences;
725
+ if (data.repository?.id !== baseRepository.id || data.repository.nameWithOwner?.toLowerCase() !== repository.toLowerCase() || live?.id !== pr.node_id || live.number !== prNumber || live.headRefOid !== pr.head.sha || live.baseRefOid !== pr.base.sha || live.headRefName !== pr.head.ref || live.baseRefName !== pr.base.ref || live.baseRepository?.id !== baseRepository.id || live.baseRepository.nameWithOwner?.toLowerCase() !== baseRepository.name.toLowerCase() || live.headRepository?.id !== headRepository.id || live.headRepository.nameWithOwner?.toLowerCase() !== headRepository.name.toLowerCase() || live.state !== (pr.merged ? "MERGED" : pr.state.toUpperCase()) || live.isDraft !== pr.draft || !["MERGEABLE", "CONFLICTING", "UNKNOWN"].includes(live.mergeable) || typeof live.mergeStateStatus !== "string" || native !== null && (native.mergeable !== live.mergeable || native.mergeStateStatus !== live.mergeStateStatus) || !links || !Array.isArray(links.nodes) || links.nodes.length > 100)
726
+ throw new DeliveryError("Native PR board snapshot is incomplete or changed.");
727
+ native = live;
728
+ for (const issue of links.nodes) {
729
+ if (issue?.__typename !== "Issue" || !nativeId(issue.id) || !Number.isSafeInteger(issue.number) || issue.number <= 0 || !nativeId(issue.repository?.id) || typeof issue.repository.nameWithOwner !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner) || issues.has(issue.id) || issueNumbers.has(`${issue.repository.nameWithOwner.toLowerCase()}#${issue.number}`) || issue.repository.nameWithOwner.toLowerCase() === repository.toLowerCase() && issue.repository.id !== baseRepository.id)
730
+ throw new DeliveryError("Native closing-issue board identity is incomplete.");
731
+ issues.add(issue.id);
732
+ issueNumbers.add(`${issue.repository.nameWithOwner.toLowerCase()}#${issue.number}`);
733
+ closingLinks.issues.push({
734
+ id: issue.id,
735
+ number: issue.number,
736
+ repository: { id: issue.repository.id, name: issue.repository.nameWithOwner }
737
+ });
738
+ }
739
+ cursor = pageCursor(links, cursors);
740
+ if (cursor === null) {
741
+ closingLinks.complete = true;
742
+ break;
743
+ }
744
+ }
745
+ } catch {
746
+ native = null;
747
+ }
748
+ const [decision, proof] = await Promise.allSettled([
749
+ readRequiredReviewState(context, prNumber, pr.head.sha),
750
+ readRequiredCheckProof(context, pr.base.ref, pr.head.sha, true)
751
+ ]);
752
+ const review = decision.status === "fulfilled" ? { ...decision.value, observed: decision.value.observed === true } : {
753
+ observed: false,
754
+ reviewDecision: null,
755
+ status: "unknown",
756
+ submittedReviewAuthorCanPushToRepository: null,
757
+ nextAction: "Refresh exact-head native review evidence."
758
+ };
759
+ const checks = {
760
+ ...proof.status === "fulfilled" ? proof.value : { state: "waiting", reason: "Native required-check evidence is unavailable." },
761
+ complete: proof.status === "fulfilled" && proof.value.state === "passed"
762
+ };
763
+ const [current, reread] = await Promise.allSettled([
764
+ context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` }),
765
+ context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })
766
+ ]);
767
+ const ref = current.status === "fulfilled" ? current.value.data : null;
768
+ const currentBaseSha = ref?.ref === `refs/heads/${pr.base.ref}` && ref.object.type === "commit" && validSha(ref.object.sha) ? ref.object.sha : null;
769
+ const final = reread.status === "fulfilled" ? reread.value.data : null;
770
+ const stable = final !== null && final.node_id === pr.node_id && final.number === pr.number && final.head.sha === pr.head.sha && final.base.sha === pr.base.sha && final.head.ref === pr.head.ref && final.base.ref === pr.base.ref && final.head.repo?.node_id === headRepository.id && final.head.repo.full_name?.toLowerCase() === headRepository.name.toLowerCase() && final.base.repo?.node_id === baseRepository.id && final.base.repo.full_name?.toLowerCase() === baseRepository.name.toLowerCase() && final.state === pr.state && final.merged === pr.merged && final.draft === pr.draft && final.body === pr.body && final.title === pr.title && final.mergeable === pr.mergeable && final.mergeable_state === pr.mergeable_state;
771
+ const reference = /^References ([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#[1-9]\d*(?:\r?\n|$)/u.exec(pr.body ?? "");
772
+ const nonClosing = reference?.[1]?.toLowerCase() === repository.toLowerCase();
773
+ const reasons = [];
774
+ if (pr.state !== "open" || pr.merged) reasons.push("pr-closed");
775
+ if (pr.draft) reasons.push("draft");
776
+ if (nonClosing) reasons.push("non-closing");
777
+ if (!native) reasons.push("native-eligibility-unknown");
778
+ else if (native.mergeable !== "MERGEABLE" || native.mergeStateStatus !== "CLEAN" || pr.mergeable !== true || pr.mergeable_state !== "clean")
779
+ reasons.push("native-not-clean");
780
+ if (!review.observed) reasons.push("review-unknown");
781
+ else if (review.reviewDecision !== "APPROVED" && review.reviewDecision !== null)
782
+ reasons.push(review.reviewDecision === "CHANGES_REQUESTED" ? "changes-requested" : "review-required");
783
+ if (checks.state !== "passed") reasons.push(checks.state === "failed" ? "checks-failed" : "checks-unproven");
784
+ if (!closingLinks.complete) reasons.push("closing-links-unknown");
785
+ else if (!closingLinks.issues.some(
786
+ (issue) => issue.repository.id === baseRepository.id && issue.repository.name.toLowerCase() === repository.toLowerCase()
787
+ ))
788
+ reasons.push("no-closing-issue");
789
+ if (!stable) reasons.push("pr-drift-or-unavailable");
790
+ if (currentBaseSha !== pr.base.sha) reasons.push("base-moved-or-unavailable");
791
+ return {
792
+ repository: baseRepository,
793
+ headRepository,
794
+ number: pr.number,
795
+ url: pr.html_url,
796
+ title: pr.title,
797
+ state: pr.state,
798
+ draft: pr.draft,
799
+ nonClosing,
800
+ headSha: pr.head.sha,
801
+ baseSha: pr.base.sha,
802
+ headRef: pr.head.ref,
803
+ baseRef: pr.base.ref,
804
+ currentBaseSha,
805
+ mergeable: native?.mergeable ?? null,
806
+ mergeStateStatus: native?.mergeStateStatus ?? null,
807
+ review,
808
+ checks,
809
+ closingLinks,
810
+ stable,
811
+ ready: reasons.length === 0,
812
+ reasons
813
+ };
814
+ }
815
+ async function prChecks(context, prNumber) {
816
+ const pr = await getPr(context, prNumber);
817
+ const requirements = await readRequiredCheckNames(context, pr.base.ref);
818
+ const [checks, status, reviewState] = await Promise.all([
819
+ context.clients.rest.checks.listForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),
820
+ context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),
821
+ readRequiredReviewState(context, prNumber, pr.head.sha)
822
+ ]);
823
+ const headChecksComplete = checks.data.total_count === checks.data.check_runs.length && status.data.total_count === status.data.statuses.length;
824
+ return {
825
+ schemaVersion: "ai-delivery.pr-checks@1",
826
+ prNumber: pr.number,
827
+ headSha: pr.head.sha,
828
+ combinedStatus: status.data.state,
829
+ mergeStateStatus: pr.mergeable_state ?? "unknown",
830
+ requiredCheckDiscovery: requirements.complete ? "complete" : "partial",
831
+ headChecksComplete,
832
+ requiredChecks: requirements.names.map((name) => {
833
+ const states = [
834
+ ...checks.data.check_runs.filter((check) => check.name === name).map((check) => `check: ${check.status}/${check.conclusion ?? "pending"}`),
835
+ ...status.data.statuses.filter((check) => check.context === name).map((check) => `status: ${check.state}`)
836
+ ];
837
+ return { name, headState: states.join("; ") || (headChecksComplete ? "not-reported" : "unknown") };
838
+ }),
839
+ reviewState,
840
+ checkRuns: checks.data.check_runs.map((check) => ({
841
+ name: check.name,
842
+ status: check.status,
843
+ conclusion: check.conclusion
844
+ }))
845
+ };
569
846
  }
570
847
  function requiredApprovalCount(value) {
571
- if (typeof value !== 'object' || value === null)
572
- return null;
573
- const count = value.required_approving_review_count;
574
- return typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 ? count : null;
848
+ if (typeof value !== "object" || value === null) return null;
849
+ const count = value.required_approving_review_count;
850
+ return typeof count === "number" && Number.isSafeInteger(count) && count >= 0 ? count : null;
575
851
  }
576
852
  function completeRulePage(response) {
577
- return (response.status === 200 &&
578
- Array.isArray(response.data) &&
579
- response.headers !== undefined &&
580
- response.headers !== null &&
581
- (response.headers.link === undefined || response.headers.link === ''));
853
+ return response.status === 200 && Array.isArray(response.data) && response.headers !== void 0 && response.headers !== null && (response.headers.link === void 0 || response.headers.link === "");
582
854
  }
583
- /** Absence is proved only by an empty successful first page with no continuation evidence. */
584
855
  function emptyRulePage(response) {
585
- return completeRulePage(response) && Array.isArray(response.data) && response.data.length === 0;
856
+ return completeRulePage(response) && Array.isArray(response.data) && response.data.length === 0;
586
857
  }
587
858
  function branchRuleSources(context, base, control) {
588
- return Promise.allSettled([
589
- context.clients.rest.request('GET /repos/{owner}/{repo}/rules/branches/{branch}', {
590
- ...context.repo,
591
- branch: base,
592
- ...(control === undefined ? {} : { request: { signal: control.signal } }),
593
- }),
594
- context.clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}/protection', {
595
- ...context.repo,
596
- branch: base,
597
- ...(control === undefined ? {} : { request: { signal: control.signal } }),
598
- }),
599
- ]);
859
+ return Promise.allSettled([
860
+ context.clients.rest.request("GET /repos/{owner}/{repo}/rules/branches/{branch}", {
861
+ ...context.repo,
862
+ branch: base,
863
+ ...control === void 0 ? {} : { request: { signal: control.signal } }
864
+ }),
865
+ context.clients.rest.request("GET /repos/{owner}/{repo}/branches/{branch}/protection", {
866
+ ...context.repo,
867
+ branch: base,
868
+ ...control === void 0 ? {} : { request: { signal: control.signal } }
869
+ })
870
+ ]);
600
871
  }
601
- /** Check selected actors and rule evidence; publication also requires the configured author source. */
602
- export async function preflightReviewRoute(context, base, selectedReviewer, purpose = 'publication', control) {
603
- if (base === undefined) {
604
- try {
605
- base = (await context.clients.rest.repos.get({ ...context.repo })).data.default_branch;
606
- }
607
- catch {
608
- throw new DeliveryError('Author cannot read the selected GitHub repository; verify configured access.');
609
- }
610
- }
611
- const check = async () => {
612
- await control?.checkResources();
613
- control?.signal.throwIfAborted();
614
- };
615
- await check();
616
- const configuredAuthorSource = context.config.roles.author.authSource ?? 'app';
617
- const personalDevelopmentOverride = purpose === 'development' && configuredAuthorSource === 'app' && context.clients.authSource === 'personal';
618
- if (context.clients.authSource !== configuredAuthorSource && !personalDevelopmentOverride) {
619
- throw new DeliveryError(purpose === 'publication'
620
- ? 'PR publication requires the configured author credential; configure the personal author role for personal publication.'
621
- : 'Development access preflight requires the configured author credential or the explicit personal author override.');
622
- }
623
- if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor) {
624
- throw new DeliveryError('Delivery access preflight requires authenticated author identity readback.');
625
- }
626
- const author = await context.clients.authenticatedAuthor(control?.signal);
627
- await check();
628
- if (!author.actorLogin || !author.credentialIdentity) {
629
- throw new DeliveryError('Author GitHub identity readback is incomplete.');
630
- }
631
- const reviewer = selectedReviewer ??
632
- context.reviewerClients ??
633
- (await githubClients.createDeliveryGitHubClients({
634
- config: context.config,
635
- identity: context.config.roles.reviewer.identity,
636
- role: 'reviewer',
637
- selectedAuthor: context.clients,
638
- ...(control === undefined ? {} : { signal: control.signal }),
639
- }));
640
- await check();
641
- if (reviewer.role !== 'reviewer' || reviewer.authSource !== 'app' || !reviewer.appActorLogin) {
642
- throw new DeliveryError('Configured reviewer GitHub App identity is unavailable.');
643
- }
644
- const reviewerActor = await reviewer.appActorLogin(control?.signal);
645
- await check();
646
- if (!reviewerActor)
647
- throw new DeliveryError('Reviewer GitHub App actor lookup is incomplete.');
648
- if (author.actorLogin.toLowerCase() === reviewerActor.toLowerCase()) {
649
- throw new DeliveryError('Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.');
872
+ async function corroborateClassicProtectionAbsence(context, base, [rulesetResult, protectionResult], control) {
873
+ let confirmedUnprotected = false;
874
+ let confirmedRulesetOnly = false;
875
+ if (rulesetResult.status === "fulfilled" && completeRulePage(rulesetResult.value) && protectionResult.status === "rejected" && githubClients.hasBranchProtectionAbsence(protectionResult.reason, context.clients, context.repo, base)) {
876
+ const parameters = { ...context.repo, ...control === void 0 ? {} : { request: { signal: control.signal } } };
877
+ const [repository, branch, rulesets] = await Promise.allSettled([
878
+ context.clients.rest.request("GET /repos/{owner}/{repo}", parameters),
879
+ context.clients.rest.request("GET /repos/{owner}/{repo}/branches/{branch}", { ...parameters, branch: base }),
880
+ context.clients.rest.request("GET /repos/{owner}/{repo}/rulesets", {
881
+ ...parameters,
882
+ includes_parents: true,
883
+ per_page: 100,
884
+ page: 1
885
+ })
886
+ ]);
887
+ await control?.checkResources();
888
+ control?.signal.throwIfAborted();
889
+ if (repository.status === "fulfilled" && branch.status === "fulfilled" && rulesets.status === "fulfilled") {
890
+ const repoData = repository.value.data;
891
+ const branchData = branch.value.data;
892
+ const corroborated = repository.value.status === 200 && branch.value.status === 200 && typeof repoData?.full_name === "string" && repoData.full_name.toLowerCase() === `${context.repo.owner}/${context.repo.repo}`.toLowerCase() && (repoData.permissions?.push === true || repoData.permissions?.admin === true) && branchData?.name === base;
893
+ confirmedUnprotected = corroborated && emptyRulePage(rulesetResult.value) && branchData?.protected === false && branchData.protection?.enabled === false && emptyRulePage(rulesets.value);
894
+ confirmedRulesetOnly = corroborated && branchData?.protected === true && typeof branchData.protection?.enabled === "boolean" && completeRulePage(rulesets.value) && rulesetResult.value.data.length > 0 && rulesetResult.value.data.every((rule) => {
895
+ if (typeof rule !== "object" || rule === null || typeof rule.type !== "string" || !rule.type || typeof rule.ruleset_id !== "number" || !Number.isSafeInteger(rule.ruleset_id) || rule.ruleset_id <= 0 || typeof rule.ruleset_source !== "string" || (rule.ruleset_source_type === "Repository" ? rule.ruleset_source.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase() : rule.ruleset_source_type !== "Organization" || rule.ruleset_source.toLowerCase() !== context.repo.owner.toLowerCase()) || rule.type === "pull_request" && requiredApprovalCount(rule.parameters) === null)
896
+ return false;
897
+ const matches = rulesets.value.data.filter((ruleset) => ruleset?.id === rule.ruleset_id);
898
+ return matches.length === 1 && matches[0]?.source_type === rule.ruleset_source_type && matches[0]?.source === rule.ruleset_source && matches[0]?.enforcement === "active";
899
+ });
650
900
  }
901
+ }
902
+ return { confirmedUnprotected, confirmedRulesetOnly };
903
+ }
904
+ async function routeAuthor(context, purpose, check = async () => {
905
+ }, signal) {
906
+ const configuredAuthorSource = context.config.roles.author.authSource ?? "app";
907
+ const personalDevelopmentOverride = purpose === "development" && configuredAuthorSource === "app" && context.clients.authSource === "personal";
908
+ if (context.clients.authSource !== configuredAuthorSource && !personalDevelopmentOverride) {
909
+ throw new DeliveryError(
910
+ purpose === "publication" ? "PR publication requires the configured author credential; configure the personal author role for personal publication." : "Development access preflight requires the configured author credential or the explicit personal author override."
911
+ );
912
+ }
913
+ if (context.clients.role !== "author" || !context.clients.authenticatedAuthor) {
914
+ throw new DeliveryError("Delivery access preflight requires authenticated author identity readback.");
915
+ }
916
+ const author = await context.clients.authenticatedAuthor(signal);
917
+ await check();
918
+ if (!author.actorLogin || !author.credentialIdentity) {
919
+ throw new DeliveryError("Author GitHub identity readback is incomplete.");
920
+ }
921
+ return {
922
+ actorLogin: author.actorLogin,
923
+ authSource: context.clients.authSource,
924
+ credentialSource: context.clients.credentialSource ?? "unreported",
925
+ identity: personalDevelopmentOverride ? "personal" : context.config.roles.author.identity
926
+ };
927
+ }
928
+ async function preflightReviewRoute(context, base, selectedReviewer, purpose = "publication", control) {
929
+ if (base === void 0) {
651
930
  try {
652
- const repository = (await reviewer.rest.repos.get({
653
- ...context.repo,
654
- ...(control === undefined ? {} : { request: { signal: control.signal } }),
655
- })).data;
656
- await check();
657
- if (repository.full_name.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()) {
658
- throw new DeliveryError('Reviewer GitHub App repository readback disagrees with the selected checkout.');
659
- }
660
- }
661
- catch (error) {
662
- if (error instanceof DeliveryError)
663
- throw error;
664
- throw new DeliveryError('Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.');
931
+ base = (await context.clients.rest.repos.get({ ...context.repo })).data.default_branch;
932
+ } catch {
933
+ throw new DeliveryError("Author cannot read the selected GitHub repository; verify configured access.");
665
934
  }
666
- const [rulesetResult, protectionResult] = await branchRuleSources(context, base, control);
935
+ }
936
+ const check = async () => {
937
+ await control?.checkResources();
938
+ control?.signal.throwIfAborted();
939
+ };
940
+ await check();
941
+ const author = await routeAuthor(context, purpose, check, control?.signal);
942
+ const reviewer = selectedReviewer ?? context.reviewerClients ?? await githubClients.createDeliveryGitHubClients({
943
+ config: context.config,
944
+ identity: context.config.roles.reviewer.identity,
945
+ role: "reviewer",
946
+ selectedAuthor: context.clients,
947
+ ...control === void 0 ? {} : { signal: control.signal }
948
+ });
949
+ await check();
950
+ if (reviewer.role !== "reviewer" || reviewer.authSource !== "app" || !reviewer.appActorLogin) {
951
+ throw new DeliveryError("Configured reviewer GitHub App identity is unavailable.");
952
+ }
953
+ const reviewerActor = await reviewer.appActorLogin(control?.signal);
954
+ await check();
955
+ if (!reviewerActor) throw new DeliveryError("Reviewer GitHub App actor lookup is incomplete.");
956
+ if (author.actorLogin.toLowerCase() === reviewerActor.toLowerCase()) {
957
+ throw new DeliveryError(
958
+ "Author and reviewer resolve to the same GitHub actor; select distinct configured credentials."
959
+ );
960
+ }
961
+ try {
962
+ const repository = (await reviewer.rest.repos.get({
963
+ ...context.repo,
964
+ ...control === void 0 ? {} : { request: { signal: control.signal } }
965
+ })).data;
667
966
  await check();
668
- let confirmedUnprotected = false;
669
- let confirmedRulesetOnly = false;
670
- if (rulesetResult.status === 'fulfilled' &&
671
- completeRulePage(rulesetResult.value) &&
672
- protectionResult.status === 'rejected' &&
673
- githubClients.hasBranchProtectionAbsence(protectionResult.reason, context.clients, context.repo, base)) {
674
- // A generic/permission 404 is never absence. Corroborate the named branch,
675
- // selected author's write access, and all repository/parent rulesets.
676
- const parameters = { ...context.repo, ...(control === undefined ? {} : { request: { signal: control.signal } }) };
677
- const [repository, branch, rulesets] = await Promise.allSettled([
678
- context.clients.rest.request('GET /repos/{owner}/{repo}', parameters),
679
- context.clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}', { ...parameters, branch: base }),
680
- context.clients.rest.request('GET /repos/{owner}/{repo}/rulesets', {
681
- ...parameters,
682
- includes_parents: true,
683
- per_page: 100,
684
- page: 1,
685
- }),
686
- ]);
687
- await check();
688
- if (repository.status === 'fulfilled' && branch.status === 'fulfilled' && rulesets.status === 'fulfilled') {
689
- const repoData = repository.value.data;
690
- const branchData = branch.value.data;
691
- const corroborated = repository.value.status === 200 &&
692
- branch.value.status === 200 &&
693
- typeof repoData?.full_name === 'string' &&
694
- repoData.full_name.toLowerCase() === `${context.repo.owner}/${context.repo.repo}`.toLowerCase() &&
695
- (repoData.permissions?.push === true || repoData.permissions?.admin === true) &&
696
- branchData?.name === base;
697
- confirmedUnprotected =
698
- corroborated &&
699
- emptyRulePage(rulesetResult.value) &&
700
- branchData?.protected === false &&
701
- branchData.protection?.enabled === false &&
702
- emptyRulePage(rulesets.value);
703
- // The applicable-rules endpoint includes all active repository/parent
704
- // rules. A classic-protection 404 needs independent identity and active
705
- // ruleset readbacks, not just an observed approval count. The aggregate
706
- // protected flag and nested enabled summary need not be equal.
707
- confirmedRulesetOnly =
708
- corroborated &&
709
- branchData?.protected === true &&
710
- typeof branchData.protection?.enabled === 'boolean' &&
711
- completeRulePage(rulesets.value) &&
712
- rulesetResult.value.data.length > 0 &&
713
- rulesetResult.value.data.every((rule) => {
714
- if (typeof rule !== 'object' ||
715
- rule === null ||
716
- typeof rule.type !== 'string' ||
717
- !rule.type ||
718
- typeof rule.ruleset_id !== 'number' ||
719
- !Number.isSafeInteger(rule.ruleset_id) ||
720
- rule.ruleset_id <= 0 ||
721
- typeof rule.ruleset_source !== 'string' ||
722
- (rule.ruleset_source_type === 'Repository'
723
- ? rule.ruleset_source.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()
724
- : rule.ruleset_source_type !== 'Organization' ||
725
- rule.ruleset_source.toLowerCase() !== context.repo.owner.toLowerCase()) ||
726
- (rule.type === 'pull_request' && requiredApprovalCount(rule.parameters) === null))
727
- return false;
728
- const matches = rulesets.value.data.filter((ruleset) => ruleset?.id === rule.ruleset_id);
729
- return (matches.length === 1 &&
730
- matches[0]?.source_type === rule.ruleset_source_type &&
731
- matches[0]?.source === rule.ruleset_source &&
732
- matches[0]?.enforcement === 'active');
733
- });
734
- }
967
+ if (repository.full_name.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()) {
968
+ throw new DeliveryError("Reviewer GitHub App repository readback disagrees with the selected checkout.");
735
969
  }
736
- const counts = [];
737
- let countsKnown = rulesetResult.status === 'fulfilled' && completeRulePage(rulesetResult.value);
738
- if (rulesetResult.status === 'fulfilled' && Array.isArray(rulesetResult.value.data)) {
739
- for (const rule of rulesetResult.value.data) {
740
- if (typeof rule !== 'object' || rule === null || typeof rule.type !== 'string' || !rule.type)
741
- countsKnown = false;
742
- if (rule?.type === 'pull_request') {
743
- const count = requiredApprovalCount(rule.parameters);
744
- if (count === null)
745
- countsKnown = false;
746
- else
747
- counts.push(count);
748
- }
749
- }
750
- }
751
- if (protectionResult.status === 'fulfilled') {
752
- const protection = protectionResult.value.data;
753
- const count = typeof protection === 'object' && protection !== null && !Array.isArray(protection)
754
- ? requiredApprovalCount(protection.required_pull_request_reviews)
755
- : null;
756
- if (protectionResult.value.status !== 200 || count === null)
757
- countsKnown = false;
758
- if (count !== null)
759
- counts.push(count);
970
+ } catch (error) {
971
+ if (error instanceof DeliveryError) throw error;
972
+ throw new DeliveryError(
973
+ "Reviewer GitHub App cannot read the selected repository; verify its installation and repository access."
974
+ );
975
+ }
976
+ const [rulesetResult, protectionResult] = await branchRuleSources(context, base, control);
977
+ await check();
978
+ const { confirmedUnprotected, confirmedRulesetOnly } = await corroborateClassicProtectionAbsence(
979
+ context,
980
+ base,
981
+ [rulesetResult, protectionResult],
982
+ control
983
+ );
984
+ const counts = [];
985
+ let countsKnown = rulesetResult.status === "fulfilled" && completeRulePage(rulesetResult.value);
986
+ if (rulesetResult.status === "fulfilled" && Array.isArray(rulesetResult.value.data)) {
987
+ for (const rule of rulesetResult.value.data) {
988
+ if (typeof rule !== "object" || rule === null || typeof rule.type !== "string" || !rule.type) countsKnown = false;
989
+ if (rule?.type === "pull_request") {
990
+ const count = requiredApprovalCount(rule.parameters);
991
+ if (count === null) countsKnown = false;
992
+ else counts.push(count);
993
+ }
760
994
  }
761
- else if (!confirmedUnprotected && !confirmedRulesetOnly)
762
- countsKnown = false;
763
- const rulesVisible = rulesetResult.status === 'fulfilled' &&
764
- Array.isArray(rulesetResult.value.data) &&
765
- (rulesetResult.value.headers?.link === undefined || rulesetResult.value.headers.link === '');
766
- const visible = Number(rulesVisible) +
767
- Number(protectionResult.status === 'fulfilled' || confirmedUnprotected || confirmedRulesetOnly);
768
- const visibility = visible === 2 ? 'complete' : visible === 1 ? 'partial' : 'unknown';
769
- // A positive observation is a conservative lower bound for permission checks.
770
- // Zero requires complete, valid requirement evidence from every source.
771
- const observedRequiredApprovals = counts.length > 0 && (countsKnown || counts.some((count) => count > 0))
772
- ? Math.max(...counts)
773
- : countsKnown && confirmedUnprotected
774
- ? 0
775
- : null;
776
- const insufficientPermission = observedRequiredApprovals !== null &&
777
- observedRequiredApprovals > 0 &&
778
- reviewer.effectiveContentsPermission === 'read';
779
- return {
780
- author: {
781
- actorLogin: author.actorLogin,
782
- authSource: context.clients.authSource,
783
- credentialSource: context.clients.credentialSource ?? 'unreported',
784
- identity: personalDevelopmentOverride ? 'personal' : context.config.roles.author.identity,
785
- },
786
- reviewer: {
787
- actorLogin: reviewerActor,
788
- credentialSource: reviewer.credentialSource ?? 'unreported',
789
- effectiveContentsPermission: reviewer.effectiveContentsPermission ?? 'unknown',
790
- identity: context.config.roles.reviewer.identity,
791
- repositoryAccess: 'readable',
792
- },
793
- rules: { observedRequiredApprovals, visibility },
794
- approvalEligibility: insufficientPermission ? 'insufficient-permission' : 'unknown',
795
- nextAction: insufficientPermission
796
- ? 'The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.'
797
- : visibility === 'complete' && observedRequiredApprovals === null
798
- ? 'No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.'
799
- : visibility === 'complete'
800
- ? 'Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.'
801
- : 'Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.',
802
- };
995
+ }
996
+ if (protectionResult.status === "fulfilled") {
997
+ const protection = protectionResult.value.data;
998
+ const count = typeof protection === "object" && protection !== null && !Array.isArray(protection) ? requiredApprovalCount(protection.required_pull_request_reviews) : null;
999
+ if (protectionResult.value.status !== 200 || count === null) countsKnown = false;
1000
+ if (count !== null) counts.push(count);
1001
+ } else if (!confirmedUnprotected && !confirmedRulesetOnly) countsKnown = false;
1002
+ const rulesVisible = rulesetResult.status === "fulfilled" && Array.isArray(rulesetResult.value.data) && (rulesetResult.value.headers?.link === void 0 || rulesetResult.value.headers.link === "");
1003
+ const visible = Number(rulesVisible) + Number(protectionResult.status === "fulfilled" || confirmedUnprotected || confirmedRulesetOnly);
1004
+ const visibility = visible === 2 ? "complete" : visible === 1 ? "partial" : "unknown";
1005
+ const observedRequiredApprovals = counts.length > 0 && (countsKnown || counts.some((count) => count > 0)) ? Math.max(...counts) : countsKnown && confirmedUnprotected ? 0 : null;
1006
+ const insufficientPermission = observedRequiredApprovals !== null && observedRequiredApprovals > 0 && reviewer.effectiveContentsPermission === "read";
1007
+ return {
1008
+ author,
1009
+ reviewer: {
1010
+ actorLogin: reviewerActor,
1011
+ credentialSource: reviewer.credentialSource ?? "unreported",
1012
+ effectiveContentsPermission: reviewer.effectiveContentsPermission ?? "unknown",
1013
+ identity: context.config.roles.reviewer.identity,
1014
+ repositoryAccess: "readable"
1015
+ },
1016
+ rules: { observedRequiredApprovals, visibility },
1017
+ approvalEligibility: insufficientPermission ? "insufficient-permission" : "unknown",
1018
+ nextAction: insufficientPermission ? "The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication." : visibility === "complete" && observedRequiredApprovals === null ? "No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission." : visibility === "complete" ? "Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility." : "Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission."
1019
+ };
803
1020
  }
804
- export async function publishPr(context, input) {
805
- const nonClosing = nonClosingMode(input.nonClosing);
806
- if (input.prNumber !== undefined && (!Number.isSafeInteger(input.prNumber) || input.prNumber <= 0))
807
- throw new DeliveryError('Existing PR selector must be a positive safe integer.');
808
- const issue = nonClosing
809
- ? await openReferenceIssue(context, input.issueNumber)
810
- : (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;
811
- if ('pull_request' in issue || issue.number !== input.issueNumber || issue.state !== 'open')
812
- throw new DeliveryError('PR creation requires the requested open GitHub issue.');
813
- const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
814
- if (repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() ||
815
- context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
816
- throw new DeliveryError('Configured and selected GitHub repository identities disagree.');
817
- if (nonClosing && !nativeId(repository.node_id))
818
- throw new DeliveryError('Incomplete canonical non-closing repository node identity.');
819
- const base = input.baseBranch ?? repository.default_branch;
820
- if (base !== repository.default_branch)
821
- throw new DeliveryError('PR delivery requires the repository default branch for durable issue association.');
822
- validBranch(base);
823
- if (input.headBranch !== undefined)
824
- validBranch(input.headBranch);
825
- const explicit = input.prNumber === undefined ? undefined : await getPr(context, input.prNumber);
826
- const explicitPromotion = input.draft === false && input.headBranch !== undefined;
827
- const selectedMatches = explicit
828
- ? await matchingPrs(context, explicit.head.ref, base)
829
- : explicitPromotion
830
- ? await matchingPrs(context, input.headBranch, base)
831
- : undefined;
832
- const branch = explicit
833
- ? explicit.head.ref
834
- : explicitPromotion && selectedMatches.length > 0
835
- ? input.headBranch
836
- : await issueBranch(context, input.issueNumber, input.headBranch);
837
- if (input.headBranch !== undefined && branch !== input.headBranch)
838
- throw new DeliveryError('Explicit PR and head selectors disagree.');
839
- validBranch(branch);
840
- const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;
841
- if (ref.ref !== `refs/heads/${branch}` || ref.object.type !== 'commit' || !validSha(ref.object.sha))
842
- throw new DeliveryError('Remote issue branch head/ref readback is invalid.');
843
- const matches = selectedMatches ?? (await matchingPrs(context, branch, base));
844
- if (matches.length > 1 || (explicit && (matches.length !== 1 || matches[0].number !== explicit.number)))
845
- throw new DeliveryError('Remote issue branch has conflicting PR matches.');
846
- let pr = explicit ?? (matches[0] === undefined ? undefined : await getPr(context, matches[0].number));
847
- const requestedBody = input.body ??
848
- (nonClosing ? (pr?.body ?? referenceLine(context, input.issueNumber)) : `Closes #${input.issueNumber}`);
849
- if (!requestedBody.trim())
850
- throw new DeliveryError('PR body must contain text.');
851
- const body = nonClosing
852
- ? nonClosingBody(context, input.issueNumber, requestedBody)
853
- : new RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${input.issueNumber}(?![0-9])`, 'iu').test(requestedBody)
854
- ? requestedBody
855
- : `${requestedBody}\n\nCloses #${input.issueNumber}`;
856
- const transition = nonClosing && pr !== undefined && pr.body !== body;
857
- if (transition && (input.prNumber === undefined || input.body === undefined))
858
- throw new DeliveryError('Non-closing body transition requires an explicit existing PR number and body.');
859
- if (pr &&
860
- (pr.head.sha !== ref.object.sha ||
861
- pr.head.ref !== branch ||
862
- pr.base.ref !== base ||
863
- pr.state !== 'open' ||
864
- pr.merged ||
865
- (!transition && input.body !== undefined && pr.body !== body) ||
866
- (input.title !== undefined && pr.title !== input.title)))
867
- throw new DeliveryError('Existing remote PR conflicts with the requested branch, intent or state.');
868
- const reviewRoute = nonClosing ? await nonClosingRoute(context, base) : await preflightReviewRoute(context, base);
869
- if (pr && pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())
870
- throw new DeliveryError('Existing PR author differs from the configured authenticated author.');
871
- if (pr && (typeof pr.node_id !== 'string' || !pr.node_id))
872
- throw new DeliveryError('Existing PR publication identity is incomplete.');
873
- if (nonClosing)
874
- refuseClosingDirective(input.title ?? pr?.title ?? issue.title);
875
- const creationTitle = input.title ?? issue.title;
876
- let publicationBaseSha;
877
- const existing = pr;
878
- let pendingTransition = transition;
879
- let expectedBody = pr?.body;
880
- const transitionDraft = pr?.draft;
881
- let promotionApplied = false;
882
- const preserveIssue = async () => {
883
- if (nonClosing)
884
- sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
885
- };
886
- const readExisting = async () => {
887
- const current = await verifyIssuePr(context, input.issueNumber, existing.number, nonClosing && !pendingTransition);
888
- if (current.state !== 'open' ||
889
- current.merged ||
890
- current.node_id !== existing.node_id ||
891
- current.head.sha !== ref.object.sha ||
892
- current.head.ref !== branch ||
893
- current.base.ref !== base ||
894
- current.base.sha !== existing.base.sha ||
895
- current.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase() ||
896
- (transition && !promotionApplied && current.draft !== transitionDraft) ||
897
- current.body !== expectedBody ||
898
- current.title !== existing.title)
899
- throw new DeliveryError('Existing PR publication head, identity, intent or author readback drifted.');
900
- if (pendingTransition) {
901
- await verifyPrIssueAssociation(context, current.number, input.issueNumber, false, current.node_id, true, issue.node_id, repository.node_id);
902
- refuseClosingDirective(current.title);
903
- await verifyNonClosingCommits(context, current);
904
- const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;
905
- if (baseRef.ref !== `refs/heads/${base}` ||
906
- baseRef.object.type !== 'commit' ||
907
- baseRef.object.sha !== current.base.sha)
908
- throw new DeliveryError('Non-closing transition default base drifted.');
909
- sameReferencePr(current, await getPr(context, current.number));
910
- }
911
- await preserveIssue();
912
- return current;
913
- };
914
- const readNew = async () => {
915
- const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;
916
- if (baseRef.ref !== `refs/heads/${base}` || baseRef.object.type !== 'commit' || !validSha(baseRef.object.sha))
917
- throw new DeliveryError('Incomplete publication default base.');
918
- if (publicationBaseSha !== undefined && publicationBaseSha !== baseRef.object.sha)
919
- throw new DeliveryError('Publication default base drifted before creation.');
920
- publicationBaseSha = baseRef.object.sha;
921
- if (nonClosing)
922
- await verifyUnpublishedCommits(context, baseRef.object.sha, ref.object.sha);
923
- const afterHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;
924
- const afterBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;
925
- if (afterHead.ref !== ref.ref ||
926
- afterHead.object.type !== 'commit' ||
927
- afterHead.object.sha !== ref.object.sha ||
928
- afterBase.ref !== baseRef.ref ||
929
- afterBase.object.type !== 'commit' ||
930
- afterBase.object.sha !== baseRef.object.sha)
931
- throw new DeliveryError('Non-closing publication head/base drifted.');
932
- await preserveIssue();
933
- };
934
- if (pr)
935
- pr = await readExisting();
936
- else
937
- await readNew();
938
- if (input.dryRun)
939
- return {
940
- dryRun: true,
941
- ...(pr === undefined ? {} : { prNumber: pr.number, draft: pr.draft }),
942
- ...(nonClosing
943
- ? {
944
- nonClosing: true,
945
- nonClosingVerified: pr !== undefined && !pendingTransition,
946
- body,
947
- bodyTransition: pendingTransition,
948
- }
949
- : {}),
950
- headSha: ref.object.sha,
951
- headBranch: branch,
952
- baseBranch: base,
953
- reviewRoute,
954
- };
955
- let created = false;
956
- if (pr) {
957
- if (pendingTransition) {
958
- pr = await readExisting();
959
- await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });
960
- pendingTransition = false;
961
- expectedBody = body;
962
- pr = await readExisting();
963
- }
964
- if (input.draft === false && pr.draft) {
965
- pr = await readExisting();
966
- if (pr.draft) {
967
- const promoted = await context.clients.graphql('mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}', { id: pr.node_id });
968
- if (promoted?.markPullRequestReadyForReview?.pullRequest?.id !== pr.node_id ||
969
- promoted.markPullRequestReadyForReview.pullRequest.isDraft !== false)
970
- throw new DeliveryError('PR promotion mutation readback is incomplete or conflicting; reconcile this PR.');
971
- promotionApplied = true;
972
- }
973
- pr = await readExisting();
974
- if (pr.draft)
975
- throw new DeliveryError('PR promotion readback is still draft.');
976
- }
977
- }
978
- else {
979
- await readNew();
980
- let response;
981
- try {
982
- response = await context.clients.rest.pulls.create({
983
- ...context.repo,
984
- head: branch,
985
- base,
986
- title: creationTitle,
987
- body,
988
- draft: input.draft !== false,
989
- });
990
- }
991
- catch (error) {
992
- throw new DeliveryError(`PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${error instanceof Error ? error.message : 'Unknown failure'}`);
993
- }
994
- if (!Number.isSafeInteger(response.data.number) || response.data.number <= 0)
995
- throw new DeliveryError('PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.');
996
- created = true;
997
- try {
998
- pr = await getPr(context, response.data.number);
999
- }
1000
- catch (error) {
1001
- throw new DeliveryError(`GitHub returned created PR #${response.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${error instanceof Error ? error.message : 'Unknown failure'}`);
1002
- }
1003
- }
1021
+ async function publishPr(context, input) {
1022
+ const nonClosing = nonClosingMode(input.nonClosing);
1023
+ const reconcileReference = nonClosingMode(input.reconcileNonClosingReference);
1024
+ if (reconcileReference) {
1025
+ if (context.clients.role !== "author" || context.clients.authSource !== (context.config.roles.author.authSource ?? "app") || !context.clients.authenticatedAuthor)
1026
+ throw new DeliveryError("Reference reconciliation requires the configured authenticated author role.");
1027
+ if (!nonClosing || input.draft === false || !validSha(input.expectedHeadSha) || !validSha(input.expectedBaseSha) || typeof input.body !== "string" || !input.body.trim())
1028
+ throw new DeliveryError(
1029
+ "Reference reconciliation requires nonClosing, DRAFT, explicit safe body and exact expected head/base SHAs."
1030
+ );
1031
+ refuseClosingDirective(input.body);
1032
+ } else if (input.expectedHeadSha !== void 0 || input.expectedBaseSha !== void 0)
1033
+ throw new DeliveryError("Expected head/base inputs require explicit reconcileNonClosingReference.");
1034
+ if (input.prNumber !== void 0 && (!Number.isSafeInteger(input.prNumber) || input.prNumber <= 0))
1035
+ throw new DeliveryError("Existing PR selector must be a positive safe integer.");
1036
+ const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;
1037
+ if ("pull_request" in issue || issue.number !== input.issueNumber || issue.state !== "open")
1038
+ throw new DeliveryError("PR creation requires the requested open GitHub issue.");
1039
+ const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
1040
+ if (repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() || context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
1041
+ throw new DeliveryError("Configured and selected GitHub repository identities disagree.");
1042
+ if (nonClosing && !nativeId(repository.node_id))
1043
+ throw new DeliveryError("Incomplete canonical non-closing repository node identity.");
1044
+ const base = input.baseBranch ?? repository.default_branch;
1045
+ if (base !== repository.default_branch)
1046
+ throw new DeliveryError("PR delivery requires the repository default branch for durable issue association.");
1047
+ validBranch(base);
1048
+ if (input.headBranch !== void 0) validBranch(input.headBranch);
1049
+ const explicit = input.prNumber === void 0 ? void 0 : await getPr(context, input.prNumber);
1050
+ const explicitPromotion = nonClosing && input.draft === false && input.headBranch !== void 0;
1051
+ const selectedMatches = explicitPromotion ? await matchingPrs(context, input.headBranch, base) : void 0;
1052
+ const branch = explicit ? explicit.head.ref : nonClosing ? explicitPromotion && selectedMatches.length > 0 ? input.headBranch : await issueBranch(context, input.issueNumber, input.headBranch) : input.headBranch ?? await issueBranch(context, input.issueNumber);
1053
+ if (input.headBranch !== void 0 && branch !== input.headBranch)
1054
+ throw new DeliveryError("Explicit PR and head selectors disagree.");
1055
+ validBranch(branch);
1056
+ const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;
1057
+ if (ref.ref !== `refs/heads/${branch}` || ref.object.type !== "commit" || !validSha(ref.object.sha))
1058
+ throw new DeliveryError("Remote issue branch head/ref readback is invalid.");
1059
+ const matches = selectedMatches ?? await matchingPrs(context, branch, base, nonClosing ? "all" : "open");
1060
+ if (matches.length > 1 || explicit && (matches.length !== 1 || matches[0].number !== explicit.number))
1061
+ throw new DeliveryError("Remote issue branch has conflicting PR matches.");
1062
+ let pr = explicit ?? (matches[0] === void 0 ? void 0 : await getPr(context, matches[0].number));
1063
+ if (pr && input.draft === false && input.headBranch === void 0 && input.prNumber === void 0 && (await linkedIssueBranches(context, input.issueNumber)).filter((entry) => entry.name === branch).length !== 1)
1064
+ throw new DeliveryError("Select an explicit PR or head after GitHub-linked branch references disappear.");
1065
+ if (reconcileReference && pr && !explicit)
1066
+ throw new DeliveryError(
1067
+ "Reference reconciliation of an existing match requires explicit --pr and caller-reconciled authority/attempt receipts."
1068
+ );
1069
+ if (nonClosing && !pr && !reconcileReference)
1070
+ throw new DeliveryError(
1071
+ "New linked-branch non-closing publication requires explicitly authorized --reconcile-non-closing-reference --expected-head SHA --expected-base SHA and --body-file PATH; bare --non-closing grants no removal authority."
1072
+ );
1073
+ if (reconcileReference && ref.object.sha !== input.expectedHeadSha)
1074
+ throw new DeliveryError("Reference reconciliation expected head differs from the exact remote linked head.");
1075
+ const requestedBody = input.body ?? pr?.body ?? (nonClosing ? referenceLine(context, input.issueNumber) : closingBody(issue));
1076
+ if ((nonClosing || input.body !== void 0) && !requestedBody.trim())
1077
+ throw new DeliveryError("PR body must contain text.");
1078
+ const body = publicationBody(
1079
+ nonClosing ? nonClosingBody(context, input.issueNumber, requestedBody) : closingBody(issue, requestedBody),
1080
+ pr?.body
1081
+ );
1082
+ const closingRepair = !nonClosing && pr !== void 0 && !hasClosingLink(pr.body, input.issueNumber);
1083
+ const transition = nonClosing && pr !== void 0 && pr.body !== body;
1084
+ const referenceUpdate = transition && hasReferenceBody(context, input.issueNumber, pr?.body);
1085
+ if (reconcileReference && transition)
1086
+ throw new DeliveryError("Reference reconciliation refuses body transition; retain exact original intent.");
1087
+ if (transition && (input.prNumber === void 0 || input.body === void 0))
1088
+ throw new DeliveryError("Non-closing body transition requires an explicit existing PR number and body.");
1089
+ if (pr && (pr.head.sha !== ref.object.sha || pr.head.ref !== branch || pr.base.ref !== base || pr.state !== "open" || pr.merged || !transition && input.body !== void 0 && pr.body !== input.body && pr.body !== body || input.title !== void 0 && pr.title !== input.title))
1090
+ throw new DeliveryError("Existing remote PR conflicts with the requested branch, intent or state.");
1091
+ const reviewRoute = nonClosing ? await nonClosingRoute(context, base) : { author: await routeAuthor(context, "publication") };
1092
+ if (pr && pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())
1093
+ throw new DeliveryError("Existing PR author differs from the configured authenticated author.");
1094
+ if (pr && (typeof pr.node_id !== "string" || !pr.node_id))
1095
+ throw new DeliveryError("Existing PR publication identity is incomplete.");
1096
+ if (nonClosing) refuseClosingDirective(input.title ?? pr?.title ?? issue.title);
1097
+ const creationTitle = input.title ?? issue.title;
1098
+ let publicationBaseSha;
1099
+ const existing = pr;
1100
+ let pendingTransition = transition;
1101
+ let pendingClosingRepair = closingRepair;
1102
+ let expectedBody = pr?.body;
1103
+ const transitionDraft = pr?.draft;
1104
+ let promotionApplied = false;
1105
+ let removalState = "not attempted";
1106
+ const preserveIssue = async () => {
1107
+ if (nonClosing) sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
1108
+ };
1109
+ const readReconciliation = async (selected) => {
1004
1110
  try {
1005
- if (created &&
1006
- (pr.body !== body ||
1007
- pr.title !== creationTitle ||
1008
- pr.draft !== (input.draft !== false) ||
1009
- pr.state !== 'open' ||
1010
- pr.merged ||
1011
- pr.base.sha !== publicationBaseSha))
1012
- throw new DeliveryError('Created PR body, title, draft/open state or default base differs from publication intent.');
1013
- if (pr.head.sha !== ref.object.sha || pr.head.ref !== branch || pr.base.ref !== base)
1014
- throw new DeliveryError('GitHub PR creation readback drifted.');
1015
- if (pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())
1016
- throw new DeliveryError('Published PR author differs from the configured authenticated author.');
1017
- if (nonClosing) {
1018
- const verified = await verifyIssuePr(context, input.issueNumber, pr.number, true);
1019
- sameReferencePr(pr, verified);
1020
- pr = verified;
1021
- await preserveIssue();
1022
- }
1023
- else
1024
- await verifyPrIssueAssociation(context, pr.number, input.issueNumber);
1025
- if (created) {
1026
- const final = await getPr(context, pr.number);
1027
- sameReferencePr(pr, final);
1028
- pr = final;
1029
- }
1111
+ if (selected.state !== "open" || selected.draft !== true || selected.merged || selected.head.sha !== input.expectedHeadSha || selected.base.sha !== input.expectedBaseSha || selected.head.ref !== branch || selected.base.ref !== base || selected.body !== body || selected.title !== (existing?.title ?? creationTitle) || selected.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())
1112
+ throw new DeliveryError("Reference reconciliation DRAFT, exact head/base, message or author drifted.");
1113
+ const graph = await readNonClosingReference(context, input.issueNumber, selected);
1114
+ sameReferenceIssue(issue, graph.issue);
1115
+ const safe = !graph.closesTarget && !graph.allClosing.length && !graph.manualClosing.length;
1116
+ if (!safe && !(graph.closesTarget && graph.allClosing.length === 1 && graph.manualClosing.length === 1))
1117
+ throw new DeliveryError(
1118
+ "Reference removal requires only the intended manual closing pair and closing cross-reference."
1119
+ );
1120
+ const currentHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;
1121
+ if (currentHead.ref !== ref.ref || currentHead.object.type !== "commit" || currentHead.object.sha !== input.expectedHeadSha)
1122
+ throw new DeliveryError("Reference reconciliation source head drifted.");
1123
+ sameReferencePr(selected, await getPr(context, selected.number));
1124
+ await preserveIssue();
1125
+ return !safe;
1126
+ } catch (error) {
1127
+ throw new DeliveryError(
1128
+ `PR #${selected.number}; reference removal ${removalState}. Reconcile read-only; do not retry without caller-established authority and attempt history. ${error instanceof Error ? error.message : "Unknown failure"}`
1129
+ );
1130
+ }
1131
+ };
1132
+ const readExisting = async () => {
1133
+ const current = reconcileReference || pendingClosingRepair ? await getPr(context, existing.number) : await verifyIssuePr(
1134
+ context,
1135
+ input.issueNumber,
1136
+ existing.number,
1137
+ nonClosing && (!pendingTransition || referenceUpdate)
1138
+ );
1139
+ if (current.state !== "open" || current.merged || current.node_id !== existing.node_id || current.head.sha !== ref.object.sha || current.head.ref !== branch || current.base.ref !== base || current.base.sha !== existing.base.sha || current.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase() || (transition || closingRepair) && !promotionApplied && current.draft !== transitionDraft || current.body !== expectedBody || current.title !== existing.title)
1140
+ throw new DeliveryError("Existing PR publication head, identity, intent or author readback drifted.");
1141
+ if (reconcileReference) await readReconciliation(current);
1142
+ if (pendingClosingRepair) {
1143
+ await verifyPrIssueAssociation(
1144
+ context,
1145
+ current.number,
1146
+ input.issueNumber,
1147
+ current.node_id,
1148
+ true,
1149
+ issue.node_id,
1150
+ repository.node_id,
1151
+ { allowMissing: true }
1152
+ );
1153
+ const currentRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;
1154
+ if (currentRef.ref !== ref.ref || currentRef.object.type !== "commit" || currentRef.object.sha !== ref.object.sha)
1155
+ throw new DeliveryError("Closing-link repair remote head drifted; reconcile read-only.");
1156
+ sameReferencePr(current, await getPr(context, current.number));
1030
1157
  }
1031
- catch (error) {
1032
- if (!created)
1033
- throw error;
1034
- throw new DeliveryError(`GitHub created PR #${pr.number} (${pr.html_url}) at ${pr.head.sha}; post-publication association/identity verification is unresolved. Reconcile this PR read-only; do not create again. ${error instanceof Error ? error.message : 'Unknown failure'}`);
1158
+ if (pendingTransition && !referenceUpdate) {
1159
+ await verifyPrIssueAssociation(
1160
+ context,
1161
+ current.number,
1162
+ input.issueNumber,
1163
+ current.node_id,
1164
+ true,
1165
+ issue.node_id,
1166
+ repository.node_id
1167
+ );
1168
+ refuseClosingDirective(current.title);
1169
+ await verifyNonClosingCommits(context, current);
1170
+ const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;
1171
+ if (baseRef.ref !== `refs/heads/${base}` || baseRef.object.type !== "commit" || baseRef.object.sha !== current.base.sha)
1172
+ throw new DeliveryError("Non-closing transition default base drifted.");
1173
+ sameReferencePr(current, await getPr(context, current.number));
1035
1174
  }
1175
+ await preserveIssue();
1176
+ return current;
1177
+ };
1178
+ const readNew = async () => {
1179
+ const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;
1180
+ if (baseRef.ref !== `refs/heads/${base}` || baseRef.object.type !== "commit" || !validSha(baseRef.object.sha))
1181
+ throw new DeliveryError("Incomplete publication default base.");
1182
+ if (publicationBaseSha !== void 0 && publicationBaseSha !== baseRef.object.sha)
1183
+ throw new DeliveryError("Publication default base drifted before creation.");
1184
+ publicationBaseSha = baseRef.object.sha;
1185
+ if (reconcileReference && publicationBaseSha !== input.expectedBaseSha)
1186
+ throw new DeliveryError("Reference reconciliation expected default base differs from the remote base.");
1187
+ if (nonClosing) await verifyUnpublishedCommits(context, baseRef.object.sha, ref.object.sha);
1188
+ const afterHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;
1189
+ const afterBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;
1190
+ if (afterHead.ref !== ref.ref || afterHead.object.type !== "commit" || afterHead.object.sha !== ref.object.sha || afterBase.ref !== baseRef.ref || afterBase.object.type !== "commit" || afterBase.object.sha !== baseRef.object.sha)
1191
+ throw new DeliveryError("Non-closing publication head/base drifted.");
1192
+ await preserveIssue();
1193
+ };
1194
+ if (pr) pr = await readExisting();
1195
+ else await readNew();
1196
+ if (input.dryRun)
1036
1197
  return {
1037
- prNumber: pr.number,
1038
- url: pr.html_url,
1039
- headSha: pr.head.sha,
1040
- draft: pr.draft,
1041
- reviewRoute,
1042
- ...(nonClosing ? { nonClosing: true } : {}),
1198
+ dryRun: true,
1199
+ ...pr === void 0 ? { body } : {},
1200
+ ...pr === void 0 ? {} : { prNumber: pr.number, draft: pr.draft },
1201
+ ...nonClosing ? {
1202
+ nonClosing: true,
1203
+ nonClosingVerified: pr !== void 0 && !pendingTransition,
1204
+ body,
1205
+ bodyTransition: pendingTransition
1206
+ } : {},
1207
+ headSha: ref.object.sha,
1208
+ headBranch: branch,
1209
+ baseBranch: base,
1210
+ reviewRoute,
1211
+ ...closingRepair ? { closingLinkAdded: false, body } : {},
1212
+ ...reconcileReference ? { referenceRemoval: "pending", nonClosingVerified: false } : {}
1043
1213
  };
1044
- }
1045
- export async function submitFormalReview(context, input) {
1046
- const nonClosing = nonClosingMode(input.nonClosing);
1047
- const pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);
1048
- const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : undefined;
1049
- const result = await submitReview({
1050
- context,
1051
- artifact: parseReviewArtifact(input.artifact),
1052
- issueNumber: input.issueNumber,
1053
- prNumber: input.prNumber,
1054
- ...(input.dryRun === undefined ? {} : { dryRun: input.dryRun }),
1055
- });
1056
- if (nonClosing) {
1057
- sameReferencePr(pr, await verifyIssuePr(context, input.issueNumber, input.prNumber, true));
1058
- sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
1214
+ let created = false;
1215
+ const warnings = [];
1216
+ if (pr) {
1217
+ if (pendingClosingRepair) {
1218
+ pr = await readExisting();
1219
+ try {
1220
+ await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });
1221
+ } catch (error) {
1222
+ throw new DeliveryError(
1223
+ `PR #${pr.number} closing-link repair acknowledgement is uncertain; reconcile this PR read-only before retrying. ${error instanceof Error ? error.message : "Unknown failure"}`
1224
+ );
1225
+ }
1226
+ pendingClosingRepair = false;
1227
+ expectedBody = body;
1228
+ pr = await readExisting();
1059
1229
  }
1060
- return result;
1061
- }
1062
- export async function mergePr(context, input) {
1063
- const nonClosing = nonClosingMode(input.nonClosing);
1064
- if (nonClosing && input.strategy !== undefined && input.strategy !== 'squash')
1065
- throw new DeliveryError('Non-closing merge requires squash with explicit safe messages.');
1066
- if (context.clients.role !== 'author' ||
1067
- context.clients.authSource !== (context.config.roles.author.authSource ?? 'app') ||
1068
- !context.clients.authenticatedAuthor)
1069
- throw new DeliveryError('Merge and finish require the configured authenticated author role.');
1070
- const author = await context.clients.authenticatedAuthor();
1071
- if (!author.actorLogin || !author.credentialIdentity)
1072
- throw new DeliveryError('Author identity readback is incomplete.');
1073
- let pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);
1074
- const initialPr = pr;
1075
- const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : undefined;
1076
- const squash = nonClosing
1077
- ? {
1078
- commit_title: pr.title,
1079
- commit_message: `${referenceLine(context, input.issueNumber)}\n\nDelivered by PR #${pr.number}.`,
1080
- }
1081
- : undefined;
1082
- if (squash) {
1083
- refuseClosingDirective(squash.commit_title);
1084
- refuseClosingDirective(squash.commit_message);
1230
+ if (pendingTransition) {
1231
+ pr = await readExisting();
1232
+ await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });
1233
+ pendingTransition = false;
1234
+ expectedBody = body;
1235
+ pr = await readExisting();
1085
1236
  }
1086
- if (input.reviewedHeadSha !== undefined && input.reviewedHeadSha !== pr.head.sha)
1087
- throw new DeliveryError('Requested reviewed head differs from the GitHub PR.');
1088
- if (pr.merged && pr.state === 'closed' && validSha(pr.merge_commit_sha))
1089
- return { mergeSha: pr.merge_commit_sha, headSha: pr.head.sha, reused: true };
1090
- if (pr.state !== 'open' || pr.draft)
1091
- throw new DeliveryError('GitHub PR must be open and ready for merge.');
1092
- if (pr.user.login.toLowerCase() !== author.actorLogin.toLowerCase())
1093
- throw new DeliveryError('Merge requires the configured PR author.');
1094
- const reviewedHead = pr.head.sha;
1095
- const blockers = await getNativeBlockerRelationships({
1096
- graphql: context.clients.graphql,
1097
- issueNumber: input.issueNumber,
1098
- repo: context.repo,
1099
- });
1100
- if (blockers.blockers.some((value) => value.state === 'OPEN'))
1101
- throw new DeliveryError('GitHub issue has unresolved native blockers.');
1102
- pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);
1103
- if (nonClosing) {
1104
- sameReferencePr(initialPr, pr);
1105
- sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
1106
- refuseClosingDirective(squash.commit_title);
1107
- refuseClosingDirective(squash.commit_message);
1237
+ if (input.draft === false && pr.draft) {
1238
+ pr = await readExisting();
1239
+ if (pr.draft) {
1240
+ const promoted = await context.clients.graphql(
1241
+ "mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}",
1242
+ { id: pr.node_id }
1243
+ );
1244
+ if (promoted?.markPullRequestReadyForReview?.pullRequest?.id !== pr.node_id || promoted.markPullRequestReadyForReview.pullRequest.isDraft !== false)
1245
+ throw new DeliveryError("PR promotion mutation readback is incomplete or conflicting; reconcile this PR.");
1246
+ promotionApplied = true;
1247
+ }
1248
+ pr = await readExisting();
1249
+ if (pr.draft) throw new DeliveryError("PR promotion readback is still draft.");
1108
1250
  }
1109
- const decision = await readRequiredReviewState(context, input.prNumber, reviewedHead);
1110
- pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);
1111
- if (nonClosing) {
1112
- sameReferencePr(initialPr, pr);
1113
- sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
1251
+ } else {
1252
+ await readNew();
1253
+ let response;
1254
+ try {
1255
+ response = await context.clients.rest.pulls.create({
1256
+ ...context.repo,
1257
+ head: branch,
1258
+ base,
1259
+ title: creationTitle,
1260
+ body,
1261
+ draft: input.draft !== false
1262
+ });
1263
+ } catch (error) {
1264
+ throw new DeliveryError(
1265
+ `PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${error instanceof Error ? error.message : "Unknown failure"}`
1266
+ );
1114
1267
  }
1115
- if (pr.head.sha !== reviewedHead || pr.base.ref !== initialPr.base.ref || pr.base.sha !== initialPr.base.sha)
1116
- throw new DeliveryError('GitHub head/base changed; refresh native merge eligibility.');
1117
- if (pr.state !== 'open' ||
1118
- pr.draft ||
1119
- pr.mergeable !== true ||
1120
- !['clean', 'has_hooks', 'unstable'].includes(pr.mergeable_state ?? '') ||
1121
- !decision.observed ||
1122
- (decision.reviewDecision !== 'APPROVED' && decision.reviewDecision !== null)) {
1123
- const requirements = await readRequiredCheckNames(context, pr.base.ref);
1124
- throw new DeliveryError(`GitHub merge eligibility is ${pr.mergeable_state ?? 'unknown'}; review eligibility is ${decision.status}. Required checks: ${requirements.names.join(', ') || (requirements.complete ? 'none' : 'unknown')}; requirement discovery is ${requirements.complete ? 'complete' : 'partial'}. ${decision.nextAction}`);
1268
+ if (!Number.isSafeInteger(response.data.number) || response.data.number <= 0)
1269
+ throw new DeliveryError(
1270
+ "PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again."
1271
+ );
1272
+ created = true;
1273
+ try {
1274
+ pr = await getPr(context, response.data.number);
1275
+ } catch (error) {
1276
+ throw new DeliveryError(
1277
+ `GitHub returned created PR #${response.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${error instanceof Error ? error.message : "Unknown failure"}`
1278
+ );
1125
1279
  }
1126
- const currentBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data
1127
- .object.sha;
1128
- if (!validSha(currentBase) || currentBase !== pr.base.sha)
1129
- throw new DeliveryError('GitHub base moved; refresh native merge eligibility before merge.');
1130
- if (input.dryRun)
1131
- return {
1132
- dryRun: true,
1133
- headSha: reviewedHead,
1134
- prNumber: pr.number,
1135
- ...(squash === undefined ? {} : { nonClosing: true, ...squash }),
1136
- };
1137
- const result = (await context.clients.rest.pulls.merge({
1138
- ...context.repo,
1139
- pull_number: input.prNumber,
1140
- sha: reviewedHead,
1141
- merge_method: input.strategy ?? 'squash',
1142
- ...squash,
1143
- })).data;
1144
- if (!result.merged || !validSha(result.sha))
1145
- throw new DeliveryError('GitHub refused the reviewed-head merge.');
1146
- const readback = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);
1280
+ }
1281
+ try {
1282
+ if (created && (pr.body !== body || pr.title !== creationTitle || pr.draft !== (input.draft !== false) || pr.state !== "open" || pr.merged || pr.base.sha !== publicationBaseSha))
1283
+ throw new DeliveryError(
1284
+ "Created PR body, title, draft/open state or default base differs from publication intent."
1285
+ );
1286
+ if (pr.head.sha !== ref.object.sha || pr.head.ref !== branch || pr.base.ref !== base)
1287
+ throw new DeliveryError("GitHub PR creation readback drifted.");
1288
+ if (pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())
1289
+ throw new DeliveryError("Published PR author differs from the configured authenticated author.");
1147
1290
  if (nonClosing) {
1148
- sameReferencePr(initialPr, readback, true);
1149
- sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
1150
- }
1151
- if (!readback.merged ||
1152
- readback.state !== 'closed' ||
1153
- readback.head.sha !== reviewedHead ||
1154
- readback.merge_commit_sha !== result.sha)
1155
- throw new DeliveryError('GitHub merged PR readback disagrees with the reviewed-head mutation.');
1156
- return { mergeSha: result.sha, headSha: reviewedHead, reused: false };
1157
- }
1158
- export async function finishIssue(context, input) {
1159
- if (nonClosingMode(input.nonClosing))
1160
- throw new DeliveryError('Non-closing delivery cannot finish or close its retained issue.');
1161
- const result = await mergePr(context, input);
1162
- if (input.dryRun)
1163
- return result;
1164
- const pr = await verifyIssuePr(context, input.issueNumber, input.prNumber);
1165
- if (!pr.merged || pr.state !== 'closed' || pr.merge_commit_sha !== result.mergeSha)
1166
- throw new DeliveryError('Intended GitHub PR is not verifiably merged; issue remains open.');
1167
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;
1168
- if (issue.number !== input.issueNumber || 'pull_request' in issue)
1169
- throw new DeliveryError('Finish target is not the intended GitHub issue.');
1170
- if (issue.state !== 'closed')
1171
- await context.clients.rest.issues.update({
1172
- ...context.repo,
1173
- issue_number: input.issueNumber,
1174
- state: 'closed',
1175
- state_reason: 'completed',
1176
- });
1177
- const readback = (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;
1178
- if (readback.number !== input.issueNumber || readback.state !== 'closed')
1179
- throw new DeliveryError('GitHub issue closure readback disagrees.');
1180
- return { ...result, issueClosed: true };
1181
- }
1182
- export { startIssueBranch };
1183
- function investigationRoot(context) {
1184
- const root = primaryGitRoot(context.root);
1185
- const repo = resolveRepoFromRemote(root, 'origin');
1186
- if (`${repo.owner}/${repo.repo}`.toLowerCase() !== context.config.repository.toLowerCase() ||
1187
- `${context.repo.owner}/${context.repo.repo}`.toLowerCase() !== context.config.repository.toLowerCase())
1188
- throw new DeliveryError('Investigation repository identity disagrees.');
1189
- return root;
1190
- }
1191
- async function withInvestigationExclusion(root, target, operation) {
1192
- const common = gitCommonDir(root);
1193
- for (const directory of [join(common, 'ai-delivery'), join(common, 'ai-delivery', 'writers@1')]) {
1194
- try {
1195
- const metadata = lstatSync(directory);
1196
- if (!metadata.isDirectory() || metadata.isSymbolicLink())
1197
- throw new DeliveryError('Investigation writer namespace is unsafe.');
1198
- }
1199
- catch (error) {
1200
- if (error.code !== 'ENOENT')
1201
- throw error;
1291
+ if (reconcileReference && await readReconciliation(pr)) {
1292
+ if (await readReconciliation(pr)) {
1293
+ removalState = "uncertain";
1294
+ try {
1295
+ const removed = await context.clients.graphql(
1296
+ "mutation DeliveryRemoveClosingReference($issueId:ID!,$pullRequestIds:[ID!]!,$clientMutationId:String!){removeCloseIssueReferences(input:{issueId:$issueId,pullRequestIds:$pullRequestIds,clientMutationId:$clientMutationId}){issue{id}}}",
1297
+ { issueId: issue.node_id, pullRequestIds: [pr.node_id], clientMutationId: randomUUID() }
1298
+ );
1299
+ if (removed.removeCloseIssueReferences?.issue?.id !== issue.node_id)
1300
+ throw new DeliveryError("Incomplete reference-removal acknowledgement.");
1301
+ removalState = "acknowledged";
1302
+ } catch (error) {
1303
+ throw new DeliveryError(
1304
+ `PR #${pr.number}; reference removal acknowledgement is uncertain. Reconcile read-only; no automatic retry or rollback. ${error instanceof Error ? error.message : "Unknown failure"}`
1305
+ );
1306
+ }
1202
1307
  }
1203
- ensurePrivateDirectoryDurably(directory);
1308
+ }
1309
+ const verified = await verifyIssuePr(context, input.issueNumber, pr.number, true);
1310
+ sameReferencePr(pr, verified);
1311
+ pr = verified;
1312
+ await preserveIssue();
1313
+ } else if (
1314
+ // GitHub lists a new PR's closing link a few seconds after creation (aviaratech/ai#3780).
1315
+ await verifyPrIssueAssociation(context, pr.number, input.issueNumber, void 0, false, void 0, void 0, {
1316
+ allowMissing: created
1317
+ }) === 0
1318
+ )
1319
+ warnings.push(
1320
+ `GitHub has not yet listed PR #${pr.number} as closing #${input.issueNumber}; confirm with issue_pr_info.`
1321
+ );
1322
+ if (created) {
1323
+ const final = await getPr(context, pr.number);
1324
+ sameReferencePr(pr, final);
1325
+ pr = final;
1204
1326
  }
1205
- return withWorktreeTransitionWriterAbsent(root, target, operation);
1206
- }
1207
- async function investigationNativeSource(context, issueNumber, headSha, state) {
1208
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
1209
- if (issue.number !== issueNumber ||
1210
- 'pull_request' in issue ||
1211
- issue.state !== state ||
1212
- new URL(issue.html_url).pathname.toLowerCase() !==
1213
- `/${context.config.repository}/issues/${String(issueNumber)}`.toLowerCase())
1214
- throw new DeliveryError('Investigation requires the exact native issue and expected state.');
1215
- const branches = await linkedIssueBranches(context, issueNumber);
1216
- if (branches.length !== 1 || branches[0].name !== `issue/${String(issueNumber)}` || branches[0].sha !== headSha)
1217
- throw new DeliveryError('Investigation requires one exact unchanged native linked branch.');
1218
- const prs = (await context.clients.rest.pulls.list({
1219
- ...context.repo,
1220
- state: 'all',
1221
- head: `${context.repo.owner}:${branches[0].name}`,
1222
- per_page: 100,
1223
- })).data;
1224
- if (prs.length !== 0)
1225
- throw new DeliveryError('Investigation completion cannot substitute for PR delivery.');
1226
- }
1227
- export function investigationPreparationBody(preparation) {
1228
- return stableJson({
1229
- schemaVersion: 'ai-delivery.investigation-preparation-acknowledgement@1',
1230
- preparation,
1231
- authority: 'prospective-registration-before-investigation-no-legacy-adoption',
1232
- });
1233
- }
1234
- export function investigationAuthorityBody(preparation, resultDigest) {
1235
- return stableJson({
1236
- schemaVersion: 'ai-delivery.investigation-removal-authority@1',
1237
- preparationId: preparation.preparationId,
1238
- repository: preparation.repository,
1239
- issueNumber: preparation.row.issueNumber,
1240
- head: preparation.head,
1241
- worktree: preparation.row.path,
1242
- branch: preparation.row.branch,
1243
- resultDigest,
1244
- disposition: 'remove-only-this-unchanged-investigation-worktree-retain-branch-and-evidence',
1245
- operationalClosure: 'all-investigation-producers-quiescent-and-excluded-through-completion-and-resume-no-outstanding-holds',
1246
- });
1327
+ } catch (error) {
1328
+ if (!created && !reconcileReference) throw error;
1329
+ throw new DeliveryError(
1330
+ `GitHub ${created ? "created" : "selected"} PR #${pr.number} (${pr.html_url}) at ${pr.head.sha}; post-publication association/identity verification is unresolved.${reconcileReference ? ` Reference removal ${removalState}.` : ""} Reconcile this PR read-only; do not create again. ${error instanceof Error ? error.message : "Unknown failure"}`
1331
+ );
1332
+ }
1333
+ return {
1334
+ prNumber: pr.number,
1335
+ url: pr.html_url,
1336
+ headSha: pr.head.sha,
1337
+ state: pr.draft ? "draft" : pr.state,
1338
+ ...closingRepair ? { closingLinkAdded: true } : {},
1339
+ ...nonClosing ? { nonClosing: true, nonClosingVerified: true } : {},
1340
+ ...reconcileReference ? { referenceRemoval: removalState } : {},
1341
+ ...warnings.length ? { warnings } : {}
1342
+ };
1247
1343
  }
1248
- export function investigationAcceptanceBody(preparation, resultDigest, authorityCommentId) {
1249
- return stableJson({
1250
- schemaVersion: 'ai-delivery.investigation-result-acceptance@1',
1251
- authority: JSON.parse(investigationAuthorityBody(preparation, resultDigest)),
1252
- authorityCommentId,
1253
- verdict: 'approved',
1254
- independentlyReviewed: 'complete-durable-result-exact-source-and-removal-scope',
1255
- });
1256
- }
1257
- /** Explicit author mode for a host-created worktree; ordinary start remains remote-only. */
1258
- export async function registerInvestigation(context, input) {
1259
- if (!Number.isSafeInteger(input.issueNumber) || input.issueNumber <= 0 || !Sha.test(input.expectedHeadSha))
1260
- throw new DeliveryError('Investigation preparation requires a positive issue and expected commit.');
1261
- const root = investigationRoot(context);
1262
- const target = join(root, '.worktrees', `issue-${String(input.issueNumber)}`);
1263
- if (input.investigationWorktree !== target || realpathSync(target) !== target)
1264
- throw new DeliveryError('Investigation worktree must be the exact canonical .worktrees/issue-N path.');
1265
- if (existsSync(join(root, '.issue-cli', 'issues', String(input.issueNumber))))
1266
- throw new DeliveryError('Historical issue custody remains preservation-only; investigation cannot adopt it.');
1267
- const actors = await authenticatedWorktreeActors(context);
1268
- const observed = investigationSourceIdentity(root, input.issueNumber);
1269
- const prior = readInvestigationPreparation(root, input.issueNumber);
1270
- await investigationNativeSource(context, input.issueNumber, observed.head.sha, 'open');
1271
- if (observed.head.sha !== input.expectedHeadSha)
1272
- throw new DeliveryError('Investigation preparation source drifted from the expected head.');
1273
- if (prior === undefined) {
1274
- const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
1275
- if (repository.full_name.toLowerCase() !== context.config.repository.toLowerCase() || !repository.default_branch)
1276
- throw new DeliveryError('Investigation native repository identity is incomplete.');
1277
- const base = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${repository.default_branch}` }))
1278
- .data;
1279
- if (base.object.sha !== observed.head.sha)
1280
- throw new DeliveryError('Prospective investigation must begin at the current native default commit.');
1344
+ async function submitFormalReview(context, input) {
1345
+ const nonClosing = nonClosingMode(input.nonClosing);
1346
+ const pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing, true);
1347
+ const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : void 0;
1348
+ const result = await submitReview({
1349
+ context,
1350
+ artifact: parseReviewArtifact(input.artifact),
1351
+ issueNumber: input.issueNumber,
1352
+ prNumber: input.prNumber,
1353
+ ...input.dryRun === void 0 ? {} : { dryRun: input.dryRun }
1354
+ });
1355
+ try {
1356
+ if (nonClosing) {
1357
+ sameReferencePr(pr, await verifyIssuePr(context, input.issueNumber, input.prNumber, true, true));
1358
+ sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));
1281
1359
  }
1282
- const date = new Date().toISOString();
1283
- const content = {
1284
- schemaVersion: 'ai-delivery.investigation-preparation@1',
1285
- repository: context.config.repository,
1286
- repoRoot: root,
1287
- row: prior?.row ?? {
1288
- branch: `issue/${String(input.issueNumber)}`,
1289
- createdAt: date,
1290
- identity: context.config.roles.author.identity,
1291
- issueNumber: input.issueNumber,
1292
- path: target,
1293
- status: 'active',
1294
- type: 'issue',
1295
- updatedAt: date,
1296
- },
1297
- ...observed,
1298
- operator: { actorLogin: actors.operator.actorLogin, credentialIdentity: actors.operator.credentialIdentity },
1299
- reviewerActor: actors.reviewerActor,
1300
- };
1301
- const preparation = InvestigationPreparationSchema.parse({ ...content, preparationId: digestValue(content) });
1302
- await withInvestigationExclusion(root, target, () => registerInvestigationCustody(preparation, async () => {
1303
- if (stableJson(investigationSourceIdentity(root, input.issueNumber)) !== stableJson(observed))
1304
- throw new DeliveryError('Investigation source changed before preparation acknowledgement.');
1305
- await investigationNativeSource(context, input.issueNumber, observed.head.sha, 'open');
1306
- const { commentId, url, body } = await commentIssue(context, {
1307
- issueNumber: input.issueNumber,
1308
- body: investigationPreparationBody(preparation),
1309
- });
1310
- if (stableJson(investigationSourceIdentity(root, input.issueNumber)) !== stableJson(observed))
1311
- throw new DeliveryError('Investigation source changed during preparation acknowledgement.');
1312
- return { commentId, url, body };
1313
- }));
1314
- return { preparation, acknowledgement: readInvestigationAcknowledgement(root, input.issueNumber), registered: true };
1315
- }
1316
- /** One non-mergeable completion path. No PR, issue close, reviewer submission or branch deletion occurs. */
1317
- export async function finishInvestigation(context, input) {
1318
- if (['prNumber', 'strategy', 'reviewedHeadSha', 'nonClosing'].some((key) => key in input))
1319
- throw new DeliveryError('Investigation completion refuses PR or merge options.');
1320
- const root = investigationRoot(context);
1321
- const preparation = readInvestigationPreparation(root, input.issueNumber);
1322
- if (!preparation)
1323
- throw new DeliveryError('No prospective investigation preparation; historical custody cannot be reconstructed.');
1324
- const resultPath = resolve(input.resultPath);
1325
- const resultRelative = relative(preparation.row.path, resultPath);
1326
- const resultOutside = resultRelative === '..' || resultRelative.startsWith(`..${sep}`) || isAbsolute(resultRelative);
1327
- if (realpathSync(resultPath) !== resultPath || !resultOutside)
1328
- throw new DeliveryError('Durable investigation result must be canonical and outside the removable worktree.');
1329
- const result = assertPrivateFile(resultPath, { maxBytes: 512 * 1024 });
1330
- if (result.length === 0)
1331
- throw new DeliveryError('Investigation result must contain durable evidence.');
1332
- const resultDigest = digestBytes(result);
1333
- const authorityBody = investigationAuthorityBody(preparation, resultDigest);
1334
- const acceptanceBody = input.authorityCommentId === undefined
1335
- ? undefined
1336
- : investigationAcceptanceBody(preparation, resultDigest, input.authorityCommentId);
1337
- const authorize = async () => {
1338
- await investigationNativeSource(context, input.issueNumber, preparation.head.sha, 'closed');
1339
- const closure = await readIssueClosure(context, input.issueNumber);
1340
- if (closure.state !== 'closed' || closure.closeReason !== 'completed' || closure.duplicateOf !== null)
1341
- throw new DeliveryError('Investigation requires native completed closed-issue authority.');
1342
- const acknowledgement = readInvestigationAcknowledgement(root, input.issueNumber);
1343
- const native = (await context.clients.rest.issues.getComment({ ...context.repo, comment_id: acknowledgement.commentId })).data;
1344
- if (native.id !== acknowledgement.commentId ||
1345
- native.body !== investigationPreparationBody(preparation) ||
1346
- native.body !== acknowledgement.body ||
1347
- native.issue_url.toLowerCase() !==
1348
- `https://api.github.com/repos/${preparation.repository}/issues/${String(input.issueNumber)}`.toLowerCase() ||
1349
- native.user?.type !== 'User' ||
1350
- native.user.login.toLowerCase() !== preparation.operator.actorLogin.toLowerCase() ||
1351
- `user:${String(native.user.id)}` !== preparation.operator.credentialIdentity)
1352
- throw new DeliveryError('Native prospective preparation acknowledgement changed.');
1353
- if (input.authorityCommentId === undefined ||
1354
- input.acceptanceCommentId === undefined ||
1355
- acceptanceBody === undefined)
1356
- throw new DeliveryError('Existing authentic operator and independent App acceptance comments are required.');
1357
- const authority = await assertNativeWorktreeAcceptance(context, {
1358
- repository: preparation.repository,
1359
- subject: input.issueNumber,
1360
- operator: preparation.operator,
1361
- reviewerActor: preparation.reviewerActor,
1362
- authorityCommentId: input.authorityCommentId,
1363
- acceptanceCommentId: input.acceptanceCommentId,
1364
- operatorBody: authorityBody,
1365
- reviewerBody: acceptanceBody,
1366
- revokedBody: stableJson({
1367
- schemaVersion: 'ai-delivery.investigation-removal-revocation@1',
1368
- preparationId: preparation.preparationId,
1369
- resultDigest,
1370
- authorityCommentId: input.authorityCommentId,
1371
- }),
1372
- });
1373
- const preparedAt = Date.parse(native.created_at);
1374
- for (const value of [authority.relinquishment, authority.acceptance]) {
1375
- const createdAt = Date.parse(value.created_at);
1376
- if (!Number.isFinite(preparedAt) || !Number.isFinite(createdAt) || createdAt < preparedAt)
1377
- throw new DeliveryError('Investigation acceptance must follow its prospective preparation.');
1378
- }
1379
- return { acknowledgement: native, closure, ...authority };
1360
+ if ("dryRun" in result) return result;
1361
+ return {
1362
+ ...result,
1363
+ requiredReview: await readRequiredReviewState(context, input.prNumber, result.headSha, {
1364
+ id: result.githubReviewId,
1365
+ login: result.login,
1366
+ state: result.state
1367
+ })
1380
1368
  };
1381
- if (input.dryRun && (input.authorityCommentId === undefined || input.acceptanceCommentId === undefined)) {
1382
- assertInvestigationSource(preparation, context.root);
1383
- await investigationNativeSource(context, input.issueNumber, preparation.head.sha, 'closed');
1384
- return {
1385
- completed: false,
1386
- ready: false,
1387
- preparationId: preparation.preparationId,
1388
- resultDigest,
1389
- authorityBody,
1390
- ...(acceptanceBody === undefined ? {} : { acceptanceBody }),
1391
- missingEvidence: 'Existing authentic operator and configured-App exact-result acceptance are prerequisites; no submission route is supplied.',
1392
- };
1393
- }
1394
- if (!Number.isSafeInteger(input.authorityCommentId) ||
1395
- !Number.isSafeInteger(input.acceptanceCommentId) ||
1396
- input.authorityCommentId <= 0 ||
1397
- input.acceptanceCommentId <= 0)
1398
- throw new DeliveryError('Investigation evidence requires positive native comment IDs.');
1399
- return withInvestigationExclusion(root, preparation.row.path, () => completeInvestigationCustody({
1400
- preparation,
1401
- result,
1402
- authorityCommentId: input.authorityCommentId,
1403
- acceptanceCommentId: input.acceptanceCommentId,
1404
- dryRun: input.dryRun === true,
1405
- authorize,
1406
- assertSource: (allowAbsent) => assertInvestigationSource(preparation, context.root, allowAbsent),
1407
- removeSource: () => removeInvestigationSource(preparation, context.root),
1408
- }));
1369
+ } catch (error) {
1370
+ if ("dryRun" in result) throw error;
1371
+ throw new ReviewSubmissionError(
1372
+ error instanceof DeliveryError ? error.message : "Post-submission status is unavailable.",
1373
+ {
1374
+ artifactId: result.artifact.artifactId,
1375
+ repository: result.repository,
1376
+ headSha: result.headSha,
1377
+ prNumber: result.prNumber,
1378
+ githubReviewId: result.githubReviewId,
1379
+ githubReviewUrl: result.githubReviewUrl
1380
+ }
1381
+ );
1382
+ }
1409
1383
  }
1410
- //# sourceMappingURL=pr.js.map
1384
+ export {
1385
+ hasDeliveryMergeTrailer,
1386
+ hasDeliveryPrMarker,
1387
+ listPrs,
1388
+ prChecks,
1389
+ prInfo,
1390
+ preflightReviewRoute,
1391
+ publishPr,
1392
+ queueChecks,
1393
+ readPrBoardFacts,
1394
+ startIssueBranch,
1395
+ submitFormalReview
1396
+ };
1397
+ //# sourceMappingURL=pr.js.map