@aviaratech/ai-delivery 0.3.24 → 0.3.26

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 (177) hide show
  1. package/CONTRIBUTING.md +157 -16
  2. package/README.md +124 -9
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +1 -0
  5. package/dist/agent.js.map +1 -1
  6. package/dist/agentReadiness.test.d.ts +1 -0
  7. package/dist/agentReadiness.test.js +77 -0
  8. package/dist/agentReadiness.test.js.map +1 -0
  9. package/dist/cli.js +136 -36
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config/deliveryConfig.js +5 -1
  12. package/dist/config/deliveryConfig.js.map +1 -1
  13. package/dist/contributorChecks.test.d.ts +1 -0
  14. package/dist/contributorChecks.test.js +1010 -0
  15. package/dist/contributorChecks.test.js.map +1 -0
  16. package/dist/currentConsumer.test.d.ts +1 -0
  17. package/dist/currentConsumer.test.js +832 -0
  18. package/dist/currentConsumer.test.js.map +1 -0
  19. package/dist/deliveryHealth.test.d.ts +1 -0
  20. package/dist/deliveryHealth.test.js +167 -0
  21. package/dist/deliveryHealth.test.js.map +1 -0
  22. package/dist/dependencyCompatibility.test.d.ts +1 -0
  23. package/dist/dependencyCompatibility.test.js +175 -0
  24. package/dist/dependencyCompatibility.test.js.map +1 -0
  25. package/dist/directoryIndependent.test.js +91 -1
  26. package/dist/directoryIndependent.test.js.map +1 -1
  27. package/dist/dispatch.d.ts +1 -0
  28. package/dist/dispatch.js +53 -4
  29. package/dist/dispatch.js.map +1 -1
  30. package/dist/fixtures/inertEntrypointChild.d.ts +1 -0
  31. package/dist/fixtures/inertEntrypointChild.js +62 -0
  32. package/dist/fixtures/inertEntrypointChild.js.map +1 -0
  33. package/dist/fixtures/inertEntrypoints.d.ts +49 -0
  34. package/dist/fixtures/inertEntrypoints.js +276 -0
  35. package/dist/fixtures/inertEntrypoints.js.map +1 -0
  36. package/dist/fixtures/inertTarget.d.ts +643 -0
  37. package/dist/fixtures/inertTarget.js +713 -0
  38. package/dist/fixtures/inertTarget.js.map +1 -0
  39. package/dist/fixtures/issue63.d.ts +68 -0
  40. package/dist/fixtures/issue63.js +272 -0
  41. package/dist/fixtures/issue63.js.map +1 -0
  42. package/dist/github/client.d.ts +2 -0
  43. package/dist/github/client.js +94 -12
  44. package/dist/github/client.js.map +1 -1
  45. package/dist/github/issueHistory.d.ts +40 -0
  46. package/dist/github/issueHistory.js +144 -0
  47. package/dist/github/issueHistory.js.map +1 -0
  48. package/dist/github/machineAuth.d.ts +9 -0
  49. package/dist/github/machineAuth.js +135 -0
  50. package/dist/github/machineAuth.js.map +1 -0
  51. package/dist/github/machineAuth.test.d.ts +1 -0
  52. package/dist/github/machineAuth.test.js +409 -0
  53. package/dist/github/machineAuth.test.js.map +1 -0
  54. package/dist/github/projectDelivery.d.ts +2 -0
  55. package/dist/github/projectDelivery.js +6 -0
  56. package/dist/github/projectDelivery.js.map +1 -1
  57. package/dist/github/relationships.d.ts +9 -2
  58. package/dist/github/relationships.js +6 -2
  59. package/dist/github/relationships.js.map +1 -1
  60. package/dist/investigationCompletion.test.d.ts +1 -0
  61. package/dist/investigationCompletion.test.js +728 -0
  62. package/dist/investigationCompletion.test.js.map +1 -0
  63. package/dist/issue.d.ts +29 -6
  64. package/dist/issue.js +153 -22
  65. package/dist/issue.js.map +1 -1
  66. package/dist/issue63History.test.d.ts +1 -0
  67. package/dist/issue63History.test.js +45 -0
  68. package/dist/issue63History.test.js.map +1 -0
  69. package/dist/issue63Routes.test.d.ts +1 -0
  70. package/dist/issue63Routes.test.js +153 -0
  71. package/dist/issue63Routes.test.js.map +1 -0
  72. package/dist/issueBlockerGuard.test.d.ts +1 -0
  73. package/dist/issueBlockerGuard.test.js +162 -0
  74. package/dist/issueBlockerGuard.test.js.map +1 -0
  75. package/dist/issueContract.d.ts +230 -0
  76. package/dist/issueContract.js +341 -0
  77. package/dist/issueContract.js.map +1 -0
  78. package/dist/issueContract.test.d.ts +27 -0
  79. package/dist/issueContract.test.js +314 -0
  80. package/dist/issueContract.test.js.map +1 -0
  81. package/dist/issueIntake.test.d.ts +1 -0
  82. package/dist/issueIntake.test.js +649 -0
  83. package/dist/issueIntake.test.js.map +1 -0
  84. package/dist/issueJournal.d.ts +1 -1
  85. package/dist/issueJournal.test.js +88 -6
  86. package/dist/issueJournal.test.js.map +1 -1
  87. package/dist/issueTracking.test.js +16 -8
  88. package/dist/issueTracking.test.js.map +1 -1
  89. package/dist/mcp/tools.d.ts +142 -12
  90. package/dist/mcp/tools.js +104 -34
  91. package/dist/mcp/tools.js.map +1 -1
  92. package/dist/pluginAuthProbe.d.ts +6 -0
  93. package/dist/pluginAuthProbe.js +53 -0
  94. package/dist/pluginAuthProbe.js.map +1 -0
  95. package/dist/pluginAuthProbe.test.d.ts +1 -0
  96. package/dist/pluginAuthProbe.test.js +66 -0
  97. package/dist/pluginAuthProbe.test.js.map +1 -0
  98. package/dist/pluginCredentials.test.d.ts +1 -0
  99. package/dist/pluginCredentials.test.js +277 -0
  100. package/dist/pluginCredentials.test.js.map +1 -0
  101. package/dist/pluginDoctor.test.d.ts +1 -0
  102. package/dist/pluginDoctor.test.js +627 -0
  103. package/dist/pluginDoctor.test.js.map +1 -0
  104. package/dist/pluginInstaller.d.ts +36 -0
  105. package/dist/pluginInstaller.js +238 -11
  106. package/dist/pluginInstaller.js.map +1 -1
  107. package/dist/pluginInstaller.test.js +242 -2
  108. package/dist/pluginInstaller.test.js.map +1 -1
  109. package/dist/pluginPackaging.test.js +123 -9
  110. package/dist/pluginPackaging.test.js.map +1 -1
  111. package/dist/pr.d.ts +90 -13
  112. package/dist/pr.js +875 -66
  113. package/dist/pr.js.map +1 -1
  114. package/dist/pr.test.js +166 -7
  115. package/dist/pr.test.js.map +1 -1
  116. package/dist/prAssociation.test.d.ts +1 -0
  117. package/dist/prAssociation.test.js +1336 -0
  118. package/dist/prAssociation.test.js.map +1 -0
  119. package/dist/prDispatch.test.d.ts +1 -0
  120. package/dist/prDispatch.test.js +96 -0
  121. package/dist/prDispatch.test.js.map +1 -0
  122. package/dist/releaseReconciliation.test.js +6 -2
  123. package/dist/releaseReconciliation.test.js.map +1 -1
  124. package/dist/releaseWorkflow.test.d.ts +1 -0
  125. package/dist/releaseWorkflow.test.js +447 -0
  126. package/dist/releaseWorkflow.test.js.map +1 -0
  127. package/dist/services/agentReadinessService.d.ts +9 -8
  128. package/dist/services/agentReadinessService.js +32 -223
  129. package/dist/services/agentReadinessService.js.map +1 -1
  130. package/dist/services/blockerGuardService.d.ts +17 -0
  131. package/dist/services/blockerGuardService.js +194 -0
  132. package/dist/services/blockerGuardService.js.map +1 -0
  133. package/dist/services/deliveryAdmission.js +22 -19
  134. package/dist/services/deliveryAdmission.js.map +1 -1
  135. package/dist/services/deliveryHealthService.d.ts +84 -0
  136. package/dist/services/deliveryHealthService.js +206 -0
  137. package/dist/services/deliveryHealthService.js.map +1 -0
  138. package/dist/services/worktreeRegistry.d.ts +84 -0
  139. package/dist/services/worktreeRegistry.js +265 -1
  140. package/dist/services/worktreeRegistry.js.map +1 -1
  141. package/dist/setup.test.js +97 -3
  142. package/dist/setup.test.js.map +1 -1
  143. package/dist/stagedChecks.test.d.ts +1 -0
  144. package/dist/stagedChecks.test.js +228 -0
  145. package/dist/stagedChecks.test.js.map +1 -0
  146. package/dist/start.test.js +30 -3
  147. package/dist/start.test.js.map +1 -1
  148. package/dist/stdoutRegression.test.js +36 -6
  149. package/dist/stdoutRegression.test.js.map +1 -1
  150. package/dist/targetPolicyEntrypoints.test.d.ts +1 -0
  151. package/dist/targetPolicyEntrypoints.test.js +275 -0
  152. package/dist/targetPolicyEntrypoints.test.js.map +1 -0
  153. package/dist/targetPolicyLocal.test.d.ts +1 -0
  154. package/dist/targetPolicyLocal.test.js +707 -0
  155. package/dist/targetPolicyLocal.test.js.map +1 -0
  156. package/dist/targetPolicyRoutes.test.d.ts +1 -0
  157. package/dist/targetPolicyRoutes.test.js +298 -0
  158. package/dist/targetPolicyRoutes.test.js.map +1 -0
  159. package/dist/verification.js +48 -12
  160. package/dist/verification.js.map +1 -1
  161. package/dist/verificationGate.test.d.ts +1 -0
  162. package/dist/verificationGate.test.js +106 -0
  163. package/dist/verificationGate.test.js.map +1 -0
  164. package/dist/worktree.d.ts +6 -1
  165. package/dist/worktree.js +90 -3
  166. package/dist/worktree.js.map +1 -1
  167. package/dist/worktreeTransition.test.js +1 -1
  168. package/dist/worktreeTransition.test.js.map +1 -1
  169. package/package.json +9 -6
  170. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  171. package/plugins/ai-delivery/README.md +160 -1
  172. package/plugins/ai-delivery/plugin.json +1 -1
  173. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +1 -1
  174. package/plugins/ai-delivery/runtime/dist/cli.js +83 -49
  175. package/plugins/ai-delivery/runtime/package.json +1 -1
  176. package/plugins/ai-delivery/skills/intake-create/SKILL.md +45 -30
  177. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +20 -0
@@ -0,0 +1,649 @@
1
+ import assert from 'node:assert/strict';
2
+ import { readFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { execFileSync, spawnSync } from 'node:child_process';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { test } from 'vitest';
7
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
9
+ import { z } from 'zod';
10
+ import { createIssue, updateIssue, canonicalIssueBody } from './issue.js';
11
+ import { executeTool, startTrackedIssue } from './dispatch.js';
12
+ import { digestValue } from './delivery/common.js';
13
+ import { getAiDeliveryMcpTool } from './mcp/tools.js';
14
+ import { IssueFields, ReadyIssue, renderIssueBody, parseIssueBody, ISSUE_BODY_MARKER } from './issueContract.js';
15
+ import { syntheticDiscoveryConfig } from './fixtures/discovery.js';
16
+ const ready = () => IssueFields.parse({
17
+ title: 'Reject invalid widget identifiers before persistence',
18
+ issueType: 'Task',
19
+ points: 2,
20
+ problem: 'Malformed identifiers reach persistence.',
21
+ outcome: 'Reject malformed widget identifiers before persistence.',
22
+ acceptanceCriteria: [
23
+ {
24
+ behavior: 'An invalid identifier returns an error with zero persistence calls.',
25
+ verifiedBy: 'A portable mocked persistence regression test.',
26
+ },
27
+ ],
28
+ outOfScope: ['Storage changes.'],
29
+ context: { components: ['widget'], files: [], evidence: [] },
30
+ });
31
+ function fixture() {
32
+ const live = {
33
+ number: 17,
34
+ id: 117,
35
+ node_id: 'ISSUE17',
36
+ title: ready().title,
37
+ body: renderIssueBody(ready()),
38
+ state: 'open',
39
+ created_at: '2026-01-01T00:00:00Z',
40
+ type: { name: 'Task' },
41
+ html_url: 'https://github.com/example/widget/issues/17',
42
+ };
43
+ const writes = [];
44
+ const comments = [];
45
+ const controls = {
46
+ role: 'author',
47
+ ignoreBody: false,
48
+ wrongCreateRepo: false,
49
+ driftAfterHistory: false,
50
+ created: true,
51
+ blockers: false,
52
+ trackingParent: false,
53
+ livePoints: 2,
54
+ };
55
+ const branchWrites = [];
56
+ const branches = [];
57
+ let points = 2;
58
+ let status = 'Queued';
59
+ const values = () => [
60
+ {
61
+ issue_field_id: 101,
62
+ issue_field_name: 'Estimate',
63
+ data_type: 'single_select',
64
+ value: String(controls.livePoints),
65
+ },
66
+ ];
67
+ const context = {
68
+ root: '/synthetic-non-git',
69
+ repo: { owner: 'example', repo: 'widget' },
70
+ config: syntheticDiscoveryConfig,
71
+ projectConfiguration: {
72
+ projectId: 'PROJECT',
73
+ projectNumber: 1,
74
+ title: 'Delivery',
75
+ writable: true,
76
+ pointsFieldId: 'POINTS',
77
+ priorityFieldId: 'PRIORITY',
78
+ statusFieldId: 'STATUS',
79
+ statusOptionIds: { Todo: 'TODO', 'In Progress': 'ACTIVE', Blocked: 'BLOCKED', Done: 'DONE' },
80
+ settings: {
81
+ number: 1,
82
+ title: 'Delivery',
83
+ statusField: 'Flow',
84
+ statuses: { Todo: 'Queued', 'In Progress': 'Active', Blocked: 'Waiting', Done: 'Shipped' },
85
+ },
86
+ },
87
+ clients: {
88
+ get role() {
89
+ return controls.role;
90
+ },
91
+ authenticatedAuthor: async () => ({ actorLogin: 'operator', credentialIdentity: 'user:1' }),
92
+ rest: {
93
+ issues: {
94
+ listSubIssues: async () => ({ data: controls.trackingParent ? [{ number: 18 }] : [] }),
95
+ get: async () => ({ data: { ...live } }),
96
+ listForRepo: async () => ({ data: controls.created ? [{ ...live }] : [] }),
97
+ create: async (input) => {
98
+ writes.push(input);
99
+ controls.created = true;
100
+ live.title = String(input.title);
101
+ live.body = String(input.body);
102
+ live.type = { name: String(input.type) };
103
+ return {
104
+ data: {
105
+ ...live,
106
+ ...(controls.wrongCreateRepo ? { html_url: 'https://github.com/other/widget/issues/17' } : {}),
107
+ },
108
+ };
109
+ },
110
+ update: async (input) => {
111
+ writes.push(input);
112
+ if (!controls.ignoreBody && typeof input.body === 'string')
113
+ live.body = input.body;
114
+ if (typeof input.title === 'string')
115
+ live.title = input.title;
116
+ if (typeof input.type === 'string')
117
+ live.type = { name: input.type };
118
+ return { data: { ...live } };
119
+ },
120
+ listComments: async () => ({ data: comments }),
121
+ createComment: async (input) => {
122
+ const comment = {
123
+ id: 91 + comments.length,
124
+ body: input.body,
125
+ html_url: 'https://github.com/example/widget/issues/17#issuecomment-' + String(91 + comments.length),
126
+ user: { login: 'operator' },
127
+ issue_url: 'https://api.github.com/repos/example/widget/issues/17',
128
+ };
129
+ comments.push(comment);
130
+ return { data: comment };
131
+ },
132
+ getComment: async (input) => {
133
+ if (controls.driftAfterHistory)
134
+ live.body = 'Concurrent owner content';
135
+ return { data: comments.find((c) => c.id === input.comment_id) };
136
+ },
137
+ },
138
+ repos: { get: async () => ({ data: { default_branch: 'main', node_id: 'REPOSITORY' } }) },
139
+ git: { getRef: async () => ({ data: { object: { sha: 'a'.repeat(40) } } }) },
140
+ request: async (route, input) => {
141
+ if (route === 'GET /orgs/{org}/issue-fields')
142
+ return {
143
+ data: [
144
+ {
145
+ id: 101,
146
+ name: 'Estimate',
147
+ data_type: 'single_select',
148
+ options: ['1', '2', '4'].map((name) => ({ name })),
149
+ },
150
+ {
151
+ id: 102,
152
+ name: 'Urgency',
153
+ data_type: 'single_select',
154
+ options: ['High', 'Low'].map((name) => ({ name })),
155
+ },
156
+ ],
157
+ };
158
+ if (route.startsWith('POST ')) {
159
+ const fields = input.issue_field_values;
160
+ points = Number(fields.find((f) => f.field_id === 101)?.value ?? points);
161
+ controls.livePoints = points;
162
+ return { data: values() };
163
+ }
164
+ if (route.startsWith('GET '))
165
+ return { data: values() };
166
+ throw new Error('Unexpected native request ' + route);
167
+ },
168
+ },
169
+ graphql: async (query, input) => {
170
+ if (query.includes('DeliveryIssueBranches'))
171
+ return {
172
+ repository: {
173
+ issue: {
174
+ linkedBranches: {
175
+ nodes: branches.map((branch) => ({
176
+ ref: {
177
+ name: branch.name,
178
+ target: { oid: branch.sha },
179
+ repository: { nameWithOwner: 'example/widget' },
180
+ },
181
+ })),
182
+ pageInfo: { hasNextPage: false, endCursor: null },
183
+ },
184
+ },
185
+ },
186
+ };
187
+ if (query.includes('DeliveryStartBranch')) {
188
+ const fields = input.input;
189
+ branchWrites.push(fields);
190
+ branches.push({ name: String(fields.name), sha: String(fields.oid) });
191
+ return { createLinkedBranch: { linkedBranch: { ref: { name: fields.name, target: { oid: fields.oid } } } } };
192
+ }
193
+ if (query.includes('blockedBy(first:'))
194
+ return {
195
+ repository: {
196
+ issue: {
197
+ parent: null,
198
+ blockedBy: {
199
+ nodes: controls.blockers
200
+ ? [
201
+ {
202
+ id: 'ISSUE18',
203
+ number: 18,
204
+ title: 'Resolve prerequisite',
205
+ state: 'OPEN',
206
+ repository: { nameWithOwner: 'example/widget' },
207
+ },
208
+ ]
209
+ : [],
210
+ pageInfo: { hasNextPage: false, endCursor: null },
211
+ },
212
+ },
213
+ },
214
+ };
215
+ if (query.includes('ProjectDeliveryItems'))
216
+ return {
217
+ organization: {
218
+ projectV2: {
219
+ items: {
220
+ nodes: [
221
+ {
222
+ id: 'ITEM17',
223
+ isArchived: false,
224
+ content: { id: 'ISSUE17' },
225
+ fieldValueByName: { name: status, optionId: status === 'Queued' ? 'TODO' : 'ACTIVE' },
226
+ },
227
+ ],
228
+ pageInfo: { hasNextPage: false, endCursor: null },
229
+ },
230
+ },
231
+ },
232
+ };
233
+ if (query.includes('UpdateProjectDeliveryStatus')) {
234
+ status = input.optionId === 'TODO' ? 'Queued' : input.optionId === 'DONE' ? 'Shipped' : 'Active';
235
+ return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'ITEM17' } } };
236
+ }
237
+ if (query.includes('ProjectDeliveryItemReadback'))
238
+ return {
239
+ node: {
240
+ id: 'ITEM17',
241
+ isArchived: false,
242
+ project: { id: 'PROJECT', number: 1 },
243
+ content: { id: 'ISSUE17' },
244
+ fieldValueByName: { name: status, optionId: status === 'Queued' ? 'TODO' : 'ACTIVE' },
245
+ },
246
+ };
247
+ throw new Error('Unexpected native query ' + query);
248
+ },
249
+ },
250
+ };
251
+ return { context, live, writes, comments, controls, branchWrites, getStatus: () => status };
252
+ }
253
+ test('native create validates first, writes canonical fields, reads back metadata and returns warnings', async () => {
254
+ const f = fixture();
255
+ await assert.rejects(createIssue(f.context, { ...ready(), openQuestions: ['Select behavior.'] }), /open-questions/u);
256
+ assert.equal(f.writes.length, 0);
257
+ const result = await createIssue(f.context, ready());
258
+ assert.equal(f.writes.length, 1);
259
+ assert.equal(result.body, renderIssueBody(ready()));
260
+ assert.equal(parseIssueBody(result.body, { title: result.created.title }).issue.points, 2);
261
+ assert.deepEqual(result.warnings, []);
262
+ assert.equal(f.getStatus(), 'Queued');
263
+ });
264
+ test('incomplete drafts write parked; reviewer-role writes and wrong native repository readback are refused', async () => {
265
+ const f = fixture();
266
+ await createIssue(f.context, { title: 'Investigate invalid widget identifiers', draft: true });
267
+ assert.equal(f.getStatus(), 'Queued');
268
+ assert.match(f.live.body, /Draft — parked/u);
269
+ f.controls.role = 'reviewer';
270
+ await assert.rejects(createIssue(f.context, ready()), /author role/u);
271
+ await assert.rejects(updateIssue(f.context, { issueNumber: 17, draft: true }), /author role/u);
272
+ const bad = fixture();
273
+ bad.controls.wrongCreateRepo = true;
274
+ await assert.rejects(createIssue(bad.context, ready()), /created but native tracking did not complete/u);
275
+ assert.equal(bad.writes.length, 1);
276
+ });
277
+ test('first legacy update retains exact history and full diff, then typed patches preserve unspecified fields', async () => {
278
+ const f = fixture();
279
+ const legacy = '## Problem\nMalformed identifiers reach persistence.\n## Outcome\nReject malformed identifiers.\n## Acceptance Criteria\n- [ ] Invalid identifiers return an error without persistence.\n## Verification\nA portable regression asserts no write.\n## Out of scope\n- Storage changes.\n## Scope\nwidget component\n';
280
+ f.live.body = legacy;
281
+ const result = await updateIssue(f.context, { issueNumber: 17 });
282
+ assert.equal(f.comments.length, 1);
283
+ assert.equal(result.conversion?.priorBody, legacy);
284
+ assert.match(result.conversion.diff, /^--- prior body\n\+\+\+ canonical body/u);
285
+ assert.match(f.comments[0].body, /Malformed identifiers reach persistence/u);
286
+ assert.equal(parseIssueBody(result.body, { title: result.title }).issue.legacyBody, legacy);
287
+ const patched = await updateIssue(f.context, {
288
+ issueNumber: 17,
289
+ outcome: 'Reject malformed identifiers with a typed error.',
290
+ preserveHistory: true,
291
+ });
292
+ assert.equal(parseIssueBody(patched.body, { title: patched.title }).issue.acceptanceCriteria.length, 1);
293
+ assert.equal(patched.conversion, undefined);
294
+ assert.equal(f.comments.length, 2);
295
+ });
296
+ test('legacy replacement updates preserve the actual previous body and diff for canonical and handwritten input', async () => {
297
+ const original = 'Original native legacy bytes, including unclassified operator context.\n';
298
+ for (const replacement of [renderIssueBody(ready()), 'Replacement handwritten context.\n']) {
299
+ const f = fixture();
300
+ f.live.body = original;
301
+ const result = await updateIssue(f.context, { issueNumber: 17, body: replacement, ...ready() });
302
+ assert.equal(f.comments.length, 1);
303
+ assert.ok(f.comments[0].body.includes(original));
304
+ assert.equal(result.conversion?.priorBody, original);
305
+ assert.ok(result.conversion.diff.includes('-' + original.trim()));
306
+ const preserved = parseIssueBody(result.body, { title: result.title }).issue.legacyBody;
307
+ assert.ok(preserved?.includes(original));
308
+ if (!replacement.startsWith(ISSUE_BODY_MARKER))
309
+ assert.ok(preserved?.includes(replacement));
310
+ assert.equal(result.conversion?.canonicalBody, result.body);
311
+ const patch = await updateIssue(f.context, {
312
+ issueNumber: 17,
313
+ outcome: 'Reject invalid input before persistence.',
314
+ });
315
+ assert.equal(patch.conversion, undefined);
316
+ assert.equal(f.comments.length, 1);
317
+ assert.equal(parseIssueBody(patch.body, { title: patch.title }).issue.legacyBody, preserved);
318
+ }
319
+ });
320
+ test('validation, history drift and corrupted native update readback fail without a fabricated success', async () => {
321
+ const f = fixture();
322
+ await assert.rejects(updateIssue(f.context, { issueNumber: 17, openQuestions: ['Choose a policy.'] }), /open-questions/u);
323
+ assert.equal(f.writes.length, 0);
324
+ assert.equal(f.comments.length, 0);
325
+ f.controls.driftAfterHistory = true;
326
+ await assert.rejects(updateIssue(f.context, {
327
+ issueNumber: 17,
328
+ outcome: 'Reject malformed input before all writes.',
329
+ preserveHistory: true,
330
+ }), /content changed/u);
331
+ assert.equal(f.writes.length, 0);
332
+ const bad = fixture();
333
+ bad.controls.ignoreBody = true;
334
+ await assert.rejects(updateIssue(bad.context, { issueNumber: 17, outcome: 'Reject malformed input before all writes.' }), /update readback disagrees/u);
335
+ });
336
+ test('normal-start canonical retry body keeps exact intent markers through create/readiness', async () => {
337
+ const issue = ready();
338
+ const canonical = canonicalIssueBody(issue);
339
+ const footer = '\n\n<!-- ai-delivery-start-intent: ' +
340
+ digestValue({ intent: 'fixture' }) +
341
+ ' -->\n<!-- ai-delivery-start: ' +
342
+ digestValue({ request: 'fixture' }) +
343
+ ' -->';
344
+ const result = await createIssue(fixture().context, {
345
+ title: issue.title,
346
+ body: canonical + footer,
347
+ points: 2,
348
+ issueType: 'Task',
349
+ });
350
+ assert.equal(result.body, canonical + footer);
351
+ assert.deepEqual(parseIssueBody(result.body, { title: issue.title }).issue, issue);
352
+ });
353
+ test('actual normal-start creation and retry reuse the exact canonical body, branch and authored journal', async () => {
354
+ const f = fixture();
355
+ f.controls.created = false;
356
+ const request = getAiDeliveryMcpTool('issue_start').inputSchema.parse({
357
+ title: ready().title,
358
+ body: renderIssueBody(ready()),
359
+ issueType: 'Task',
360
+ points: 2,
361
+ requestId: 'issue68-normal-start',
362
+ });
363
+ const first = await startTrackedIssue(f.context, request);
364
+ assert.ok('issueNumber' in first);
365
+ assert.equal(first.issueNumber, 17);
366
+ assert.ok('reused' in first && first.reused === false);
367
+ const body = f.live.body;
368
+ assert.match(body, /ai-delivery-start-intent: sha256:[a-f0-9]{64}/u);
369
+ assert.match(body, /ai-delivery-start: sha256:[a-f0-9]{64}/u);
370
+ assert.deepEqual(parseIssueBody(body, { title: f.live.title }).issue, ready());
371
+ assert.equal(f.branchWrites.length, 1);
372
+ assert.equal(f.branchWrites[0]?.clientMutationId, digestValue({ repository: 'example/widget', issueNumber: 17, name: 'issue/17', base: 'a'.repeat(40) }));
373
+ assert.equal(f.comments.length, 1);
374
+ const retry = await startTrackedIssue(f.context, request);
375
+ assert.ok('reused' in retry && retry.reused === true);
376
+ assert.equal(retry.issueNumber, 17);
377
+ assert.equal(f.writes.filter((input) => !('issue_number' in input)).length, 1);
378
+ assert.equal(f.branchWrites.length, 1);
379
+ assert.equal(f.comments.length, 1);
380
+ assert.equal(f.live.body, body);
381
+ await assert.rejects(startTrackedIssue(f.context, {
382
+ ...request,
383
+ body: renderIssueBody({ ...ready(), outcome: 'A conflicting new outcome.' }),
384
+ }), /conflicts/u);
385
+ assert.equal(f.branchWrites.length, 1);
386
+ });
387
+ test('a history rewrite refuses to republish secret-bearing prior text', async () => {
388
+ const f = fixture();
389
+ f.live.body = 'An accidental fixture ' + ['gh', 'p_'].join('') + 'A'.repeat(24);
390
+ await assert.rejects(updateIssue(f.context, { issueNumber: 17, body: renderIssueBody(ready()), preserveHistory: true }), /secrets/u);
391
+ assert.equal(f.comments.length, 0);
392
+ assert.equal(f.writes.length, 0);
393
+ });
394
+ test('ordinary start checks typed Draft, Points and live eligibility before branch or journal mutation', async () => {
395
+ for (const [expected, change] of [
396
+ [
397
+ 'draft',
398
+ (f) => {
399
+ f.live.body = renderIssueBody({ ...ready(), draft: true });
400
+ },
401
+ ],
402
+ [
403
+ 'points.sync',
404
+ (f) => {
405
+ f.controls.livePoints = 4;
406
+ },
407
+ ],
408
+ [
409
+ 'blocked',
410
+ (f) => {
411
+ f.controls.blockers = true;
412
+ },
413
+ ],
414
+ [
415
+ 'tracking-parent',
416
+ (f) => {
417
+ f.controls.trackingParent = true;
418
+ },
419
+ ],
420
+ ]) {
421
+ const f = fixture();
422
+ change(f);
423
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), (error) => {
424
+ assert.ok(error instanceof Error);
425
+ const diagnostics = JSON.parse(error.message);
426
+ assert(diagnostics.failures.some((failure) => failure.code === expected && failure.field && failure.fixHint));
427
+ return true;
428
+ });
429
+ assert.equal(f.branchWrites.length, 0);
430
+ assert.equal(f.comments.length, 0);
431
+ assert.equal(f.writes.length, 0);
432
+ }
433
+ const f = fixture();
434
+ f.live.body = renderIssueBody({ ...ready(), outcome: 'Retain the Todo label when validation passes.' });
435
+ const first = await startTrackedIssue(f.context, { issueNumber: 17 });
436
+ assert.ok('reused' in first && first.reused === false);
437
+ assert.ok('reused' in (await startTrackedIssue(f.context, { issueNumber: 17 })));
438
+ assert.equal(f.branchWrites.length, 1);
439
+ assert.equal(f.comments.length, 1);
440
+ });
441
+ test('joined MCP start modes preserve ordinary input and reject mixed investigation or foreign repository calls before configuration', async () => {
442
+ const schema = getAiDeliveryMcpTool('issue_start').inputSchema;
443
+ assert(schema.safeParse({ issueNumber: 17, repo: 'example/widget' }).success);
444
+ assert(schema.safeParse({ body: renderIssueBody(ready()), title: ready().title, points: 2, issueType: 'Task' }).success);
445
+ for (const arguments_ of [
446
+ { issueNumber: 17, expectedHeadSha: 'a'.repeat(40) },
447
+ {
448
+ issueNumber: 17,
449
+ investigationWorktree: '/fictional/issue-17',
450
+ expectedHeadSha: 'a'.repeat(40),
451
+ body: renderIssueBody(ready()),
452
+ },
453
+ ])
454
+ assert.equal(schema.safeParse(arguments_).success, false);
455
+ await assert.rejects(executeTool('issue_start', { repo: 'foreign/widget', issueNumber: 17 }, { repo: 'example/widget', repoRoot: '/synthetic-non-git' }), /selectors disagree/u);
456
+ const finish = getAiDeliveryMcpTool('issue_finish').inputSchema;
457
+ assert(finish.safeParse({ issueNumber: 17, prNumber: 23 }).success);
458
+ assert.equal(finish.safeParse({ issueNumber: 17 }).success, false);
459
+ assert.equal(finish.safeParse({ issueNumber: 17, investigation: true, resultPath: '/fictional/result', prNumber: 23 }).success, false);
460
+ });
461
+ test('created readiness refusal returns exact retry markers through safe resume and original request retry', async () => {
462
+ const f = fixture();
463
+ f.controls.created = false;
464
+ f.controls.trackingParent = true;
465
+ const schema = getAiDeliveryMcpTool('issue_start').inputSchema;
466
+ const request = schema.parse({
467
+ title: ready().title,
468
+ body: renderIssueBody(ready()),
469
+ issueType: 'Task',
470
+ points: 2,
471
+ requestId: 'issue68-readiness-recovery',
472
+ });
473
+ const interrupted = await startTrackedIssue(f.context, request);
474
+ if (!('status' in interrupted))
475
+ assert.fail('Expected a known-created readiness refusal.');
476
+ assert.equal(interrupted.status, 'created-not-started');
477
+ const nativeBody = f.live.body;
478
+ assert.match(nativeBody, /ai-delivery-start-intent: sha256:[a-f0-9]{64}/u);
479
+ assert.match(nativeBody, /ai-delivery-start: sha256:[a-f0-9]{64}/u);
480
+ assert.equal(interrupted.safeResume.arguments.body, nativeBody);
481
+ assert.equal(f.branchWrites.length, 0);
482
+ assert.equal(f.comments.length, 0);
483
+ assert.equal(f.writes.filter((write) => !('issue_number' in write)).length, 1);
484
+ f.controls.trackingParent = false;
485
+ const resumed = await startTrackedIssue(f.context, schema.parse(interrupted.safeResume.arguments));
486
+ assert.ok('reused' in resumed && resumed.reused === false);
487
+ assert.equal(f.live.body, nativeBody);
488
+ const retry = await startTrackedIssue(f.context, request);
489
+ assert.ok('reused' in retry && retry.reused === true);
490
+ assert.equal(f.live.body, nativeBody);
491
+ assert.equal(f.writes.filter((write) => !('issue_number' in write)).length, 1);
492
+ assert.equal(f.branchWrites.length, 1);
493
+ assert.equal(f.comments.length, 1);
494
+ });
495
+ test('actual compiled stdio MCP returns every Ready diagnostic before credentials and refuses a foreign caller repo', async () => {
496
+ const root = mkdtempSync(join(tmpdir(), 'issue-contract-stdio-'));
497
+ const transport = new StdioClientTransport({
498
+ command: process.execPath,
499
+ args: [resolve('dist/cli.js'), '--identity', 'host-author', '--repo', 'example/widget', 'mcp:serve'],
500
+ cwd: root,
501
+ stderr: 'pipe',
502
+ env: {
503
+ HOME: root,
504
+ PATH: process.env.PATH ?? '',
505
+ AI_DELIVERY_CONFIG: join(root, 'missing-config.json'),
506
+ LANG: 'en_US.UTF-8',
507
+ },
508
+ });
509
+ const client = new Client({ name: 'issue68-synthetic-client', version: '1.0.0' });
510
+ let spawnedPid = null;
511
+ let closeObserved = false;
512
+ try {
513
+ await client.connect(transport);
514
+ spawnedPid = transport.pid;
515
+ assert.ok(spawnedPid);
516
+ const original = transport.onclose;
517
+ transport.onclose = () => {
518
+ closeObserved = true;
519
+ original?.();
520
+ };
521
+ const listing = await client.listTools();
522
+ assert.ok(listing.tools.find((t) => t.name === 'issue_create')?.inputSchema.properties?.acceptanceCriteria);
523
+ const result = await client.callTool({
524
+ name: 'issue_create',
525
+ arguments: { ...ready(), points: 13, openQuestions: ['Select behavior.'] },
526
+ });
527
+ assert.equal(result.isError, true);
528
+ const content = z.array(z.object({ type: z.literal('text'), text: z.string() })).parse(result.content);
529
+ const diagnostic = z
530
+ .object({
531
+ contract: z.literal('ai-delivery.issue@1'),
532
+ failures: z.array(z.object({ code: z.string(), field: z.string(), fixHint: z.string() })),
533
+ })
534
+ .parse(JSON.parse(content[0].text));
535
+ assert.deepEqual(diagnostic.failures.map((f) => f.code).sort(), ['open-questions', 'points']);
536
+ assert.ok(diagnostic.failures.every((f) => f.field && f.fixHint));
537
+ for (const name of ['issue_create', 'issue_update']) {
538
+ const malformed = await client.callTool({
539
+ name,
540
+ arguments: {
541
+ ...ready(),
542
+ ...(name === 'issue_update' ? { issueNumber: 17 } : {}),
543
+ acceptanceCriteria: [{ behavior: ready().acceptanceCriteria[0].behavior }],
544
+ context: { components: 9 },
545
+ },
546
+ });
547
+ assert.equal(malformed.isError, true);
548
+ const blocks = z.array(z.object({ type: z.literal('text'), text: z.string() })).parse(malformed.content);
549
+ const failure = z
550
+ .object({
551
+ contract: z.literal('ai-delivery.issue@1'),
552
+ failures: z.array(z.object({ code: z.string(), field: z.string(), fixHint: z.string() })),
553
+ })
554
+ .parse(JSON.parse(blocks[0].text));
555
+ assert.deepEqual(failure.failures.map((f) => f.field).sort(), [
556
+ 'acceptanceCriteria.0.verifiedBy',
557
+ 'context.components',
558
+ ]);
559
+ assert.ok(failure.failures.every((f) => f.code && f.fixHint));
560
+ assert.doesNotMatch(blocks[0].text, /missing-config/u);
561
+ const unknown = await client.callTool({
562
+ name,
563
+ arguments: {
564
+ ...ready(),
565
+ ...(name === 'issue_update' ? { issueNumber: 17 } : {}),
566
+ unexpectedField: 'Root field must be refused.',
567
+ context: { ...ready().context, unexpectedField: 'Nested field must be refused.' },
568
+ acceptanceCriteria: [{ ...ready().acceptanceCriteria[0], unexpectedField: 'Unknown criterion field.' }],
569
+ },
570
+ });
571
+ assert.equal(unknown.isError, true);
572
+ const unknownBlocks = z.array(z.object({ type: z.literal('text'), text: z.string() })).parse(unknown.content);
573
+ const unknownFailure = z
574
+ .object({
575
+ contract: z.literal('ai-delivery.issue@1'),
576
+ failures: z.array(z.object({ code: z.literal('field.unknown'), field: z.string(), fixHint: z.string() })),
577
+ })
578
+ .parse(JSON.parse(unknownBlocks[0].text));
579
+ assert.deepEqual(unknownFailure.failures.map((f) => f.field).sort(), [
580
+ 'acceptanceCriteria.0',
581
+ 'context',
582
+ 'issue',
583
+ ]);
584
+ assert.ok(unknownFailure.failures.every((f) => f.fixHint.length > 10));
585
+ assert.doesNotMatch(unknownBlocks[0].text, /unexpectedField|Nested field|Unknown criterion/u, 'Diagnostics do not echo untrusted keys or values.');
586
+ }
587
+ const foreign = await client.callTool({ name: 'issue_create', arguments: { ...ready(), repo: 'other/widget' } });
588
+ assert.equal(foreign.isError, true);
589
+ assert.match(JSON.stringify(foreign.content), /repository selectors disagree/u);
590
+ }
591
+ finally {
592
+ await client.close();
593
+ assert.equal(closeObserved, true, 'SDK spawned-child close event was actually observed');
594
+ rmSync(root, { recursive: true, force: true });
595
+ console.info(JSON.stringify({
596
+ fixture: 'issue68-compiled-stdio',
597
+ spawnedPid,
598
+ childCloseObserved: closeObserved,
599
+ syntheticRootRemoved: true,
600
+ }));
601
+ }
602
+ });
603
+ test('intake skill example is Ready and every CLI line has actual required options and an explicit identity', () => {
604
+ const skill = readFileSync(resolve('plugins/ai-delivery/skills/intake-create/SKILL.md'), 'utf8');
605
+ const json = /```json\n([\s\S]*?)\n```/u.exec(skill)?.[1];
606
+ assert.ok(json);
607
+ assert.ok(ReadyIssue.safeParse(JSON.parse(json)).success);
608
+ const root = mkdtempSync(join(tmpdir(), 'intake-cli-'));
609
+ try {
610
+ const fields = join(root, 'issue.json');
611
+ writeFileSync(fields, json);
612
+ for (const line of skill.split('\n').filter((line) => line.startsWith('ai-delivery '))) {
613
+ assert.match(line, /--identity host-author/u);
614
+ assert.match(line, /--repo example\/widget/u);
615
+ const argv = (line.match(/'[^']*'|[^\s]+/gu) ?? [])
616
+ .slice(1)
617
+ .map((token) => token.replace(/^'|'$/gu, ''))
618
+ .map((token) => token.replace('/owned/issue.json', fields));
619
+ const command = argv.find((token) => ['create', 'update', 'info', 'ready:check', 'start'].includes(token));
620
+ assert.ok(command);
621
+ assert.ok(argv.includes(command === 'create' ? '--title' : '--issue'));
622
+ const result = spawnSync(process.execPath, [resolve('dist/cli.js'), ...argv], {
623
+ cwd: root,
624
+ env: {
625
+ PATH: process.env.PATH ?? '',
626
+ HOME: root,
627
+ AI_DELIVERY_CONFIG: join(root, 'missing-config.json'),
628
+ LANG: 'en_US.UTF-8',
629
+ },
630
+ encoding: 'utf8',
631
+ });
632
+ assert.notEqual(result.status, 0);
633
+ assert.doesNotMatch(result.stderr, /unknown option|unknown command|required option/u);
634
+ assert.match(result.stderr, /missing-config|ENOENT|identity|configuration|config/iu);
635
+ }
636
+ const missing = spawnSync(process.execPath, [resolve('dist/cli.js'), '--identity', 'host-author', '--repo', 'example/widget', 'create'], { cwd: root, env: { HOME: root, PATH: process.env.PATH ?? '' }, encoding: 'utf8' });
637
+ assert.match(missing.stderr, /required option.*--title/u);
638
+ assert.ok(execFileSync(process.execPath, [resolve('dist/cli.js'), '--help'], {
639
+ env: { HOME: root, PATH: process.env.PATH ?? '' },
640
+ encoding: 'utf8',
641
+ }).includes('create'));
642
+ }
643
+ finally {
644
+ rmSync(root, { recursive: true, force: true });
645
+ }
646
+ assert.ok(skill.includes(ISSUE_BODY_MARKER));
647
+ assert.ok(!skill.includes('ai-delivery develop'));
648
+ });
649
+ //# sourceMappingURL=issueIntake.test.js.map