@aviaratech/ai-delivery 0.3.35 → 0.3.37

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