@aviaratech/ai-delivery 0.3.34 → 0.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -477
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
package/dist/issue.js CHANGED
@@ -1,712 +1,830 @@
1
- import { types } from 'node:util';
2
- import { z } from 'zod';
3
- import { loadDeliveryConfig, WipLimits } from './config/deliveryConfig.js';
4
- import { digestValue } from './delivery/legacy.js';
5
- import { DeliveryError, getRateLimitDiagnostics, getMachineRequestDiagnostics, } from './errors.js';
6
- import { createDeliveryGitHubClients } from './github/client.js';
7
- import { NATIVE_ISSUE_API_VERSION, applyNativeIssueDates, prepareNativeIssueDates, parseConfiguredNativeIssueMetadata, clearConfiguredNativeIssuePoints, getConfiguredNativeIssueMetadata, nativeIssueSettingsFromDeliveryConfig, setConfiguredNativeIssueMetadata, } from './github/nativeIssueMetadata.js';
8
- import { getIssueProjectStatus, getProjectDeliveryConfiguration, projectSettingsFromDeliveryConfig, syncIssueProjectStatus, } from './github/projectDelivery.js';
9
- import { getNativeBlockerRelationships, hasNativeSubIssues, linkBlockedBy, replaceBlockedBy, replaceParentIssue, resolveNativeRelationshipTargets, } from './github/relationships.js';
10
- import { prepareBlockerGuard, OverrideReason } from './services/blockerGuardService.js';
11
- import {} from './github/repo.js';
12
- import { evaluateAgentReadiness } from './services/agentReadinessService.js';
13
- import { JournalInputSchema, renderJournal } from './issueJournal.js';
14
- import { IssueFields, IssueWriteFields, CreateIssueStatus, IssueStatusPatch, requireIssueStatus, parseIssueBody, requireIssue, renderIssueBody, issueWarnings, issueBodyDiff, issueStartFooter, validateIssue, IssueValidationError, requireDeferralPatch, } from './issueContract.js';
15
- // Matches GitHub's first-party JavaScript comment-length validation:
16
- // https://github.com/github/gh-aw/blob/3ead8042c7b1edc2128ba1b28b1b80d00b7f4c22/actions/setup/js/comment_limit_helpers.cjs
17
- export const ISSUE_COMMENT_BODY_LIMIT = 65_536;
1
+ import { types } from "node:util";
2
+ import { z } from "zod";
3
+ import { loadDeliveryConfig, WipLimits } from "./config/deliveryConfig.js";
4
+ import { digestValue } from "./delivery/legacy.js";
5
+ import {
6
+ CollectionLimitError,
7
+ DeliveryError,
8
+ getRateLimitDiagnostics,
9
+ getMachineRequestDiagnostics,
10
+ setMachineRequestDiagnostics
11
+ } from "./errors.js";
12
+ import { createDeliveryGitHubClients } from "./github/client.js";
13
+ import {
14
+ NATIVE_ISSUE_API_VERSION,
15
+ applyNativeIssueDates,
16
+ prepareNativeIssueDates,
17
+ parseConfiguredNativeIssueMetadata,
18
+ clearConfiguredNativeIssuePoints,
19
+ getConfiguredNativeIssueMetadata,
20
+ nativeIssueSettingsFromDeliveryConfig,
21
+ setConfiguredNativeIssueMetadata
22
+ } from "./github/nativeIssueMetadata.js";
23
+ import {
24
+ getArchivedIssueProjectStatus,
25
+ getIssueProjectStatus,
26
+ assertIssueProjectWritable,
27
+ getProjectDeliveryConfiguration,
28
+ projectSettingsFromDeliveryConfig,
29
+ syncIssueProjectStatus,
30
+ readBackProjectItem
31
+ } from "./github/projectDelivery.js";
32
+ import {
33
+ getNativeBlockerRelationships,
34
+ hasNativeSubIssues,
35
+ linkBlockedBy,
36
+ replaceBlockedBy,
37
+ replaceParentIssue,
38
+ resolveNativeRelationshipTargets
39
+ } from "./github/relationships.js";
40
+ import { prepareBlockerGuard, OverrideReason } from "./services/blockerGuardService.js";
41
+ import {} from "./github/repo.js";
42
+ import { evaluateAgentReadiness } from "./services/agentReadinessService.js";
43
+ import { JournalInputSchema, renderJournal } from "./issueJournal.js";
44
+ import {
45
+ IssueFields,
46
+ IssueWriteFields,
47
+ CreateIssueStatus,
48
+ IssueStatusPatch,
49
+ ProjectStatusPatch,
50
+ ISSUE_COMMENT_BODY_LIMIT,
51
+ requireIssueStatus,
52
+ parseIssueBody,
53
+ requireIssue,
54
+ renderIssueBody,
55
+ issueWarnings,
56
+ issueBodyDiff,
57
+ issueTrackingFooter,
58
+ validateIssue,
59
+ IssueValidationError,
60
+ requireDeferralPatch
61
+ } from "./issueContract.js";
62
+ import { ISSUE_COMMENT_BODY_LIMIT as ISSUE_COMMENT_BODY_LIMIT2 } from "./issueContract.js";
18
63
  const RawIssueCommentSchema = z.strictObject({ issueNumber: z.number().int().positive(), body: z.string() });
19
- /** One canonical exact-body operation shared by direct calls, MCP, and lifecycle journals. */
20
- export async function commentIssue(context, input, lifecycleKey) {
21
- return writeAuthenticatedIssueComment(context, input, lifecycleKey);
64
+ async function commentIssue(context, input, lifecycleKey) {
65
+ return writeAuthenticatedIssueComment(context, input, lifecycleKey);
22
66
  }
23
67
  async function writeAuthenticatedIssueComment(context, input, lifecycleKey, rawMarker) {
24
- const accepted = 'body' in input ? RawIssueCommentSchema.parse(input) : JournalInputSchema.parse(input);
25
- const rawBody = 'body' in accepted ? accepted.body : undefined;
26
- if (rawBody !== undefined && lifecycleKey !== undefined)
27
- throw new DeliveryError('Raw issue comments do not accept a lifecycle journal key.');
28
- const marker = rawBody === undefined
29
- ? `<!-- ai-delivery:journal@1:${digestValue({ issueNumber: accepted.issueNumber, key: lifecycleKey ?? accepted })} -->`
30
- : rawMarker;
31
- const body = rawBody ?? renderJournal(accepted, marker);
32
- if (body.length > ISSUE_COMMENT_BODY_LIMIT || !body.trim())
33
- throw new DeliveryError(`Issue comment body must contain text and fit ${String(ISSUE_COMMENT_BODY_LIMIT)} UTF-16 code units.`);
34
- if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor)
35
- throw new DeliveryError('Issue comments require the authenticated author role.');
36
- const actor = (await context.clients.authenticatedAuthor()).actorLogin;
37
- if (!actor)
38
- throw new DeliveryError('Issue comment author identity is missing.');
39
- const operation = async () => {
40
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;
41
- if ('pull_request' in issue || issue.number !== input.issueNumber)
42
- throw new DeliveryError('Issue comment target is not the requested issue.');
43
- const matches = [];
44
- for (let page = 1; page <= 20; page += 1) {
45
- const batch = (await context.clients.rest.issues.listComments({
46
- ...context.repo,
47
- issue_number: input.issueNumber,
48
- page,
49
- per_page: 100,
50
- })).data;
51
- matches.push(...batch.filter((comment) => (marker === undefined
52
- ? comment.body === body
53
- : rawMarker === undefined
54
- ? comment.body?.endsWith(marker)
55
- : comment.body?.includes(marker)) && comment.user?.login.toLowerCase() === actor.toLowerCase()));
56
- if (batch.length < 100)
57
- break;
58
- if (page === 20)
59
- throw new DeliveryError('Issue comment history exceeds the bounded readback window.');
60
- }
61
- if (matches.length > 1)
62
- throw new DeliveryError('Issue comment has duplicate authored retry matches.');
63
- const existing = matches[0];
64
- if (rawMarker !== undefined && existing && existing.body !== body)
65
- throw new DeliveryError('Issue comment conflicts with its authored operation marker.');
66
- const created = existing ??
67
- (await context.clients.rest.issues.createComment({ ...context.repo, issue_number: input.issueNumber, body }))
68
- .data;
69
- if (lifecycleKey === undefined && (existing?.body ?? body) !== body)
70
- throw new DeliveryError('Issue comment readback disagrees with the authored issue comment.');
71
- const readback = await readAuthoredIssueComment(context, input.issueNumber, created, existing?.body ?? body, actor);
72
- return { ...readback, reused: existing !== undefined };
73
- };
74
- return operation();
68
+ const accepted = "body" in input ? RawIssueCommentSchema.parse(input) : JournalInputSchema.parse(input);
69
+ const rawBody = "body" in accepted ? accepted.body : void 0;
70
+ if (rawBody !== void 0 && lifecycleKey !== void 0)
71
+ throw new DeliveryError("Raw issue comments do not accept a lifecycle journal key.");
72
+ const marker = rawBody === void 0 ? `<!-- ai-delivery:journal@1:${digestValue({ issueNumber: accepted.issueNumber, key: lifecycleKey ?? accepted })} -->` : rawMarker;
73
+ const body = rawBody ?? renderJournal(accepted, marker);
74
+ if (body.length > ISSUE_COMMENT_BODY_LIMIT || !body.trim())
75
+ throw new DeliveryError(
76
+ `Issue comment body must contain text and fit ${String(ISSUE_COMMENT_BODY_LIMIT)} UTF-16 code units.`
77
+ );
78
+ if (context.clients.role !== "author" || !context.clients.authenticatedAuthor)
79
+ throw new DeliveryError("Issue comments require the authenticated author role.");
80
+ const actor = (await context.clients.authenticatedAuthor()).actorLogin;
81
+ if (!actor) throw new DeliveryError("Issue comment author identity is missing.");
82
+ const operation = async () => {
83
+ const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;
84
+ if ("pull_request" in issue || issue.number !== input.issueNumber)
85
+ throw new DeliveryError("Issue comment target is not the requested issue.");
86
+ const matches = [];
87
+ for (let page = 1; page <= 20; page += 1) {
88
+ const batch = (await context.clients.rest.issues.listComments({
89
+ ...context.repo,
90
+ issue_number: input.issueNumber,
91
+ page,
92
+ per_page: 100
93
+ })).data;
94
+ matches.push(
95
+ ...batch.filter(
96
+ (comment) => (marker === void 0 ? comment.body === body : rawMarker === void 0 ? comment.body?.endsWith(marker) : comment.body?.includes(marker)) && comment.user?.login.toLowerCase() === actor.toLowerCase()
97
+ )
98
+ );
99
+ if (batch.length < 100) break;
100
+ if (page === 20) throw new DeliveryError("Issue comment history exceeds the bounded readback window.");
101
+ }
102
+ if (matches.length > 1) throw new DeliveryError("Issue comment has duplicate authored retry matches.");
103
+ const existing = matches[0];
104
+ if (rawMarker !== void 0 && existing && existing.body !== body)
105
+ throw new DeliveryError("Issue comment conflicts with its authored operation marker.");
106
+ const created = existing ?? (await context.clients.rest.issues.createComment({ ...context.repo, issue_number: input.issueNumber, body })).data;
107
+ if (lifecycleKey === void 0 && (existing?.body ?? body) !== body)
108
+ throw new DeliveryError("Issue comment readback disagrees with the authored issue comment.");
109
+ const readback = await readAuthoredIssueComment(context, input.issueNumber, created, existing?.body ?? body, actor);
110
+ return { ...readback, reused: existing !== void 0 };
111
+ };
112
+ return operation();
75
113
  }
76
114
  async function readAuthoredIssueComment(context, issueNumber, created, body, actor) {
77
- const readback = (await context.clients.rest.issues.getComment({ ...context.repo, comment_id: created.id })).data;
78
- const expectedIssuePath = `/repos/${context.repo.owner}/${context.repo.repo}/issues/${String(issueNumber)}`;
79
- if (!Number.isSafeInteger(readback.id) ||
80
- readback.id <= 0 ||
81
- readback.id !== created.id ||
82
- readback.html_url !== created.html_url ||
83
- readback.body !== body ||
84
- readback.user?.login.toLowerCase() !== actor.toLowerCase() ||
85
- new URL(readback.issue_url).pathname.toLowerCase() !== expectedIssuePath.toLowerCase() ||
86
- !readback.html_url.startsWith('https://'))
87
- throw new DeliveryError('Issue comment readback disagrees with the authored issue comment.');
88
- return { commentId: readback.id, url: readback.html_url, body: readback.body };
115
+ const readback = (await context.clients.rest.issues.getComment({ ...context.repo, comment_id: created.id })).data;
116
+ const expectedIssuePath = `/repos/${context.repo.owner}/${context.repo.repo}/issues/${String(issueNumber)}`;
117
+ if (!Number.isSafeInteger(readback.id) || readback.id <= 0 || readback.id !== created.id || readback.html_url !== created.html_url || readback.body !== body || readback.user?.login.toLowerCase() !== actor.toLowerCase() || new URL(readback.issue_url).pathname.toLowerCase() !== expectedIssuePath.toLowerCase() || !readback.html_url.startsWith("https://"))
118
+ throw new DeliveryError("Issue comment readback disagrees with the authored issue comment.");
119
+ return { commentId: readback.id, url: readback.html_url, body: readback.body };
89
120
  }
90
- export async function journalIssueStart(context, issueNumber) {
91
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
92
- return commentIssue(context, {
93
- issueNumber,
94
- kind: 'start',
95
- summary: `Work started on ${issue.title}.`,
96
- status: 'Started',
97
- outcome: issue.title,
98
- keyNumbers: [`Issue #${String(issueNumber)}`],
99
- evidence: [issue.html_url],
100
- nextStep: 'Implement the issue acceptance criteria and run its verification',
101
- nextDate: null,
102
- }, `start:${issue.created_at}`);
121
+ async function journalIssueStart(context, issueNumber) {
122
+ const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
123
+ return commentIssue(
124
+ context,
125
+ {
126
+ issueNumber,
127
+ kind: "start",
128
+ summary: `Work started on ${issue.title}.`,
129
+ status: "Started",
130
+ outcome: issue.title,
131
+ keyNumbers: [`Issue #${String(issueNumber)}`],
132
+ evidence: [issue.html_url],
133
+ nextStep: "Implement the issue acceptance criteria and run its verification",
134
+ nextDate: null
135
+ },
136
+ `start:${issue.created_at}`
137
+ );
103
138
  }
104
- export async function loadDeliveryContext(input) {
105
- const loaded = await loadDeliveryConfig(input.repoRoot, {
106
- ...(input.repository === undefined ? {} : { repository: input.repository }),
107
- ...(input.personalAuth === undefined ? {} : { personalAuth: input.personalAuth }),
108
- ...(input.signal === undefined ? {} : { signal: input.signal }),
109
- });
110
- const config = loaded.config;
111
- const [owner, repositoryName] = config.repository.split('/');
112
- if (!owner || !repositoryName)
113
- throw new DeliveryError('Repository must be owner/name.');
114
- const repo = { owner, repo: repositoryName };
115
- const clients = await createDeliveryGitHubClients({
116
- config,
117
- identity: input.identity,
118
- ...(input.personalAuth ? { personalAuth: { enabled: true } } : {}),
119
- role: input.role,
120
- ...(input.signal === undefined ? {} : { signal: input.signal }),
121
- });
122
- const routing = loaded.routing;
123
- const projectConfiguration = {
124
- projectId: routing.projectId,
125
- projectNumber: config.native.project.number,
126
- title: config.native.project.title,
127
- pointsFieldId: routing.pointsFieldId,
128
- priorityFieldId: routing.priorityFieldId,
129
- statusFieldId: routing.statusFieldId,
130
- statusOptionIds: routing.statusOptionIds,
131
- settings: projectSettingsFromDeliveryConfig(config),
132
- writable: true,
133
- };
134
- return { clients, config, configuration: loaded, projectConfiguration, repo, root: '' };
139
+ async function loadDeliveryContext(input) {
140
+ const loaded = await loadDeliveryConfig(input.repoRoot, {
141
+ ...input.settings === void 0 ? {} : { settings: input.settings },
142
+ ...input.env === void 0 ? {} : { env: input.env },
143
+ ...input.readPageLimit === void 0 ? {} : { readPageLimit: input.readPageLimit },
144
+ ...input.requireWritableProject === void 0 ? {} : { requireWritableProject: input.requireWritableProject },
145
+ ...input.repository === void 0 ? {} : { repository: input.repository },
146
+ ...input.personalAuth === void 0 ? {} : { personalAuth: input.personalAuth },
147
+ ...input.signal === void 0 ? {} : { signal: input.signal }
148
+ });
149
+ const config = loaded.config;
150
+ const [owner, repositoryName] = config.repository.split("/");
151
+ if (!owner || !repositoryName) throw new DeliveryError("Repository must be owner/name.");
152
+ const repo = { owner, repo: repositoryName };
153
+ const clients = await createDeliveryGitHubClients({
154
+ config,
155
+ identity: input.identity,
156
+ ...input.personalAuth ? { personalAuth: { enabled: true } } : {},
157
+ role: input.role,
158
+ ...input.env === void 0 ? {} : { env: input.env },
159
+ ...input.signal === void 0 ? {} : { signal: input.signal }
160
+ });
161
+ const routing = loaded.routing;
162
+ const projectConfiguration = {
163
+ projectId: routing.projectId,
164
+ projectNumber: config.native.project.number,
165
+ title: config.native.project.title,
166
+ pointsFieldId: routing.pointsFieldId,
167
+ priorityFieldId: routing.priorityFieldId,
168
+ statusFieldId: routing.statusFieldId,
169
+ statusOptionIds: routing.statusOptionIds,
170
+ ...routing.reviewOptionId ? { reviewOptionId: routing.reviewOptionId } : {},
171
+ settings: projectSettingsFromDeliveryConfig(config),
172
+ writable: true
173
+ };
174
+ return {
175
+ clients,
176
+ ...input.env === void 0 ? {} : { credentialEnvironment: input.env },
177
+ config,
178
+ configuration: loaded,
179
+ ...input.requireWritableProject === false ? {} : { projectConfiguration },
180
+ repo,
181
+ root: "",
182
+ ...input.readPageLimit === void 0 ? {} : { readPageLimit: input.readPageLimit }
183
+ };
135
184
  }
136
185
  async function labels(context, input) {
137
- const selected = input ?? [];
138
- if (selected.some((label) => !label.trim()) ||
139
- new Set(selected.map((label) => label.toLowerCase())).size !== selected.length)
140
- throw new DeliveryError('Issue labels must be non-empty and unique.');
141
- if (selected.length === 0)
142
- return [];
143
- const available = new Set();
144
- for (let page = 1; page <= 100; page++) {
145
- const batch = (await context.clients.rest.issues.listLabelsForRepo({ ...context.repo, page, per_page: 100 })).data;
146
- for (const label of batch)
147
- available.add(label.name.toLowerCase());
148
- if (batch.length < 100) {
149
- const missing = selected.filter((label) => !available.has(label.toLowerCase()));
150
- if (missing.length)
151
- throw new DeliveryError(`Unknown repository label(s): ${missing.join(', ')}.`);
152
- return [...selected];
153
- }
186
+ const selected = input ?? [];
187
+ if (selected.some((label) => !label.trim()) || new Set(selected.map((label) => label.toLowerCase())).size !== selected.length)
188
+ throw new DeliveryError("Issue labels must be non-empty and unique.");
189
+ if (selected.length === 0) return [];
190
+ const available = /* @__PURE__ */ new Set();
191
+ for (let page = 1; page <= 100; page++) {
192
+ if (context.readPageLimit !== void 0 && page > context.readPageLimit)
193
+ throw new CollectionLimitError({
194
+ collection: "repository-labels",
195
+ pagesRequested: page - 1,
196
+ rowsObserved: available.size,
197
+ limit: context.readPageLimit
198
+ });
199
+ const batch = (await context.clients.rest.issues.listLabelsForRepo({ ...context.repo, page, per_page: 100 })).data;
200
+ for (const label of batch) available.add(label.name.toLowerCase());
201
+ if (batch.length < 100) {
202
+ const missing = selected.filter((label) => !available.has(label.toLowerCase()));
203
+ if (missing.length) throw new DeliveryError(`Unknown repository label(s): ${missing.join(", ")}.`);
204
+ return [...selected];
154
205
  }
155
- throw new DeliveryError('Repository label listing exceeds the bounded readback window.');
206
+ }
207
+ throw new DeliveryError("Repository label listing exceeds the bounded readback window.");
156
208
  }
157
209
  function prepareIssueWrite(input, current, forIntent = false) {
158
- const patch = input.status === undefined
159
- ? undefined
160
- : requireIssueStatus(IssueStatusPatch, current === undefined ? requireIssueStatus(CreateIssueStatus, input.status) : input.status);
161
- if (input.blockedBy !== undefined && patch && 'blockers' in patch)
162
- throw new DeliveryError('Choose native blockedBy or display-only status.blockers in one update, not both.');
163
- const statusOnly = patch !== undefined &&
164
- Object.entries(input).every(([key, value]) => value === undefined || ['repo', 'issueNumber', 'status'].includes(key));
165
- const title = input.title ?? current?.title ?? '';
166
- const source = input.body ?? current?.body;
167
- const prior = current?.body ?? source;
168
- const currentParsed = current === undefined
169
- ? undefined
170
- : parseIssueBody(current.body, {
171
- title: current.title,
172
- ...(current.points === undefined ? {} : { points: current.points }),
173
- ...(current.issueType === null ? {} : { issueType: current.issueType }),
174
- });
175
- const currentLegacy = currentParsed?.legacy === true;
176
- if (statusOnly && currentLegacy)
177
- throw new DeliveryError('Convert the legacy contract explicitly before a status-only update.');
178
- const points = statusOnly ? currentParsed?.issue.points : (input.points ?? current?.points);
179
- const issueType = statusOnly ? currentParsed?.issue.issueType : (input.issueType ?? current?.issueType ?? undefined);
180
- const metadata = {
181
- title: input.body === undefined && current ? current.title : title,
182
- ...(points === undefined ? {} : { points }),
183
- ...(issueType === undefined ? {} : { issueType }),
184
- };
185
- const parsed = source === undefined ? { issue: IssueFields.parse({ title }), legacy: false } : parseIssueBody(source, metadata);
186
- let legacyBody = currentParsed?.issue.legacyBody ?? parsed.issue.legacyBody;
187
- if (parsed.issue.legacyBody !== undefined &&
188
- legacyBody !== undefined &&
189
- !legacyBody.includes(parsed.issue.legacyBody))
190
- legacyBody += '\n\n' + parsed.issue.legacyBody;
191
- const incomingLegacy = current !== undefined &&
192
- parsed.issue.legacyBody !== undefined &&
193
- parsed.issue.legacyBody !== currentParsed?.issue.legacyBody &&
194
- parsed.issue.legacyBody !== current.body;
195
- const fields = Object.fromEntries(Object.keys(IssueWriteFields).flatMap((key) => {
196
- const value = input[key];
197
- return value === undefined ? [] : [[key, value]];
198
- }));
199
- const issue = requireIssue({
200
- ...parsed.issue,
201
- // Body replacements and unrelated typed patches cannot implicitly resume deferred work.
202
- deferral: input.undefer === true
203
- ? undefined
204
- : (input.defer ?? (current === undefined ? parsed.issue.deferral : currentParsed?.issue.deferral)),
205
- ...metadata,
206
- ...fields,
207
- title,
208
- ...(legacyBody === undefined ? {} : { legacyBody }),
209
- ...(input.retainLegacyBody !== undefined
210
- ? { retainLegacyBody: input.retainLegacyBody }
211
- : incomingLegacy
212
- ? { retainLegacyBody: true }
213
- : current !== undefined && legacyBody !== undefined && input.preserveHistory !== false && !statusOnly
214
- ? { retainLegacyBody: false }
215
- : {}),
216
- ...(input.park ? { draft: true } : {}),
217
- });
218
- const unchangedContract = currentParsed !== undefined && JSON.stringify(issue) === JSON.stringify(currentParsed.issue);
219
- const legacyFormatting = unchangedContract && parsed.legacyFormatting === true;
220
- const base = parsed.status ?? currentParsed?.status;
221
- const proposed = {
222
- state: issue.draft ? 'Draft' : 'Ready',
223
- lastUpdated: base?.lastUpdated ?? new Date(Date.now()).toISOString(),
224
- nextMilestone: patch?.nextMilestone ?? base?.nextMilestone ?? 'Not started',
225
- blockers: patch?.blockers ?? base?.blockers ?? 'None',
226
- latestJournal: patch?.latestJournal ?? base?.latestJournal ?? 'None yet',
227
- ...(input.blockedBy === undefined
228
- ? {}
229
- : {
230
- blockers: input.blockedBy.length ? input.blockedBy.map((number) => '#' + String(number)).join(', ') : 'None',
231
- }),
232
- };
233
- const unchangedDisplay = currentParsed?.status !== undefined &&
234
- ['state', 'nextMilestone', 'blockers', 'latestJournal'].every((key) => proposed[key] === currentParsed.status[key]);
235
- const displayChanged = JSON.stringify(proposed) !== JSON.stringify(base);
236
- const status = forIntent
237
- ? undefined
238
- : current === undefined
239
- ? {
240
- ...proposed,
241
- state: issue.draft ? 'Draft' : 'Ready',
242
- lastUpdated: new Date(Date.now()).toISOString(),
243
- blockers: input.blockedBy?.length ? input.blockedBy.map((number) => '#' + String(number)).join(', ') : 'None',
244
- latestJournal: 'None yet',
245
- }
246
- : unchangedContract && unchangedDisplay
247
- ? currentParsed?.status
248
- : !unchangedContract ||
249
- (patch !== undefined && displayChanged) ||
250
- (input.blockedBy !== undefined && displayChanged)
251
- ? {
252
- ...proposed,
253
- lastUpdated: new Date(Date.now()).toISOString(),
254
- }
255
- : base;
256
- const body = renderIssueBody(issue, status, forIntent ? false : legacyFormatting) +
257
- (source === undefined || parsed.legacy ? '' : issueStartFooter(source));
258
- return {
259
- issue,
260
- body,
261
- statusOnly,
262
- preserveHistory: input.preserveHistory ??
263
- ((currentLegacy ||
264
- parsed.legacy ||
265
- (legacyBody !== undefined &&
266
- issue.retainLegacyBody === false &&
267
- currentParsed?.issue.retainLegacyBody !== false)) &&
268
- !statusOnly),
269
- warnings: issueWarnings(issue, status, legacyFormatting),
270
- ...((currentLegacy || parsed.legacy) && prior !== undefined
271
- ? { conversion: { priorBody: prior, canonicalBody: body, diff: issueBodyDiff(prior, body) } }
272
- : {}),
273
- };
210
+ const patch = input.status === void 0 ? void 0 : requireIssueStatus(
211
+ IssueStatusPatch,
212
+ current === void 0 ? requireIssueStatus(CreateIssueStatus, input.status) : input.status
213
+ );
214
+ if (input.blockedBy !== void 0 && patch && "blockers" in patch)
215
+ throw new DeliveryError("Choose native blockedBy or display-only status.blockers in one update, not both.");
216
+ const statusOnly = patch !== void 0 && Object.entries(input).every(
217
+ ([key, value]) => value === void 0 || ["repo", "issueNumber", "status", "projectStatus"].includes(key)
218
+ );
219
+ const title = input.title ?? current?.title ?? "";
220
+ const source = input.body ?? current?.body;
221
+ const prior = current?.body ?? source;
222
+ const currentParsed = current === void 0 ? void 0 : parseIssueBody(current.body, {
223
+ title: current.title,
224
+ ...current.points === void 0 ? {} : { points: current.points },
225
+ ...current.issueType === null ? {} : { issueType: current.issueType }
226
+ });
227
+ const currentLegacy = currentParsed?.legacy === true;
228
+ if (statusOnly && currentLegacy)
229
+ throw new DeliveryError("Convert the legacy contract explicitly before a status-only update.");
230
+ const points = statusOnly ? currentParsed?.issue.points : input.points ?? current?.points;
231
+ const issueType = statusOnly ? currentParsed?.issue.issueType : input.issueType ?? current?.issueType ?? void 0;
232
+ const metadata = {
233
+ title: input.body === void 0 && current ? current.title : title,
234
+ ...points === void 0 ? {} : { points },
235
+ ...issueType === void 0 ? {} : { issueType }
236
+ };
237
+ const parsed = source === void 0 ? { issue: IssueFields.parse({ title }), legacy: false } : parseIssueBody(source, metadata);
238
+ let legacyBody = currentParsed?.issue.legacyBody ?? parsed.issue.legacyBody;
239
+ if (parsed.issue.legacyBody !== void 0 && legacyBody !== void 0 && !legacyBody.includes(parsed.issue.legacyBody))
240
+ legacyBody += "\n\n" + parsed.issue.legacyBody;
241
+ const incomingLegacy = current !== void 0 && parsed.issue.legacyBody !== void 0 && parsed.issue.legacyBody !== currentParsed?.issue.legacyBody && parsed.issue.legacyBody !== current.body;
242
+ const fields = Object.fromEntries(
243
+ Object.keys(IssueWriteFields).flatMap((key) => {
244
+ const value = input[key];
245
+ return value === void 0 ? [] : [[key, value]];
246
+ })
247
+ );
248
+ const issue = requireIssue({
249
+ ...parsed.issue,
250
+ // Body replacements and unrelated typed patches cannot implicitly resume deferred work.
251
+ deferral: input.undefer === true ? void 0 : input.defer ?? (current === void 0 ? parsed.issue.deferral : currentParsed?.issue.deferral),
252
+ ...metadata,
253
+ ...fields,
254
+ title,
255
+ ...legacyBody === void 0 ? {} : { legacyBody },
256
+ ...input.retainLegacyBody !== void 0 ? { retainLegacyBody: input.retainLegacyBody } : incomingLegacy ? { retainLegacyBody: true } : current !== void 0 && legacyBody !== void 0 && input.preserveHistory !== false && !statusOnly ? { retainLegacyBody: false } : {},
257
+ ...input.park ? { draft: true } : {}
258
+ });
259
+ const unchangedContract = currentParsed !== void 0 && JSON.stringify(issue) === JSON.stringify(currentParsed.issue);
260
+ const legacyFormatting = unchangedContract && parsed.legacyFormatting === true;
261
+ const base = parsed.status ?? currentParsed?.status;
262
+ const proposed = {
263
+ state: issue.draft ? "Draft" : "Ready",
264
+ lastUpdated: base?.lastUpdated ?? new Date(Date.now()).toISOString(),
265
+ nextMilestone: patch?.nextMilestone ?? base?.nextMilestone ?? "Not started",
266
+ blockers: patch?.blockers ?? base?.blockers ?? "None",
267
+ latestJournal: patch?.latestJournal ?? base?.latestJournal ?? "None yet",
268
+ ...input.blockedBy === void 0 ? {} : {
269
+ blockers: input.blockedBy.length ? input.blockedBy.map((number) => "#" + String(number)).join(", ") : "None"
270
+ }
271
+ };
272
+ const unchangedDisplay = currentParsed?.status !== void 0 && ["state", "nextMilestone", "blockers", "latestJournal"].every(
273
+ (key) => proposed[key] === currentParsed.status[key]
274
+ );
275
+ const displayChanged = JSON.stringify(proposed) !== JSON.stringify(base);
276
+ const status = forIntent ? void 0 : current === void 0 ? {
277
+ ...proposed,
278
+ state: issue.draft ? "Draft" : "Ready",
279
+ lastUpdated: new Date(Date.now()).toISOString(),
280
+ blockers: input.blockedBy?.length ? input.blockedBy.map((number) => "#" + String(number)).join(", ") : "None",
281
+ latestJournal: "None yet"
282
+ } : unchangedContract && unchangedDisplay ? currentParsed?.status : !unchangedContract || patch !== void 0 && displayChanged || input.blockedBy !== void 0 && displayChanged ? {
283
+ ...proposed,
284
+ lastUpdated: new Date(Date.now()).toISOString()
285
+ } : base;
286
+ const body = renderIssueBody(issue, status, forIntent ? false : legacyFormatting) + (source === void 0 || parsed.legacy ? "" : issueTrackingFooter(source));
287
+ return {
288
+ issue,
289
+ body,
290
+ statusOnly,
291
+ preserveHistory: input.preserveHistory ?? ((currentLegacy || parsed.legacy || legacyBody !== void 0 && issue.retainLegacyBody === false && currentParsed?.issue.retainLegacyBody !== false) && !statusOnly),
292
+ warnings: issueWarnings(issue, status, legacyFormatting),
293
+ ...(currentLegacy || parsed.legacy) && prior !== void 0 ? { conversion: { priorBody: prior, canonicalBody: body, diff: issueBodyDiff(prior, body) } } : {}
294
+ };
274
295
  }
275
- /** Display timestamps are excluded from the contract-bound normal-start retry intent. */
276
- export function canonicalIssueBody(input) {
277
- return prepareIssueWrite(input, undefined, true).body;
296
+ function canonicalIssueBody(input) {
297
+ return prepareIssueWrite(input, void 0, true).body;
278
298
  }
279
- export class CreatedTrackingIssueError extends DeliveryError {
280
- created;
281
- constructor(created, cause) {
282
- super(`Issue #${created.number} was created but native tracking did not complete: ${String(cause)}. Resume this known issue; do not create another.`);
283
- this.created = created;
284
- }
299
+ class CreatedTrackingIssueError extends DeliveryError {
300
+ constructor(created, cause, failedStep, remainingSteps, opId) {
301
+ super(
302
+ `Issue #${created.number} was created but native tracking did not complete: ${String(cause)}. ${failedStep === void 0 ? "" : `Failed step: ${failedStep}. Remaining steps: ${remainingSteps?.join(", ")}. `}${opId === void 0 ? "Resume this known issue; do not create another." : "Repeat issue_create with the same opId and original arguments to finish this known issue."}`
303
+ );
304
+ this.created = created;
305
+ this.failedStep = failedStep;
306
+ this.remainingSteps = remainingSteps;
307
+ this.opId = opId;
308
+ }
309
+ created;
310
+ failedStep;
311
+ remainingSteps;
312
+ opId;
285
313
  }
286
- export async function createIssue(context, input) {
287
- if (context.clients.role !== 'author')
288
- throw new DeliveryError('Issue writes require the configured author role.');
289
- const prepared = prepareIssueWrite(input);
290
- const dateChanges = await prepareIssueDates(context, input);
291
- input = {
292
- ...input,
293
- title: prepared.issue.title,
294
- body: prepared.body,
295
- ...(prepared.issue.issueType === undefined ? {} : { issueType: prepared.issue.issueType }),
296
- ...(prepared.issue.points === undefined ? {} : { points: prepared.issue.points }),
297
- };
298
- if (!input.title.trim())
299
- throw new DeliveryError('Issue title is required.');
300
- if (input.issueType !== undefined && !context.config.native.issueTypes.includes(input.issueType)) {
301
- throw new DeliveryError('Unsupported configured Issue Type.');
302
- }
303
- if (input.points !== undefined && !context.config.native.points.values.includes(String(input.points))) {
304
- throw new DeliveryError('Unsupported configured Points value.');
305
- }
306
- if (input.priority !== undefined && !context.config.native.priority.values.includes(input.priority)) {
307
- throw new DeliveryError('Unsupported configured Priority value.');
314
+ async function createIssue(context, input) {
315
+ if (context.clients.role !== "author") throw new DeliveryError("Issue writes require the configured author role.");
316
+ const canonicalBody = canonicalIssueBody(input);
317
+ const prepared = prepareIssueWrite(input);
318
+ const originalIntent = digestValue(
319
+ Object.fromEntries(
320
+ Object.entries({ ...input, opId: void 0, body: canonicalBody }).filter(([, value]) => value !== void 0)
321
+ )
322
+ );
323
+ const dateChanges = await prepareIssueDates(context, input);
324
+ input = {
325
+ ...input,
326
+ title: prepared.issue.title,
327
+ body: prepared.body,
328
+ ...prepared.issue.issueType === void 0 ? {} : { issueType: prepared.issue.issueType },
329
+ ...prepared.issue.points === void 0 ? {} : { points: prepared.issue.points }
330
+ };
331
+ if (!input.title.trim()) throw new DeliveryError("Issue title is required.");
332
+ if (input.issueType !== void 0 && !context.config.native.issueTypes.includes(input.issueType)) {
333
+ throw new DeliveryError("Unsupported configured Issue Type.");
334
+ }
335
+ if (input.points !== void 0 && !context.config.native.points.values.includes(String(input.points))) {
336
+ throw new DeliveryError("Unsupported configured Points value.");
337
+ }
338
+ if (input.priority !== void 0 && !context.config.native.priority.values.includes(input.priority)) {
339
+ throw new DeliveryError("Unsupported configured Priority value.");
340
+ }
341
+ const { clients, config, repo } = context;
342
+ const targets = await resolveNativeRelationshipTargets({
343
+ blockers: input.blockedBy ?? [],
344
+ ...input.parentIssueNumber === void 0 ? {} : { parentIssueNumber: input.parentIssueNumber },
345
+ repo,
346
+ rest: clients.rest
347
+ });
348
+ const beforeAdd = (input.blocks?.length ?? 0) > 0 || (input.blockedBy?.length ?? 0) > 0 ? await prepareBlockerGuard(
349
+ context,
350
+ (input.blocks ?? []).map((dependent) => ({ dependent, blockers: [], pendingBlocker: true })),
351
+ input.overrideReason,
352
+ input.blockedBy ?? []
353
+ ) : async () => {
354
+ };
355
+ let prior;
356
+ if (input.opId !== void 0) {
357
+ const opId = z.string().trim().min(1).max(256).parse(input.opId);
358
+ const actor = (await clients.authenticatedAuthor?.())?.actorLogin;
359
+ if (!actor) throw new DeliveryError("Create retry requires authenticated author identity.");
360
+ const key = digestValue({ repository: config.repository.toLowerCase(), actor: actor.toLowerCase(), opId });
361
+ const marker = `<!-- ai-delivery-create: ${key} intent: ${originalIntent} -->`;
362
+ const matches = [];
363
+ for (let page = 1; page <= Math.min(20, context.readPageLimit ?? 20); page++) {
364
+ const batch = (await clients.rest.issues.listForRepo({ ...repo, state: "all", page, per_page: 100 })).data;
365
+ matches.push(
366
+ ...batch.filter(
367
+ (row) => !("pull_request" in row) && row.body?.includes(`<!-- ai-delivery-create: ${key} intent:`)
368
+ )
369
+ );
370
+ if (batch.length < 100) break;
371
+ if (page === Math.min(20, context.readPageLimit ?? 20))
372
+ throw new DeliveryError("Create retry search exceeds the bounded readback window; reconcile the known issue.");
308
373
  }
309
- const { clients, config, repo } = context;
310
- const targets = await resolveNativeRelationshipTargets({
311
- blockers: input.blockedBy ?? [],
312
- ...(input.parentIssueNumber === undefined ? {} : { parentIssueNumber: input.parentIssueNumber }),
313
- repo,
374
+ if (matches.length > 1) throw new DeliveryError("Conflicting issues claim the same create opId.");
375
+ prior = matches[0];
376
+ if (prior) {
377
+ const footer = issueTrackingFooter(prior.body ?? "");
378
+ if (prior.user?.login.toLowerCase() !== actor.toLowerCase() || prior.state !== "open" || prior.title !== input.title || footer !== `
379
+
380
+ ${marker}` || canonicalIssueBody({ title: prior.title, body: (prior.body ?? "").slice(0, -footer.length) }) !== canonicalBody)
381
+ throw new DeliveryError("Prior create opId conflicts with its author, original intent or current issue state.");
382
+ input.body = prior.body ?? "";
383
+ } else input.body = `${input.body}
384
+
385
+ ${marker}`;
386
+ }
387
+ const created = prior ? { data: prior } : await clients.rest.issues.create({
388
+ body: input.body ?? "",
389
+ labels: await labels(context, input.labels),
390
+ ...input.milestone === void 0 ? {} : { milestone: input.milestone },
391
+ owner: repo.owner,
392
+ repo: repo.repo,
393
+ title: input.title,
394
+ ...input.issueType === void 0 ? {} : { type: input.issueType }
395
+ });
396
+ const issueNumber = created.data.number;
397
+ const steps = [
398
+ "created-readback",
399
+ ...input.points !== void 0 || input.priority !== void 0 ? ["metadata"] : [],
400
+ ...dateChanges.length ? ["dates"] : [],
401
+ "project",
402
+ ...input.parentIssueNumber !== void 0 ? ["parent", "parent-points"] : [],
403
+ ...(input.blockedBy?.length ?? 0) > 0 ? ["blockers"] : [],
404
+ ...(input.blocks?.length ?? 0) > 0 ? ["dependents"] : [],
405
+ "readback"
406
+ ];
407
+ let step = steps[0];
408
+ try {
409
+ if (created.data.title !== input.title || (created.data.body ?? "") !== input.body || !Number.isSafeInteger(issueNumber) || issueNumber <= 0 || new URL(created.data.html_url).pathname.toLowerCase() !== `/${repo.owner}/${repo.repo}/issues/${String(issueNumber)}`.toLowerCase())
410
+ throw new DeliveryError(
411
+ "Created issue content or repository identity readback disagrees; reconcile this existing issue before retrying."
412
+ );
413
+ const existing = prior === void 0 ? void 0 : await issueInfo(context, issueNumber);
414
+ const existingRelationships = prior === void 0 ? void 0 : await getNativeBlockerRelationships({ graphql: clients.graphql, issueNumber, repo });
415
+ if (existing && (existing.projectStatus === "In Progress" || existing.projectStatus === "Done" || input.points !== void 0 && existing.points !== void 0 && existing.points !== input.points || input.priority !== void 0 && existing.priority !== void 0 && existing.priority !== input.priority || dateChanges.some(
416
+ (change) => existing.fields[change.name] != null && existing.fields[change.name] !== change.value
417
+ ) || existing.parentIssueNumber !== null && existing.parentIssueNumber !== (input.parentIssueNumber ?? null) || existingRelationships.blockers.some((blocker) => !(input.blockedBy ?? []).includes(blocker.number))))
418
+ throw new DeliveryError("Prior create opId conflicts with later native tracking changes.");
419
+ step = "metadata";
420
+ if (input.points !== void 0 && existing?.points !== input.points || input.priority !== void 0 && existing?.priority !== input.priority)
421
+ await setConfiguredNativeIssueMetadata({
422
+ issueNumber,
423
+ metadata: {
424
+ ...input.points === void 0 ? {} : { points: input.points },
425
+ ...input.priority === void 0 ? {} : { priority: input.priority }
426
+ },
427
+ org: config.native.organization,
428
+ owner: repo.owner,
429
+ repo: repo.repo,
314
430
  rest: clients.rest,
431
+ settings: nativeIssueSettingsFromDeliveryConfig(config)
432
+ });
433
+ step = "dates";
434
+ await applyNativeIssueDates({
435
+ changes: dateChanges.filter(
436
+ (change) => existing === void 0 || (existing.fields[change.name] ?? null) !== change.value
437
+ ),
438
+ issueNumber,
439
+ ...repo,
440
+ rest: clients.rest
315
441
  });
316
- const beforeAdd = (input.blocks?.length ?? 0) > 0 || (input.blockedBy?.length ?? 0) > 0
317
- ? await prepareBlockerGuard(context, (input.blocks ?? []).map((dependent) => ({ dependent, blockers: [], pendingBlocker: true })), input.overrideReason, input.blockedBy ?? [])
318
- : async () => { };
319
- const created = await clients.rest.issues.create({
320
- body: input.body ?? '',
321
- labels: await labels(context, input.labels),
322
- ...(input.milestone === undefined ? {} : { milestone: input.milestone }),
442
+ step = "project";
443
+ if (existing?.projectStatus !== (targets.unresolvedBlockers.length > 0 ? "Blocked" : "Todo"))
444
+ await syncIssueProjectStatus({
445
+ graphql: clients.graphql,
446
+ issueNodeId: created.data.node_id,
447
+ org: config.native.organization,
448
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
449
+ settings: projectSettingsFromDeliveryConfig(config),
450
+ status: targets.unresolvedBlockers.length > 0 ? "Blocked" : "Todo"
451
+ });
452
+ step = "parent";
453
+ if (input.parentIssueNumber !== void 0)
454
+ await replaceParentIssue({
455
+ graphql: clients.graphql,
456
+ issueNumber,
457
+ parentIssueNumber: input.parentIssueNumber,
458
+ repo,
459
+ rest: clients.rest
460
+ });
461
+ step = "parent-points";
462
+ if (input.parentIssueNumber !== void 0)
463
+ await clearConfiguredNativeIssuePoints({
464
+ issueNumber: input.parentIssueNumber,
465
+ org: config.native.organization,
323
466
  owner: repo.owner,
324
467
  repo: repo.repo,
325
- title: input.title,
326
- ...(input.issueType === undefined ? {} : { type: input.issueType }),
327
- });
328
- const issueNumber = created.data.number;
329
- try {
330
- if (created.data.title !== input.title ||
331
- (created.data.body ?? '') !== input.body ||
332
- !Number.isSafeInteger(issueNumber) ||
333
- issueNumber <= 0 ||
334
- new URL(created.data.html_url).pathname.toLowerCase() !==
335
- `/${repo.owner}/${repo.repo}/issues/${String(issueNumber)}`.toLowerCase())
336
- throw new DeliveryError('Created issue content or repository identity readback disagrees; reconcile this existing issue before retrying.');
337
- if (input.points !== undefined || input.priority !== undefined)
338
- await setConfiguredNativeIssueMetadata({
339
- issueNumber,
340
- metadata: {
341
- ...(input.points === undefined ? {} : { points: input.points }),
342
- ...(input.priority === undefined ? {} : { priority: input.priority }),
343
- },
344
- org: config.native.organization,
345
- owner: repo.owner,
346
- repo: repo.repo,
347
- rest: clients.rest,
348
- settings: nativeIssueSettingsFromDeliveryConfig(config),
349
- });
350
- await applyNativeIssueDates({ changes: dateChanges, issueNumber, ...repo, rest: clients.rest });
351
- if (input.parentIssueNumber !== undefined)
352
- await replaceParentIssue({
353
- graphql: clients.graphql,
354
- issueNumber,
355
- parentIssueNumber: input.parentIssueNumber,
356
- repo,
357
- rest: clients.rest,
358
- });
359
- if (input.parentIssueNumber !== undefined)
360
- await clearConfiguredNativeIssuePoints({
361
- issueNumber: input.parentIssueNumber,
362
- org: config.native.organization,
363
- owner: repo.owner,
364
- repo: repo.repo,
365
- rest: clients.rest,
366
- settings: nativeIssueSettingsFromDeliveryConfig(config),
367
- });
368
- await syncIssueProjectStatus({
369
- graphql: clients.graphql,
370
- issueNodeId: created.data.node_id,
371
- org: config.native.organization,
372
- ...(context.projectConfiguration ? { configuration: context.projectConfiguration } : {}),
373
- settings: projectSettingsFromDeliveryConfig(config),
374
- status: targets.unresolvedBlockers.length > 0 ? 'Blocked' : 'Todo',
375
- });
376
- if ((input.blockedBy?.length ?? 0) > 0)
377
- await replaceBlockedBy({
378
- beforeAdd,
379
- blockers: input.blockedBy ?? [],
380
- graphql: clients.graphql,
381
- issueNumber,
382
- repo,
383
- rest: clients.rest,
384
- });
385
- for (const dependent of new Set(input.blocks ?? []))
386
- await linkBlockedBy({
387
- beforeAdd,
388
- blockers: [issueNumber],
389
- graphql: clients.graphql,
390
- issueNumber: dependent,
391
- repo,
392
- rest: clients.rest,
393
- });
394
- const readback = await issueInfo(context, issueNumber);
395
- if (readback.title !== input.title ||
396
- readback.body !== input.body ||
397
- (input.points !== undefined && readback.points !== input.points) ||
398
- (input.issueType !== undefined && readback.issueType !== input.issueType))
399
- throw new DeliveryError('Created issue native content or metadata readback disagrees; resume this known issue.');
400
- }
401
- catch (error) {
402
- throw new CreatedTrackingIssueError({ number: issueNumber, title: created.data.title, url: created.data.html_url }, error);
403
- }
404
- return {
405
- ...(context.configuration ? { routing: context.configuration.routing } : {}),
406
- body: created.data.body ?? input.body ?? '',
407
- created: { number: issueNumber, title: created.data.title, url: created.data.html_url },
408
- warnings: prepared.warnings,
409
- };
468
+ rest: clients.rest,
469
+ settings: nativeIssueSettingsFromDeliveryConfig(config)
470
+ });
471
+ step = "blockers";
472
+ if ((input.blockedBy?.length ?? 0) > 0)
473
+ await replaceBlockedBy({
474
+ beforeAdd,
475
+ blockers: input.blockedBy ?? [],
476
+ graphql: clients.graphql,
477
+ issueNumber,
478
+ repo,
479
+ rest: clients.rest
480
+ });
481
+ step = "dependents";
482
+ for (const dependent of new Set(input.blocks ?? []))
483
+ await linkBlockedBy({
484
+ beforeAdd,
485
+ blockers: [issueNumber],
486
+ graphql: clients.graphql,
487
+ issueNumber: dependent,
488
+ repo,
489
+ rest: clients.rest
490
+ });
491
+ step = "readback";
492
+ const readback = await issueInfo(context, issueNumber);
493
+ if (readback.title !== input.title || readback.body !== input.body || input.points !== void 0 && readback.points !== input.points || input.issueType !== void 0 && readback.issueType !== input.issueType)
494
+ throw new DeliveryError("Created issue native content or metadata readback disagrees; resume this known issue.");
495
+ } catch (error) {
496
+ throw new CreatedTrackingIssueError(
497
+ { number: issueNumber, title: created.data.title, url: created.data.html_url },
498
+ error,
499
+ step,
500
+ steps.slice(steps.indexOf(step)),
501
+ input.opId
502
+ );
503
+ }
504
+ return {
505
+ ...context.configuration ? { routing: context.configuration.routing } : {},
506
+ body: created.data.body ?? input.body ?? "",
507
+ created: { number: issueNumber, title: created.data.title, url: created.data.html_url },
508
+ warnings: prepared.warnings
509
+ };
410
510
  }
411
511
  const FieldCatalogEntry = z.object({
412
- id: z.number().int().positive().safe(),
413
- name: z.string().min(1),
414
- data_type: z.enum(['text', 'number', 'date', 'single_select', 'multi_select']),
512
+ id: z.number().int().positive().safe(),
513
+ name: z.string().min(1),
514
+ data_type: z.enum(["text", "number", "date", "single_select", "multi_select"])
415
515
  });
416
516
  const FieldValueEntry = z.object({
417
- issue_field_id: z.number().int().positive().safe(),
418
- issue_field_name: z.string().min(1),
419
- data_type: FieldCatalogEntry.shape.data_type,
420
- value: z.unknown().optional(),
421
- single_select_option: z
422
- .object({ name: z.string().min(1) })
423
- .nullable()
424
- .optional(),
425
- multi_select_options: z.array(z.object({ name: z.string().min(1) })).optional(),
517
+ issue_field_id: z.number().int().positive().safe(),
518
+ issue_field_name: z.string().min(1),
519
+ data_type: FieldCatalogEntry.shape.data_type,
520
+ value: z.unknown().optional(),
521
+ single_select_option: z.object({ name: z.string().min(1) }).nullable().optional(),
522
+ multi_select_options: z.array(z.object({ name: z.string().min(1) })).optional()
426
523
  });
427
524
  const ListedIssue = z.object({
428
- number: z.number().int().positive().safe(),
429
- node_id: z.string().min(1),
430
- title: z.string(),
431
- body: z.string().nullable().optional(),
432
- state: z.enum(['open', 'closed']),
433
- labels: z.array(z.union([z.string(), z.object({ name: z.string() })])),
434
- type: z.object({ name: z.string() }).nullable().optional(),
435
- html_url: z.url(),
436
- updated_at: z.iso.datetime({ offset: true }),
525
+ number: z.number().int().positive().safe(),
526
+ node_id: z.string().min(1),
527
+ title: z.string(),
528
+ body: z.string().nullable().optional(),
529
+ state: z.enum(["open", "closed"]),
530
+ labels: z.array(z.union([z.string(), z.object({ name: z.string() })])),
531
+ type: z.object({ name: z.string() }).nullable().optional(),
532
+ html_url: z.url(),
533
+ updated_at: z.iso.datetime({ offset: true })
437
534
  });
438
535
  function capacityNextPage(response, page, perPage) {
439
- if (!Array.isArray(response.data) || response.data.length > perPage)
440
- throw new DeliveryError('WIP capacity pagination returned invalid native data.');
441
- const link = response.headers?.link;
442
- if (link === undefined || link === '')
443
- return response.data.length === perPage ? page + 1 : null;
444
- const parts = [...link.matchAll(/<([^>]+)>;\s*rel="([^"]+)"/gu)];
445
- const next = parts.filter((part) => part[2] === 'next');
446
- const residue = link.replace(/<([^>]+)>;\s*rel="([^"]+)"/gu, '').replace(/[,\s]/gu, '');
447
- if (!parts.length ||
448
- residue ||
449
- next.length > 1 ||
450
- parts.some((part) => !['first', 'prev', 'next', 'last'].includes(part[2])))
451
- throw new DeliveryError('WIP capacity native pagination is malformed.');
452
- if (!next.length)
453
- return null;
454
- const url = new URL(next[0][1]);
455
- if (url.protocol !== 'https:' ||
456
- url.hostname !== 'api.github.com' ||
457
- url.searchParams.get('page') !== String(page + 1) ||
458
- url.searchParams.get('per_page') !== String(perPage))
459
- throw new DeliveryError('WIP capacity native pagination did not advance consistently.');
460
- return page + 1;
536
+ if (!Array.isArray(response.data) || response.data.length > perPage)
537
+ throw new DeliveryError("WIP capacity pagination returned invalid native data.");
538
+ const link = response.headers?.link;
539
+ if (link === void 0 || link === "") return response.data.length === perPage ? page + 1 : null;
540
+ const parts = [...link.matchAll(/<([^>]+)>;\s*rel="([^"]+)"/gu)];
541
+ const next = parts.filter((part) => part[2] === "next");
542
+ const residue = link.replace(/<([^>]+)>;\s*rel="([^"]+)"/gu, "").replace(/[,\s]/gu, "");
543
+ if (!parts.length || residue || next.length > 1 || parts.some((part) => !["first", "prev", "next", "last"].includes(part[2])))
544
+ throw new DeliveryError("WIP capacity native pagination is malformed.");
545
+ if (!next.length) return null;
546
+ const url = new URL(next[0][1]);
547
+ if (url.protocol !== "https:" || url.hostname !== "api.github.com" || url.searchParams.get("page") !== String(page + 1) || url.searchParams.get("per_page") !== String(perPage))
548
+ throw new DeliveryError("WIP capacity native pagination did not advance consistently.");
549
+ return page + 1;
550
+ }
551
+ function nativeReadNextPage(response, page, path) {
552
+ if (!Array.isArray(response.data) || response.data.length > 100)
553
+ throw new DeliveryError("Parent progress native pagination returned invalid page data.");
554
+ const link = response.headers?.link;
555
+ if (link === void 0 || link === "") return response.data.length === 100 ? page + 1 : null;
556
+ if (typeof link !== "string") throw new DeliveryError("Parent progress native pagination is malformed.");
557
+ const parts = [...link.matchAll(/<([^>]+)>;\s*rel="([^"]+)"/gu)];
558
+ const residue = link.replace(/<([^>]+)>;\s*rel="([^"]+)"/gu, "").replace(/[,\s]/gu, "");
559
+ const next = parts.filter((part) => part[2] === "next");
560
+ if (!parts.length || residue || new Set(parts.map((part) => part[2])).size !== parts.length || parts.some((part) => !["first", "prev", "next", "last"].includes(part[2])))
561
+ throw new DeliveryError("Parent progress native pagination is malformed.");
562
+ for (const part of parts) {
563
+ let url;
564
+ try {
565
+ url = new URL(part[1]);
566
+ } catch {
567
+ throw new DeliveryError("Parent progress native pagination URL is malformed.");
568
+ }
569
+ if (url.protocol !== "https:" || url.hostname !== "api.github.com" || url.port || url.username || url.password || url.hash || url.pathname.toLowerCase() !== path.toLowerCase() || url.searchParams.getAll("page").length !== 1 || url.searchParams.getAll("per_page").length !== 1 || [...url.searchParams.keys()].some((key) => !["page", "per_page"].includes(key)) || !/^[1-9]\d*$/u.test(url.searchParams.get("page") ?? "") || url.searchParams.get("per_page") !== "100")
570
+ throw new DeliveryError("Parent progress native pagination changed repository, endpoint or page scope.");
571
+ const declaredPage = Number(url.searchParams.get("page"));
572
+ const afterLast = response.data.length === 0 && declaredPage === page - 1 && !next.length;
573
+ if (!Number.isSafeInteger(declaredPage) || part[2] === "next" && declaredPage !== page + 1 || part[2] === "prev" && declaredPage !== page - 1 || part[2] === "first" && declaredPage !== 1 || part[2] === "last" && !afterLast && (declaredPage < page || declaredPage > page !== next.length > 0))
574
+ throw new DeliveryError("Parent progress native pagination did not advance consistently.");
575
+ }
576
+ if (next.length && response.data.length === 0)
577
+ throw new DeliveryError("Parent progress native pagination claims continuation after an empty page.");
578
+ return next.length ? page + 1 : null;
461
579
  }
462
- async function issueFieldPages(context, route, parameters, maxPages) {
463
- const values = [];
464
- const seenPages = new Set();
465
- for (let page = 1;; page += 1) {
466
- if (maxPages !== undefined && page > maxPages)
467
- throw new DeliveryError('WIP capacity native field pagination is incomplete.');
468
- const response = await context.clients.rest.request(route, {
469
- ...parameters,
470
- headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
471
- page,
472
- per_page: 100,
580
+ async function issueFieldPages(context, route, parameters, maxPages, strictRead = false) {
581
+ const values = [];
582
+ const seenPages = /* @__PURE__ */ new Set();
583
+ for (let page = 1; ; page += 1) {
584
+ if (maxPages !== void 0 && page > maxPages) {
585
+ if (context.readPageLimit !== void 0)
586
+ throw new CollectionLimitError({
587
+ collection: route.includes("/orgs/") ? "native-field-catalog" : "native-field-values",
588
+ pagesRequested: page - 1,
589
+ rowsObserved: values.length,
590
+ limit: maxPages
473
591
  });
474
- if (!Array.isArray(response.data))
475
- throw new DeliveryError('GitHub returned invalid native issue fields.');
476
- const fingerprint = digestValue(response.data);
477
- if (response.data.length > 0 && seenPages.has(fingerprint))
478
- throw new DeliveryError('Native issue fields repeated a pagination page.');
479
- seenPages.add(fingerprint);
480
- values.push(...response.data);
481
- if (maxPages === undefined ? response.data.length < 100 : capacityNextPage(response, page, 100) === null)
482
- return values;
592
+ throw new DeliveryError("WIP capacity native field pagination is incomplete.");
483
593
  }
594
+ const response = await context.clients.rest.request(route, {
595
+ ...parameters,
596
+ headers: { "X-GitHub-Api-Version": NATIVE_ISSUE_API_VERSION },
597
+ page,
598
+ per_page: 100
599
+ });
600
+ if (!Array.isArray(response.data)) throw new DeliveryError("GitHub returned invalid native issue fields.");
601
+ const fingerprint = digestValue(response.data);
602
+ if (response.data.length > 0 && seenPages.has(fingerprint))
603
+ throw new DeliveryError("Native issue fields repeated a pagination page.");
604
+ seenPages.add(fingerprint);
605
+ values.push(...response.data);
606
+ const next = strictRead ? nativeReadNextPage(
607
+ response,
608
+ page,
609
+ route.slice(4).replace(/\{([^}]+)\}/gu, (_match, key) => encodeURIComponent(String(parameters[key])))
610
+ ) : maxPages === void 0 ? response.data.length < 100 ? null : page + 1 : capacityNextPage(response, page, 100);
611
+ if (next === null) return values;
612
+ }
484
613
  }
485
- async function readIssueFieldCatalog(context, capacityRead = false) {
486
- const catalog = z
487
- .array(FieldCatalogEntry)
488
- .parse(await issueFieldPages(context, 'GET /orgs/{org}/issue-fields', { org: context.config.native.organization }, capacityRead ? 20 : undefined));
489
- if (new Set(catalog.map((field) => field.name)).size !== catalog.length ||
490
- new Set(catalog.map((field) => field.id)).size !== catalog.length)
491
- throw new DeliveryError('Native issue field catalog has duplicate identities or names.');
492
- return catalog;
614
+ async function readIssueFieldCatalog(context, capacityRead = false, strictRead = false) {
615
+ const catalog = z.array(FieldCatalogEntry).parse(
616
+ await issueFieldPages(
617
+ context,
618
+ "GET /orgs/{org}/issue-fields",
619
+ { org: context.config.native.organization },
620
+ capacityRead ? Math.min(context.readPageLimit ?? 20, 20) : context.readPageLimit,
621
+ strictRead
622
+ )
623
+ );
624
+ if (new Set(catalog.map((field) => field.name)).size !== catalog.length || new Set(catalog.map((field) => field.id)).size !== catalog.length)
625
+ throw new DeliveryError("Native issue field catalog has duplicate identities or names.");
626
+ return catalog;
493
627
  }
494
- async function readIssueFields(context, issueNumber, catalog, capacityRead = false) {
495
- const fields = Object.fromEntries(catalog.map((field) => [field.name, null]));
496
- const values = z.array(FieldValueEntry).parse(await issueFieldPages(context, 'GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {
628
+ async function readIssueFields(context, issueNumber, catalog, capacityRead = false, strictRead = false) {
629
+ const fields = Object.fromEntries(catalog.map((field) => [field.name, null]));
630
+ const values = z.array(FieldValueEntry).parse(
631
+ await issueFieldPages(
632
+ context,
633
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values",
634
+ {
497
635
  ...context.repo,
498
- issue_number: issueNumber,
499
- }, capacityRead ? 20 : undefined));
500
- const observed = new Set();
501
- for (const field of values) {
502
- const definition = catalog.find((candidate) => candidate.id === field.issue_field_id);
503
- if (!definition ||
504
- definition.name !== field.issue_field_name ||
505
- definition.data_type !== field.data_type ||
506
- observed.has(field.issue_field_id))
507
- throw new DeliveryError('Native issue field readback conflicts with its catalog.');
508
- observed.add(field.issue_field_id);
509
- if (capacityRead &&
510
- (field.data_type === 'single_select'
511
- ? field.single_select_option === undefined && field.value !== null
512
- : field.data_type === 'multi_select'
513
- ? field.multi_select_options === undefined && field.value !== null
514
- : field.value === undefined))
515
- throw new DeliveryError('WIP capacity native field value payload is missing.');
516
- // Existing issue-info metadata accepts configured option names as raw values.
517
- // Preserve that exact compatibility without treating numeric option IDs as names.
518
- const configuredOptionName = !capacityRead &&
519
- field.data_type === 'single_select' &&
520
- typeof field.value === 'string' &&
521
- ((field.issue_field_name === context.config.native.points.name &&
522
- String(field.issue_field_id) === context.config.native.points.databaseId &&
523
- context.config.native.points.values.includes(field.value)) ||
524
- (field.issue_field_name === context.config.native.priority.name &&
525
- String(field.issue_field_id) === context.config.native.priority.databaseId &&
526
- context.config.native.priority.values.includes(field.value)))
527
- ? field.value
528
- : undefined;
529
- if (((field.data_type === 'single_select' && !field.single_select_option && configuredOptionName === undefined) ||
530
- (field.data_type === 'multi_select' && field.multi_select_options === undefined)) &&
531
- field.value !== null &&
532
- field.value !== undefined)
533
- throw new DeliveryError('Native select field omitted its named option readback.');
534
- const value = field.data_type === 'single_select'
535
- ? (field.single_select_option?.name ?? configuredOptionName ?? null)
536
- : field.data_type === 'multi_select'
537
- ? field.multi_select_options?.map((option) => option.name)
538
- : field.value;
539
- if (field.data_type === 'date' && value !== null && value !== undefined && !z.iso.date().safeParse(value).success)
540
- throw new DeliveryError('Native date field has an invalid date value.');
541
- if (value === null || value === undefined)
542
- fields[definition.name] = null;
543
- else if (field.data_type === 'number'
544
- ? typeof value === 'number' && Number.isFinite(value)
545
- : field.data_type === 'multi_select'
546
- ? Array.isArray(value)
547
- : typeof value === 'string')
548
- fields[definition.name] = value;
549
- else
550
- throw new DeliveryError('Native issue field has an invalid value type.');
551
- }
552
- return { fields, values, catalog };
636
+ issue_number: issueNumber
637
+ },
638
+ capacityRead ? Math.min(context.readPageLimit ?? 20, 20) : context.readPageLimit,
639
+ strictRead
640
+ )
641
+ );
642
+ const observed = /* @__PURE__ */ new Set();
643
+ for (const field of values) {
644
+ const definition = catalog.find((candidate) => candidate.id === field.issue_field_id);
645
+ if (!definition || definition.name !== field.issue_field_name || definition.data_type !== field.data_type || observed.has(field.issue_field_id))
646
+ throw new DeliveryError("Native issue field readback conflicts with its catalog.");
647
+ observed.add(field.issue_field_id);
648
+ if (capacityRead && (field.data_type === "single_select" ? field.single_select_option === void 0 && field.value !== null : field.data_type === "multi_select" ? field.multi_select_options === void 0 && field.value !== null : field.value === void 0))
649
+ throw new DeliveryError("WIP capacity native field value payload is missing.");
650
+ const configuredOptionName = !capacityRead && field.data_type === "single_select" && typeof field.value === "string" && (field.issue_field_name === context.config.native.points.name && String(field.issue_field_id) === context.config.native.points.databaseId && context.config.native.points.values.includes(field.value) || field.issue_field_name === context.config.native.priority.name && String(field.issue_field_id) === context.config.native.priority.databaseId && context.config.native.priority.values.includes(field.value)) ? field.value : void 0;
651
+ if (strictRead && (field.data_type === "single_select" ? field.single_select_option == null && configuredOptionName === void 0 && field.value !== null : field.data_type === "multi_select" ? field.multi_select_options === void 0 && field.value !== null : field.value === void 0))
652
+ throw new DeliveryError("Parent progress native field value payload is missing or malformed.");
653
+ if ((field.data_type === "single_select" && !field.single_select_option && configuredOptionName === void 0 || field.data_type === "multi_select" && field.multi_select_options === void 0) && field.value !== null && field.value !== void 0)
654
+ throw new DeliveryError("Native select field omitted its named option readback.");
655
+ const value = field.data_type === "single_select" ? field.single_select_option?.name ?? configuredOptionName ?? null : field.data_type === "multi_select" ? field.multi_select_options?.map((option) => option.name) : field.value;
656
+ if (field.data_type === "date" && value !== null && value !== void 0 && !z.iso.date().safeParse(value).success)
657
+ throw new DeliveryError("Native date field has an invalid date value.");
658
+ if (value === null || value === void 0) fields[definition.name] = null;
659
+ else if (field.data_type === "number" ? typeof value === "number" && Number.isFinite(value) : field.data_type === "multi_select" ? Array.isArray(value) : typeof value === "string")
660
+ fields[definition.name] = value;
661
+ else throw new DeliveryError("Native issue field has an invalid value type.");
662
+ }
663
+ return { fields, values, catalog };
664
+ }
665
+ async function readIssueNativeFields(context, issueNumber, strictRead = false) {
666
+ return readIssueFields(
667
+ context,
668
+ issueNumber,
669
+ await readIssueFieldCatalog(context, false, strictRead),
670
+ false,
671
+ strictRead
672
+ );
553
673
  }
554
674
  async function prepareIssueDates(context, patch) {
555
- if (patch.startDate === undefined && patch.targetDate === undefined)
556
- return [];
557
- return prepareNativeIssueDates(patch, await readIssueFieldCatalog(context));
675
+ if (patch.startDate === void 0 && patch.targetDate === void 0) return [];
676
+ return prepareNativeIssueDates(patch, await readIssueFieldCatalog(context));
558
677
  }
559
- /** A bounded GitHub page; local filters can produce an empty page with a nextPage. */
560
- export async function listIssues(context, input, options = {}) {
561
- const page = input.page ?? 1;
562
- const perPage = input.perPage ?? 30;
563
- if (!Number.isSafeInteger(page) || page <= 0 || !Number.isSafeInteger(perPage) || perPage <= 0 || perPage > 100)
564
- throw new DeliveryError('Issue pagination must use a positive page and perPage from 1 to 100.');
565
- if (input.query !== undefined && (!input.query.trim() || input.query.length > 256 || /["\\\r\n]/u.test(input.query)))
566
- throw new DeliveryError('Issue search requires literal text without quotes, backslashes or newlines.');
567
- if (input.labels?.some((label) => !label || /["\\\r\n]/u.test(label)))
568
- throw new DeliveryError('Issue filter labels must be nonempty literal names.');
569
- if (input.updatedSince !== undefined && !z.iso.datetime({ offset: true }).safeParse(input.updatedSince).success)
570
- throw new DeliveryError('updatedSince must be an ISO timestamp.');
571
- let raw;
572
- let nextPage;
573
- if (input.query !== undefined) {
574
- const q = [
575
- `repo:${context.repo.owner}/${context.repo.repo}`,
576
- 'is:issue',
577
- JSON.stringify(input.query.trim()),
578
- ...(input.state === undefined || input.state === 'all' ? [] : [`is:${input.state}`]),
579
- ...(input.labels ?? []).map((label) => `label:${JSON.stringify(label)}`),
580
- ...(input.updatedSince === undefined ? [] : [`updated:>=${input.updatedSince}`]),
581
- ].join(' ');
582
- const response = (await context.clients.rest.search.issuesAndPullRequests({
583
- q,
584
- page,
585
- per_page: perPage,
586
- sort: 'updated',
587
- order: 'desc',
588
- headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
589
- })).data;
590
- if (response.incomplete_results)
591
- throw new DeliveryError('GitHub issue search returned incomplete results; narrow the query.');
592
- if (response.total_count > 1000)
593
- throw new DeliveryError('GitHub issue search exceeds its 1000-result window; narrow the query.');
594
- raw = response.items;
595
- nextPage = page * perPage < response.total_count ? page + 1 : null;
596
- }
597
- else {
598
- const response = await context.clients.rest.issues.listForRepo({
599
- ...context.repo,
600
- state: input.state ?? 'open',
601
- ...(input.labels === undefined ? {} : { labels: input.labels.join(',') }),
602
- ...(input.updatedSince === undefined ? {} : { since: input.updatedSince }),
603
- page,
604
- per_page: perPage,
605
- sort: 'updated',
606
- direction: 'desc',
607
- headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
608
- });
609
- raw = response.data;
610
- nextPage = options.capacityRead
611
- ? capacityNextPage(response, page, perPage)
612
- : raw.length === perPage
613
- ? page + 1
614
- : null;
615
- }
616
- const catalog = await readIssueFieldCatalog(context, options.capacityRead);
617
- const issues = [];
618
- const seen = new Set();
619
- for (const entry of raw) {
620
- if (typeof entry === 'object' && entry !== null && 'pull_request' in entry)
621
- continue;
622
- const current = ListedIssue.parse(entry);
623
- if (seen.has(current.number))
624
- throw new DeliveryError('GitHub issue page repeats an issue.');
625
- seen.add(current.number);
626
- if (new URL(current.html_url).pathname.toLowerCase() !==
627
- `/${context.repo.owner}/${context.repo.repo}/issues/${String(current.number)}`.toLowerCase())
628
- throw new DeliveryError('GitHub issue list returned a foreign repository issue.');
629
- const selectedLabels = current.labels.map((label) => (typeof label === 'string' ? label : label.name));
630
- if (options.capacityRead) {
631
- const url = new URL(current.html_url);
632
- if (url.protocol !== 'https:' || url.hostname !== 'github.com')
633
- throw new DeliveryError('WIP capacity issue URL is not the selected GitHub repository.');
634
- const native = (await context.clients.rest.issues.get({ ...context.repo, issue_number: current.number })).data;
635
- if ('pull_request' in native ||
636
- native.number !== current.number ||
637
- native.node_id !== current.node_id ||
638
- native.html_url !== current.html_url ||
639
- native.state !== current.state)
640
- throw new DeliveryError('WIP capacity issue identity or state changed during native readback.');
641
- }
642
- if (input.state !== undefined && input.state !== 'all' && current.state !== input.state)
643
- continue;
644
- if ((input.labels ?? []).some((label) => !selectedLabels.some((selected) => selected.toLowerCase() === label.toLowerCase())))
645
- continue;
646
- if (input.issueType !== undefined && current.type?.name !== input.issueType)
647
- continue;
648
- if (input.updatedSince !== undefined && Date.parse(current.updated_at) < Date.parse(input.updatedSince))
649
- continue;
650
- const relationships = await getNativeBlockerRelationships({
651
- graphql: context.clients.graphql,
652
- issueNumber: current.number,
653
- repo: context.repo,
654
- requireRepositoryIdentity: true,
655
- });
656
- const localParent = relationships.parentRepository?.toLowerCase() === `${context.repo.owner}/${context.repo.repo}`.toLowerCase()
657
- ? relationships.parentNumber
658
- : null;
659
- if (input.parentIssueNumber !== undefined &&
660
- (input.parentIssueNumber === null ? relationships.parentNumber !== null : localParent !== input.parentIssueNumber))
661
- continue;
662
- const project = await getIssueProjectStatus({
663
- graphql: context.clients.graphql,
664
- issueNodeId: current.node_id,
665
- ...(options.capacityRead ? { capacityRead: true, maxPages: 20 } : {}),
666
- org: context.config.native.organization,
667
- ...(context.projectConfiguration ? { configuration: context.projectConfiguration } : {}),
668
- settings: projectSettingsFromDeliveryConfig(context.config),
669
- });
670
- if (input.projectStatus !== undefined && (project?.status ?? null) !== input.projectStatus)
671
- continue;
672
- const { fields } = await readIssueFields(context, current.number, catalog, options.capacityRead);
673
- issues.push({
674
- ...(options.capacityRead
675
- ? { nodeId: current.node_id, fieldIds: Object.fromEntries(catalog.map((field) => [field.name, field.id])) }
676
- : {}),
677
- ...deferralReadback(current.body, current.title),
678
- number: current.number,
679
- title: current.title,
680
- state: current.state,
681
- labels: selectedLabels,
682
- issueType: current.type?.name ?? null,
683
- parentIssueNumber: localParent,
684
- parent: relationships.parentNumber === null
685
- ? null
686
- : { repository: relationships.parentRepository, number: relationships.parentNumber },
687
- blockers: relationships.blockers.map(({ number, title, state, repository }) => ({
688
- repository: repository,
689
- number,
690
- title,
691
- state,
692
- })),
693
- projectStatus: project?.status ?? null,
694
- fields,
695
- url: current.html_url,
696
- updatedAt: current.updated_at,
697
- });
678
+ async function listIssues(context, input, options = {}) {
679
+ const page = input.page ?? 1;
680
+ const perPage = input.perPage ?? 30;
681
+ if (!Number.isSafeInteger(page) || page <= 0 || !Number.isSafeInteger(perPage) || perPage <= 0 || perPage > 100)
682
+ throw new DeliveryError("Issue pagination must use a positive page and perPage from 1 to 100.");
683
+ if (input.query !== void 0 && (!input.query.trim() || input.query.length > 256 || /["\\\r\n]/u.test(input.query)))
684
+ throw new DeliveryError("Issue search requires literal text without quotes, backslashes or newlines.");
685
+ if (input.labels?.some((label) => !label || /["\\\r\n]/u.test(label)))
686
+ throw new DeliveryError("Issue filter labels must be nonempty literal names.");
687
+ if (input.updatedSince !== void 0 && !z.iso.datetime({ offset: true }).safeParse(input.updatedSince).success)
688
+ throw new DeliveryError("updatedSince must be an ISO timestamp.");
689
+ let raw;
690
+ let nextPage;
691
+ if (input.query !== void 0) {
692
+ const q = [
693
+ `repo:${context.repo.owner}/${context.repo.repo}`,
694
+ "is:issue",
695
+ JSON.stringify(input.query.trim()),
696
+ ...input.state === void 0 || input.state === "all" ? [] : [`is:${input.state}`],
697
+ ...(input.labels ?? []).map((label) => `label:${JSON.stringify(label)}`),
698
+ ...input.updatedSince === void 0 ? [] : [`updated:>=${input.updatedSince}`]
699
+ ].join(" ");
700
+ const response = (await context.clients.rest.search.issuesAndPullRequests({
701
+ q,
702
+ page,
703
+ per_page: perPage,
704
+ sort: "updated",
705
+ order: "desc",
706
+ headers: { "X-GitHub-Api-Version": NATIVE_ISSUE_API_VERSION }
707
+ })).data;
708
+ if (response.incomplete_results)
709
+ throw new DeliveryError("GitHub issue search returned incomplete results; narrow the query.");
710
+ if (response.total_count > 1e3)
711
+ throw new DeliveryError("GitHub issue search exceeds its 1000-result window; narrow the query.");
712
+ raw = response.items;
713
+ nextPage = page * perPage < response.total_count ? page + 1 : null;
714
+ } else {
715
+ const response = await context.clients.rest.issues.listForRepo({
716
+ ...context.repo,
717
+ state: input.state ?? "open",
718
+ ...input.labels === void 0 ? {} : { labels: input.labels.join(",") },
719
+ ...input.updatedSince === void 0 ? {} : { since: input.updatedSince },
720
+ page,
721
+ per_page: perPage,
722
+ sort: "updated",
723
+ direction: "desc",
724
+ headers: { "X-GitHub-Api-Version": NATIVE_ISSUE_API_VERSION }
725
+ });
726
+ raw = response.data;
727
+ nextPage = options.capacityRead ? capacityNextPage(response, page, perPage) : raw.length === perPage ? page + 1 : null;
728
+ }
729
+ const catalog = await readIssueFieldCatalog(context, options.capacityRead);
730
+ const seen = /* @__PURE__ */ new Set();
731
+ const entries = [];
732
+ for (const entry of raw) {
733
+ if (typeof entry === "object" && entry !== null && "pull_request" in entry) continue;
734
+ const current = ListedIssue.parse(entry);
735
+ if (seen.has(current.number)) throw new DeliveryError("GitHub issue page repeats an issue.");
736
+ seen.add(current.number);
737
+ if (new URL(current.html_url).pathname.toLowerCase() !== `/${context.repo.owner}/${context.repo.repo}/issues/${String(current.number)}`.toLowerCase())
738
+ throw new DeliveryError("GitHub issue list returned a foreign repository issue.");
739
+ entries.push({
740
+ current,
741
+ selectedLabels: current.labels.map((label) => typeof label === "string" ? label : label.name)
742
+ });
743
+ }
744
+ const rows = await mapConcurrent(entries, READ_CONCURRENCY, async ({ current, selectedLabels }) => {
745
+ if (options.capacityRead) {
746
+ const url = new URL(current.html_url);
747
+ if (url.protocol !== "https:" || url.hostname !== "github.com")
748
+ throw new DeliveryError("WIP capacity issue URL is not the selected GitHub repository.");
749
+ const native = (await context.clients.rest.issues.get({ ...context.repo, issue_number: current.number })).data;
750
+ if ("pull_request" in native || native.number !== current.number || native.node_id !== current.node_id || native.html_url !== current.html_url || native.state !== current.state)
751
+ throw new DeliveryError("WIP capacity issue identity or state changed during native readback.");
698
752
  }
699
- return { issues, page, perPage, nextPage };
753
+ if (input.state !== void 0 && input.state !== "all" && current.state !== input.state) return null;
754
+ if ((input.labels ?? []).some(
755
+ (label) => !selectedLabels.some((selected) => selected.toLowerCase() === label.toLowerCase())
756
+ ))
757
+ return null;
758
+ if (input.issueType !== void 0 && current.type?.name !== input.issueType) return null;
759
+ if (input.updatedSince !== void 0 && Date.parse(current.updated_at) < Date.parse(input.updatedSince))
760
+ return null;
761
+ const [relationships, project, { fields }] = await Promise.all([
762
+ getNativeBlockerRelationships({
763
+ graphql: context.clients.graphql,
764
+ issueNumber: current.number,
765
+ repo: context.repo,
766
+ requireRepositoryIdentity: true,
767
+ ...context.readPageLimit === void 0 ? {} : { maxPages: context.readPageLimit, issueNodeId: current.node_id }
768
+ }),
769
+ getIssueProjectStatus({
770
+ graphql: context.clients.graphql,
771
+ issueNodeId: current.node_id,
772
+ ...options.capacityRead ? { capacityRead: true, maxPages: 20 } : {},
773
+ ...context.readPageLimit === void 0 ? {} : { maxPages: Math.min(context.readPageLimit, options.capacityRead ? 20 : context.readPageLimit) },
774
+ org: context.config.native.organization,
775
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
776
+ settings: projectSettingsFromDeliveryConfig(context.config)
777
+ }),
778
+ readIssueFields(context, current.number, catalog, options.capacityRead)
779
+ ]);
780
+ const localParent = relationships.parentRepository?.toLowerCase() === `${context.repo.owner}/${context.repo.repo}`.toLowerCase() ? relationships.parentNumber : null;
781
+ if (input.parentIssueNumber !== void 0 && (input.parentIssueNumber === null ? relationships.parentNumber !== null : localParent !== input.parentIssueNumber))
782
+ return null;
783
+ if (input.projectStatus !== void 0 && (project?.status ?? null) !== input.projectStatus) return null;
784
+ const listed = {
785
+ ...options.capacityRead ? { nodeId: current.node_id, fieldIds: Object.fromEntries(catalog.map((field) => [field.name, field.id])) } : {},
786
+ ...deferralReadback(current.body, current.title),
787
+ number: current.number,
788
+ title: current.title,
789
+ state: current.state,
790
+ labels: selectedLabels,
791
+ issueType: current.type?.name ?? null,
792
+ parentIssueNumber: localParent,
793
+ parent: relationships.parentNumber === null ? null : { repository: relationships.parentRepository, number: relationships.parentNumber },
794
+ blockers: relationships.blockers.map(({ number, title, state, repository }) => ({
795
+ repository,
796
+ number,
797
+ title,
798
+ state
799
+ })),
800
+ projectStatus: project?.status ?? null,
801
+ ...project?.review ? { inReview: true } : {},
802
+ fields,
803
+ url: current.html_url,
804
+ updatedAt: current.updated_at
805
+ };
806
+ return listed;
807
+ });
808
+ const issues = rows.filter((row) => row !== null);
809
+ return { issues, page, perPage, nextPage };
700
810
  }
701
- /** @internal Render previous content as inert text without trimming or interpreting its Markdown. */
702
- export function renderIssueHistory(title, body) {
703
- const escape = (value) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
704
- return `<details>\n<summary>Previous issue title and body</summary>\n\nTitle:\n<pre>${escape(title)}</pre>\n\nBody:\n<pre>${escape(body)}</pre>\n\n</details>`;
811
+ function renderIssueHistory(title, body) {
812
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
813
+ return `<details>
814
+ <summary>Previous issue title and body</summary>
815
+
816
+ Title:
817
+ <pre>${escape(title)}</pre>
818
+
819
+ Body:
820
+ <pre>${escape(body)}</pre>
821
+
822
+ </details>`;
705
823
  }
706
- /** @internal Native closure evidence is independent of an input or a posted comment. */
707
- export async function readIssueClosure(context, issueNumber) {
708
- const Repository = z.object({ nameWithOwner: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u) });
709
- const response = await context.clients.graphql(`
824
+ async function readIssueClosure(context, issueNumber) {
825
+ const Repository = z.object({ nameWithOwner: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u) });
826
+ const response = await context.clients.graphql(
827
+ `
710
828
  query IssueClosureReadback($owner: String!, $name: String!, $number: Int!) {
711
829
  repository(owner: $owner, name: $name) {
712
830
  issue(number: $number) {
@@ -715,933 +833,1372 @@ export async function readIssueClosure(context, issueNumber) {
715
833
  }
716
834
  }
717
835
  }
718
- `, { owner: context.repo.owner, name: context.repo.repo, number: issueNumber });
719
- const parsed = z
720
- .object({
721
- repository: z.object({
722
- issue: z.object({
723
- number: z.number().int().positive().safe(),
724
- repository: Repository,
725
- state: z.enum(['OPEN', 'CLOSED']),
726
- stateReason: z.enum(['COMPLETED', 'NOT_PLANNED', 'DUPLICATE', 'REOPENED']).nullable(),
727
- duplicateOf: z.object({ number: z.number().int().positive().safe(), repository: Repository }).nullable(),
728
- }),
729
- }),
836
+ `,
837
+ { owner: context.repo.owner, name: context.repo.repo, number: issueNumber }
838
+ );
839
+ const parsed = z.object({
840
+ repository: z.object({
841
+ issue: z.object({
842
+ number: z.number().int().positive().safe(),
843
+ repository: Repository,
844
+ state: z.enum(["OPEN", "CLOSED"]),
845
+ stateReason: z.enum(["COMPLETED", "NOT_PLANNED", "DUPLICATE", "REOPENED"]).nullable(),
846
+ duplicateOf: z.object({ number: z.number().int().positive().safe(), repository: Repository }).nullable()
847
+ })
730
848
  })
731
- .parse(response).repository.issue;
732
- if (parsed.number !== issueNumber ||
733
- parsed.repository.nameWithOwner.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
734
- throw new DeliveryError('Native closure readback returned a foreign issue identity.');
735
- if ((parsed.state === 'OPEN' && parsed.stateReason !== null && parsed.stateReason !== 'REOPENED') ||
736
- (parsed.state === 'CLOSED' && parsed.stateReason === 'REOPENED') ||
737
- (parsed.duplicateOf !== null && parsed.stateReason !== 'DUPLICATE'))
738
- throw new DeliveryError('Native closure readback has contradictory state evidence.');
739
- return {
740
- state: parsed.state === 'OPEN' ? 'open' : 'closed',
741
- closeReason: parsed.stateReason === null || parsed.stateReason === 'REOPENED'
742
- ? null
743
- : parsed.stateReason.toLowerCase(),
744
- duplicateOf: parsed.duplicateOf === null
745
- ? null
746
- : { number: parsed.duplicateOf.number, repository: parsed.duplicateOf.repository.nameWithOwner },
747
- };
849
+ }).parse(response).repository.issue;
850
+ if (parsed.number !== issueNumber || parsed.repository.nameWithOwner.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
851
+ throw new DeliveryError("Native closure readback returned a foreign issue identity.");
852
+ if (parsed.state === "OPEN" && parsed.stateReason !== null && parsed.stateReason !== "REOPENED" || parsed.state === "CLOSED" && parsed.stateReason === "REOPENED" || parsed.duplicateOf !== null && parsed.stateReason !== "DUPLICATE")
853
+ throw new DeliveryError("Native closure readback has contradictory state evidence.");
854
+ return {
855
+ state: parsed.state === "OPEN" ? "open" : "closed",
856
+ closeReason: parsed.stateReason === null || parsed.stateReason === "REOPENED" ? null : parsed.stateReason.toLowerCase(),
857
+ duplicateOf: parsed.duplicateOf === null ? null : { number: parsed.duplicateOf.number, repository: parsed.duplicateOf.repository.nameWithOwner }
858
+ };
859
+ }
860
+ const incompleteUpdates = /* @__PURE__ */ new WeakMap();
861
+ class IssueUpdateIncompleteError extends DeliveryError {
862
+ constructor(result) {
863
+ super("Issue update is incomplete; reconcile native state and only remaining Project work.");
864
+ this.result = result;
865
+ incompleteUpdates.set(this, result);
866
+ }
867
+ result;
868
+ }
869
+ function getIncompleteIssueUpdate(error) {
870
+ return typeof error === "object" && error !== null ? incompleteUpdates.get(error) : void 0;
748
871
  }
749
872
  function updateProjectStatus(info, input) {
750
- return info.state === 'closed' || info.projectStatus === 'Done'
751
- ? 'Done'
752
- : info.blockedBy.length > 0
753
- ? 'Blocked'
754
- : input.park === true || input.blockedBy !== undefined || info.projectStatus === null
755
- ? 'Todo'
756
- : info.projectStatus === 'In Progress' || (info.projectStatus === 'Blocked' && input.state === undefined)
757
- ? info.projectStatus
758
- : 'Todo';
873
+ return input.projectStatus?.status ?? (info.state === "closed" || info.projectStatus === "Done" ? "Done" : info.blockedBy.length > 0 ? "Blocked" : input.park === true || input.blockedBy !== void 0 || info.projectStatus === null ? "Todo" : info.projectStatus === "In Progress" || info.projectStatus === "Blocked" && input.state === void 0 ? info.projectStatus : "Todo");
874
+ }
875
+ function projectStatusBody(input) {
876
+ return input.projectStatus === void 0 ? void 0 : `Requested Project Status: ${input.projectStatus.status}.
877
+
878
+ ${input.projectStatus.reason}`;
879
+ }
880
+ async function assertProjectTransition(context, plan, recordOverride = false, validateTransition = true) {
881
+ const request = plan.input.projectStatus;
882
+ if (request === void 0) return;
883
+ const { clients, repo } = context;
884
+ const target = (await clients.rest.issues.get({ ...repo, issue_number: plan.input.issueNumber })).data;
885
+ if (target.node_id !== plan.nativeTarget.nodeId || target.html_url !== plan.nativeTarget.url || target.number !== plan.input.issueNumber || "pull_request" in target || !["open", "closed"].includes(target.state))
886
+ throw new DeliveryError("Native Project transition target is inconsistent; reconcile the repository issue.");
887
+ const native = await getNativeBlockerRelationships({
888
+ graphql: clients.graphql,
889
+ repo,
890
+ issueNumber: plan.input.issueNumber,
891
+ requireRepositoryIdentity: true,
892
+ maxPages: context.readPageLimit ?? 20,
893
+ issueNodeId: plan.nativeTarget.nodeId
894
+ });
895
+ const repository = `${repo.owner}/${repo.repo}`.toLowerCase();
896
+ const targets = await Promise.all(
897
+ native.blockers.map(async (edge) => {
898
+ const issue = (await clients.rest.issues.get({ ...repo, issue_number: edge.number })).data;
899
+ if (edge.repository?.toLowerCase() !== repository || issue.number !== edge.number || issue.node_id !== edge.id || "pull_request" in issue || issue.html_url.toLowerCase() !== `https://github.com/${repository}/issues/${edge.number}` || issue.state.toUpperCase() !== edge.state)
900
+ throw new DeliveryError("Native blocker evidence conflicts; reconcile the repository relationships.");
901
+ return issue;
902
+ })
903
+ );
904
+ if (!validateTransition) return;
905
+ if (request.status === "Done" && target.state !== "closed")
906
+ throw new DeliveryError("An open issue cannot move to Done; close the issue through its native workflow.");
907
+ if (request.status === "Todo" && targets.some((x) => x.state === "open"))
908
+ throw new DeliveryError("Unresolved native blockers prevent Todo; resolve the blockers first.");
909
+ if (request.status === "In Progress") {
910
+ const ready = await readyCheck(context, plan.input.issueNumber);
911
+ if (!ready.ready) throw new IssueValidationError(ready.failures);
912
+ if (target.state !== "open") throw new DeliveryError("In Progress requires an open issue; inspect native state.");
913
+ await assertIssueStartCapacity(context, plan.input.issueNumber, plan.input.overrideReason, recordOverride);
914
+ const current = await issueInfo(context, plan.input.issueNumber);
915
+ if (current.state !== "open") throw new DeliveryError("In Progress requires an open issue; inspect native state.");
916
+ const finalReady = await readyCheck(context, plan.input.issueNumber);
917
+ if (!finalReady.ready) throw new IssueValidationError(finalReady.failures);
918
+ }
759
919
  }
760
920
  async function prepareIssueUpdate(context, input) {
761
- requireDeferralPatch({
762
- ...(input.defer === undefined ? {} : { defer: input.defer }),
763
- ...(input.undefer === undefined ? {} : { undefer: input.undefer }),
921
+ if (input.projectStatus !== void 0)
922
+ input = { ...input, projectStatus: ProjectStatusPatch.parse(input.projectStatus) };
923
+ const projectOnly = input.projectStatus !== void 0 && Object.entries(input).every(
924
+ ([key, value]) => value === void 0 || ["repo", "issueNumber", "projectStatus", "overrideReason"].includes(key)
925
+ );
926
+ requireDeferralPatch({
927
+ ...input.defer === void 0 ? {} : { defer: input.defer },
928
+ ...input.undefer === void 0 ? {} : { undefer: input.undefer }
929
+ });
930
+ if ("deferral" in input) throw new DeliveryError("Use defer or undefer to change deferral state.");
931
+ if (context.clients.role !== "author") throw new DeliveryError("Issue writes require the configured author role.");
932
+ if (input.closeReason !== void 0 && !["completed", "not_planned", "duplicate"].includes(input.closeReason) || (input.closeReason !== void 0 || input.supersededBy !== void 0) && input.state !== "closed")
933
+ throw new DeliveryError("Closure details require state closed and a supported close reason.");
934
+ if (input.supersededBy !== void 0 && (!Number.isSafeInteger(input.supersededBy) || input.supersededBy <= 0 || input.supersededBy === input.issueNumber))
935
+ throw new DeliveryError("A superseding issue must be a different positive issue number.");
936
+ const { clients, config, repo } = context;
937
+ const preserveArchived = Object.keys(input).every(
938
+ (key) => ["issueNumber", "title", "state", "closeReason", "supersededBy", "preserveHistory"].includes(key)
939
+ );
940
+ const dateChanges = await prepareIssueDates(context, input);
941
+ const currentContent = await issueInfo(context, input.issueNumber);
942
+ const archivedItemId = preserveArchived ? await assertIssueProjectWritable({
943
+ preserveArchived: true,
944
+ graphql: clients.graphql,
945
+ issueNodeId: (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data.node_id,
946
+ org: config.native.organization,
947
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
948
+ settings: projectSettingsFromDeliveryConfig(config)
949
+ }) : null;
950
+ const legacyNativeEdit = archivedItemId !== null && !currentContent.body.trimStart().startsWith("<!-- ai-delivery:issue@1 -->");
951
+ const prepared = legacyNativeEdit || projectOnly ? {
952
+ issue: IssueFields.parse({ title: input.title ?? currentContent.title, draft: true }),
953
+ body: currentContent.body,
954
+ statusOnly: true,
955
+ preserveHistory: input.preserveHistory ?? false,
956
+ warnings: []
957
+ } : prepareIssueWrite(input, currentContent);
958
+ input = {
959
+ ...input,
960
+ ...projectOnly ? {} : { body: prepared.body },
961
+ ...prepared.statusOnly ? {} : {
962
+ title: prepared.issue.title,
963
+ ...prepared.issue.draft ? { park: true } : {}
964
+ },
965
+ preserveHistory: prepared.preserveHistory
966
+ };
967
+ const acceptedLabels = input.labels === void 0 ? void 0 : await labels(context, input.labels);
968
+ if (input.issueType !== void 0 && !config.native.issueTypes.includes(input.issueType)) {
969
+ throw new DeliveryError("Unsupported configured Issue Type.");
970
+ }
971
+ if (input.points !== void 0 && !config.native.points.values.includes(String(input.points))) {
972
+ throw new DeliveryError("Unsupported configured Points value.");
973
+ }
974
+ if (input.priority !== void 0 && !config.native.priority.values.includes(input.priority)) {
975
+ throw new DeliveryError("Unsupported configured Priority value.");
976
+ }
977
+ if (input.parentIssueNumber !== void 0 || input.blockedBy !== void 0) {
978
+ const current = await getNativeBlockerRelationships({
979
+ graphql: clients.graphql,
980
+ issueNumber: input.issueNumber,
981
+ repo
764
982
  });
765
- if ('deferral' in input)
766
- throw new DeliveryError('Use defer or undefer to change deferral state.');
767
- if (context.clients.role !== 'author')
768
- throw new DeliveryError('Issue writes require the configured author role.');
769
- if ((input.closeReason !== undefined && !['completed', 'not_planned', 'duplicate'].includes(input.closeReason)) ||
770
- ((input.closeReason !== undefined || input.supersededBy !== undefined) && input.state !== 'closed'))
771
- throw new DeliveryError('Closure details require state closed and a supported close reason.');
772
- if (input.supersededBy !== undefined &&
773
- (!Number.isSafeInteger(input.supersededBy) || input.supersededBy <= 0 || input.supersededBy === input.issueNumber))
774
- throw new DeliveryError('A superseding issue must be a different positive issue number.');
775
- const { clients, config, repo } = context;
776
- const dateChanges = await prepareIssueDates(context, input);
777
- const currentContent = await issueInfo(context, input.issueNumber);
778
- const prepared = prepareIssueWrite(input, currentContent);
779
- input = {
780
- ...input,
781
- body: prepared.body,
782
- ...(prepared.statusOnly
783
- ? {}
784
- : {
785
- title: prepared.issue.title,
786
- ...(prepared.issue.issueType === undefined ? {} : { issueType: prepared.issue.issueType }),
787
- ...(prepared.issue.points === undefined ? {} : { points: prepared.issue.points }),
788
- ...(prepared.issue.draft ? { park: true } : {}),
789
- }),
790
- preserveHistory: prepared.preserveHistory,
791
- };
792
- const acceptedLabels = input.labels === undefined ? undefined : await labels(context, input.labels);
793
- if (input.issueType !== undefined && !config.native.issueTypes.includes(input.issueType)) {
794
- throw new DeliveryError('Unsupported configured Issue Type.');
795
- }
796
- if (input.points !== undefined && !config.native.points.values.includes(String(input.points))) {
797
- throw new DeliveryError('Unsupported configured Points value.');
798
- }
799
- if (input.priority !== undefined && !config.native.priority.values.includes(input.priority)) {
800
- throw new DeliveryError('Unsupported configured Priority value.');
801
- }
802
- if (input.parentIssueNumber !== undefined || input.blockedBy !== undefined) {
803
- const current = await getNativeBlockerRelationships({
804
- graphql: clients.graphql,
805
- issueNumber: input.issueNumber,
806
- repo,
807
- });
808
- // Tracking edges validate native endpoints without adopting their source worktrees.
809
- await resolveNativeRelationshipTargets({
810
- blockers: current.blockers.map((blocker) => blocker.number),
811
- ...(current.parentNumber === null ? {} : { parentIssueNumber: current.parentNumber }),
812
- repo,
813
- rest: clients.rest,
814
- });
815
- await resolveNativeRelationshipTargets({
816
- blockers: input.blockedBy ?? [],
817
- ...(input.parentIssueNumber === undefined || input.parentIssueNumber === null
818
- ? {}
819
- : { parentIssueNumber: input.parentIssueNumber }),
820
- repo,
821
- rest: clients.rest,
822
- });
823
- }
824
- const beforeAdd = input.blockedBy !== undefined || input.blocks !== undefined
825
- ? await prepareBlockerGuard(context, [
826
- ...(input.blockedBy === undefined ? [] : [{ dependent: input.issueNumber, blockers: input.blockedBy }]),
827
- ...(input.blocks ?? []).map((dependent) => ({ dependent, blockers: [input.issueNumber] })),
828
- ], input.overrideReason)
829
- : undefined;
830
- const closeReason = input.closeReason ?? (input.supersededBy === undefined ? undefined : 'completed');
831
- let supersedingIssueId;
832
- if (input.supersededBy !== undefined) {
833
- const target = (await clients.rest.issues.get({ ...repo, issue_number: input.supersededBy })).data;
834
- if (target.number !== input.supersededBy ||
835
- 'pull_request' in target ||
836
- !Number.isSafeInteger(target.id) ||
837
- target.id <= 0 ||
838
- new URL(target.html_url).pathname.toLowerCase() !==
839
- `/${repo.owner}/${repo.repo}/issues/${String(input.supersededBy)}`.toLowerCase())
840
- throw new DeliveryError('Superseding issue readback is not the requested repository issue.');
841
- supersedingIssueId = target.id;
842
- }
843
- const assertClosure = (closure) => {
844
- if (closure.state !== 'closed' ||
845
- closure.closeReason !== closeReason ||
846
- (closeReason === 'duplicate' &&
847
- input.supersededBy !== undefined &&
848
- (closure.duplicateOf?.number !== input.supersededBy ||
849
- closure.duplicateOf.repository.toLowerCase() !== `${repo.owner}/${repo.repo}`.toLowerCase())))
850
- throw new DeliveryError('Native closure readback disagrees with the requested reason or superseding issue.');
851
- };
852
- if (closeReason !== undefined) {
853
- const current = await readIssueClosure(context, input.issueNumber);
854
- if (current.state === 'closed') {
855
- try {
856
- assertClosure(current);
857
- }
858
- catch {
859
- throw new DeliveryError('Issue is already closed with different closure evidence; reopen it explicitly first.');
860
- }
861
- }
983
+ await resolveNativeRelationshipTargets({
984
+ blockers: current.blockers.map((blocker) => blocker.number),
985
+ ...current.parentNumber === null ? {} : { parentIssueNumber: current.parentNumber },
986
+ repo,
987
+ rest: clients.rest
988
+ });
989
+ await resolveNativeRelationshipTargets({
990
+ blockers: input.blockedBy ?? [],
991
+ ...input.parentIssueNumber === void 0 || input.parentIssueNumber === null ? {} : { parentIssueNumber: input.parentIssueNumber },
992
+ repo,
993
+ rest: clients.rest
994
+ });
995
+ }
996
+ const beforeAdd = input.blockedBy !== void 0 || input.blocks !== void 0 ? await prepareBlockerGuard(
997
+ context,
998
+ [
999
+ ...input.blockedBy === void 0 ? [] : [{ dependent: input.issueNumber, blockers: input.blockedBy }],
1000
+ ...(input.blocks ?? []).map((dependent) => ({ dependent, blockers: [input.issueNumber] }))
1001
+ ],
1002
+ input.overrideReason
1003
+ ) : void 0;
1004
+ const closeReason = input.closeReason ?? (input.supersededBy === void 0 ? void 0 : "completed");
1005
+ let supersedingIssueId;
1006
+ if (input.supersededBy !== void 0) {
1007
+ const target2 = (await clients.rest.issues.get({ ...repo, issue_number: input.supersededBy })).data;
1008
+ if (target2.number !== input.supersededBy || "pull_request" in target2 || !Number.isSafeInteger(target2.id) || target2.id <= 0 || new URL(target2.html_url).pathname.toLowerCase() !== `/${repo.owner}/${repo.repo}/issues/${String(input.supersededBy)}`.toLowerCase())
1009
+ throw new DeliveryError("Superseding issue readback is not the requested repository issue.");
1010
+ supersedingIssueId = target2.id;
1011
+ }
1012
+ const assertClosure = (closure) => {
1013
+ if (closure.state !== "closed" || closure.closeReason !== closeReason || closeReason === "duplicate" && input.supersededBy !== void 0 && (closure.duplicateOf?.number !== input.supersededBy || closure.duplicateOf.repository.toLowerCase() !== `${repo.owner}/${repo.repo}`.toLowerCase()))
1014
+ throw new DeliveryError("Native closure readback disagrees with the requested reason or superseding issue.");
1015
+ };
1016
+ if (closeReason !== void 0) {
1017
+ const current = await readIssueClosure(context, input.issueNumber);
1018
+ if (current.state === "closed") {
1019
+ try {
1020
+ assertClosure(current);
1021
+ } catch {
1022
+ throw new DeliveryError("Issue is already closed with different closure evidence; reopen it explicitly first.");
1023
+ }
862
1024
  }
863
- let historyBody;
864
- let priorContent = input.status === undefined ? undefined : { title: currentContent.title, body: currentContent.body };
865
- if (input.preserveHistory === true && (input.title !== undefined || input.body !== undefined)) {
866
- const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
867
- if (current.number !== input.issueNumber || 'pull_request' in current)
868
- throw new DeliveryError('History target is not the requested issue.');
869
- const prior = { title: current.title, body: current.body ?? '' };
870
- if (prior.title !== currentContent.title || prior.body !== currentContent.body)
871
- throw new DeliveryError('Issue content changed after preparation; retry against the current title and body.');
872
- if ((input.title !== undefined && input.title !== prior.title) ||
873
- (input.body !== undefined && input.body !== prior.body)) {
874
- const body = renderIssueHistory(prior.title, prior.body);
875
- const publicHistory = validateIssue({ title: prior.title, legacyBody: prior.body, draft: true }, false);
876
- if (publicHistory.failures.length)
877
- throw new IssueValidationError(publicHistory.failures);
878
- if (body.length > ISSUE_COMMENT_BODY_LIMIT)
879
- throw new DeliveryError('Complete issue history exceeds the supported comment body limit; issue was not rewritten.');
880
- priorContent = prior;
881
- historyBody = body;
882
- }
1025
+ }
1026
+ let historyBody;
1027
+ let priorContent = input.status === void 0 ? void 0 : { title: currentContent.title, body: currentContent.body };
1028
+ if (input.preserveHistory === true && (input.title !== void 0 || input.body !== void 0)) {
1029
+ const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
1030
+ if (current.number !== input.issueNumber || "pull_request" in current)
1031
+ throw new DeliveryError("History target is not the requested issue.");
1032
+ const prior = { title: current.title, body: current.body ?? "" };
1033
+ if (prior.title !== currentContent.title || prior.body !== currentContent.body)
1034
+ throw new DeliveryError("Issue content changed after preparation; retry against the current title and body.");
1035
+ if (input.title !== void 0 && input.title !== prior.title || input.body !== void 0 && input.body !== prior.body) {
1036
+ const body = renderIssueHistory(prior.title, prior.body);
1037
+ const publicHistory = validateIssue({ title: prior.title, legacyBody: prior.body, draft: true }, false);
1038
+ if (publicHistory.failures.length) throw new IssueValidationError(publicHistory.failures);
1039
+ if (body.length > ISSUE_COMMENT_BODY_LIMIT)
1040
+ throw new DeliveryError(
1041
+ "Complete issue history exceeds the supported comment body limit; issue was not rewritten."
1042
+ );
1043
+ priorContent = prior;
1044
+ historyBody = body;
883
1045
  }
884
- const closureBody = closeReason === undefined
885
- ? undefined
886
- : `Requested closure reason: ${closeReason}.${input.supersededBy === undefined ? '' : `\nSuperseded by ${repo.owner}/${repo.repo}#${String(input.supersededBy)}.`}`;
887
- return {
888
- input,
889
- prepared,
890
- acceptedLabels,
891
- beforeAdd,
892
- closeReason,
893
- supersedingIssueId,
894
- assertClosure,
895
- currentContent,
896
- dateChanges,
897
- priorContent,
898
- historyBody,
899
- closureBody,
900
- };
1046
+ }
1047
+ const closureBody = closeReason === void 0 ? void 0 : `Requested closure reason: ${closeReason}.${input.supersededBy === void 0 ? "" : `
1048
+ Superseded by ${repo.owner}/${repo.repo}#${String(input.supersededBy)}.`}`;
1049
+ const target = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
1050
+ if (target.number !== input.issueNumber || "pull_request" in target || !target.node_id || target.html_url !== currentContent.url || new URL(target.html_url).pathname.toLowerCase() !== `/${repo.owner}/${repo.repo}/issues/${String(input.issueNumber)}`.toLowerCase())
1051
+ throw new DeliveryError("History target is not the requested issue.");
1052
+ await assertIssueProjectWritable({
1053
+ preserveArchived,
1054
+ graphql: clients.graphql,
1055
+ issueNodeId: target.node_id,
1056
+ org: config.native.organization,
1057
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
1058
+ settings: projectSettingsFromDeliveryConfig(config)
1059
+ });
1060
+ return {
1061
+ input,
1062
+ prepared,
1063
+ acceptedLabels,
1064
+ beforeAdd,
1065
+ closeReason,
1066
+ supersedingIssueId,
1067
+ assertClosure,
1068
+ currentContent,
1069
+ projectOnly,
1070
+ preserveArchived,
1071
+ nativeTarget: { nodeId: target.node_id, url: target.html_url },
1072
+ dateChanges,
1073
+ priorContent,
1074
+ historyBody,
1075
+ closureBody
1076
+ };
901
1077
  }
902
- export async function updateIssue(context, input) {
903
- return applyIssueUpdate(context, await prepareIssueUpdate(context, input));
1078
+ async function updateIssue(context, input) {
1079
+ return applyIssueUpdate(context, await prepareIssueUpdate(context, input));
904
1080
  }
905
- async function applyIssueUpdate(context, plan) {
906
- const { clients, config, repo } = context;
907
- const { input, prepared, acceptedLabels, beforeAdd, closeReason, supersedingIssueId, assertClosure, priorContent, historyBody, closureBody, } = plan;
908
- const historyComment = historyBody === undefined
909
- ? undefined
910
- : await commentIssue(context, { issueNumber: input.issueNumber, body: historyBody });
911
- let closureComment;
912
- if (closureBody !== undefined)
913
- closureComment = await commentIssue(context, {
914
- issueNumber: input.issueNumber,
915
- body: closureBody,
916
- });
917
- if (priorContent !== undefined) {
918
- const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
919
- if (current.number !== input.issueNumber ||
920
- 'pull_request' in current ||
921
- current.title !== priorContent.title ||
922
- (current.body ?? '') !== priorContent.body)
923
- throw new DeliveryError('Issue content changed after preparation; retry against the current title and body.');
924
- }
1081
+ async function applyIssueUpdate(context, plan, changes) {
1082
+ const { clients, config, repo } = context;
1083
+ const {
1084
+ input,
1085
+ prepared,
1086
+ acceptedLabels,
1087
+ beforeAdd,
1088
+ closeReason,
1089
+ supersedingIssueId,
1090
+ assertClosure,
1091
+ priorContent,
1092
+ historyBody,
1093
+ closureBody
1094
+ } = plan;
1095
+ const pending = (key) => (changes === void 0 || key in changes) && (!plan.projectOnly || key === "projectStatus" || key === "projectStatusComment");
1096
+ const historyComment = historyBody === void 0 ? void 0 : await commentIssue(context, { issueNumber: input.issueNumber, body: historyBody });
1097
+ let closureComment;
1098
+ if (closureBody !== void 0)
1099
+ closureComment = await commentIssue(context, {
1100
+ issueNumber: input.issueNumber,
1101
+ body: closureBody
1102
+ });
1103
+ if (priorContent !== void 0) {
1104
+ const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
1105
+ if (current.number !== input.issueNumber || "pull_request" in current || current.title !== priorContent.title || (current.body ?? "") !== priorContent.body)
1106
+ throw new DeliveryError("Issue content changed after preparation; retry against the current title and body.");
1107
+ }
1108
+ if (["body", "issueType", "labels", "milestone", "state", "closeReason", "supersededBy", "title"].some(pending))
925
1109
  await clients.rest.issues.update({
926
- issue_number: input.issueNumber,
927
- owner: repo.owner,
928
- repo: repo.repo,
929
- ...(input.body === undefined ? {} : { body: input.body }),
930
- ...(input.issueType === undefined ? {} : { type: input.issueType }),
931
- ...(acceptedLabels === undefined ? {} : { labels: acceptedLabels }),
932
- ...(input.milestone === undefined ? {} : { milestone: input.milestone }),
933
- ...(input.state === undefined ? {} : { state: input.state }),
934
- ...(closeReason === undefined
935
- ? {}
936
- : { state_reason: closeReason, headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION } }),
937
- ...(closeReason !== 'duplicate' || supersedingIssueId === undefined
938
- ? {}
939
- : { duplicate_issue_id: supersedingIssueId }),
940
- ...(input.title === undefined ? {} : { title: input.title }),
1110
+ issue_number: input.issueNumber,
1111
+ owner: repo.owner,
1112
+ repo: repo.repo,
1113
+ ...input.body === void 0 || !pending("body") ? {} : { body: input.body },
1114
+ ...input.issueType === void 0 || !pending("issueType") ? {} : { type: input.issueType },
1115
+ ...acceptedLabels === void 0 || !pending("labels") ? {} : { labels: acceptedLabels },
1116
+ ...input.milestone === void 0 || !pending("milestone") ? {} : { milestone: input.milestone },
1117
+ ...input.state === void 0 || !pending("state") ? {} : { state: input.state },
1118
+ ...closeReason === void 0 || !pending("closeReason") && !pending("state") ? {} : { state_reason: closeReason, headers: { "X-GitHub-Api-Version": NATIVE_ISSUE_API_VERSION } },
1119
+ ...closeReason !== "duplicate" || supersedingIssueId === void 0 || !pending("supersededBy") && !pending("state") ? {} : { duplicate_issue_id: supersedingIssueId },
1120
+ ...input.title === void 0 || !pending("title") ? {} : { title: input.title }
941
1121
  });
942
- const closure = closeReason === undefined ? undefined : await readIssueClosure(context, input.issueNumber);
943
- if (closure !== undefined)
944
- assertClosure(closure);
945
- if (input.points !== undefined || input.priority !== undefined)
946
- await setConfiguredNativeIssueMetadata({
947
- issueNumber: input.issueNumber,
948
- metadata: {
949
- ...(input.points === undefined ? {} : { points: input.points }),
950
- ...(input.priority === undefined ? {} : { priority: input.priority }),
951
- },
952
- org: config.native.organization,
953
- owner: repo.owner,
954
- repo: repo.repo,
955
- rest: clients.rest,
956
- settings: nativeIssueSettingsFromDeliveryConfig(config),
957
- });
958
- await applyNativeIssueDates({
959
- changes: plan.dateChanges,
960
- issueNumber: input.issueNumber,
961
- ...repo,
962
- rest: clients.rest,
1122
+ const closure = closeReason === void 0 ? void 0 : await readIssueClosure(context, input.issueNumber);
1123
+ if (closure !== void 0) assertClosure(closure);
1124
+ if (input.points !== void 0 && pending("points") || input.priority !== void 0 && pending("priority"))
1125
+ await setConfiguredNativeIssueMetadata({
1126
+ issueNumber: input.issueNumber,
1127
+ metadata: {
1128
+ ...input.points === void 0 || !pending("points") ? {} : { points: input.points },
1129
+ ...input.priority === void 0 || !pending("priority") ? {} : { priority: input.priority }
1130
+ },
1131
+ org: config.native.organization,
1132
+ owner: repo.owner,
1133
+ repo: repo.repo,
1134
+ rest: clients.rest,
1135
+ settings: nativeIssueSettingsFromDeliveryConfig(config)
963
1136
  });
964
- if (input.parentIssueNumber !== undefined)
965
- await replaceParentIssue({
966
- graphql: clients.graphql,
967
- issueNumber: input.issueNumber,
968
- parentIssueNumber: input.parentIssueNumber,
969
- repo,
970
- rest: clients.rest,
971
- });
972
- if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null)
973
- await clearConfiguredNativeIssuePoints({
974
- issueNumber: input.parentIssueNumber,
975
- org: config.native.organization,
976
- owner: repo.owner,
977
- repo: repo.repo,
978
- rest: clients.rest,
979
- settings: nativeIssueSettingsFromDeliveryConfig(config),
980
- });
981
- try {
982
- if (input.blockedBy !== undefined)
983
- await replaceBlockedBy({
984
- ...(beforeAdd === undefined ? {} : { beforeAdd }),
985
- blockers: input.blockedBy,
986
- graphql: clients.graphql,
987
- issueNumber: input.issueNumber,
988
- repo,
989
- rest: clients.rest,
990
- });
991
- for (const dependent of new Set(input.blocks ?? []))
992
- await linkBlockedBy({
993
- ...(beforeAdd === undefined ? {} : { beforeAdd }),
994
- blockers: [input.issueNumber],
995
- graphql: clients.graphql,
996
- issueNumber: dependent,
997
- repo,
998
- rest: clients.rest,
999
- });
1000
- }
1001
- catch (error) {
1002
- throw new DeliveryError(`Issue #${input.issueNumber} content or metadata may have changed, but dependency tracking did not complete: ${error instanceof Error ? error.message : String(error)}. Inspect native state and resume this existing issue.`);
1003
- }
1137
+ await applyNativeIssueDates({
1138
+ changes: plan.dateChanges.filter((change) => pending(change.name === "Start date" ? "startDate" : "targetDate")),
1139
+ issueNumber: input.issueNumber,
1140
+ ...repo,
1141
+ rest: clients.rest
1142
+ });
1143
+ if (input.parentIssueNumber !== void 0 && pending("parentIssueNumber"))
1144
+ await replaceParentIssue({
1145
+ graphql: clients.graphql,
1146
+ issueNumber: input.issueNumber,
1147
+ parentIssueNumber: input.parentIssueNumber,
1148
+ repo,
1149
+ rest: clients.rest
1150
+ });
1151
+ if (input.parentIssueNumber !== void 0 && input.parentIssueNumber !== null && pending("parentPoints"))
1152
+ await clearConfiguredNativeIssuePoints({
1153
+ issueNumber: input.parentIssueNumber,
1154
+ org: config.native.organization,
1155
+ owner: repo.owner,
1156
+ repo: repo.repo,
1157
+ rest: clients.rest,
1158
+ settings: nativeIssueSettingsFromDeliveryConfig(config)
1159
+ });
1160
+ try {
1161
+ if (input.blockedBy !== void 0 && pending("blockedBy"))
1162
+ await replaceBlockedBy({
1163
+ ...beforeAdd === void 0 ? {} : { beforeAdd },
1164
+ blockers: input.blockedBy,
1165
+ graphql: clients.graphql,
1166
+ issueNumber: input.issueNumber,
1167
+ repo,
1168
+ rest: clients.rest
1169
+ });
1170
+ for (const dependent of new Set(pending("blocks") ? input.blocks ?? [] : []))
1171
+ await linkBlockedBy({
1172
+ ...beforeAdd === void 0 ? {} : { beforeAdd },
1173
+ blockers: [input.issueNumber],
1174
+ graphql: clients.graphql,
1175
+ issueNumber: dependent,
1176
+ repo,
1177
+ rest: clients.rest
1178
+ });
1179
+ } catch (error) {
1180
+ throw new DeliveryError(
1181
+ `Issue #${input.issueNumber} content or metadata may have changed, but dependency tracking did not complete: ${error instanceof Error ? error.message : String(error)}. Inspect native state and resume this existing issue.`
1182
+ );
1183
+ }
1184
+ let status = updateProjectStatus(
1185
+ { ...plan.currentContent, state: input.state ?? plan.currentContent.state },
1186
+ input
1187
+ );
1188
+ let readback;
1189
+ let latestProjectStatus = plan.currentContent.projectStatus;
1190
+ let projectStatusComment;
1191
+ const priorRateObservation = clients.rateLimitObservation?.();
1192
+ try {
1193
+ await assertProjectTransition(context, plan);
1004
1194
  const info = await issueInfo(context, input.issueNumber);
1005
- const status = updateProjectStatus(info, input);
1006
- const issue = (await clients.rest.issues.get({ issue_number: input.issueNumber, ...repo })).data;
1007
- await syncIssueProjectStatus({
1195
+ latestProjectStatus = info.projectStatus;
1196
+ status = updateProjectStatus(info, input);
1197
+ const target = (await clients.rest.issues.get({ issue_number: input.issueNumber, ...repo })).data;
1198
+ if (target.node_id !== plan.nativeTarget.nodeId || target.html_url !== plan.nativeTarget.url || target.number !== input.issueNumber || "pull_request" in target)
1199
+ throw new DeliveryError("Native closure readback returned a foreign issue identity.");
1200
+ const archivedItemId = plan.preserveArchived ? await assertIssueProjectWritable({
1201
+ preserveArchived: true,
1202
+ graphql: clients.graphql,
1203
+ issueNodeId: target.node_id,
1204
+ org: config.native.organization,
1205
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
1206
+ settings: projectSettingsFromDeliveryConfig(config)
1207
+ }) : null;
1208
+ if (archivedItemId !== null) {
1209
+ readback = info;
1210
+ prepared.warnings.push({
1211
+ code: "project.archived",
1212
+ field: "project",
1213
+ message: `Archived Project item ${archivedItemId} was preserved.`,
1214
+ fixHint: `Archived Project item ${archivedItemId} was preserved.`
1215
+ });
1216
+ } else {
1217
+ const reasonBody = projectStatusBody(input);
1218
+ if (reasonBody !== void 0)
1219
+ projectStatusComment = {
1220
+ ...await commentIssue(context, { issueNumber: input.issueNumber, body: reasonBody }),
1221
+ ...input.projectStatus
1222
+ };
1223
+ const configuration = input.projectStatus === void 0 ? context.projectConfiguration : context.projectConfiguration ?? await getProjectDeliveryConfiguration({
1008
1224
  graphql: clients.graphql,
1009
- issueNodeId: issue.node_id,
1010
1225
  org: config.native.organization,
1011
- ...(context.projectConfiguration ? { configuration: context.projectConfiguration } : {}),
1012
1226
  settings: projectSettingsFromDeliveryConfig(config),
1013
- status,
1014
- });
1015
- const readback = await issueInfo(context, input.issueNumber);
1016
- if ((input.title !== undefined && readback.title !== input.title) ||
1017
- (input.body !== undefined && readback.body !== input.body) ||
1018
- (input.state !== undefined && readback.state !== input.state) ||
1019
- (input.points !== undefined && readback.points !== input.points) ||
1020
- (input.issueType !== undefined && readback.issueType !== input.issueType))
1021
- throw new DeliveryError('Issue update readback disagrees with the requested content or state.');
1022
- return {
1023
- ...readback,
1024
- warnings: prepared.warnings,
1025
- ...(prepared.conversion === undefined ? {} : { conversion: prepared.conversion }),
1026
- ...(historyComment === undefined ? {} : { historyComment }),
1027
- ...(closure === undefined || closureComment === undefined
1028
- ? {}
1029
- : { closure: { ...closure, supersededBy: input.supersededBy ?? null, comment: closureComment } }),
1227
+ requireWritable: true
1228
+ });
1229
+ const projected = await syncIssueProjectStatus({
1230
+ ...input.projectStatus === void 0 ? {} : {
1231
+ beforeAdd: () => assertProjectTransition(context, plan),
1232
+ beforeAdvance: () => assertProjectTransition(context, plan, true)
1233
+ },
1234
+ graphql: clients.graphql,
1235
+ issueNodeId: target.node_id,
1236
+ org: config.native.organization,
1237
+ ...configuration ? { configuration } : {},
1238
+ settings: projectSettingsFromDeliveryConfig(config),
1239
+ status
1240
+ });
1241
+ if (input.projectStatus !== void 0 && configuration !== void 0) {
1242
+ await assertProjectTransition(context, plan);
1243
+ await readBackProjectItem({
1244
+ graphql: clients.graphql,
1245
+ configuration,
1246
+ issueNodeId: target.node_id,
1247
+ itemId: projected.itemId,
1248
+ status
1249
+ });
1250
+ await readAuthoredIssueComment(
1251
+ context,
1252
+ input.issueNumber,
1253
+ { id: projectStatusComment.commentId, html_url: projectStatusComment.url },
1254
+ reasonBody,
1255
+ (await clients.authenticatedAuthor()).actorLogin
1256
+ );
1257
+ }
1258
+ readback = await issueInfo(context, input.issueNumber);
1259
+ if (readback.projectStatus !== status)
1260
+ throw new DeliveryError("Project Status readback disagrees with the requested outcome.");
1261
+ }
1262
+ } catch (error) {
1263
+ const observedRate = clients.rateLimitObservation?.();
1264
+ const limit = getRateLimitDiagnostics(error) ?? (observedRate !== priorRateObservation ? observedRate : void 0);
1265
+ const diagnostic = getMachineRequestDiagnostics(error);
1266
+ const cancelled = diagnostic?.code === "ABORT_ERR" || !types.isProxy(error) && error instanceof DOMException && error.name === "AbortError";
1267
+ const result = {
1268
+ status: "update-incomplete",
1269
+ ...limit === void 0 ? {} : { rateLimit: limit },
1270
+ native: {
1271
+ status: "unknown",
1272
+ repository: `${repo.owner}/${repo.repo}`,
1273
+ issueNumber: input.issueNumber,
1274
+ readback: null,
1275
+ readbackError: limit !== void 0 || cancelled ? "Readback deferred after rate-limit exhaustion or cancellation." : "Native issue evidence is unavailable or inconsistent."
1276
+ },
1277
+ project: {
1278
+ status: localBatchFailureReason(error) === "The issue delivery Project item is archived and cannot be updated." ? "pending" : "unknown",
1279
+ desiredStatus: input.blockedBy === void 0 ? status : null,
1280
+ reason: localBatchFailureReason(error) === "The issue delivery Project item is archived and cannot be updated." ? "archived" : "unavailable"
1281
+ },
1282
+ recovery: {
1283
+ tool: "issue_batch_update",
1284
+ instruction: "Reconcile this existing issue with the original desired fields through issue_batch_update. Do not replay the full issue_update. An archived Project item requires separately authorized restoration before projection-only recovery."
1285
+ }
1030
1286
  };
1031
- }
1032
- /** Read-only inspection of the same authenticated closure journal used by updateIssue. */
1033
- async function hasUpdateComment(context, issueNumber, body) {
1034
- if (!context.clients.authenticatedAuthor)
1035
- throw new DeliveryError('Authenticated update journal author is missing.');
1036
- const actor = (await context.clients.authenticatedAuthor()).actorLogin;
1037
- if (!actor)
1038
- throw new DeliveryError('Update journal author identity is missing.');
1039
- const matches = [];
1040
- let complete = false;
1041
- for (let page = 1; page <= 20; page++) {
1042
- const comments = (await context.clients.rest.issues.listComments({
1043
- ...context.repo,
1044
- issue_number: issueNumber,
1045
- per_page: 100,
1046
- page,
1047
- })).data;
1048
- matches.push(...comments.filter((comment) => comment.user?.login?.toLowerCase() === actor.toLowerCase() && comment.body === body));
1049
- if (comments.length < 100) {
1050
- complete = true;
1051
- break;
1287
+ if (limit === void 0 && !cancelled) {
1288
+ try {
1289
+ const native = await updateProjection(context, plan, true);
1290
+ const desired = await desiredUpdateValues(context, plan);
1291
+ delete desired.projectStatus;
1292
+ delete desired.projectStatusReason;
1293
+ if (Object.keys(pendingUpdateValues(desired, native.values)).length)
1294
+ throw new DeliveryError("Issue update readback disagrees with the requested content or state.");
1295
+ if (historyBody !== void 0 && !await findUpdateComment(context, input.issueNumber, historyBody))
1296
+ throw new DeliveryError("Issue comment readback disagrees with the authored issue comment.");
1297
+ result.project.desiredStatus = updateProjectStatus(
1298
+ { ...native.readback, projectStatus: latestProjectStatus },
1299
+ input
1300
+ );
1301
+ if (input.projectStatus !== void 0) {
1302
+ const comment = await findUpdateComment(context, input.issueNumber, projectStatusBody(input));
1303
+ projectStatusComment = comment === null ? void 0 : { ...comment, ...input.projectStatus };
1052
1304
  }
1305
+ result.native = {
1306
+ ...result.native,
1307
+ status: "confirmed",
1308
+ readback: native.readback,
1309
+ ...projectStatusComment === void 0 ? {} : { projectStatusComment },
1310
+ ...historyComment === void 0 ? {} : { historyComment },
1311
+ ...closure === void 0 || closureComment === void 0 ? {} : { closure: { ...closure, supersededBy: input.supersededBy ?? null, comment: closureComment } }
1312
+ };
1313
+ delete result.native.readbackError;
1314
+ } catch (readbackError) {
1315
+ const latest = clients.rateLimitObservation?.();
1316
+ const readbackLimit = getRateLimitDiagnostics(readbackError) ?? (latest !== priorRateObservation ? latest : void 0);
1317
+ if (readbackLimit !== void 0) result.rateLimit = readbackLimit;
1318
+ }
1053
1319
  }
1054
- if (!complete)
1055
- throw new DeliveryError('Update journal readback exceeds the bounded history window.');
1056
- if (matches.length > 1)
1057
- throw new DeliveryError('Issue comment has duplicate authored retry matches.');
1058
- if (!matches[0])
1059
- return false;
1060
- await readAuthoredIssueComment(context, issueNumber, matches[0], body, actor);
1061
- return true;
1320
+ const incomplete = new IssueUpdateIncompleteError(result);
1321
+ if (diagnostic !== void 0) setMachineRequestDiagnostics(incomplete, diagnostic);
1322
+ throw incomplete;
1323
+ }
1324
+ if (input.title !== void 0 && readback.title !== input.title || input.body !== void 0 && readback.body !== input.body || input.state !== void 0 && readback.state !== input.state || input.points !== void 0 && readback.points !== input.points || input.issueType !== void 0 && readback.issueType !== input.issueType)
1325
+ throw new DeliveryError("Issue update readback disagrees with the requested content or state.");
1326
+ return {
1327
+ ...readback,
1328
+ warnings: prepared.warnings,
1329
+ ...prepared.conversion === void 0 ? {} : { conversion: prepared.conversion },
1330
+ ...projectStatusComment === void 0 ? {} : { projectStatusComment },
1331
+ ...historyComment === void 0 ? {} : { historyComment },
1332
+ ...closure === void 0 || closureComment === void 0 ? {} : { closure: { ...closure, supersededBy: input.supersededBy ?? null, comment: closureComment } }
1333
+ };
1062
1334
  }
1063
- async function updateProjection(context, plan) {
1064
- const { input } = plan;
1065
- const readback = await issueInfo(context, input.issueNumber);
1066
- const values = { ...readback };
1067
- const relationships = async (issueNumber) => {
1068
- const native = await getNativeBlockerRelationships({
1069
- graphql: context.clients.graphql,
1070
- repo: context.repo,
1071
- issueNumber,
1072
- requireRepositoryIdentity: true,
1073
- });
1074
- const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1075
- const edges = [
1076
- ...native.blockers,
1077
- ...(native.parentNumber === null
1078
- ? []
1079
- : [{ number: native.parentNumber, id: native.parentId, repository: native.parentRepository }]),
1080
- ];
1081
- if (edges.some((edge) => edge.repository?.toLowerCase() !== repository))
1082
- throw new DeliveryError('Native batch relationship belongs to a different repository.');
1083
- const targets = await resolveNativeRelationshipTargets({
1084
- blockers: edges.map((edge) => edge.number),
1085
- repo: context.repo,
1086
- rest: context.clients.rest,
1087
- });
1088
- if (edges.some((edge) => edge.id !== targets.blockerNodeIds.get(edge.number)))
1089
- throw new DeliveryError('Native batch relationship node identity disagrees with its repository issue.');
1090
- return native;
1091
- };
1092
- if (input.blockedBy !== undefined || input.parentIssueNumber !== undefined) {
1093
- const native = await relationships(input.issueNumber);
1094
- if (native.parentNumber !== readback.parentIssueNumber)
1095
- throw new DeliveryError('Native parent changed during batch readback; reconcile the current state.');
1096
- if (input.blockedBy !== undefined)
1097
- values.blockedBy = native.blockers.map((value) => value.number).sort((a, b) => a - b);
1335
+ async function findUpdateComment(context, issueNumber, body) {
1336
+ if (!context.clients.authenticatedAuthor) throw new DeliveryError("Authenticated update journal author is missing.");
1337
+ const actor = (await context.clients.authenticatedAuthor()).actorLogin;
1338
+ if (!actor) throw new DeliveryError("Update journal author identity is missing.");
1339
+ const matches = [];
1340
+ let complete = false;
1341
+ for (let page = 1; page <= 20; page++) {
1342
+ const comments = (await context.clients.rest.issues.listComments({
1343
+ ...context.repo,
1344
+ issue_number: issueNumber,
1345
+ per_page: 100,
1346
+ page
1347
+ })).data;
1348
+ matches.push(
1349
+ ...comments.filter(
1350
+ (comment) => comment.user?.login?.toLowerCase() === actor.toLowerCase() && comment.body === body
1351
+ )
1352
+ );
1353
+ if (comments.length < 100) {
1354
+ complete = true;
1355
+ break;
1098
1356
  }
1099
- if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null) {
1100
- const metadata = await getConfiguredNativeIssueMetadata({
1101
- issueNumber: input.parentIssueNumber,
1102
- ...context.repo,
1103
- rest: context.clients.rest,
1104
- settings: nativeIssueSettingsFromDeliveryConfig(context.config),
1357
+ }
1358
+ if (!complete) throw new DeliveryError("Update journal readback exceeds the bounded history window.");
1359
+ if (matches.length > 1) throw new DeliveryError("Issue comment has duplicate authored retry matches.");
1360
+ if (!matches[0]) return null;
1361
+ return { ...await readAuthoredIssueComment(context, issueNumber, matches[0], body, actor), reused: true };
1362
+ }
1363
+ async function updateProjection(context, plan, nativeOnly = false) {
1364
+ const { input } = plan;
1365
+ const { info: readback } = await readIssueInfo(
1366
+ context,
1367
+ input.issueNumber,
1368
+ !nativeOnly,
1369
+ nativeOnly ? plan.nativeTarget : void 0
1370
+ );
1371
+ const values = { ...readback };
1372
+ if (plan.preserveArchived && readback.projectStatus === null)
1373
+ values.projectStatus = await getArchivedIssueProjectStatus({
1374
+ graphql: context.clients.graphql,
1375
+ issueNodeId: plan.nativeTarget.nodeId,
1376
+ org: context.config.native.organization,
1377
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
1378
+ settings: projectSettingsFromDeliveryConfig(context.config)
1379
+ });
1380
+ if (input.projectStatus !== void 0) {
1381
+ const comment = await findUpdateComment(context, input.issueNumber, projectStatusBody(input));
1382
+ values.projectStatusReason = comment === null ? null : input.projectStatus.reason;
1383
+ values.projectStatusComment = comment;
1384
+ if (!nativeOnly) {
1385
+ const nativeChanges = pendingUpdateValues(await desiredUpdateValues(context, plan), values);
1386
+ delete nativeChanges.projectStatus;
1387
+ delete nativeChanges.projectStatusReason;
1388
+ await assertProjectTransition(context, plan, false, Object.keys(nativeChanges).length === 0);
1389
+ const configuration = context.projectConfiguration ?? await getProjectDeliveryConfiguration({
1390
+ graphql: context.clients.graphql,
1391
+ org: context.config.native.organization,
1392
+ settings: projectSettingsFromDeliveryConfig(context.config)
1393
+ });
1394
+ const item = await getIssueProjectStatus({
1395
+ graphql: context.clients.graphql,
1396
+ configuration,
1397
+ org: context.config.native.organization,
1398
+ issueNodeId: plan.nativeTarget.nodeId
1399
+ });
1400
+ if ((item?.status ?? null) !== readback.projectStatus)
1401
+ throw new DeliveryError("Project Status changed during readback; reconcile the configured item.");
1402
+ if (item !== null)
1403
+ await readBackProjectItem({
1404
+ graphql: context.clients.graphql,
1405
+ configuration,
1406
+ issueNodeId: plan.nativeTarget.nodeId,
1407
+ itemId: item.itemId,
1408
+ status: item.status
1105
1409
  });
1106
- values.parentPoints = { issueNumber: input.parentIssueNumber, points: metadata.points ?? null };
1107
1410
  }
1108
- if (input.blocks !== undefined) {
1109
- values.blocks = await Promise.all([...new Set(input.blocks)].map(async (dependent) => ({
1110
- issueNumber: dependent,
1111
- linked: (await relationships(dependent)).blockers.some((value) => value.number === input.issueNumber),
1112
- })));
1113
- }
1114
- if (plan.closeReason !== undefined) {
1115
- const closure = await readIssueClosure(context, input.issueNumber);
1116
- values.closeReason = closure.closeReason;
1117
- if (plan.closeReason === 'duplicate' && input.supersededBy !== undefined)
1118
- values.supersededBy = closure.duplicateOf?.number ?? null;
1119
- values.closureComment = await hasUpdateComment(context, input.issueNumber, plan.closureBody);
1120
- }
1121
- return { readback, values };
1411
+ }
1412
+ const relationships = async (issueNumber) => {
1413
+ const native = await getNativeBlockerRelationships({
1414
+ graphql: context.clients.graphql,
1415
+ repo: context.repo,
1416
+ issueNumber,
1417
+ requireRepositoryIdentity: true
1418
+ });
1419
+ const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1420
+ const edges = [
1421
+ ...native.blockers,
1422
+ ...native.parentNumber === null ? [] : [{ number: native.parentNumber, id: native.parentId, repository: native.parentRepository }]
1423
+ ];
1424
+ if (edges.some((edge) => edge.repository?.toLowerCase() !== repository))
1425
+ throw new DeliveryError("Native batch relationship belongs to a different repository.");
1426
+ const targets = await resolveNativeRelationshipTargets({
1427
+ blockers: edges.map((edge) => edge.number),
1428
+ repo: context.repo,
1429
+ rest: context.clients.rest
1430
+ });
1431
+ if (edges.some((edge) => edge.id !== targets.blockerNodeIds.get(edge.number)))
1432
+ throw new DeliveryError("Native batch relationship node identity disagrees with its repository issue.");
1433
+ return native;
1434
+ };
1435
+ if (input.blockedBy !== void 0 || input.parentIssueNumber !== void 0) {
1436
+ const native = await relationships(input.issueNumber);
1437
+ if (native.parentNumber !== readback.parentIssueNumber)
1438
+ throw new DeliveryError("Native parent changed during batch readback; reconcile the current state.");
1439
+ if (input.blockedBy !== void 0)
1440
+ values.blockedBy = native.blockers.map((value) => value.number).sort((a, b) => a - b);
1441
+ }
1442
+ if (input.parentIssueNumber !== void 0 && input.parentIssueNumber !== null) {
1443
+ const metadata = await getConfiguredNativeIssueMetadata({
1444
+ issueNumber: input.parentIssueNumber,
1445
+ ...context.repo,
1446
+ rest: context.clients.rest,
1447
+ settings: nativeIssueSettingsFromDeliveryConfig(context.config)
1448
+ });
1449
+ values.parentPoints = { issueNumber: input.parentIssueNumber, points: metadata.points ?? null };
1450
+ }
1451
+ if (input.blocks !== void 0) {
1452
+ values.blocks = await Promise.all(
1453
+ [...new Set(input.blocks)].map(async (dependent) => ({
1454
+ issueNumber: dependent,
1455
+ linked: (await relationships(dependent)).blockers.some((value) => value.number === input.issueNumber)
1456
+ }))
1457
+ );
1458
+ }
1459
+ if (plan.closeReason !== void 0) {
1460
+ const closure = await readIssueClosure(context, input.issueNumber);
1461
+ if (nativeOnly) plan.assertClosure(closure);
1462
+ values.closeReason = closure.closeReason;
1463
+ if (plan.closeReason === "duplicate" && input.supersededBy !== void 0)
1464
+ values.supersededBy = closure.duplicateOf?.number ?? null;
1465
+ values.closureComment = Boolean(await findUpdateComment(context, input.issueNumber, plan.closureBody));
1466
+ }
1467
+ return { readback, values };
1122
1468
  }
1123
1469
  async function desiredUpdateValues(context, plan) {
1124
- const { input } = plan;
1125
- const values = {};
1126
- for (const key of [
1127
- 'title',
1128
- 'body',
1129
- 'issueType',
1130
- 'points',
1131
- 'priority',
1132
- 'startDate',
1133
- 'targetDate',
1134
- 'milestone',
1135
- 'state',
1136
- 'parentIssueNumber',
1137
- ]) {
1138
- if (input[key] !== undefined)
1139
- values[key] = input[key];
1140
- }
1141
- if (plan.acceptedLabels !== undefined)
1142
- values.labels = [...plan.acceptedLabels].sort();
1143
- let openBlockers = plan.currentContent.blockedBy;
1144
- if (input.blockedBy !== undefined) {
1145
- values.blockedBy = [...new Set(input.blockedBy)].sort((a, b) => a - b);
1146
- const targets = await Promise.all(input.blockedBy.map(async (number) => (await context.clients.rest.issues.get({ ...context.repo, issue_number: number })).data));
1147
- openBlockers = targets.filter((target) => target.state === 'open').map((target) => target.number);
1148
- }
1149
- values.projectStatus = updateProjectStatus({
1150
- ...plan.currentContent,
1151
- state: input.state ?? plan.currentContent.state,
1152
- blockedBy: openBlockers,
1153
- }, input);
1154
- if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null)
1155
- values.parentPoints = { issueNumber: input.parentIssueNumber, points: null };
1156
- if (input.blocks !== undefined)
1157
- values.blocks = [...new Set(input.blocks)].map((issueNumber) => ({ issueNumber, linked: true }));
1158
- if (plan.closeReason !== undefined) {
1159
- values.closeReason = plan.closeReason;
1160
- if (plan.closeReason === 'duplicate' && input.supersededBy !== undefined)
1161
- values.supersededBy = input.supersededBy;
1162
- values.closureComment = true;
1163
- }
1164
- return values;
1470
+ const { input } = plan;
1471
+ const values = {};
1472
+ for (const key of [
1473
+ "title",
1474
+ "body",
1475
+ "issueType",
1476
+ "points",
1477
+ "priority",
1478
+ "startDate",
1479
+ "targetDate",
1480
+ "milestone",
1481
+ "state",
1482
+ "parentIssueNumber"
1483
+ ]) {
1484
+ if (!plan.projectOnly && input[key] !== void 0) values[key] = input[key];
1485
+ }
1486
+ if (input.projectStatus !== void 0) values.projectStatusReason = input.projectStatus.reason;
1487
+ if (plan.acceptedLabels !== void 0) values.labels = [...plan.acceptedLabels].sort();
1488
+ let openBlockers = plan.currentContent.blockedBy;
1489
+ if (input.blockedBy !== void 0) {
1490
+ values.blockedBy = [...new Set(input.blockedBy)].sort((a, b) => a - b);
1491
+ const targets = await Promise.all(
1492
+ input.blockedBy.map(
1493
+ async (number) => (await context.clients.rest.issues.get({ ...context.repo, issue_number: number })).data
1494
+ )
1495
+ );
1496
+ openBlockers = targets.filter((target) => target.state === "open").map((target) => target.number);
1497
+ }
1498
+ values.projectStatus = updateProjectStatus(
1499
+ {
1500
+ ...plan.currentContent,
1501
+ state: input.state ?? plan.currentContent.state,
1502
+ blockedBy: openBlockers
1503
+ },
1504
+ input
1505
+ );
1506
+ if (input.parentIssueNumber !== void 0 && input.parentIssueNumber !== null)
1507
+ values.parentPoints = { issueNumber: input.parentIssueNumber, points: null };
1508
+ if (input.blocks !== void 0)
1509
+ values.blocks = [...new Set(input.blocks)].map((issueNumber) => ({ issueNumber, linked: true }));
1510
+ if (plan.closeReason !== void 0) {
1511
+ values.closeReason = plan.closeReason;
1512
+ if (plan.closeReason === "duplicate" && input.supersededBy !== void 0) values.supersededBy = input.supersededBy;
1513
+ values.closureComment = true;
1514
+ }
1515
+ return values;
1165
1516
  }
1166
1517
  function pendingUpdateValues(desired, actual) {
1167
- const labels = (value) => Array.isArray(value) && value.every((label) => typeof label === 'string')
1168
- ? value.map((label) => label.toLowerCase()).sort()
1169
- : value;
1170
- return Object.fromEntries(Object.entries(desired).filter(([key, value]) => JSON.stringify(key === 'labels' ? labels(value) : value) !==
1171
- JSON.stringify(key === 'labels' ? labels(actual[key]) : actual[key])));
1518
+ const labels2 = (value) => Array.isArray(value) && value.every((label) => typeof label === "string") ? value.map((label) => label.toLowerCase()).sort() : value;
1519
+ return Object.fromEntries(
1520
+ Object.entries(desired).filter(
1521
+ ([key, value]) => JSON.stringify(key === "labels" ? labels2(value) : value) !== JSON.stringify(key === "labels" ? labels2(actual[key]) : actual[key])
1522
+ )
1523
+ );
1172
1524
  }
1173
1525
  function localBatchFailureReason(error) {
1174
- if (typeof error !== 'object' || error === null || types.isProxy(error))
1175
- return undefined;
1176
- const prototype = Object.getPrototypeOf(error);
1177
- if (prototype === IssueValidationError.prototype)
1178
- return 'Requested issue fields do not satisfy the issue contract.';
1179
- if (prototype !== DeliveryError.prototype)
1180
- return undefined;
1181
- const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
1182
- const message = descriptor && 'value' in descriptor ? descriptor.value : undefined;
1183
- if (typeof message !== 'string')
1184
- return undefined;
1185
- if ([
1186
- 'Choose a valid defer condition or explicit undefer, never both.',
1187
- 'Use defer or undefer to change deferral state.',
1188
- 'Choose native blockedBy or display-only status.blockers in one update, not both.',
1189
- 'Convert the legacy contract explicitly before a status-only update.',
1190
- 'Issue labels must be non-empty and unique.',
1191
- 'Repository label listing exceeds the bounded readback window.',
1192
- 'Unsupported configured Issue Type.',
1193
- 'Unsupported configured Points value.',
1194
- 'Unsupported configured Priority value.',
1195
- 'Closure details require state closed and a supported close reason.',
1196
- 'A superseding issue must be a different positive issue number.',
1197
- 'Superseding issue readback is not the requested repository issue.',
1198
- 'Issue is already closed with different closure evidence; reopen it explicitly first.',
1199
- 'Native closure readback disagrees with the requested reason or superseding issue.',
1200
- 'Native closure readback returned a foreign issue identity.',
1201
- 'Native closure readback has contradictory state evidence.',
1202
- 'History target is not the requested issue.',
1203
- 'Issue content changed after preparation; retry against the current title and body.',
1204
- 'Complete issue history exceeds the supported comment body limit; issue was not rewritten.',
1205
- 'Issue update readback disagrees with the requested content or state.',
1206
- 'Issue comments require the authenticated author role.',
1207
- 'Issue comment author identity is missing.',
1208
- 'Issue comment target is not the requested issue.',
1209
- 'Issue comment history exceeds the bounded readback window.',
1210
- 'Issue comment has duplicate authored retry matches.',
1211
- 'Issue comment conflicts with its authored operation marker.',
1212
- 'Issue comment readback disagrees with the authored issue comment.',
1213
- 'Authenticated update journal author is missing.',
1214
- 'Update journal author identity is missing.',
1215
- 'Update journal readback exceeds the bounded history window.',
1216
- 'An issue cannot be its own parent or blocker.',
1217
- 'Native blockers must be unique.',
1218
- 'Native Points and Priority catalogs must select distinct issue fields.',
1219
- 'Dependency endpoint must be a positive issue number.',
1220
- 'Dependency endpoint is not the requested repository issue.',
1221
- 'Dependency writes require configured author authority.',
1222
- 'Dependency author identity is unavailable.',
1223
- 'An issue cannot block itself.',
1224
- 'Dependency removal episode is ambiguous.',
1225
- 'Complete dependency history is required for an active blocker override.',
1226
- 'Override comment author, body or issue readback disagrees; native dependency was not added.',
1227
- 'Override comment search is incomplete or has duplicate authoritative markers.',
1228
- 'Override comment evidence is malformed.',
1229
- 'Existing override comment conflicts with the requested reason or endpoint evidence.',
1230
- 'Native batch relationship belongs to a different repository.',
1231
- 'Native batch relationship node identity disagrees with its repository issue.',
1232
- 'Native parent changed during batch readback; reconcile the current state.',
1233
- 'Native issue changed during batch preparation; reconcile the current state.',
1234
- 'Native batch readback disagrees with the requested outcomes.',
1235
- ].includes(message))
1236
- return message;
1237
- if (message.startsWith('Unknown repository label(s): '))
1238
- return 'One or more requested labels do not exist in the selected repository.';
1239
- if (/^Adding a blocker to active issue #\d+ requires overrideReason\.$/u.test(message))
1240
- return 'Adding a blocker to an active issue requires overrideReason.';
1241
- if (/^Project status for dependent #\d+ is unresolved; dependency additions were refused\.$/u.test(message))
1242
- return 'Project status for a dependent is unresolved; dependency additions were refused.';
1243
- if (message.startsWith('Complete dependency history is required for an active blocker override: '))
1244
- return 'Complete dependency history is required for an active blocker override.';
1245
- if (/^Issue #\d+ content or metadata may have changed, but dependency tracking did not complete: /u.test(message))
1246
- return 'Issue content or metadata may have changed, but dependency tracking did not complete. Inspect native state and resume this existing issue.';
1247
- return undefined;
1526
+ if (typeof error !== "object" || error === null || types.isProxy(error)) return void 0;
1527
+ const prototype = Object.getPrototypeOf(error);
1528
+ if (prototype === IssueValidationError.prototype) return "Requested issue fields do not satisfy the issue contract.";
1529
+ if (prototype !== DeliveryError.prototype) return void 0;
1530
+ const descriptor = Object.getOwnPropertyDescriptor(error, "message");
1531
+ const message = descriptor && "value" in descriptor ? descriptor.value : void 0;
1532
+ if (typeof message !== "string") return void 0;
1533
+ if ([
1534
+ "Choose a valid defer condition or explicit undefer, never both.",
1535
+ "Use defer or undefer to change deferral state.",
1536
+ "Choose native blockedBy or display-only status.blockers in one update, not both.",
1537
+ "Convert the legacy contract explicitly before a status-only update.",
1538
+ "Issue labels must be non-empty and unique.",
1539
+ "Repository label listing exceeds the bounded readback window.",
1540
+ "Unsupported configured Issue Type.",
1541
+ "Unsupported configured Points value.",
1542
+ "Unsupported configured Priority value.",
1543
+ "Closure details require state closed and a supported close reason.",
1544
+ "A superseding issue must be a different positive issue number.",
1545
+ "Superseding issue readback is not the requested repository issue.",
1546
+ "Issue is already closed with different closure evidence; reopen it explicitly first.",
1547
+ "Native closure readback disagrees with the requested reason or superseding issue.",
1548
+ "Native closure readback returned a foreign issue identity.",
1549
+ "Native closure readback has contradictory state evidence.",
1550
+ "History target is not the requested issue.",
1551
+ "Issue content changed after preparation; retry against the current title and body.",
1552
+ "Complete issue history exceeds the supported comment body limit; issue was not rewritten.",
1553
+ "Issue update readback disagrees with the requested content or state.",
1554
+ "Issue comments require the authenticated author role.",
1555
+ "Issue comment author identity is missing.",
1556
+ "Issue comment target is not the requested issue.",
1557
+ "Issue comment history exceeds the bounded readback window.",
1558
+ "Issue comment has duplicate authored retry matches.",
1559
+ "Issue comment conflicts with its authored operation marker.",
1560
+ "Issue comment readback disagrees with the authored issue comment.",
1561
+ "Authenticated update journal author is missing.",
1562
+ "Update journal author identity is missing.",
1563
+ "Update journal readback exceeds the bounded history window.",
1564
+ "An issue cannot be its own parent or blocker.",
1565
+ "Native blockers must be unique.",
1566
+ "Native Points and Priority catalogs must select distinct issue fields.",
1567
+ "Dependency endpoint must be a positive issue number.",
1568
+ "Dependency endpoint is not the requested repository issue.",
1569
+ "Dependency writes require configured author authority.",
1570
+ "Dependency author identity is unavailable.",
1571
+ "An issue cannot block itself.",
1572
+ "Dependency removal episode is ambiguous.",
1573
+ "Complete dependency history is required for an active blocker override.",
1574
+ "Override comment author, body or issue readback disagrees; native dependency was not added.",
1575
+ "Override comment search is incomplete or has duplicate authoritative markers.",
1576
+ "Override comment evidence is malformed.",
1577
+ "Existing override comment conflicts with the requested reason or endpoint evidence.",
1578
+ "Native batch relationship belongs to a different repository.",
1579
+ "Native batch relationship node identity disagrees with its repository issue.",
1580
+ "Native parent changed during batch readback; reconcile the current state.",
1581
+ "Native issue changed during batch preparation; reconcile the current state.",
1582
+ "Native batch readback disagrees with the requested outcomes.",
1583
+ "The issue delivery Project item is archived and cannot be updated."
1584
+ ].includes(message))
1585
+ return message;
1586
+ if (message.startsWith("Unknown repository label(s): "))
1587
+ return "One or more requested labels do not exist in the selected repository.";
1588
+ if (/^Adding a blocker to active issue #\d+ requires overrideReason\.$/u.test(message))
1589
+ return "Adding a blocker to an active issue requires overrideReason.";
1590
+ if (/^Project status for dependent #\d+ is unresolved; dependency additions were refused\.$/u.test(message))
1591
+ return "Project status for a dependent is unresolved; dependency additions were refused.";
1592
+ if (message.startsWith("Complete dependency history is required for an active blocker override: "))
1593
+ return "Complete dependency history is required for an active blocker override.";
1594
+ if (/^Issue #\d+ content or metadata may have changed, but dependency tracking did not complete: /u.test(message))
1595
+ return "Issue content or metadata may have changed, but dependency tracking did not complete. Inspect native state and resume this existing issue.";
1596
+ return void 0;
1248
1597
  }
1249
- /** One serial operation; each application uses the existing single-update mutation owner. */
1250
- export async function batchUpdateIssues(context, input, signal) {
1251
- if (context.clients.role !== 'author')
1252
- throw new DeliveryError('Batch updates require the configured author role.');
1253
- if (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > 50)
1254
- throw new DeliveryError('Provide 1–50 batch items.');
1255
- const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1256
- if (input.items.some((item) => item.repo !== undefined && item.repo.toLowerCase() !== repository))
1257
- throw new DeliveryError('Every batch item must use the selected repository.');
1258
- const results = [];
1259
- const rateLimits = [];
1260
- const priorRateObservation = context.clients.rateLimitObservation?.();
1261
- let limited = false;
1262
- for (const { repo: _repo, ...item } of input.items) {
1263
- if (limited || signal?.aborted) {
1264
- results.push({
1265
- issueNumber: item.issueNumber,
1266
- status: 'failed',
1267
- reason: limited ? 'Not attempted: GitHub rate limit exhausted.' : 'Not attempted: operation cancelled.',
1268
- readback: null,
1269
- readbackError: 'No new readback requested after rate-limit exhaustion or cancellation.',
1270
- });
1271
- continue;
1272
- }
1273
- let phase = 'preparation';
1598
+ async function batchUpdateIssues(context, input, signal) {
1599
+ if (context.clients.role !== "author") throw new DeliveryError("Batch updates require the configured author role.");
1600
+ if (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > 50)
1601
+ throw new DeliveryError("Provide 1\u201350 batch items.");
1602
+ const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1603
+ if (input.items.some((item) => item.repo !== void 0 && item.repo.toLowerCase() !== repository))
1604
+ throw new DeliveryError("Every batch item must use the selected repository.");
1605
+ const results = [];
1606
+ const rateLimits = [];
1607
+ const priorRateObservation = context.clients.rateLimitObservation?.();
1608
+ let limited = false;
1609
+ for (const { repo: _repo, ...item } of input.items) {
1610
+ if (limited || signal?.aborted) {
1611
+ results.push({
1612
+ issueNumber: item.issueNumber,
1613
+ status: "failed",
1614
+ reason: limited ? "Not attempted: GitHub rate limit exhausted." : "Not attempted: operation cancelled.",
1615
+ readback: null,
1616
+ readbackError: "No new readback requested after rate-limit exhaustion or cancellation."
1617
+ });
1618
+ continue;
1619
+ }
1620
+ let phase = "preparation";
1621
+ try {
1622
+ const plan = await prepareIssueUpdate(context, item);
1623
+ const desired = await desiredUpdateValues(context, plan);
1624
+ const before = await updateProjection(context, plan);
1625
+ if (JSON.stringify(before.readback) !== JSON.stringify(plan.currentContent))
1626
+ throw new DeliveryError("Native issue changed during batch preparation; reconcile the current state.");
1627
+ if (context.clients.rateLimitObservation?.() !== priorRateObservation)
1628
+ throw new DeliveryError("A native request exhausted its rate limit during batch preparation.");
1629
+ const changes = pendingUpdateValues(desired, before.values);
1630
+ if (Object.keys(changes).length === 0 || input.dryRun === true) {
1631
+ results.push({
1632
+ issueNumber: item.issueNumber,
1633
+ status: Object.keys(changes).length === 0 ? "unchanged" : "planned",
1634
+ changes,
1635
+ readback: before.readback,
1636
+ relatedReadback: before.values
1637
+ });
1638
+ continue;
1639
+ }
1640
+ phase = "application";
1641
+ await applyIssueUpdate(
1642
+ context,
1643
+ {
1644
+ ...plan,
1645
+ priorContent: { title: before.readback.title, body: before.readback.body }
1646
+ },
1647
+ changes
1648
+ );
1649
+ phase = "readback";
1650
+ const after = await updateProjection(context, plan);
1651
+ if (Object.keys(pendingUpdateValues(desired, after.values)).length)
1652
+ throw new DeliveryError("Native batch readback disagrees with the requested outcomes.");
1653
+ results.push({
1654
+ issueNumber: item.issueNumber,
1655
+ status: "applied",
1656
+ changes,
1657
+ readback: after.readback,
1658
+ relatedReadback: after.values
1659
+ });
1660
+ } catch (error) {
1661
+ const observed = context.clients.rateLimitObservation?.();
1662
+ const incomplete = getIncompleteIssueUpdate(error);
1663
+ const limit = getRateLimitDiagnostics(error) ?? incomplete?.rateLimit ?? (observed !== priorRateObservation ? observed : void 0);
1664
+ if (limit !== void 0) {
1665
+ limited = true;
1666
+ rateLimits.push(limit);
1667
+ }
1668
+ const diagnostics = getMachineRequestDiagnostics(error);
1669
+ const failed = {
1670
+ issueNumber: item.issueNumber,
1671
+ status: "failed",
1672
+ readback: null,
1673
+ reason: limit !== void 0 ? "GitHub rate limit exhausted; reconcile native state before retrying." : localBatchFailureReason(error) ?? `Issue update ${phase} failed; inspect native readback before retrying.`,
1674
+ ...diagnostics === void 0 ? {} : { diagnostics },
1675
+ ...incomplete === void 0 ? {} : { incomplete }
1676
+ };
1677
+ if (!limited && !signal?.aborted) {
1274
1678
  try {
1275
- const plan = await prepareIssueUpdate(context, item);
1276
- const desired = await desiredUpdateValues(context, plan);
1277
- const before = await updateProjection(context, plan);
1278
- if (JSON.stringify(before.readback) !== JSON.stringify(plan.currentContent))
1279
- throw new DeliveryError('Native issue changed during batch preparation; reconcile the current state.');
1280
- if (context.clients.rateLimitObservation?.() !== priorRateObservation)
1281
- throw new DeliveryError('A native request exhausted its rate limit during batch preparation.');
1282
- const changes = pendingUpdateValues(desired, before.values);
1283
- if (Object.keys(changes).length === 0 || input.dryRun === true) {
1284
- results.push({
1285
- issueNumber: item.issueNumber,
1286
- status: Object.keys(changes).length === 0 ? 'unchanged' : 'planned',
1287
- changes,
1288
- readback: before.readback,
1289
- relatedReadback: before.values,
1290
- });
1291
- continue;
1292
- }
1293
- phase = 'application';
1294
- await applyIssueUpdate(context, {
1295
- ...plan,
1296
- priorContent: { title: before.readback.title, body: before.readback.body },
1297
- });
1298
- phase = 'readback';
1299
- const after = await updateProjection(context, plan);
1300
- if (Object.keys(pendingUpdateValues(desired, after.values)).length)
1301
- throw new DeliveryError('Native batch readback disagrees with the requested outcomes.');
1302
- results.push({
1303
- issueNumber: item.issueNumber,
1304
- status: 'applied',
1305
- changes,
1306
- readback: after.readback,
1307
- relatedReadback: after.values,
1308
- });
1309
- }
1310
- catch (error) {
1311
- const observed = context.clients.rateLimitObservation?.();
1312
- const limit = getRateLimitDiagnostics(error) ?? (observed !== priorRateObservation ? observed : undefined);
1313
- if (limit !== undefined) {
1314
- limited = true;
1315
- rateLimits.push(limit);
1316
- }
1317
- const diagnostics = getMachineRequestDiagnostics(error);
1318
- const failed = {
1319
- issueNumber: item.issueNumber,
1320
- status: 'failed',
1321
- readback: null,
1322
- reason: limit !== undefined
1323
- ? 'GitHub rate limit exhausted; reconcile native state before retrying.'
1324
- : (localBatchFailureReason(error) ??
1325
- `Issue update ${phase} failed; inspect native readback before retrying.`),
1326
- ...(diagnostics === undefined ? {} : { diagnostics }),
1327
- };
1328
- if (!limited && !signal?.aborted) {
1329
- try {
1330
- failed.readback = await issueInfo(context, item.issueNumber);
1331
- }
1332
- catch (readbackError) {
1333
- const latest = context.clients.rateLimitObservation?.();
1334
- const readbackLimit = getRateLimitDiagnostics(readbackError) ?? (latest !== priorRateObservation ? latest : undefined);
1335
- if (readbackLimit !== undefined) {
1336
- limited = true;
1337
- rateLimits.push(readbackLimit);
1338
- }
1339
- failed.readbackError = 'Native issue readback unavailable; reconcile this existing issue before retrying.';
1340
- }
1341
- }
1342
- else
1343
- failed.readbackError = 'Readback deferred after rate-limit exhaustion or cancellation.';
1344
- results.push(failed);
1679
+ failed.readback = await issueInfo(context, item.issueNumber);
1680
+ } catch (readbackError) {
1681
+ const latest = context.clients.rateLimitObservation?.();
1682
+ const readbackLimit = getRateLimitDiagnostics(readbackError) ?? (latest !== priorRateObservation ? latest : void 0);
1683
+ if (readbackLimit !== void 0) {
1684
+ limited = true;
1685
+ rateLimits.push(readbackLimit);
1686
+ }
1687
+ failed.readbackError = "Native issue readback unavailable; reconcile this existing issue before retrying.";
1345
1688
  }
1689
+ } else failed.readbackError = "Readback deferred after rate-limit exhaustion or cancellation.";
1690
+ results.push(failed);
1346
1691
  }
1347
- return {
1348
- dryRun: input.dryRun === true,
1349
- results,
1350
- summary: {
1351
- total: results.length,
1352
- applied: results.filter((item) => item.status === 'applied').length,
1353
- planned: results.filter((item) => item.status === 'planned').length,
1354
- unchanged: results.filter((item) => item.status === 'unchanged').length,
1355
- failed: results.filter((item) => item.status === 'failed').length,
1356
- rateLimits,
1357
- },
1358
- };
1692
+ }
1693
+ return {
1694
+ dryRun: input.dryRun === true,
1695
+ results,
1696
+ summary: {
1697
+ total: results.length,
1698
+ applied: results.filter((item) => item.status === "applied").length,
1699
+ planned: results.filter((item) => item.status === "planned").length,
1700
+ unchanged: results.filter((item) => item.status === "unchanged").length,
1701
+ failed: results.filter((item) => item.status === "failed").length,
1702
+ rateLimits
1703
+ }
1704
+ };
1359
1705
  }
1360
- /** Complete the native tracking and Project state of an issue created before an interrupted response. */
1361
- export async function resumeCreatedIssue(context, input) {
1362
- // Tracking recovery must not trigger an unrelated first render omission and change the retry intent.
1363
- return updateIssue(context, { ...input, preserveHistory: input.preserveHistory ?? false });
1706
+ async function resumeCreatedIssue(context, input) {
1707
+ return updateIssue(context, { ...input, preserveHistory: input.preserveHistory ?? false });
1364
1708
  }
1365
- export async function issueInfo(context, issueNumber) {
1366
- const { clients, config, repo } = context;
1367
- const issue = (await clients.rest.issues.get({ issue_number: issueNumber, owner: repo.owner, repo: repo.repo })).data;
1368
- if ('pull_request' in issue)
1369
- throw new DeliveryError('Requested issue number is a pull request.');
1370
- const [nativeFields, relationships, project] = await Promise.all([
1371
- readIssueFieldCatalog(context).then((catalog) => readIssueFields(context, issueNumber, catalog)),
1372
- getNativeBlockerRelationships({ graphql: clients.graphql, issueNumber, repo }),
1373
- getIssueProjectStatus({
1374
- graphql: clients.graphql,
1375
- issueNodeId: issue.node_id,
1376
- org: config.native.organization,
1377
- ...(context.projectConfiguration ? { configuration: context.projectConfiguration } : {}),
1378
- settings: projectSettingsFromDeliveryConfig(config),
1379
- }),
1380
- ]);
1381
- const metadata = parseConfiguredNativeIssueMetadata(nativeFields.values, nativeIssueSettingsFromDeliveryConfig(config));
1382
- const info = {
1383
- ...deferralReadback(issue.body, issue.title),
1384
- ...(context.configuration ? { routing: context.configuration.routing } : {}),
1385
- blockedBy: relationships.blockers.filter((blocker) => blocker.state === 'OPEN').map((blocker) => blocker.number),
1386
- body: issue.body ?? '',
1387
- issueNumber,
1388
- issueType: issue.type?.name ?? null,
1389
- labels: (issue.labels ?? []).flatMap((label) => typeof label === 'string' ? [label] : label.name === undefined ? [] : [label.name]),
1390
- milestone: issue.milestone?.number ?? null,
1391
- fields: nativeFields.fields,
1392
- ...(nativeFields.catalog.some((field) => field.name === 'Start date' && field.data_type === 'date')
1393
- ? { startDate: nativeFields.fields['Start date'] }
1394
- : {}),
1395
- ...(nativeFields.catalog.some((field) => field.name === 'Target date' && field.data_type === 'date')
1396
- ? { targetDate: nativeFields.fields['Target date'] }
1397
- : {}),
1398
- parentIssueNumber: relationships.parentNumber,
1399
- ...(metadata.points === undefined ? {} : { points: metadata.points }),
1400
- ...(metadata.priority === undefined ? {} : { priority: metadata.priority }),
1401
- projectStatus: project?.status ?? null,
1402
- state: issue.state,
1403
- title: issue.title,
1404
- url: issue.html_url,
1405
- worktree: null,
1406
- };
1407
- return info;
1709
+ async function readIssueInfo(context, issueNumber, includeProject = true, expectedTarget, childDetail = true) {
1710
+ const { clients, config, repo } = context;
1711
+ const issue = (await clients.rest.issues.get({ issue_number: issueNumber, owner: repo.owner, repo: repo.repo })).data;
1712
+ if ("pull_request" in issue) throw new DeliveryError("Requested issue number is a pull request.");
1713
+ if (!includeProject && (issue.number !== issueNumber || issue.node_id !== expectedTarget?.nodeId || issue.html_url !== expectedTarget?.url || new URL(issue.html_url).pathname.toLowerCase() !== `/${repo.owner}/${repo.repo}/issues/${String(issueNumber)}`.toLowerCase()))
1714
+ throw new DeliveryError("Native closure readback returned a foreign issue identity.");
1715
+ const children = includeProject ? await readDirectIssueChildren(context, issueNumber, issue) : [];
1716
+ const strictRead = children.length > 0;
1717
+ const [nativeFields, relationships, project] = await Promise.all([
1718
+ readIssueNativeFields(context, issueNumber, strictRead),
1719
+ getNativeBlockerRelationships({
1720
+ graphql: clients.graphql,
1721
+ issueNumber,
1722
+ repo,
1723
+ ...context.readPageLimit === void 0 ? {} : { maxPages: context.readPageLimit, requireRepositoryIdentity: true, issueNodeId: issue.node_id }
1724
+ }),
1725
+ includeProject ? getIssueProjectStatus({
1726
+ graphql: clients.graphql,
1727
+ issueNodeId: issue.node_id,
1728
+ org: config.native.organization,
1729
+ ...context.readPageLimit === void 0 ? {} : { maxPages: context.readPageLimit },
1730
+ ...context.projectConfiguration ? { configuration: context.projectConfiguration } : {},
1731
+ settings: projectSettingsFromDeliveryConfig(config)
1732
+ }) : Promise.resolve(null)
1733
+ ]);
1734
+ const metadata = parseConfiguredNativeIssueMetadata(
1735
+ nativeFields.values,
1736
+ nativeIssueSettingsFromDeliveryConfig(config)
1737
+ );
1738
+ const info = {
1739
+ ...children.length ? {
1740
+ childProgress: childDetail ? await readChildProgress(context, children, nativeFields.catalog) : childCounts(children)
1741
+ } : {},
1742
+ ...deferralReadback(issue.body, issue.title),
1743
+ ...context.configuration ? { routing: context.configuration.routing } : {},
1744
+ blockedBy: relationships.blockers.filter((blocker) => blocker.state === "OPEN").map((blocker) => blocker.number),
1745
+ body: issue.body ?? "",
1746
+ issueNumber,
1747
+ issueType: issue.type?.name ?? null,
1748
+ labels: (issue.labels ?? []).flatMap(
1749
+ (label) => typeof label === "string" ? [label] : label.name === void 0 ? [] : [label.name]
1750
+ ),
1751
+ milestone: issue.milestone?.number ?? null,
1752
+ fields: nativeFields.fields,
1753
+ ...nativeFields.catalog.some((field) => field.name === "Start date" && field.data_type === "date") ? { startDate: nativeFields.fields["Start date"] } : {},
1754
+ ...nativeFields.catalog.some((field) => field.name === "Target date" && field.data_type === "date") ? { targetDate: nativeFields.fields["Target date"] } : {},
1755
+ parentIssueNumber: relationships.parentNumber,
1756
+ ...metadata.points === void 0 ? {} : { points: metadata.points },
1757
+ ...metadata.priority === void 0 ? {} : { priority: metadata.priority },
1758
+ projectStatus: project?.status ?? null,
1759
+ ...project?.review ? { inReview: true } : {},
1760
+ state: issue.state,
1761
+ title: issue.title,
1762
+ url: issue.html_url,
1763
+ worktree: null
1764
+ };
1765
+ return { info, issueNodeId: issue.node_id, issueNumber: issue.number };
1766
+ }
1767
+ async function issueInfo(context, issueNumber, options = {}) {
1768
+ return (await readIssueInfo(context, issueNumber, true, void 0, options.childDetail)).info;
1769
+ }
1770
+ function childCounts(children) {
1771
+ const closedChildCount = children.filter((child) => child.state === "closed").length;
1772
+ return {
1773
+ childCount: children.length,
1774
+ closedChildCount,
1775
+ percentClosed: Math.round(1e3 * closedChildCount / children.length) / 10
1776
+ };
1408
1777
  }
1409
- /** Invalid canonical content stays inspectable; omitted state is unknown, never an assertion of undeferred. */
1410
1778
  function deferralReadback(body, title) {
1411
- if (body === undefined)
1412
- return {};
1413
- try {
1414
- return { deferred: parseIssueBody(body ?? '', { title }).issue.deferral ?? null };
1415
- }
1416
- catch (error) {
1417
- if (!(error instanceof IssueValidationError))
1418
- throw error;
1419
- return {};
1420
- }
1779
+ if (body === void 0) return {};
1780
+ try {
1781
+ return { deferred: parseIssueBody(body ?? "", { title }).issue.deferral ?? null };
1782
+ } catch (error) {
1783
+ if (!(error instanceof IssueValidationError)) throw error;
1784
+ return {};
1785
+ }
1421
1786
  }
1422
- export async function listIssueSubissues(context, issueNumber) {
1423
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
1424
- if ('pull_request' in issue)
1425
- throw new DeliveryError('Requested issue number is a pull request.');
1426
- const children = await context.clients.rest.paginate(context.clients.rest.issues.listSubIssues, {
1427
- ...context.repo,
1428
- issue_number: issueNumber,
1429
- per_page: 100,
1787
+ const DirectIssueChild = z.object({
1788
+ id: z.number().int().positive().safe(),
1789
+ number: z.number().int().positive().safe(),
1790
+ node_id: z.string().min(1).refine((value) => value.trim() === value && value.trim().length > 0),
1791
+ state: z.enum(["open", "closed"]),
1792
+ url: z.url(),
1793
+ html_url: z.url(),
1794
+ repository_url: z.url()
1795
+ });
1796
+ async function readDirectIssueChildren(context, issueNumber, parent) {
1797
+ const children = [];
1798
+ const numbers = /* @__PURE__ */ new Set(), ids = /* @__PURE__ */ new Set(), nodes = /* @__PURE__ */ new Set();
1799
+ const repositoryPath = `/repos/${context.repo.owner}/${context.repo.repo}`;
1800
+ for (let page = 1; ; page += 1) {
1801
+ if (context.readPageLimit !== void 0 && page > context.readPageLimit)
1802
+ throw new CollectionLimitError({
1803
+ collection: "native-sub-issues",
1804
+ pagesRequested: page - 1,
1805
+ rowsObserved: children.length,
1806
+ limit: context.readPageLimit
1807
+ });
1808
+ const response = await context.clients.rest.issues.listSubIssues({
1809
+ ...context.repo,
1810
+ issue_number: issueNumber,
1811
+ page,
1812
+ per_page: 100
1430
1813
  });
1431
- return children.map((child) => child.number).sort((left, right) => left - right);
1814
+ const next = nativeReadNextPage(response, page, `${repositoryPath}/issues/${issueNumber}/sub_issues`);
1815
+ for (const raw of response.data) {
1816
+ if (Object.hasOwn(raw, "pull_request")) throw new DeliveryError("Parent progress child is a pull request.");
1817
+ const child = DirectIssueChild.parse(raw);
1818
+ if (child.number === issueNumber || child.id === parent.id || child.node_id === parent.node_id || numbers.has(child.number) || ids.has(child.id) || nodes.has(child.node_id))
1819
+ throw new DeliveryError("Parent progress has duplicate or self-referencing child identities.");
1820
+ for (const [value, host, path] of [
1821
+ [child.url, "api.github.com", `${repositoryPath}/issues/${child.number}`],
1822
+ [child.repository_url, "api.github.com", repositoryPath],
1823
+ [child.html_url, "github.com", `/${context.repo.owner}/${context.repo.repo}/issues/${child.number}`]
1824
+ ]) {
1825
+ const url = new URL(value);
1826
+ if (url.protocol !== "https:" || url.hostname !== host || url.port || url.username || url.password || url.search || url.hash || url.pathname.toLowerCase() !== path.toLowerCase())
1827
+ throw new DeliveryError("Parent progress child repository or issue-number identity disagrees.");
1828
+ }
1829
+ numbers.add(child.number);
1830
+ ids.add(child.id);
1831
+ nodes.add(child.node_id);
1832
+ children.push(child);
1833
+ }
1834
+ if (next === null) return children.sort((left, right) => left.number - right.number);
1835
+ }
1432
1836
  }
1433
- export async function readyCheck(context, issueNumber) {
1434
- const info = await issueInfo(context, issueNumber);
1435
- const trackingParent = await hasNativeSubIssues({ issueNumber, repo: context.repo, rest: context.clients.rest });
1436
- return evaluateAgentReadiness({
1437
- blockedBy: info.blockedBy,
1438
- body: info.body,
1439
- ...(info.points === undefined ? {} : { points: info.points }),
1440
- repoRoot: undefined,
1441
- title: info.title,
1442
- ...(info.issueType === null ? {} : { issueType: info.issueType }),
1443
- trackingParent,
1444
- });
1837
+ const READ_CONCURRENCY = 6;
1838
+ async function mapConcurrent(items, limit, read) {
1839
+ const results = [];
1840
+ let next = 0;
1841
+ await Promise.all(
1842
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
1843
+ while (next < items.length) {
1844
+ const index = next++;
1845
+ results[index] = await read(items[index]);
1846
+ }
1847
+ })
1848
+ );
1849
+ return results;
1445
1850
  }
1446
- export async function linkedIssueBranches(context, issueNumber) {
1447
- const branches = [];
1448
- const cursors = new Set();
1449
- let cursor = null;
1450
- for (let page = 0; page < 20; page++) {
1451
- const response = await context.clients.graphql('query DeliveryIssueBranches($owner:String!,$repo:String!,$issue:Int!,$cursor:String){repository(owner:$owner,name:$repo){issue(number:$issue){linkedBranches(first:100,after:$cursor){nodes{ref{name target{oid} repository{nameWithOwner}}} pageInfo{hasNextPage endCursor}}}}}', { owner: context.repo.owner, repo: context.repo.repo, issue: issueNumber, cursor });
1452
- const connection = response.repository?.issue?.linkedBranches;
1453
- if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean')
1454
- throw new DeliveryError('Incomplete GitHub linked issue branch readback.');
1455
- for (const node of connection.nodes) {
1456
- const ref = node?.ref;
1457
- if (!ref || !ref.name || !/^[a-f0-9]{40}$/u.test(ref.target.oid) || !ref.repository.nameWithOwner)
1458
- throw new DeliveryError('Incomplete GitHub linked branch identity.');
1459
- if (ref.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())
1460
- branches.push({ name: ref.name, sha: ref.target.oid, repository: ref.repository.nameWithOwner });
1461
- }
1462
- if (!connection.pageInfo.hasNextPage)
1463
- return branches;
1464
- const next = connection.pageInfo.endCursor;
1465
- if (!next || cursors.has(next))
1466
- throw new DeliveryError('GitHub linked branch pagination did not advance.');
1467
- cursors.add(next);
1468
- cursor = next;
1851
+ async function readChildProgress(context, children, catalog) {
1852
+ const date = catalog.find((field) => field.name === "Target date");
1853
+ if (date && date.data_type !== "date")
1854
+ throw new DeliveryError("Parent progress Target date has an incompatible type.");
1855
+ const pointField = catalog.find((field) => field.name === context.config.native.points.name);
1856
+ if (pointField && (String(pointField.id) !== context.config.native.points.databaseId || pointField.data_type !== "single_select"))
1857
+ throw new DeliveryError("Parent progress configured Points field identity or type disagrees.");
1858
+ const configuration = context.projectConfiguration ?? await getProjectDeliveryConfiguration({
1859
+ graphql: context.clients.graphql,
1860
+ org: context.config.native.organization,
1861
+ settings: projectSettingsFromDeliveryConfig(context.config),
1862
+ ...context.readPageLimit === void 0 ? {} : { maxPages: context.readPageLimit }
1863
+ });
1864
+ const progress = {
1865
+ childCount: children.length,
1866
+ closedChildCount: children.filter((child) => child.state === "closed").length,
1867
+ percentClosed: 0,
1868
+ pointsTotal: 0,
1869
+ inProgressChildren: [],
1870
+ nextTargetDate: null,
1871
+ missingPoints: [],
1872
+ missingProjectStatus: [],
1873
+ undatedOpenChildren: [],
1874
+ targetDateConfigured: date !== void 0
1875
+ };
1876
+ let pointsTotal = 0;
1877
+ const inProgress = [];
1878
+ const reads = await mapConcurrent(children, READ_CONCURRENCY, async (child) => {
1879
+ const [fields, status] = await Promise.all([
1880
+ readIssueFields(context, child.number, catalog, false, true),
1881
+ getIssueProjectStatus({
1882
+ graphql: context.clients.graphql,
1883
+ org: context.config.native.organization,
1884
+ issueNodeId: child.node_id,
1885
+ configuration,
1886
+ settings: projectSettingsFromDeliveryConfig(context.config),
1887
+ capacityRead: true,
1888
+ ...context.readPageLimit === void 0 ? {} : { maxPages: context.readPageLimit }
1889
+ })
1890
+ ]);
1891
+ return { fields, status };
1892
+ });
1893
+ for (const [index, child] of children.entries()) {
1894
+ const { fields, status } = reads[index];
1895
+ const points = fields.values.find(
1896
+ (field) => String(field.issue_field_id) === context.config.native.points.databaseId
1897
+ );
1898
+ if (!points || points.value === null && points.single_select_option == null)
1899
+ progress.missingPoints.push(child.number);
1900
+ else {
1901
+ const parsed = parseConfiguredNativeIssueMetadata(
1902
+ [points],
1903
+ nativeIssueSettingsFromDeliveryConfig(context.config)
1904
+ );
1905
+ if (parsed.points === void 0)
1906
+ throw new DeliveryError("Parent progress configured Points readback is missing.");
1907
+ pointsTotal += parsed.points;
1908
+ if (!Number.isSafeInteger(pointsTotal))
1909
+ throw new DeliveryError("Parent progress Points aggregate exceeds the safe integer range.");
1910
+ }
1911
+ if (status === null) progress.missingProjectStatus.push(child.number);
1912
+ else if (status.status === "In Progress") inProgress.push(child.number);
1913
+ if (child.state === "open") {
1914
+ const value = date === void 0 ? null : fields.fields["Target date"];
1915
+ if (typeof value !== "string") progress.undatedOpenChildren.push(child.number);
1916
+ else if (progress.nextTargetDate === null || value < progress.nextTargetDate) progress.nextTargetDate = value;
1469
1917
  }
1470
- throw new DeliveryError('GitHub linked issue branches exceed the bounded readback window.');
1918
+ }
1919
+ progress.percentClosed = Math.round(1e3 * progress.closedChildCount / progress.childCount) / 10;
1920
+ progress.pointsTotal = progress.missingPoints.length ? null : pointsTotal;
1921
+ progress.inProgressChildren = progress.missingProjectStatus.length ? null : inProgress;
1922
+ return progress;
1471
1923
  }
1472
- export async function issueBranch(context, issueNumber, selected) {
1473
- const branches = (await linkedIssueBranches(context, issueNumber)).filter((branch) => selected === undefined || branch.name === selected);
1474
- if (branches.length !== 1)
1475
- throw new DeliveryError('Select exactly one GitHub-linked issue branch; no local worktree or receipt fallback is available.');
1476
- return branches[0].name;
1924
+ async function listIssueSubissues(context, issueNumber) {
1925
+ const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
1926
+ if ("pull_request" in issue) throw new DeliveryError("Requested issue number is a pull request.");
1927
+ return (await readDirectIssueChildren(context, issueNumber, issue)).map((child) => child.number);
1477
1928
  }
1478
- export async function startIssueBranch(context, issueNumber, selected) {
1479
- const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
1480
- if (issue.number !== issueNumber || 'pull_request' in issue || issue.state !== 'open')
1481
- throw new DeliveryError('Start requires the requested open GitHub issue.');
1482
- const branches = await linkedIssueBranches(context, issueNumber);
1483
- const name = selected ?? (branches.length === 1 ? branches[0].name : `issue/${issueNumber}`);
1484
- if (!/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u.test(name) ||
1485
- name.startsWith('/') ||
1486
- name.endsWith('/') ||
1487
- name.endsWith('.lock'))
1488
- throw new DeliveryError('Invalid issue branch name.');
1489
- const existing = branches.filter((branch) => branch.name === name);
1490
- if (branches.length > 0 && existing.length !== 1)
1491
- throw new DeliveryError('Select exactly one existing GitHub-linked issue branch before start.');
1492
- if (existing.length > 1)
1493
- throw new DeliveryError('GitHub issue branch has conflicting linked matches.');
1494
- if (existing.length === 1)
1495
- return { issueNumber, issueUrl: issue.html_url, branch: name, headSha: existing[0].sha, reused: true };
1496
- const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
1497
- const base = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${repository.default_branch}` }))
1498
- .data.object.sha;
1499
- if (!/^[a-f0-9]{40}$/u.test(base) || !repository.node_id)
1500
- throw new DeliveryError('GitHub repository default branch identity is incomplete.');
1501
- await context.clients.graphql('mutation DeliveryStartBranch($input:CreateLinkedBranchInput!){createLinkedBranch(input:$input){linkedBranch{ref{name target{oid}}}}}', {
1502
- input: {
1503
- issueId: issue.node_id,
1504
- repositoryId: repository.node_id,
1505
- oid: base,
1506
- name,
1507
- clientMutationId: digestValue({ repository: context.config.repository, issueNumber, name, base }),
1508
- },
1929
+ async function readyCheck(context, issueNumber, onReadback) {
1930
+ const observation = await readIssueInfo(context, issueNumber);
1931
+ const { info } = observation;
1932
+ const trackingParent = await hasNativeSubIssues({
1933
+ issueNumber,
1934
+ repo: context.repo,
1935
+ rest: context.clients.rest,
1936
+ requireComplete: context.readPageLimit !== void 0
1937
+ });
1938
+ onReadback?.({ ...observation, trackingParent });
1939
+ return evaluateAgentReadiness({
1940
+ blockedBy: info.blockedBy,
1941
+ body: info.body,
1942
+ ...info.points === void 0 ? {} : { points: info.points },
1943
+ repoRoot: void 0,
1944
+ title: info.title,
1945
+ ...info.issueType === null ? {} : { issueType: info.issueType },
1946
+ trackingParent
1947
+ });
1948
+ }
1949
+ async function linkedIssueBranches(context, issueNumber) {
1950
+ const branches = [];
1951
+ const cursors = /* @__PURE__ */ new Set();
1952
+ let cursor = null;
1953
+ const limit = Math.min(context.readPageLimit ?? 20, 20);
1954
+ for (let page = 0; page < limit; page++) {
1955
+ const response = await context.clients.graphql(
1956
+ "query DeliveryIssueBranches($owner:String!,$repo:String!,$issue:Int!,$cursor:String){repository(owner:$owner,name:$repo){issue(number:$issue){linkedBranches(first:100,after:$cursor){nodes{ref{name target{oid} repository{nameWithOwner}}} pageInfo{hasNextPage endCursor}}}}}",
1957
+ { owner: context.repo.owner, repo: context.repo.repo, issue: issueNumber, cursor }
1958
+ );
1959
+ const connection = response.repository?.issue?.linkedBranches;
1960
+ if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== "boolean")
1961
+ throw new DeliveryError("Incomplete GitHub linked issue branch readback.");
1962
+ for (const node of connection.nodes) {
1963
+ const ref = node?.ref;
1964
+ if (!ref || !ref.name || !/^[a-f0-9]{40}$/u.test(ref.target.oid) || !ref.repository.nameWithOwner)
1965
+ throw new DeliveryError("Incomplete GitHub linked branch identity.");
1966
+ if (ref.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())
1967
+ branches.push({ name: ref.name, sha: ref.target.oid, repository: ref.repository.nameWithOwner });
1968
+ }
1969
+ if (!connection.pageInfo.hasNextPage) return branches;
1970
+ const next = connection.pageInfo.endCursor;
1971
+ if (!next || cursors.has(next)) throw new DeliveryError("GitHub linked branch pagination did not advance.");
1972
+ cursors.add(next);
1973
+ cursor = next;
1974
+ }
1975
+ if (context.readPageLimit !== void 0)
1976
+ throw new CollectionLimitError({
1977
+ collection: "linked-branches",
1978
+ pagesRequested: limit,
1979
+ rowsObserved: branches.length,
1980
+ limit
1509
1981
  });
1510
- const readback = (await linkedIssueBranches(context, issueNumber)).filter((branch) => branch.name === name);
1511
- if (readback.length !== 1 || readback[0].sha !== base)
1512
- throw new DeliveryError('Started GitHub branch/link readback disagrees; resume this issue without creating another.');
1513
- return { issueNumber, issueUrl: issue.html_url, branch: name, headSha: base, reused: false };
1982
+ throw new DeliveryError("GitHub linked issue branches exceed the bounded readback window.");
1514
1983
  }
1515
- /** Recheck native eligibility before an explicit start changes its selected Project. */
1516
- export async function startIssueProject(context, issueNumber, overrideReason) {
1517
- const readiness = await readyCheck(context, issueNumber);
1518
- if (!readiness.ready)
1519
- throw new IssueValidationError(readiness.failures);
1984
+ async function issueBranch(context, issueNumber, selected) {
1985
+ const linked = await linkedIssueBranches(context, issueNumber);
1986
+ const branches = linked.filter((branch) => selected === void 0 || branch.name === selected);
1987
+ if (linked.length === 0 && (selected === void 0 || selected === `issue/${issueNumber}`)) {
1520
1988
  const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
1521
- if (issue.number !== issueNumber || 'pull_request' in issue || issue.state !== 'open' || !issue.node_id)
1522
- throw new DeliveryError('Start requires the requested open GitHub issue before Project synchronization.');
1523
- return syncIssueProjectStatus({
1524
- graphql: context.clients.graphql,
1525
- issueNodeId: issue.node_id,
1526
- org: context.config.native.organization,
1527
- ...(context.projectConfiguration === undefined ? {} : { configuration: context.projectConfiguration }),
1528
- settings: projectSettingsFromDeliveryConfig(context.config),
1529
- status: 'In Progress',
1530
- beforeAdvance: async () => {
1531
- const eligible = await readyCheck(context, issueNumber);
1532
- if (!eligible.ready)
1533
- throw new IssueValidationError(eligible.failures);
1534
- await assertIssueStartCapacity(context, issueNumber, overrideReason, true);
1535
- const current = await issueInfo(context, issueNumber);
1536
- if (current.state !== 'open')
1537
- throw new DeliveryError('Start requires the requested open issue.');
1538
- const finalEligibility = await readyCheck(context, issueNumber);
1539
- if (!finalEligibility.ready)
1540
- throw new IssueValidationError(finalEligibility.failures);
1541
- },
1542
- });
1989
+ if (issue.number !== issueNumber || "pull_request" in issue || issue.state !== "open")
1990
+ throw new DeliveryError("Canonical issue branch requires its matching open GitHub issue.");
1991
+ const name = `issue/${issueNumber}`;
1992
+ const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${name}` })).data;
1993
+ if (ref.ref !== `refs/heads/${name}` || ref.object.type !== "commit" || !/^[a-f0-9]{40}$/u.test(ref.object.sha))
1994
+ throw new DeliveryError("Canonical issue branch head/ref readback is invalid.");
1995
+ return name;
1996
+ }
1997
+ if (branches.length !== 1) {
1998
+ const found = linked.map((branch) => branch.name).join(", ") || "none";
1999
+ throw new DeliveryError(
2000
+ selected === void 0 ? `Issue #${issueNumber} has no single linked branch (GitHub-linked: ${found}); pass the branch you pushed as headBranch.` : `Branch ${selected} is not linked to issue #${issueNumber} (GitHub-linked: ${found}); ${linked.length ? "select one of those" : `push the work as issue/${issueNumber}`}.`
2001
+ );
2002
+ }
2003
+ return branches[0].name;
1543
2004
  }
1544
- /** A complete observed-capacity guard, not a cross-writer GitHub transaction. */
1545
- export async function assertIssueStartCapacity(context, issueNumber, overrideReason, recordOverride = false) {
1546
- const lanes = WipLimits.parse(context.config.wipLimits ?? []).filter((lane) => lane.repository.toLowerCase() === context.config.repository.toLowerCase());
1547
- if (!lanes.length)
1548
- return undefined;
1549
- const configuration = context.projectConfiguration ??
1550
- (await getProjectDeliveryConfiguration({
1551
- graphql: context.clients.graphql,
1552
- org: context.config.native.organization,
1553
- settings: projectSettingsFromDeliveryConfig(context.config),
1554
- }));
1555
- const capacityContext = { ...context, projectConfiguration: configuration };
1556
- const reason = overrideReason === undefined ? undefined : OverrideReason.parse(overrideReason);
1557
- const publicReason = validateIssue({ title: 'WIP capacity override', legacyBody: reason ?? '', draft: true }, false);
1558
- if (publicReason.failures.length)
1559
- throw new IssueValidationError(publicReason.failures);
1560
- if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
1561
- throw new DeliveryError('WIP capacity repository identity disagrees with the selected repository.');
1562
- const configuredLabels = lanes.flatMap((lane) => ('label' in lane.match ? [lane.match.label] : []));
1563
- if (configuredLabels.length)
1564
- await labels(context, [...new Map(configuredLabels.map((label) => [label.toLowerCase(), label])).values()]);
1565
- const rows = [];
1566
- const seen = new Set();
1567
- for (let page = 1;; page++) {
1568
- if (page > 20)
1569
- throw new DeliveryError('WIP capacity issue pagination is incomplete.');
1570
- const batch = await listIssues(capacityContext, { state: 'open', page, perPage: 100 }, { capacityRead: true });
1571
- for (const row of batch.issues) {
1572
- if (seen.has(row.number))
1573
- throw new DeliveryError('WIP capacity repeats a native issue across pages.');
1574
- seen.add(row.number);
1575
- rows.push(row);
1576
- }
1577
- if (batch.nextPage === null)
1578
- break;
1579
- if (batch.nextPage !== page + 1)
1580
- throw new DeliveryError('WIP capacity pagination did not advance.');
2005
+ async function startIssueBranch(context, issueNumber, selected) {
2006
+ const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
2007
+ if (issue.number !== issueNumber || "pull_request" in issue || issue.state !== "open")
2008
+ throw new DeliveryError("Start requires the requested open GitHub issue.");
2009
+ const branches = await linkedIssueBranches(context, issueNumber);
2010
+ const name = selected ?? (branches.length === 1 ? branches[0].name : `issue/${issueNumber}`);
2011
+ if (!/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u.test(name) || name.startsWith("/") || name.endsWith("/") || name.endsWith(".lock"))
2012
+ throw new DeliveryError("Invalid issue branch name.");
2013
+ const existing = branches.filter((branch) => branch.name === name);
2014
+ if (branches.length > 0 && existing.length !== 1)
2015
+ throw new DeliveryError("Select exactly one existing GitHub-linked issue branch before start.");
2016
+ if (existing.length > 1) throw new DeliveryError("GitHub issue branch has conflicting linked matches.");
2017
+ if (existing.length === 1)
2018
+ return { issueNumber, issueUrl: issue.html_url, branch: name, headSha: existing[0].sha, reused: true };
2019
+ const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;
2020
+ const base = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${repository.default_branch}` })).data.object.sha;
2021
+ if (!/^[a-f0-9]{40}$/u.test(base) || !repository.node_id)
2022
+ throw new DeliveryError("GitHub repository default branch identity is incomplete.");
2023
+ await context.clients.graphql(
2024
+ "mutation DeliveryStartBranch($input:CreateLinkedBranchInput!){createLinkedBranch(input:$input){linkedBranch{ref{name target{oid}}}}}",
2025
+ {
2026
+ input: {
2027
+ issueId: issue.node_id,
2028
+ repositoryId: repository.node_id,
2029
+ oid: base,
2030
+ name,
2031
+ clientMutationId: digestValue({ repository: context.config.repository, issueNumber, name, base })
2032
+ }
1581
2033
  }
1582
- const target = rows.find((row) => row.number === issueNumber);
1583
- if (!target?.nodeId)
1584
- throw new DeliveryError('WIP capacity target is missing from the complete native issue readback.');
1585
- const matches = (lane, row) => {
1586
- if ('label' in lane.match) {
1587
- const selected = lane.match.label;
1588
- return row.labels.some((label) => label.toLowerCase() === selected.toLowerCase());
1589
- }
1590
- const { field, value } = lane.match;
1591
- if (!row.fieldIds?.[field] || row.fieldIds[field] !== target.fieldIds?.[field] || !Object.hasOwn(row.fields, field))
1592
- throw new DeliveryError(`WIP capacity native field ${field} is unknown or changed identity.`);
1593
- const observed = row.fields[field];
1594
- return Array.isArray(observed) ? typeof value === 'string' && observed.includes(value) : observed === value;
1595
- };
1596
- const observations = lanes.flatMap((lane) => {
1597
- // Validate every configured field across the full snapshot, even when the target does not match it.
1598
- const matching = rows.filter((row) => matches(lane, row));
1599
- if (!matches(lane, target))
1600
- return [];
1601
- const count = matching.filter((row) => row.projectStatus === 'In Progress').length;
1602
- return [
1603
- {
1604
- name: lane.name,
1605
- match: lane.match,
1606
- ...('field' in lane.match ? { fieldId: target.fieldIds[lane.match.field] } : {}),
1607
- count,
1608
- limit: lane.limit,
1609
- },
1610
- ];
1611
- });
1612
- const exceeded = target.projectStatus === 'In Progress' ? [] : observations.filter((lane) => lane.count + 1 > lane.limit);
1613
- if (exceeded.length && reason === undefined)
1614
- throw new DeliveryError(`WIP capacity limit exceeded: ${exceeded.map((lane) => `${lane.name} (${lane.count}/${lane.limit})`).join(', ')}. Supply overrideReason for a recorded capacity exception.`);
1615
- const evidence = {
1616
- schema: 'ai-delivery.wip-override@1',
1617
- repository: context.config.repository,
1618
- projectId: configuration.projectId,
1619
- issue: { number: issueNumber, id: target.nodeId },
1620
- observedStatus: target.projectStatus,
1621
- lanes: observations,
1622
- };
1623
- if (!evidence.projectId)
1624
- throw new DeliveryError('WIP capacity configured Project identity is unavailable.');
1625
- const snapshot = JSON.stringify(evidence);
1626
- if (exceeded.length && recordOverride) {
1627
- if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor)
1628
- throw new DeliveryError('WIP capacity override requires the authenticated configured author.');
1629
- const author = await context.clients.authenticatedAuthor();
1630
- if (!author.actorLogin || !author.credentialIdentity)
1631
- throw new DeliveryError('WIP capacity author identity is incomplete.');
1632
- const record = { ...evidence, author: author.actorLogin, reason };
1633
- const marker = `<!-- ai-delivery:wip-override@1:${digestValue(record)} -->`;
1634
- const body = `WIP capacity override.\n\n\`\`\`json\n${JSON.stringify(record, null, 2)}\n\`\`\`\n\n${marker}`;
1635
- const publicRecord = validateIssue({ title: 'WIP capacity override', legacyBody: body, draft: true }, false);
1636
- if (publicRecord.failures.length)
1637
- throw new IssueValidationError(publicRecord.failures);
1638
- await writeAuthenticatedIssueComment(context, { issueNumber, body }, undefined, marker);
1639
- const finalAuthor = await context.clients.authenticatedAuthor();
1640
- if (finalAuthor.actorLogin !== author.actorLogin || finalAuthor.credentialIdentity !== author.credentialIdentity)
1641
- throw new DeliveryError('WIP capacity override author changed during comment verification.');
1642
- if ((await assertIssueStartCapacity(context, issueNumber, reason)) !== snapshot)
1643
- throw new DeliveryError('WIP capacity changed while recording the override; inspect native state and resume this issue.');
2034
+ );
2035
+ const readback = (await linkedIssueBranches(context, issueNumber)).filter((branch) => branch.name === name);
2036
+ if (readback.length !== 1 || readback[0].sha !== base)
2037
+ throw new DeliveryError(
2038
+ "Started GitHub branch/link readback disagrees; resume this issue without creating another."
2039
+ );
2040
+ return { issueNumber, issueUrl: issue.html_url, branch: name, headSha: base, reused: false };
2041
+ }
2042
+ async function startIssueProject(context, issueNumber, overrideReason) {
2043
+ const readiness = await readyCheck(context, issueNumber);
2044
+ if (!readiness.ready) throw new IssueValidationError(readiness.failures);
2045
+ const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
2046
+ if (issue.number !== issueNumber || "pull_request" in issue || issue.state !== "open" || !issue.node_id)
2047
+ throw new DeliveryError("Start requires the requested open GitHub issue before Project synchronization.");
2048
+ return syncIssueProjectStatus({
2049
+ graphql: context.clients.graphql,
2050
+ issueNodeId: issue.node_id,
2051
+ org: context.config.native.organization,
2052
+ ...context.projectConfiguration === void 0 ? {} : { configuration: context.projectConfiguration },
2053
+ settings: projectSettingsFromDeliveryConfig(context.config),
2054
+ status: "In Progress",
2055
+ beforeAdvance: async () => {
2056
+ const eligible = await readyCheck(context, issueNumber);
2057
+ if (!eligible.ready) throw new IssueValidationError(eligible.failures);
2058
+ await assertIssueStartCapacity(context, issueNumber, overrideReason, true);
2059
+ const current = await issueInfo(context, issueNumber);
2060
+ if (current.state !== "open") throw new DeliveryError("Start requires the requested open issue.");
2061
+ const finalEligibility = await readyCheck(context, issueNumber);
2062
+ if (!finalEligibility.ready) throw new IssueValidationError(finalEligibility.failures);
2063
+ }
2064
+ });
2065
+ }
2066
+ async function assertIssueStartCapacity(context, issueNumber, overrideReason, recordOverride = false) {
2067
+ const lanes = WipLimits.parse(context.config.wipLimits ?? []).filter(
2068
+ (lane) => lane.repository.toLowerCase() === context.config.repository.toLowerCase()
2069
+ );
2070
+ if (!lanes.length) return void 0;
2071
+ const configuration = context.projectConfiguration ?? await getProjectDeliveryConfiguration({
2072
+ graphql: context.clients.graphql,
2073
+ org: context.config.native.organization,
2074
+ settings: projectSettingsFromDeliveryConfig(context.config),
2075
+ ...context.readPageLimit === void 0 ? {} : { maxPages: context.readPageLimit }
2076
+ });
2077
+ const capacityContext = { ...context, projectConfiguration: configuration };
2078
+ const reason = overrideReason === void 0 ? void 0 : OverrideReason.parse(overrideReason);
2079
+ const publicReason = validateIssue({ title: "WIP capacity override", legacyBody: reason ?? "", draft: true }, false);
2080
+ if (publicReason.failures.length) throw new IssueValidationError(publicReason.failures);
2081
+ if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
2082
+ throw new DeliveryError("WIP capacity repository identity disagrees with the selected repository.");
2083
+ const configuredLabels = lanes.flatMap((lane) => "label" in lane.match ? [lane.match.label] : []);
2084
+ if (configuredLabels.length)
2085
+ await labels(context, [...new Map(configuredLabels.map((label) => [label.toLowerCase(), label])).values()]);
2086
+ const rows = [];
2087
+ const seen = /* @__PURE__ */ new Set();
2088
+ for (let page = 1; ; page++) {
2089
+ if (context.readPageLimit !== void 0 && page > Math.min(context.readPageLimit, 20))
2090
+ throw new CollectionLimitError({
2091
+ collection: "wip-issues",
2092
+ pagesRequested: page - 1,
2093
+ rowsObserved: rows.length,
2094
+ limit: Math.min(context.readPageLimit, 20)
2095
+ });
2096
+ if (page > 20) throw new DeliveryError("WIP capacity issue pagination is incomplete.");
2097
+ const batch = await listIssues(capacityContext, { state: "open", page, perPage: 100 }, { capacityRead: true });
2098
+ for (const row of batch.issues) {
2099
+ if (seen.has(row.number)) throw new DeliveryError("WIP capacity repeats a native issue across pages.");
2100
+ seen.add(row.number);
2101
+ rows.push(row);
2102
+ }
2103
+ if (batch.nextPage === null) break;
2104
+ if (batch.nextPage !== page + 1) throw new DeliveryError("WIP capacity pagination did not advance.");
2105
+ }
2106
+ const target = rows.find((row) => row.number === issueNumber);
2107
+ if (!target?.nodeId)
2108
+ throw new DeliveryError("WIP capacity target is missing from the complete native issue readback.");
2109
+ const matches = (lane, row) => {
2110
+ if ("label" in lane.match) {
2111
+ const selected = lane.match.label;
2112
+ return row.labels.some((label) => label.toLowerCase() === selected.toLowerCase());
1644
2113
  }
1645
- return snapshot;
2114
+ const { field, value } = lane.match;
2115
+ if (!row.fieldIds?.[field] || row.fieldIds[field] !== target.fieldIds?.[field] || !Object.hasOwn(row.fields, field))
2116
+ throw new DeliveryError(`WIP capacity native field ${field} is unknown or changed identity.`);
2117
+ const observed = row.fields[field];
2118
+ return Array.isArray(observed) ? typeof value === "string" && observed.includes(value) : observed === value;
2119
+ };
2120
+ const observations = lanes.flatMap((lane) => {
2121
+ const matching = rows.filter((row) => matches(lane, row));
2122
+ if (!matches(lane, target)) return [];
2123
+ const count = matching.filter((row) => row.projectStatus === "In Progress").length;
2124
+ return [
2125
+ {
2126
+ name: lane.name,
2127
+ match: lane.match,
2128
+ ..."field" in lane.match ? { fieldId: target.fieldIds[lane.match.field] } : {},
2129
+ count,
2130
+ limit: lane.limit
2131
+ }
2132
+ ];
2133
+ });
2134
+ const exceeded = target.projectStatus === "In Progress" ? [] : observations.filter((lane) => lane.count + 1 > lane.limit);
2135
+ if (exceeded.length && reason === void 0)
2136
+ throw new DeliveryError(
2137
+ `WIP capacity limit exceeded: ${exceeded.map((lane) => `${lane.name} (${lane.count}/${lane.limit})`).join(", ")}. Supply overrideReason for a recorded capacity exception.`
2138
+ );
2139
+ const evidence = {
2140
+ schema: "ai-delivery.wip-override@1",
2141
+ repository: context.config.repository,
2142
+ projectId: configuration.projectId,
2143
+ issue: { number: issueNumber, id: target.nodeId },
2144
+ observedStatus: target.projectStatus,
2145
+ lanes: observations
2146
+ };
2147
+ if (!evidence.projectId) throw new DeliveryError("WIP capacity configured Project identity is unavailable.");
2148
+ const snapshot = JSON.stringify(evidence);
2149
+ if (exceeded.length && recordOverride) {
2150
+ if (context.clients.role !== "author" || !context.clients.authenticatedAuthor)
2151
+ throw new DeliveryError("WIP capacity override requires the authenticated configured author.");
2152
+ const author = await context.clients.authenticatedAuthor();
2153
+ if (!author.actorLogin || !author.credentialIdentity)
2154
+ throw new DeliveryError("WIP capacity author identity is incomplete.");
2155
+ const record = { ...evidence, author: author.actorLogin, reason };
2156
+ const marker = `<!-- ai-delivery:wip-override@1:${digestValue(record)} -->`;
2157
+ const body = `WIP capacity override.
2158
+
2159
+ \`\`\`json
2160
+ ${JSON.stringify(record, null, 2)}
2161
+ \`\`\`
2162
+
2163
+ ${marker}`;
2164
+ const publicRecord = validateIssue({ title: "WIP capacity override", legacyBody: body, draft: true }, false);
2165
+ if (publicRecord.failures.length) throw new IssueValidationError(publicRecord.failures);
2166
+ await writeAuthenticatedIssueComment(context, { issueNumber, body }, void 0, marker);
2167
+ const finalAuthor = await context.clients.authenticatedAuthor();
2168
+ if (finalAuthor.actorLogin !== author.actorLogin || finalAuthor.credentialIdentity !== author.credentialIdentity)
2169
+ throw new DeliveryError("WIP capacity override author changed during comment verification.");
2170
+ if (await assertIssueStartCapacity(context, issueNumber, reason) !== snapshot)
2171
+ throw new DeliveryError(
2172
+ "WIP capacity changed while recording the override; inspect native state and resume this issue."
2173
+ );
2174
+ }
2175
+ return snapshot;
1646
2176
  }
1647
- //# sourceMappingURL=issue.js.map
2177
+ export {
2178
+ CreatedTrackingIssueError,
2179
+ ISSUE_COMMENT_BODY_LIMIT2 as ISSUE_COMMENT_BODY_LIMIT,
2180
+ IssueUpdateIncompleteError,
2181
+ assertIssueStartCapacity,
2182
+ batchUpdateIssues,
2183
+ canonicalIssueBody,
2184
+ capacityNextPage,
2185
+ commentIssue,
2186
+ createIssue,
2187
+ getIncompleteIssueUpdate,
2188
+ issueBranch,
2189
+ issueInfo,
2190
+ journalIssueStart,
2191
+ linkedIssueBranches,
2192
+ listIssueSubissues,
2193
+ listIssues,
2194
+ loadDeliveryContext,
2195
+ readIssueClosure,
2196
+ readIssueNativeFields,
2197
+ readyCheck,
2198
+ renderIssueHistory,
2199
+ resumeCreatedIssue,
2200
+ startIssueBranch,
2201
+ startIssueProject,
2202
+ updateIssue
2203
+ };
2204
+ //# sourceMappingURL=issue.js.map