@aviaratech/ai-delivery 0.3.35 → 0.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -554
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +402 -515
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +329 -353
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +59 -19
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.js +73 -67
  95. package/dist/git.js.map +7 -1
  96. package/dist/gitProcess.d.ts +1 -1
  97. package/dist/gitProcess.js +58 -53
  98. package/dist/gitProcess.js.map +7 -1
  99. package/dist/github/client.d.ts +2 -2
  100. package/dist/github/client.js +484 -379
  101. package/dist/github/client.js.map +7 -1
  102. package/dist/github/commandIdentityPolicy.js +44 -52
  103. package/dist/github/commandIdentityPolicy.js.map +7 -1
  104. package/dist/github/discovery.d.ts +1 -0
  105. package/dist/github/discovery.js +197 -215
  106. package/dist/github/discovery.js.map +7 -1
  107. package/dist/github/discovery.test.js +223 -177
  108. package/dist/github/discovery.test.js.map +7 -1
  109. package/dist/github/issueHistory.d.ts +2 -2
  110. package/dist/github/issueHistory.js +117 -125
  111. package/dist/github/issueHistory.js.map +7 -1
  112. package/dist/github/machineAuth.d.ts +1 -1
  113. package/dist/github/machineAuth.js +126 -117
  114. package/dist/github/machineAuth.js.map +7 -1
  115. package/dist/github/machineAuth.test.js +755 -639
  116. package/dist/github/machineAuth.test.js.map +7 -1
  117. package/dist/github/nativeIssueMetadata.js +286 -273
  118. package/dist/github/nativeIssueMetadata.js.map +7 -1
  119. package/dist/github/projectDelivery.d.ts +18 -2
  120. package/dist/github/projectDelivery.js +615 -557
  121. package/dist/github/projectDelivery.js.map +7 -1
  122. package/dist/github/relationships.js +433 -389
  123. package/dist/github/relationships.js.map +7 -1
  124. package/dist/github/repo.d.ts +1 -0
  125. package/dist/github/repo.js +123 -96
  126. package/dist/github/repo.js.map +7 -1
  127. package/dist/index.js +3 -3
  128. package/dist/index.js.map +7 -1
  129. package/dist/issue.d.ts +40 -9
  130. package/dist/issue.js +2102 -1742
  131. package/dist/issue.js.map +7 -1
  132. package/dist/issue63History.test.js +40 -42
  133. package/dist/issue63History.test.js.map +7 -1
  134. package/dist/issue63Routes.test.js +154 -143
  135. package/dist/issue63Routes.test.js.map +7 -1
  136. package/dist/issueBatchUpdate.test.js +989 -885
  137. package/dist/issueBatchUpdate.test.js.map +7 -1
  138. package/dist/issueBlockerGuard.test.js +262 -226
  139. package/dist/issueBlockerGuard.test.js.map +7 -1
  140. package/dist/issueContract.d.ts +23 -4
  141. package/dist/issueContract.js +416 -395
  142. package/dist/issueContract.js.map +7 -1
  143. package/dist/issueContract.test.d.ts +4 -3
  144. package/dist/issueContract.test.js +358 -321
  145. package/dist/issueContract.test.js.map +7 -1
  146. package/dist/issueDates.test.js +235 -233
  147. package/dist/issueDates.test.js.map +7 -1
  148. package/dist/issueInfoReadback.test.js +304 -190
  149. package/dist/issueInfoReadback.test.js.map +7 -1
  150. package/dist/issueIntake.test.js +1945 -1732
  151. package/dist/issueIntake.test.js.map +7 -1
  152. package/dist/issueJournal.d.ts +40 -19
  153. package/dist/issueJournal.js +229 -138
  154. package/dist/issueJournal.js.map +7 -1
  155. package/dist/issueJournal.test.js +605 -422
  156. package/dist/issueJournal.test.js.map +7 -1
  157. package/dist/issueRollup.test.d.ts +1 -0
  158. package/dist/issueRollup.test.js +476 -0
  159. package/dist/issueRollup.test.js.map +7 -0
  160. package/dist/issueTracking.test.js +1059 -989
  161. package/dist/issueTracking.test.js.map +7 -1
  162. package/dist/issueWriteRecovery.test.d.ts +1 -0
  163. package/dist/issueWriteRecovery.test.js +260 -0
  164. package/dist/issueWriteRecovery.test.js.map +7 -0
  165. package/dist/lifecycle.test.js +112 -441
  166. package/dist/lifecycle.test.js.map +7 -1
  167. package/dist/logger.js +80 -74
  168. package/dist/logger.js.map +7 -1
  169. package/dist/mcp/index.js +116 -94
  170. package/dist/mcp/index.js.map +7 -1
  171. package/dist/mcp/tools.d.ts +264 -286
  172. package/dist/mcp/tools.js +267 -340
  173. package/dist/mcp/tools.js.map +7 -1
  174. package/dist/pluginAuthProbe.js +63 -52
  175. package/dist/pluginAuthProbe.js.map +7 -1
  176. package/dist/pluginAuthProbe.test.js +85 -62
  177. package/dist/pluginAuthProbe.test.js.map +7 -1
  178. package/dist/pluginCredentials.test.js +282 -259
  179. package/dist/pluginCredentials.test.js.map +7 -1
  180. package/dist/pluginDoctor.test.js +653 -588
  181. package/dist/pluginDoctor.test.js.map +7 -1
  182. package/dist/pluginInstaller.d.ts +7 -5
  183. package/dist/pluginInstaller.js +1173 -1229
  184. package/dist/pluginInstaller.js.map +7 -1
  185. package/dist/pluginInstaller.test.js +1842 -1423
  186. package/dist/pluginInstaller.test.js.map +7 -1
  187. package/dist/pluginPackaging.test.js +460 -409
  188. package/dist/pluginPackaging.test.js.map +7 -1
  189. package/dist/pr.d.ts +132 -94
  190. package/dist/pr.js +1521 -1323
  191. package/dist/pr.js.map +7 -1
  192. package/dist/pr.test.js +1678 -632
  193. package/dist/pr.test.js.map +7 -1
  194. package/dist/prAssociation.test.js +2419 -1788
  195. package/dist/prAssociation.test.js.map +7 -1
  196. package/dist/prDispatch.test.js +150 -89
  197. package/dist/prDispatch.test.js.map +7 -1
  198. package/dist/readView.d.ts +183 -0
  199. package/dist/readView.js +217 -0
  200. package/dist/readView.js.map +7 -0
  201. package/dist/readView.test.d.ts +1 -0
  202. package/dist/readView.test.js +119 -0
  203. package/dist/readView.test.js.map +7 -0
  204. package/dist/releaseReconciliation.test.js +267 -288
  205. package/dist/releaseReconciliation.test.js.map +7 -1
  206. package/dist/releaseWorkflow.test.js +2493 -422
  207. package/dist/releaseWorkflow.test.js.map +7 -1
  208. package/dist/review.d.ts +738 -2
  209. package/dist/review.js +601 -348
  210. package/dist/review.js.map +7 -1
  211. package/dist/review.test.js +1218 -812
  212. package/dist/review.test.js.map +7 -1
  213. package/dist/reviewSubmit.test.d.ts +1 -0
  214. package/dist/reviewSubmit.test.js +747 -0
  215. package/dist/reviewSubmit.test.js.map +7 -0
  216. package/dist/services/agentReadinessService.js +42 -37
  217. package/dist/services/agentReadinessService.js.map +7 -1
  218. package/dist/services/blockerGuardService.js +188 -188
  219. package/dist/services/blockerGuardService.js.map +7 -1
  220. package/dist/services/boardReconcileService.d.ts +125 -125
  221. package/dist/services/boardReconcileService.js +1295 -1421
  222. package/dist/services/boardReconcileService.js.map +7 -1
  223. package/dist/services/deliveryAdmission.js +131 -154
  224. package/dist/services/deliveryAdmission.js.map +7 -1
  225. package/dist/services/deliveryHealthService.js +197 -199
  226. package/dist/services/deliveryHealthService.js.map +7 -1
  227. package/dist/services/legacyIssueMigration.js +263 -277
  228. package/dist/services/legacyIssueMigration.js.map +7 -1
  229. package/dist/services/worktreeRegistry.d.ts +27 -119
  230. package/dist/services/worktreeRegistry.js +765 -1182
  231. package/dist/services/worktreeRegistry.js.map +7 -1
  232. package/dist/stagedChecks.test.js +396 -194
  233. package/dist/stagedChecks.test.js.map +7 -1
  234. package/dist/start.test.js +99 -95
  235. package/dist/start.test.js.map +7 -1
  236. package/dist/stdoutRegression.test.js +353 -352
  237. package/dist/stdoutRegression.test.js.map +7 -1
  238. package/dist/targetPolicyDiscovery.test.js +141 -143
  239. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  240. package/dist/targetPolicyEntrypoints.test.js +308 -269
  241. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  242. package/dist/targetPolicyLocal.test.js +580 -1051
  243. package/dist/targetPolicyLocal.test.js.map +7 -1
  244. package/dist/targetPolicyRoutes.test.js +305 -281
  245. package/dist/targetPolicyRoutes.test.js.map +7 -1
  246. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  247. package/dist/targetRepositoryExecution.test.js +463 -0
  248. package/dist/targetRepositoryExecution.test.js.map +7 -0
  249. package/dist/terminalMessages.js +41 -35
  250. package/dist/terminalMessages.js.map +7 -1
  251. package/dist/toolOutput.d.ts +2 -0
  252. package/dist/toolOutput.js +36 -0
  253. package/dist/toolOutput.js.map +7 -0
  254. package/dist/toolOutput.test.d.ts +1 -0
  255. package/dist/toolOutput.test.js +240 -0
  256. package/dist/toolOutput.test.js.map +7 -0
  257. package/dist/utils/atomicJson.js +84 -76
  258. package/dist/utils/atomicJson.js.map +7 -1
  259. package/dist/utils/filesystem.js +15 -18
  260. package/dist/utils/filesystem.js.map +7 -1
  261. package/dist/utils/lockfile.js +68 -71
  262. package/dist/utils/lockfile.js.map +7 -1
  263. package/dist/verification.d.ts +1 -19
  264. package/dist/verification.js +1020 -1939
  265. package/dist/verification.js.map +7 -1
  266. package/dist/verificationGate.test.js +127 -117
  267. package/dist/verificationGate.test.js.map +7 -1
  268. package/dist/version.js +23 -24
  269. package/dist/version.js.map +7 -1
  270. package/dist/worktree.d.ts +3 -15
  271. package/dist/worktree.js +97 -177
  272. package/dist/worktree.js.map +7 -1
  273. package/package.json +9 -8
  274. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  275. package/plugins/ai-delivery/README.md +47 -156
  276. package/plugins/ai-delivery/plugin.json +1 -1
  277. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  278. package/plugins/ai-delivery/runtime/dist/cli.js +358 -115
  279. package/plugins/ai-delivery/runtime/package.json +1 -1
  280. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  281. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  282. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  283. package/dist/investigationCompletion.test.js +0 -728
  284. package/dist/investigationCompletion.test.js.map +0 -1
  285. package/dist/setup.d.ts +0 -60
  286. package/dist/setup.js +0 -585
  287. package/dist/setup.js.map +0 -1
  288. package/dist/setup.test.js +0 -3329
  289. package/dist/setup.test.js.map +0 -1
  290. package/dist/worktreeTransition.d.ts +0 -211
  291. package/dist/worktreeTransition.js +0 -1037
  292. package/dist/worktreeTransition.js.map +0 -1
  293. package/dist/worktreeTransition.test.js +0 -1191
  294. package/dist/worktreeTransition.test.js.map +0 -1
  295. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  296. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  297. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,443 +1,626 @@
1
- import assert from 'node:assert/strict';
2
- import { test, vi } from 'vitest';
3
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
- import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
5
- import { createAiDeliveryMcpServer } from './mcp/index.js';
6
- import { inertTarget } from './fixtures/inertTarget.js';
7
- import { getAiDeliveryMcpTool } from './mcp/tools.js';
8
- import * as issue from './issue.js';
9
- import { JournalInputSchema, renderJournal, acceptanceCriteria, issueFollowUps } from './issueJournal.js';
10
- import { executeTool } from './dispatch.js';
11
- import * as configuration from './config/deliveryConfig.js';
12
- import * as githubClients from './github/client.js';
13
- import { execFileSync } from 'node:child_process';
14
- import { mkdtempSync, rmSync } from 'node:fs';
15
- import { tmpdir } from 'node:os';
16
- import { join } from 'node:path';
17
- test('decision journal list fields start below their label and preserve nested structure', () => {
18
- const result = renderJournal({
1
+ import assert from "node:assert/strict";
2
+ import { z } from "zod";
3
+ import { test, vi } from "vitest";
4
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
6
+ import { createAiDeliveryMcpServer } from "./mcp/index.js";
7
+ import { inertTarget } from "./fixtures/inertTarget.js";
8
+ import { getAiDeliveryMcpTool } from "./mcp/tools.js";
9
+ import * as issue from "./issue.js";
10
+ import * as journalReaders from "./issueJournal.js";
11
+ import { JournalInputSchema, renderJournal, acceptanceCriteria, issueFollowUps } from "./issueJournal.js";
12
+ import { executeTool } from "./dispatch.js";
13
+ import * as configuration from "./config/deliveryConfig.js";
14
+ import * as githubClients from "./github/client.js";
15
+ import { execFileSync } from "node:child_process";
16
+ import { mkdtempSync, rmSync } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { join } from "node:path";
19
+ test("latest rendered progress attention is unambiguous", () => {
20
+ const parse = Reflect.get(journalReaders, "parseJournalAttention");
21
+ assert.equal(typeof parse, "function", "rendered journal attention reader is available");
22
+ const progress = (decisionNeeded, extra = {}) => renderJournal({
23
+ issueNumber: 17,
24
+ kind: "progress",
25
+ summary: "Current work.",
26
+ status: "In Progress",
27
+ done: ["Prepared the design"],
28
+ decisionNeeded,
29
+ nextStep: "Implement",
30
+ nextDate: null,
31
+ keyNumbers: [],
32
+ evidence: ["https://github.com/example/widget/issues/17"],
33
+ ...extra
34
+ });
35
+ for (const sentinel of ["None", "None.", "N/A", "Not needed", " nOnE. "])
36
+ assert.equal(parse(progress(sentinel)).state, "clear");
37
+ for (const request of [
38
+ "Approve design",
39
+ "Approve design\nThen select an approach",
40
+ "- Approve design\n- Select approach"
41
+ ])
42
+ assert.deepEqual(parse(progress(request)), { kind: "progress", state: "pending", request, reason: null });
43
+ assert.equal(parse(progress("Approve design", { done: ["x".repeat(600)], lengthCap: 600 })).state, "pending");
44
+ const marker = `<!-- ai-delivery:journal@1:sha256:${"a".repeat(64)} -->`;
45
+ const prose = `${progress("Approve ai-delivery:journal@1 documentation")}
46
+
47
+ ${marker}`;
48
+ assert.equal(parse(prose).state, "pending");
49
+ assert.equal(parse(`${prose}
50
+
51
+ ${marker}`).state, "unknown");
52
+ assert.equal(
53
+ parse(
54
+ renderJournal({
19
55
  issueNumber: 17,
20
- kind: 'decision',
21
- summary: 'A decision was made.',
22
- status: 'Ready',
23
- decision: '- First\n - Nested\n- Second',
24
- rationale: 'The existing owner is sufficient.',
25
- nextStep: 'Run checks',
56
+ kind: "decision",
57
+ summary: "Approved.",
58
+ status: "Ready",
59
+ decision: "Use the design",
60
+ rationale: "Reviewed",
61
+ nextStep: "Implement",
26
62
  nextDate: null,
27
63
  keyNumbers: [],
28
- evidence: [],
29
- });
30
- assert.equal(result, 'A decision was made.\n\n**Kind:** decision. **Status:** Ready\n\n**Decision:**\n- First\n - Nested\n- Second\n\n**Rationale:** The existing owner is sufficient.\n\n**Key numbers:** None reported.\n\n**Next:** Run checks (date not scheduled).\n\n**Evidence:** None yet.');
64
+ evidence: []
65
+ })
66
+ ).state,
67
+ "clear"
68
+ );
31
69
  });
32
- test('journal tool validates all five typed templates before dispatch', () => {
33
- const tool = getAiDeliveryMcpTool('issue_comment');
34
- assert.ok(tool, 'issue_comment must be exposed');
35
- const common = {
36
- issueNumber: 17,
37
- summary: 'Parser work is underway.',
38
- status: 'In progress',
39
- nextStep: 'Run checks',
40
- nextDate: '2026-10-09',
41
- keyNumbers: ['3 checks'],
42
- evidence: ['https://github.com/example/widget/pull/23'],
43
- };
44
- const valid = [
45
- { ...common, kind: 'start', outcome: 'Deliver a safe parser' },
46
- { ...common, kind: 'progress', done: ['Added validation'], decisionNeeded: 'None' },
47
- { ...common, kind: 'decision', decision: 'Use the existing parser', rationale: 'Preserves the contract' },
48
- { ...common, kind: 'blocker', blocker: 'Review pending', resolution: 'Independent acceptance' },
70
+ test("duplicate free-text structural labels are unknown", () => {
71
+ const parse = Reflect.get(journalReaders, "parseJournalAttention");
72
+ assert.equal(typeof parse, "function");
73
+ const input = {
74
+ issueNumber: 17,
75
+ kind: "progress",
76
+ summary: "Current work.",
77
+ status: "Ready",
78
+ done: ["Prepared"],
79
+ decisionNeeded: "Approve design",
80
+ nextStep: "Implement",
81
+ nextDate: null,
82
+ keyNumbers: [],
83
+ evidence: ["https://github.com/example/widget/issues/17"]
84
+ };
85
+ for (const details of [
86
+ "**Decision needed:** None",
87
+ "> **Decision needed:** None",
88
+ "```md\n**Decision needed:** None\n```",
89
+ "**Kind:** decision. **Status:** Ready",
90
+ "<details>\n**Decision needed:** None\n</details>"
91
+ ])
92
+ assert.equal(parse(renderJournal({ ...input, details })).state, "unknown", details);
93
+ for (const summary of ["```md", "~~~"]) assert.equal(parse(renderJournal({ ...input, summary })).state, "unknown");
94
+ for (const status of ["<det**ails>", "<!**-- ai-delivery:journal@1"])
95
+ assert.equal(parse(renderJournal({ ...input, status })).state, "pending");
96
+ assert.equal(parse(renderJournal({ ...input, status: "\u{1F642}".repeat(16), nextStep: "a. Next: b" })).state, "pending");
97
+ const marked = renderJournal(
98
+ { ...input, decisionNeeded: "None" },
99
+ `<!-- ai-delivery:journal@1:sha256:${"a".repeat(64)} -->`
100
+ );
101
+ for (const header of [
102
+ "Status: <!-- ai-delivery:journal@. Next: Review.",
103
+ "Status: **Decision needed:** None. Next: Review.",
104
+ "Status: Ready . Next: Review.",
105
+ `Status: ${"\u{1F642}".repeat(17)}. Next: Review.`
106
+ ])
107
+ assert.equal(parse(`${header}${marked.slice(marked.indexOf("\n\n"))}`).state, "unknown");
108
+ const legacy = "Status: Ready. Next: Review.\n\n**Kind:** progress. **Status:** Ready\n\n**Done since last:**\n- Prepared\n\n**Decision needed:** Approve design\n\n**Key numbers:** None reported.\n\n**Next:** Review (date not scheduled).\n\n**Evidence:** https://github.com/example/widget/issues/17";
109
+ assert.equal(parse(legacy).state, "pending");
110
+ for (const body of [
111
+ "> **Kind:** progress. **Status:** Ready\n\n**Decision needed:** Approve",
112
+ "```\n**Kind:** progress. **Status:** Ready\n\n**Decision needed:** Approve\n```",
113
+ "**Kind:** progress. **Status:** Ready\n\n**Decision needed:**"
114
+ ])
115
+ assert.equal(parse(body).state, "unknown");
116
+ });
117
+ test("decision journal list fields start below their label and preserve nested structure", () => {
118
+ const result = renderJournal({
119
+ issueNumber: 17,
120
+ kind: "decision",
121
+ summary: "A decision was made.",
122
+ status: "Ready",
123
+ decision: "- First\n - Nested\n- Second",
124
+ rationale: "The existing owner is sufficient.",
125
+ nextStep: "Run checks",
126
+ nextDate: null,
127
+ keyNumbers: [],
128
+ evidence: []
129
+ });
130
+ assert.equal(
131
+ result,
132
+ "Status: Ready. Next: Run checks.\n\nA decision was made.\n\n**Kind:** decision. **Status:** Ready\n\n**Decision:**\n- First\n - Nested\n- Second\n\n**Rationale:** The existing owner is sufficient.\n\n**Key numbers:** None reported.\n\n**Next:** Run checks (date not scheduled).\n\n**Evidence:** None yet."
133
+ );
134
+ });
135
+ test("published comment schema lists required fields for every journal kind", () => {
136
+ const schema = z.toJSONSchema(getAiDeliveryMcpTool("issue_comment").inputSchema);
137
+ assert.deepEqual(schema.anyOf, [
138
+ { properties: { kind: { const: "start" } }, required: ["outcome"] },
139
+ { properties: { kind: { const: "progress" } }, required: ["done", "decisionNeeded"] },
140
+ { properties: { kind: { const: "decision" } }, required: ["decision", "rationale"] },
141
+ { properties: { kind: { const: "blocker" } }, required: ["blocker", "resolution"] },
142
+ { properties: { kind: { const: "closeout" } }, required: ["acceptance", "followUps"] }
143
+ ]);
144
+ });
145
+ test("all typed journals validate and lead with plain status and next-step previews", () => {
146
+ const tool = getAiDeliveryMcpTool("issue_comment");
147
+ assert.ok(tool, "issue_comment must be exposed");
148
+ const common = {
149
+ issueNumber: 17,
150
+ summary: "Parser work is underway.",
151
+ status: "In progress",
152
+ nextStep: "Run checks",
153
+ nextDate: "2026-10-09",
154
+ keyNumbers: ["3 checks"],
155
+ evidence: ["https://github.com/example/widget/pull/23"]
156
+ };
157
+ const valid = [
158
+ { ...common, kind: "start", outcome: "Deliver a safe parser" },
159
+ { ...common, kind: "progress", done: ["Added validation"], decisionNeeded: "None" },
160
+ { ...common, kind: "decision", decision: "Use the existing parser", rationale: "Preserves the contract" },
161
+ { ...common, kind: "blocker", blocker: "Review pending", resolution: "Independent acceptance" },
162
+ {
163
+ ...common,
164
+ kind: "closeout",
165
+ acceptance: [{ criterion: "Reject malformed input", evidence: "https://github.com/example/widget/pull/23" }],
166
+ followUps: []
167
+ }
168
+ ];
169
+ for (const input of valid) {
170
+ for (const repo of [void 0, "example/widget"]) {
171
+ for (const nextDate of [null, "2026-10-09", "2028-02-29"]) {
172
+ const selected = { ...input, nextDate, ...repo === void 0 ? {} : { repo } };
173
+ const parsed = tool.inputSchema.safeParse(selected);
174
+ assert.equal(parsed.success, true, JSON.stringify(selected));
175
+ if (parsed.success) assert.deepEqual(parsed.data, selected);
176
+ }
177
+ }
178
+ assert.equal(JournalInputSchema.safeParse(input).success, true);
179
+ assert.equal(JournalInputSchema.safeParse({ ...input, repo: "example/widget" }).success, false);
180
+ for (const summary of [input.summary, "S".repeat(500)]) {
181
+ const marker = `<!-- ai-delivery:journal@1:sha256:${"a".repeat(64)} -->`;
182
+ const body = renderJournal(
49
183
  {
50
- ...common,
51
- kind: 'closeout',
52
- acceptance: [{ criterion: 'Reject malformed input', evidence: 'https://github.com/example/widget/pull/23' }],
53
- followUps: [],
184
+ ...input,
185
+ summary,
186
+ status: "**In progress**",
187
+ nextStep: "Run\nchecks",
188
+ lengthCap: 600,
189
+ details: "D".repeat(900)
54
190
  },
55
- ];
56
- for (const input of valid) {
57
- for (const repo of [undefined, 'example/widget']) {
58
- for (const nextDate of [null, '2026-10-09', '2028-02-29']) {
59
- const selected = { ...input, nextDate, ...(repo === undefined ? {} : { repo }) };
60
- const parsed = tool.inputSchema.safeParse(selected);
61
- assert.equal(parsed.success, true, JSON.stringify(selected));
62
- if (parsed.success)
63
- assert.deepEqual(parsed.data, selected);
64
- }
65
- }
66
- assert.equal(JournalInputSchema.safeParse(input).success, true);
67
- assert.equal(JournalInputSchema.safeParse({ ...input, repo: 'example/widget' }).success, false);
191
+ marker
192
+ );
193
+ assert.equal(body.startsWith(`Status: In progress. Next: Run checks.
194
+
195
+ ${summary}
196
+
197
+ `), true);
198
+ assert.match(body, /<details>/u);
199
+ assert.ok(body.endsWith(marker));
200
+ assert.deepEqual(journalReaders.parseJournalAttention(body), {
201
+ kind: input.kind,
202
+ state: "clear",
203
+ request: null,
204
+ reason: null
205
+ });
68
206
  }
207
+ }
208
+ for (const input of [
209
+ { ...common, kind: "progress" },
210
+ { ...common, kind: "start", outcome: "" },
211
+ { ...common, kind: "closeout", acceptance: [], followUps: [] },
212
+ {
213
+ ...common,
214
+ kind: "decision",
215
+ decision: "Use parser",
216
+ rationale: "Works",
217
+ evidence: ["/Users/operator/checks.log"]
218
+ },
219
+ { ...common, kind: "start", outcome: "Deliver", nextDate: "tomorrow" },
220
+ { ...common, kind: "start", outcome: "Deliver", done: ["Wrong variant"] },
221
+ { ...common, kind: "progress", done: ["Deliver"], decisionNeeded: "None", rationale: "Wrong variant" },
222
+ { ...common, kind: "decision", decision: "Use parser", rationale: "Works", blocker: "Wrong variant" },
223
+ { ...common, kind: "blocker", blocker: "Review", resolution: "Accept", outcome: "Wrong variant" },
224
+ { ...valid[4], done: ["Wrong variant"] },
225
+ { ...valid[0], unknown: true },
226
+ { ...valid[0], kind: "unsupported" },
227
+ { ...valid[0], nextDate: "2026-02-30" },
228
+ { ...valid[0], nextDate: 20261009 },
229
+ { ...valid[0], keyNumbers: "3 checks" },
230
+ { ...valid[0], issueNumber: "17" },
231
+ { ...valid[4], acceptance: [{ criterion: "Deliver", evidence: common.evidence[0], unknown: true }] }
232
+ ])
233
+ for (const repo of [void 0, "example/widget"])
234
+ assert.equal(tool.inputSchema.safeParse({ ...input, ...repo === void 0 ? {} : { repo } }).success, false);
235
+ for (const repo of [
236
+ "",
237
+ "example",
238
+ "example/widget/extra",
239
+ "https://github.com/example/widget",
240
+ "example/\nwidget",
241
+ 17,
242
+ null,
243
+ []
244
+ ])
245
+ assert.equal(tool.inputSchema.safeParse({ ...valid[0], repo }).success, false);
246
+ });
247
+ test("journal dispatch refuses invalid fields and repository conflicts before configuration or authentication", async () => {
248
+ const settings = vi.spyOn(configuration, "loadDeliverySettings").mockImplementation(async () => {
249
+ throw new Error("Configuration must not load for an invalid journal");
250
+ });
251
+ const clients = vi.spyOn(githubClients, "createDeliveryGitHubClients");
252
+ const valid = {
253
+ repo: "example/widget",
254
+ issueNumber: 17,
255
+ kind: "progress",
256
+ summary: "Parser work is underway.",
257
+ status: "In progress",
258
+ done: ["Added validation"],
259
+ decisionNeeded: "None",
260
+ keyNumbers: [],
261
+ evidence: ["https://github.com/example/widget/pull/23"],
262
+ nextStep: "Run checks",
263
+ nextDate: null
264
+ };
265
+ try {
69
266
  for (const input of [
70
- { ...common, kind: 'progress' },
71
- { ...common, kind: 'start', outcome: '' },
72
- { ...common, kind: 'closeout', acceptance: [], followUps: [] },
73
- {
74
- ...common,
75
- kind: 'decision',
76
- decision: 'Use parser',
77
- rationale: 'Works',
78
- evidence: ['/Users/operator/checks.log'],
79
- },
80
- { ...common, kind: 'start', outcome: 'Deliver', nextDate: 'tomorrow' },
81
- { ...common, kind: 'start', outcome: 'Deliver', done: ['Wrong variant'] },
82
- { ...common, kind: 'progress', done: ['Deliver'], decisionNeeded: 'None', rationale: 'Wrong variant' },
83
- { ...common, kind: 'decision', decision: 'Use parser', rationale: 'Works', blocker: 'Wrong variant' },
84
- { ...common, kind: 'blocker', blocker: 'Review', resolution: 'Accept', outcome: 'Wrong variant' },
85
- { ...valid[4], done: ['Wrong variant'] },
86
- { ...valid[0], unknown: true },
87
- { ...valid[0], kind: 'unsupported' },
88
- { ...valid[0], nextDate: '2026-02-30' },
89
- { ...valid[0], nextDate: 20261009 },
90
- { ...valid[0], keyNumbers: '3 checks' },
91
- { ...valid[0], issueNumber: '17' },
92
- { ...valid[4], acceptance: [{ criterion: 'Deliver', evidence: common.evidence[0], unknown: true }] },
93
- ])
94
- for (const repo of [undefined, 'example/widget'])
95
- assert.equal(tool.inputSchema.safeParse({ ...input, ...(repo === undefined ? {} : { repo }) }).success, false);
96
- for (const repo of [
97
- '',
98
- 'example',
99
- 'example/widget/extra',
100
- 'https://github.com/example/widget',
101
- 'example/\nwidget',
102
- 17,
103
- null,
104
- [],
267
+ { ...valid, kind: "unsupported" },
268
+ { ...valid, outcome: "Wrong variant" },
269
+ { ...valid, unknown: true },
270
+ { ...valid, done: [] },
271
+ { ...valid, evidence: [] },
272
+ { ...valid, repo: "invalid" },
273
+ { ...valid, repo: 17 },
274
+ { ...valid, nextDate: "2026-02-30" }
105
275
  ])
106
- assert.equal(tool.inputSchema.safeParse({ ...valid[0], repo }).success, false);
107
- });
108
- test('journal dispatch refuses invalid fields and repository conflicts before configuration or authentication', async () => {
109
- const settings = vi.spyOn(configuration, 'loadDeliverySettings').mockImplementation(async () => {
110
- throw new Error('Configuration must not load for an invalid journal');
111
- });
112
- const clients = vi.spyOn(githubClients, 'createDeliveryGitHubClients');
113
- const valid = {
114
- repo: 'example/widget',
115
- issueNumber: 17,
116
- kind: 'progress',
117
- summary: 'Parser work is underway.',
118
- status: 'In progress',
119
- done: ['Added validation'],
120
- decisionNeeded: 'None',
121
- keyNumbers: [],
122
- evidence: ['https://github.com/example/widget/pull/23'],
123
- nextStep: 'Run checks',
124
- nextDate: null,
125
- };
126
- try {
127
- for (const input of [
128
- { ...valid, kind: 'unsupported' },
129
- { ...valid, outcome: 'Wrong variant' },
130
- { ...valid, unknown: true },
131
- { ...valid, done: [] },
132
- { ...valid, evidence: [] },
133
- { ...valid, repo: 'invalid' },
134
- { ...valid, repo: 17 },
135
- { ...valid, nextDate: '2026-02-30' },
136
- ])
137
- await assert.rejects(executeTool('issue_comment', input, { repoRoot: '/non-git-fixture' }));
138
- await assert.rejects(executeTool('issue_comment', valid, { repoRoot: '/non-git-fixture', repo: 'example/other' }), /selectors disagree/u);
139
- assert.equal(settings.mock.calls.length, 0);
140
- assert.equal(clients.mock.calls.length, 0, 'no authenticated client or comment writer is reached');
141
- }
142
- finally {
143
- settings.mockRestore();
144
- clients.mockRestore();
145
- }
276
+ await assert.rejects(executeTool("issue_comment", input, { repoRoot: "/non-git-fixture" }));
277
+ await assert.rejects(
278
+ executeTool("issue_comment", valid, { repoRoot: "/non-git-fixture", repo: "example/other" }),
279
+ /selectors disagree/u
280
+ );
281
+ assert.equal(settings.mock.calls.length, 0);
282
+ assert.equal(clients.mock.calls.length, 0, "no authenticated client or comment writer is reached");
283
+ } finally {
284
+ settings.mockRestore();
285
+ clients.mockRestore();
286
+ }
146
287
  });
147
- test('canonical comment writes read back and recover a lost response without duplicates', async () => {
148
- const comment = issue.commentIssue;
149
- assert.ok(comment, 'canonical comment writer must exist');
150
- const agent = await import('./agent.js');
151
- assert.equal(agent.commentIssue, comment);
152
- assert.equal(agent.ISSUE_COMMENT_BODY_LIMIT, 65536);
153
- const root = mkdtempSync(join(tmpdir(), 'ai-delivery-journal-'));
154
- execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: root });
155
- const stored = [];
156
- let loseResponse = true;
157
- let corruptReadback = false;
158
- let authorCalls = 0;
159
- const context = {
160
- root,
161
- repo: { owner: 'example', repo: 'widget' },
162
- clients: {
163
- role: 'author',
164
- authenticatedAuthor: async () => {
165
- authorCalls += 1;
166
- return { actorLogin: 'operator', credentialIdentity: 'user:1' };
167
- },
168
- rest: {
169
- issues: {
170
- get: async () => ({ data: { number: 17, state: 'open' } }),
171
- listComments: async () => ({ data: stored }),
172
- createComment: async (input) => {
173
- const id = 91 + stored.length;
174
- const data = {
175
- id,
176
- body: input.body,
177
- html_url: `https://github.com/example/widget/issues/17#issuecomment-${String(id)}`,
178
- issue_url: 'https://api.github.com/repos/example/widget/issues/17',
179
- user: { login: 'operator' },
180
- };
181
- stored.push(data);
182
- if (loseResponse) {
183
- loseResponse = false;
184
- throw new Error('response lost');
185
- }
186
- return { data };
187
- },
188
- getComment: async (input) => ({
189
- data: {
190
- ...stored.find((item) => item.id === input.comment_id),
191
- ...(corruptReadback ? { body: 'changed' } : {}),
192
- },
193
- }),
194
- },
195
- },
196
- },
197
- };
198
- const input = {
199
- issueNumber: 17,
200
- kind: 'start',
201
- summary: 'Implementation started.',
202
- status: 'In progress',
203
- outcome: 'Deliver validation',
204
- keyNumbers: [],
205
- evidence: [],
206
- nextStep: 'Run checks',
207
- nextDate: '2026-10-09',
208
- };
209
- try {
210
- await assert.rejects(comment(context, input), /response lost/u);
211
- const recovered = await comment(context, input);
212
- assert.equal(recovered.commentId, 91);
213
- assert.equal(recovered.reused, true);
214
- assert.equal(stored.length, 1);
215
- assert.match(recovered.body, /^Implementation started\./u);
216
- corruptReadback = true;
217
- await assert.rejects(comment(context, input), /readback/u);
218
- corruptReadback = false;
219
- stored.push({ ...stored[0], id: 99, html_url: 'https://github.com/example/widget/issues/17#issuecomment-99' });
220
- await assert.rejects(comment(context, input), /duplicate authored retry matches/u);
221
- assert.equal(stored.length, 2, 'ambiguous retries must not write another comment');
222
- stored.pop();
223
- const rawBody = `\r\n <details>\n<summary>Prior content</summary>\n<pre>${'🙂 &amp; prior title/body\r\n'.repeat(600)}</pre>\n</details> \t\n`;
224
- assert.ok(rawBody.length > 10000);
225
- loseResponse = true;
226
- await assert.rejects(comment(context, { issueNumber: 17, body: rawBody }), /response lost/u);
227
- const rawRecovered = await comment(context, { issueNumber: 17, body: rawBody });
228
- assert.equal(rawRecovered.body, rawBody, 'raw history content must remain exact and unwrapped');
229
- assert.equal(rawRecovered.commentId, 92);
230
- assert.equal(rawRecovered.reused, true);
231
- assert.equal(stored.length, 2);
232
- assert.equal(stored[1].body, rawBody, 'no journal marker or unrequested content is appended');
233
- const maximumBody = '🙂'.repeat(32768);
234
- assert.equal(maximumBody.length, 65536);
235
- assert.equal((await comment(context, { issueNumber: 17, body: maximumBody })).body, maximumBody);
236
- assert.equal(stored.length, 3);
237
- const beforeInvalid = authorCalls;
238
- for (const body of ['', ' \r\n\t ', 'x'.repeat(65537), `${maximumBody}🙂`])
239
- await assert.rejects(comment(context, { issueNumber: 17, body }), /comment body/u);
240
- await assert.rejects(comment(context, {
241
- ...input,
242
- status: 'x'.repeat(9000),
243
- outcome: 'x'.repeat(9000),
244
- nextStep: 'x'.repeat(9000),
245
- details: 'x'.repeat(9000),
246
- keyNumbers: Array.from({ length: 4 }, () => 'x'.repeat(9000)),
247
- }), /comment body/u);
248
- await assert.rejects(comment(context, { issueNumber: 17, body: rawBody }, 'start:legacy'), /lifecycle journal key/u);
249
- assert.equal(authorCalls, beforeInvalid, 'unsupported payloads fail before authentication or mutation');
250
- assert.equal(stored.length, 3);
251
- corruptReadback = true;
252
- await assert.rejects(comment(context, { issueNumber: 17, body: rawBody }), /readback/u);
253
- }
254
- finally {
255
- rmSync(root, { recursive: true, force: true });
288
+ test("canonical comment writes read back and recover a lost response without duplicates", async () => {
289
+ const comment = issue.commentIssue;
290
+ assert.ok(comment, "canonical comment writer must exist");
291
+ const agent = await import("./agent.js");
292
+ assert.equal(agent.commentIssue, comment);
293
+ assert.equal(agent.ISSUE_COMMENT_BODY_LIMIT, 65536);
294
+ const root = mkdtempSync(join(tmpdir(), "ai-delivery-journal-"));
295
+ execFileSync("git", ["init", "-q", "-b", "main"], { cwd: root });
296
+ const stored = [];
297
+ let loseResponse = true;
298
+ let corruptReadback = false;
299
+ let authorCalls = 0;
300
+ const context = {
301
+ root,
302
+ repo: { owner: "example", repo: "widget" },
303
+ clients: {
304
+ role: "author",
305
+ authenticatedAuthor: async () => {
306
+ authorCalls += 1;
307
+ return { actorLogin: "operator", credentialIdentity: "user:1" };
308
+ },
309
+ rest: {
310
+ issues: {
311
+ get: async () => ({ data: { number: 17, state: "open" } }),
312
+ listComments: async () => ({ data: stored }),
313
+ createComment: async (input2) => {
314
+ const id = 91 + stored.length;
315
+ const data = {
316
+ id,
317
+ body: input2.body,
318
+ html_url: `https://github.com/example/widget/issues/17#issuecomment-${String(id)}`,
319
+ issue_url: "https://api.github.com/repos/example/widget/issues/17",
320
+ user: { login: "operator" }
321
+ };
322
+ stored.push(data);
323
+ if (loseResponse) {
324
+ loseResponse = false;
325
+ throw new Error("response lost");
326
+ }
327
+ return { data };
328
+ },
329
+ getComment: async (input2) => ({
330
+ data: {
331
+ ...stored.find((item) => item.id === input2.comment_id),
332
+ ...corruptReadback ? { body: "changed" } : {}
333
+ }
334
+ })
335
+ }
336
+ }
256
337
  }
338
+ };
339
+ const input = {
340
+ issueNumber: 17,
341
+ kind: "start",
342
+ summary: "Implementation started.",
343
+ status: "In progress",
344
+ outcome: "Deliver validation",
345
+ keyNumbers: [],
346
+ evidence: [],
347
+ nextStep: "Run checks",
348
+ nextDate: "2026-10-09"
349
+ };
350
+ try {
351
+ await assert.rejects(comment(context, input), /response lost/u);
352
+ const recovered = await comment(context, input);
353
+ assert.equal(recovered.commentId, 91);
354
+ assert.equal(recovered.reused, true);
355
+ assert.equal(stored.length, 1);
356
+ assert.match(recovered.body, /^Status: In progress\. Next: Run checks\.\n\nImplementation started\./u);
357
+ corruptReadback = true;
358
+ await assert.rejects(comment(context, input), /readback/u);
359
+ corruptReadback = false;
360
+ stored.push({ ...stored[0], id: 99, html_url: "https://github.com/example/widget/issues/17#issuecomment-99" });
361
+ await assert.rejects(comment(context, input), /duplicate authored retry matches/u);
362
+ assert.equal(stored.length, 2, "ambiguous retries must not write another comment");
363
+ stored.pop();
364
+ const rawBody = `\r
365
+ <details>
366
+ <summary>Prior content</summary>
367
+ <pre>${"\u{1F642} &amp; prior title/body\r\n".repeat(600)}</pre>
368
+ </details>
369
+ `;
370
+ assert.ok(rawBody.length > 1e4);
371
+ loseResponse = true;
372
+ await assert.rejects(comment(context, { issueNumber: 17, body: rawBody }), /response lost/u);
373
+ const rawRecovered = await comment(context, { issueNumber: 17, body: rawBody });
374
+ assert.equal(rawRecovered.body, rawBody, "raw history content must remain exact and unwrapped");
375
+ assert.equal(rawRecovered.commentId, 92);
376
+ assert.equal(rawRecovered.reused, true);
377
+ assert.equal(stored.length, 2);
378
+ assert.equal(stored[1].body, rawBody, "no journal marker or unrequested content is appended");
379
+ const maximumBody = "\u{1F642}".repeat(32768);
380
+ assert.equal(maximumBody.length, 65536);
381
+ assert.equal((await comment(context, { issueNumber: 17, body: maximumBody })).body, maximumBody);
382
+ assert.equal(stored.length, 3);
383
+ const beforeInvalid = authorCalls;
384
+ for (const body of ["", " \r\n ", "x".repeat(65537), `${maximumBody}\u{1F642}`])
385
+ await assert.rejects(comment(context, { issueNumber: 17, body }), /comment body/u);
386
+ await assert.rejects(
387
+ comment(context, {
388
+ ...input,
389
+ status: "x".repeat(9e3),
390
+ outcome: "x".repeat(9e3),
391
+ nextStep: "x".repeat(9e3),
392
+ details: "x".repeat(9e3),
393
+ keyNumbers: Array.from({ length: 4 }, () => "x".repeat(9e3))
394
+ }),
395
+ /comment body/u
396
+ );
397
+ await assert.rejects(
398
+ comment(context, { issueNumber: 17, body: rawBody }, "start:legacy"),
399
+ /lifecycle journal key/u
400
+ );
401
+ assert.equal(authorCalls, beforeInvalid, "unsupported payloads fail before authentication or mutation");
402
+ assert.equal(stored.length, 3);
403
+ corruptReadback = true;
404
+ await assert.rejects(comment(context, { issueNumber: 17, body: rawBody }), /readback/u);
405
+ } finally {
406
+ rmSync(root, { recursive: true, force: true });
407
+ }
257
408
  });
258
- test('length cap keeps the summary visible and moves every excess field into collapsed detail', () => {
259
- const rendered = renderJournal({
260
- issueNumber: 17,
261
- kind: 'progress',
262
- summary: 'Validation is implemented.',
263
- status: 'In progress',
264
- done: ['A'.repeat(900)],
265
- decisionNeeded: 'None',
266
- keyNumbers: ['7 tests'],
267
- evidence: ['https://github.com/example/widget/pull/23'],
268
- nextStep: 'Review',
269
- nextDate: '2026-10-09',
270
- lengthCap: 600,
271
- });
272
- assert.equal(rendered.split('\n')[0], 'Validation is implemented.');
273
- assert.match(rendered, /<details>/u);
274
- assert.match(rendered, /A{900}/u);
275
- assert.match(rendered, /7 tests/u);
276
- assert.match(rendered, /https:\/\/github.com\/example\/widget\/pull\/23/u);
409
+ test("length cap keeps the summary visible and moves every excess field into collapsed detail", () => {
410
+ const summary = "S".repeat(500);
411
+ const rendered = renderJournal({
412
+ issueNumber: 17,
413
+ kind: "progress",
414
+ summary,
415
+ status: "In progress ".repeat(500),
416
+ done: ["A".repeat(900)],
417
+ decisionNeeded: "None",
418
+ keyNumbers: ["7 tests"],
419
+ evidence: ["https://github.com/example/widget/pull/23"],
420
+ nextStep: "Review ".repeat(1e3),
421
+ nextDate: "2026-10-09",
422
+ lengthCap: 600
423
+ });
424
+ const first = rendered.split("\n")[0];
425
+ assert.ok(first.startsWith("Status: In progress"));
426
+ assert.ok(first.length <= 100 && rendered.split("\n")[2] === summary);
427
+ assert.ok(rendered.indexOf("Next: Review") < rendered.indexOf(summary));
428
+ assert.match(rendered, /<details>/u);
429
+ assert.match(rendered, /A{900}/u);
430
+ assert.match(rendered, /7 tests/u);
431
+ assert.match(rendered, /https:\/\/github.com\/example\/widget\/pull\/23/u);
277
432
  });
278
- test('automatic closeout selects acceptance checkboxes and declared follow-ups without swallowing other sections', () => {
279
- const body = '## Outcome\nShip.\n\n## Acceptance Criteria\n- [ ] Validation works\n- [x] Recovery works\n\n## Follow-ups\n- Track post-release adoption: https://github.com/example/widget/issues/24\n\n## Non-goals\n- [ ] Not an acceptance criterion';
280
- assert.deepEqual(acceptanceCriteria(body), ['Validation works', 'Recovery works']);
281
- assert.deepEqual(issueFollowUps(body), ['Track post-release adoption: https://github.com/example/widget/issues/24']);
433
+ test("automatic closeout selects acceptance checkboxes and declared follow-ups without swallowing other sections", () => {
434
+ const body = "## Outcome\nShip.\n\n## Acceptance Criteria\n- [ ] Validation works\n- [x] Recovery works\n\n## Follow-ups\n- Track post-release adoption: https://github.com/example/widget/issues/24\n\n## Non-goals\n- [ ] Not an acceptance criterion";
435
+ assert.deepEqual(acceptanceCriteria(body), ["Validation works", "Recovery works"]);
436
+ assert.deepEqual(issueFollowUps(body), ["Track post-release adoption: https://github.com/example/widget/issues/24"]);
282
437
  });
283
- test('closeout accepts every readiness heading level and stops at the next heading', () => {
284
- for (let level = 1; level <= 6; level += 1) {
285
- for (let indent = 0; indent <= 3; indent += 1) {
286
- const heading = `${' '.repeat(indent)}${'#'.repeat(level)}`;
287
- const body = `${heading}\tAcceptance Criteria\n-[ ] Compact bullet\n*\t[X]\tTabbed bullet\n+ [x] Checked bullet\n###### Other section\n- [ ] Excluded\n${heading} Follow-ups\n- [ ] Deferred work\n# Other section\n- Excluded`;
288
- assert.deepEqual(acceptanceCriteria(body), ['Compact bullet', 'Tabbed bullet', 'Checked bullet']);
289
- assert.deepEqual(issueFollowUps(body), ['Deferred work']);
290
- }
438
+ test("closeout accepts every readiness heading level and stops at the next heading", () => {
439
+ for (let level = 1; level <= 6; level += 1) {
440
+ for (let indent = 0; indent <= 3; indent += 1) {
441
+ const heading = `${" ".repeat(indent)}${"#".repeat(level)}`;
442
+ const body = `${heading} Acceptance Criteria
443
+ -[ ] Compact bullet
444
+ * [X] Tabbed bullet
445
+ + [x] Checked bullet
446
+ ###### Other section
447
+ - [ ] Excluded
448
+ ${heading} Follow-ups
449
+ - [ ] Deferred work
450
+ # Other section
451
+ - Excluded`;
452
+ assert.deepEqual(acceptanceCriteria(body), ["Compact bullet", "Tabbed bullet", "Checked bullet"]);
453
+ assert.deepEqual(issueFollowUps(body), ["Deferred work"]);
291
454
  }
455
+ }
292
456
  });
293
- test('journal evidence rejects local hosts and IP literals while accepting public DNS names', () => {
294
- const tool = getAiDeliveryMcpTool('issue_comment');
295
- const input = {
296
- issueNumber: 17,
297
- kind: 'start',
298
- summary: 'Work started.',
299
- status: 'Started',
300
- outcome: 'Deliver validation',
301
- keyNumbers: [],
302
- nextStep: 'Run checks',
303
- nextDate: null,
304
- };
305
- for (const host of [
306
- 'localhost',
307
- 'localhost.',
308
- 'api.localhost',
309
- 'runner.local',
310
- '127.0.0.1',
311
- '10.1.2.3',
312
- '172.16.0.1',
313
- '192.168.1.1',
314
- '169.254.1.1',
315
- '[::1]',
316
- '[fd00::1]',
317
- '[fe80::1]',
318
- '8.8.8.8',
319
- ])
320
- assert.equal(tool.inputSchema.safeParse({ ...input, evidence: [`https://${host}/evidence`] }).success, false, host);
321
- for (const host of ['github.com', '10.docs.example.com'])
322
- assert.equal(tool.inputSchema.safeParse({ ...input, evidence: [`https://${host}/evidence`] }).success, true, host);
457
+ test("journal evidence rejects local hosts and IP literals while accepting public DNS names", () => {
458
+ const tool = getAiDeliveryMcpTool("issue_comment");
459
+ const input = {
460
+ issueNumber: 17,
461
+ kind: "start",
462
+ summary: "Work started.",
463
+ status: "Started",
464
+ outcome: "Deliver validation",
465
+ keyNumbers: [],
466
+ nextStep: "Run checks",
467
+ nextDate: null
468
+ };
469
+ for (const host of [
470
+ "localhost",
471
+ "localhost.",
472
+ "api.localhost",
473
+ "runner.local",
474
+ "127.0.0.1",
475
+ "10.1.2.3",
476
+ "172.16.0.1",
477
+ "192.168.1.1",
478
+ "169.254.1.1",
479
+ "[::1]",
480
+ "[fd00::1]",
481
+ "[fe80::1]",
482
+ "8.8.8.8"
483
+ ])
484
+ assert.equal(tool.inputSchema.safeParse({ ...input, evidence: [`https://${host}/evidence`] }).success, false, host);
485
+ for (const host of ["github.com", "10.docs.example.com"])
486
+ assert.equal(tool.inputSchema.safeParse({ ...input, evidence: [`https://${host}/evidence`] }).success, true, host);
323
487
  });
324
- test('registered journal tool returns actionable decision refusals before native writes', async ({ signal }) => {
325
- const f = inertTarget(signal);
326
- const server = createAiDeliveryMcpServer({ repoRoot: f.root, signal });
327
- const client = new Client({ name: 'journal-contract-fixture', version: '1' });
328
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
329
- const common = {
330
- repo: 'example/widget',
331
- issueNumber: 17,
332
- summary: 'Parser validation is ready.',
333
- status: 'In progress',
334
- nextStep: 'Review the parser',
335
- nextDate: null,
336
- keyNumbers: [],
337
- evidence: ['https://github.com/example/widget/pull/23'],
338
- };
339
- const decision = {
488
+ test("registered journal tool returns actionable decision refusals before native writes", async ({ signal }) => {
489
+ const f = inertTarget(signal);
490
+ const server = createAiDeliveryMcpServer({ repoRoot: f.root, signal });
491
+ const client = new Client({ name: "journal-contract-fixture", version: "1" });
492
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
493
+ const common = {
494
+ repo: "example/widget",
495
+ issueNumber: 17,
496
+ summary: "Parser validation is ready.",
497
+ status: "In progress",
498
+ nextStep: "Review the parser",
499
+ nextDate: null,
500
+ keyNumbers: [],
501
+ evidence: ["https://github.com/example/widget/pull/23"]
502
+ };
503
+ const decision = {
504
+ ...common,
505
+ kind: "decision",
506
+ decision: "Use the existing parser",
507
+ rationale: "Preserves compatibility"
508
+ };
509
+ try {
510
+ await server.connect(serverTransport);
511
+ await client.connect(clientTransport);
512
+ const valid = await client.callTool({ name: "issue_comment", arguments: decision });
513
+ assert.notEqual(valid.isError, true, JSON.stringify(valid));
514
+ assert.equal(f.comments.length, 1);
515
+ const before = f.calls.length;
516
+ const { rationale: _rationale, ...missingRationale } = decision;
517
+ const refused = await client.callTool({ name: "issue_comment", arguments: missingRationale });
518
+ assert.equal(refused.isError, true);
519
+ assert.equal(f.comments.length, 1, "the invalid call makes zero additional native writes");
520
+ assert.equal(f.calls.length, before, "refusal precedes external authentication and reads");
521
+ const text = JSON.stringify(refused);
522
+ assert.doesNotMatch(text, /-32602|Input validation error/u, "a normal contract refusal must reach the handler");
523
+ assert.match(text, /rationale/u);
524
+ const missingBoth = await client.callTool({ name: "issue_comment", arguments: { ...common, kind: "progress" } });
525
+ assert.equal(missingBoth.isError, true);
526
+ assert.match(JSON.stringify(missingBoth), /Missing required fields: done, decisionNeeded/u);
527
+ const missingCommon = await client.callTool({
528
+ name: "issue_comment",
529
+ arguments: { repo: "example/widget", issueNumber: 17, kind: "decision" }
530
+ });
531
+ assert.equal(missingCommon.isError, true);
532
+ assert.match(
533
+ JSON.stringify(missingCommon),
534
+ /Missing required fields: summary, status, nextStep, nextDate, keyNumbers, evidence, decision, rationale/u
535
+ );
536
+ assert.doesNotMatch(JSON.stringify(missingCommon), /-32602|Input validation error/u);
537
+ const published = (await client.listTools()).tools.find((t) => t.name === "issue_comment");
538
+ assert.deepEqual(
539
+ published?.inputSchema.anyOf,
540
+ z.toJSONSchema(getAiDeliveryMcpTool("issue_comment").inputSchema).anyOf
541
+ );
542
+ assert.match(text, /[Pp]rovide/u, "the refusal explains the correction");
543
+ const listed = (await client.listTools()).tools.find((tool) => tool.name === "issue_comment");
544
+ assert.ok(listed);
545
+ assert.match(listed.description ?? "", /decision: non-empty decision and rationale/u);
546
+ const properties = listed.inputSchema.properties;
547
+ for (const field of ["decision", "rationale"])
548
+ assert.match(properties[field]?.description ?? "", /Required non-empty text when kind is decision/u);
549
+ assert.match(properties.kind?.description ?? "", /progress: done, decisionNeeded and non-empty evidence/u);
550
+ assert.equal(listed.inputSchema.additionalProperties, false);
551
+ const { decision: _decision, ...missingDecision } = decision;
552
+ for (const invalid of [
553
+ missingDecision,
554
+ { ...missingRationale, decision: "PRIVATE_INPUT_SENTINEL" },
555
+ { ...decision, rationale: "" },
556
+ { ...decision, rationale: 17 },
557
+ { ...decision, kind: "PRIVATE_INPUT_SENTINEL" },
558
+ { ...decision, unknown: "PRIVATE_INPUT_SENTINEL" },
559
+ { ...decision, PRIVATE_INPUT_SENTINEL: "private value" },
560
+ {
340
561
  ...common,
341
- kind: 'decision',
342
- decision: 'Use the existing parser',
343
- rationale: 'Preserves compatibility',
344
- };
345
- try {
346
- await server.connect(serverTransport);
347
- await client.connect(clientTransport);
348
- // A successful call first proves the synthetic external ports and real dispatch are wired correctly.
349
- const valid = await client.callTool({ name: 'issue_comment', arguments: decision });
350
- assert.notEqual(valid.isError, true, JSON.stringify(valid));
351
- assert.equal(f.comments.length, 1);
352
- const before = f.calls.length;
353
- const { rationale: _rationale, ...missingRationale } = decision;
354
- const refused = await client.callTool({ name: 'issue_comment', arguments: missingRationale });
355
- assert.equal(refused.isError, true);
356
- assert.equal(f.comments.length, 1, 'the invalid call makes zero additional native writes');
357
- assert.equal(f.calls.length, before, 'refusal precedes external authentication and reads');
358
- const text = JSON.stringify(refused);
359
- assert.doesNotMatch(text, /-32602|Input validation error/u, 'a normal contract refusal must reach the handler');
360
- assert.match(text, /rationale/u);
361
- assert.match(text, /[Pp]rovide/u, 'the refusal explains the correction');
362
- const listed = (await client.listTools()).tools.find((tool) => tool.name === 'issue_comment');
363
- assert.ok(listed);
364
- assert.match(listed.description ?? '', /decision: non-empty decision and rationale/u);
365
- const properties = listed.inputSchema.properties;
366
- for (const field of ['decision', 'rationale'])
367
- assert.match(properties[field]?.description ?? '', /Required non-empty text when kind is decision/u);
368
- assert.match(properties.kind?.description ?? '', /progress: done, decisionNeeded and non-empty evidence/u);
369
- assert.equal(listed.inputSchema.additionalProperties, false);
370
- const { decision: _decision, ...missingDecision } = decision;
371
- for (const invalid of [
372
- missingDecision,
373
- { ...missingRationale, decision: 'PRIVATE_INPUT_SENTINEL' },
374
- { ...decision, rationale: '' },
375
- { ...decision, rationale: 17 },
376
- { ...decision, kind: 'PRIVATE_INPUT_SENTINEL' },
377
- { ...decision, unknown: 'PRIVATE_INPUT_SENTINEL' },
378
- { ...decision, PRIVATE_INPUT_SENTINEL: 'private value' },
379
- {
380
- ...common,
381
- kind: 'closeout',
382
- acceptance: [{ criterion: 'Validated', evidence: common.evidence[0], PRIVATE_INPUT_SENTINEL: 'private value' }],
383
- followUps: [],
384
- },
385
- { ...decision, outcome: 'PRIVATE_INPUT_SENTINEL' },
386
- { ...common, kind: 'start' },
387
- { ...common, kind: 'progress', done: ['Validated'], decisionNeeded: 'None', evidence: [] },
388
- { ...common, kind: 'blocker', blocker: 'Review pending' },
389
- { ...common, kind: 'closeout', acceptance: [], followUps: [] },
390
- ]) {
391
- const invalidResult = await client.callTool({ name: 'issue_comment', arguments: invalid });
392
- assert.equal(invalidResult.isError, true);
393
- assert.doesNotMatch(JSON.stringify(invalidResult), /PRIVATE_INPUT_SENTINEL/u);
394
- assert.equal(f.comments.length, 1, 'invalid journals never create a native comment');
395
- assert.equal(f.calls.length, before, 'invalid journals stop before external ports');
396
- }
397
- const renderedDecision = f.comments[0].body;
398
- assert.match(renderedDecision, /^Parser validation is ready\.\n\n\*\*Kind:\*\* decision\. \*\*Status:\*\* In progress\n\n\*\*Decision:\*\* Use the existing parser\n\n\*\*Rationale:\*\* Preserves compatibility/u);
399
- assert.match(renderedDecision, /<!-- ai-delivery:journal@1:sha256:[a-f0-9]{64} -->$/u);
400
- const retry = await client.callTool({ name: 'issue_comment', arguments: decision });
401
- assert.notEqual(retry.isError, true);
402
- const retried = JSON.parse(retry.content[0].text);
403
- assert.equal(retried.reused, true);
404
- assert.equal(retried.body, renderedDecision);
405
- assert.equal(retried.commentId, 101);
406
- assert.equal(retried.url, 'https://github.com/example/widget/issues/17#issuecomment-101');
407
- assert.equal(f.comments.length, 1);
408
- for (const [variant, section] of [
409
- [{ ...common, kind: 'start', outcome: 'Deliver validation' }, '**Outcome:** Deliver validation'],
410
- [
411
- { ...common, kind: 'progress', done: ['Validated'], decisionNeeded: 'None' },
412
- '**Done since last:**\n- Validated',
413
- ],
414
- [
415
- { ...common, kind: 'blocker', blocker: 'Review pending', resolution: 'Independent acceptance' },
416
- '**Resolution needed:** Independent acceptance',
417
- ],
418
- [
419
- {
420
- ...common,
421
- kind: 'closeout',
422
- acceptance: [{ criterion: 'Validation works', evidence: common.evidence[0] }],
423
- followUps: [],
424
- },
425
- '**Follow-ups:** None.',
426
- ],
427
- ]) {
428
- const accepted = await client.callTool({ name: 'issue_comment', arguments: variant });
429
- assert.notEqual(accepted.isError, true, JSON.stringify(accepted));
430
- const value = JSON.parse(accepted.content[0].text);
431
- assert.equal(value.reused, false);
432
- assert.ok(value.body.includes(section));
433
- assert.equal(value.body, f.comments.at(-1).body, 'response retains authoritative native readback');
434
- }
435
- assert.equal(f.comments.length, 5, 'all five valid journal kinds remain usable');
562
+ kind: "closeout",
563
+ acceptance: [{ criterion: "Validated", evidence: common.evidence[0], PRIVATE_INPUT_SENTINEL: "private value" }],
564
+ followUps: []
565
+ },
566
+ { ...decision, outcome: "PRIVATE_INPUT_SENTINEL" },
567
+ { ...common, kind: "start" },
568
+ { ...common, kind: "progress", done: ["Validated"], decisionNeeded: "None", evidence: [] },
569
+ { ...common, kind: "blocker", blocker: "Review pending" },
570
+ { ...common, kind: "closeout", acceptance: [], followUps: [] }
571
+ ]) {
572
+ const invalidResult = await client.callTool({ name: "issue_comment", arguments: invalid });
573
+ assert.equal(invalidResult.isError, true);
574
+ assert.doesNotMatch(JSON.stringify(invalidResult), /PRIVATE_INPUT_SENTINEL/u);
575
+ assert.equal(f.comments.length, 1, "invalid journals never create a native comment");
576
+ assert.equal(f.calls.length, before, "invalid journals stop before external ports");
436
577
  }
437
- finally {
438
- await client.close();
439
- await server.close();
440
- await f.dispose(undefined);
578
+ const renderedDecision = f.comments[0].body;
579
+ assert.match(
580
+ renderedDecision,
581
+ /^Status: In progress\. Next: Review the parser\.\n\nParser validation is ready\.\n\n\*\*Kind:\*\* decision\. \*\*Status:\*\* In progress\n\n\*\*Decision:\*\* Use the existing parser\n\n\*\*Rationale:\*\* Preserves compatibility/u
582
+ );
583
+ assert.match(renderedDecision, /<!-- ai-delivery:journal@1:sha256:[a-f0-9]{64} -->$/u);
584
+ const retry = await client.callTool({ name: "issue_comment", arguments: { ...decision, verbose: true } });
585
+ assert.notEqual(retry.isError, true);
586
+ const retried = JSON.parse(retry.content[0].text);
587
+ assert.equal(retried.reused, true);
588
+ assert.equal(retried.body, renderedDecision);
589
+ assert.equal(retried.commentId, 101);
590
+ assert.equal(retried.url, "https://github.com/example/widget/issues/17#issuecomment-101");
591
+ assert.equal(f.comments.length, 1);
592
+ for (const [variant, section] of [
593
+ [{ ...common, kind: "start", outcome: "Deliver validation" }, "**Outcome:** Deliver validation"],
594
+ [
595
+ { ...common, kind: "progress", done: ["Validated"], decisionNeeded: "None" },
596
+ "**Done since last:**\n- Validated"
597
+ ],
598
+ [
599
+ { ...common, kind: "blocker", blocker: "Review pending", resolution: "Independent acceptance" },
600
+ "**Resolution needed:** Independent acceptance"
601
+ ],
602
+ [
603
+ {
604
+ ...common,
605
+ kind: "closeout",
606
+ acceptance: [{ criterion: "Validation works", evidence: common.evidence[0] }],
607
+ followUps: []
608
+ },
609
+ "**Follow-ups:** None."
610
+ ]
611
+ ]) {
612
+ const accepted = await client.callTool({ name: "issue_comment", arguments: { ...variant, verbose: true } });
613
+ assert.notEqual(accepted.isError, true, JSON.stringify(accepted));
614
+ const value = JSON.parse(accepted.content[0].text);
615
+ assert.equal(value.reused, false);
616
+ assert.ok(value.body.includes(section));
617
+ assert.equal(value.body, f.comments.at(-1).body, "response retains authoritative native readback");
441
618
  }
619
+ assert.equal(f.comments.length, 5, "all five valid journal kinds remain usable");
620
+ } finally {
621
+ await client.close();
622
+ await server.close();
623
+ await f.dispose(void 0);
624
+ }
442
625
  });
443
- //# sourceMappingURL=issueJournal.test.js.map
626
+ //# sourceMappingURL=issueJournal.test.js.map