@aviaratech/ai-delivery 0.3.34 → 0.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -477
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,632 +1,1127 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync } from 'node:child_process';
3
- import { mkdtempSync, rmSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
6
- import { test } from 'vitest';
7
- import * as issue from './issue.js';
8
- import { getAiDeliveryMcpTool } from './mcp/tools.js';
9
- import { syntheticDiscoveryConfig } from './fixtures/discovery.js';
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { test } from "vitest";
7
+ import * as issue from "./issue.js";
8
+ import { getAiDeliveryMcpTool } from "./mcp/tools.js";
9
+ import { syntheticDiscoveryConfig } from "./fixtures/discovery.js";
10
+ import { getNativeBlockerRelationships } from "./github/relationships.js";
11
+ import * as projectDelivery from "./github/projectDelivery.js";
12
+ import { issueProjectItemsResponse } from "./fixtures/issueProjectItems.js";
10
13
  function updateFixture() {
11
- const root = mkdtempSync(join(tmpdir(), 'ai-delivery-history-'));
12
- execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: root });
13
- const events = [];
14
- const live = {
15
- number: 17,
16
- id: 117,
17
- node_id: 'ISSUE17',
18
- title: ' Prior <title>\r\n',
19
- body: '\nprior & body\t ',
20
- state: 'open',
21
- html_url: 'https://github.com/example/widget/issues/17',
22
- };
23
- const controls = {
24
- corruptComment: false,
25
- failUpdate: false,
26
- ignoreClosure: false,
27
- drift: false,
28
- targetPr: false,
29
- reason: null,
30
- duplicate: null,
31
- };
32
- const comments = [];
33
- const updates = [];
34
- let projectStatus = 'Active';
35
- const context = {
36
- root,
37
- repo: { owner: 'example', repo: 'widget' },
38
- config: syntheticDiscoveryConfig,
39
- projectConfiguration: { ...listingFixture().context.projectConfiguration, writable: true },
40
- clients: {
41
- role: 'author',
42
- authenticatedAuthor: async () => {
43
- events.push('author');
44
- return { actorLogin: 'operator', credentialIdentity: 'user:1' };
45
- },
46
- rest: {
47
- issues: {
48
- get: async (input) => ({
49
- data: input.issue_number === 17
50
- ? { ...live }
51
- : {
52
- number: input.issue_number,
53
- id: 118,
54
- html_url: `https://github.com/example/widget/issues/${String(input.issue_number)}`,
55
- ...(controls.targetPr ? { pull_request: {} } : {}),
56
- },
57
- }),
58
- listComments: async () => ({ data: comments }),
59
- createComment: async (input) => {
60
- events.push('comment');
61
- const id = 91 + comments.length;
62
- const data = {
63
- id,
64
- body: input.body,
65
- html_url: `https://github.com/example/widget/issues/17#issuecomment-${String(id)}`,
66
- user: { login: 'operator' },
67
- issue_url: 'https://api.github.com/repos/example/widget/issues/17',
68
- };
69
- comments.push(data);
70
- return { data };
71
- },
72
- getComment: async (input) => {
73
- events.push('comment-readback');
74
- if (controls.drift)
75
- live.body = 'Concurrent human edit';
76
- return {
77
- data: {
78
- ...comments.find((comment) => comment.id === input.comment_id),
79
- ...(controls.corruptComment ? { body: 'Wrong body' } : {}),
80
- },
81
- };
82
- },
83
- update: async (input) => {
84
- events.push('update');
85
- updates.push(input);
86
- if (controls.failUpdate)
87
- throw new Error('Update unavailable');
88
- if (typeof input.title === 'string')
89
- live.title = input.title;
90
- if (typeof input.body === 'string')
91
- live.body = input.body;
92
- if (!controls.ignoreClosure && typeof input.state === 'string') {
93
- live.state = input.state;
94
- controls.reason =
95
- input.state === 'closed'
96
- ? (typeof input.state_reason === 'string' ? input.state_reason : 'completed').toUpperCase()
97
- : 'REOPENED';
98
- if (input.duplicate_issue_id !== undefined)
99
- controls.duplicate = 18;
100
- }
101
- return { data: { ...live } };
102
- },
103
- },
104
- request: async () => ({ data: [] }),
105
- },
106
- graphql: async (query, variables) => {
107
- if (query.includes('IssueClosureReadback'))
108
- return {
109
- repository: {
110
- issue: {
111
- number: 17,
112
- repository: { nameWithOwner: 'example/widget' },
113
- state: live.state.toUpperCase(),
114
- stateReason: controls.reason,
115
- duplicateOf: controls.duplicate === null
116
- ? null
117
- : { number: controls.duplicate, repository: { nameWithOwner: 'example/widget' } },
118
- },
119
- },
120
- };
121
- if (query.includes('blockedBy(first:'))
122
- return {
123
- repository: {
124
- issue: { parent: null, blockedBy: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } },
125
- },
126
- };
127
- if (query.includes('ProjectDeliveryItems'))
128
- return {
129
- organization: {
130
- projectV2: {
131
- items: {
132
- nodes: [
133
- {
134
- id: 'ITEM17',
135
- isArchived: false,
136
- content: { id: 'ISSUE17' },
137
- fieldValueByName: {
138
- name: projectStatus,
139
- optionId: projectStatus === 'Active' ? 'ACTIVE' : projectStatus === 'Queued' ? 'TODO' : 'DONE',
140
- },
141
- },
142
- ],
143
- pageInfo: { hasNextPage: false, endCursor: null },
144
- },
145
- },
146
- },
147
- };
148
- if (query.includes('UpdateProjectDeliveryStatus')) {
149
- projectStatus =
150
- variables.optionId === 'DONE' ? 'Shipped' : variables.optionId === 'TODO' ? 'Queued' : 'Active';
151
- return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'ITEM17' } } };
152
- }
153
- if (query.includes('ProjectDeliveryItemReadback'))
154
- return {
155
- node: {
156
- id: 'ITEM17',
157
- isArchived: false,
158
- project: { id: 'PROJECT', number: 1 },
159
- content: { id: 'ISSUE17' },
160
- fieldValueByName: {
161
- name: projectStatus,
162
- optionId: projectStatus === 'Active' ? 'ACTIVE' : projectStatus === 'Queued' ? 'TODO' : 'DONE',
163
- },
164
- },
165
- };
166
- throw new Error(`Unexpected update fixture query: ${query}`);
167
- },
14
+ const root = mkdtempSync(join(tmpdir(), "ai-delivery-history-"));
15
+ execFileSync("git", ["init", "-q", "-b", "main"], { cwd: root });
16
+ const events = [];
17
+ const live = {
18
+ number: 17,
19
+ id: 117,
20
+ node_id: "ISSUE17",
21
+ title: " Prior <title>\r\n",
22
+ body: "\nprior & body ",
23
+ state: "open",
24
+ html_url: "https://github.com/example/widget/issues/17"
25
+ };
26
+ const controls = {
27
+ corruptComment: false,
28
+ failUpdate: false,
29
+ ignoreClosure: false,
30
+ drift: false,
31
+ targetPr: false,
32
+ reason: null,
33
+ duplicate: null,
34
+ archived: false,
35
+ archiveAfterUpdate: false,
36
+ projectUnavailableAfterUpdate: false,
37
+ nativeUnavailableAfterUpdate: false,
38
+ foreignAfterUpdate: false,
39
+ wrongNodeAfterUpdate: false,
40
+ driftAfterUpdate: false,
41
+ projectFailure: "",
42
+ nativeReadsAfterUpdate: 0,
43
+ failChildReadAfterUpdate: false,
44
+ childReadsAfterUpdate: 0
45
+ };
46
+ const comments = [];
47
+ const updates = [];
48
+ let projectStatus = "Active";
49
+ const context = {
50
+ root,
51
+ repo: { owner: "example", repo: "widget" },
52
+ config: syntheticDiscoveryConfig,
53
+ projectConfiguration: { ...listingFixture().context.projectConfiguration, writable: true },
54
+ clients: {
55
+ role: "author",
56
+ authenticatedAuthor: async () => {
57
+ events.push("author");
58
+ return { actorLogin: "operator", credentialIdentity: "user:1" };
59
+ },
60
+ rest: {
61
+ issues: {
62
+ listSubIssues: async () => {
63
+ if (updates.length) controls.childReadsAfterUpdate++;
64
+ if (updates.length && controls.failChildReadAfterUpdate) throw new Error("Child progress unavailable");
65
+ return { data: [] };
66
+ },
67
+ get: async (input) => {
68
+ if (updates.length) controls.nativeReadsAfterUpdate++;
69
+ if (updates.length && controls.nativeUnavailableAfterUpdate) throw new Error("Native unavailable");
70
+ return {
71
+ data: input.issue_number === 17 ? {
72
+ ...live,
73
+ ...updates.length && controls.wrongNodeAfterUpdate ? { node_id: "FOREIGN_ISSUE" } : {},
74
+ ...updates.length && controls.foreignAfterUpdate ? { html_url: "https://github.com/other/widget/issues/17" } : {},
75
+ ...updates.length && controls.driftAfterUpdate ? { body: "Concurrent later edit" } : {}
76
+ } : {
77
+ number: input.issue_number,
78
+ id: 118,
79
+ html_url: `https://github.com/example/widget/issues/${String(input.issue_number)}`,
80
+ ...controls.targetPr ? { pull_request: {} } : {}
81
+ }
82
+ };
83
+ },
84
+ listComments: async () => ({ data: comments }),
85
+ createComment: async (input) => {
86
+ events.push("comment");
87
+ const id = 91 + comments.length;
88
+ const data = {
89
+ id,
90
+ body: input.body,
91
+ html_url: `https://github.com/example/widget/issues/17#issuecomment-${String(id)}`,
92
+ user: { login: "operator" },
93
+ issue_url: "https://api.github.com/repos/example/widget/issues/17"
94
+ };
95
+ comments.push(data);
96
+ return { data };
97
+ },
98
+ getComment: async (input) => {
99
+ events.push("comment-readback");
100
+ if (controls.drift) live.body = "Concurrent human edit";
101
+ return {
102
+ data: {
103
+ ...comments.find((comment) => comment.id === input.comment_id),
104
+ ...controls.corruptComment ? { body: "Wrong body" } : {}
105
+ }
106
+ };
107
+ },
108
+ update: async (input) => {
109
+ events.push("update");
110
+ updates.push(input);
111
+ if (controls.failUpdate) throw new Error("Update unavailable");
112
+ if (controls.archiveAfterUpdate) controls.archived = true;
113
+ if (typeof input.title === "string") live.title = input.title;
114
+ if (typeof input.body === "string") live.body = input.body;
115
+ if (!controls.ignoreClosure && typeof input.state === "string") {
116
+ live.state = input.state;
117
+ controls.reason = input.state === "closed" ? (typeof input.state_reason === "string" ? input.state_reason : "completed").toUpperCase() : "REOPENED";
118
+ if (input.duplicate_issue_id !== void 0) controls.duplicate = 18;
119
+ }
120
+ return { data: { ...live } };
121
+ }
168
122
  },
169
- };
170
- return {
171
- context,
172
- live,
173
- controls,
174
- comments,
175
- events,
176
- updates,
177
- cleanup: () => rmSync(root, { recursive: true, force: true }),
178
- };
123
+ request: async () => ({ data: [] })
124
+ },
125
+ graphql: async (query, variables) => {
126
+ if (query.includes("ProjectDelivery") && updates.length && controls.projectFailure) {
127
+ if (controls.projectFailure === "cancel") throw new DOMException("Cancelled", "AbortError");
128
+ throw Object.assign(new Error("PRIVATE_RATE_CONTENT"), {
129
+ status: 429,
130
+ response: { headers: { "retry-after": "60" } }
131
+ });
132
+ }
133
+ if (query.includes("ProjectDelivery") && updates.length && controls.projectUnavailableAfterUpdate)
134
+ throw new Error("PRIVATE_REMOTE_CONTENT");
135
+ if (query.includes("IssueClosureReadback"))
136
+ return {
137
+ repository: {
138
+ issue: {
139
+ number: 17,
140
+ repository: { nameWithOwner: "example/widget" },
141
+ state: live.state.toUpperCase(),
142
+ stateReason: controls.reason,
143
+ duplicateOf: controls.duplicate === null ? null : { number: controls.duplicate, repository: { nameWithOwner: "example/widget" } }
144
+ }
145
+ }
146
+ };
147
+ if (query.includes("blockedBy(first:"))
148
+ return {
149
+ repository: {
150
+ issue: { parent: null, blockedBy: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } }
151
+ }
152
+ };
153
+ if (query.includes("ProjectDeliveryIssueItems"))
154
+ return issueProjectItemsResponse(variables, [
155
+ {
156
+ id: "ITEM17",
157
+ isArchived: controls.archived,
158
+ content: { id: "ISSUE17" },
159
+ fieldValueByName: {
160
+ name: projectStatus,
161
+ optionId: projectStatus === "Active" ? "ACTIVE" : projectStatus === "Queued" ? "TODO" : "DONE"
162
+ }
163
+ }
164
+ ]);
165
+ if (query.includes("UpdateProjectDeliveryStatus")) {
166
+ events.push("project-update");
167
+ projectStatus = variables.optionId === "DONE" ? "Shipped" : variables.optionId === "TODO" ? "Queued" : "Active";
168
+ return { updateProjectV2ItemFieldValue: { projectV2Item: { id: "ITEM17" } } };
169
+ }
170
+ if (query.includes("ProjectDeliveryItemReadback"))
171
+ return {
172
+ node: {
173
+ id: "ITEM17",
174
+ isArchived: false,
175
+ project: { id: "PROJECT", number: 1 },
176
+ content: { id: "ISSUE17" },
177
+ fieldValueByName: {
178
+ name: projectStatus,
179
+ optionId: projectStatus === "Active" ? "ACTIVE" : projectStatus === "Queued" ? "TODO" : "DONE"
180
+ }
181
+ }
182
+ };
183
+ throw new Error(`Unexpected update fixture query: ${query}`);
184
+ }
185
+ }
186
+ };
187
+ return {
188
+ context,
189
+ live,
190
+ controls,
191
+ comments,
192
+ events,
193
+ updates,
194
+ cleanup: () => rmSync(root, { recursive: true, force: true })
195
+ };
179
196
  }
180
- test('history preserves exact prior content before a rewrite and retries a failed mutation once', async () => {
181
- const fixture = updateFixture();
197
+ test("history preserves exact prior content before a rewrite and retries a failed mutation once", async () => {
198
+ const fixture = updateFixture();
199
+ try {
200
+ const oldTitle = fixture.live.title;
201
+ const oldBody = fixture.live.body;
202
+ fixture.controls.failUpdate = true;
203
+ const input = { issueNumber: 17, title: "New title", body: "New body", draft: true, preserveHistory: true };
204
+ await assert.rejects(issue.updateIssue(fixture.context, input), /Update unavailable/u);
205
+ assert.equal(fixture.comments.length, 1);
206
+ assert.equal(fixture.comments[0].body, issue.renderIssueHistory(oldTitle, oldBody));
207
+ assert.ok(fixture.events.indexOf("comment-readback") < fixture.events.indexOf("update"));
208
+ fixture.controls.failUpdate = false;
209
+ const result = await issue.updateIssue(fixture.context, input);
210
+ assert.equal(result.title, "New title");
211
+ assert.equal(result.conversion?.priorBody, oldBody);
212
+ assert.ok(oldBody.split("\n").every((line) => result.conversion?.diff.includes("-" + line)));
213
+ assert.match(result.body, /ai-delivery:issue@1/u);
214
+ assert.equal(fixture.comments.length, 1);
215
+ assert.equal(result.historyComment.reused, true);
216
+ await issue.updateIssue(fixture.context, input);
217
+ assert.equal(fixture.comments.length, 1, "a no-op rewrite adds no history");
218
+ } finally {
219
+ fixture.cleanup();
220
+ }
221
+ });
222
+ test.each([{ state: "closed" }, { state: "open" }, { title: "Retitled archived issue safely" }])(
223
+ "archived native update preserves the item and returns its identity: %j",
224
+ async (patch) => {
225
+ const f = updateFixture();
182
226
  try {
183
- const oldTitle = fixture.live.title;
184
- const oldBody = fixture.live.body;
185
- fixture.controls.failUpdate = true;
186
- const input = { issueNumber: 17, title: 'New title', body: 'New body', draft: true, preserveHistory: true };
187
- await assert.rejects(issue.updateIssue(fixture.context, input), /Update unavailable/u);
188
- assert.equal(fixture.comments.length, 1);
189
- assert.equal(fixture.comments[0].body, issue.renderIssueHistory(oldTitle, oldBody));
190
- assert.ok(fixture.events.indexOf('comment-readback') < fixture.events.indexOf('update'));
191
- fixture.controls.failUpdate = false;
192
- const result = await issue.updateIssue(fixture.context, input);
193
- assert.equal(result.title, 'New title');
194
- assert.equal(result.conversion?.priorBody, oldBody);
195
- assert.ok(oldBody.split('\n').every((line) => result.conversion?.diff.includes('-' + line)));
196
- assert.match(result.body, /ai-delivery:issue@1/u);
197
- assert.equal(fixture.comments.length, 1);
198
- assert.equal(result.historyComment.reused, true);
199
- await issue.updateIssue(fixture.context, input);
200
- assert.equal(fixture.comments.length, 1, 'a no-op rewrite adds no history');
201
- }
202
- finally {
203
- fixture.cleanup();
227
+ f.controls.archived = true;
228
+ if (patch.state === "open") f.live.state = "closed";
229
+ const result = await issue.updateIssue(f.context, { issueNumber: 17, ...patch });
230
+ assert.equal(f.live.state, patch.state ?? "open");
231
+ if (patch.title) assert.equal(f.live.title, patch.title);
232
+ assert.equal(f.controls.archived, true);
233
+ assert.equal(f.events.includes("project-update"), false);
234
+ assert.ok(result.warnings.some((w) => w.code === "project.archived" && w.message.includes("ITEM17")));
235
+ } finally {
236
+ f.cleanup();
204
237
  }
238
+ }
239
+ );
240
+ test("initially archived issue update refuses before history, closure or native writes", async () => {
241
+ const f = updateFixture();
242
+ try {
243
+ f.controls.archived = true;
244
+ await assert.rejects(
245
+ issue.updateIssue(f.context, {
246
+ issueNumber: 17,
247
+ body: "Replacement",
248
+ draft: true,
249
+ preserveHistory: true,
250
+ state: "closed",
251
+ closeReason: "not_planned"
252
+ }),
253
+ /archived/u
254
+ );
255
+ assert.deepEqual(f.updates, []);
256
+ assert.deepEqual(f.comments, []);
257
+ assert.equal(f.events.includes("project-update"), false);
258
+ assert.equal(f.live.state, "open");
259
+ } finally {
260
+ f.cleanup();
261
+ }
205
262
  });
206
- test('history overflow, invalid metadata, failed comment readback and concurrent edits prevent rewrites', async () => {
207
- for (const failure of ['overflow', 'labels', 'readback', 'drift']) {
208
- const fixture = updateFixture();
209
- try {
210
- if (failure === 'overflow')
211
- fixture.live.body = '&'.repeat(14000);
212
- if (failure === 'readback')
213
- fixture.controls.corruptComment = true;
214
- if (failure === 'drift')
215
- fixture.controls.drift = true;
216
- const oldBody = fixture.live.body;
217
- await assert.rejects(issue.updateIssue(fixture.context, {
218
- issueNumber: 17,
219
- body: 'Replacement',
220
- draft: true,
221
- preserveHistory: true,
222
- ...(failure === 'labels' ? { labels: ['invalid'] } : {}),
223
- }));
224
- assert.equal(fixture.updates.length, 0, failure);
225
- if (failure !== 'drift')
226
- assert.equal(fixture.live.body, oldBody);
227
- if (failure === 'overflow' || failure === 'labels')
228
- assert.equal(fixture.comments.length, 0);
229
- if (failure === 'overflow')
230
- assert.ok(!fixture.events.includes('author'));
231
- }
232
- finally {
233
- fixture.cleanup();
263
+ test.each(["archive", "unavailable"])(
264
+ "post-commit %s reports confirmed native content and closure separately from pending Project work",
265
+ async (failure) => {
266
+ const f = updateFixture();
267
+ try {
268
+ f.controls.archiveAfterUpdate = failure === "archive";
269
+ f.controls.projectUnavailableAfterUpdate = failure === "unavailable";
270
+ await assert.rejects(
271
+ issue.updateIssue(f.context, {
272
+ issueNumber: 17,
273
+ body: "Replacement",
274
+ draft: true,
275
+ preserveHistory: true,
276
+ state: "closed",
277
+ closeReason: "not_planned"
278
+ }),
279
+ (error) => {
280
+ const result = error.result;
281
+ assert.equal(result.status, "update-incomplete");
282
+ assert.equal(result.native.status, "confirmed");
283
+ assert.equal(result.native.repository, "example/widget");
284
+ assert.equal(result.native.readback.state, "closed");
285
+ assert.match(result.native.readback.body, /Replacement/u);
286
+ assert.equal(result.native.closure.closeReason, "not_planned");
287
+ assert.equal(result.native.historyComment.commentId, 91);
288
+ assert.equal(result.project.status, failure === "archive" ? "pending" : "unknown");
289
+ assert.equal(result.project.desiredStatus, "Done");
290
+ assert.equal(result.recovery.tool, "issue_batch_update");
291
+ assert.equal(JSON.stringify(result).includes("PRIVATE_"), false);
292
+ return true;
234
293
  }
294
+ );
295
+ assert.equal(f.updates.length, 1);
296
+ assert.equal(f.comments.length, 2);
297
+ } finally {
298
+ f.cleanup();
235
299
  }
300
+ }
301
+ );
302
+ test("native fallback confirms committed closure without requiring child progress", async () => {
303
+ const f = updateFixture();
304
+ try {
305
+ f.controls.archiveAfterUpdate = true;
306
+ f.controls.failChildReadAfterUpdate = true;
307
+ await assert.rejects(
308
+ issue.updateIssue(f.context, {
309
+ issueNumber: 17,
310
+ body: "Replacement",
311
+ draft: true,
312
+ state: "closed",
313
+ closeReason: "not_planned"
314
+ }),
315
+ (error) => {
316
+ const result = issue.getIncompleteIssueUpdate(error);
317
+ assert.equal(result?.native.status, "confirmed");
318
+ assert.equal(result?.native.readback?.state, "closed");
319
+ assert.match(result?.native.readback?.body ?? "", /Replacement/u);
320
+ assert.equal(result?.native.closure?.closeReason, "not_planned");
321
+ assert.equal(result?.native.readback?.childProgress, void 0);
322
+ return true;
323
+ }
324
+ );
325
+ assert.equal(f.updates.length, 1);
326
+ assert.equal(f.controls.childReadsAfterUpdate, 1);
327
+ } finally {
328
+ f.cleanup();
329
+ }
236
330
  });
237
- test('reasoned closure records supersession and verifies native reason and duplicate identity', async () => {
238
- for (const closeReason of ['completed', 'not_planned', 'duplicate']) {
239
- const fixture = updateFixture();
240
- try {
241
- const input = { issueNumber: 17, state: 'closed', draft: true, closeReason, supersededBy: 18 };
242
- const result = await issue.updateIssue(fixture.context, input);
243
- const closure = result.closure;
244
- assert.equal(result.state, 'closed');
245
- assert.equal(closure.closeReason, closeReason);
246
- assert.equal(closure.supersededBy, 18);
247
- assert.match(closure.comment.body, /example\/widget#18/u);
248
- assert.equal(fixture.updates[0].state_reason, closeReason);
249
- if (closeReason === 'duplicate') {
250
- assert.equal(fixture.updates[0].duplicate_issue_id, 118);
251
- assert.deepEqual(closure.duplicateOf, { number: 18, repository: 'example/widget' });
252
- }
253
- await issue.updateIssue(fixture.context, input);
254
- assert.equal(fixture.comments.length, 2, 'closure retries reuse authoritative comments');
255
- await assert.rejects(issue.updateIssue(fixture.context, {
256
- ...input,
257
- closeReason: closeReason === 'completed' ? 'not_planned' : 'completed',
258
- }), /already closed/u);
331
+ test.each(["unavailable", "foreign", "drift", "node"])(
332
+ "post-commit native %s evidence remains unknown",
333
+ async (failure) => {
334
+ const f = updateFixture();
335
+ try {
336
+ f.controls.archiveAfterUpdate = true;
337
+ f.controls.nativeUnavailableAfterUpdate = failure === "unavailable";
338
+ f.controls.foreignAfterUpdate = failure === "foreign";
339
+ f.controls.wrongNodeAfterUpdate = failure === "node";
340
+ f.controls.driftAfterUpdate = failure === "drift";
341
+ await assert.rejects(
342
+ issue.updateIssue(f.context, { issueNumber: 17, body: "Replacement", draft: true }),
343
+ (error) => {
344
+ const result = error.result;
345
+ assert.equal(result.native.status, "unknown");
346
+ assert.equal(result.native.readback, null);
347
+ return true;
259
348
  }
260
- finally {
261
- fixture.cleanup();
349
+ );
350
+ assert.equal(f.updates.length, 1);
351
+ } finally {
352
+ f.cleanup();
353
+ }
354
+ }
355
+ );
356
+ test.each(["rate-limit", "cancel"])(
357
+ "post-commit %s defers native readback without another request",
358
+ async (failure) => {
359
+ const f = updateFixture();
360
+ try {
361
+ f.controls.projectFailure = failure;
362
+ await assert.rejects(
363
+ issue.updateIssue(f.context, { issueNumber: 17, body: "Replacement", draft: true }),
364
+ (error) => {
365
+ const partial = issue.getIncompleteIssueUpdate(error);
366
+ assert.equal(partial?.native.status, "unknown");
367
+ assert.equal(partial?.native.readback, null);
368
+ if (failure === "rate-limit") assert.equal(partial?.rateLimit?.retryAfterSeconds, 60);
369
+ assert.equal(JSON.stringify(partial).includes("PRIVATE_"), false);
370
+ return true;
262
371
  }
372
+ );
373
+ assert.equal(f.controls.nativeReadsAfterUpdate, 1);
374
+ } finally {
375
+ f.cleanup();
263
376
  }
377
+ }
378
+ );
379
+ test("history overflow, invalid metadata, failed comment readback and concurrent edits prevent rewrites", async () => {
380
+ for (const failure of ["overflow", "labels", "readback", "drift"]) {
381
+ const fixture = updateFixture();
382
+ try {
383
+ if (failure === "overflow") fixture.live.body = "&".repeat(14e3);
384
+ if (failure === "readback") fixture.controls.corruptComment = true;
385
+ if (failure === "drift") fixture.controls.drift = true;
386
+ const oldBody = fixture.live.body;
387
+ await assert.rejects(
388
+ issue.updateIssue(fixture.context, {
389
+ issueNumber: 17,
390
+ body: "Replacement",
391
+ draft: true,
392
+ preserveHistory: true,
393
+ ...failure === "labels" ? { labels: ["invalid"] } : {}
394
+ })
395
+ );
396
+ assert.equal(fixture.updates.length, 0, failure);
397
+ if (failure !== "drift") assert.equal(fixture.live.body, oldBody);
398
+ if (failure === "overflow" || failure === "labels") assert.equal(fixture.comments.length, 0);
399
+ if (failure === "overflow") assert.ok(!fixture.events.includes("author"));
400
+ } finally {
401
+ fixture.cleanup();
402
+ }
403
+ }
264
404
  });
265
- test('invalid superseding issues and contradictory native closure fail closed', async () => {
266
- for (const failure of ['self', 'pull-request', 'reason', 'duplicate']) {
267
- const fixture = updateFixture();
268
- try {
269
- fixture.controls.targetPr = failure === 'pull-request';
270
- fixture.controls.ignoreClosure = failure === 'reason';
271
- if (failure === 'duplicate') {
272
- fixture.live.state = 'closed';
273
- fixture.controls.reason = 'DUPLICATE';
274
- fixture.controls.duplicate = 19;
275
- }
276
- await assert.rejects(issue.updateIssue(fixture.context, {
277
- issueNumber: 17,
278
- state: 'closed',
279
- draft: true,
280
- closeReason: failure === 'duplicate' ? 'duplicate' : 'completed',
281
- supersededBy: failure === 'self' ? 17 : 18,
282
- }));
283
- if (failure !== 'reason') {
284
- assert.equal(fixture.updates.length, 0);
285
- assert.equal(fixture.comments.length, 0);
286
- }
287
- }
288
- finally {
289
- fixture.cleanup();
290
- }
405
+ test("reasoned closure records supersession and verifies native reason and duplicate identity", async () => {
406
+ for (const closeReason of ["completed", "not_planned", "duplicate"]) {
407
+ const fixture = updateFixture();
408
+ try {
409
+ const input = { issueNumber: 17, state: "closed", draft: true, closeReason, supersededBy: 18 };
410
+ const result = await issue.updateIssue(fixture.context, input);
411
+ const closure = result.closure;
412
+ assert.equal(result.state, "closed");
413
+ assert.equal(closure.closeReason, closeReason);
414
+ assert.equal(closure.supersededBy, 18);
415
+ assert.match(closure.comment.body, /example\/widget#18/u);
416
+ assert.equal(fixture.updates[0].state_reason, closeReason);
417
+ if (closeReason === "duplicate") {
418
+ assert.equal(fixture.updates[0].duplicate_issue_id, 118);
419
+ assert.deepEqual(closure.duplicateOf, { number: 18, repository: "example/widget" });
420
+ }
421
+ await issue.updateIssue(fixture.context, input);
422
+ assert.equal(fixture.comments.length, 2, "closure retries reuse authoritative comments");
423
+ await assert.rejects(
424
+ issue.updateIssue(fixture.context, {
425
+ ...input,
426
+ closeReason: closeReason === "completed" ? "not_planned" : "completed"
427
+ }),
428
+ /already closed/u
429
+ );
430
+ } finally {
431
+ fixture.cleanup();
291
432
  }
433
+ }
434
+ });
435
+ test("invalid superseding issues and contradictory native closure fail closed", async () => {
436
+ for (const failure of ["self", "pull-request", "reason", "duplicate"]) {
437
+ const fixture = updateFixture();
438
+ try {
439
+ fixture.controls.targetPr = failure === "pull-request";
440
+ fixture.controls.ignoreClosure = failure === "reason";
441
+ if (failure === "duplicate") {
442
+ fixture.live.state = "closed";
443
+ fixture.controls.reason = "DUPLICATE";
444
+ fixture.controls.duplicate = 19;
445
+ }
446
+ await assert.rejects(
447
+ issue.updateIssue(fixture.context, {
448
+ issueNumber: 17,
449
+ state: "closed",
450
+ draft: true,
451
+ closeReason: failure === "duplicate" ? "duplicate" : "completed",
452
+ supersededBy: failure === "self" ? 17 : 18
453
+ })
454
+ );
455
+ if (failure !== "reason") {
456
+ assert.equal(fixture.updates.length, 0);
457
+ assert.equal(fixture.comments.length, 0);
458
+ }
459
+ } finally {
460
+ fixture.cleanup();
461
+ }
462
+ }
292
463
  });
293
464
  const listIssues = issue.listIssues;
294
465
  function listingFixture(options = {}) {
295
- const requests = [];
296
- const context = {
297
- root: '/synthetic',
298
- repo: { owner: 'example', repo: 'widget' },
299
- config: syntheticDiscoveryConfig,
300
- projectConfiguration: {
301
- projectId: 'PROJECT',
302
- projectNumber: 1,
303
- title: 'Delivery',
304
- writable: false,
305
- pointsFieldId: 'POINTS',
306
- priorityFieldId: 'PRIORITY',
307
- statusFieldId: 'STATUS',
308
- statusOptionIds: { Todo: 'TODO', 'In Progress': 'ACTIVE', Blocked: 'BLOCKED', Done: 'DONE' },
309
- settings: {
310
- number: 1,
311
- title: 'Delivery',
312
- statusField: 'Flow',
313
- statuses: { Todo: 'Queued', 'In Progress': 'Active', Blocked: 'Waiting', Done: 'Shipped' },
314
- },
466
+ const requests = [];
467
+ const context = {
468
+ root: "/synthetic",
469
+ repo: { owner: "example", repo: "widget" },
470
+ config: syntheticDiscoveryConfig,
471
+ projectConfiguration: {
472
+ projectId: "PROJECT",
473
+ projectNumber: 1,
474
+ title: "Delivery",
475
+ writable: false,
476
+ pointsFieldId: "POINTS",
477
+ priorityFieldId: "PRIORITY",
478
+ statusFieldId: "STATUS",
479
+ statusOptionIds: { Todo: "TODO", "In Progress": "ACTIVE", Blocked: "BLOCKED", Done: "DONE" },
480
+ settings: {
481
+ number: 1,
482
+ title: "Delivery",
483
+ statusField: "Flow",
484
+ statuses: { Todo: "Queued", "In Progress": "Active", Blocked: "Waiting", Done: "Shipped" }
485
+ }
486
+ },
487
+ clients: {
488
+ rest: {
489
+ issues: {
490
+ listForRepo: async (params) => {
491
+ requests.push(params);
492
+ return {
493
+ data: [
494
+ {
495
+ number: 17,
496
+ node_id: "ISSUE17",
497
+ title: "Repair widget",
498
+ state: "open",
499
+ labels: [{ name: "area:widget" }],
500
+ type: { name: "Task" },
501
+ html_url: options.foreign ? "https://github.com/elsewhere/widget/issues/17" : "https://github.com/example/widget/issues/17",
502
+ updated_at: "2026-10-07T00:00:00Z"
503
+ },
504
+ { number: 18, pull_request: {} }
505
+ ]
506
+ };
507
+ }
315
508
  },
316
- clients: {
317
- rest: {
318
- issues: {
319
- listForRepo: async (params) => {
320
- requests.push(params);
321
- return {
322
- data: [
323
- {
324
- number: 17,
325
- node_id: 'ISSUE17',
326
- title: 'Repair widget',
327
- state: 'open',
328
- labels: [{ name: 'area:widget' }],
329
- type: { name: 'Task' },
330
- html_url: options.foreign
331
- ? 'https://github.com/elsewhere/widget/issues/17'
332
- : 'https://github.com/example/widget/issues/17',
333
- updated_at: '2026-10-07T00:00:00Z',
334
- },
335
- { number: 18, pull_request: {} },
336
- ],
337
- };
338
- },
509
+ search: {
510
+ issuesAndPullRequests: async (params) => {
511
+ requests.push(params);
512
+ return { data: { total_count: 0, incomplete_results: options.incomplete ?? false, items: [] } };
513
+ }
514
+ },
515
+ request: async (route, params) => {
516
+ requests.push({ route, ...params });
517
+ if (route.includes("/orgs/"))
518
+ return {
519
+ data: [
520
+ { id: 101, name: "Estimate", data_type: "single_select" },
521
+ { id: 102, name: "Urgency", data_type: "single_select" },
522
+ { id: 103, name: "Start date", data_type: "date" },
523
+ ...options.missingMulti ? [{ id: 104, name: "Tags", data_type: "multi_select" }] : []
524
+ ]
525
+ };
526
+ return {
527
+ data: [
528
+ {
529
+ issue_field_id: 101,
530
+ issue_field_name: options.invalidField ? "Foreign estimate" : "Estimate",
531
+ data_type: "single_select",
532
+ value: 44,
533
+ ...options.missingOption ? {} : { single_select_option: { id: 44, name: "4" } }
534
+ },
535
+ { issue_field_id: 103, issue_field_name: "Start date", data_type: "date", value: "2026-10-07" },
536
+ ...options.missingMulti ? [{ issue_field_id: 104, issue_field_name: "Tags", data_type: "multi_select", value: "one" }] : []
537
+ ]
538
+ };
539
+ }
540
+ },
541
+ graphql: async (query, variables) => {
542
+ if (query.includes("blockedBy(first:"))
543
+ return {
544
+ repository: {
545
+ issue: {
546
+ parent: {
547
+ id: "PARENT9",
548
+ number: 9,
549
+ repository: { nameWithOwner: options.foreignParent ? "example/other" : "example/widget" }
339
550
  },
340
- search: {
341
- issuesAndPullRequests: async (params) => {
342
- requests.push(params);
343
- return { data: { total_count: 0, incomplete_results: options.incomplete ?? false, items: [] } };
551
+ blockedBy: {
552
+ nodes: [
553
+ {
554
+ id: "BLOCKER8",
555
+ number: 8,
556
+ title: "Prerequisite",
557
+ state: "CLOSED",
558
+ repository: { nameWithOwner: "example/widget" }
344
559
  },
345
- },
346
- request: async (route, params) => {
347
- requests.push({ route, ...params });
348
- if (route.includes('/orgs/'))
349
- return {
350
- data: [
351
- { id: 101, name: 'Estimate', data_type: 'single_select' },
352
- { id: 102, name: 'Urgency', data_type: 'single_select' },
353
- { id: 103, name: 'Start date', data_type: 'date' },
354
- ...(options.missingMulti ? [{ id: 104, name: 'Tags', data_type: 'multi_select' }] : []),
355
- ],
356
- };
357
- return {
358
- data: [
359
- {
360
- issue_field_id: 101,
361
- issue_field_name: options.invalidField ? 'Foreign estimate' : 'Estimate',
362
- data_type: 'single_select',
363
- value: 44,
364
- ...(options.missingOption ? {} : { single_select_option: { id: 44, name: '4' } }),
365
- },
366
- { issue_field_id: 103, issue_field_name: 'Start date', data_type: 'date', value: '2026-10-07' },
367
- ...(options.missingMulti
368
- ? [{ issue_field_id: 104, issue_field_name: 'Tags', data_type: 'multi_select', value: 'one' }]
369
- : []),
370
- ],
371
- };
372
- },
373
- },
374
- graphql: async (query) => {
375
- if (query.includes('blockedBy(first:'))
376
- return {
377
- repository: {
378
- issue: {
379
- parent: {
380
- id: 'PARENT9',
381
- number: 9,
382
- repository: { nameWithOwner: options.foreignParent ? 'example/other' : 'example/widget' },
383
- },
384
- blockedBy: {
385
- nodes: [
386
- {
387
- id: 'BLOCKER8',
388
- number: 8,
389
- title: 'Prerequisite',
390
- state: 'CLOSED',
391
- repository: { nameWithOwner: 'example/widget' },
392
- },
393
- ...(options.dualBlockers
394
- ? [
395
- {
396
- id: 'FOREIGN8',
397
- number: 8,
398
- title: 'Other prerequisite',
399
- state: 'OPEN',
400
- repository: { nameWithOwner: 'example/other' },
401
- },
402
- ]
403
- : []),
404
- ],
405
- pageInfo: { hasNextPage: false, endCursor: null },
406
- },
407
- },
408
- },
409
- };
410
- if (query.includes('ProjectDeliveryItems'))
411
- return {
412
- organization: {
413
- projectV2: {
414
- items: {
415
- nodes: [
416
- {
417
- id: 'ITEM17',
418
- isArchived: false,
419
- content: { id: 'ISSUE17' },
420
- fieldValueByName: { name: 'Active', optionId: 'ACTIVE' },
421
- },
422
- ],
423
- pageInfo: { hasNextPage: false, endCursor: null },
424
- },
425
- },
426
- },
427
- };
428
- throw new Error('Unexpected query');
429
- },
430
- },
431
- };
432
- return { context, requests };
560
+ ...options.dualBlockers ? [
561
+ {
562
+ id: "FOREIGN8",
563
+ number: 8,
564
+ title: "Other prerequisite",
565
+ state: "OPEN",
566
+ repository: { nameWithOwner: "example/other" }
567
+ }
568
+ ] : []
569
+ ],
570
+ pageInfo: { hasNextPage: false, endCursor: null }
571
+ }
572
+ }
573
+ }
574
+ };
575
+ if (query.includes("ProjectDeliveryIssueItems"))
576
+ return issueProjectItemsResponse(variables, [
577
+ {
578
+ id: "ITEM17",
579
+ isArchived: false,
580
+ content: { id: "ISSUE17" },
581
+ fieldValueByName: { name: "Active", optionId: "ACTIVE" }
582
+ }
583
+ ]);
584
+ throw new Error("Unexpected query");
585
+ }
586
+ }
587
+ };
588
+ return { context, requests };
433
589
  }
434
- test('typed listing filters stay repository-bound and expose named fields without identifiers', async () => {
435
- const tool = getAiDeliveryMcpTool('issue_list');
436
- assert.ok(tool, 'issue_list is registered');
437
- const input = tool.inputSchema.parse({
438
- state: 'open',
439
- labels: ['area:widget'],
440
- parentIssueNumber: 9,
441
- issueType: 'Task',
442
- projectStatus: 'In Progress',
443
- updatedSince: '2026-10-01T00:00:00Z',
444
- perPage: 2,
445
- });
446
- const { context, requests } = listingFixture();
447
- const result = await listIssues(context, input);
448
- assert.equal(result.nextPage, 2);
449
- assert.deepEqual(result.issues, [
450
- {
451
- number: 17,
452
- title: 'Repair widget',
453
- state: 'open',
454
- labels: ['area:widget'],
455
- issueType: 'Task',
456
- parentIssueNumber: 9,
457
- parent: { repository: 'example/widget', number: 9 },
458
- blockers: [{ repository: 'example/widget', number: 8, title: 'Prerequisite', state: 'CLOSED' }],
459
- projectStatus: 'In Progress',
460
- fields: { Estimate: '4', Urgency: null, 'Start date': '2026-10-07' },
461
- url: 'https://github.com/example/widget/issues/17',
462
- updatedAt: '2026-10-07T00:00:00Z',
463
- },
464
- ]);
465
- assert.equal(requests[0]?.owner, 'example');
466
- assert.equal(requests[0]?.since, '2026-10-01T00:00:00Z');
467
- assert.equal(JSON.stringify(result).includes('BLOCKER8'), false);
590
+ test("typed listing filters stay repository-bound and expose named fields without identifiers", async () => {
591
+ const tool = getAiDeliveryMcpTool("issue_list");
592
+ assert.ok(tool, "issue_list is registered");
593
+ const input = tool.inputSchema.parse({
594
+ state: "open",
595
+ labels: ["area:widget"],
596
+ parentIssueNumber: 9,
597
+ issueType: "Task",
598
+ projectStatus: "In Progress",
599
+ updatedSince: "2026-10-01T00:00:00Z",
600
+ perPage: 2
601
+ });
602
+ const { context, requests } = listingFixture();
603
+ const result = await listIssues(context, input);
604
+ assert.equal(result.nextPage, 2);
605
+ assert.deepEqual(result.issues, [
606
+ {
607
+ number: 17,
608
+ title: "Repair widget",
609
+ state: "open",
610
+ labels: ["area:widget"],
611
+ issueType: "Task",
612
+ parentIssueNumber: 9,
613
+ parent: { repository: "example/widget", number: 9 },
614
+ blockers: [{ repository: "example/widget", number: 8, title: "Prerequisite", state: "CLOSED" }],
615
+ projectStatus: "In Progress",
616
+ fields: { Estimate: "4", Urgency: null, "Start date": "2026-10-07" },
617
+ url: "https://github.com/example/widget/issues/17",
618
+ updatedAt: "2026-10-07T00:00:00Z"
619
+ }
620
+ ]);
621
+ assert.equal(requests[0]?.owner, "example");
622
+ assert.equal(requests[0]?.since, "2026-10-01T00:00:00Z");
623
+ assert.equal(JSON.stringify(result).includes("BLOCKER8"), false);
468
624
  });
469
- test('search quotes user text so it cannot change the selected repository', async () => {
470
- const tool = getAiDeliveryMcpTool('issue_search');
471
- assert.ok(tool, 'issue_search is registered');
472
- const input = tool.inputSchema.parse({ query: 'repo:elsewhere/project', page: 2, perPage: 10 });
473
- const { context, requests } = listingFixture();
474
- const result = await listIssues(context, input);
475
- assert.equal(result.nextPage, null);
476
- assert.equal(requests[0]?.q, 'repo:example/widget is:issue "repo:elsewhere/project"');
625
+ test("search quotes user text so it cannot change the selected repository", async () => {
626
+ const tool = getAiDeliveryMcpTool("issue_search");
627
+ assert.ok(tool, "issue_search is registered");
628
+ const input = tool.inputSchema.parse({ query: "repo:elsewhere/project", page: 2, perPage: 10 });
629
+ const { context, requests } = listingFixture();
630
+ const result = await listIssues(context, input);
631
+ assert.equal(result.nextPage, null);
632
+ assert.equal(requests[0]?.q, 'repo:example/widget is:issue "repo:elsewhere/project"');
477
633
  });
478
- test('update accepts history and reasoned closure while rejecting incoherent requests', () => {
479
- const tool = getAiDeliveryMcpTool('issue_update');
480
- assert.ok(tool);
481
- assert.equal(tool.inputSchema.safeParse({ issueNumber: 17, body: 'new body', preserveHistory: true }).success, true);
482
- assert.equal(tool.inputSchema.safeParse({ issueNumber: 17, state: 'closed', closeReason: 'duplicate', supersededBy: 9 }).success, true);
483
- assert.throws(() => tool.inputSchema.safeParse({ issueNumber: 17, state: 'open', closeReason: 'completed' }), /Closure details require state closed/u);
634
+ test("update accepts history and reasoned closure while rejecting incoherent requests", () => {
635
+ const tool = getAiDeliveryMcpTool("issue_update");
636
+ assert.ok(tool);
637
+ assert.equal(tool.inputSchema.safeParse({ issueNumber: 17, body: "new body", preserveHistory: true }).success, true);
638
+ assert.equal(
639
+ tool.inputSchema.safeParse({ issueNumber: 17, state: "closed", closeReason: "duplicate", supersededBy: 9 }).success,
640
+ true
641
+ );
642
+ assert.throws(
643
+ () => tool.inputSchema.safeParse({ issueNumber: 17, state: "open", closeReason: "completed" }),
644
+ /"code":"closure.state"/u
645
+ );
484
646
  });
485
- test('local filters retain pagination when the current GitHub page has no matching issue', async () => {
486
- const { context } = listingFixture();
487
- const result = await listIssues(context, { parentIssueNumber: null, perPage: 2 });
488
- assert.deepEqual(result.issues, []);
489
- assert.equal(result.nextPage, 2);
647
+ test("local filters retain pagination when the current GitHub page has no matching issue", async () => {
648
+ const { context } = listingFixture();
649
+ const result = await listIssues(context, { parentIssueNumber: null, perPage: 2 });
650
+ assert.deepEqual(result.issues, []);
651
+ assert.equal(result.nextPage, 2);
490
652
  });
491
- test('foreign issue identity and mismatched organization fields fail rather than returning false readback', async () => {
492
- await assert.rejects(listIssues(listingFixture({ foreign: true }).context, {}), /foreign repository/u);
493
- await assert.rejects(listIssues(listingFixture({ invalidField: true }).context, {}), /conflicts with its catalog/u);
653
+ test("foreign issue identity and mismatched organization fields fail rather than returning false readback", async () => {
654
+ await assert.rejects(listIssues(listingFixture({ foreign: true }).context, {}), /foreign repository/u);
655
+ await assert.rejects(listIssues(listingFixture({ invalidField: true }).context, {}), /conflicts with its catalog/u);
494
656
  });
495
- test('search refuses incomplete upstream results and invalid literal text', async () => {
496
- await assert.rejects(listIssues(listingFixture({ incomplete: true }).context, { query: 'widget' }), /incomplete results/u);
497
- await assert.rejects(listIssues(listingFixture().context, { query: '" repo:elsewhere/widget' }), /literal text/u);
498
- assert.equal(getAiDeliveryMcpTool('issue_list')?.inputSchema.safeParse({ perPage: 101 }).success, false);
657
+ test("search refuses incomplete upstream results and invalid literal text", async () => {
658
+ await assert.rejects(
659
+ listIssues(listingFixture({ incomplete: true }).context, { query: "widget" }),
660
+ /incomplete results/u
661
+ );
662
+ await assert.rejects(listIssues(listingFixture().context, { query: '" repo:elsewhere/widget' }), /literal text/u);
663
+ assert.equal(getAiDeliveryMcpTool("issue_list")?.inputSchema.safeParse({ perPage: 101 }).success, false);
499
664
  });
500
- test('a foreign parent with the same issue number cannot satisfy a local parent filter', async () => {
501
- const { context } = listingFixture({ foreignParent: true });
502
- assert.deepEqual((await listIssues(context, { parentIssueNumber: 9 })).issues, []);
665
+ test("a foreign parent with the same issue number cannot satisfy a local parent filter", async () => {
666
+ const { context } = listingFixture({ foreignParent: true });
667
+ assert.deepEqual((await listIssues(context, { parentIssueNumber: 9 })).issues, []);
503
668
  });
504
- test('label filters preserve GitHub case-insensitive label identity', async () => {
505
- const { context } = listingFixture();
506
- assert.equal((await listIssues(context, { labels: ['AREA:Widget'] })).issues.length, 1);
669
+ test("label filters preserve GitHub case-insensitive label identity", async () => {
670
+ const { context } = listingFixture();
671
+ assert.equal((await listIssues(context, { labels: ["AREA:Widget"] })).issues.length, 1);
507
672
  });
508
- test('a set select field without its named option fails rather than reporting unset', async () => {
509
- await assert.rejects(listIssues(listingFixture({ missingOption: true }).context, {}), /option/u);
673
+ test("a set select field without its named option fails rather than reporting unset", async () => {
674
+ await assert.rejects(listIssues(listingFixture({ missingOption: true }).context, {}), /option/u);
510
675
  });
511
- test('same-number blockers in different repositories retain both qualified identities', async () => {
512
- const { context } = listingFixture({ dualBlockers: true });
513
- const result = await issue.listIssues(context, {});
514
- assert.deepEqual(result.issues[0]?.blockers, [
515
- { repository: 'example/widget', number: 8, title: 'Prerequisite', state: 'CLOSED' },
516
- { repository: 'example/other', number: 8, title: 'Other prerequisite', state: 'OPEN' },
517
- ]);
676
+ test("same-number blockers in different repositories retain both qualified identities", async () => {
677
+ const { context } = listingFixture({ dualBlockers: true });
678
+ const result = await issue.listIssues(context, {});
679
+ assert.deepEqual(result.issues[0]?.blockers, [
680
+ { repository: "example/widget", number: 8, title: "Prerequisite", state: "CLOSED" },
681
+ { repository: "example/other", number: 8, title: "Other prerequisite", state: "OPEN" }
682
+ ]);
518
683
  });
519
- test('a set multi-select field without named options cannot be reported unset', async () => {
520
- await assert.rejects(listIssues(listingFixture({ missingMulti: true }).context, {}), /option/u);
684
+ test("a set multi-select field without named options cannot be reported unset", async () => {
685
+ await assert.rejects(listIssues(listingFixture({ missingMulti: true }).context, {}), /option/u);
521
686
  });
522
- test('history rendering preserves whitespace and escapes content that could end the collapsed section', () => {
523
- const render = issue
524
- .renderIssueHistory;
525
- assert.equal(typeof render, 'function');
526
- const body = ' old body\n</pre></details><script>x</script> & text ';
527
- const result = render('Old <title> & name', body);
528
- assert.equal(result, '<details>\n<summary>Previous issue title and body</summary>\n\nTitle:\n<pre>Old &lt;title&gt; &amp; name</pre>\n\nBody:\n<pre> old body\n&lt;/pre&gt;&lt;/details&gt;&lt;script&gt;x&lt;/script&gt; &amp; text </pre>\n\n</details>');
687
+ test("history rendering preserves whitespace and escapes content that could end the collapsed section", () => {
688
+ const render = issue.renderIssueHistory;
689
+ assert.equal(typeof render, "function");
690
+ const body = " old body\n</pre></details><script>x</script> & text ";
691
+ const result = render("Old <title> & name", body);
692
+ assert.equal(
693
+ result,
694
+ "<details>\n<summary>Previous issue title and body</summary>\n\nTitle:\n<pre>Old &lt;title&gt; &amp; name</pre>\n\nBody:\n<pre> old body\n&lt;/pre&gt;&lt;/details&gt;&lt;script&gt;x&lt;/script&gt; &amp; text </pre>\n\n</details>"
695
+ );
529
696
  });
530
- test('closure evidence reads native reason and preserves qualified duplicate identity', async () => {
531
- const { context } = listingFixture();
532
- context.clients.graphql = (async () => ({
533
- repository: {
534
- issue: {
535
- number: 17,
536
- repository: { nameWithOwner: 'example/widget' },
537
- state: 'CLOSED',
538
- stateReason: 'DUPLICATE',
539
- duplicateOf: { number: 9, repository: { nameWithOwner: 'example/other' } },
540
- },
697
+ test("closure evidence reads native reason and preserves qualified duplicate identity", async () => {
698
+ const { context } = listingFixture();
699
+ context.clients.graphql = (async () => ({
700
+ repository: {
701
+ issue: {
702
+ number: 17,
703
+ repository: { nameWithOwner: "example/widget" },
704
+ state: "CLOSED",
705
+ stateReason: "DUPLICATE",
706
+ duplicateOf: { number: 9, repository: { nameWithOwner: "example/other" } }
707
+ }
708
+ }
709
+ }));
710
+ const read = issue.readIssueClosure;
711
+ assert.equal(typeof read, "function");
712
+ assert.deepEqual(await read(context, 17), {
713
+ state: "closed",
714
+ closeReason: "duplicate",
715
+ duplicateOf: { number: 9, repository: "example/other" }
716
+ });
717
+ });
718
+ test("native field catalog and values both paginate through the last named field", async () => {
719
+ const { context } = listingFixture();
720
+ const requests = [];
721
+ context.clients.rest.request = (async (route, params) => {
722
+ requests.push({ route, page: params.page });
723
+ const catalog = route.includes("/orgs/");
724
+ if (params.page === 2)
725
+ return {
726
+ data: catalog ? [{ id: 201, name: "Late date", data_type: "date" }] : [{ issue_field_id: 201, issue_field_name: "Late date", data_type: "date", value: "2026-10-09" }]
727
+ };
728
+ return {
729
+ data: catalog ? [
730
+ { id: 101, name: "Estimate", data_type: "single_select" },
731
+ { id: 102, name: "Urgency", data_type: "single_select" },
732
+ ...Array.from({ length: 98 }, (_, index) => ({
733
+ id: index + 103,
734
+ name: `Custom ${String(index)}`,
735
+ data_type: "text"
736
+ }))
737
+ ] : [
738
+ {
739
+ issue_field_id: 101,
740
+ issue_field_name: "Estimate",
741
+ data_type: "single_select",
742
+ value: 44,
743
+ single_select_option: { name: "4" }
541
744
  },
542
- }));
543
- const read = issue.readIssueClosure;
544
- assert.equal(typeof read, 'function');
545
- assert.deepEqual(await read(context, 17), {
546
- state: 'closed',
547
- closeReason: 'duplicate',
548
- duplicateOf: { number: 9, repository: 'example/other' },
549
- });
745
+ { issue_field_id: 102, issue_field_name: "Urgency", data_type: "single_select", value: null },
746
+ ...Array.from({ length: 98 }, (_, index) => ({
747
+ issue_field_id: index + 103,
748
+ issue_field_name: `Custom ${String(index)}`,
749
+ data_type: "text",
750
+ value: "retained"
751
+ }))
752
+ ]
753
+ };
754
+ });
755
+ const result = await issue.listIssues(context, {});
756
+ assert.equal(result.issues[0]?.fields["Late date"], "2026-10-09");
757
+ assert.equal(result.issues[0]?.fields.Urgency, null);
758
+ assert.deepEqual(
759
+ requests.map((request) => request.page),
760
+ [1, 2, 1, 2]
761
+ );
550
762
  });
551
- test('native field catalog and values both paginate through the last named field', async () => {
552
- const { context } = listingFixture();
553
- const requests = [];
554
- context.clients.rest.request = (async (route, params) => {
555
- requests.push({ route, page: params.page });
556
- const catalog = route.includes('/orgs/');
557
- if (params.page === 2)
558
- return {
559
- data: catalog
560
- ? [{ id: 201, name: 'Late date', data_type: 'date' }]
561
- : [{ issue_field_id: 201, issue_field_name: 'Late date', data_type: 'date', value: '2026-10-09' }],
562
- };
563
- return {
564
- data: catalog
565
- ? [
566
- { id: 101, name: 'Estimate', data_type: 'single_select' },
567
- { id: 102, name: 'Urgency', data_type: 'single_select' },
568
- ...Array.from({ length: 98 }, (_, index) => ({
569
- id: index + 103,
570
- name: `Custom ${String(index)}`,
571
- data_type: 'text',
572
- })),
573
- ]
574
- : [
575
- {
576
- issue_field_id: 101,
577
- issue_field_name: 'Estimate',
578
- data_type: 'single_select',
579
- value: 44,
580
- single_select_option: { name: '4' },
581
- },
582
- { issue_field_id: 102, issue_field_name: 'Urgency', data_type: 'single_select', value: null },
583
- ...Array.from({ length: 98 }, (_, index) => ({
584
- issue_field_id: index + 103,
585
- issue_field_name: `Custom ${String(index)}`,
586
- data_type: 'text',
587
- value: 'retained',
588
- })),
589
- ],
590
- };
763
+ test("native field pagination fails closed on a repeated nonadvancing page", async () => {
764
+ const { context } = listingFixture();
765
+ context.clients.rest.request = (async () => ({
766
+ data: Array.from({ length: 100 }, (_, index) => ({
767
+ id: index + 1,
768
+ name: `Field ${String(index)}`,
769
+ data_type: "text"
770
+ }))
771
+ }));
772
+ await assert.rejects(issue.listIssues(context, {}), /repeated a pagination page/u);
773
+ });
774
+ test.each([
775
+ ["catalog", "list"],
776
+ ["values", "list"],
777
+ ["catalog", "ready"],
778
+ ["values", "ready"],
779
+ ["catalog", "capacity"],
780
+ ["values", "capacity"]
781
+ ])("reconciliation bounds native %s through %s reads", async (collection, entry) => {
782
+ const { context } = listingFixture();
783
+ Object.assign(context, { readPageLimit: 20 });
784
+ if (entry === "ready")
785
+ context.clients.rest.issues.listSubIssues = (async (input) => {
786
+ assert.equal(input.owner, "example");
787
+ assert.equal(input.repo, "widget");
788
+ assert.equal(input.issue_number, 17);
789
+ return { data: [] };
790
+ });
791
+ context.clients.rest.issues.get = (async () => ({
792
+ data: {
793
+ number: 17,
794
+ node_id: "ISSUE17",
795
+ state: "open",
796
+ body: "",
797
+ title: "Repair widget",
798
+ html_url: "https://github.com/example/widget/issues/17"
799
+ }
800
+ }));
801
+ if (entry === "capacity")
802
+ context.config = {
803
+ ...context.config,
804
+ wipLimits: [{ repository: "example/widget", name: "Native", match: { field: "Estimate", value: "4" }, limit: 2 }]
805
+ };
806
+ const originalGraphql = context.clients.graphql;
807
+ context.clients.graphql = (async (query, variables) => {
808
+ const response = await originalGraphql(query, variables);
809
+ if (!query.includes("blockedBy(first:")) return response;
810
+ const parsed = response;
811
+ Object.assign(parsed.repository.issue, {
812
+ id: "ISSUE17",
813
+ number: 17,
814
+ repository: { nameWithOwner: "example/widget" }
591
815
  });
592
- const result = await issue.listIssues(context, {});
593
- assert.equal(result.issues[0]?.fields['Late date'], '2026-10-09');
594
- assert.equal(result.issues[0]?.fields.Urgency, null);
595
- assert.deepEqual(requests.map((request) => request.page), [1, 2, 1, 2]);
816
+ return parsed;
817
+ });
818
+ const original = context.clients.rest.request;
819
+ let requests = 0;
820
+ context.clients.rest.request = (async (route, params) => {
821
+ if (route.includes("/orgs/") !== (collection === "catalog")) return original(route);
822
+ requests++;
823
+ return {
824
+ data: params.page > 20 ? [] : Array.from({ length: 100 }, (_, index) => {
825
+ const id = 1e3 + params.page * 100 + index;
826
+ return collection === "catalog" ? { id, name: `Extra ${String(id)}`, data_type: "text" } : { issue_field_id: id, issue_field_name: `Extra ${String(id)}`, data_type: "text", value: "value" };
827
+ })
828
+ };
829
+ });
830
+ const operation = entry === "list" ? issue.listIssues(context, {}) : entry === "ready" ? issue.readyCheck(context, 17) : issue.assertIssueStartCapacity(context, 17);
831
+ await assert.rejects(operation, (error) => {
832
+ assert.ok(error instanceof Error);
833
+ assert.equal(error.name, "CollectionLimitError");
834
+ assert.equal(Reflect.get(error, "pagesRequested"), 20);
835
+ return true;
836
+ });
837
+ assert.equal(requests, 20);
838
+ });
839
+ test("reconciliation bounds blocker pages and binds their source issue", async () => {
840
+ const { context } = listingFixture();
841
+ let requests = 0;
842
+ context.clients.graphql = (async () => {
843
+ requests++;
844
+ return {
845
+ repository: {
846
+ issue: {
847
+ id: "ISSUE17",
848
+ number: 17,
849
+ repository: { nameWithOwner: "example/widget" },
850
+ parent: null,
851
+ blockedBy: { nodes: [], pageInfo: { hasNextPage: requests < 21, endCursor: `page-${String(requests)}` } }
852
+ }
853
+ }
854
+ };
855
+ });
856
+ const input = { graphql: context.clients.graphql, repo: context.repo, issueNumber: 17, maxPages: 20 };
857
+ await assert.rejects(getNativeBlockerRelationships(input), (error) => {
858
+ assert.ok(error instanceof Error);
859
+ assert.equal(error.name, "CollectionLimitError");
860
+ assert.equal(Reflect.get(error, "pagesRequested"), 20);
861
+ return true;
862
+ });
863
+ assert.equal(requests, 20);
596
864
  });
597
- test('native field pagination fails closed on a repeated nonadvancing page', async () => {
598
- const { context } = listingFixture();
599
- context.clients.rest.request = (async () => ({
600
- data: Array.from({ length: 100 }, (_, index) => ({
601
- id: index + 1,
602
- name: `Field ${String(index)}`,
603
- data_type: 'text',
604
- })),
605
- }));
606
- await assert.rejects(issue.listIssues(context, {}), /repeated a pagination page/u);
865
+ test("reconciliation WIP guards bound their label catalog", async () => {
866
+ const { context } = listingFixture();
867
+ Object.assign(context, { readPageLimit: 20 });
868
+ context.config = {
869
+ ...context.config,
870
+ wipLimits: [{ repository: "example/widget", name: "Urgent", match: { label: "urgent" }, limit: 2 }]
871
+ };
872
+ let requests = 0;
873
+ context.clients.rest.issues.listLabelsForRepo = (async () => {
874
+ requests++;
875
+ return {
876
+ data: requests > 20 ? [] : Array.from({ length: 100 }, (_, index) => ({
877
+ name: index === 0 && requests === 1 ? "urgent" : `label-${String(requests)}-${String(index)}`
878
+ }))
879
+ };
880
+ });
881
+ await assert.rejects(issue.assertIssueStartCapacity(context, 17), (error) => {
882
+ assert.ok(error instanceof Error);
883
+ assert.equal(error.name, "CollectionLimitError");
884
+ return true;
885
+ });
886
+ assert.equal(requests, 20);
607
887
  });
608
- test('search applies the same case-insensitive label filter to authoritative result rows', async () => {
609
- const { context } = listingFixture();
610
- context.clients.rest.search.issuesAndPullRequests = (async () => ({
611
- data: {
612
- total_count: 1,
613
- incomplete_results: false,
614
- items: [
615
- {
616
- number: 17,
617
- node_id: 'ISSUE17',
618
- title: 'Repair widget',
619
- state: 'open',
620
- labels: [{ name: 'area:widget' }],
621
- type: { name: 'Task' },
622
- html_url: 'https://github.com/example/widget/issues/17',
623
- updated_at: '2026-10-07T00:00:00Z',
624
- },
625
- ],
626
- },
627
- }));
628
- const result = await issue.listIssues(context, { query: 'widget', labels: ['AREA:Widget'] });
629
- assert.equal(result.issues.length, 1);
630
- assert.equal(result.nextPage, null);
888
+ function membershipFixture() {
889
+ const configuration = { ...listingFixture().context.projectConfiguration, writable: true };
890
+ const events = [];
891
+ const controls = { corrupt: "", archived: false, duplicate: false, unreadable: false };
892
+ let member = false;
893
+ let status = null;
894
+ const item = (readback = false) => ({
895
+ id: readback && controls.corrupt === "item" ? "WRONG" : "ITEM17",
896
+ isArchived: controls.archived,
897
+ project: { id: readback && controls.corrupt === "project" ? "WRONG" : "PROJECT", number: 1 },
898
+ content: controls.unreadable ? null : {
899
+ __typename: "Issue",
900
+ id: readback && controls.corrupt === "issue" ? "WRONG" : "ISSUE17",
901
+ number: 17,
902
+ repository: { nameWithOwner: "example/widget" }
903
+ },
904
+ fieldValueByName: status === null ? null : { name: "Active", optionId: controls.corrupt === "option" ? "WRONG" : "ACTIVE" }
905
+ });
906
+ const graphql = (async (query, variables) => {
907
+ if (query.includes("mutation AddProjectDeliveryItem")) {
908
+ events.push("add");
909
+ member = true;
910
+ return { addProjectV2ItemById: { item: { id: "ITEM17" } } };
911
+ }
912
+ if (query.includes("mutation UpdateProjectDeliveryStatus")) {
913
+ events.push("status");
914
+ status = "In Progress";
915
+ return { updateProjectV2ItemFieldValue: { projectV2Item: { id: "ITEM17" } } };
916
+ }
917
+ if (query.includes("query ProjectDeliveryItemReadback")) {
918
+ events.push("readback");
919
+ return { node: item(true) };
920
+ }
921
+ const items = member ? controls.duplicate ? [item(), { ...item(), id: "SECOND" }] : [item()] : [];
922
+ if (query.includes("query ProjectDeliveryIssueItems")) return issueProjectItemsResponse(variables, items);
923
+ if (query.includes("query ProjectDeliveryItems"))
924
+ return {
925
+ organization: {
926
+ projectV2: { id: "PROJECT", number: 1, items: { nodes: items, pageInfo: { hasNextPage: false } } }
927
+ }
928
+ };
929
+ throw new Error("Unexpected membership fixture query.");
930
+ });
931
+ return {
932
+ input: { graphql, configuration, org: "example", issueNodeId: "ISSUE17" },
933
+ events,
934
+ controls,
935
+ setMember: () => {
936
+ member = true;
937
+ }
938
+ };
939
+ }
940
+ test("membership-only add verifies the exact unarchived item and reuse writes nothing", async () => {
941
+ const f = membershipFixture();
942
+ const ensure = Reflect.get(projectDelivery, "ensureIssueProjectMembership");
943
+ assert.equal(typeof ensure, "function");
944
+ const result = await ensure({
945
+ ...f.input,
946
+ beforeAdd: async () => {
947
+ f.events.push("before-add");
948
+ }
949
+ });
950
+ assert.deepEqual(result, { itemId: "ITEM17", archived: false });
951
+ assert.deepEqual(f.events, ["before-add", "add", "readback"]);
952
+ f.events.length = 0;
953
+ await ensure(f.input);
954
+ assert.deepEqual(f.events, ["readback"]);
955
+ });
956
+ test.each(["project", "issue", "item", "archive", "duplicate", "unreadable"])(
957
+ "membership refuses %s evidence without a repair write",
958
+ async (failure) => {
959
+ const f = membershipFixture();
960
+ f.setMember();
961
+ if (failure === "archive") f.controls.archived = true;
962
+ else if (failure === "duplicate") f.controls.duplicate = true;
963
+ else if (failure === "unreadable") f.controls.unreadable = true;
964
+ else f.controls.corrupt = failure;
965
+ const ensure = Reflect.get(projectDelivery, "ensureIssueProjectMembership");
966
+ assert.equal(typeof ensure, "function");
967
+ await assert.rejects(ensure(f.input));
968
+ assert.deepEqual(
969
+ f.events.filter((e) => e === "add" || e === "status"),
970
+ []
971
+ );
972
+ }
973
+ );
974
+ const projectRow = {
975
+ id: "ITEM17",
976
+ isArchived: false,
977
+ project: { id: "PROJECT", number: 1 },
978
+ content: { id: "ISSUE17" },
979
+ fieldValueByName: { name: "Active", optionId: "ACTIVE" }
980
+ };
981
+ function readStatus(nodes, overrides = {}) {
982
+ const { input } = membershipFixture();
983
+ const graphql = (async () => ({
984
+ node: {
985
+ id: overrides.nodeId ?? "ISSUE17",
986
+ projectItems: { nodes, pageInfo: { hasNextPage: overrides.hasNextPage ?? false } }
987
+ }
988
+ }));
989
+ return projectDelivery.getIssueProjectStatus({ ...input, graphql });
990
+ }
991
+ test("issue Project Status is the exact configured item and never a guess (#180)", async () => {
992
+ assert.deepEqual(await readStatus([projectRow]), { itemId: "ITEM17", status: "In Progress" });
993
+ assert.equal(await readStatus([]), null);
994
+ assert.equal(await readStatus([{ ...projectRow, isArchived: true }]), null);
995
+ assert.equal(await readStatus([{ ...projectRow, project: { id: "OTHER", number: 9 } }]), null);
996
+ });
997
+ test.each([
998
+ ["a different issue node", () => readStatus([projectRow], { nodeId: "ISSUE99" }), /different issue/u],
999
+ ["more than 50 Projects", () => readStatus([projectRow], { hasNextPage: true }), /more than 50 Projects/u],
1000
+ ["an unreadable item in the configured Project", () => readStatus([{ ...projectRow, content: null }]), /unreadable/u],
1001
+ [
1002
+ "a duplicate item in the configured Project",
1003
+ () => readStatus([projectRow, { ...projectRow, id: "SECOND" }]),
1004
+ /duplicate/u
1005
+ ]
1006
+ ])("issue Project lookup refuses %s", async (_name, read, message) => {
1007
+ await assert.rejects(read(), message);
1008
+ });
1009
+ test("guards run immediately before both Project mutation boundaries", async () => {
1010
+ const f = membershipFixture();
1011
+ const input = {
1012
+ ...f.input,
1013
+ status: "In Progress",
1014
+ beforeAdd: async () => {
1015
+ f.events.push("before-add");
1016
+ },
1017
+ beforeAdvance: async () => {
1018
+ f.events.push("before-advance");
1019
+ }
1020
+ };
1021
+ await projectDelivery.syncIssueProjectStatus(input);
1022
+ assert.deepEqual(
1023
+ f.events.filter((e) => e !== "readback"),
1024
+ ["before-add", "add", "before-advance", "status"]
1025
+ );
1026
+ const refused = membershipFixture();
1027
+ const fail = {
1028
+ ...refused.input,
1029
+ status: "In Progress",
1030
+ beforeAdd: async () => {
1031
+ throw new Error("native drift");
1032
+ }
1033
+ };
1034
+ await assert.rejects(projectDelivery.syncIssueProjectStatus(fail), /native drift/u);
1035
+ assert.deepEqual(refused.events, []);
1036
+ });
1037
+ test("strict Project observation refuses hidden content instead of proving absence", async () => {
1038
+ const f = membershipFixture();
1039
+ f.setMember();
1040
+ f.controls.unreadable = true;
1041
+ const read = Reflect.get(projectDelivery, "readProjectDeliveryItems");
1042
+ assert.equal(typeof read, "function");
1043
+ await assert.rejects(read({ ...f.input, maxPages: 20 }));
1044
+ assert.deepEqual(f.events, []);
1045
+ });
1046
+ test("strict Project observation retains exact identities and verified non-issue kinds", async () => {
1047
+ const f = membershipFixture();
1048
+ f.setMember();
1049
+ const base = f.input.graphql;
1050
+ const graphql = (async (query) => {
1051
+ const response = await base(query);
1052
+ const data = response;
1053
+ data.organization.projectV2.items.nodes.push(
1054
+ {
1055
+ id: "DRAFT",
1056
+ isArchived: false,
1057
+ content: { __typename: "DraftIssue", id: "DRAFT-CONTENT" },
1058
+ fieldValueByName: null
1059
+ },
1060
+ { id: "PR", isArchived: true, content: { __typename: "PullRequest", id: "PR-CONTENT" }, fieldValueByName: null }
1061
+ );
1062
+ return data;
1063
+ });
1064
+ const result = await projectDelivery.readProjectDeliveryItems({ ...f.input, graphql, maxPages: 20 });
1065
+ assert.deepEqual(result[0], {
1066
+ id: "ITEM17",
1067
+ archived: false,
1068
+ contentId: "ISSUE17",
1069
+ status: null,
1070
+ statusOptionId: null,
1071
+ projectId: "PROJECT",
1072
+ projectNumber: 1,
1073
+ contentKind: "issue",
1074
+ statusRead: "unset",
1075
+ statusName: null,
1076
+ repository: "example/widget",
1077
+ issueNumber: 17
1078
+ });
1079
+ assert.deepEqual(
1080
+ result.map((item) => item.contentKind),
1081
+ ["issue", "draft", "pull-request"]
1082
+ );
1083
+ assert.deepEqual(f.events, []);
1084
+ });
1085
+ test.each(["project", "option"])(
1086
+ "Project %s readback failure preserves an attempted write without retry",
1087
+ async (failure) => {
1088
+ const f = membershipFixture();
1089
+ f.controls.corrupt = failure;
1090
+ if (failure === "project") {
1091
+ await assert.rejects(projectDelivery.ensureIssueProjectMembership(f.input), /exact issue item/u);
1092
+ assert.deepEqual(f.events, ["add", "readback"]);
1093
+ } else {
1094
+ f.setMember();
1095
+ await assert.rejects(
1096
+ projectDelivery.syncIssueProjectStatus({ ...f.input, status: "In Progress" }),
1097
+ /unsupported Project Status/u
1098
+ );
1099
+ assert.deepEqual(f.events, ["status", "readback"]);
1100
+ }
1101
+ }
1102
+ );
1103
+ test("search applies the same case-insensitive label filter to authoritative result rows", async () => {
1104
+ const { context } = listingFixture();
1105
+ context.clients.rest.search.issuesAndPullRequests = (async () => ({
1106
+ data: {
1107
+ total_count: 1,
1108
+ incomplete_results: false,
1109
+ items: [
1110
+ {
1111
+ number: 17,
1112
+ node_id: "ISSUE17",
1113
+ title: "Repair widget",
1114
+ state: "open",
1115
+ labels: [{ name: "area:widget" }],
1116
+ type: { name: "Task" },
1117
+ html_url: "https://github.com/example/widget/issues/17",
1118
+ updated_at: "2026-10-07T00:00:00Z"
1119
+ }
1120
+ ]
1121
+ }
1122
+ }));
1123
+ const result = await issue.listIssues(context, { query: "widget", labels: ["AREA:Widget"] });
1124
+ assert.equal(result.issues.length, 1);
1125
+ assert.equal(result.nextPage, null);
631
1126
  });
632
- //# sourceMappingURL=issueTracking.test.js.map
1127
+ //# sourceMappingURL=issueTracking.test.js.map