@aviaratech/ai-delivery 0.3.25 → 0.3.27

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 (156) hide show
  1. package/README.md +115 -14
  2. package/dist/agent.d.ts +2 -0
  3. package/dist/agent.js +1 -0
  4. package/dist/agent.js.map +1 -1
  5. package/dist/agentReadiness.test.js +61 -123
  6. package/dist/agentReadiness.test.js.map +1 -1
  7. package/dist/cli.js +121 -32
  8. package/dist/cli.js.map +1 -1
  9. package/dist/cliResult.js +1 -1
  10. package/dist/cliResult.js.map +1 -1
  11. package/dist/cliResult.test.js +18 -0
  12. package/dist/cliResult.test.js.map +1 -1
  13. package/dist/config/deliveryConfig.js +5 -1
  14. package/dist/config/deliveryConfig.js.map +1 -1
  15. package/dist/deliveryHealth.test.d.ts +1 -0
  16. package/dist/deliveryHealth.test.js +167 -0
  17. package/dist/deliveryHealth.test.js.map +1 -0
  18. package/dist/dispatch.d.ts +26 -2
  19. package/dist/dispatch.js +78 -7
  20. package/dist/dispatch.js.map +1 -1
  21. package/dist/fixtures/inertEntrypointChild.d.ts +1 -0
  22. package/dist/fixtures/inertEntrypointChild.js +62 -0
  23. package/dist/fixtures/inertEntrypointChild.js.map +1 -0
  24. package/dist/fixtures/inertEntrypoints.d.ts +49 -0
  25. package/dist/fixtures/inertEntrypoints.js +276 -0
  26. package/dist/fixtures/inertEntrypoints.js.map +1 -0
  27. package/dist/fixtures/inertTarget.d.ts +643 -0
  28. package/dist/fixtures/inertTarget.js +713 -0
  29. package/dist/fixtures/inertTarget.js.map +1 -0
  30. package/dist/fixtures/issue63.d.ts +68 -0
  31. package/dist/fixtures/issue63.js +272 -0
  32. package/dist/fixtures/issue63.js.map +1 -0
  33. package/dist/github/client.d.ts +2 -0
  34. package/dist/github/client.js +94 -12
  35. package/dist/github/client.js.map +1 -1
  36. package/dist/github/issueHistory.d.ts +40 -0
  37. package/dist/github/issueHistory.js +144 -0
  38. package/dist/github/issueHistory.js.map +1 -0
  39. package/dist/github/machineAuth.d.ts +9 -0
  40. package/dist/github/machineAuth.js +135 -0
  41. package/dist/github/machineAuth.js.map +1 -0
  42. package/dist/github/machineAuth.test.d.ts +1 -0
  43. package/dist/github/machineAuth.test.js +409 -0
  44. package/dist/github/machineAuth.test.js.map +1 -0
  45. package/dist/github/projectDelivery.d.ts +2 -0
  46. package/dist/github/projectDelivery.js +6 -0
  47. package/dist/github/projectDelivery.js.map +1 -1
  48. package/dist/github/relationships.d.ts +9 -2
  49. package/dist/github/relationships.js +6 -2
  50. package/dist/github/relationships.js.map +1 -1
  51. package/dist/investigationCompletion.test.d.ts +1 -0
  52. package/dist/investigationCompletion.test.js +728 -0
  53. package/dist/investigationCompletion.test.js.map +1 -0
  54. package/dist/issue.d.ts +24 -6
  55. package/dist/issue.js +169 -21
  56. package/dist/issue.js.map +1 -1
  57. package/dist/issue63History.test.d.ts +1 -0
  58. package/dist/issue63History.test.js +45 -0
  59. package/dist/issue63History.test.js.map +1 -0
  60. package/dist/issue63Routes.test.d.ts +1 -0
  61. package/dist/issue63Routes.test.js +153 -0
  62. package/dist/issue63Routes.test.js.map +1 -0
  63. package/dist/issueBlockerGuard.test.d.ts +1 -0
  64. package/dist/issueBlockerGuard.test.js +162 -0
  65. package/dist/issueBlockerGuard.test.js.map +1 -0
  66. package/dist/issueContract.d.ts +230 -0
  67. package/dist/issueContract.js +341 -0
  68. package/dist/issueContract.js.map +1 -0
  69. package/dist/issueContract.test.d.ts +27 -0
  70. package/dist/issueContract.test.js +314 -0
  71. package/dist/issueContract.test.js.map +1 -0
  72. package/dist/issueIntake.test.d.ts +1 -0
  73. package/dist/issueIntake.test.js +994 -0
  74. package/dist/issueIntake.test.js.map +1 -0
  75. package/dist/issueJournal.d.ts +1 -1
  76. package/dist/issueTracking.test.js +16 -8
  77. package/dist/issueTracking.test.js.map +1 -1
  78. package/dist/mcp/tools.d.ts +135 -11
  79. package/dist/mcp/tools.js +85 -33
  80. package/dist/mcp/tools.js.map +1 -1
  81. package/dist/pluginAuthProbe.d.ts +6 -0
  82. package/dist/pluginAuthProbe.js +53 -0
  83. package/dist/pluginAuthProbe.js.map +1 -0
  84. package/dist/pluginAuthProbe.test.d.ts +1 -0
  85. package/dist/pluginAuthProbe.test.js +66 -0
  86. package/dist/pluginAuthProbe.test.js.map +1 -0
  87. package/dist/pluginCredentials.test.d.ts +1 -0
  88. package/dist/pluginCredentials.test.js +277 -0
  89. package/dist/pluginCredentials.test.js.map +1 -0
  90. package/dist/pluginDoctor.test.d.ts +1 -0
  91. package/dist/pluginDoctor.test.js +627 -0
  92. package/dist/pluginDoctor.test.js.map +1 -0
  93. package/dist/pluginInstaller.d.ts +36 -0
  94. package/dist/pluginInstaller.js +231 -10
  95. package/dist/pluginInstaller.js.map +1 -1
  96. package/dist/pluginInstaller.test.js +29 -0
  97. package/dist/pluginInstaller.test.js.map +1 -1
  98. package/dist/pluginPackaging.test.js +23 -3
  99. package/dist/pluginPackaging.test.js.map +1 -1
  100. package/dist/pr.d.ts +70 -0
  101. package/dist/pr.js +290 -3
  102. package/dist/pr.js.map +1 -1
  103. package/dist/prAssociation.test.js +31 -0
  104. package/dist/prAssociation.test.js.map +1 -1
  105. package/dist/review.test.js +133 -0
  106. package/dist/review.test.js.map +1 -1
  107. package/dist/services/agentReadinessService.d.ts +9 -8
  108. package/dist/services/agentReadinessService.js +32 -224
  109. package/dist/services/agentReadinessService.js.map +1 -1
  110. package/dist/services/blockerGuardService.d.ts +17 -0
  111. package/dist/services/blockerGuardService.js +194 -0
  112. package/dist/services/blockerGuardService.js.map +1 -0
  113. package/dist/services/deliveryAdmission.js +22 -19
  114. package/dist/services/deliveryAdmission.js.map +1 -1
  115. package/dist/services/deliveryHealthService.d.ts +84 -0
  116. package/dist/services/deliveryHealthService.js +206 -0
  117. package/dist/services/deliveryHealthService.js.map +1 -0
  118. package/dist/services/worktreeRegistry.d.ts +84 -0
  119. package/dist/services/worktreeRegistry.js +265 -1
  120. package/dist/services/worktreeRegistry.js.map +1 -1
  121. package/dist/setup.test.js +97 -3
  122. package/dist/setup.test.js.map +1 -1
  123. package/dist/start.test.js +31 -3
  124. package/dist/start.test.js.map +1 -1
  125. package/dist/stdoutRegression.test.js +38 -8
  126. package/dist/stdoutRegression.test.js.map +1 -1
  127. package/dist/targetPolicyDiscovery.test.d.ts +1 -0
  128. package/dist/targetPolicyDiscovery.test.js +150 -0
  129. package/dist/targetPolicyDiscovery.test.js.map +1 -0
  130. package/dist/targetPolicyEntrypoints.test.d.ts +1 -0
  131. package/dist/targetPolicyEntrypoints.test.js +275 -0
  132. package/dist/targetPolicyEntrypoints.test.js.map +1 -0
  133. package/dist/targetPolicyLocal.test.d.ts +1 -0
  134. package/dist/targetPolicyLocal.test.js +707 -0
  135. package/dist/targetPolicyLocal.test.js.map +1 -0
  136. package/dist/targetPolicyRoutes.test.d.ts +1 -0
  137. package/dist/targetPolicyRoutes.test.js +298 -0
  138. package/dist/targetPolicyRoutes.test.js.map +1 -0
  139. package/dist/verification.js +48 -12
  140. package/dist/verification.js.map +1 -1
  141. package/dist/verificationGate.test.d.ts +1 -0
  142. package/dist/verificationGate.test.js +106 -0
  143. package/dist/verificationGate.test.js.map +1 -0
  144. package/dist/worktree.d.ts +6 -1
  145. package/dist/worktree.js +90 -3
  146. package/dist/worktree.js.map +1 -1
  147. package/dist/worktreeTransition.test.js +1 -1
  148. package/dist/worktreeTransition.test.js.map +1 -1
  149. package/package.json +1 -1
  150. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  151. package/plugins/ai-delivery/README.md +160 -1
  152. package/plugins/ai-delivery/plugin.json +1 -1
  153. package/plugins/ai-delivery/runtime/dist/cli.js +83 -49
  154. package/plugins/ai-delivery/runtime/package.json +1 -1
  155. package/plugins/ai-delivery/skills/intake-create/SKILL.md +45 -30
  156. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +20 -0
@@ -0,0 +1,728 @@
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync, spawnSync } from 'node:child_process';
3
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+ import { test, vi } from 'vitest';
7
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
9
+ import * as settings from './config/deliveryConfig.js';
10
+ import * as issues from './issue.js';
11
+ import { createAiDeliveryMcpServer } from './mcp/index.js';
12
+ import { digestBytes, digestValue, stableJson } from './delivery/common.js';
13
+ import { gitCommonDir } from './git.js';
14
+ import { getAiDeliveryMcpTool } from './mcp/tools.js';
15
+ import { finishInvestigation, investigationAcceptanceBody, investigationAuthorityBody, registerInvestigation, } from './pr.js';
16
+ import { assertIssueWorktreeTransitionAdmission, readInvestigationPreparation, } from './services/worktreeRegistry.js';
17
+ const native = vi.hoisted(() => ({
18
+ comments: new Map(),
19
+ reviewer: 'reviewer[bot]',
20
+ fault: '',
21
+ }));
22
+ vi.mock('./github/client.js', async (original) => ({
23
+ ...(await original()),
24
+ createDeliveryGitHubClients: async () => ({
25
+ authSource: 'app',
26
+ role: 'reviewer',
27
+ appActorLogin: async () => native.reviewer,
28
+ rest: {
29
+ issues: {
30
+ getComment: async ({ comment_id }) => ({ data: native.comments.get(comment_id) }),
31
+ },
32
+ },
33
+ }),
34
+ }));
35
+ vi.mock('./utils/atomicJson.js', async (original) => {
36
+ const actual = await original();
37
+ return {
38
+ ...actual,
39
+ writeJsonFileAtomically(path, value) {
40
+ if (native.fault === 'registry' &&
41
+ basename(path) === 'worktrees.json' &&
42
+ value.worktrees.length === 1) {
43
+ native.fault = '';
44
+ throw new Error('Fixture interruption after Git removal, before registry commit.');
45
+ }
46
+ return actual.writeJsonFileAtomically(path, value);
47
+ },
48
+ };
49
+ });
50
+ vi.mock('./delivery/common.js', async (original) => {
51
+ const actual = await original();
52
+ return {
53
+ ...actual,
54
+ writeCreateOnly(path, bytes, digest) {
55
+ if (native.fault === 'seal' && basename(path) === 'completion.json') {
56
+ native.fault = '';
57
+ throw new Error('Fixture interruption before completion seal.');
58
+ }
59
+ const result = actual.writeCreateOnly(path, bytes, digest);
60
+ if (native.fault === 'intent' && basename(path) === 'intent.json') {
61
+ native.fault = '';
62
+ throw new Error('Fixture interruption after durable intent.');
63
+ }
64
+ return result;
65
+ },
66
+ };
67
+ });
68
+ function git(root, ...args) {
69
+ return execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'credential.helper=', '-C', root, ...args], {
70
+ encoding: 'utf8',
71
+ stdio: ['ignore', 'pipe', 'pipe'],
72
+ env: {
73
+ PATH: '/usr/bin:/bin',
74
+ HOME: tmpdir(),
75
+ GIT_CONFIG_NOSYSTEM: '1',
76
+ GIT_CONFIG_GLOBAL: '/dev/null',
77
+ GIT_TERMINAL_PROMPT: '0',
78
+ GIT_AUTHOR_NAME: 'Fictional Operator',
79
+ GIT_AUTHOR_EMAIL: 'operator@example.invalid',
80
+ GIT_COMMITTER_NAME: 'Fictional Operator',
81
+ GIT_COMMITTER_EMAIL: 'operator@example.invalid',
82
+ },
83
+ }).trim();
84
+ }
85
+ async function fixture(run, trackedChildResult = false) {
86
+ const f = createFixture(trackedChildResult);
87
+ try {
88
+ await run(f);
89
+ }
90
+ finally {
91
+ native.fault = '';
92
+ assert.equal(realpathSync(f.directory), f.directory);
93
+ assert.equal(lstatSync(f.directory).isSymbolicLink(), false);
94
+ assert.equal(readFileSync(join(f.directory, 'FICTIONAL_FIXTURE'), 'utf8'), f.directory);
95
+ assert.equal(gitCommonDir(f.root), join(f.root, '.git'));
96
+ const paths = git(f.root, 'worktree', 'list', '--porcelain')
97
+ .split('\n')
98
+ .filter((line) => line.startsWith('worktree '));
99
+ assert(paths.every((line) => line.slice(9).startsWith(`${f.directory}/`)));
100
+ rmSync(f.directory, { recursive: true });
101
+ assert.equal(existsSync(f.directory), false);
102
+ }
103
+ }
104
+ function createFixture(trackedChildResult = false) {
105
+ native.comments.clear();
106
+ native.reviewer = 'reviewer[bot]';
107
+ native.fault = '';
108
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-investigation-fictional-')));
109
+ writeFileSync(join(directory, 'FICTIONAL_FIXTURE'), directory);
110
+ const root = join(directory, 'repository');
111
+ mkdirSync(root);
112
+ git(root, 'init', '--initial-branch=main');
113
+ writeFileSync(join(root, '.gitignore'), '.worktrees/\n.issue-cli/\nignored/\n');
114
+ writeFileSync(join(root, 'source.txt'), 'unchanged fictional source\n');
115
+ if (trackedChildResult) {
116
+ mkdirSync(join(root, '..notes'));
117
+ writeFileSync(join(root, '..notes', 'result.txt'), 'Fictional independently reviewed investigation: no change needed; all producers stopped.\n', { mode: 0o600 });
118
+ }
119
+ git(root, 'add', '.');
120
+ git(root, 'commit', '-m', 'Fictional initial source');
121
+ git(root, 'remote', 'add', 'origin', 'https://github.com/example/widget.git');
122
+ const head = git(root, 'rev-parse', 'HEAD');
123
+ const tree = git(root, 'rev-parse', 'HEAD^{tree}');
124
+ const target = join(root, '.worktrees', 'issue-17');
125
+ git(root, 'worktree', 'add', '-b', 'issue/17', target, head);
126
+ const unrelated = {
127
+ branch: 'issue/23',
128
+ identity: 'other',
129
+ issueNumber: 23,
130
+ path: join(directory, 'retained-other'),
131
+ status: 'active',
132
+ type: 'issue',
133
+ createdAt: '2026-01-01',
134
+ updatedAt: '2026-01-01',
135
+ };
136
+ mkdirSync(join(root, '.issue-cli'));
137
+ writeFileSync(join(root, '.issue-cli', 'worktrees.json'), JSON.stringify({ worktrees: [unrelated] }));
138
+ const state = {
139
+ issue: 'open',
140
+ reason: 'COMPLETED',
141
+ branches: [{ name: 'issue/17', sha: head }],
142
+ prs: [],
143
+ acknowledgementId: 101,
144
+ };
145
+ const user = { id: 42, login: 'operator', type: 'User' };
146
+ const comment = (id, body, app = false) => ({
147
+ id,
148
+ body,
149
+ issue_url: 'https://api.github.com/repos/example/widget/issues/17',
150
+ html_url: `https://github.com/example/widget/issues/17#issuecomment-${id}`,
151
+ created_at: '2026-01-01T00:00:00Z',
152
+ user: app ? { id: 99, login: 'reviewer[bot]', type: 'Bot' } : user,
153
+ });
154
+ const context = {
155
+ root,
156
+ repo: { owner: 'example', repo: 'widget' },
157
+ config: {
158
+ repository: 'example/widget',
159
+ roles: { author: { identity: 'operator' }, reviewer: { identity: 'independent' } },
160
+ },
161
+ clients: {
162
+ role: 'author',
163
+ authSource: 'personal',
164
+ authenticatedAuthor: async () => ({ actorLogin: user.login, credentialIdentity: `user:${user.id}` }),
165
+ rest: {
166
+ issues: {
167
+ get: async () => ({
168
+ data: { number: 17, state: state.issue, html_url: 'https://github.com/example/widget/issues/17' },
169
+ }),
170
+ listComments: async () => ({ data: [...native.comments.values()] }),
171
+ createComment: async ({ body }) => {
172
+ const c = comment(state.acknowledgementId, body);
173
+ native.comments.set(c.id, c);
174
+ return { data: c };
175
+ },
176
+ getComment: async ({ comment_id }) => ({ data: native.comments.get(comment_id) }),
177
+ },
178
+ pulls: { list: async () => ({ data: state.prs }) },
179
+ repos: { get: async () => ({ data: { full_name: 'example/widget', default_branch: 'main' } }) },
180
+ git: { getRef: async () => ({ data: { ref: 'refs/heads/main', object: { sha: head } } }) },
181
+ },
182
+ graphql: async (query) => {
183
+ if (query.includes('IssueClosureReadback'))
184
+ return {
185
+ repository: {
186
+ issue: {
187
+ number: 17,
188
+ repository: { nameWithOwner: 'example/widget' },
189
+ state: state.issue.toUpperCase(),
190
+ stateReason: state.reason,
191
+ duplicateOf: null,
192
+ },
193
+ },
194
+ };
195
+ return {
196
+ repository: {
197
+ issue: {
198
+ linkedBranches: {
199
+ nodes: state.branches.map((b) => ({
200
+ ref: { name: b.name, target: { oid: b.sha }, repository: { nameWithOwner: 'example/widget' } },
201
+ })),
202
+ pageInfo: { hasNextPage: false, endCursor: null },
203
+ },
204
+ },
205
+ },
206
+ };
207
+ },
208
+ },
209
+ };
210
+ const resultPath = trackedChildResult ? join(target, '..notes', 'result.txt') : join(directory, 'durable-result.txt');
211
+ writeFileSync(resultPath, 'Fictional independently reviewed investigation: no change needed; all producers stopped.\n', { mode: 0o600 });
212
+ if (trackedChildResult)
213
+ chmodSync(resultPath, 0o600);
214
+ const registry = () => JSON.parse(readFileSync(join(root, '.issue-cli', 'worktrees.json'), 'utf8'));
215
+ const prepare = async () => (await registerInvestigation(context, { issueNumber: 17, investigationWorktree: target, expectedHeadSha: head }))
216
+ .preparation;
217
+ const accept = (preparation) => {
218
+ state.issue = 'closed';
219
+ const digest = digestBytes(readFileSync(resultPath));
220
+ native.comments.set(201, comment(201, investigationAuthorityBody(preparation, digest)));
221
+ native.comments.set(202, comment(202, investigationAcceptanceBody(preparation, digest, 201), true));
222
+ };
223
+ const finish = (extra = {}) => finishInvestigation(context, {
224
+ issueNumber: 17,
225
+ resultPath,
226
+ authorityCommentId: 201,
227
+ acceptanceCommentId: 202,
228
+ ...extra,
229
+ });
230
+ const evidence = join(root, '.git', 'ai-delivery', 'investigations', '17');
231
+ return {
232
+ directory,
233
+ root,
234
+ target,
235
+ head,
236
+ tree,
237
+ context,
238
+ state,
239
+ unrelated,
240
+ prepare,
241
+ accept,
242
+ finish,
243
+ resultPath,
244
+ registry,
245
+ evidence,
246
+ };
247
+ }
248
+ test('prospective registration is exact, acknowledged, idempotent and does not manufacture merged custody', async () => fixture(async (f) => {
249
+ const preparation = await f.prepare();
250
+ assert.equal(preparation.head.sha, f.head);
251
+ assert.equal(preparation.head.tree, f.tree);
252
+ assert.equal((await f.prepare()).preparationId, preparation.preparationId);
253
+ assert.deepEqual(f.registry().worktrees, [f.unrelated, preparation.row]);
254
+ assert.equal(native.comments.size, 1);
255
+ assert.deepEqual(readInvestigationPreparation(f.root, 17), preparation);
256
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
257
+ }));
258
+ test('completion consumes closed native authority and App acceptance, preserving branch, result and unrelated custody', async () => fixture(async (f) => {
259
+ const preparation = await f.prepare();
260
+ f.accept(preparation);
261
+ const dry = await f.finish({ dryRun: true });
262
+ assert.equal(dry.completed, false);
263
+ assert(existsSync(f.target));
264
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
265
+ const completed = await f.finish();
266
+ assert.equal(completed.completed, true);
267
+ assert.equal(existsSync(f.target), false);
268
+ assert.equal(existsSync(preparation.physical.gitDirectory), false);
269
+ assert(!git(f.root, 'worktree', 'list', '--porcelain').includes(f.target));
270
+ assert.equal(git(f.root, 'rev-parse', 'refs/heads/issue/17'), f.head);
271
+ assert.deepEqual(f.registry().worktrees, [f.unrelated]);
272
+ assert(existsSync(f.resultPath));
273
+ const resultDigest = digestBytes(readFileSync(f.resultPath));
274
+ assert.equal(readFileSync(join(f.evidence, `${resultDigest.slice(7)}.bin`), 'utf8'), readFileSync(f.resultPath, 'utf8'));
275
+ const replay = await f.finish();
276
+ assert('replayed' in replay && replay.replayed);
277
+ assert.throws(() => assertIssueWorktreeTransitionAdmission(17, f.root), /pending or terminal/u);
278
+ }));
279
+ for (const failure of ['intent', 'registry', 'seal'])
280
+ test(`interrupted ${failure} resumes the same durable intent and seals exact disk/Git/registry state`, async () => fixture(async (f) => {
281
+ const preparation = await f.prepare();
282
+ f.accept(preparation);
283
+ native.fault = failure;
284
+ await assert.rejects(f.finish(), /Fixture interruption/u);
285
+ const intentBytes = readFileSync(join(f.evidence, 'intent.json'));
286
+ assert.equal(existsSync(f.target), failure === 'intent');
287
+ assert.equal(f.registry().worktrees.length, failure === 'seal' ? 1 : 2);
288
+ const completed = await f.finish();
289
+ assert.equal(completed.completed, true);
290
+ assert('replayed' in completed && completed.replayed);
291
+ assert(readFileSync(join(f.evidence, 'intent.json')).equals(intentBytes));
292
+ assert.equal(existsSync(f.target), false);
293
+ assert.equal(existsSync(preparation.physical.gitDirectory), false);
294
+ assert.deepEqual(f.registry().worktrees, [f.unrelated]);
295
+ assert.equal((await f.finish()).completed, true);
296
+ }));
297
+ const unsafeSource = {
298
+ dirty: (f) => writeFileSync(join(f.target, 'source.txt'), 'must preserve dirty data'),
299
+ untracked: (f) => writeFileSync(join(f.target, 'untracked.txt'), 'must preserve untracked data'),
300
+ ignored: (f) => {
301
+ mkdirSync(join(f.target, 'ignored'));
302
+ writeFileSync(join(f.target, 'ignored', 'incident.txt'), 'must preserve ignored data');
303
+ },
304
+ 'same-tree new commit': (f) => git(f.target, 'commit', '--allow-empty', '-m', 'Unpushed same-tree commit'),
305
+ 'native branch drift': (f) => {
306
+ f.state.branches[0].sha = 'a'.repeat(40);
307
+ },
308
+ 'ambiguous native branches': (f) => {
309
+ f.state.branches.push({ name: 'issue/other', sha: f.head });
310
+ },
311
+ 'locked worktree': (f) => git(f.root, 'worktree', 'lock', f.target),
312
+ 'foreign repository': (f) => git(f.root, 'remote', 'set-url', 'origin', 'https://github.com/foreign/widget.git'),
313
+ 'PR association': (f) => {
314
+ f.state.prs = [{ number: 88 }];
315
+ },
316
+ 'current worktree': (f) => {
317
+ f.context.root = f.target;
318
+ },
319
+ 'registry identity drift': (f) => {
320
+ const r = f.registry();
321
+ r.worktrees[1].identity = 'foreign';
322
+ writeFileSync(join(f.root, '.issue-cli', 'worktrees.json'), JSON.stringify(r));
323
+ },
324
+ 'registry ambiguity': (f) => {
325
+ const r = f.registry();
326
+ r.worktrees.push(r.worktrees[1]);
327
+ writeFileSync(join(f.root, '.issue-cli', 'worktrees.json'), JSON.stringify(r));
328
+ },
329
+ };
330
+ for (const [name, mutate] of Object.entries(unsafeSource))
331
+ test(`refuses ${name} without removal or intent`, async () => fixture(async (f) => {
332
+ const p = await f.prepare();
333
+ f.accept(p);
334
+ mutate(f);
335
+ const before = readFileSync(join(f.root, '.issue-cli', 'worktrees.json'));
336
+ await assert.rejects(f.finish());
337
+ assert(existsSync(f.target));
338
+ assert(existsSync(p.physical.gitDirectory));
339
+ assert(readFileSync(join(f.root, '.issue-cli', 'worktrees.json')).equals(before));
340
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
341
+ }));
342
+ const unsafeAuthority = {
343
+ 'open issue': (f) => {
344
+ f.state.issue = 'open';
345
+ },
346
+ 'not-planned closure': (f) => {
347
+ f.state.reason = 'NOT_PLANNED';
348
+ },
349
+ 'duplicate closure': (f) => {
350
+ f.state.reason = 'DUPLICATE';
351
+ },
352
+ 'missing App evidence': () => {
353
+ native.comments.delete(202);
354
+ },
355
+ 'author quotation of App body': () => {
356
+ native.comments.get(202).user = { id: 42, login: 'operator', type: 'User' };
357
+ },
358
+ 'foreign App': () => {
359
+ native.comments.get(202).user = { id: 99, login: 'foreign[bot]', type: 'Bot' };
360
+ },
361
+ 'changed whole App body': () => {
362
+ native.comments.get(202).body = `${String(native.comments.get(202).body)}\nchanged`;
363
+ },
364
+ 'foreign subject': () => {
365
+ native.comments.get(202).issue_url = 'https://api.github.com/repos/example/widget/issues/18';
366
+ },
367
+ 'operator identity drift': () => {
368
+ native.comments.get(201).user = { id: 43, login: 'operator', type: 'User' };
369
+ },
370
+ 'preparation acknowledgement changed': () => {
371
+ native.comments.get(101).body = 'changed';
372
+ },
373
+ 'acceptance predates preparation': () => {
374
+ native.comments.get(202).created_at = '2025-01-01T00:00:00Z';
375
+ },
376
+ 'changed durable result': (f) => writeFileSync(f.resultPath, 'different durable conclusion'),
377
+ };
378
+ for (const [name, mutate] of Object.entries(unsafeAuthority))
379
+ test(`refuses ${name} and preserves custody`, async () => fixture(async (f) => {
380
+ const p = await f.prepare();
381
+ f.accept(p);
382
+ mutate(f);
383
+ await assert.rejects(f.finish());
384
+ assert(existsSync(f.target));
385
+ assert.deepEqual(f.registry().worktrees, [f.unrelated, p.row]);
386
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
387
+ }));
388
+ test('revoked operator authority cannot be resumed or replaced by local review assertions', async () => fixture(async (f) => {
389
+ const p = await f.prepare();
390
+ f.accept(p);
391
+ native.comments.set(203, {
392
+ ...native.comments.get(201),
393
+ id: 203,
394
+ body: stableJson({
395
+ schemaVersion: 'ai-delivery.investigation-removal-revocation@1',
396
+ preparationId: p.preparationId,
397
+ resultDigest: digestBytes(readFileSync(f.resultPath)),
398
+ authorityCommentId: 201,
399
+ }),
400
+ });
401
+ await assert.rejects(f.finish(), /revoked/u);
402
+ assert(existsSync(f.target));
403
+ }));
404
+ test('inspection explains missing native acceptance without granting removal', async () => fixture(async (f) => {
405
+ const p = await f.prepare();
406
+ f.state.issue = 'closed';
407
+ const result = await finishInvestigation(f.context, { issueNumber: 17, resultPath: f.resultPath, dryRun: true });
408
+ assert.equal(result.completed, false);
409
+ assert('ready' in result && result.ready === false);
410
+ assert(existsSync(f.target));
411
+ assert.deepEqual(f.registry().worktrees, [f.unrelated, p.row]);
412
+ await assert.rejects(finishInvestigation(f.context, { issueNumber: 17, resultPath: f.resultPath }), /positive native/u);
413
+ }));
414
+ test('legacy rows or absent preparation cannot be retrospectively adopted', async () => fixture(async (f) => {
415
+ await assert.rejects(f.finish(), /No prospective/u);
416
+ const row = { ...f.unrelated, issueNumber: 17, path: f.target, branch: 'issue/17' };
417
+ writeFileSync(join(f.root, '.issue-cli', 'worktrees.json'), JSON.stringify({ worktrees: [row] }));
418
+ await assert.rejects(f.prepare(), /Legacy custody/u);
419
+ assert(existsSync(f.target));
420
+ }));
421
+ test('existing writer custody refuses prospective registration without attempting legacy recovery', async () => fixture(async (f) => {
422
+ const directory = join(f.root, '.git', 'ai-delivery', 'writers@1');
423
+ mkdirSync(directory, { recursive: true });
424
+ writeFileSync(join(directory, `${digestValue(f.target).slice(7)}.json`), 'retained historical writer');
425
+ await assert.rejects(f.prepare(), /writer absence/u);
426
+ assert(existsSync(f.target));
427
+ assert.equal(readInvestigationPreparation(f.root, 17), undefined);
428
+ }));
429
+ test('unexplained absence cannot create removal authority, and recreated paths cannot replay a sealed completion', async () => fixture(async (f) => {
430
+ const p = await f.prepare();
431
+ f.accept(p);
432
+ git(f.root, 'worktree', 'remove', f.target);
433
+ await assert.rejects(f.finish(), /missing/u);
434
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
435
+ }));
436
+ test('recreated worktree refuses terminal replay even with identical Git source', async () => fixture(async (f) => {
437
+ const p = await f.prepare();
438
+ f.accept(p);
439
+ await f.finish();
440
+ git(f.root, 'worktree', 'add', f.target, 'issue/17');
441
+ await assert.rejects(f.finish(), /physical identity/u);
442
+ assert(existsSync(f.target));
443
+ }));
444
+ test('resume requires the original evidence digest and revalidates current native acceptance', async () => fixture(async (f) => {
445
+ const p = await f.prepare();
446
+ f.accept(p);
447
+ native.fault = 'registry';
448
+ await assert.rejects(f.finish());
449
+ const before = readFileSync(join(f.evidence, 'intent.json'));
450
+ writeFileSync(f.resultPath, 'replacement result');
451
+ await assert.rejects(f.finish(), /same exact/u);
452
+ assert(readFileSync(join(f.evidence, 'intent.json')).equals(before));
453
+ assert.equal(f.registry().worktrees.length, 2);
454
+ }));
455
+ test('result inside worktree is preserved and refused before removal', async () => fixture(async (f) => {
456
+ const p = await f.prepare();
457
+ f.accept(p);
458
+ const path = join(f.target, 'private-result');
459
+ writeFileSync(path, 'retain', { mode: 0o600 });
460
+ await assert.rejects(f.finish({ resultPath: path }), /outside/u);
461
+ assert.equal(readFileSync(path, 'utf8'), 'retain');
462
+ }));
463
+ test('a clean tracked result under a ..-prefixed child is not external durable evidence', async () => fixture(async (f) => {
464
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
465
+ assert.match(git(f.target, 'ls-tree', f.head, '--', '..notes/result.txt'), /^100644 blob /u);
466
+ assert.equal(lstatSync(f.resultPath).mode & 0o777, 0o600);
467
+ const p = await f.prepare();
468
+ assert.equal(p.head.sha, f.head);
469
+ f.accept(p);
470
+ const bytes = readFileSync(f.resultPath);
471
+ const registry = readFileSync(join(f.root, '.issue-cli', 'worktrees.json'));
472
+ const comments = [...native.comments.entries()];
473
+ const authority = vi.spyOn(f.context.clients.rest.issues, 'get');
474
+ try {
475
+ await assert.rejects(f.finish(), /canonical and outside/u);
476
+ assert.equal(authority.mock.calls.length, 0);
477
+ }
478
+ finally {
479
+ authority.mockRestore();
480
+ }
481
+ assert(readFileSync(f.resultPath).equals(bytes));
482
+ assert(existsSync(f.target));
483
+ assert(existsSync(p.physical.gitDirectory));
484
+ assert(readFileSync(join(f.root, '.issue-cli', 'worktrees.json')).equals(registry));
485
+ assert.deepEqual([...native.comments.entries()], comments);
486
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
487
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
488
+ }, true));
489
+ test('registration requires exact canonical path and authoritative initial default head', async () => fixture(async (f) => {
490
+ await assert.rejects(registerInvestigation(f.context, {
491
+ issueNumber: 17,
492
+ investigationWorktree: `${f.target}/../issue-17`,
493
+ expectedHeadSha: f.head,
494
+ }), /canonical/u);
495
+ git(f.target, 'commit', '--allow-empty', '-m', 'Already investigated');
496
+ f.state.branches[0].sha = git(f.target, 'rev-parse', 'HEAD');
497
+ await assert.rejects(registerInvestigation(f.context, {
498
+ issueNumber: 17,
499
+ investigationWorktree: f.target,
500
+ expectedHeadSha: f.state.branches[0].sha,
501
+ }), /current native default/u);
502
+ }));
503
+ test('CLI/MCP modes reject PR mixing, preserve ordinary required PR and refuse local approval substitutions', () => {
504
+ const start = getAiDeliveryMcpTool('issue_start').inputSchema;
505
+ const finish = getAiDeliveryMcpTool('issue_finish').inputSchema;
506
+ const registration = {
507
+ issueNumber: 17,
508
+ investigationWorktree: '/fictional/.worktrees/issue-17',
509
+ expectedHeadSha: 'a'.repeat(40),
510
+ };
511
+ assert(start.safeParse(registration).success);
512
+ for (const extra of [{ branch: 'issue/17' }, { request: 'create another' }, { expectedHeadSha: 'invalid' }])
513
+ assert.equal(start.safeParse({ ...registration, ...extra }).success, false);
514
+ const completion = { issueNumber: 17, investigation: true, resultPath: '/fictional/result' };
515
+ assert(finish.safeParse(completion).success);
516
+ for (const extra of [
517
+ { prNumber: 23 },
518
+ { nonClosing: true },
519
+ { strategy: 'squash' },
520
+ { reviewedHeadSha: 'a'.repeat(40) },
521
+ { approved: true },
522
+ ])
523
+ assert.equal(finish.safeParse({ ...completion, ...extra }).success, false);
524
+ assert(finish.safeParse({ issueNumber: 17, prNumber: 23 }).success);
525
+ assert.equal(finish.safeParse({ issueNumber: 17 }).success, false);
526
+ });
527
+ test('an explicit repo-root cannot hide the physical current worktree', async () => fixture(async (f) => {
528
+ const p = await f.prepare();
529
+ f.accept(p);
530
+ const original = process.cwd();
531
+ try {
532
+ process.chdir(f.target);
533
+ await assert.rejects(f.finish(), /current worktree/u);
534
+ }
535
+ finally {
536
+ process.chdir(original);
537
+ }
538
+ assert(existsSync(f.target));
539
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
540
+ }));
541
+ test('an explicit repo-root cannot hide an empty ..-prefixed physical current-worktree child', async () => fixture(async (f) => {
542
+ const p = await f.prepare();
543
+ f.accept(p);
544
+ const directory = join(f.target, '..notes');
545
+ mkdirSync(directory);
546
+ assert.equal(readdirSync(directory).length, 0);
547
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
548
+ assert.equal(f.context.root, f.root);
549
+ const registry = readFileSync(join(f.root, '.issue-cli', 'worktrees.json'));
550
+ const original = process.cwd();
551
+ try {
552
+ process.chdir(directory);
553
+ await assert.rejects(f.finish(), /current worktree/u);
554
+ }
555
+ finally {
556
+ process.chdir(original);
557
+ }
558
+ assert(existsSync(directory));
559
+ assert(existsSync(f.target));
560
+ assert(existsSync(p.physical.gitDirectory));
561
+ assert(readFileSync(join(f.root, '.issue-cli', 'worktrees.json')).equals(registry));
562
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
563
+ }));
564
+ test('primary worktree registration is refused without touching its source', async () => fixture(async (f) => {
565
+ await assert.rejects(registerInvestigation(f.context, { issueNumber: 17, investigationWorktree: f.root, expectedHeadSha: f.head }), /canonical/u);
566
+ assert.equal(git(f.root, 'rev-parse', 'HEAD'), f.head);
567
+ assert(existsSync(f.target));
568
+ }));
569
+ test('missing ownership witness or registry row refuses cleanup rather than reconstructing custody', async () => fixture(async (f) => {
570
+ const p = await f.prepare();
571
+ f.accept(p);
572
+ const directory = join(f.root, '.git', 'ai-delivery', 'worktree-owners');
573
+ for (const name of readdirSync(directory))
574
+ rmSync(join(directory, name));
575
+ await assert.rejects(f.finish(), /ownership witness/u);
576
+ assert(existsSync(f.target));
577
+ }));
578
+ test('row absence without durable removal intent refuses cleanup', async () => fixture(async (f) => {
579
+ const p = await f.prepare();
580
+ f.accept(p);
581
+ writeFileSync(join(f.root, '.issue-cli', 'worktrees.json'), JSON.stringify({ worktrees: [f.unrelated] }));
582
+ await assert.rejects(f.finish(), /without a removal intent/u);
583
+ assert(existsSync(f.target));
584
+ }));
585
+ test('terminal replay still requires current authentic App acceptance', async () => fixture(async (f) => {
586
+ const p = await f.prepare();
587
+ f.accept(p);
588
+ await f.finish();
589
+ native.comments.delete(202);
590
+ await assert.rejects(f.finish(), /reviewer-App/u);
591
+ assert.deepEqual(f.registry().worktrees, [f.unrelated]);
592
+ }));
593
+ test('corrupt preserved result prevents interruption recovery from deleting or retiring more data', async () => fixture(async (f) => {
594
+ const p = await f.prepare();
595
+ f.accept(p);
596
+ native.fault = 'intent';
597
+ await assert.rejects(f.finish());
598
+ const digest = digestBytes(readFileSync(f.resultPath));
599
+ writeFileSync(join(f.evidence, `${digest.slice(7)}.bin`), 'corrupt');
600
+ await assert.rejects(f.finish(), /evidence changed/u);
601
+ assert(existsSync(f.target));
602
+ assert.equal(f.registry().worktrees.length, 2);
603
+ }));
604
+ test('MCP investigation lifecycle resolves the selected checkout and completes through the shared owner', async () => fixture(async (f) => {
605
+ const loadSettings = vi.spyOn(settings, 'loadDeliverySettings').mockResolvedValue({
606
+ roles: {
607
+ author: { identity: 'operator', authSource: 'personal' },
608
+ reviewer: { identity: 'independent' },
609
+ },
610
+ checkoutRoots: [f.root],
611
+ });
612
+ const loadContext = vi.spyOn(issues, 'loadDeliveryContext').mockResolvedValue(f.context);
613
+ const server = createAiDeliveryMcpServer({ repoRoot: f.directory });
614
+ const client = new Client({ name: 'fictional-investigation', version: '1' });
615
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
616
+ try {
617
+ await server.connect(serverTransport);
618
+ await client.connect(clientTransport);
619
+ const started = await client.callTool({
620
+ name: 'issue_start',
621
+ arguments: {
622
+ repo: 'example/widget',
623
+ issueNumber: 17,
624
+ investigationWorktree: f.target,
625
+ expectedHeadSha: f.head,
626
+ },
627
+ });
628
+ assert.equal(started.isError, undefined, JSON.stringify(started));
629
+ const p = readInvestigationPreparation(f.root, 17);
630
+ f.accept(p);
631
+ const finished = await client.callTool({
632
+ name: 'issue_finish',
633
+ arguments: {
634
+ repo: 'example/widget',
635
+ issueNumber: 17,
636
+ investigation: true,
637
+ resultPath: f.resultPath,
638
+ authorityCommentId: 201,
639
+ acceptanceCommentId: 202,
640
+ },
641
+ });
642
+ assert.equal(finished.isError, undefined, JSON.stringify(finished));
643
+ assert.equal(existsSync(f.target), false);
644
+ assert.deepEqual(f.registry().worktrees, [f.unrelated]);
645
+ assert.equal(git(f.root, 'rev-parse', 'refs/heads/issue/17'), f.head);
646
+ }
647
+ finally {
648
+ await client.close();
649
+ await server.close();
650
+ loadSettings.mockRestore();
651
+ loadContext.mockRestore();
652
+ }
653
+ }));
654
+ for (const flag of ['--assume-unchanged', '--skip-worktree']) {
655
+ test(`registration refuses ${flag} without recording prospective custody`, async () => fixture(async (f) => {
656
+ git(f.target, 'update-index', flag, '--', 'source.txt');
657
+ writeFileSync(join(f.target, 'source.txt'), 'hidden private bytes before registration\n');
658
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
659
+ await assert.rejects(f.prepare(), /index entries/u);
660
+ assert.equal(readFileSync(join(f.target, 'source.txt'), 'utf8'), 'hidden private bytes before registration\n');
661
+ assert.equal(readInvestigationPreparation(f.root, 17), undefined);
662
+ assert.deepEqual(f.registry().worktrees, [f.unrelated]);
663
+ }));
664
+ test(`completion refuses ${flag} and preserves hidden bytes, administration and registry`, async () => fixture(async (f) => {
665
+ const p = await f.prepare();
666
+ f.accept(p);
667
+ git(f.target, 'update-index', flag, '--', 'source.txt');
668
+ writeFileSync(join(f.target, 'source.txt'), 'hidden private bytes after registration\n');
669
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
670
+ const before = readFileSync(join(f.root, '.issue-cli', 'worktrees.json'));
671
+ await assert.rejects(f.finish(), /index entries/u);
672
+ assert.equal(readFileSync(join(f.target, 'source.txt'), 'utf8'), 'hidden private bytes after registration\n');
673
+ assert(existsSync(p.physical.gitDirectory));
674
+ assert(readFileSync(join(f.root, '.issue-cli', 'worktrees.json')).equals(before));
675
+ assert.equal(git(f.target, 'rev-parse', 'HEAD'), f.head);
676
+ assert.equal(existsSync(join(f.evidence, 'intent.json')), false);
677
+ }));
678
+ test(`interrupted resume refuses ${flag} without retiring hidden bytes or changing its intent`, async () => fixture(async (f) => {
679
+ const p = await f.prepare();
680
+ f.accept(p);
681
+ native.fault = 'intent';
682
+ await assert.rejects(f.finish(), /Fixture interruption/u);
683
+ const intent = readFileSync(join(f.evidence, 'intent.json'));
684
+ git(f.target, 'update-index', flag, '--', 'source.txt');
685
+ writeFileSync(join(f.target, 'source.txt'), 'hidden private bytes during recovery\n');
686
+ assert.equal(git(f.target, 'status', '--porcelain', '--untracked-files=all'), '');
687
+ await assert.rejects(f.finish(), /index entries/u);
688
+ assert.equal(readFileSync(join(f.target, 'source.txt'), 'utf8'), 'hidden private bytes during recovery\n');
689
+ assert(readFileSync(join(f.evidence, 'intent.json')).equals(intent));
690
+ assert(existsSync(p.physical.gitDirectory));
691
+ assert.deepEqual(f.registry().worktrees, [f.unrelated, p.row]);
692
+ }));
693
+ }
694
+ for (const [mode, args, refusal] of [
695
+ [
696
+ 'start',
697
+ [
698
+ 'start',
699
+ '--issue',
700
+ '17',
701
+ '--investigation-worktree',
702
+ '/fictional',
703
+ '--expected-head',
704
+ 'a'.repeat(40),
705
+ '--branch',
706
+ 'issue/17',
707
+ ],
708
+ /cannot create or change/u,
709
+ ],
710
+ [
711
+ 'finish',
712
+ ['finish', '--issue', '17', '--investigation', '--result', '/fictional-result', '--pr', '23'],
713
+ /cannot accept PR or merge/u,
714
+ ],
715
+ ])
716
+ test(`CLI ${mode} refuses mixed modes before authentication and preserves fixture source`, async () => fixture(async (f) => {
717
+ const cli = new URL('./cli.js', import.meta.url);
718
+ const response = spawnSync(process.execPath, [cli.pathname, '--repo', 'example/widget', ...args], {
719
+ cwd: f.directory,
720
+ env: { HOME: f.directory, PATH: '/usr/bin:/bin', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
721
+ encoding: 'utf8',
722
+ });
723
+ assert.equal(response.status, 1, response.stderr);
724
+ assert.match(response.stderr, refusal);
725
+ assert.equal(git(f.target, 'rev-parse', 'HEAD'), f.head);
726
+ assert.deepEqual(f.registry().worktrees, [f.unrelated]);
727
+ }));
728
+ //# sourceMappingURL=investigationCompletion.test.js.map