@aviaratech/ai-delivery 0.3.25 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +104 -9
  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/config/deliveryConfig.js +5 -1
  10. package/dist/config/deliveryConfig.js.map +1 -1
  11. package/dist/deliveryHealth.test.d.ts +1 -0
  12. package/dist/deliveryHealth.test.js +167 -0
  13. package/dist/deliveryHealth.test.js.map +1 -0
  14. package/dist/dispatch.d.ts +1 -0
  15. package/dist/dispatch.js +47 -4
  16. package/dist/dispatch.js.map +1 -1
  17. package/dist/fixtures/inertEntrypointChild.d.ts +1 -0
  18. package/dist/fixtures/inertEntrypointChild.js +62 -0
  19. package/dist/fixtures/inertEntrypointChild.js.map +1 -0
  20. package/dist/fixtures/inertEntrypoints.d.ts +49 -0
  21. package/dist/fixtures/inertEntrypoints.js +276 -0
  22. package/dist/fixtures/inertEntrypoints.js.map +1 -0
  23. package/dist/fixtures/inertTarget.d.ts +643 -0
  24. package/dist/fixtures/inertTarget.js +713 -0
  25. package/dist/fixtures/inertTarget.js.map +1 -0
  26. package/dist/fixtures/issue63.d.ts +68 -0
  27. package/dist/fixtures/issue63.js +272 -0
  28. package/dist/fixtures/issue63.js.map +1 -0
  29. package/dist/github/client.d.ts +2 -0
  30. package/dist/github/client.js +94 -12
  31. package/dist/github/client.js.map +1 -1
  32. package/dist/github/issueHistory.d.ts +40 -0
  33. package/dist/github/issueHistory.js +144 -0
  34. package/dist/github/issueHistory.js.map +1 -0
  35. package/dist/github/machineAuth.d.ts +9 -0
  36. package/dist/github/machineAuth.js +135 -0
  37. package/dist/github/machineAuth.js.map +1 -0
  38. package/dist/github/machineAuth.test.d.ts +1 -0
  39. package/dist/github/machineAuth.test.js +409 -0
  40. package/dist/github/machineAuth.test.js.map +1 -0
  41. package/dist/github/projectDelivery.d.ts +2 -0
  42. package/dist/github/projectDelivery.js +6 -0
  43. package/dist/github/projectDelivery.js.map +1 -1
  44. package/dist/github/relationships.d.ts +9 -2
  45. package/dist/github/relationships.js +6 -2
  46. package/dist/github/relationships.js.map +1 -1
  47. package/dist/investigationCompletion.test.d.ts +1 -0
  48. package/dist/investigationCompletion.test.js +728 -0
  49. package/dist/investigationCompletion.test.js.map +1 -0
  50. package/dist/issue.d.ts +22 -6
  51. package/dist/issue.js +152 -21
  52. package/dist/issue.js.map +1 -1
  53. package/dist/issue63History.test.d.ts +1 -0
  54. package/dist/issue63History.test.js +45 -0
  55. package/dist/issue63History.test.js.map +1 -0
  56. package/dist/issue63Routes.test.d.ts +1 -0
  57. package/dist/issue63Routes.test.js +153 -0
  58. package/dist/issue63Routes.test.js.map +1 -0
  59. package/dist/issueBlockerGuard.test.d.ts +1 -0
  60. package/dist/issueBlockerGuard.test.js +162 -0
  61. package/dist/issueBlockerGuard.test.js.map +1 -0
  62. package/dist/issueContract.d.ts +230 -0
  63. package/dist/issueContract.js +341 -0
  64. package/dist/issueContract.js.map +1 -0
  65. package/dist/issueContract.test.d.ts +27 -0
  66. package/dist/issueContract.test.js +314 -0
  67. package/dist/issueContract.test.js.map +1 -0
  68. package/dist/issueIntake.test.d.ts +1 -0
  69. package/dist/issueIntake.test.js +649 -0
  70. package/dist/issueIntake.test.js.map +1 -0
  71. package/dist/issueJournal.d.ts +1 -1
  72. package/dist/issueTracking.test.js +16 -8
  73. package/dist/issueTracking.test.js.map +1 -1
  74. package/dist/mcp/tools.d.ts +135 -11
  75. package/dist/mcp/tools.js +85 -33
  76. package/dist/mcp/tools.js.map +1 -1
  77. package/dist/pluginAuthProbe.d.ts +6 -0
  78. package/dist/pluginAuthProbe.js +53 -0
  79. package/dist/pluginAuthProbe.js.map +1 -0
  80. package/dist/pluginAuthProbe.test.d.ts +1 -0
  81. package/dist/pluginAuthProbe.test.js +66 -0
  82. package/dist/pluginAuthProbe.test.js.map +1 -0
  83. package/dist/pluginCredentials.test.d.ts +1 -0
  84. package/dist/pluginCredentials.test.js +277 -0
  85. package/dist/pluginCredentials.test.js.map +1 -0
  86. package/dist/pluginDoctor.test.d.ts +1 -0
  87. package/dist/pluginDoctor.test.js +627 -0
  88. package/dist/pluginDoctor.test.js.map +1 -0
  89. package/dist/pluginInstaller.d.ts +36 -0
  90. package/dist/pluginInstaller.js +231 -10
  91. package/dist/pluginInstaller.js.map +1 -1
  92. package/dist/pluginInstaller.test.js +29 -0
  93. package/dist/pluginInstaller.test.js.map +1 -1
  94. package/dist/pluginPackaging.test.js +23 -3
  95. package/dist/pluginPackaging.test.js.map +1 -1
  96. package/dist/pr.d.ts +70 -0
  97. package/dist/pr.js +238 -1
  98. package/dist/pr.js.map +1 -1
  99. package/dist/services/agentReadinessService.d.ts +9 -8
  100. package/dist/services/agentReadinessService.js +32 -224
  101. package/dist/services/agentReadinessService.js.map +1 -1
  102. package/dist/services/blockerGuardService.d.ts +17 -0
  103. package/dist/services/blockerGuardService.js +194 -0
  104. package/dist/services/blockerGuardService.js.map +1 -0
  105. package/dist/services/deliveryAdmission.js +22 -19
  106. package/dist/services/deliveryAdmission.js.map +1 -1
  107. package/dist/services/deliveryHealthService.d.ts +84 -0
  108. package/dist/services/deliveryHealthService.js +206 -0
  109. package/dist/services/deliveryHealthService.js.map +1 -0
  110. package/dist/services/worktreeRegistry.d.ts +84 -0
  111. package/dist/services/worktreeRegistry.js +265 -1
  112. package/dist/services/worktreeRegistry.js.map +1 -1
  113. package/dist/setup.test.js +97 -3
  114. package/dist/setup.test.js.map +1 -1
  115. package/dist/start.test.js +30 -3
  116. package/dist/start.test.js.map +1 -1
  117. package/dist/stdoutRegression.test.js +36 -6
  118. package/dist/stdoutRegression.test.js.map +1 -1
  119. package/dist/targetPolicyEntrypoints.test.d.ts +1 -0
  120. package/dist/targetPolicyEntrypoints.test.js +275 -0
  121. package/dist/targetPolicyEntrypoints.test.js.map +1 -0
  122. package/dist/targetPolicyLocal.test.d.ts +1 -0
  123. package/dist/targetPolicyLocal.test.js +707 -0
  124. package/dist/targetPolicyLocal.test.js.map +1 -0
  125. package/dist/targetPolicyRoutes.test.d.ts +1 -0
  126. package/dist/targetPolicyRoutes.test.js +298 -0
  127. package/dist/targetPolicyRoutes.test.js.map +1 -0
  128. package/dist/verification.js +48 -12
  129. package/dist/verification.js.map +1 -1
  130. package/dist/verificationGate.test.d.ts +1 -0
  131. package/dist/verificationGate.test.js +106 -0
  132. package/dist/verificationGate.test.js.map +1 -0
  133. package/dist/worktree.d.ts +6 -1
  134. package/dist/worktree.js +90 -3
  135. package/dist/worktree.js.map +1 -1
  136. package/dist/worktreeTransition.test.js +1 -1
  137. package/dist/worktreeTransition.test.js.map +1 -1
  138. package/package.json +1 -1
  139. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  140. package/plugins/ai-delivery/README.md +160 -1
  141. package/plugins/ai-delivery/plugin.json +1 -1
  142. package/plugins/ai-delivery/runtime/dist/cli.js +83 -49
  143. package/plugins/ai-delivery/runtime/package.json +1 -1
  144. package/plugins/ai-delivery/skills/intake-create/SKILL.md +45 -30
  145. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +20 -0
@@ -0,0 +1,627 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createHash, generateKeyPairSync } from 'node:crypto';
3
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { afterEach, beforeEach, test, vi } from 'vitest';
7
+ import { syntheticDiscoveryClients, syntheticDiscoveryConfig } from './fixtures/discovery.js';
8
+ // Native selections, keys and HTTP responses below are fictional. This tests
9
+ // the selected-process contract, not a GUI or an authenticated live service.
10
+ const fixture = vi.hoisted(() => ({
11
+ home: '',
12
+ config: '',
13
+ root: '',
14
+ host: 'codex',
15
+ enabled: true,
16
+ mode: 'success',
17
+ authCalls: 0,
18
+ machine: false,
19
+ ghCalls: [],
20
+ keyReads: 0,
21
+ settingsReads: 0,
22
+ requestErrorLogs: [],
23
+ childStderrLines: [],
24
+ commands: [],
25
+ requests: [],
26
+ startupEnvironments: [],
27
+ }));
28
+ vi.mock('node:os', async (original) => ({
29
+ ...(await original()),
30
+ homedir: () => fixture.home,
31
+ }));
32
+ vi.mock('node:fs', async (original) => {
33
+ const actual = await original();
34
+ return {
35
+ ...actual,
36
+ readFileSync: (...args) => {
37
+ if (String(args[0]) === fixture.config)
38
+ fixture.settingsReads++;
39
+ if (String(args[0]).endsWith('.pem'))
40
+ fixture.keyReads++;
41
+ return actual.readFileSync(...args);
42
+ },
43
+ };
44
+ });
45
+ // Octokit binds console.error at module import. Capture its real request-log
46
+ // hook through a logger sink instead of a later console spy, as subprocess
47
+ // stderr would do. Requests, authentication and error owners remain real.
48
+ vi.mock('@octokit/rest', async (original) => {
49
+ const actual = await original();
50
+ return {
51
+ ...actual,
52
+ Octokit: actual.Octokit.defaults({
53
+ log: {
54
+ debug: () => { },
55
+ info: () => { },
56
+ warn: () => { },
57
+ error: (...values) => {
58
+ const line = values.filter((value) => typeof value === 'string').join(' ');
59
+ fixture.childStderrLines.push(line);
60
+ fixture.requestErrorLogs.push(line);
61
+ },
62
+ },
63
+ }),
64
+ };
65
+ });
66
+ vi.mock('@modelcontextprotocol/sdk/client/stdio.js', async (original) => ({
67
+ ...(await original()),
68
+ StdioClientTransport: class {
69
+ constructor(options) {
70
+ fixture.startupEnvironments.push(options.env);
71
+ }
72
+ close() { }
73
+ },
74
+ }));
75
+ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
76
+ Client: class {
77
+ connect() {
78
+ if (fixture.mode === 'startup_failed')
79
+ throw new Error('fictional-upstream-secret');
80
+ }
81
+ getServerVersion() {
82
+ return { version: '0.3.24' };
83
+ }
84
+ listTools() {
85
+ return { tools: [] };
86
+ }
87
+ close() { }
88
+ },
89
+ }));
90
+ vi.mock('./verification.js', async (original) => ({
91
+ ...(await original()),
92
+ runStageCommand: async (_root, args, _signal, _a, _b, _c, _d, writer, options) => {
93
+ if (args[0] === process.execPath) {
94
+ const { execFile } = await import('node:child_process');
95
+ return new Promise((resolve, reject) => {
96
+ execFile(process.execPath, args.slice(1), {
97
+ env: options.environment,
98
+ cwd: options.cwd ?? _root,
99
+ maxBuffer: options.maxCapturedOutputBytes ?? 1024 * 1024,
100
+ encoding: 'utf8',
101
+ }, (error, stdout, stderr) => {
102
+ writer?.idle();
103
+ if (error) {
104
+ options.failedOutput?.(Buffer.from(stdout + stderr));
105
+ reject(new Error('Synthetic selected CLI failed; output withheld.'));
106
+ }
107
+ else
108
+ resolve(Buffer.from(stdout));
109
+ });
110
+ });
111
+ }
112
+ fixture.commands.push({ args, environment: options.environment });
113
+ assert.deepEqual(args, fixture.host === 'codex'
114
+ ? ['codex', 'plugin', 'list', '--marketplace', 'ai-delivery-user', '--available', '--json']
115
+ : ['claude', 'plugin', 'list', '--json']);
116
+ const catalog = join(fixture.home, '.cache/ai-delivery/plugins', fixture.host, 'user/marketplace');
117
+ const entry = { version: '0.3.24', enabled: fixture.enabled };
118
+ return Buffer.from(JSON.stringify(fixture.host === 'codex'
119
+ ? {
120
+ installed: [
121
+ {
122
+ ...entry,
123
+ pluginId: 'ai-delivery@ai-delivery-user',
124
+ marketplaceName: 'ai-delivery-user',
125
+ source: { source: 'local', path: join(catalog, 'versions/0.3.24/plugins/ai-delivery') },
126
+ marketplaceSource: { sourceType: 'local', source: catalog },
127
+ },
128
+ ],
129
+ available: [],
130
+ }
131
+ : [
132
+ {
133
+ ...entry,
134
+ id: 'ai-delivery@ai-delivery-user',
135
+ scope: 'user',
136
+ installPath: fixture.root,
137
+ mcpServers: {
138
+ 'ai-delivery': { command: 'node', args: ['${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js'] },
139
+ },
140
+ },
141
+ ]));
142
+ },
143
+ }));
144
+ vi.mock('node:child_process', async (original) => ({
145
+ ...(await original()),
146
+ execFile: (binary, args, options, callback) => {
147
+ if (args[0] === 'auth') {
148
+ assert.equal(fixture.machine, true);
149
+ assert.equal(binary, realpathSync(join(fixture.home, 'bin', 'gh')));
150
+ assert.equal(options.maxBuffer, 64 * 1024);
151
+ for (const name of [
152
+ 'GH_TOKEN',
153
+ 'GITHUB_TOKEN',
154
+ 'DELIVERY_REVIEW_APP_ID',
155
+ 'DELIVERY_REVIEW_INSTALLATION_ID',
156
+ 'DELIVERY_REVIEW_KEY_PATH',
157
+ 'NODE_OPTIONS',
158
+ 'GH_DEBUG',
159
+ 'UNRELATED_SERVICE_TOKEN',
160
+ ])
161
+ assert.equal(options.env[name], undefined);
162
+ fixture.ghCalls.push(args);
163
+ if (args[1] === 'status')
164
+ callback(null, JSON.stringify({
165
+ hosts: {
166
+ 'github.com': [{ active: true, host: 'github.com', login: 'fixture-author-login', state: 'success' }],
167
+ },
168
+ }), 'fictional-opaque-stderr');
169
+ else {
170
+ assert.deepEqual(args, ['auth', 'token', '--hostname', 'github.com', '--user', 'fixture-author-login']);
171
+ callback(null, 'fictional_machine_author_value', 'fictional-opaque-stderr');
172
+ }
173
+ return;
174
+ }
175
+ assert.equal(binary, process.execPath);
176
+ assert.deepEqual(args, [join(fixture.root, 'runtime/dist/cli.js'), '--repo', args[2], 'config:resolve']);
177
+ assert.equal(options.timeout, undefined);
178
+ assert.equal(options.maxBuffer, 1024 * 1024);
179
+ const forwarded = Object.keys(options.env).sort();
180
+ assert.deepEqual(forwarded, (fixture.machine
181
+ ? [
182
+ 'AI_DELIVERY_CONFIG',
183
+ 'DELIVERY_REVIEW_APP_ID',
184
+ 'DELIVERY_REVIEW_INSTALLATION_ID',
185
+ 'DELIVERY_REVIEW_KEY_PATH',
186
+ 'DISABLE_AUTOUPDATER',
187
+ 'HOME',
188
+ 'LANG',
189
+ 'LC_ALL',
190
+ 'NODE_OPTIONS',
191
+ 'PATH',
192
+ ]
193
+ : [
194
+ 'AI_DELIVERY_CONFIG',
195
+ 'DELIVERY_AUTHOR_TOKEN',
196
+ 'DELIVERY_REVIEW_APP_ID',
197
+ 'DELIVERY_REVIEW_INSTALLATION_ID',
198
+ 'DELIVERY_REVIEW_KEY_PATH',
199
+ 'DISABLE_AUTOUPDATER',
200
+ 'NODE_OPTIONS',
201
+ 'PATH',
202
+ ]).sort());
203
+ fixture.authCalls++;
204
+ const run = async () => {
205
+ if (fixture.mode === 'raw_failure') {
206
+ callback(new Error('fictional-value-header'), 'fictional-value-body', 'fictional-value-key-path');
207
+ return;
208
+ }
209
+ const ambient = process.env;
210
+ process.env = { ...options.env };
211
+ fixture.childStderrLines = [];
212
+ try {
213
+ const { contextFor } = await import('./dispatch.js');
214
+ const { preflightReviewRoute } = await import('./pr.js');
215
+ const context = await contextFor({ repoRoot: options.cwd, repo: args[2] }, 'config:resolve');
216
+ const data = {
217
+ routing: context.configuration.routing,
218
+ reviewRoute: await preflightReviewRoute(context, undefined, undefined, 'development'),
219
+ };
220
+ if (fixture.mode === 'wrong_repo')
221
+ data.routing.repository = 'example/unselected';
222
+ if (fixture.mode === 'same_actor')
223
+ data.reviewRoute.reviewer.actorLogin = data.reviewRoute.author.actorLogin;
224
+ if (fixture.mode === 'secret_actor')
225
+ data.reviewRoute.author.actorLogin = options.env.DELIVERY_AUTHOR_TOKEN;
226
+ callback(null, JSON.stringify({
227
+ ...data,
228
+ untrustedBody: 'fictional-value-body',
229
+ untrustedHeaders: 'fictional-value-header',
230
+ }), 'fictional-value-key-path');
231
+ }
232
+ catch (error) {
233
+ callback(new Error('Selected CLI failed'), '', [...fixture.childStderrLines, `ai-delivery: ${error instanceof Error ? error.message : 'unknown'}`].join('\n') + '\n');
234
+ }
235
+ finally {
236
+ process.env = ambient;
237
+ }
238
+ };
239
+ void run();
240
+ },
241
+ }));
242
+ const { managePlugin } = await import('./pluginInstaller.js');
243
+ let settings;
244
+ function file(path, bytes) {
245
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
246
+ writeFileSync(path, bytes, { mode: 0o600 });
247
+ }
248
+ function native(host = 'codex') {
249
+ fixture.host = host;
250
+ const directory = join(fixture.home, '.cache/ai-delivery/plugins', host, 'user');
251
+ const catalog = join(directory, 'marketplace');
252
+ const unit = join(catalog, 'versions/0.3.24');
253
+ const source = join(unit, 'plugins/ai-delivery');
254
+ const nativeHome = join(fixture.home, host === 'codex' ? '.codex' : '.claude');
255
+ const cache = join(nativeHome, 'plugins/cache/ai-delivery-user/ai-delivery/0.3.24');
256
+ fixture.root = host === 'codex' ? cache : source;
257
+ const files = {
258
+ 'runtime/dist/cli.js': 'fictional selected CLI; execution simulated',
259
+ 'dist/mcp-launcher.js': 'fictional launcher',
260
+ 'skills/intake/SKILL.md': 'fictional skill',
261
+ };
262
+ for (const root of [source, cache])
263
+ for (const [name, bytes] of Object.entries(files))
264
+ file(join(root, name), bytes);
265
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
266
+ file(join(unit, 'archive.tgz'), 'fictional archive');
267
+ file(join(unit, 'version.json'), JSON.stringify({
268
+ owner: '@aviaratech/ai-delivery.plugin-version@1',
269
+ version: '0.3.24',
270
+ archiveSha256: hash('fictional archive'),
271
+ files: Object.fromEntries(Object.entries(files)
272
+ .sort(([a], [b]) => a.localeCompare(b))
273
+ .map(([name, bytes]) => [name, hash(bytes)])),
274
+ }));
275
+ file(join(directory, 'state.json'), JSON.stringify({
276
+ owner: '@aviaratech/ai-delivery.plugin@1',
277
+ host,
278
+ scope: 'user',
279
+ projectRoot: null,
280
+ nativeHome,
281
+ marketplace: 'ai-delivery-user',
282
+ currentVersion: '0.3.24',
283
+ previousVersion: null,
284
+ installedPath: cache,
285
+ }));
286
+ if (host === 'claude-code') {
287
+ file(join(nativeHome, 'plugins/known_marketplaces.json'), JSON.stringify({
288
+ 'ai-delivery-user': { source: { source: 'directory', path: catalog }, installLocation: catalog },
289
+ }));
290
+ file(join(catalog, '.claude-plugin/marketplace.json'), JSON.stringify({
291
+ name: 'ai-delivery-user',
292
+ plugins: [{ name: 'ai-delivery', version: '0.3.24', source: './versions/0.3.24/plugins/ai-delivery' }],
293
+ }));
294
+ }
295
+ }
296
+ beforeEach(() => {
297
+ fixture.home = mkdtempSync(join(tmpdir(), 'ai-delivery-doctor-'));
298
+ fixture.config = join(fixture.home, 'settings.json');
299
+ fixture.enabled = true;
300
+ fixture.mode = 'success';
301
+ fixture.authCalls = 0;
302
+ fixture.machine = false;
303
+ fixture.ghCalls = [];
304
+ fixture.keyReads = 0;
305
+ fixture.settingsReads = 0;
306
+ fixture.requestErrorLogs = [];
307
+ fixture.childStderrLines = [];
308
+ fixture.commands = [];
309
+ fixture.requests = [];
310
+ fixture.startupEnvironments = [];
311
+ vi.stubEnv('CODEX_HOME', join(fixture.home, '.codex'));
312
+ vi.stubEnv('CLAUDE_CONFIG_DIR', join(fixture.home, '.claude'));
313
+ vi.stubEnv('AI_DELIVERY_CONFIG', fixture.config);
314
+ settings = {
315
+ schemaVersion: 'ai-delivery.user@1',
316
+ roles: {
317
+ author: { authSource: 'personal', identity: 'fixture-author', credentialEnv: { token: 'DELIVERY_AUTHOR_TOKEN' } },
318
+ reviewer: {
319
+ identity: 'fixture-reviewer',
320
+ credentialEnv: {
321
+ appId: 'DELIVERY_REVIEW_APP_ID',
322
+ installationId: 'DELIVERY_REVIEW_INSTALLATION_ID',
323
+ privateKeyPath: 'DELIVERY_REVIEW_KEY_PATH',
324
+ },
325
+ },
326
+ },
327
+ project: 1,
328
+ checkoutRoots: [],
329
+ pointsField: 'Estimate',
330
+ priorityField: 'Urgency',
331
+ statusField: 'Flow',
332
+ statuses: syntheticDiscoveryConfig.native.project.statuses,
333
+ };
334
+ file(fixture.config, JSON.stringify(settings));
335
+ vi.stubEnv('DELIVERY_AUTHOR_TOKEN', 'fictional-author-value');
336
+ vi.stubEnv('DELIVERY_REVIEW_APP_ID', '654321');
337
+ vi.stubEnv('DELIVERY_REVIEW_INSTALLATION_ID', '765432');
338
+ const key = join(fixture.home, 'fictional-reviewer.pem');
339
+ file(key, generateKeyPairSync('rsa', {
340
+ modulusLength: 2048,
341
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
342
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
343
+ }).privateKey);
344
+ vi.stubEnv('DELIVERY_REVIEW_KEY_PATH', key);
345
+ for (const name of ['GH_TOKEN', 'GITHUB_TOKEN', 'UNRELATED_SERVICE_TOKEN', 'AI_DELIVERY_IDENTITY'])
346
+ vi.stubEnv(name, 'fictional-unrelated-value');
347
+ vi.stubGlobal('fetch', () => {
348
+ throw new Error('Unexpected HTTP in a synthetic doctor fixture');
349
+ });
350
+ native();
351
+ });
352
+ afterEach(() => {
353
+ vi.unstubAllEnvs();
354
+ vi.unstubAllGlobals();
355
+ vi.restoreAllMocks();
356
+ rmSync(fixture.home, { recursive: true, force: true });
357
+ });
358
+ function http() {
359
+ vi.stubGlobal('fetch', async (input, init) => {
360
+ const url = input instanceof Request ? input.url : String(input);
361
+ const path = new URL(url).pathname;
362
+ const method = init?.method ?? 'GET';
363
+ fixture.requests.push(`${method} ${path}`);
364
+ const json = (data, status = 200) => new Response(JSON.stringify(data), {
365
+ status,
366
+ headers: { 'content-type': 'application/json', 'x-fixture-secret': 'fictional-value-header' },
367
+ });
368
+ if (path === '/graphql' && method === 'POST') {
369
+ assert.equal(typeof init?.body, 'string');
370
+ const body = JSON.parse(init.body);
371
+ assert.ok(!body.query.includes('mutation'));
372
+ const config = { ...syntheticDiscoveryConfig, repository: `${body.variables.owner}/${body.variables.repo}` };
373
+ return json({ data: await syntheticDiscoveryClients(config).graphql(body.query) });
374
+ }
375
+ if (method === 'POST' && path === '/app/installations/765432/access_tokens')
376
+ return json({
377
+ token: 'ghs_fictional_installation',
378
+ expires_at: '2099-01-01T00:00:00Z',
379
+ permissions: { contents: 'read', pull_requests: 'write' },
380
+ });
381
+ assert.equal(method, 'GET');
382
+ if (path === '/user')
383
+ return fixture.mode === 'expired'
384
+ ? json({ message: 'fictional-author-value' }, 401)
385
+ : json({ id: 42, login: 'fixture-author-login', type: 'User' });
386
+ if (path === '/app')
387
+ return json({ id: 654321, slug: 'fixture-reviewer' });
388
+ if (/^\/repos\/example\/(widget|service)$/u.test(path)) {
389
+ if (fixture.mode === 'denied' && new Headers(init?.headers).get('authorization')?.includes('ghs_'))
390
+ return json({ message: 'fictional-value-body' }, 403);
391
+ return json({ full_name: path.slice(7), default_branch: 'main' });
392
+ }
393
+ if (path.endsWith('/rules/branches/main'))
394
+ return fixture.mode === 'unknown_rules' ? json({ message: 'fictional-value-body' }, 403) : json([]);
395
+ if (path.endsWith('/branches/main/protection'))
396
+ return fixture.mode === 'unknown_rules' ? json({ message: 'fictional-value-body' }, 403) : json({});
397
+ throw new Error('Unapproved endpoint in simulated doctor readback');
398
+ });
399
+ }
400
+ function doctor(repo = 'example/widget', checkAuth = true) {
401
+ return managePlugin({
402
+ action: 'doctor',
403
+ host: fixture.host,
404
+ scope: 'user',
405
+ repoRoot: fixture.home,
406
+ ...(checkAuth ? { checkAuth, repo } : {}),
407
+ });
408
+ }
409
+ test('default doctor has no settings, reference, key or authentication access; native inventory/startup exclude credentials', async () => {
410
+ file(fixture.config, '{invalid fictional settings');
411
+ const result = await doctor('example/widget', false);
412
+ assert.equal(result.mcp?.startup, 'ready');
413
+ assert.equal(result.authProbe, undefined);
414
+ assert.equal(fixture.settingsReads, 0);
415
+ assert.equal(fixture.keyReads, 0);
416
+ assert.equal(fixture.authCalls, 0);
417
+ assert.deepEqual(fixture.requests, []);
418
+ for (const env of [...fixture.commands.map((c) => c.environment), ...fixture.startupEnvironments]) {
419
+ assert.equal(env.GH_TOKEN, undefined);
420
+ assert.equal(env.DELIVERY_AUTHOR_TOKEN, undefined);
421
+ assert.equal(env.AI_DELIVERY_IDENTITY, undefined);
422
+ }
423
+ });
424
+ test('the actual SDK startup subprocess receives no inherited-name credential sentinels', async () => {
425
+ const sdk = await vi.importActual('@modelcontextprotocol/sdk/client/stdio.js');
426
+ settings.roles.author.credentialEnv = { token: 'LOGNAME' };
427
+ file(fixture.config, JSON.stringify(settings));
428
+ for (const name of sdk.DEFAULT_INHERITED_ENV_VARS)
429
+ vi.stubEnv(name, `fictional-inherited-${name}`);
430
+ await doctor('example/widget', false);
431
+ const transport = new sdk.StdioClientTransport({
432
+ command: process.execPath,
433
+ args: [
434
+ '--input-type=module',
435
+ '-e',
436
+ "process.stdout.write(JSON.stringify({jsonrpc:'2.0',method:'fixture.environment',params:Object.fromEntries(['HOME','LOGNAME','PATH','SHELL','TERM','USER'].map(name=>[name,process.env[name]]))})+'\\n');process.stdin.resume();",
437
+ ],
438
+ cwd: fixture.home,
439
+ env: fixture.startupEnvironments[0],
440
+ stderr: 'pipe',
441
+ });
442
+ try {
443
+ const readback = new Promise((resolve, reject) => {
444
+ transport.onmessage = resolve;
445
+ transport.onerror = reject;
446
+ });
447
+ await transport.start();
448
+ const message = (await readback);
449
+ assert.deepEqual(message.params, Object.fromEntries(sdk.DEFAULT_INHERITED_ENV_VARS.map((name) => [name, ''])));
450
+ assert.equal(fixture.settingsReads, 0);
451
+ assert.equal(fixture.authCalls, 0);
452
+ assert.equal(fixture.keyReads, 0);
453
+ }
454
+ finally {
455
+ await transport.close();
456
+ }
457
+ });
458
+ test('auth opt-in requires an explicit valid repository, even outside Git or in dry-run', async () => {
459
+ await assert.rejects(managePlugin({ action: 'doctor', host: 'codex', scope: 'user', repoRoot: fixture.home, checkAuth: true }), /requires explicit --repo/u);
460
+ await assert.rejects(doctor('invalid'), /Invalid string/u);
461
+ assert.equal(fixture.commands.length, 0);
462
+ const result = await managePlugin({
463
+ action: 'doctor',
464
+ host: 'codex',
465
+ scope: 'user',
466
+ repoRoot: fixture.home,
467
+ checkAuth: true,
468
+ repo: 'example/widget',
469
+ dryRun: true,
470
+ });
471
+ assert.equal(result.authProbe?.reason, 'dry_run');
472
+ assert.equal(fixture.settingsReads, 0);
473
+ });
474
+ test('invalid settings stop before reading a key or executing the authenticated child', async () => {
475
+ file(fixture.config, JSON.stringify({
476
+ ...settings,
477
+ roles: { ...settings.roles, reviewer: { ...settings.roles.reviewer, identity: settings.roles.author.identity } },
478
+ }));
479
+ const result = await doctor();
480
+ assert.equal(result.authProbe?.settings, 'unavailable_or_invalid');
481
+ assert.equal(fixture.keyReads, 0);
482
+ assert.equal(fixture.authCalls, 0);
483
+ assert.ok(!JSON.stringify(result.authProbe).includes(fixture.config));
484
+ });
485
+ test('all missing selected references gate both roles; unrelated legacy credentials cannot satisfy them', async () => {
486
+ vi.stubEnv('DELIVERY_AUTHOR_TOKEN', '');
487
+ vi.stubEnv('DELIVERY_REVIEW_APP_ID', '');
488
+ const result = await doctor();
489
+ assert.deepEqual(result.authProbe?.processReferences.missingNames, [
490
+ 'DELIVERY_AUTHOR_TOKEN',
491
+ 'DELIVERY_REVIEW_APP_ID',
492
+ ]);
493
+ assert.equal(result.authProbe?.authentication.status, 'not_checked');
494
+ assert.equal(fixture.keyReads, 0);
495
+ assert.equal(fixture.authCalls, 0);
496
+ assert.ok(!JSON.stringify(result.authProbe).includes('fictional-unrelated-value'));
497
+ });
498
+ test.each(['codex', 'claude-code'])('%s doctor may explicitly resolve an absent default reference through the selected machine session', async (host) => {
499
+ native(host);
500
+ fixture.machine = true;
501
+ settings.roles.author.credentialEnv = { token: 'GH_TOKEN' };
502
+ file(fixture.config, JSON.stringify(settings));
503
+ vi.stubEnv('GH_TOKEN', undefined);
504
+ vi.stubEnv('HOME', fixture.home);
505
+ // Own optional language selectors instead of assuming the verification wrapper supplies them.
506
+ vi.stubEnv('LANG', 'C');
507
+ vi.stubEnv('LC_ALL', 'C');
508
+ vi.stubEnv('USER', undefined);
509
+ vi.stubEnv('LOGNAME', undefined);
510
+ const bin = join(fixture.home, 'bin');
511
+ mkdirSync(bin);
512
+ file(join(bin, 'gh'), 'fictional CLI; execution simulated');
513
+ chmodSync(join(bin, 'gh'), 0o755);
514
+ vi.stubEnv('PATH', bin);
515
+ http();
516
+ for (const repo of ['example/widget', 'example/service', 'example/widget']) {
517
+ const result = await doctor(repo);
518
+ assert.equal(result.authProbe?.outcome, 'readback_complete');
519
+ assert.equal(result.authProbe?.processReferences.status, 'complete');
520
+ assert.ok(!result.authProbe?.processReferences.requiredNames.includes('GH_TOKEN'));
521
+ assert.equal(result.authProbe?.authentication.author?.credentialSource, `gh:github.com:${realpathSync(join(bin, 'gh'))}`);
522
+ assert.equal(result.authProbe?.nativeGuiPropagation, 'unverified');
523
+ assert.ok(!JSON.stringify(result).includes('fictional_machine_author_value'));
524
+ }
525
+ assert.equal(fixture.ghCalls.length, 6, 'One status/token selection per command, retained across routing and operation');
526
+ });
527
+ test('absent default author input still gates missing reviewer references before machine/session/key access', async () => {
528
+ settings.roles.author.credentialEnv = { token: 'GH_TOKEN' };
529
+ file(fixture.config, JSON.stringify(settings));
530
+ vi.stubEnv('GH_TOKEN', undefined);
531
+ vi.stubEnv('DELIVERY_REVIEW_APP_ID', undefined);
532
+ const result = await doctor();
533
+ assert.deepEqual(result.authProbe?.processReferences.missingNames, ['DELIVERY_REVIEW_APP_ID']);
534
+ assert.equal(fixture.authCalls, 0);
535
+ assert.equal(fixture.ghCalls.length, 0);
536
+ assert.equal(fixture.keyReads, 0);
537
+ });
538
+ test('invalid App references and reserved runtime credential names stop before key/network access', async () => {
539
+ vi.stubEnv('DELIVERY_REVIEW_INSTALLATION_ID', 'not-an-id');
540
+ assert.equal((await doctor()).authProbe?.reason, 'invalid_references');
541
+ vi.stubEnv('DELIVERY_REVIEW_INSTALLATION_ID', '765432');
542
+ settings.roles.author.credentialEnv = { token: 'NODE_OPTIONS' };
543
+ file(fixture.config, JSON.stringify(settings));
544
+ vi.stubEnv('NODE_OPTIONS', 'fictional-runtime-value');
545
+ assert.equal((await doctor()).authProbe?.reason, 'invalid_references');
546
+ assert.equal(fixture.keyReads, 0);
547
+ assert.equal(fixture.authCalls, 0);
548
+ });
549
+ test.each(['codex', 'claude-code'])('%s synthetic selection outside Git probes A → B → A through existing read-only auth owners', async (host) => {
550
+ native(host);
551
+ http();
552
+ for (const repo of ['example/widget', 'example/service', 'example/widget']) {
553
+ const result = await doctor(repo);
554
+ assert.equal(result.authProbe?.outcome, 'readback_complete');
555
+ assert.deepEqual(result.authProbe?.authentication, {
556
+ status: 'verified',
557
+ author: { actorLogin: 'fixture-author-login', authSource: 'personal' },
558
+ reviewer: { actorLogin: 'fixture-reviewer[bot]', authSource: 'app' },
559
+ });
560
+ assert.deepEqual(result.authProbe?.repositoryAccess, { repository: repo, status: 'verified' });
561
+ assert.equal(result.authProbe?.nativeGuiPropagation, 'unverified');
562
+ assert.equal(result.authProbe?.reviewRules?.approvalEligibility, 'unknown');
563
+ assert.ok(!JSON.stringify(result).includes('fictional-author-value'));
564
+ assert.ok(!JSON.stringify(result.authProbe).includes('fictional-reviewer.pem'));
565
+ }
566
+ assert.equal(fixture.authCalls, 3);
567
+ assert.ok(fixture.requests.includes('POST /app/installations/765432/access_tokens'));
568
+ });
569
+ test.each(['changed', 'disabled', 'startup_failed'])('auth probe refuses %s selected native bytes/startup', async (mode) => {
570
+ if (mode === 'changed')
571
+ file(join(fixture.root, 'skills/intake/SKILL.md'), 'modified skill');
572
+ if (mode === 'disabled')
573
+ fixture.enabled = false;
574
+ if (mode === 'startup_failed')
575
+ fixture.mode = mode;
576
+ const result = await doctor();
577
+ assert.equal(result.authProbe?.reason, 'native_plugin_not_ready');
578
+ assert.equal(fixture.authCalls, 0);
579
+ assert.equal(fixture.keyReads, 0);
580
+ assert.equal(fixture.settingsReads, 0);
581
+ assert.ok(!JSON.stringify(result).includes('fictional-upstream-secret'));
582
+ });
583
+ test.each(['expired', 'denied', 'raw_failure'])('safe labelled %s failure does not reveal body/header/key-path sentinels or claim verified access', async (mode) => {
584
+ fixture.mode = mode;
585
+ http();
586
+ const result = await doctor();
587
+ assert.equal(result.authProbe?.outcome, 'failed');
588
+ assert.equal(result.authProbe?.reason, mode === 'expired' ? 'authentication_failed' : mode === 'denied' ? 'repository_denied' : 'probe_failed');
589
+ if (mode !== 'raw_failure')
590
+ assert.ok(fixture.requestErrorLogs.some((line) => line.startsWith('GET ')), 'Installed Octokit REST logger must precede the final diagnostic');
591
+ assert.notEqual(result.authProbe?.authentication.status, 'verified');
592
+ assert.notEqual(result.authProbe?.repositoryAccess.status, 'verified');
593
+ for (const sentinel of [
594
+ 'fictional-author-value',
595
+ 'fictional-value-body',
596
+ 'fictional-value-header',
597
+ 'fictional-value-key-path',
598
+ ])
599
+ assert.ok(!JSON.stringify(result).includes(sentinel));
600
+ });
601
+ test('hidden rules remain unknown after authenticated identity/repository reads; no counted approval is inferred', async () => {
602
+ fixture.mode = 'unknown_rules';
603
+ http();
604
+ const result = await doctor();
605
+ assert.equal(result.authProbe?.outcome, 'readback_complete');
606
+ assert.deepEqual(result.authProbe?.reviewRules, {
607
+ visibility: 'unknown',
608
+ observedRequiredApprovals: null,
609
+ approvalEligibility: 'unknown',
610
+ });
611
+ });
612
+ test.each(['wrong_repo', 'same_actor', 'secret_actor'])('rejects %s readback without reflecting unsafe identity data', async (mode) => {
613
+ fixture.mode = mode;
614
+ http();
615
+ const result = await doctor();
616
+ assert.equal(result.authProbe?.reason, 'invalid_readback');
617
+ assert.equal(result.authProbe?.authentication.status, 'unverified');
618
+ assert.ok(!JSON.stringify(result).includes('fictional-author-value'));
619
+ });
620
+ test('synthetic doctor reads never change managed state or settings', async () => {
621
+ http();
622
+ const state = join(fixture.home, '.cache/ai-delivery/plugins/codex/user/state.json');
623
+ const before = [readFileSync(state), readFileSync(fixture.config)];
624
+ await doctor();
625
+ assert.deepEqual([readFileSync(state), readFileSync(fixture.config)], before);
626
+ });
627
+ //# sourceMappingURL=pluginDoctor.test.js.map