@aviaratech/ai-delivery 0.3.34 → 0.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -477
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,730 +1,1051 @@
1
- import assert from 'node:assert/strict';
2
- import { afterEach, test, vi } from 'vitest';
3
- import * as issue from './issue.js';
4
- import * as configuration from './config/deliveryConfig.js';
5
- import { executeTool } from './dispatch.js';
6
- import { getAiDeliveryMcpTool } from './mcp/tools.js';
7
- import { DeliveryError, getRateLimitDiagnostics } from './errors.js';
8
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
9
- import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
10
- import { createAiDeliveryMcpServer } from './mcp/index.js';
11
- import { syntheticDiscoveryConfig } from './fixtures/discovery.js';
12
- import { IssueFields, renderIssueBody } from './issueContract.js';
1
+ import { issueProjectItemsResponse } from "./fixtures/issueProjectItems.js";
2
+ import assert from "node:assert/strict";
3
+ import { afterEach, test, vi } from "vitest";
4
+ import * as issue from "./issue.js";
5
+ import * as configuration from "./config/deliveryConfig.js";
6
+ import { executeTool } from "./dispatch.js";
7
+ import { getAiDeliveryMcpTool } from "./mcp/tools.js";
8
+ import { DeliveryError, getRateLimitDiagnostics } from "./errors.js";
9
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
10
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
11
+ import { createAiDeliveryMcpServer } from "./mcp/index.js";
12
+ import { syntheticDiscoveryConfig } from "./fixtures/discovery.js";
13
+ import { IssueFields, renderIssueBody } from "./issueContract.js";
14
+ import { syncIssueProjectStatus } from "./github/projectDelivery.js";
13
15
  function batchFixture() {
14
- const rows = new Map(Array.from({ length: 5 }, (_, index) => {
15
- const number = index + 1;
16
- return [
17
- number,
18
- {
19
- number,
20
- id: number + 100,
21
- node_id: `ISSUE${number}`,
22
- title: `Synthetic item ${number}`,
23
- body: renderIssueBody(IssueFields.parse({ title: `Synthetic item ${number}`, draft: true })),
24
- state: 'open',
25
- type: { name: 'Task' },
26
- labels: [],
27
- milestone: null,
28
- html_url: `https://github.com/example/widget/issues/${number}`,
29
- },
30
- ];
31
- }));
32
- const writes = [];
33
- const controls = {
34
- failAfterWrite: 0,
35
- failReadback: 0,
36
- driftOnRead: 0,
37
- rateLimited: 0,
38
- ignoreLabels: false,
39
- parentRepository: 'example/widget',
40
- parentNodeId: '',
41
- };
42
- const reads = new Map();
43
- const metadata = new Map();
44
- const parents = new Map();
45
- const blockers = new Map();
46
- const reasons = new Map();
47
- const duplicates = new Map();
48
- const fieldValues = (number) => Object.entries(metadata.get(number) ?? {}).map(([id, value]) => ({
49
- data_type: 'single_select',
50
- issue_field_id: Number(id),
51
- issue_field_name: id === '101' ? 'Estimate' : 'Urgency',
52
- value,
53
- }));
54
- const comments = [];
55
- const statuses = new Map(Array.from(rows.keys(), (number) => [number, 'Active']));
56
- const context = {
57
- root: '/synthetic',
58
- repo: { owner: 'example', repo: 'widget' },
59
- config: syntheticDiscoveryConfig,
60
- projectConfiguration: {
61
- projectId: 'PROJECT',
62
- projectNumber: 1,
63
- title: 'Delivery',
64
- writable: true,
65
- pointsFieldId: 'POINTS',
66
- priorityFieldId: 'PRIORITY',
67
- statusFieldId: 'STATUS',
68
- statusOptionIds: { Todo: 'TODO', 'In Progress': 'ACTIVE', Blocked: 'BLOCKED', Done: 'DONE' },
69
- settings: {
70
- number: 1,
71
- title: 'Delivery',
72
- statusField: 'Flow',
73
- statuses: { Todo: 'Queued', 'In Progress': 'Active', Blocked: 'Waiting', Done: 'Shipped' },
74
- },
75
- },
76
- clients: {
77
- role: 'author',
78
- authenticatedAuthor: async () => ({ actorLogin: 'operator', credentialIdentity: 'user:1' }),
79
- rest: {
80
- issues: {
81
- get: async ({ issue_number }) => {
82
- reads.set(issue_number, (reads.get(issue_number) ?? 0) + 1);
83
- if (controls.failReadback === issue_number && writes.includes(`update:${issue_number}`))
84
- throw new Error('Synthetic readback transport failure');
85
- const row = rows.get(issue_number);
86
- if (row && controls.driftOnRead === issue_number && reads.get(issue_number) === 2)
87
- row.body = 'Concurrent operator edit';
88
- if (!row)
89
- throw new Error('Synthetic issue unavailable');
90
- return { data: structuredClone(row) };
91
- },
92
- listComments: async ({ issue_number }) => ({
93
- data: comments.filter((comment) => comment.issue_url.endsWith('/' + String(issue_number))),
94
- }),
95
- listLabelsForRepo: async () => ({ data: [{ name: 'enhancement' }] }),
96
- listSubIssues: async () => ({ data: [] }),
97
- addSubIssue: async ({ issue_number, sub_issue_id }) => {
98
- writes.push('parent');
99
- parents.set(sub_issue_id - 100, issue_number);
100
- return { data: {} };
101
- },
102
- removeSubIssue: async ({ sub_issue_id }) => {
103
- writes.push('parent');
104
- parents.delete(sub_issue_id - 100);
105
- return { data: {} };
106
- },
107
- createComment: async ({ issue_number, body }) => {
108
- writes.push('comment');
109
- const comment = {
110
- id: comments.length + 1000,
111
- body,
112
- html_url: `https://github.com/example/widget/issues/${issue_number}#issuecomment-${comments.length + 1000}`,
113
- user: { login: 'operator' },
114
- issue_url: `https://api.github.com/repos/example/widget/issues/${issue_number}`,
115
- };
116
- comments.push(comment);
117
- return { data: comment };
118
- },
119
- getComment: async ({ comment_id }) => ({
120
- data: comments.find((comment) => comment.id === comment_id),
121
- }),
122
- update: async ({ issue_number, ...patch }) => {
123
- writes.push(`update:${issue_number}`);
124
- if (controls.rateLimited === issue_number)
125
- throw Object.assign(new Error('PRIVATE_REMOTE_CONTENT'), {
126
- status: 429,
127
- response: {
128
- headers: {
129
- 'retry-after': '60',
130
- 'x-ratelimit-remaining': '0',
131
- 'x-ratelimit-reset': '1900000000',
132
- authorization: 'PRIVATE_TOKEN',
133
- },
134
- },
135
- });
136
- const row = rows.get(issue_number);
137
- if (typeof patch.title === 'string')
138
- row.title = patch.title;
139
- if (typeof patch.body === 'string')
140
- row.body = patch.body;
141
- if (typeof patch.type === 'string')
142
- row.type = { name: patch.type };
143
- if (Array.isArray(patch.labels) && !controls.ignoreLabels)
144
- row.labels = patch.labels.map((label) => label.toLowerCase());
145
- if (patch.milestone !== undefined)
146
- Object.assign(row, { milestone: patch.milestone === null ? null : { number: patch.milestone } });
147
- if (typeof patch.state === 'string') {
148
- row.state = patch.state;
149
- reasons.set(issue_number, patch.state === 'closed'
150
- ? (typeof patch.state_reason === 'string' ? patch.state_reason : 'completed').toUpperCase()
151
- : 'REOPENED');
152
- }
153
- if (typeof patch.duplicate_issue_id === 'number')
154
- duplicates.set(issue_number, patch.duplicate_issue_id - 100);
155
- if (controls.failAfterWrite === issue_number) {
156
- controls.failAfterWrite = 0;
157
- throw new Error('Synthetic acknowledgement lost');
158
- }
159
- return { data: rows.get(issue_number) };
160
- },
161
- },
162
- paginate: async (_method, { issue_number }) => [...parents].filter(([, parent]) => parent === issue_number).map(([number]) => rows.get(number)),
163
- request: async (route, params) => {
164
- if (route.startsWith('GET /orgs'))
165
- return {
166
- data: Object.values(syntheticDiscoveryConfig.native)
167
- .filter((field) => typeof field === 'object' && field !== null && 'databaseId' in field)
168
- .map((field) => ({
169
- id: Number(field.databaseId),
170
- name: field.name,
171
- data_type: 'single_select',
172
- options: field.values.map((name) => ({ name })),
173
- })),
174
- };
175
- if (route.startsWith('POST ')) {
176
- writes.push('metadata');
177
- metadata.set(params.issue_number, {
178
- ...metadata.get(params.issue_number),
179
- ...Object.fromEntries(params.issue_field_values.map((value) => [String(value.field_id), value.value])),
180
- });
181
- }
182
- if (route.startsWith('DELETE ')) {
183
- writes.push('metadata');
184
- delete metadata.get(params.issue_number)[String(params.issue_field_id)];
185
- }
186
- return { data: fieldValues(params.issue_number) };
187
- },
188
- },
189
- graphql: async (query, variables) => {
190
- const numeric = variables.number ?? variables.issueNumber;
191
- const nodeId = variables.issueNodeId ?? variables.itemId ?? '1';
192
- const number = typeof numeric === 'number' ? numeric : typeof nodeId === 'string' ? Number(nodeId.replace(/\D/gu, '')) : NaN;
193
- if (query.includes('IssueClosureReadback'))
194
- return {
195
- repository: {
196
- issue: {
197
- number,
198
- repository: { nameWithOwner: 'example/widget' },
199
- state: rows.get(number).state.toUpperCase(),
200
- stateReason: reasons.get(number) ?? null,
201
- duplicateOf: duplicates.has(number)
202
- ? { number: duplicates.get(number), repository: { nameWithOwner: 'example/widget' } }
203
- : null,
204
- },
205
- },
206
- };
207
- if (query.includes('blockedBy(first:'))
208
- return {
209
- repository: {
210
- issue: {
211
- parent: parents.has(number)
212
- ? {
213
- id: controls.parentNodeId || `ISSUE${parents.get(number)}`,
214
- number: parents.get(number),
215
- repository: { nameWithOwner: controls.parentRepository },
216
- }
217
- : null,
218
- blockedBy: {
219
- nodes: (blockers.get(number) ?? []).map((n) => ({
220
- id: `ISSUE${n}`,
221
- number: n,
222
- state: rows.get(n).state.toUpperCase(),
223
- title: rows.get(n).title,
224
- repository: { nameWithOwner: 'example/widget' },
225
- })),
226
- pageInfo: { hasNextPage: false, endCursor: null },
227
- },
228
- },
229
- },
230
- };
231
- if (query.includes('mutation') && (query.includes('addBlockedBy') || query.includes('removeBlockedBy'))) {
232
- writes.push('dependency');
233
- const dependent = Number(String(variables.issue).replace(/\D/gu, ''));
234
- const blocker = Number(String(variables.blocking).replace(/\D/gu, ''));
235
- blockers.set(dependent, query.includes('addBlockedBy')
236
- ? [...new Set([...(blockers.get(dependent) ?? []), blocker])]
237
- : (blockers.get(dependent) ?? []).filter((n) => n !== blocker));
238
- return {};
16
+ const rows = new Map(
17
+ Array.from({ length: 5 }, (_, index) => {
18
+ const number = index + 1;
19
+ return [
20
+ number,
21
+ {
22
+ number,
23
+ id: number + 100,
24
+ node_id: `ISSUE${number}`,
25
+ title: `Synthetic item ${number}`,
26
+ body: renderIssueBody(IssueFields.parse({ title: `Synthetic item ${number}`, draft: true })),
27
+ state: "open",
28
+ type: { name: "Task" },
29
+ labels: [],
30
+ milestone: null,
31
+ html_url: `https://github.com/example/widget/issues/${number}`
32
+ }
33
+ ];
34
+ })
35
+ );
36
+ const writes = [];
37
+ const dateWrites = [];
38
+ const controls = {
39
+ failAfterWrite: 0,
40
+ failReadback: 0,
41
+ driftOnRead: 0,
42
+ rateLimited: 0,
43
+ ignoreLabels: false,
44
+ parentRepository: "example/widget",
45
+ parentNodeId: "",
46
+ archived: false,
47
+ archiveAfterWrite: false,
48
+ loseProjectAck: false,
49
+ projectUnavailableAfterDependency: false,
50
+ nativeUnavailableAfterDependency: false,
51
+ moveProjectToTodoAfterWrite: false,
52
+ projectReadsAfterWrite: 0
53
+ };
54
+ const reads = /* @__PURE__ */ new Map();
55
+ const metadata = /* @__PURE__ */ new Map();
56
+ const parents = /* @__PURE__ */ new Map();
57
+ const blockers = /* @__PURE__ */ new Map();
58
+ const reasons = /* @__PURE__ */ new Map();
59
+ const duplicates = /* @__PURE__ */ new Map();
60
+ const fieldValues = (number) => Object.entries(metadata.get(number) ?? {}).map(([id, value]) => ({
61
+ data_type: Number(id) >= 103 ? "date" : "single_select",
62
+ issue_field_id: Number(id),
63
+ issue_field_name: id === "101" ? "Estimate" : id === "102" ? "Urgency" : id === "103" ? "Start date" : "Target date",
64
+ value
65
+ }));
66
+ const comments = [];
67
+ const statuses = new Map(Array.from(rows.keys(), (number) => [number, "Active"]));
68
+ const statusOptionIds = {
69
+ "In Review": "REVIEW",
70
+ Active: "ACTIVE",
71
+ Shipped: "DONE",
72
+ Waiting: "BLOCKED"
73
+ };
74
+ const context = {
75
+ root: "/synthetic",
76
+ repo: { owner: "example", repo: "widget" },
77
+ config: syntheticDiscoveryConfig,
78
+ projectConfiguration: {
79
+ projectId: "PROJECT",
80
+ projectNumber: 1,
81
+ title: "Delivery",
82
+ writable: true,
83
+ pointsFieldId: "POINTS",
84
+ priorityFieldId: "PRIORITY",
85
+ statusFieldId: "STATUS",
86
+ statusOptionIds: { Todo: "TODO", "In Progress": "ACTIVE", Blocked: "BLOCKED", Done: "DONE" },
87
+ reviewOptionId: "REVIEW",
88
+ settings: {
89
+ number: 1,
90
+ title: "Delivery",
91
+ statusField: "Flow",
92
+ statuses: { Todo: "Queued", "In Progress": "Active", Blocked: "Waiting", Done: "Shipped" }
93
+ }
94
+ },
95
+ clients: {
96
+ role: "author",
97
+ authenticatedAuthor: async () => ({ actorLogin: "operator", credentialIdentity: "user:1" }),
98
+ rest: {
99
+ issues: {
100
+ get: async ({ issue_number }) => {
101
+ if (controls.nativeUnavailableAfterDependency && writes.includes("dependency"))
102
+ throw new Error("PRIVATE_NATIVE_READ_FAILURE");
103
+ reads.set(issue_number, (reads.get(issue_number) ?? 0) + 1);
104
+ if (controls.failReadback === issue_number && writes.includes(`update:${issue_number}`))
105
+ throw new Error("Synthetic readback transport failure");
106
+ const row = rows.get(issue_number);
107
+ if (row && controls.driftOnRead === issue_number && reads.get(issue_number) === 2)
108
+ row.body = "Concurrent operator edit";
109
+ if (!row) throw new Error("Synthetic issue unavailable");
110
+ return { data: structuredClone(row) };
111
+ },
112
+ listComments: async ({ issue_number }) => ({
113
+ data: comments.filter((comment) => comment.issue_url.endsWith("/" + String(issue_number)))
114
+ }),
115
+ listLabelsForRepo: async () => ({ data: [{ name: "enhancement" }] }),
116
+ listSubIssues: async () => ({ data: [] }),
117
+ addSubIssue: async ({ issue_number, sub_issue_id }) => {
118
+ writes.push("parent");
119
+ parents.set(sub_issue_id - 100, issue_number);
120
+ return { data: {} };
121
+ },
122
+ removeSubIssue: async ({ sub_issue_id }) => {
123
+ writes.push("parent");
124
+ parents.delete(sub_issue_id - 100);
125
+ return { data: {} };
126
+ },
127
+ createComment: async ({ issue_number, body }) => {
128
+ writes.push("comment");
129
+ const comment = {
130
+ id: comments.length + 1e3,
131
+ body,
132
+ html_url: `https://github.com/example/widget/issues/${issue_number}#issuecomment-${comments.length + 1e3}`,
133
+ user: { login: "operator" },
134
+ issue_url: `https://api.github.com/repos/example/widget/issues/${issue_number}`
135
+ };
136
+ comments.push(comment);
137
+ return { data: comment };
138
+ },
139
+ getComment: async ({ comment_id }) => ({
140
+ data: comments.find((comment) => comment.id === comment_id)
141
+ }),
142
+ update: async ({ issue_number, ...patch }) => {
143
+ writes.push(`update:${issue_number}`);
144
+ if (controls.moveProjectToTodoAfterWrite) statuses.set(issue_number, "Queued");
145
+ if (controls.archiveAfterWrite) controls.archived = true;
146
+ if (controls.rateLimited === issue_number)
147
+ throw Object.assign(new Error("PRIVATE_REMOTE_CONTENT"), {
148
+ status: 429,
149
+ response: {
150
+ headers: {
151
+ "retry-after": "60",
152
+ "x-ratelimit-remaining": "0",
153
+ "x-ratelimit-reset": "1900000000",
154
+ authorization: "PRIVATE_TOKEN"
155
+ }
239
156
  }
240
- if (query.includes('ProjectDeliveryItems'))
241
- return {
242
- organization: {
243
- projectV2: {
244
- items: {
245
- nodes: [...rows.keys()].map((n) => ({
246
- id: `ITEM${n}`,
247
- isArchived: false,
248
- content: { id: `ISSUE${n}` },
249
- fieldValueByName: {
250
- name: statuses.get(n),
251
- optionId: statuses.get(n) === 'Active'
252
- ? 'ACTIVE'
253
- : statuses.get(n) === 'Shipped'
254
- ? 'DONE'
255
- : statuses.get(n) === 'Waiting'
256
- ? 'BLOCKED'
257
- : 'TODO',
258
- },
259
- })),
260
- pageInfo: { hasNextPage: false, endCursor: null },
261
- },
262
- },
263
- },
264
- };
265
- if (query.includes('UpdateProjectDeliveryStatus')) {
266
- writes.push('project');
267
- statuses.set(number, variables.optionId === 'DONE'
268
- ? 'Shipped'
269
- : variables.optionId === 'BLOCKED'
270
- ? 'Waiting'
271
- : variables.optionId === 'ACTIVE'
272
- ? 'Active'
273
- : 'Queued');
274
- return { updateProjectV2ItemFieldValue: { projectV2Item: { id: `ITEM${number}` } } };
275
- }
276
- if (query.includes('ProjectDeliveryItemReadback'))
277
- return {
278
- node: {
279
- id: `ITEM${number}`,
280
- isArchived: false,
281
- project: { id: 'PROJECT', number: 1 },
282
- content: { id: `ISSUE${number}` },
283
- fieldValueByName: {
284
- name: statuses.get(number),
285
- optionId: statuses.get(number) === 'Active'
286
- ? 'ACTIVE'
287
- : statuses.get(number) === 'Shipped'
288
- ? 'DONE'
289
- : statuses.get(number) === 'Waiting'
290
- ? 'BLOCKED'
291
- : 'TODO',
292
- },
293
- },
294
- };
295
- throw new Error('Unexpected synthetic native query');
296
- },
157
+ });
158
+ const row = rows.get(issue_number);
159
+ if (typeof patch.title === "string") row.title = patch.title;
160
+ if (typeof patch.body === "string") row.body = patch.body;
161
+ if (typeof patch.type === "string") row.type = { name: patch.type };
162
+ if (Array.isArray(patch.labels) && !controls.ignoreLabels)
163
+ row.labels = patch.labels.map((label) => label.toLowerCase());
164
+ if (patch.milestone !== void 0)
165
+ Object.assign(row, { milestone: patch.milestone === null ? null : { number: patch.milestone } });
166
+ if (typeof patch.state === "string") {
167
+ row.state = patch.state;
168
+ reasons.set(
169
+ issue_number,
170
+ patch.state === "closed" ? (typeof patch.state_reason === "string" ? patch.state_reason : "completed").toUpperCase() : "REOPENED"
171
+ );
172
+ }
173
+ if (typeof patch.duplicate_issue_id === "number")
174
+ duplicates.set(issue_number, patch.duplicate_issue_id - 100);
175
+ if (controls.failAfterWrite === issue_number) {
176
+ controls.failAfterWrite = 0;
177
+ throw new Error("Synthetic acknowledgement lost");
178
+ }
179
+ return { data: rows.get(issue_number) };
180
+ }
297
181
  },
298
- };
299
- vi.spyOn(configuration, 'loadDeliverySettings').mockResolvedValue({
300
- roles: { author: { identity: 'host-author', authSource: 'personal' }, reviewer: { identity: 'app-reviewer' } },
301
- });
302
- vi.spyOn(issue, 'loadDeliveryContext').mockResolvedValue(context);
303
- return { context, rows, writes, comments, controls, metadata, parents, blockers, statuses };
182
+ paginate: async (_method, { issue_number }) => [...parents].filter(([, parent]) => parent === issue_number).map(([number]) => rows.get(number)),
183
+ request: async (route, params) => {
184
+ if (route.startsWith("GET /orgs"))
185
+ return {
186
+ data: [
187
+ ...Object.values(syntheticDiscoveryConfig.native).filter(
188
+ (field) => typeof field === "object" && field !== null && "databaseId" in field
189
+ ).map((field) => ({
190
+ id: Number(field.databaseId),
191
+ name: field.name,
192
+ data_type: "single_select",
193
+ options: field.values.map((name) => ({ name }))
194
+ })),
195
+ { id: 103, name: "Start date", data_type: "date" },
196
+ { id: 104, name: "Target date", data_type: "date" }
197
+ ]
198
+ };
199
+ if (route.startsWith("POST ")) {
200
+ const dates = params.issue_field_values.filter((value) => value.field_id >= 103);
201
+ if (dates.length) dateWrites.push(dates.map((value) => value.field_id));
202
+ writes.push("metadata");
203
+ metadata.set(params.issue_number, {
204
+ ...metadata.get(params.issue_number),
205
+ ...Object.fromEntries(params.issue_field_values.map((value) => [String(value.field_id), value.value]))
206
+ });
207
+ }
208
+ if (route.startsWith("DELETE ")) {
209
+ if (params.issue_field_id >= 103) dateWrites.push([params.issue_field_id]);
210
+ writes.push("metadata");
211
+ delete metadata.get(params.issue_number)[String(params.issue_field_id)];
212
+ }
213
+ return { data: fieldValues(params.issue_number) };
214
+ }
215
+ },
216
+ graphql: async (query, variables) => {
217
+ if (controls.moveProjectToTodoAfterWrite && writes.includes("update:1") && query.includes("ProjectDeliveryIssueItems") && ++controls.projectReadsAfterWrite === 2)
218
+ throw new Error("PRIVATE_SYNC_READ_FAILURE");
219
+ if (controls.projectUnavailableAfterDependency && writes.includes("dependency") && query.includes("ProjectDelivery"))
220
+ throw new Error("PRIVATE_PROJECT_READ_FAILURE");
221
+ const numeric = variables.number ?? variables.issueNumber;
222
+ const nodeId = variables.issueNodeId ?? variables.itemId ?? "1";
223
+ const number = typeof numeric === "number" ? numeric : typeof nodeId === "string" ? Number(nodeId.replace(/\D/gu, "")) : NaN;
224
+ if (query.includes("IssueClosureReadback"))
225
+ return {
226
+ repository: {
227
+ issue: {
228
+ number,
229
+ repository: { nameWithOwner: "example/widget" },
230
+ state: rows.get(number).state.toUpperCase(),
231
+ stateReason: reasons.get(number) ?? null,
232
+ duplicateOf: duplicates.has(number) ? { number: duplicates.get(number), repository: { nameWithOwner: "example/widget" } } : null
233
+ }
234
+ }
235
+ };
236
+ if (query.includes("blockedBy(first:"))
237
+ return {
238
+ repository: {
239
+ issue: {
240
+ parent: parents.has(number) ? {
241
+ id: controls.parentNodeId || `ISSUE${parents.get(number)}`,
242
+ number: parents.get(number),
243
+ repository: { nameWithOwner: controls.parentRepository }
244
+ } : null,
245
+ blockedBy: {
246
+ nodes: (blockers.get(number) ?? []).map((n) => ({
247
+ id: `ISSUE${n}`,
248
+ number: n,
249
+ state: rows.get(n).state.toUpperCase(),
250
+ title: rows.get(n).title,
251
+ repository: { nameWithOwner: "example/widget" }
252
+ })),
253
+ pageInfo: { hasNextPage: false, endCursor: null }
254
+ }
255
+ }
256
+ }
257
+ };
258
+ if (query.includes("mutation") && (query.includes("addBlockedBy") || query.includes("removeBlockedBy"))) {
259
+ writes.push("dependency");
260
+ const dependent = Number(String(variables.issue).replace(/\D/gu, ""));
261
+ const blocker = Number(String(variables.blocking).replace(/\D/gu, ""));
262
+ blockers.set(
263
+ dependent,
264
+ query.includes("addBlockedBy") ? [.../* @__PURE__ */ new Set([...blockers.get(dependent) ?? [], blocker])] : (blockers.get(dependent) ?? []).filter((n) => n !== blocker)
265
+ );
266
+ return {};
267
+ }
268
+ if (query.includes("ProjectDeliveryIssueItems"))
269
+ return issueProjectItemsResponse(
270
+ variables,
271
+ [...rows.keys()].filter((n) => `ISSUE${n}` === variables.issueNodeId).map((n) => ({
272
+ id: `ITEM${n}`,
273
+ isArchived: controls.archived,
274
+ content: { id: `ISSUE${n}` },
275
+ fieldValueByName: {
276
+ name: statuses.get(n),
277
+ optionId: statusOptionIds[statuses.get(n)] ?? "TODO"
278
+ }
279
+ }))
280
+ );
281
+ if (query.includes("UpdateProjectDeliveryStatus")) {
282
+ writes.push("project");
283
+ statuses.set(
284
+ number,
285
+ variables.optionId === "DONE" ? "Shipped" : variables.optionId === "BLOCKED" ? "Waiting" : variables.optionId === "ACTIVE" ? "Active" : "Queued"
286
+ );
287
+ if (controls.loseProjectAck) {
288
+ controls.loseProjectAck = false;
289
+ throw new Error("PRIVATE_PROJECT_ACK");
290
+ }
291
+ return { updateProjectV2ItemFieldValue: { projectV2Item: { id: `ITEM${number}` } } };
292
+ }
293
+ if (query.includes("ProjectDeliveryItemReadback"))
294
+ return {
295
+ node: {
296
+ id: `ITEM${number}`,
297
+ isArchived: false,
298
+ project: { id: "PROJECT", number: 1 },
299
+ content: { id: `ISSUE${number}` },
300
+ fieldValueByName: {
301
+ name: statuses.get(number),
302
+ optionId: statusOptionIds[statuses.get(number)] ?? "TODO"
303
+ }
304
+ }
305
+ };
306
+ throw new Error("Unexpected synthetic native query");
307
+ }
308
+ }
309
+ };
310
+ vi.spyOn(configuration, "loadDeliverySettings").mockResolvedValue({
311
+ roles: { author: { identity: "host-author", authSource: "personal" }, reviewer: { identity: "app-reviewer" } }
312
+ });
313
+ vi.spyOn(issue, "loadDeliveryContext").mockResolvedValue(context);
314
+ return { context, rows, writes, dateWrites, comments, controls, metadata, parents, blockers, statuses };
304
315
  }
305
316
  afterEach(() => vi.restoreAllMocks());
306
- test('batch dry run returns each planned title change without native writes', async () => {
307
- const f = batchFixture();
308
- const result = (await executeTool('issue_batch_update', {
309
- repo: 'example/widget',
310
- dryRun: true,
311
- items: [
312
- { issueNumber: 1, title: 'First requested title' },
313
- { issueNumber: 2, title: 'Second requested title' },
314
- ],
315
- }, { repoRoot: '/synthetic', identity: 'host-author' }));
316
- assert.equal(result.dryRun, true);
317
- assert.deepEqual(result.results.map((item) => [item.issueNumber, item.changes.title, item.readback.title]), [
318
- [1, 'First requested title', 'Synthetic item 1'],
319
- [2, 'Second requested title', 'Synthetic item 2'],
320
- ]);
321
- assert.deepEqual(f.writes, []);
322
- assert.equal(f.rows.get(1).title, 'Synthetic item 1');
317
+ test("batch dry run returns each planned title change without native writes", async () => {
318
+ const f = batchFixture();
319
+ const result = await executeTool(
320
+ "issue_batch_update",
321
+ {
322
+ repo: "example/widget",
323
+ dryRun: true,
324
+ items: [
325
+ { issueNumber: 1, title: "First requested title" },
326
+ { issueNumber: 2, title: "Second requested title" }
327
+ ]
328
+ },
329
+ { repoRoot: "/synthetic", identity: "host-author" }
330
+ );
331
+ assert.equal(result.dryRun, true);
332
+ assert.deepEqual(
333
+ result.results.map((item) => [item.issueNumber, item.changes.title, item.readback.title]),
334
+ [
335
+ [1, "First requested title", "Synthetic item 1"],
336
+ [2, "Second requested title", "Synthetic item 2"]
337
+ ]
338
+ );
339
+ assert.deepEqual(f.writes, []);
340
+ assert.equal(f.rows.get(1).title, "Synthetic item 1");
323
341
  });
324
342
  async function runBatch(input) {
325
- return executeTool('issue_batch_update', { repo: 'example/widget', ...input }, { repoRoot: '/synthetic', identity: 'host-author' });
343
+ return executeTool(
344
+ "issue_batch_update",
345
+ { repo: "example/widget", ...input },
346
+ { repoRoot: "/synthetic", identity: "host-author" }
347
+ );
326
348
  }
327
- test.each([{}, { status: { nextMilestone: 'Run checks' } }, { blockedBy: [2] }])('canonical-body retries with overrides %j preserve generated timestamps and history', async (overrides) => {
328
- const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-17T00:00:00.000Z'));
349
+ test.each([{}, { status: { nextMilestone: "Run checks" } }, { blockedBy: [2] }])(
350
+ "canonical-body retries with overrides %j preserve generated timestamps and history",
351
+ async (overrides) => {
352
+ const clock = vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-10-17T00:00:00.000Z"));
329
353
  const f = batchFixture();
330
- const body = renderIssueBody(IssueFields.parse({ title: 'Synthetic item 1', draft: true, problem: 'Changed contract' }), {
331
- state: 'Draft',
332
- lastUpdated: '2026-01-01T00:00:00.000Z',
333
- nextMilestone: 'Not started',
334
- blockers: 'None',
335
- latestJournal: 'None yet',
336
- });
337
- f.statuses.set(1, 'Queued');
354
+ const body = renderIssueBody(
355
+ IssueFields.parse({ title: "Synthetic item 1", draft: true, problem: "Changed contract" }),
356
+ {
357
+ state: "Draft",
358
+ lastUpdated: "2026-01-01T00:00:00.000Z",
359
+ nextMilestone: "Not started",
360
+ blockers: "None",
361
+ latestJournal: "None yet"
362
+ }
363
+ );
364
+ f.statuses.set(1, "Queued");
338
365
  const input = { items: [{ issueNumber: 1, body, preserveHistory: true, ...overrides }] };
339
366
  const first = await runBatch(input);
340
- assert.equal(first.results[0].status, 'applied', JSON.stringify(first));
367
+ assert.equal(first.results[0].status, "applied", JSON.stringify(first));
341
368
  const writtenBody = f.rows.get(1).body;
342
369
  const writes = [...f.writes];
343
370
  const comments = [...f.comments];
344
- clock.mockReturnValue(Date.parse('2026-10-17T00:01:00.000Z'));
371
+ clock.mockReturnValue(Date.parse("2026-10-17T00:01:00.000Z"));
345
372
  const retry = await runBatch(input);
346
- assert.equal(retry.results[0].status, 'unchanged', JSON.stringify(retry));
373
+ assert.equal(retry.results[0].status, "unchanged", JSON.stringify(retry));
347
374
  assert.equal(f.rows.get(1).body, writtenBody);
348
375
  assert.deepEqual(f.writes, writes);
349
376
  assert.deepEqual(f.comments, comments);
350
- clock.mockReturnValue(Date.parse('2026-10-17T00:02:00.000Z'));
351
- assert.equal((await runBatch(input)).results[0].status, 'unchanged');
377
+ clock.mockReturnValue(Date.parse("2026-10-17T00:02:00.000Z"));
378
+ assert.equal((await runBatch(input)).results[0].status, "unchanged");
352
379
  assert.deepEqual(f.writes, writes);
353
380
  assert.deepEqual(f.comments, comments);
354
- });
381
+ }
382
+ );
355
383
  test.each([
356
- ['foreign/repository', 'FOREIGN5'],
357
- ['example/widget', 'DIFFERENT5'],
358
- ])('same-number parent in %s with node %s cannot satisfy a batch retry', async (repository, nodeId) => {
359
- const f = batchFixture();
360
- const input = { items: [{ issueNumber: 1, parentIssueNumber: 5 }] };
361
- assert.equal((await runBatch(input)).results[0].status, 'applied');
362
- const writes = [...f.writes];
363
- f.controls.parentRepository = repository;
364
- f.controls.parentNodeId = nodeId;
365
- const result = await runBatch(input);
366
- assert.equal(result.results[0].status, 'failed', JSON.stringify(result));
367
- assert.deepEqual(f.writes, writes);
384
+ ["foreign/repository", "FOREIGN5"],
385
+ ["example/widget", "DIFFERENT5"]
386
+ ])("same-number parent in %s with node %s cannot satisfy a batch retry", async (repository, nodeId) => {
387
+ const f = batchFixture();
388
+ const input = { items: [{ issueNumber: 1, parentIssueNumber: 5 }] };
389
+ assert.equal((await runBatch(input)).results[0].status, "applied");
390
+ const writes = [...f.writes];
391
+ f.controls.parentRepository = repository;
392
+ f.controls.parentNodeId = nodeId;
393
+ const result = await runBatch(input);
394
+ assert.equal(result.results[0].status, "failed", JSON.stringify(result));
395
+ assert.deepEqual(f.writes, writes);
368
396
  });
369
- test('correctable local batch refusals retain distinct bounded reasons', async () => {
370
- const f = batchFixture();
371
- const result = await runBatch({
372
- items: [
373
- { issueNumber: 1, priority: 'Unsupported' },
374
- { issueNumber: 2, labels: ['unknown-label-private-content'] },
375
- { issueNumber: 3, blocks: [4] },
376
- ],
377
- });
378
- assert.deepEqual(result.results.map((item) => item.status), ['failed', 'failed', 'failed']);
379
- assert.match(result.results[0].reason, /configured Priority/u);
380
- assert.match(result.results[1].reason, /labels.*selected repository/u);
381
- assert.match(result.results[2].reason, /overrideReason/u);
382
- assert.equal(JSON.stringify(result).includes('unknown-label-private-content'), false);
383
- assert.deepEqual(f.writes, []);
397
+ test("correctable local batch refusals retain distinct bounded reasons", async () => {
398
+ const f = batchFixture();
399
+ const result = await runBatch({
400
+ items: [
401
+ { issueNumber: 1, priority: "Unsupported" },
402
+ { issueNumber: 2, labels: ["unknown-label-private-content"] },
403
+ { issueNumber: 3, blocks: [4] }
404
+ ]
405
+ });
406
+ assert.deepEqual(
407
+ result.results.map((item) => item.status),
408
+ ["failed", "failed", "failed"]
409
+ );
410
+ assert.match(result.results[0].reason, /configured Priority/u);
411
+ assert.match(result.results[1].reason, /labels.*selected repository/u);
412
+ assert.match(result.results[2].reason, /overrideReason/u);
413
+ assert.equal(JSON.stringify(result).includes("unknown-label-private-content"), false);
414
+ assert.deepEqual(f.writes, []);
384
415
  });
385
- test('a conflicting closure reason explains the required explicit reopen without more writes', async () => {
386
- const f = batchFixture();
387
- assert.equal((await runBatch({ items: [{ issueNumber: 1, state: 'closed', closeReason: 'not_planned' }] })).results[0].status, 'applied');
388
- const writes = [...f.writes];
389
- const comments = [...f.comments];
390
- const result = await runBatch({ items: [{ issueNumber: 1, state: 'closed', closeReason: 'completed' }] });
391
- assert.equal(result.results[0].status, 'failed');
392
- assert.match(result.results[0].reason, /different closure evidence; reopen it explicitly/u);
393
- assert.deepEqual(f.writes, writes);
394
- assert.deepEqual(f.comments, comments);
416
+ test("a conflicting closure reason explains the required explicit reopen without more writes", async () => {
417
+ const f = batchFixture();
418
+ assert.equal(
419
+ (await runBatch({ items: [{ issueNumber: 1, state: "closed", closeReason: "not_planned" }] })).results[0].status,
420
+ "applied"
421
+ );
422
+ const writes = [...f.writes];
423
+ const comments = [...f.comments];
424
+ const result = await runBatch({ items: [{ issueNumber: 1, state: "closed", closeReason: "completed" }] });
425
+ assert.equal(result.results[0].status, "failed");
426
+ assert.match(result.results[0].reason, /different closure evidence; reopen it explicitly/u);
427
+ assert.deepEqual(f.writes, writes);
428
+ assert.deepEqual(f.comments, comments);
395
429
  });
396
- test('unknown remote errors, message getters and proxies retain the generic safe batch failure', async () => {
397
- const f = batchFixture();
398
- let inspected = 0;
399
- const getter = Object.defineProperty(new DeliveryError(''), 'message', {
400
- get() {
401
- inspected++;
402
- throw new Error('PRIVATE_GETTER_CONTENT');
403
- },
404
- });
405
- const proxy = new Proxy(new DeliveryError('PRIVATE_PROXY_CONTENT'), {
406
- get() {
407
- inspected++;
408
- throw new Error('PRIVATE_PROXY_CONTENT');
409
- },
410
- getPrototypeOf() {
411
- inspected++;
412
- throw new Error('PRIVATE_PROXY_CONTENT');
413
- },
414
- });
415
- const get = vi.spyOn(f.context.clients.rest.issues, 'get');
416
- for (const error of [new DeliveryError('PRIVATE_REMOTE_CONTENT'), getter, proxy]) {
417
- get.mockRejectedValue(error);
418
- const result = await runBatch({ items: [{ issueNumber: 1, title: 'Requested update' }] });
419
- assert.equal(result.results[0].status, 'failed');
420
- assert.match(result.results[0].reason, /preparation failed/u);
421
- assert.equal(JSON.stringify(result).includes('PRIVATE_'), false);
430
+ test("unknown remote errors, message getters and proxies retain the generic safe batch failure", async () => {
431
+ const f = batchFixture();
432
+ let inspected = 0;
433
+ const getter = Object.defineProperty(new DeliveryError(""), "message", {
434
+ get() {
435
+ inspected++;
436
+ throw new Error("PRIVATE_GETTER_CONTENT");
422
437
  }
423
- assert.equal(inspected, 0);
424
- assert.deepEqual(f.writes, []);
438
+ });
439
+ const proxy = new Proxy(new DeliveryError("PRIVATE_PROXY_CONTENT"), {
440
+ get() {
441
+ inspected++;
442
+ throw new Error("PRIVATE_PROXY_CONTENT");
443
+ },
444
+ getPrototypeOf() {
445
+ inspected++;
446
+ throw new Error("PRIVATE_PROXY_CONTENT");
447
+ }
448
+ });
449
+ const get = vi.spyOn(f.context.clients.rest.issues, "get");
450
+ for (const error of [new DeliveryError("PRIVATE_REMOTE_CONTENT"), getter, proxy]) {
451
+ get.mockRejectedValue(error);
452
+ const result = await runBatch({ items: [{ issueNumber: 1, title: "Requested update" }] });
453
+ assert.equal(result.results[0].status, "failed");
454
+ assert.match(result.results[0].reason, /preparation failed/u);
455
+ assert.equal(JSON.stringify(result).includes("PRIVATE_"), false);
456
+ }
457
+ assert.equal(inspected, 0);
458
+ assert.deepEqual(f.writes, []);
425
459
  });
426
- test('mixed failures retain later results and a rerun reports unchanged native outcomes', async () => {
427
- const f = batchFixture();
428
- const input = {
429
- items: [
430
- { issueNumber: 1, title: 'Changed title' },
431
- { issueNumber: 99, title: 'Missing target' },
432
- { issueNumber: 2, defer: { trigger: 'Review next sprint' } },
433
- ],
434
- };
435
- const first = await runBatch(input);
436
- assert.deepEqual(first.results.map((item) => item.status), ['applied', 'failed', 'applied']);
437
- assert.equal(first.results[0].readback.title, 'Changed title');
438
- assert.match(first.results[1].reason, /preparation failed/u);
439
- assert.match(first.results[1].readbackError, /unavailable/u);
440
- assert.deepEqual(first.results[2].readback.deferred, { trigger: 'Review next sprint' });
441
- const writes = f.writes.length;
442
- const second = await runBatch(input);
443
- assert.deepEqual(second.results.map((item) => item.status), ['unchanged', 'failed', 'unchanged']);
444
- assert.equal(f.writes.length, writes);
460
+ test("mixed failures retain later results and a rerun reports unchanged native outcomes", async () => {
461
+ const f = batchFixture();
462
+ const input = {
463
+ items: [
464
+ { issueNumber: 1, title: "Changed title" },
465
+ { issueNumber: 99, title: "Missing target" },
466
+ { issueNumber: 2, defer: { trigger: "Review next sprint" } }
467
+ ]
468
+ };
469
+ const first = await runBatch(input);
470
+ assert.deepEqual(
471
+ first.results.map((item) => item.status),
472
+ ["applied", "failed", "applied"]
473
+ );
474
+ assert.equal(first.results[0].readback.title, "Changed title");
475
+ assert.match(first.results[1].reason, /preparation failed/u);
476
+ assert.match(first.results[1].readbackError, /unavailable/u);
477
+ assert.deepEqual(first.results[2].readback.deferred, { trigger: "Review next sprint" });
478
+ const writes = f.writes.length;
479
+ const second = await runBatch(input);
480
+ assert.deepEqual(
481
+ second.results.map((item) => item.status),
482
+ ["unchanged", "failed", "unchanged"]
483
+ );
484
+ assert.equal(f.writes.length, writes);
445
485
  });
446
- test('lost acknowledgement exposes partial state and a rerun completes remaining Project work', async () => {
447
- const f = batchFixture();
448
- f.controls.failAfterWrite = 1;
449
- const input = {
450
- items: [
451
- { issueNumber: 1, title: 'Acknowledgement lost', preserveHistory: true },
452
- { issueNumber: 2, title: 'Later item proceeds' },
453
- ],
454
- };
455
- const first = await runBatch(input);
456
- assert.deepEqual(first.results.map((item) => item.status), ['failed', 'applied']);
457
- assert.equal(first.results[0].readback.title, 'Acknowledgement lost');
458
- assert.equal(first.results[0].readback.projectStatus, 'In Progress');
459
- const historyCount = f.comments.length;
460
- const second = await runBatch(input);
461
- assert.deepEqual(second.results.map((item) => item.status), ['applied', 'unchanged']);
462
- assert.equal(second.results[0].readback.projectStatus, 'Todo');
463
- assert.equal(f.comments.length, historyCount);
464
- assert.deepEqual((await runBatch(input)).results.map((item) => item.status), ['unchanged', 'unchanged']);
486
+ test("lost acknowledgement exposes partial state and a rerun completes remaining Project work", async () => {
487
+ const f = batchFixture();
488
+ f.controls.failAfterWrite = 1;
489
+ const input = {
490
+ items: [
491
+ { issueNumber: 1, title: "Acknowledgement lost", preserveHistory: true },
492
+ { issueNumber: 2, title: "Later item proceeds" }
493
+ ]
494
+ };
495
+ const first = await runBatch(input);
496
+ assert.deepEqual(
497
+ first.results.map((item) => item.status),
498
+ ["failed", "applied"]
499
+ );
500
+ assert.equal(first.results[0].readback.title, "Acknowledgement lost");
501
+ assert.equal(first.results[0].readback.projectStatus, "In Progress");
502
+ const historyCount = f.comments.length;
503
+ const second = await runBatch(input);
504
+ assert.deepEqual(
505
+ second.results.map((item) => item.status),
506
+ ["applied", "unchanged"]
507
+ );
508
+ assert.equal(second.results[0].readback.projectStatus, "Todo");
509
+ assert.equal(f.comments.length, historyCount);
510
+ assert.equal(
511
+ f.writes.filter((write) => write.startsWith("update:1")).length,
512
+ 1,
513
+ "recovery must not replay the committed native update"
514
+ );
515
+ assert.deepEqual(
516
+ (await runBatch(input)).results.map((item) => item.status),
517
+ ["unchanged", "unchanged"]
518
+ );
465
519
  });
466
- test('dry run plans close, defer, metadata, parent Points and dependency side effects without writes', async () => {
467
- const f = batchFixture();
468
- f.metadata.set(5, { '101': '4' });
469
- f.statuses.set(4, 'Queued');
470
- const result = await runBatch({
471
- dryRun: true,
472
- items: [
473
- { issueNumber: 1, state: 'closed', closeReason: 'duplicate', supersededBy: 5 },
474
- { issueNumber: 2, defer: { until: '2026-12-01' }, preserveHistory: true },
475
- { issueNumber: 3, labels: ['enhancement'], milestone: 1, points: 2, priority: 'High', parentIssueNumber: 5 },
476
- { issueNumber: 4, blockedBy: [2] },
477
- ],
478
- });
479
- assert.deepEqual(result.results.map((item) => item.status), ['planned', 'planned', 'planned', 'planned']);
480
- assert.deepEqual(result.results[2].changes.parentPoints, { issueNumber: 5, points: null });
481
- assert.deepEqual(result.results[3].changes.blockedBy, [2]);
482
- assert.equal(result.results[0].changes.closureComment, true);
483
- assert.deepEqual(f.writes, []);
484
- assert.deepEqual(f.metadata.get(5), { '101': '4' });
485
- assert.equal(f.rows.get(1).state, 'open');
520
+ test("archived partial closure resumes only Project work after separate restoration and then becomes a no-op", async () => {
521
+ const f = batchFixture();
522
+ const unrelated = structuredClone(f.rows.get(2));
523
+ f.rows.get(1).labels.push("enhancement");
524
+ f.controls.archiveAfterWrite = true;
525
+ const input = {
526
+ items: [
527
+ {
528
+ issueNumber: 1,
529
+ title: "Closed item",
530
+ state: "closed",
531
+ closeReason: "not_planned",
532
+ preserveHistory: true
533
+ }
534
+ ]
535
+ };
536
+ const first = await runBatch(input);
537
+ assert.equal(first.summary.failed, 1);
538
+ assert.equal(f.rows.get(1).state, "closed");
539
+ const nativeWrites = f.writes.filter((write) => write !== "project");
540
+ const comments = structuredClone(f.comments);
541
+ const archived = await runBatch(input);
542
+ assert.equal(archived.summary.failed, 1);
543
+ assert.deepEqual(
544
+ f.writes.filter((write) => write !== "project"),
545
+ nativeWrites
546
+ );
547
+ assert.deepEqual(f.comments, comments);
548
+ f.controls.archiveAfterWrite = false;
549
+ f.controls.archived = false;
550
+ const resumed = await runBatch(input);
551
+ assert.equal(resumed.summary.applied, 1);
552
+ assert.equal(resumed.results[0].readback.projectStatus, "Done");
553
+ assert.deepEqual(
554
+ f.writes.filter((write) => write !== "project"),
555
+ nativeWrites
556
+ );
557
+ assert.deepEqual(f.comments, comments);
558
+ const count = f.writes.length;
559
+ assert.equal((await runBatch(input)).summary.unchanged, 1);
560
+ assert.equal(f.writes.length, count);
561
+ assert.deepEqual(f.rows.get(1).labels, ["enhancement"]);
562
+ assert.deepEqual(f.rows.get(2), unrelated);
486
563
  });
487
- test('unchanged includes labels, metadata, native parent Points and blocker relationships', async () => {
488
- const f = batchFixture();
489
- f.metadata.set(5, { '101': '4' });
490
- f.statuses.set(3, 'Queued');
491
- const input = {
492
- items: [
493
- {
494
- issueNumber: 3,
495
- labels: ['enhancement'],
496
- milestone: 1,
497
- points: 2,
498
- priority: 'High',
499
- parentIssueNumber: 5,
500
- blockedBy: [2],
501
- },
502
- ],
503
- };
504
- const first = await runBatch(input);
505
- assert.equal(first.results[0].status, 'applied', JSON.stringify(first));
506
- assert.deepEqual(first.results[0].readback.labels, ['enhancement']);
507
- assert.equal(first.results[0].readback.milestone, 1);
508
- assert.equal(first.results[0].readback.points, 2);
509
- assert.equal(first.results[0].readback.priority, 'High');
510
- assert.equal(f.parents.get(3), 5);
511
- assert.equal(f.metadata.get(5)['101'], undefined);
512
- assert.deepEqual(f.blockers.get(3), [2]);
513
- assert.equal((await runBatch(input)).results[0].status, 'unchanged');
514
- f.metadata.set(5, { '101': '4' });
515
- assert.equal((await runBatch(input)).results[0].status, 'applied', 'Parent Points repair cannot be classified unchanged');
564
+ test("archived date and parent updates resume only Project work without replaying committed native fields", async () => {
565
+ const f = batchFixture();
566
+ f.metadata.set(1, { "104": "2028-03-31" });
567
+ f.controls.archiveAfterWrite = true;
568
+ const input = {
569
+ items: [
570
+ {
571
+ issueNumber: 1,
572
+ title: "Dated item",
573
+ startDate: "2028-02-29",
574
+ targetDate: null,
575
+ parentIssueNumber: 5,
576
+ preserveHistory: true
577
+ }
578
+ ]
579
+ };
580
+ const first = await runBatch(input);
581
+ assert.equal(first.summary.failed, 1);
582
+ assert.equal(first.results[0].incomplete?.native.status, "confirmed");
583
+ assert.equal(first.results[0].incomplete?.native.readback?.startDate, "2028-02-29");
584
+ assert.equal(first.results[0].incomplete?.native.readback?.targetDate, null);
585
+ const nativeWrites = f.writes.filter((write) => write !== "project");
586
+ const comments = structuredClone(f.comments);
587
+ assert.equal((await runBatch(input)).summary.failed, 1);
588
+ assert.deepEqual(
589
+ f.writes.filter((write) => write !== "project"),
590
+ nativeWrites
591
+ );
592
+ f.controls.archiveAfterWrite = false;
593
+ f.controls.archived = false;
594
+ const resumed = await runBatch(input);
595
+ assert.equal(resumed.summary.applied, 1);
596
+ assert.deepEqual(
597
+ f.writes.filter((write) => write !== "project"),
598
+ nativeWrites
599
+ );
600
+ assert.deepEqual(f.comments, comments);
601
+ assert.deepEqual(f.dateWrites, [[103], [104]]);
602
+ assert.equal(f.parents.get(1), 5);
603
+ assert.equal((await runBatch(input)).summary.unchanged, 1);
516
604
  });
517
- test('readback disagreement and unavailable readback remain failures while later items proceed', async () => {
605
+ for (const [committedId, pendingId] of [
606
+ [103, 104],
607
+ [104, 103]
608
+ ]) {
609
+ test(`mixed date retry writes only pending field ${pendingId} and preserves committed field ${committedId}`, async () => {
518
610
  const f = batchFixture();
519
- f.controls.ignoreLabels = true;
520
- const result = await runBatch({
521
- items: [
522
- { issueNumber: 1, labels: ['enhancement'] },
523
- { issueNumber: 2, title: 'Later title' },
524
- ],
525
- });
526
- assert.deepEqual(result.results.map((item) => item.status), ['failed', 'applied']);
527
- assert.deepEqual(result.results[0].readback.labels, []);
528
- f.controls.failReadback = 3;
529
- const unavailable = await runBatch({
530
- items: [
531
- { issueNumber: 3, title: 'Written before transport failure' },
532
- { issueNumber: 4, title: 'Still executed' },
533
- ],
611
+ f.metadata.set(1, { [committedId]: "2028-02-29", [pendingId]: "2028-03-31" });
612
+ const first = await runBatch({
613
+ items: [
614
+ {
615
+ issueNumber: 1,
616
+ startDate: committedId === 103 ? "2028-02-29" : null,
617
+ targetDate: committedId === 104 ? "2028-02-29" : null
618
+ }
619
+ ]
534
620
  });
535
- assert.deepEqual(unavailable.results.map((item) => item.status), ['failed', 'applied']);
536
- assert.equal(unavailable.results[0].readback, null);
537
- assert.match(unavailable.results[0].readbackError, /unavailable/u);
621
+ assert.equal(first.summary.applied, 1);
622
+ assert.deepEqual(f.dateWrites, [[pendingId]]);
623
+ assert.equal(f.metadata.get(1)[String(committedId)], "2028-02-29");
624
+ assert.equal(f.metadata.get(1)[String(pendingId)], void 0);
625
+ });
626
+ }
627
+ test("lost Project acknowledgement is incomplete until a read-only batch reconciliation proves a no-op", async () => {
628
+ const f = batchFixture();
629
+ f.controls.loseProjectAck = true;
630
+ const input = { items: [{ issueNumber: 1, state: "closed", closeReason: "completed" }] };
631
+ const first = await runBatch(input);
632
+ assert.equal(first.summary.failed, 1);
633
+ assert.equal(first.results[0].incomplete?.native.status, "confirmed");
634
+ assert.equal(first.results[0].incomplete?.project.status, "unknown");
635
+ assert.equal(JSON.stringify(first).includes("PRIVATE_"), false);
636
+ const writes = [...f.writes];
637
+ const comments = structuredClone(f.comments);
638
+ assert.equal((await runBatch(input)).summary.unchanged, 1);
639
+ assert.deepEqual(f.writes, writes);
640
+ assert.deepEqual(f.comments, comments);
538
641
  });
539
- test('content drift after preparation refuses the stale write and preserves the operator edit', async () => {
642
+ test.each(["add", "remove"])(
643
+ "remaining Project target reflects the committed %s blocker change after Project reads fail",
644
+ async (action) => {
540
645
  const f = batchFixture();
541
- f.controls.driftOnRead = 1;
542
- const result = await runBatch({
543
- items: [
544
- { issueNumber: 1, title: 'Stale prepared update' },
545
- { issueNumber: 2, title: 'Independent update' },
546
- ],
547
- });
548
- assert.deepEqual(result.results.map((item) => item.status), ['failed', 'applied']);
549
- assert.equal(f.rows.get(1).body, 'Concurrent operator edit');
550
- assert.equal(f.rows.get(1).title, 'Synthetic item 1');
646
+ f.controls.projectUnavailableAfterDependency = true;
647
+ f.statuses.set(1, action === "remove" ? "Waiting" : "Queued");
648
+ if (action === "remove") f.blockers.set(1, [2]);
649
+ const blockers = action === "remove" ? [] : [2];
650
+ const first = await runBatch({ items: [{ issueNumber: 1, blockedBy: blockers }] });
651
+ const partial = first.results[0].incomplete;
652
+ assert.equal(first.summary.failed, 1);
653
+ assert.equal(partial?.native.status, "confirmed");
654
+ assert.deepEqual(partial?.native.readback?.blockedBy, blockers);
655
+ assert.equal(partial?.project.desiredStatus, action === "remove" ? "Todo" : "Blocked");
656
+ assert.equal(JSON.stringify(first).includes("PRIVATE_"), false);
657
+ const nativeWrites = f.writes.filter((write) => write !== "project");
658
+ f.controls.projectUnavailableAfterDependency = false;
659
+ assert.equal((await runBatch({ items: [{ issueNumber: 1, blockedBy: blockers }] })).summary.applied, 1);
660
+ assert.deepEqual(
661
+ f.writes.filter((write) => write !== "project"),
662
+ nativeWrites
663
+ );
664
+ }
665
+ );
666
+ test("unknown native blocker evidence does not claim a stale remaining Project target", async () => {
667
+ const f = batchFixture();
668
+ f.blockers.set(1, [2]);
669
+ f.statuses.set(1, "Waiting");
670
+ f.controls.nativeUnavailableAfterDependency = true;
671
+ const first = await runBatch({ items: [{ issueNumber: 1, blockedBy: [] }] });
672
+ const partial = first.results[0].incomplete;
673
+ assert.equal(partial?.native.status, "unknown");
674
+ assert.equal(partial?.project.desiredStatus, null);
675
+ assert.equal(JSON.stringify(first).includes("PRIVATE_"), false);
551
676
  });
552
- test('positive rate exhaustion suppresses remaining calls and exposes only numeric rate diagnostics', async () => {
553
- const f = batchFixture();
554
- f.controls.rateLimited = 1;
555
- const result = await runBatch({
556
- items: [
557
- { issueNumber: 1, title: 'Rate limited' },
558
- { issueNumber: 2, title: 'Not attempted' },
559
- ],
560
- });
561
- assert.deepEqual(result.results.map((item) => item.status), ['failed', 'failed']);
562
- assert.deepEqual(result.summary.rateLimits, [{ retryAfterSeconds: 60, resetAtSeconds: 1900000000, remaining: 0 }]);
563
- assert.match(result.results[1].reason, /Not attempted/u);
564
- assert.equal(f.rows.get(2).title, 'Synthetic item 2');
565
- assert.doesNotMatch(JSON.stringify(result), /PRIVATE_REMOTE_CONTENT|PRIVATE_TOKEN|authorization/u);
566
- assert.equal(getRateLimitDiagnostics({ status: 403, response: { headers: { 'x-ratelimit-remaining': '2' } } }), undefined);
567
- let getterRead = false;
568
- assert.equal(getRateLimitDiagnostics({
569
- get status() {
570
- getterRead = true;
571
- return 429;
572
- },
573
- }), undefined);
574
- assert.equal(getterRead, false);
677
+ test("a successful newer Project observation is retained when the subsequent synchronization fails", async () => {
678
+ const f = batchFixture();
679
+ f.controls.moveProjectToTodoAfterWrite = true;
680
+ const input = { items: [{ issueNumber: 1, status: { latestJournal: "Native journal updated" } }] };
681
+ const first = await runBatch(input);
682
+ assert.equal(first.summary.failed, 1);
683
+ const partial = first.results[0].incomplete;
684
+ assert.equal(partial?.native.status, "confirmed");
685
+ assert.equal(partial?.project.desiredStatus, "Todo");
686
+ assert.equal(JSON.stringify(first).includes("PRIVATE_"), false);
687
+ const writes = [...f.writes];
688
+ assert.equal((await runBatch(input)).summary.unchanged, 1);
689
+ assert.deepEqual(f.writes, writes);
575
690
  });
576
- test('a wrapped native rate error still suppresses later batch writes', async () => {
577
- const f = batchFixture();
578
- let observation;
579
- Object.assign(f.context.clients, { rateLimitObservation: () => observation });
580
- f.context.clients.rest.issues.update = (async () => {
581
- observation = { remaining: 0 };
582
- throw new Error('Dependency helper wrapped the original failure');
691
+ test("MCP serializes the actual incomplete update payload with error semantics", async () => {
692
+ const f = batchFixture();
693
+ f.controls.loseProjectAck = true;
694
+ const server = createAiDeliveryMcpServer({ repoRoot: "/synthetic", identity: "host-author" });
695
+ const client = new Client({ name: "partial-update-synthetic", version: "1" });
696
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
697
+ try {
698
+ await server.connect(serverTransport);
699
+ await client.connect(clientTransport);
700
+ const result = await client.callTool({
701
+ name: "issue_update",
702
+ arguments: { repo: "example/widget", issueNumber: 1, state: "closed", closeReason: "completed" }
583
703
  });
584
- const result = await runBatch({
585
- items: [
586
- { issueNumber: 1, title: 'Wrapped rate failure' },
587
- { issueNumber: 2, title: 'Must stay unchanged' },
588
- ],
589
- });
590
- assert.equal(result.results[1].reason, 'Not attempted: GitHub rate limit exhausted.');
591
- assert.deepEqual(result.summary.rateLimits, [{ remaining: 0 }]);
592
- assert.equal(f.rows.get(2).title, 'Synthetic item 2');
704
+ assert.equal(result.isError, true);
705
+ const content = result.content;
706
+ const partial = JSON.parse(content[0].text);
707
+ assert.equal(partial.status, "update-incomplete");
708
+ assert.equal(partial.native.status, "confirmed");
709
+ assert.equal(partial.native.readback.state, "closed");
710
+ assert.equal(partial.project.desiredStatus, "Done");
711
+ } finally {
712
+ await client.close();
713
+ await server.close();
714
+ }
593
715
  });
594
- test('schema, selected repository and author refusals perform no writes; cancellation returns every item', async () => {
595
- const f = batchFixture();
596
- for (const input of [
597
- { items: [] },
598
- { items: Array.from({ length: 51 }, () => ({ issueNumber: 1 })) },
599
- { items: [{ issueNumber: 1, undefer: true, defer: {} }] },
600
- { items: [{ issueNumber: 1, closeReason: 'completed' }] },
601
- { items: [{ issueNumber: 1, privateUnknown: 'HIDDEN_PROPERTY' }] },
602
- { items: [{ issueNumber: 1, repo: 'other/repository' }] },
603
- ])
604
- await assert.rejects(runBatch(input));
605
- await assert.rejects(executeTool('issue_batch_update', { repo: 'example/widget', items: [{ issueNumber: 1 }] }, { repoRoot: '/synthetic', identity: 'app-reviewer' }), /author/u);
606
- const abort = new AbortController();
607
- abort.abort();
608
- const cancelled = await issue.batchUpdateIssues(f.context, { items: [{ issueNumber: 1 }, { issueNumber: 2 }] }, abort.signal);
609
- assert.deepEqual(cancelled.results.map((item) => item.status), ['failed', 'failed']);
610
- assert.deepEqual(f.writes, []);
611
- const shape = getAiDeliveryMcpTool('issue_update').inputSchema;
612
- const complete = {
613
- issueNumber: 1,
614
- draft: true,
615
- retainLegacyBody: true,
616
- status: { latestJournal: 'Checked' },
617
- labels: [],
618
- milestone: null,
619
- parentIssueNumber: null,
620
- blocks: [],
621
- blockedBy: [],
622
- undefer: true,
623
- preserveHistory: false,
624
- };
625
- assert.equal(shape.safeParse(complete).success, true);
626
- assert.equal(getAiDeliveryMcpTool('issue_batch_update').inputSchema.safeParse({ items: [complete] }).success, true);
716
+ test("dry run plans close, defer, metadata, parent Points and dependency side effects without writes", async () => {
717
+ const f = batchFixture();
718
+ f.metadata.set(5, { "101": "4" });
719
+ f.statuses.set(4, "Queued");
720
+ const result = await runBatch({
721
+ dryRun: true,
722
+ items: [
723
+ { issueNumber: 1, state: "closed", closeReason: "duplicate", supersededBy: 5 },
724
+ { issueNumber: 2, defer: { until: "2026-12-01" }, preserveHistory: true },
725
+ { issueNumber: 3, labels: ["enhancement"], milestone: 1, points: 2, priority: "High", parentIssueNumber: 5 },
726
+ { issueNumber: 4, blockedBy: [2] }
727
+ ]
728
+ });
729
+ assert.deepEqual(
730
+ result.results.map((item) => item.status),
731
+ ["planned", "planned", "planned", "planned"]
732
+ );
733
+ assert.deepEqual(result.results[2].changes.parentPoints, { issueNumber: 5, points: null });
734
+ assert.deepEqual(result.results[3].changes.blockedBy, [2]);
735
+ assert.equal(result.results[0].changes.closureComment, true);
736
+ assert.deepEqual(f.writes, []);
737
+ assert.deepEqual(f.metadata.get(5), { "101": "4" });
738
+ assert.equal(f.rows.get(1).state, "open");
627
739
  });
628
- test('close journals, duplicate reason and explicit undefer are idempotent through the batch path', async () => {
629
- const f = batchFixture();
630
- const input = {
631
- items: [
632
- { issueNumber: 1, state: 'closed', closeReason: 'duplicate', supersededBy: 5 },
633
- { issueNumber: 2, defer: { trigger: 'Quarterly review' } },
634
- ],
635
- };
636
- const first = await runBatch(input);
637
- assert.deepEqual(first.results.map((item) => item.status), ['applied', 'applied']);
638
- assert.equal(first.results[0].readback.state, 'closed');
639
- assert.equal(first.results[0].relatedReadback.closeReason, 'duplicate');
640
- const count = f.comments.length;
641
- assert.deepEqual((await runBatch(input)).results.map((item) => item.status), ['unchanged', 'unchanged']);
642
- assert.equal(f.comments.length, count);
643
- const resumed = await runBatch({ items: [{ issueNumber: 2, undefer: true }] });
644
- assert.equal(resumed.results[0].status, 'applied');
645
- assert.equal(resumed.results[0].readback.deferred, null);
646
- assert.equal((await runBatch({ items: [{ issueNumber: 2, undefer: true }] })).results[0].status, 'unchanged');
740
+ test("unchanged includes labels, metadata, native parent Points and blocker relationships", async () => {
741
+ const f = batchFixture();
742
+ f.metadata.set(5, { "101": "4" });
743
+ f.statuses.set(3, "Queued");
744
+ const input = {
745
+ items: [
746
+ {
747
+ issueNumber: 3,
748
+ labels: ["enhancement"],
749
+ milestone: 1,
750
+ points: 2,
751
+ priority: "High",
752
+ parentIssueNumber: 5,
753
+ blockedBy: [2]
754
+ }
755
+ ]
756
+ };
757
+ const first = await runBatch(input);
758
+ assert.equal(first.results[0].status, "applied", JSON.stringify(first));
759
+ assert.deepEqual(first.results[0].readback.labels, ["enhancement"]);
760
+ assert.equal(first.results[0].readback.milestone, 1);
761
+ assert.equal(first.results[0].readback.points, 2);
762
+ assert.equal(first.results[0].readback.priority, "High");
763
+ assert.equal(f.parents.get(3), 5);
764
+ assert.equal(f.metadata.get(5)["101"], void 0);
765
+ assert.deepEqual(f.blockers.get(3), [2]);
766
+ assert.equal((await runBatch(input)).results[0].status, "unchanged");
767
+ f.metadata.set(5, { "101": "4" });
768
+ assert.equal(
769
+ (await runBatch(input)).results[0].status,
770
+ "applied",
771
+ "Parent Points repair cannot be classified unchanged"
772
+ );
647
773
  });
648
- test('public MCP and dispatch expose the same read-only per-item plan contract', async () => {
649
- const f = batchFixture();
650
- const server = createAiDeliveryMcpServer({ repoRoot: '/synthetic', identity: 'host-author' });
651
- const client = new Client({ name: 'batch-synthetic', version: '1' });
652
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
653
- try {
654
- await server.connect(serverTransport);
655
- await client.connect(clientTransport);
656
- const input = { repo: 'example/widget', dryRun: true, items: [{ issueNumber: 1, title: 'MCP planned title' }] };
657
- const result = await client.callTool({ name: 'issue_batch_update', arguments: input });
658
- assert.notEqual(result.isError, true);
659
- const content = result.content;
660
- const parsed = JSON.parse(content[0].text);
661
- assert.equal(parsed.results[0].changes.title, 'MCP planned title');
662
- assert.equal(parsed.results[0].status, 'planned');
663
- assert.equal(parsed.summary.planned, 1);
664
- assert.equal(parsed.results[0].readback.title, 'Synthetic item 1');
665
- const direct = await runBatch(input);
666
- assert.deepEqual(direct.summary, parsed.summary);
667
- assert.equal(direct.results[0].changes.title, parsed.results[0].changes.title);
668
- assert.deepEqual(f.writes, []);
669
- }
670
- finally {
671
- await client.close();
672
- await server.close();
673
- }
774
+ test("readback disagreement and unavailable readback remain failures while later items proceed", async () => {
775
+ const f = batchFixture();
776
+ f.controls.ignoreLabels = true;
777
+ const result = await runBatch({
778
+ items: [
779
+ { issueNumber: 1, labels: ["enhancement"] },
780
+ { issueNumber: 2, title: "Later title" }
781
+ ]
782
+ });
783
+ assert.deepEqual(
784
+ result.results.map((item) => item.status),
785
+ ["failed", "applied"]
786
+ );
787
+ assert.deepEqual(result.results[0].readback.labels, []);
788
+ f.controls.failReadback = 3;
789
+ const unavailable = await runBatch({
790
+ items: [
791
+ { issueNumber: 3, title: "Written before transport failure" },
792
+ { issueNumber: 4, title: "Still executed" }
793
+ ]
794
+ });
795
+ assert.deepEqual(
796
+ unavailable.results.map((item) => item.status),
797
+ ["failed", "applied"]
798
+ );
799
+ assert.equal(unavailable.results[0].readback, null);
800
+ assert.match(unavailable.results[0].readbackError, /unavailable/u);
674
801
  });
675
- test('the documented fifty-item boundary returns every read-only plan', async () => {
676
- const f = batchFixture();
677
- const result = await runBatch({
678
- dryRun: true,
679
- items: Array.from({ length: 50 }, () => ({ issueNumber: 1, title: 'Planned repeated item' })),
680
- });
681
- assert.equal(result.results.length, 50);
682
- assert.equal(result.summary.planned, 50);
802
+ test("content drift after preparation refuses the stale write and preserves the operator edit", async () => {
803
+ const f = batchFixture();
804
+ f.controls.driftOnRead = 1;
805
+ const result = await runBatch({
806
+ items: [
807
+ { issueNumber: 1, title: "Stale prepared update" },
808
+ { issueNumber: 2, title: "Independent update" }
809
+ ]
810
+ });
811
+ assert.deepEqual(
812
+ result.results.map((item) => item.status),
813
+ ["failed", "applied"]
814
+ );
815
+ assert.equal(f.rows.get(1).body, "Concurrent operator edit");
816
+ assert.equal(f.rows.get(1).title, "Synthetic item 1");
817
+ });
818
+ test("positive rate exhaustion suppresses remaining calls and exposes only numeric rate diagnostics", async () => {
819
+ const f = batchFixture();
820
+ f.controls.rateLimited = 1;
821
+ const result = await runBatch({
822
+ items: [
823
+ { issueNumber: 1, title: "Rate limited" },
824
+ { issueNumber: 2, title: "Not attempted" }
825
+ ]
826
+ });
827
+ assert.deepEqual(
828
+ result.results.map((item) => item.status),
829
+ ["failed", "failed"]
830
+ );
831
+ assert.deepEqual(result.summary.rateLimits, [{ retryAfterSeconds: 60, resetAtSeconds: 19e8, remaining: 0 }]);
832
+ assert.match(result.results[1].reason, /Not attempted/u);
833
+ assert.equal(f.rows.get(2).title, "Synthetic item 2");
834
+ assert.doesNotMatch(JSON.stringify(result), /PRIVATE_REMOTE_CONTENT|PRIVATE_TOKEN|authorization/u);
835
+ assert.equal(
836
+ getRateLimitDiagnostics({ status: 403, response: { headers: { "x-ratelimit-remaining": "2" } } }),
837
+ void 0
838
+ );
839
+ let getterRead = false;
840
+ assert.equal(
841
+ getRateLimitDiagnostics({
842
+ get status() {
843
+ getterRead = true;
844
+ return 429;
845
+ }
846
+ }),
847
+ void 0
848
+ );
849
+ assert.equal(getterRead, false);
850
+ });
851
+ test("a wrapped native rate error still suppresses later batch writes", async () => {
852
+ const f = batchFixture();
853
+ let observation;
854
+ Object.assign(f.context.clients, { rateLimitObservation: () => observation });
855
+ f.context.clients.rest.issues.update = (async () => {
856
+ observation = { remaining: 0 };
857
+ throw new Error("Dependency helper wrapped the original failure");
858
+ });
859
+ const result = await runBatch({
860
+ items: [
861
+ { issueNumber: 1, title: "Wrapped rate failure" },
862
+ { issueNumber: 2, title: "Must stay unchanged" }
863
+ ]
864
+ });
865
+ assert.equal(result.results[1].reason, "Not attempted: GitHub rate limit exhausted.");
866
+ assert.deepEqual(result.summary.rateLimits, [{ remaining: 0 }]);
867
+ assert.equal(f.rows.get(2).title, "Synthetic item 2");
868
+ });
869
+ test("schema, selected repository and author refusals perform no writes; cancellation returns every item", async () => {
870
+ const f = batchFixture();
871
+ for (const input of [
872
+ { items: [] },
873
+ { items: Array.from({ length: 51 }, () => ({ issueNumber: 1 })) },
874
+ { items: [{ issueNumber: 1, undefer: true, defer: {} }] },
875
+ { items: [{ issueNumber: 1, closeReason: "completed" }] },
876
+ { items: [{ issueNumber: 1, privateUnknown: "HIDDEN_PROPERTY" }] },
877
+ { items: [{ issueNumber: 1, repo: "other/repository" }] }
878
+ ])
879
+ await assert.rejects(runBatch(input));
880
+ await assert.rejects(
881
+ executeTool(
882
+ "issue_batch_update",
883
+ { repo: "example/widget", items: [{ issueNumber: 1 }] },
884
+ { repoRoot: "/synthetic", identity: "app-reviewer" }
885
+ ),
886
+ /author/u
887
+ );
888
+ const abort = new AbortController();
889
+ abort.abort();
890
+ const cancelled = await issue.batchUpdateIssues(
891
+ f.context,
892
+ { items: [{ issueNumber: 1 }, { issueNumber: 2 }] },
893
+ abort.signal
894
+ );
895
+ assert.deepEqual(
896
+ cancelled.results.map((item) => item.status),
897
+ ["failed", "failed"]
898
+ );
899
+ assert.deepEqual(f.writes, []);
900
+ const shape = getAiDeliveryMcpTool("issue_update").inputSchema;
901
+ const complete = {
902
+ issueNumber: 1,
903
+ draft: true,
904
+ retainLegacyBody: true,
905
+ status: { latestJournal: "Checked" },
906
+ labels: [],
907
+ milestone: null,
908
+ parentIssueNumber: null,
909
+ blocks: [],
910
+ blockedBy: [],
911
+ undefer: true,
912
+ preserveHistory: false
913
+ };
914
+ assert.equal(shape.safeParse(complete).success, true);
915
+ assert.equal(getAiDeliveryMcpTool("issue_batch_update").inputSchema.safeParse({ items: [complete] }).success, true);
916
+ });
917
+ test("close journals, duplicate reason and explicit undefer are idempotent through the batch path", async () => {
918
+ const f = batchFixture();
919
+ const input = {
920
+ items: [
921
+ { issueNumber: 1, state: "closed", closeReason: "duplicate", supersededBy: 5 },
922
+ { issueNumber: 2, defer: { trigger: "Quarterly review" } }
923
+ ]
924
+ };
925
+ const first = await runBatch(input);
926
+ assert.deepEqual(
927
+ first.results.map((item) => item.status),
928
+ ["applied", "applied"]
929
+ );
930
+ assert.equal(first.results[0].readback.state, "closed");
931
+ assert.equal(first.results[0].relatedReadback.closeReason, "duplicate");
932
+ const count = f.comments.length;
933
+ assert.deepEqual(
934
+ (await runBatch(input)).results.map((item) => item.status),
935
+ ["unchanged", "unchanged"]
936
+ );
937
+ assert.equal(f.comments.length, count);
938
+ const resumed = await runBatch({ items: [{ issueNumber: 2, undefer: true }] });
939
+ assert.equal(resumed.results[0].status, "applied");
940
+ assert.equal(resumed.results[0].readback.deferred, null);
941
+ assert.equal((await runBatch({ items: [{ issueNumber: 2, undefer: true }] })).results[0].status, "unchanged");
942
+ });
943
+ test("public MCP and dispatch expose the same read-only per-item plan contract", async () => {
944
+ const f = batchFixture();
945
+ const server = createAiDeliveryMcpServer({ repoRoot: "/synthetic", identity: "host-author" });
946
+ const client = new Client({ name: "batch-synthetic", version: "1" });
947
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
948
+ try {
949
+ await server.connect(serverTransport);
950
+ await client.connect(clientTransport);
951
+ const input = { repo: "example/widget", dryRun: true, items: [{ issueNumber: 1, title: "MCP planned title" }] };
952
+ const result = await client.callTool({ name: "issue_batch_update", arguments: input });
953
+ assert.notEqual(result.isError, true);
954
+ const content = result.content;
955
+ const parsed = JSON.parse(content[0].text);
956
+ assert.equal(parsed.results[0].changes.title, "MCP planned title");
957
+ assert.equal(parsed.results[0].status, "planned");
958
+ assert.equal(parsed.summary.planned, 1);
959
+ assert.equal(parsed.results[0].readback.title, "Synthetic item 1");
960
+ const direct = await runBatch(input);
961
+ assert.deepEqual(direct.summary, parsed.summary);
962
+ assert.equal(direct.results[0].changes.title, parsed.results[0].changes.title);
683
963
  assert.deepEqual(f.writes, []);
964
+ } finally {
965
+ await client.close();
966
+ await server.close();
967
+ }
684
968
  });
685
- test('native label casing preserves the existing case-insensitive update intent', async () => {
686
- const f = batchFixture();
687
- const input = { items: [{ issueNumber: 1, labels: ['ENHANCEMENT'] }] };
688
- const first = await runBatch(input);
689
- assert.equal(first.results[0].status, 'applied');
690
- assert.deepEqual(f.rows.get(1).labels, ['enhancement']);
691
- assert.equal((await runBatch(input)).results[0].status, 'unchanged');
969
+ test("the documented fifty-item boundary returns every read-only plan", async () => {
970
+ const f = batchFixture();
971
+ const result = await runBatch({
972
+ dryRun: true,
973
+ items: Array.from({ length: 50 }, () => ({ issueNumber: 1, title: "Planned repeated item" }))
974
+ });
975
+ assert.equal(result.results.length, 50);
976
+ assert.equal(result.summary.planned, 50);
977
+ assert.deepEqual(f.writes, []);
978
+ });
979
+ test("native label casing preserves the existing case-insensitive update intent", async () => {
980
+ const f = batchFixture();
981
+ const input = { items: [{ issueNumber: 1, labels: ["ENHANCEMENT"] }] };
982
+ const first = await runBatch(input);
983
+ assert.equal(first.results[0].status, "applied");
984
+ assert.deepEqual(f.rows.get(1).labels, ["enhancement"]);
985
+ assert.equal((await runBatch(input)).results[0].status, "unchanged");
986
+ });
987
+ test("rate exhaustion during fallback readback stops later writes and appears in the summary", async () => {
988
+ const f = batchFixture();
989
+ f.controls.failAfterWrite = 1;
990
+ const get = f.context.clients.rest.issues.get;
991
+ f.context.clients.rest.issues.get = (async (params) => {
992
+ if (params.issue_number === 1 && f.writes.includes("update:1"))
993
+ throw Object.assign(new Error("Private readback error"), { status: 429, headers: { "retry-after": "10" } });
994
+ return get({ ...f.context.repo, ...params });
995
+ });
996
+ const result = await runBatch({
997
+ items: [
998
+ { issueNumber: 1, title: "Partial item" },
999
+ { issueNumber: 2, title: "No later write" }
1000
+ ]
1001
+ });
1002
+ assert.deepEqual(
1003
+ result.results.map((item) => item.status),
1004
+ ["failed", "failed"]
1005
+ );
1006
+ assert.match(result.results[1].reason, /Not attempted/u);
1007
+ assert.deepEqual(result.summary.rateLimits, [{ retryAfterSeconds: 10 }]);
1008
+ assert.equal(f.rows.get(2).title, "Synthetic item 2");
692
1009
  });
693
- test('rate exhaustion during fallback readback stops later writes and appears in the summary', async () => {
1010
+ test("closure reuse refuses duplicate authored journals and corrupted authoritative comment readback", async () => {
1011
+ for (const mode of ["duplicate", "corrupt"]) {
694
1012
  const f = batchFixture();
695
- f.controls.failAfterWrite = 1;
696
- const get = f.context.clients.rest.issues.get;
697
- f.context.clients.rest.issues.get = (async (params) => {
698
- if (params.issue_number === 1 && f.writes.includes('update:1'))
699
- throw Object.assign(new Error('Private readback error'), { status: 429, headers: { 'retry-after': '10' } });
700
- return get({ ...f.context.repo, ...params });
701
- });
702
- const result = await runBatch({
703
- items: [
704
- { issueNumber: 1, title: 'Partial item' },
705
- { issueNumber: 2, title: 'No later write' },
706
- ],
707
- });
708
- assert.deepEqual(result.results.map((item) => item.status), ['failed', 'failed']);
709
- assert.match(result.results[1].reason, /Not attempted/u);
710
- assert.deepEqual(result.summary.rateLimits, [{ retryAfterSeconds: 10 }]);
711
- assert.equal(f.rows.get(2).title, 'Synthetic item 2');
1013
+ const input = { items: [{ issueNumber: 1, state: "closed", closeReason: "completed" }] };
1014
+ assert.equal((await runBatch(input)).results[0].status, "applied");
1015
+ const existing = f.comments.find((comment) => comment.body === "Requested closure reason: completed.");
1016
+ if (mode === "duplicate") f.comments.push({ ...existing, id: 9999 });
1017
+ else
1018
+ f.context.clients.rest.issues.getComment = (async () => ({
1019
+ data: { ...existing, body: "Corrupted journal readback" }
1020
+ }));
1021
+ const writes = f.writes.length;
1022
+ assert.equal((await runBatch(input)).results[0].status, "failed", mode);
1023
+ assert.equal(f.writes.length, writes);
1024
+ }
712
1025
  });
713
- test('closure reuse refuses duplicate authored journals and corrupted authoritative comment readback', async () => {
714
- for (const mode of ['duplicate', 'corrupt']) {
715
- const f = batchFixture();
716
- const input = { items: [{ issueNumber: 1, state: 'closed', closeReason: 'completed' }] };
717
- assert.equal((await runBatch(input)).results[0].status, 'applied');
718
- const existing = f.comments.find((comment) => comment.body === 'Requested closure reason: completed.');
719
- if (mode === 'duplicate')
720
- f.comments.push({ ...existing, id: 9999 });
721
- else
722
- f.context.clients.rest.issues.getComment = (async () => ({
723
- data: { ...existing, body: 'Corrupted journal readback' },
724
- }));
725
- const writes = f.writes.length;
726
- assert.equal((await runBatch(input)).results[0].status, 'failed', mode);
727
- assert.equal(f.writes.length, writes);
728
- }
1026
+ test("closing an issue whose archived Project item already shows Done reports applied", async () => {
1027
+ const f = batchFixture();
1028
+ f.controls.archived = true;
1029
+ f.statuses.set(1, "Shipped");
1030
+ const result = await runBatch({ items: [{ issueNumber: 1, state: "closed", closeReason: "not_planned" }] });
1031
+ assert.equal(f.rows.get(1).state, "closed");
1032
+ assert.deepEqual(result.summary, { total: 1, applied: 1, planned: 0, unchanged: 0, failed: 0, rateLimits: [] });
1033
+ });
1034
+ test("an In Review item reads as active work, survives In Progress and moves to Done on close", async () => {
1035
+ const f = batchFixture();
1036
+ f.statuses.set(1, "In Review");
1037
+ const info = await issue.issueInfo(f.context, 1);
1038
+ assert.equal(info.projectStatus, "In Progress");
1039
+ assert.equal(info.inReview, true);
1040
+ await syncIssueProjectStatus({
1041
+ configuration: f.context.projectConfiguration,
1042
+ graphql: f.context.clients.graphql,
1043
+ issueNodeId: "ISSUE1",
1044
+ org: "example",
1045
+ status: "In Progress"
1046
+ });
1047
+ assert.equal(f.statuses.get(1), "In Review");
1048
+ await runBatch({ items: [{ issueNumber: 1, state: "closed", closeReason: "completed" }] });
1049
+ assert.equal(f.statuses.get(1), "Shipped");
729
1050
  });
730
- //# sourceMappingURL=issueBatchUpdate.test.js.map
1051
+ //# sourceMappingURL=issueBatchUpdate.test.js.map