@aviaratech/ai-delivery 0.3.31 → 0.3.33

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 (74) hide show
  1. package/README.md +116 -3
  2. package/dist/cli.js +28 -3
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cliResult.js +10 -0
  5. package/dist/cliResult.js.map +1 -1
  6. package/dist/cliResult.test.js +61 -0
  7. package/dist/cliResult.test.js.map +1 -1
  8. package/dist/config/deliveryConfig.d.ts +36 -0
  9. package/dist/config/deliveryConfig.js +27 -2
  10. package/dist/config/deliveryConfig.js.map +1 -1
  11. package/dist/config/deliveryConfig.test.js +39 -2
  12. package/dist/config/deliveryConfig.test.js.map +1 -1
  13. package/dist/currentTrackingScenario.test.js +5 -1
  14. package/dist/currentTrackingScenario.test.js.map +1 -1
  15. package/dist/dispatch.d.ts +2 -0
  16. package/dist/dispatch.js +15 -4
  17. package/dist/dispatch.js.map +1 -1
  18. package/dist/errors.d.ts +11 -0
  19. package/dist/errors.js +35 -0
  20. package/dist/errors.js.map +1 -1
  21. package/dist/fixtures/discovery.d.ts +11 -0
  22. package/dist/fixtures/inertTarget.d.ts +5 -0
  23. package/dist/fixtures/issue63.d.ts +11 -0
  24. package/dist/fixtures/issue63.js +16 -9
  25. package/dist/fixtures/issue63.js.map +1 -1
  26. package/dist/github/client.d.ts +3 -0
  27. package/dist/github/client.js +21 -10
  28. package/dist/github/client.js.map +1 -1
  29. package/dist/github/commandIdentityPolicy.js +1 -0
  30. package/dist/github/commandIdentityPolicy.js.map +1 -1
  31. package/dist/github/machineAuth.test.js +20 -0
  32. package/dist/github/machineAuth.test.js.map +1 -1
  33. package/dist/github/projectDelivery.d.ts +3 -0
  34. package/dist/github/projectDelivery.js +44 -12
  35. package/dist/github/projectDelivery.js.map +1 -1
  36. package/dist/issue.d.ts +53 -6
  37. package/dist/issue.js +696 -58
  38. package/dist/issue.js.map +1 -1
  39. package/dist/issueBatchUpdate.test.d.ts +1 -0
  40. package/dist/issueBatchUpdate.test.js +730 -0
  41. package/dist/issueBatchUpdate.test.js.map +1 -0
  42. package/dist/issueBlockerGuard.test.js +78 -0
  43. package/dist/issueBlockerGuard.test.js.map +1 -1
  44. package/dist/issueContract.d.ts +68 -2
  45. package/dist/issueContract.js +101 -9
  46. package/dist/issueContract.js.map +1 -1
  47. package/dist/issueContract.test.d.ts +5 -0
  48. package/dist/issueContract.test.js +28 -1
  49. package/dist/issueContract.test.js.map +1 -1
  50. package/dist/issueIntake.test.js +972 -19
  51. package/dist/issueIntake.test.js.map +1 -1
  52. package/dist/issueJournal.js +12 -8
  53. package/dist/issueJournal.js.map +1 -1
  54. package/dist/issueJournal.test.js +138 -0
  55. package/dist/issueJournal.test.js.map +1 -1
  56. package/dist/mcp/index.js +20 -2
  57. package/dist/mcp/index.js.map +1 -1
  58. package/dist/mcp/tools.d.ts +104 -12
  59. package/dist/mcp/tools.js +50 -34
  60. package/dist/mcp/tools.js.map +1 -1
  61. package/dist/services/agentReadinessService.js +2 -0
  62. package/dist/services/agentReadinessService.js.map +1 -1
  63. package/dist/setup.js +65 -2
  64. package/dist/setup.js.map +1 -1
  65. package/dist/setup.test.js +857 -23
  66. package/dist/setup.test.js.map +1 -1
  67. package/dist/verification.js +42 -3
  68. package/dist/verification.js.map +1 -1
  69. package/package.json +1 -1
  70. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  71. package/plugins/ai-delivery/plugin.json +1 -1
  72. package/plugins/ai-delivery/runtime/dist/cli.js +67 -55
  73. package/plugins/ai-delivery/runtime/package.json +1 -1
  74. package/plugins/ai-delivery/skills/intake-create/SKILL.md +22 -2
@@ -5,17 +5,237 @@ import { tmpdir } from 'node:os';
5
5
  import { join, resolve } from 'node:path';
6
6
  import { afterEach, test, vi } from 'vitest';
7
7
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
8
- import { createAiDeliveryMcpServer } from './mcp/index.js';
9
8
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
10
9
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
11
10
  import { z } from 'zod';
12
- import { createIssue, updateIssue, canonicalIssueBody } from './issue.js';
11
+ import { createIssue, updateIssue, canonicalIssueBody, renderIssueHistory, readyCheck, issueInfo, listIssues, } from './issue.js';
13
12
  import { executeTool, startTrackedIssue } from './dispatch.js';
14
13
  import { digestValue } from './delivery/common.js';
15
14
  import { getAiDeliveryMcpTool } from './mcp/tools.js';
16
15
  import { IssueFields, ReadyIssue, renderIssueBody, parseIssueBody, ISSUE_BODY_MARKER } from './issueContract.js';
17
16
  import { syntheticDiscoveryConfig } from './fixtures/discovery.js';
18
- afterEach(() => vi.restoreAllMocks());
17
+ afterEach(() => {
18
+ vi.restoreAllMocks();
19
+ vi.unstubAllEnvs();
20
+ });
21
+ test('create renders all five status fields with a UTC timestamp and optional milestone', async () => {
22
+ vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-16T20:30:00Z'));
23
+ for (const draft of [false, true]) {
24
+ const f = fixture();
25
+ const input = { ...ready(), draft, status: { nextMilestone: 'Run checks' } };
26
+ const result = await createIssue(f.context, input);
27
+ const status = result.body.split('## Status\n\n')[1].split('\n\n## Problem')[0];
28
+ assert.equal(status, `- **State:** ${draft ? 'Draft' : 'Ready'}\n- **Last updated:** 2026-10-16T20:30:00.000Z UTC\n- **Next milestone:** Run checks\n- **Blockers:** None\n- **Latest journal:** None yet`);
29
+ }
30
+ const f = fixture();
31
+ assert.match((await createIssue(f.context, ready())).body, /\*\*Next milestone:\*\* Not started/u);
32
+ });
33
+ test('status-only patches preserve every outside-Status byte including canonical data and start markers', async () => {
34
+ const f = fixture();
35
+ const created = await createIssue(f.context, ready());
36
+ f.live.body =
37
+ created.body +
38
+ '\n\n<!-- ai-delivery-start-intent: sha256:' +
39
+ 'a'.repeat(64) +
40
+ ' -->\n<!-- ai-delivery-start: sha256:' +
41
+ 'b'.repeat(64) +
42
+ ' -->';
43
+ const before = f.live.body;
44
+ const patch = { issueNumber: 17, status: { nextMilestone: 'Await review', blockers: 'None' } };
45
+ const result = await updateIssue(f.context, patch);
46
+ const outside = (body) => body.replace(/(## Status\n\n)[\s\S]*?(\n\n## Problem)/u, '$1$2');
47
+ assert.match(result.body, /\*\*Next milestone:\*\* Await review/u);
48
+ assert.equal(outside(result.body), outside(before));
49
+ assert.equal((await updateIssue(f.context, patch)).body, result.body);
50
+ assert.equal(f.comments.length, 0);
51
+ });
52
+ test('legacy rendering drops only by explicit retention choice or verified history and does not grow on repeat', async () => {
53
+ const legacy = 'Retired criterion: accept every invalid identifier.\n';
54
+ for (const preserveHistory of [undefined, false, true]) {
55
+ const f = fixture();
56
+ f.live.body = renderIssueBody({ ...ready(), legacyBody: legacy });
57
+ const before = f.live.body;
58
+ const result = await updateIssue(f.context, {
59
+ issueNumber: 17,
60
+ ...(preserveHistory === undefined ? {} : { preserveHistory }),
61
+ });
62
+ const readable = result.body.split('<!-- ai-delivery:issue-data@1 ')[0];
63
+ assert.equal(readable.includes(legacy), preserveHistory === false);
64
+ assert.equal(f.comments.length, preserveHistory === false ? 0 : 1);
65
+ if (preserveHistory !== false) {
66
+ const retained = f.comments[0].body.match(/Body:\n<pre>([\s\S]*)<\/pre>/u)[1]
67
+ .replaceAll('&lt;', '<')
68
+ .replaceAll('&gt;', '>')
69
+ .replaceAll('&amp;', '&');
70
+ assert.equal(retained, before);
71
+ }
72
+ const again = await updateIssue(f.context, {
73
+ issueNumber: 17,
74
+ ...(preserveHistory === undefined ? {} : { preserveHistory }),
75
+ });
76
+ assert.equal(again.body, result.body);
77
+ assert.equal(f.comments.length, preserveHistory === false ? 0 : 1);
78
+ }
79
+ const f = fixture();
80
+ f.live.body = renderIssueBody({ ...ready(), legacyBody: legacy });
81
+ const drop = { issueNumber: 17, preserveHistory: false, retainLegacyBody: false };
82
+ const result = await updateIssue(f.context, drop);
83
+ assert.ok(!result.body.split('<!-- ai-delivery:issue-data@1 ')[0].includes(legacy));
84
+ assert.equal(f.comments.length, 0);
85
+ });
86
+ test('replacement legacy text remains visible until those incoming bytes have native history', async () => {
87
+ const f = fixture();
88
+ f.live.body = 'Original operator text.\n';
89
+ const incoming = 'New operator text that was never in the previous body.\n';
90
+ const result = await updateIssue(f.context, { issueNumber: 17, body: incoming, ...ready(), preserveHistory: true });
91
+ assert.ok(result.body.split('<!-- ai-delivery:issue-data@1 ')[0].includes(incoming));
92
+ assert.ok(!f.comments[0].body.includes(incoming));
93
+ });
94
+ test('default render omission reuses an existing exact authored history snapshot', async () => {
95
+ const f = fixture();
96
+ f.live.body = renderIssueBody({ ...ready(), legacyBody: 'Retired synthetic criterion.\n' });
97
+ const before = f.live.body;
98
+ const history = renderIssueHistory(f.live.title, before);
99
+ f.comments.push({
100
+ id: 91,
101
+ body: history,
102
+ html_url: 'https://github.com/example/widget/issues/17#issuecomment-91',
103
+ user: { login: 'operator' },
104
+ issue_url: 'https://api.github.com/repos/example/widget/issues/17',
105
+ });
106
+ const result = await updateIssue(f.context, { issueNumber: 17 });
107
+ assert.equal(result.historyComment?.reused, true);
108
+ assert.equal(f.comments.length, 1);
109
+ assert.equal(f.comments[0].body, history);
110
+ assert.ok(!result.body.split('<!-- ai-delivery:issue-data@1 ')[0].includes('Retired synthetic criterion.'));
111
+ });
112
+ test('normal-start recovery preserves legacy rendering across repeated exact retries', async () => {
113
+ const f = fixture();
114
+ f.controls.created = false;
115
+ const request = getAiDeliveryMcpTool('issue_start').inputSchema.parse({
116
+ title: ready().title,
117
+ body: renderIssueBody({ ...ready(), legacyBody: 'Original operator context.\n' }),
118
+ issueType: 'Task',
119
+ points: 2,
120
+ requestId: 'legacy-status-retry',
121
+ });
122
+ await startTrackedIssue(f.context, request);
123
+ const before = f.live.body;
124
+ for (let retry = 0; retry < 2; retry++) {
125
+ const result = await startTrackedIssue(f.context, request);
126
+ assert.ok('reused' in result && result.reused);
127
+ assert.equal(f.live.body, before);
128
+ }
129
+ assert.equal(f.writes.filter((input) => !('issue_number' in input)).length, 1);
130
+ assert.equal(f.comments.length, 1);
131
+ });
132
+ test.each([{ points: 4 }, { issueType: 'Feature' }])('normal-start retry refuses changed contract metadata %j before native writes', async (patch) => {
133
+ const f = fixture();
134
+ f.controls.created = false;
135
+ f.context.config = { ...f.context.config, native: { ...f.context.config.native, issueTypes: ['Task', 'Feature'] } };
136
+ const request = getAiDeliveryMcpTool('issue_start').inputSchema.parse({
137
+ title: ready().title,
138
+ body: renderIssueBody(ready()),
139
+ issueType: 'Task',
140
+ points: 2,
141
+ requestId: 'contract-metadata-retry',
142
+ });
143
+ await startTrackedIssue(f.context, request);
144
+ await updateIssue(f.context, { issueNumber: 17, ...patch });
145
+ const before = f.live.body;
146
+ const writes = f.writes.length;
147
+ const comments = f.comments.length;
148
+ await assert.rejects(startTrackedIssue(f.context, request), /conflicts/u);
149
+ assert.equal(f.live.body, before);
150
+ assert.equal(f.writes.length, writes);
151
+ assert.equal(f.comments.length, comments);
152
+ });
153
+ test('default legacy omission refuses drift between preparation and the history snapshot', async () => {
154
+ const f = fixture();
155
+ f.live.body = renderIssueBody({ ...ready(), legacyBody: 'Original unpreserved legacy bytes.\n' });
156
+ f.controls.driftBeforeUpdate = true;
157
+ await assert.rejects(updateIssue(f.context, { issueNumber: 17 }), /content changed/u);
158
+ assert.equal(f.live.body, 'Concurrent operator edit');
159
+ assert.equal(f.comments.length, 0);
160
+ assert.equal(f.writes.length, 0);
161
+ });
162
+ test('status-only updates preserve embedded metadata and old formatting despite different native metadata', async () => {
163
+ const f = fixture();
164
+ const data = {
165
+ ...ready(),
166
+ acceptanceCriteria: [{ behavior: 'Reject malformed input:\n- Empty input', verifiedBy: 'Regression test.' }],
167
+ };
168
+ f.live.body =
169
+ renderIssueBody(data).replace(' - Empty input\n\n Verified', '- Empty input\n Verified') +
170
+ '\n\n<!-- ai-delivery-start-intent: sha256:' +
171
+ 'a'.repeat(64) +
172
+ ' -->\n<!-- ai-delivery-start: sha256:' +
173
+ 'b'.repeat(64) +
174
+ ' -->';
175
+ f.controls.livePoints = 4;
176
+ f.live.type.name = 'Feature';
177
+ const before = f.live.body;
178
+ const patch = { issueNumber: 17, status: { nextMilestone: 'Await review' } };
179
+ const result = await updateIssue(f.context, patch);
180
+ const outside = (body) => body.replace(/(## Status\n\n)[\s\S]*?(\n\n## Problem)/u, '$1$2');
181
+ assert.equal(outside(result.body), outside(before));
182
+ assert.equal(f.controls.livePoints, 4);
183
+ assert.equal(f.live.type.name, 'Feature');
184
+ assert.equal(f.writes.length, 1);
185
+ assert.deepEqual(Object.keys(f.writes[0]).sort(), ['body', 'issue_number', 'owner', 'repo']);
186
+ });
187
+ test('status patches reject secrets, multiline and unknown fields without native writes', async () => {
188
+ for (const status of [
189
+ { nextMilestone: 'password=' + 'X'.repeat(16) },
190
+ { nextMilestone: 'Next\n## Problem' },
191
+ { unknown: 'unexpected' },
192
+ ]) {
193
+ const f = fixture();
194
+ const patch = { issueNumber: 17, status };
195
+ await assert.rejects(updateIssue(f.context, patch));
196
+ assert.equal(f.writes.length, 0);
197
+ assert.equal(f.comments.length, 0);
198
+ }
199
+ });
200
+ test('status-only patches refuse concurrent native body drift before overwriting it', async () => {
201
+ const f = fixture();
202
+ f.controls.driftBeforeUpdate = true;
203
+ const patch = { issueNumber: 17, status: { nextMilestone: 'Await review' } };
204
+ await assert.rejects(updateIssue(f.context, patch), /content changed/u);
205
+ assert.equal(f.live.body, 'Concurrent operator edit');
206
+ assert.equal(f.writes.length, 0);
207
+ });
208
+ test('CLI typed field files reach status privacy validation before configuration', () => {
209
+ const root = mkdtempSync(join(tmpdir(), 'delivery130-status-'));
210
+ try {
211
+ const file = join(root, 'fields.json');
212
+ writeFileSync(file, JSON.stringify({ ...ready(), status: { nextMilestone: 'password=' + 'X'.repeat(16) } }));
213
+ const result = spawnSync(process.execPath, [resolve('dist/cli.js'), '--repo', 'example/widget', 'create', '--title', ready().title, '--fields-file', file], { encoding: 'utf8' });
214
+ assert.notEqual(result.status, 0);
215
+ assert.match(result.stderr, /Remove credentials and private keys from public status fields/u);
216
+ assert.ok(!result.stderr.includes('X'.repeat(16)));
217
+ }
218
+ finally {
219
+ rmSync(root, { recursive: true, force: true });
220
+ }
221
+ });
222
+ test('status updates retain old multiline canonical formatting and reject ambiguous status blocks', async () => {
223
+ const f = fixture();
224
+ const data = {
225
+ ...ready(),
226
+ acceptanceCriteria: [{ behavior: 'Reject malformed input:\n- Empty input', verifiedBy: 'Regression test.' }],
227
+ };
228
+ f.live.body = renderIssueBody(data).replace(' - Empty input\n\n Verified', '- Empty input\n Verified');
229
+ const before = f.live.body.split('\n\n## Problem')[1];
230
+ const patch = { issueNumber: 17, status: { nextMilestone: '<literal> *text* [link]' } };
231
+ const result = await updateIssue(f.context, patch);
232
+ assert.equal(result.body.split('\n\n## Problem')[1], before);
233
+ assert.match(result.body, /&lt;literal&gt; \\\*text\\\* \\\[link\\\]/u);
234
+ f.live.body = result.body.replace('- **Blockers:** None', '- **Blockers:** None\n- **Blockers:** Other');
235
+ const writes = f.writes.length;
236
+ await assert.rejects(updateIssue(f.context, patch), /unambiguous status/u);
237
+ assert.equal(f.writes.length, writes);
238
+ });
19
239
  const ready = () => IssueFields.parse({
20
240
  title: 'Reject invalid widget identifiers before persistence',
21
241
  issueType: 'Task',
@@ -40,6 +260,8 @@ function fixture() {
40
260
  body: renderIssueBody(ready()),
41
261
  state: 'open',
42
262
  created_at: '2026-01-01T00:00:00Z',
263
+ updated_at: '2026-01-01T00:00:00Z',
264
+ labels: [],
43
265
  type: { name: 'Task' },
44
266
  html_url: 'https://github.com/example/widget/issues/17',
45
267
  };
@@ -50,6 +272,7 @@ function fixture() {
50
272
  ignoreBody: false,
51
273
  wrongCreateRepo: false,
52
274
  driftAfterHistory: false,
275
+ driftBeforeUpdate: false,
53
276
  created: true,
54
277
  blockers: false,
55
278
  trackingParent: false,
@@ -61,21 +284,47 @@ function fixture() {
61
284
  branchFailure: false,
62
285
  closeAfterBranch: false,
63
286
  blockAfterBranch: false,
287
+ capacityMode: false,
288
+ growAfterBranch: false,
289
+ incompleteCapacity: false,
290
+ corruptCapacityComment: false,
291
+ capacityPageSize: 0,
64
292
  };
293
+ const capacity = [];
65
294
  const branchWrites = [];
66
295
  const branches = [];
67
296
  let points = 2;
68
297
  let status = 'Queued';
69
298
  const statusWrites = [];
70
299
  const membershipWrites = [];
300
+ let issueReads = 0;
71
301
  const optionId = () => ({ Queued: 'TODO', Active: 'ACTIVE', Waiting: 'BLOCKED', Shipped: 'DONE' })[status];
72
- const values = () => [
302
+ const values = (number = 17) => [
73
303
  {
74
304
  issue_field_id: 101,
75
305
  issue_field_name: 'Estimate',
76
306
  data_type: 'single_select',
77
307
  value: String(controls.livePoints),
308
+ single_select_option: { name: String(controls.livePoints) },
78
309
  },
310
+ ...(controls.capacityMode
311
+ ? [
312
+ {
313
+ issue_field_id: 102,
314
+ issue_field_name: 'Urgency',
315
+ data_type: 'single_select',
316
+ single_select_option: {
317
+ name: number === 17 ? 'High' : (capacity.find((x) => x.number === number)?.value ?? 'Low'),
318
+ },
319
+ },
320
+ {
321
+ issue_field_id: 103,
322
+ issue_field_name: 'Tags',
323
+ data_type: 'multi_select',
324
+ multi_select_options: [{ name: '0' }],
325
+ },
326
+ ]
327
+ : []),
79
328
  ];
80
329
  const context = {
81
330
  root: '/synthetic-non-git',
@@ -105,8 +354,45 @@ function fixture() {
105
354
  rest: {
106
355
  issues: {
107
356
  listSubIssues: async () => ({ data: controls.trackingParent ? [{ number: 18 }] : [] }),
108
- get: async () => ({ data: { ...live } }),
109
- listForRepo: async () => ({ data: controls.created ? [{ ...live }] : [] }),
357
+ get: async (input) => {
358
+ if (controls.driftBeforeUpdate && ++issueReads > 1)
359
+ live.body = 'Concurrent operator edit';
360
+ if (controls.capacityMode && input.issue_number !== 17) {
361
+ const row = capacity.find((x) => x.number === input.issue_number);
362
+ return {
363
+ data: {
364
+ ...live,
365
+ number: row.number,
366
+ node_id: 'ISSUE' + String(row.number),
367
+ labels: [row.label],
368
+ html_url: 'https://github.com/example/widget/issues/' + String(row.number),
369
+ },
370
+ };
371
+ }
372
+ return { data: { ...live } };
373
+ },
374
+ listLabelsForRepo: async () => ({ data: [{ name: 'critical' }, { name: 'other' }] }),
375
+ listForRepo: async (input) => ({
376
+ headers: controls.capacityPageSize && (input.page ?? 1) === 1
377
+ ? { link: '<https://api.github.com/repos/example/widget/issues?page=2&per_page=100>; rel="next"' }
378
+ : {},
379
+ data: controls.capacityMode
380
+ ? (controls.incompleteCapacity
381
+ ? []
382
+ : [
383
+ { ...live },
384
+ ...capacity.map((x) => ({
385
+ ...live,
386
+ number: x.number,
387
+ node_id: 'ISSUE' + String(x.number),
388
+ labels: [x.label],
389
+ html_url: 'https://github.com/example/widget/issues/' + String(x.number),
390
+ })),
391
+ ]).slice(((input.page ?? 1) - 1) * (controls.capacityPageSize || input.per_page || 100), (input.page ?? 1) * (controls.capacityPageSize || input.per_page || 100))
392
+ : controls.created
393
+ ? [{ ...live }]
394
+ : [],
395
+ }),
110
396
  create: async (input) => {
111
397
  writes.push(input);
112
398
  controls.created = true;
@@ -147,7 +433,10 @@ function fixture() {
147
433
  getComment: async (input) => {
148
434
  if (controls.driftAfterHistory)
149
435
  live.body = 'Concurrent owner content';
150
- return { data: comments.find((c) => c.id === input.comment_id) };
436
+ const found = comments.find((c) => c.id === input.comment_id);
437
+ return {
438
+ data: controls.corruptCapacityComment && found ? { ...found, user: { login: 'foreign-writer' } } : found,
439
+ };
151
440
  },
152
441
  },
153
442
  repos: { get: async () => ({ data: { default_branch: 'main', node_id: 'REPOSITORY' } }) },
@@ -168,6 +457,7 @@ function fixture() {
168
457
  data_type: 'single_select',
169
458
  options: ['High', 'Low'].map((name) => ({ name })),
170
459
  },
460
+ ...(controls.capacityMode ? [{ id: 103, name: 'Tags', data_type: 'multi_select' }] : []),
171
461
  ],
172
462
  };
173
463
  if (route.startsWith('POST ')) {
@@ -177,7 +467,7 @@ function fixture() {
177
467
  return { data: values() };
178
468
  }
179
469
  if (route.startsWith('GET '))
180
- return { data: values() };
470
+ return { data: values(Number(input.issue_number ?? 17)) };
181
471
  throw new Error('Unexpected native request ' + route);
182
472
  },
183
473
  },
@@ -207,6 +497,8 @@ function fixture() {
207
497
  live.state = 'closed';
208
498
  if (controls.blockAfterBranch)
209
499
  controls.blockers = true;
500
+ if (controls.growAfterBranch)
501
+ capacity.push({ number: 99, label: 'critical', value: 'High', status: 'Active' });
210
502
  if (controls.branchFailure)
211
503
  throw new Error('Lost branch response');
212
504
  return { createLinkedBranch: { linkedBranch: { ref: { name: fields.name, target: { oid: fields.oid } } } } };
@@ -237,8 +529,20 @@ function fixture() {
237
529
  return {
238
530
  organization: {
239
531
  projectV2: {
532
+ id: 'PROJECT',
533
+ number: 1,
240
534
  items: {
241
535
  nodes: [
536
+ ...capacity.map((x) => ({
537
+ id: 'ITEM' + String(x.number),
538
+ isArchived: false,
539
+ content: { id: 'ISSUE' + String(x.number) },
540
+ fieldValueByName: x.status === 'Unset'
541
+ ? null
542
+ : x.status === 'Missing'
543
+ ? undefined
544
+ : { name: x.status, optionId: x.status === 'Active' ? 'ACTIVE' : 'TODO' },
545
+ })),
242
546
  {
243
547
  id: 'OTHER',
244
548
  isArchived: false,
@@ -280,24 +584,37 @@ function fixture() {
280
584
  throw new Error('Lost Project response');
281
585
  return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'ITEM17' } } };
282
586
  }
283
- if (query.includes('ProjectDeliveryItemReadback'))
587
+ if (query.includes('ProjectDeliveryItemReadback')) {
588
+ const number = Number(String(input.itemId).replace('ITEM', ''));
589
+ const selected = number === 17 ? status : capacity.find((x) => x.number === number)?.status;
284
590
  return {
285
591
  node: {
286
- id: 'ITEM17',
592
+ id: input.itemId,
287
593
  isArchived: false,
288
594
  project: { id: 'PROJECT', number: 1 },
289
595
  content: {
290
- id: status === 'Active' && controls.projectFailure === 'readback' ? 'OTHER-ISSUE' : 'ISSUE17',
596
+ id: status === 'Active' && controls.projectFailure === 'readback'
597
+ ? 'OTHER-ISSUE'
598
+ : 'ISSUE' + String(number),
291
599
  },
292
- fieldValueByName: { name: status, optionId: optionId() },
600
+ fieldValueByName: selected === 'Unset'
601
+ ? null
602
+ : selected === 'Missing'
603
+ ? undefined
604
+ : {
605
+ name: selected,
606
+ optionId: number === 17 ? optionId() : selected === 'Active' ? 'ACTIVE' : 'TODO',
607
+ },
293
608
  },
294
609
  };
610
+ }
295
611
  throw new Error('Unexpected native query ' + query);
296
612
  },
297
613
  },
298
614
  };
299
615
  return {
300
616
  context,
617
+ capacity,
301
618
  live,
302
619
  writes,
303
620
  comments,
@@ -312,13 +629,527 @@ function fixture() {
312
629
  },
313
630
  };
314
631
  }
632
+ test('manual deferral survives other updates and past dates, appears in reads, and blocks all start writes', async () => {
633
+ const f = fixture();
634
+ const footer = '\n\n<!-- ai-delivery-start-intent: sha256:' +
635
+ 'a'.repeat(64) +
636
+ ' -->\n<!-- ai-delivery-start: sha256:' +
637
+ 'b'.repeat(64) +
638
+ ' -->';
639
+ f.live.body += footer;
640
+ const condition = { until: '2020-01-01', trigger: 'Upstream ships the prerequisite.' };
641
+ const patch = getAiDeliveryMcpTool('issue_update').inputSchema.parse({ issueNumber: 17, defer: condition });
642
+ const deferred = await updateIssue(f.context, patch);
643
+ assert.deepEqual(Reflect.get(deferred, 'deferred'), condition);
644
+ assert.deepEqual(Reflect.get(await issueInfo(f.context, 17), 'deferred'), condition);
645
+ assert.deepEqual(Reflect.get((await listIssues(f.context, {})).issues[0], 'deferred'), condition);
646
+ const saved = parseIssueBody(deferred.body, { title: f.live.title }).issue;
647
+ assert.ok(deferred.body.endsWith(footer));
648
+ assert.deepEqual(Reflect.get(saved, 'deferral'), condition);
649
+ assert.match(deferred.body, /Deferred/u);
650
+ assert.equal((await readyCheck(f.context, 17)).ready, false);
651
+ await updateIssue(f.context, { issueNumber: 17, status: { nextMilestone: 'Wait for upstream' } });
652
+ assert.deepEqual(Reflect.get(await issueInfo(f.context, 17), 'deferred'), condition);
653
+ assert.ok(f.live.body.endsWith(footer));
654
+ const writes = f.writes.length;
655
+ const comments = f.comments.length;
656
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /deferred|undefer/iu);
657
+ assert.equal(f.branchWrites.length, 0);
658
+ assert.equal(f.statusWrites.filter((x) => x.optionId === 'ACTIVE').length, 0);
659
+ assert.equal(f.writes.length, writes);
660
+ assert.equal(f.comments.length, comments);
661
+ const clear = { issueNumber: 17, undefer: true };
662
+ const resumed = await updateIssue(f.context, clear);
663
+ assert.equal(Reflect.get(resumed, 'deferred'), null);
664
+ assert.ok(resumed.body.endsWith(footer));
665
+ assert.deepEqual(parseIssueBody(resumed.body, { title: f.live.title }).issue.acceptanceCriteria, saved.acceptanceCriteria);
666
+ assert.equal((await readyCheck(f.context, 17)).ready, true);
667
+ await startTrackedIssue(f.context, { issueNumber: 17 });
668
+ assert.equal(f.branchWrites.length, 1);
669
+ assert.equal(f.getStatus(), 'Active');
670
+ });
671
+ test('canonical new-start intent preserves supplied deferral rather than silently resuming it', async () => {
672
+ const deferred = renderIssueBody(IssueFields.parse({ ...ready(), deferral: { trigger: 'Explicit undefer' } }));
673
+ const canonical = canonicalIssueBody({ ...ready(), body: deferred });
674
+ assert.deepEqual(Reflect.get(parseIssueBody(canonical, { title: ready().title }).issue, 'deferral'), {
675
+ trigger: 'Explicit undefer',
676
+ });
677
+ const f = fixture();
678
+ f.controls.created = false;
679
+ const request = { ...ready(), body: deferred };
680
+ const first = await startTrackedIssue(f.context, request);
681
+ assert.equal(Reflect.get(first, 'status'), 'created-not-started');
682
+ assert.deepEqual(Reflect.get(parseIssueBody(f.live.body, { title: f.live.title }).issue, 'deferral'), {
683
+ trigger: 'Explicit undefer',
684
+ });
685
+ await startTrackedIssue(f.context, request);
686
+ assert.equal(f.writes.filter((write) => !Object.hasOwn(write, 'issue_number')).length, 1);
687
+ assert.equal(f.branchWrites.length, 0);
688
+ });
689
+ test('WIP partial Project acknowledgment preserves the exact reason and reuses its authored comment', async () => {
690
+ const f = fixture();
691
+ f.controls.capacityMode = true;
692
+ f.live.labels = ['critical'];
693
+ f.context.config = {
694
+ ...f.context.config,
695
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 0 }],
696
+ };
697
+ f.controls.projectFailure = 'after';
698
+ const result = await startTrackedIssue(f.context, {
699
+ issueNumber: 17,
700
+ overrideReason: 'Approved synthetic exception.',
701
+ });
702
+ assert.equal(Reflect.get(result, 'status'), 'start-incomplete');
703
+ const recovery = result;
704
+ assert.ok(recovery.safeResume);
705
+ const resume = recovery.safeResume.arguments;
706
+ assert.equal(resume.overrideReason, 'Approved synthetic exception.');
707
+ assert.equal(f.comments.length, 1);
708
+ f.controls.projectFailure = '';
709
+ await startTrackedIssue(f.context, resume);
710
+ assert.equal(f.branchWrites.length, 1);
711
+ assert.equal(f.statusWrites.length, 1);
712
+ assert.equal(f.comments.length, 2);
713
+ });
714
+ test('deferral remains orthogonal to park and only explicit undefer clears it', async () => {
715
+ const f = fixture();
716
+ const patch = { issueNumber: 17, defer: {} };
717
+ await updateIssue(f.context, patch);
718
+ const parked = await updateIssue(f.context, { issueNumber: 17, park: true });
719
+ assert.deepEqual(Reflect.get(parked, 'deferred'), {});
720
+ assert.equal(parseIssueBody(parked.body, { title: parked.title }).issue.draft, true);
721
+ const clear = { issueNumber: 17, undefer: true };
722
+ const cleared = await updateIssue(f.context, clear);
723
+ assert.equal(Reflect.get(cleared, 'deferred'), null);
724
+ assert.equal(parseIssueBody(cleared.body, { title: cleared.title }).issue.draft, true);
725
+ assert.equal((await readyCheck(f.context, 17)).ready, false);
726
+ });
727
+ test('deferral inputs reject invalid dates, empty reasons, conflicts and direct canonical bypass before writes', async () => {
728
+ const schema = getAiDeliveryMcpTool('issue_update').inputSchema;
729
+ assert.doesNotThrow(() => schema.parse({ issueNumber: 17, defer: { until: '2026-10-17' } }));
730
+ for (const input of [
731
+ { defer: { until: '2026-02-30' } },
732
+ { defer: { until: 'tomorrow' } },
733
+ { defer: { trigger: ' ' } },
734
+ { defer: {}, undefer: true },
735
+ { deferral: {} },
736
+ { undefer: false },
737
+ ])
738
+ assert.throws(() => schema.parse({ issueNumber: 17, ...input }));
739
+ const f = fixture();
740
+ const conflicting = { issueNumber: 17, defer: {}, undefer: true };
741
+ await assert.rejects(updateIssue(f.context, conflicting));
742
+ assert.equal(f.writes.length, 0);
743
+ assert.equal(f.comments.length, 0);
744
+ });
745
+ test('WIP label and field lanes reject full capacity before creating a branch or journal', async () => {
746
+ for (const match of [{ label: 'critical' }, { field: 'Urgency', value: 'High' }]) {
747
+ const f = fixture();
748
+ f.controls.capacityMode = true;
749
+ f.live.labels = ['critical'];
750
+ f.context.config = {
751
+ ...f.context.config,
752
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match, limit: 1 }],
753
+ };
754
+ f.capacity.push({ number: 18, label: 'critical', value: 'High', status: 'Active' });
755
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /WIP|capacity|limit/u);
756
+ assert.equal(f.branchWrites.length, 0);
757
+ assert.equal(f.statusWrites.length, 0);
758
+ assert.equal(f.comments.length, 0);
759
+ }
760
+ });
761
+ test('WIP rechecks after branch creation, retains that identity, and only admits a recorded capacity override', async () => {
762
+ const f = fixture();
763
+ f.controls.capacityMode = true;
764
+ f.controls.growAfterBranch = true;
765
+ f.live.labels = ['critical'];
766
+ f.context.config = {
767
+ ...f.context.config,
768
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 1 }],
769
+ };
770
+ const refused = await startTrackedIssue(f.context, { issueNumber: 17 });
771
+ assert.equal(Reflect.get(refused, 'status'), 'start-incomplete');
772
+ assert.equal(f.branchWrites.length, 1);
773
+ assert.equal(f.statusWrites.length, 0);
774
+ assert.equal(f.comments.length, 0);
775
+ f.controls.growAfterBranch = false;
776
+ await startTrackedIssue(f.context, {
777
+ issueNumber: 17,
778
+ overrideReason: 'Operator authorizes this synthetic capacity exception.',
779
+ });
780
+ assert.equal(f.branchWrites.length, 1);
781
+ assert.equal(f.getStatus(), 'Active');
782
+ assert.equal(f.comments.length, 2);
783
+ assert.match(f.comments[0].body, /Operator authorizes this synthetic capacity exception/u);
784
+ assert.match(f.comments[0].body, /"count": 1/u);
785
+ assert.match(f.comments[0].body, /"limit": 1/u);
786
+ await startTrackedIssue(f.context, { issueNumber: 17 });
787
+ assert.equal(f.comments.length, 2);
788
+ });
789
+ test('WIP capacity override refuses a mismatched native comment author and reconciles lost comment responses', async () => {
790
+ for (const failure of ['author', 'response']) {
791
+ const f = fixture();
792
+ f.controls.capacityMode = true;
793
+ f.live.labels = ['critical'];
794
+ f.context.config = {
795
+ ...f.context.config,
796
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 0 }],
797
+ };
798
+ f.controls.corruptCapacityComment = failure === 'author';
799
+ f.controls.journalFailure = failure === 'response';
800
+ const input = { issueNumber: 17, overrideReason: 'Explicit synthetic capacity authorization.' };
801
+ const refused = await startTrackedIssue(f.context, input);
802
+ assert.equal(Reflect.get(refused, 'status'), 'start-incomplete');
803
+ assert.equal(f.getStatus(), 'Queued');
804
+ assert.equal(f.statusWrites.length, 0);
805
+ assert.equal(f.comments.length, 1);
806
+ f.controls.corruptCapacityComment = false;
807
+ f.controls.journalFailure = false;
808
+ await startTrackedIssue(f.context, input);
809
+ assert.equal(f.getStatus(), 'Active');
810
+ assert.equal(f.comments.length, 2);
811
+ assert.equal(f.branchWrites.length, 1);
812
+ }
813
+ });
814
+ test.each(['edited', 'exact-and-edited'])('WIP override retry refuses %s authored evidence with the same operation marker', async (mode) => {
815
+ const f = fixture();
816
+ f.controls.capacityMode = true;
817
+ f.live.labels = ['critical'];
818
+ f.context.config = {
819
+ ...f.context.config,
820
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 0 }],
821
+ };
822
+ f.controls.journalFailure = true;
823
+ const input = { issueNumber: 17, overrideReason: 'Explicit synthetic capacity authorization.' };
824
+ assert.equal(Reflect.get(await startTrackedIssue(f.context, input), 'status'), 'start-incomplete');
825
+ assert.equal(f.comments.length, 1);
826
+ const original = f.comments[0];
827
+ const edited = original.body.replace('WIP capacity override.', 'Edited capacity override.');
828
+ if (mode === 'edited')
829
+ original.body = edited;
830
+ else
831
+ f.comments.push({
832
+ ...original,
833
+ id: 92,
834
+ html_url: 'https://github.com/example/widget/issues/17#issuecomment-92',
835
+ body: edited,
836
+ });
837
+ const before = structuredClone(f.comments);
838
+ f.controls.journalFailure = false;
839
+ const result = await startTrackedIssue(f.context, input);
840
+ assert.equal(Reflect.get(result, 'status'), 'start-incomplete');
841
+ assert.match(Reflect.get(result, 'failure').message, /conflict|duplicate|override/iu);
842
+ assert.deepEqual(f.comments, before);
843
+ assert.equal(f.branchWrites.length, 1);
844
+ assert.equal(f.statusWrites.length, 0);
845
+ assert.equal(f.getStatus(), 'Queued');
846
+ });
847
+ test.each(['text', 'number', 'date', 'single_select', 'multi_select'].flatMap((type) => [17, 18].map((number) => ({ type, number }))))('WIP refuses omitted $type payload on issue $number even with an override reason', async ({ type, number }) => {
848
+ const f = fixture();
849
+ f.controls.capacityMode = true;
850
+ f.capacity.push({ number: 18, label: 'other', value: 'High', status: 'Active' });
851
+ const value = type === 'number' ? 1 : type === 'date' ? '2026-10-17' : 'High';
852
+ f.context.config = {
853
+ ...f.context.config,
854
+ wipLimits: [{ repository: 'example/widget', name: 'Urgent work', match: { field: 'Urgency', value }, limit: 1 }],
855
+ };
856
+ let capacityReadStarted = false;
857
+ const list = f.context.clients.rest.issues.listForRepo;
858
+ f.context.clients.rest.issues.listForRepo = (async (input) => {
859
+ capacityReadStarted = true;
860
+ return list(input);
861
+ });
862
+ const request = f.context.clients.rest.request;
863
+ f.context.clients.rest.request = (async (route, input) => {
864
+ const response = await request(route, input);
865
+ if (!capacityReadStarted || typeof route !== 'string' || !route.startsWith('GET '))
866
+ return response;
867
+ const rows = z.array(z.record(z.string(), z.unknown())).parse(response.data);
868
+ const catalog = route === 'GET /orgs/{org}/issue-fields';
869
+ return {
870
+ ...response,
871
+ data: rows.map((row) => {
872
+ if ((catalog ? row.id : row.issue_field_id) !== 102)
873
+ return row;
874
+ if (catalog)
875
+ return { ...row, data_type: type };
876
+ return {
877
+ issue_field_id: 102,
878
+ issue_field_name: 'Urgency',
879
+ data_type: type,
880
+ ...(input?.issue_number === number
881
+ ? {}
882
+ : type === 'single_select'
883
+ ? { single_select_option: { name: value } }
884
+ : type === 'multi_select'
885
+ ? { multi_select_options: [{ name: value }] }
886
+ : { value }),
887
+ };
888
+ }),
889
+ };
890
+ });
891
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17, overrideReason: 'Capacity cannot override missing evidence.' }), /capacity|payload|field/iu);
892
+ assert.equal(f.branchWrites.length, 0);
893
+ assert.equal(f.statusWrites.length, 0);
894
+ assert.equal(f.membershipWrites.length, 0);
895
+ assert.equal(f.comments.length, 0);
896
+ });
897
+ test.each(['absent', 'null', 'empty-multi'])('WIP accepts complete native %s peer values as nonmatching', async (mode) => {
898
+ const f = fixture();
899
+ f.controls.capacityMode = true;
900
+ f.capacity.push({ number: 18, label: 'other', value: 'High', status: 'Active' });
901
+ const multi = mode === 'empty-multi';
902
+ f.context.config = {
903
+ ...f.context.config,
904
+ wipLimits: [
905
+ {
906
+ repository: 'example/widget',
907
+ name: 'Urgent work',
908
+ match: { field: multi ? 'Tags' : 'Urgency', value: multi ? '0' : 'High' },
909
+ limit: 1,
910
+ },
911
+ ],
912
+ };
913
+ const request = f.context.clients.rest.request;
914
+ f.context.clients.rest.request = (async (route, input) => {
915
+ const response = await request(route, input);
916
+ if (typeof route !== 'string' || !route.endsWith('/issue-field-values') || input?.issue_number !== 18)
917
+ return response;
918
+ const rows = z.array(z.record(z.string(), z.unknown())).parse(response.data);
919
+ return {
920
+ ...response,
921
+ data: rows.flatMap((row) => row.issue_field_id !== (multi ? 103 : 102)
922
+ ? [row]
923
+ : mode === 'absent'
924
+ ? []
925
+ : [
926
+ {
927
+ issue_field_id: row.issue_field_id,
928
+ issue_field_name: row.issue_field_name,
929
+ data_type: row.data_type,
930
+ ...(multi ? { multi_select_options: [] } : { value: null }),
931
+ },
932
+ ]),
933
+ };
934
+ });
935
+ await startTrackedIssue(f.context, { issueNumber: 17 });
936
+ assert.equal(f.getStatus(), 'Active');
937
+ assert.equal(f.branchWrites.length, 1);
938
+ assert.equal(f.comments.length, 1);
939
+ });
940
+ test('WIP missing target and unknown native field evidence refuse rather than counting zero', async () => {
941
+ for (const failure of ['target', 'field']) {
942
+ const f = fixture();
943
+ f.controls.capacityMode = true;
944
+ f.controls.incompleteCapacity = failure === 'target';
945
+ f.context.config = {
946
+ ...f.context.config,
947
+ wipLimits: [
948
+ {
949
+ repository: 'example/widget',
950
+ name: 'Urgent work',
951
+ match: { field: failure === 'field' ? 'Nonexistent lane field' : 'Urgency', value: 'High' },
952
+ limit: 2,
953
+ },
954
+ ],
955
+ };
956
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17, overrideReason: 'Cannot authorize missing evidence.' }), /capacity|field|target|WIP/iu);
957
+ assert.equal(f.branchWrites.length, 0);
958
+ assert.equal(f.comments.length, 0);
959
+ }
960
+ });
961
+ test('WIP follows native continuation evidence even when a page is short', async () => {
962
+ const f = fixture();
963
+ f.controls.capacityMode = true;
964
+ f.controls.capacityPageSize = 1;
965
+ f.live.labels = ['critical'];
966
+ f.context.config = {
967
+ ...f.context.config,
968
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 1 }],
969
+ };
970
+ f.capacity.push({ number: 18, label: 'critical', value: 'High', status: 'Active' });
971
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /WIP capacity limit/u);
972
+ assert.equal(f.branchWrites.length, 0);
973
+ });
974
+ test('WIP rejects malformed continuation remnants instead of treating a short page as complete', async () => {
975
+ const f = fixture();
976
+ f.controls.capacityMode = true;
977
+ f.controls.capacityPageSize = 1;
978
+ f.live.labels = ['critical'];
979
+ f.context.config = {
980
+ ...f.context.config,
981
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 1 }],
982
+ };
983
+ f.capacity.push({ number: 18, label: 'critical', value: 'High', status: 'Active' });
984
+ const list = f.context.clients.rest.issues.listForRepo;
985
+ f.context.clients.rest.issues.listForRepo = (async (input) => ({
986
+ ...(await list(input)),
987
+ headers: {
988
+ link: '<https://api.github.com/repos/example/widget/issues?page=1&per_page=100>; rel="prev", broken next continuation',
989
+ },
990
+ }));
991
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /capacity.*pagination/iu);
992
+ assert.equal(f.branchWrites.length, 0);
993
+ });
994
+ test('WIP rejects a native page larger than its requested window', async () => {
995
+ const f = fixture();
996
+ f.controls.capacityMode = true;
997
+ f.live.labels = ['critical'];
998
+ f.context.config = {
999
+ ...f.context.config,
1000
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 1 }],
1001
+ };
1002
+ const list = f.context.clients.rest.issues.listForRepo;
1003
+ f.context.clients.rest.issues.listForRepo = (async (input) => ({
1004
+ headers: {},
1005
+ data: [
1006
+ ...(await list(input)).data,
1007
+ ...Array.from({ length: 100 }, (_, index) => ({ number: 1000 + index, pull_request: {} })),
1008
+ ],
1009
+ }));
1010
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /WIP capacity pagination/u);
1011
+ assert.equal(f.branchWrites.length, 0);
1012
+ });
1013
+ test('WIP evaluates every matching lane and capacity overrides cannot resume a deferred or blocked issue', async () => {
1014
+ const f = fixture();
1015
+ f.controls.capacityMode = true;
1016
+ f.live.labels = ['critical'];
1017
+ f.context.config = {
1018
+ ...f.context.config,
1019
+ wipLimits: [
1020
+ { repository: 'example/widget', name: 'Labels allow', match: { label: 'critical' }, limit: 1 },
1021
+ { repository: 'example/widget', name: 'Field is full', match: { field: 'Urgency', value: 'High' }, limit: 1 },
1022
+ ],
1023
+ };
1024
+ f.capacity.push({ number: 18, label: 'other', value: 'High', status: 'Active' });
1025
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /Field is full/u);
1026
+ const deferred = { issueNumber: 17, defer: { trigger: 'Manual approval' } };
1027
+ await updateIssue(f.context, deferred);
1028
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17, overrideReason: 'Capacity only.' }), /deferred/u);
1029
+ await updateIssue(f.context, { issueNumber: 17, undefer: true });
1030
+ f.controls.blockers = true;
1031
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17, overrideReason: 'Capacity only.' }), /blocked/u);
1032
+ assert.equal(f.branchWrites.length, 0);
1033
+ assert.equal(f.comments.length, 0);
1034
+ });
1035
+ test('WIP distinguishes an explicitly unset native Status from omitted Status evidence', async () => {
1036
+ for (const status of ['Unset', 'Missing']) {
1037
+ const f = fixture();
1038
+ f.controls.capacityMode = true;
1039
+ f.live.labels = ['critical'];
1040
+ f.context.config = {
1041
+ ...f.context.config,
1042
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 1 }],
1043
+ };
1044
+ f.capacity.push({ number: 18, label: 'critical', value: 'High', status });
1045
+ if (status === 'Unset') {
1046
+ await startTrackedIssue(f.context, { issueNumber: 17 });
1047
+ assert.equal(f.getStatus(), 'Active');
1048
+ }
1049
+ else {
1050
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /WIP|capacity/u);
1051
+ assert.equal(f.branchWrites.length, 0);
1052
+ }
1053
+ }
1054
+ });
1055
+ test('WIP evaluates distinct lanes using case aliases of the same native label', async () => {
1056
+ const f = fixture();
1057
+ f.controls.capacityMode = true;
1058
+ f.live.labels = ['critical'];
1059
+ f.context.config = {
1060
+ ...f.context.config,
1061
+ wipLimits: [
1062
+ { repository: 'example/widget', name: 'Available', match: { label: 'critical' }, limit: 1 },
1063
+ { repository: 'EXAMPLE/WIDGET', name: 'Hold lane', match: { label: 'CRITICAL' }, limit: 0 },
1064
+ ],
1065
+ };
1066
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /Hold lane/u);
1067
+ assert.equal(f.branchWrites.length, 0);
1068
+ });
1069
+ test('WIP field matching preserves value types for multi-select member names', async () => {
1070
+ for (const value of [0, ' 0 ', '0']) {
1071
+ const f = fixture();
1072
+ f.controls.capacityMode = true;
1073
+ f.context.config = {
1074
+ ...f.context.config,
1075
+ wipLimits: [{ repository: 'example/widget', name: 'Tagged work', match: { field: 'Tags', value }, limit: 0 }],
1076
+ };
1077
+ if (typeof value === 'number' || value === ' 0 ') {
1078
+ await startTrackedIssue(f.context, { issueNumber: 17 });
1079
+ assert.equal(f.getStatus(), 'Active');
1080
+ }
1081
+ else {
1082
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17 }), /Tagged work/u);
1083
+ assert.equal(f.branchWrites.length, 0);
1084
+ }
1085
+ }
1086
+ });
1087
+ test.each(['project', 'pagination', 'status', 'archive', 'unreadable'])('WIP refuses changed or incomplete native %s evidence after healthy readiness', async (failure) => {
1088
+ const f = fixture();
1089
+ f.controls.capacityMode = true;
1090
+ f.live.labels = ['critical'];
1091
+ f.context.config = {
1092
+ ...f.context.config,
1093
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 1 }],
1094
+ };
1095
+ const graphql = f.context.clients.graphql;
1096
+ let projectReads = 0;
1097
+ f.context.clients.graphql = (async (query, variables) => {
1098
+ const value = await graphql(query, variables);
1099
+ if (query.includes('ProjectDeliveryItems') && ++projectReads > 1) {
1100
+ const project = value.organization.projectV2;
1101
+ if (failure === 'project')
1102
+ project.id = 'FOREIGN';
1103
+ if (failure === 'pagination')
1104
+ delete project.items.pageInfo.hasNextPage;
1105
+ if (failure === 'status')
1106
+ delete project.items.nodes[0].fieldValueByName;
1107
+ if (failure === 'archive')
1108
+ delete project.items.nodes[0].isArchived;
1109
+ if (failure === 'unreadable')
1110
+ project.items.nodes.push({ id: 'UNKNOWN', isArchived: false, content: null, fieldValueByName: null });
1111
+ }
1112
+ return value;
1113
+ });
1114
+ await assert.rejects(startTrackedIssue(f.context, { issueNumber: 17, overrideReason: 'Capacity only.' }), /WIP|capacity/u);
1115
+ assert.equal(f.branchWrites.length, 0);
1116
+ assert.equal(f.comments.length, 0);
1117
+ });
1118
+ test('WIP refuses observation drift after recording an override and preserves that attempt for reconciliation', async () => {
1119
+ const f = fixture();
1120
+ f.controls.capacityMode = true;
1121
+ f.live.labels = ['critical'];
1122
+ f.context.config = {
1123
+ ...f.context.config,
1124
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 0 }],
1125
+ };
1126
+ const createComment = f.context.clients.rest.issues.createComment;
1127
+ let drift = true;
1128
+ f.context.clients.rest.issues.createComment = (async (input) => {
1129
+ const result = await createComment(input);
1130
+ if (drift) {
1131
+ drift = false;
1132
+ f.capacity.push({ number: 18, label: 'critical', value: 'High', status: 'Active' });
1133
+ }
1134
+ return result;
1135
+ });
1136
+ const input = { issueNumber: 17, overrideReason: 'Explicit synthetic capacity exception.' };
1137
+ const result = await startTrackedIssue(f.context, input);
1138
+ assert.match(Reflect.get(result, 'failure').message, /capacity changed/u);
1139
+ assert.equal(f.getStatus(), 'Queued');
1140
+ assert.equal(f.comments.length, 1);
1141
+ await startTrackedIssue(f.context, input);
1142
+ assert.equal(f.getStatus(), 'Active');
1143
+ assert.equal(f.comments.length, 3, 'two distinct native capacity observations and one start journal');
1144
+ assert.equal(f.branchWrites.length, 1);
1145
+ });
315
1146
  test('native create validates first, writes canonical fields, reads back metadata and returns warnings', async () => {
316
1147
  const f = fixture();
317
1148
  await assert.rejects(createIssue(f.context, { ...ready(), openQuestions: ['Select behavior.'] }), /open-questions/u);
318
1149
  assert.equal(f.writes.length, 0);
319
1150
  const result = await createIssue(f.context, ready());
320
1151
  assert.equal(f.writes.length, 1);
321
- assert.equal(result.body, renderIssueBody(ready()));
1152
+ assert.equal(canonicalIssueBody({ ...ready(), body: result.body }), renderIssueBody(ready()));
322
1153
  assert.equal(parseIssueBody(result.body, { title: result.created.title }).issue.points, 2);
323
1154
  assert.deepEqual(result.warnings, []);
324
1155
  assert.equal(f.getStatus(), 'Queued');
@@ -327,7 +1158,7 @@ test('incomplete drafts write parked; reviewer-role writes and wrong native repo
327
1158
  const f = fixture();
328
1159
  await createIssue(f.context, { title: 'Investigate invalid widget identifiers', draft: true });
329
1160
  assert.equal(f.getStatus(), 'Queued');
330
- assert.match(f.live.body, /Draft — parked/u);
1161
+ assert.match(f.live.body, /\*\*State:\*\* Draft/u);
331
1162
  f.controls.role = 'reviewer';
332
1163
  await assert.rejects(createIssue(f.context, ready()), /author role/u);
333
1164
  await assert.rejects(updateIssue(f.context, { issueNumber: 17, draft: true }), /author role/u);
@@ -375,7 +1206,7 @@ test('legacy replacement updates preserve the actual previous body and diff for
375
1206
  outcome: 'Reject invalid input before persistence.',
376
1207
  });
377
1208
  assert.equal(patch.conversion, undefined);
378
- assert.equal(f.comments.length, 1);
1209
+ assert.equal(f.comments.length, replacement.startsWith(ISSUE_BODY_MARKER) ? 1 : 2);
379
1210
  assert.equal(parseIssueBody(patch.body, { title: patch.title }).issue.legacyBody, preserved);
380
1211
  }
381
1212
  });
@@ -409,10 +1240,11 @@ test('normal-start canonical retry body keeps exact intent markers through creat
409
1240
  points: 2,
410
1241
  issueType: 'Task',
411
1242
  });
412
- assert.equal(result.body, canonical + footer);
1243
+ assert.equal(canonicalIssueBody({ ...issue, body: result.body }), canonical + footer);
413
1244
  assert.deepEqual(parseIssueBody(result.body, { title: issue.title }).issue, issue);
414
1245
  });
415
1246
  test('actual normal-start creation and retry reuse the exact canonical body, branch and authored journal', async () => {
1247
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-16T20:30:00Z'));
416
1248
  const f = fixture();
417
1249
  f.controls.created = false;
418
1250
  const request = getAiDeliveryMcpTool('issue_start').inputSchema.parse({
@@ -433,6 +1265,7 @@ test('actual normal-start creation and retry reuse the exact canonical body, bra
433
1265
  assert.equal(f.branchWrites.length, 1);
434
1266
  assert.equal(f.branchWrites[0]?.clientMutationId, digestValue({ repository: 'example/widget', issueNumber: 17, name: 'issue/17', base: 'a'.repeat(40) }));
435
1267
  assert.equal(f.comments.length, 1);
1268
+ clock.mockReturnValue(Date.parse('2026-10-17T20:30:00Z'));
436
1269
  const retry = await startTrackedIssue(f.context, request);
437
1270
  assert.ok('reused' in retry && retry.reused === true);
438
1271
  assert.equal(retry.issueNumber, 17);
@@ -847,6 +1680,7 @@ test.each(['closeAfterBranch', 'blockAfterBranch'])('start rechecks live eligibi
847
1680
  assert.equal(f.comments.length, 0);
848
1681
  });
849
1682
  async function bindStartFixture(f) {
1683
+ vi.stubEnv('AI_DELIVERY_CONFIG', '/synthetic-unconfigured-delivery-settings.json');
850
1684
  const settings = await import('./config/deliveryConfig.js');
851
1685
  const issues = await import('./issue.js');
852
1686
  vi.spyOn(settings, 'loadDeliverySettings').mockResolvedValue({
@@ -854,11 +1688,63 @@ async function bindStartFixture(f) {
854
1688
  });
855
1689
  vi.spyOn(issues, 'loadDeliveryContext').mockResolvedValue(f.context);
856
1690
  }
1691
+ test.each(['flags', 'file', 'undefer'])('CLI update %s changes explicit deferral through current dispatch', async (mode) => {
1692
+ vi.resetModules();
1693
+ const f = fixture();
1694
+ if (mode === 'undefer')
1695
+ f.live.body = renderIssueBody(IssueFields.parse({ ...ready(), deferral: { trigger: 'Prior condition' } }));
1696
+ await bindStartFixture(f);
1697
+ const root = mkdtempSync(join(tmpdir(), 'deferral-cli-'));
1698
+ const fieldsFile = join(root, 'patch.json');
1699
+ const condition = { until: '2020-01-01', trigger: 'CLI upstream condition' };
1700
+ writeFileSync(fieldsFile, JSON.stringify({ defer: condition }));
1701
+ const argv = process.argv;
1702
+ const exitCode = process.exitCode;
1703
+ let stdout = '';
1704
+ let complete = () => { };
1705
+ const output = new Promise((resolve) => {
1706
+ complete = resolve;
1707
+ });
1708
+ vi.spyOn(process.stdout, 'write').mockImplementation((value) => {
1709
+ stdout += String(value);
1710
+ if (String(value).startsWith('{'))
1711
+ complete();
1712
+ return true;
1713
+ });
1714
+ try {
1715
+ process.exitCode = undefined;
1716
+ process.argv = [
1717
+ process.execPath,
1718
+ 'ai-delivery',
1719
+ '--repo',
1720
+ 'example/widget',
1721
+ 'update',
1722
+ '--issue',
1723
+ '17',
1724
+ ...(mode === 'undefer'
1725
+ ? ['--undefer']
1726
+ : mode === 'file'
1727
+ ? ['--fields-file', fieldsFile]
1728
+ : ['--defer-until', condition.until, '--defer-trigger', condition.trigger]),
1729
+ ];
1730
+ await import('./cli.js');
1731
+ await output;
1732
+ const result = z.object({ deferred: z.record(z.string(), z.string()).nullable() }).parse(JSON.parse(stdout));
1733
+ assert.deepEqual(result.deferred, mode === 'undefer' ? null : condition);
1734
+ assert.equal(f.writes.length, 1);
1735
+ assert.equal(process.exitCode, undefined);
1736
+ }
1737
+ finally {
1738
+ process.argv = argv;
1739
+ process.exitCode = exitCode;
1740
+ rmSync(root, { recursive: true, force: true });
1741
+ }
1742
+ });
857
1743
  test('MCP explicit start returns Project recovery and reuses the exact branch on retry', async () => {
858
1744
  const f = fixture();
859
1745
  await bindStartFixture(f);
860
1746
  f.controls.projectFailure = 'after';
861
- const server = createAiDeliveryMcpServer({ repoRoot: '/unrelated' });
1747
+ const server = (await import('./mcp/index.js')).createAiDeliveryMcpServer({ repoRoot: '/unrelated' });
862
1748
  const client = new Client({ name: 'fictional-start-project', version: '1.0.0' });
863
1749
  const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
864
1750
  try {
@@ -888,15 +1774,68 @@ test('MCP explicit start returns Project recovery and reuses the exact branch on
888
1774
  await server.close();
889
1775
  }
890
1776
  });
891
- test.each(['success', 'failure'])('CLI explicit start shares Project transition and %s output', async (mode) => {
1777
+ test('current MCP update/read/list/start routes enforce deferral and recorded WIP capacity override', async () => {
1778
+ const f = fixture();
1779
+ await bindStartFixture(f);
1780
+ const server = (await import('./mcp/index.js')).createAiDeliveryMcpServer({ repoRoot: '/unrelated' });
1781
+ const client = new Client({ name: 'synthetic-deferral-wip', version: '1.0.0' });
1782
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
1783
+ const call = async (name, args, error = false) => {
1784
+ const result = await client.callTool({ name, arguments: { repo: 'example/widget', ...args } });
1785
+ assert.equal(Boolean(result.isError), error, JSON.stringify(result.content));
1786
+ const content = result.content;
1787
+ const value = error ? content[0].text : JSON.parse(content[0].text);
1788
+ return value;
1789
+ };
1790
+ try {
1791
+ await server.connect(serverTransport);
1792
+ await client.connect(clientTransport);
1793
+ const condition = { until: '2020-01-01', trigger: 'Upstream ships' };
1794
+ const readback = z.object({ deferred: z.record(z.string(), z.string()).nullable() });
1795
+ assert.deepEqual(readback.parse(await call('issue_update', { issueNumber: 17, defer: condition })).deferred, condition);
1796
+ assert.deepEqual(readback.parse(await call('issue_info', { issueNumber: 17 })).deferred, condition);
1797
+ assert.deepEqual(z.object({ issues: z.array(readback) }).parse(await call('issue_list', {})).issues[0].deferred, condition);
1798
+ assert.match(z.string().parse(await call('issue_start', { issueNumber: 17, overrideReason: 'Capacity only.' }, true)), /deferred/u);
1799
+ await call('issue_update', { issueNumber: 17, undefer: true });
1800
+ f.controls.capacityMode = true;
1801
+ f.live.labels = ['critical'];
1802
+ f.context.config = {
1803
+ ...f.context.config,
1804
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 0 }],
1805
+ };
1806
+ assert.match(z.string().parse(await call('issue_start', { issueNumber: 17 }, true)), /WIP/u);
1807
+ assert.equal(f.branchWrites.length, 0);
1808
+ await call('issue_start', { issueNumber: 17, overrideReason: 'Explicit synthetic capacity exception.' });
1809
+ assert.equal(f.getStatus(), 'Active');
1810
+ assert.equal(f.comments.length, 2);
1811
+ await call('issue_start', { issueNumber: 17 });
1812
+ assert.equal(f.comments.length, 2);
1813
+ }
1814
+ finally {
1815
+ await client.close();
1816
+ await server.close();
1817
+ }
1818
+ });
1819
+ test.each(['success', 'failure', 'capacity', 'deferred', 'capacity-override'])('CLI explicit start shares Project transition and %s output', async (mode) => {
892
1820
  vi.resetModules();
893
1821
  const f = fixture();
894
1822
  await bindStartFixture(f);
895
1823
  if (mode === 'failure')
896
1824
  f.controls.projectFailure = 'before';
1825
+ if (mode === 'deferred')
1826
+ await updateIssue(f.context, { issueNumber: 17, defer: {} });
1827
+ if (mode === 'capacity' || mode === 'capacity-override') {
1828
+ f.controls.capacityMode = true;
1829
+ f.live.labels = ['critical'];
1830
+ f.context.config = {
1831
+ ...f.context.config,
1832
+ wipLimits: [{ repository: 'example/widget', name: 'Critical work', match: { label: 'critical' }, limit: 0 }],
1833
+ };
1834
+ }
897
1835
  const argv = process.argv;
898
1836
  const exitCode = process.exitCode;
899
1837
  let stdout = '';
1838
+ let stderr = '';
900
1839
  let completed = () => { };
901
1840
  const output = new Promise((resolve) => {
902
1841
  completed = resolve;
@@ -907,11 +1846,25 @@ test.each(['success', 'failure'])('CLI explicit start shares Project transition
907
1846
  completed();
908
1847
  return true;
909
1848
  });
1849
+ vi.spyOn(process.stderr, 'write').mockImplementation((value) => {
1850
+ stderr += String(value);
1851
+ completed();
1852
+ return true;
1853
+ });
910
1854
  try {
911
1855
  process.exitCode = undefined;
912
1856
  process.argv = [process.execPath, 'ai-delivery', '--repo', 'example/widget', 'start', '--issue', '17'];
1857
+ if (mode === 'capacity-override')
1858
+ process.argv.push('--override-reason', 'Explicit synthetic capacity exception.');
913
1859
  await import('./cli.js');
914
1860
  await output;
1861
+ if (mode === 'deferred' || mode === 'capacity') {
1862
+ assert.match(stderr, mode === 'deferred' ? /deferred/u : /WIP/u);
1863
+ assert.equal(process.exitCode, 1);
1864
+ assert.equal(f.branchWrites.length, 0);
1865
+ assert.equal(f.statusWrites.filter((x) => x.optionId === 'ACTIVE').length, 0);
1866
+ return;
1867
+ }
915
1868
  const result = JSON.parse(stdout);
916
1869
  if (mode === 'failure') {
917
1870
  assert.equal(result.status, 'start-incomplete');
@@ -924,7 +1877,7 @@ test.each(['success', 'failure'])('CLI explicit start shares Project transition
924
1877
  assert.equal(result.branch, 'issue/17');
925
1878
  assert.equal(process.exitCode, undefined);
926
1879
  assert.equal(f.getStatus(), 'Active');
927
- assert.equal(f.comments.length, 1);
1880
+ assert.equal(f.comments.length, mode === 'capacity-override' ? 2 : 1);
928
1881
  }
929
1882
  assert.equal(f.branchWrites.length, 1);
930
1883
  assert.equal(f.statusWrites.length, 1);