@aviaratech/ai-delivery 0.3.35 → 0.3.36

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