burnoff 1.4.1 → 2.1.0

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 (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -0,0 +1,735 @@
1
+ /**
2
+ * @file src/cli/startup-audit/mcp-audit.mjs
3
+ * Eager MCP Turn-0 bloat, tool-name length, list_changed invalidation, and subagent MCP tax auditing.
4
+ */
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { compareSemver } from '../../config/semver.mjs';
9
+ import { getHomeDir } from '../../config/paths.mjs';
10
+ import { CHARS_PER_TOKEN, parseJsoncReadOnly } from './jsonc.mjs';
11
+
12
+ export const LIST_CHANGED_PREFIX_THRESHOLD = 20000;
13
+ export const SUBAGENT_MCP_MIN_SERVERS = 5;
14
+ export const DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER = 600;
15
+ export const COARSE_META_TOOL_MIN_SERVERS = 3;
16
+ export const COARSE_META_TOOL_MIN_TOKENS = 10000;
17
+
18
+ function collectClaudeMcpServers({ workspacePath, claudeJsonParsed }) {
19
+ const servers = new Map();
20
+ const addMap = (serversMap, sourceFile) => {
21
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
22
+ for (const [name, cfg] of Object.entries(serversMap)) {
23
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
24
+ if (cfg.disabled === true || cfg.enabled === false) continue;
25
+ const hint = Number(cfg.estimatedTokens ?? cfg.schemaTokens ?? cfg.tokenCount ?? 0);
26
+ servers.set(name, {
27
+ name,
28
+ sourceFile,
29
+ hintTokens: Number.isFinite(hint) && hint > 0 ? hint : 0
30
+ });
31
+ }
32
+ };
33
+
34
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
35
+ if (projMcp.parseOk && projMcp.parsed) {
36
+ addMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
37
+ }
38
+
39
+ if (claudeJsonParsed && typeof claudeJsonParsed === 'object') {
40
+ addMap(claudeJsonParsed.mcpServers, '~/.claude.json');
41
+ const projects = claudeJsonParsed.projects;
42
+ if (projects && typeof projects === 'object') {
43
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
44
+ for (const [projKey, projCfg] of Object.entries(projects)) {
45
+ if (!projCfg || typeof projCfg !== 'object') continue;
46
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
47
+ if (normKey === normWs && projCfg.mcpServers) {
48
+ addMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
49
+ }
50
+ }
51
+ }
52
+ }
53
+
54
+ return Array.from(servers.values());
55
+ }
56
+
57
+ function evaluateClaudeEagerMcpGate({
58
+ paths,
59
+ env = process.env,
60
+ claudeCodeVersion = null,
61
+ claudeJsonParsed = null,
62
+ userSettingsParsed = null,
63
+ projSettingsParsed = null,
64
+ projLocalSettingsParsed = null,
65
+ mcpToolCalls7d = {},
66
+ schemaTokensByServer = {},
67
+ gatewaySupportsToolSearch = false
68
+ }) {
69
+ const readLayeredEnv = (key) => {
70
+ let val = null;
71
+ for (const doc of [userSettingsParsed, projSettingsParsed, projLocalSettingsParsed]) {
72
+ if (doc?.env && doc.env[key] !== undefined && String(doc.env[key]).trim() !== '') {
73
+ val = String(doc.env[key]).trim();
74
+ }
75
+ }
76
+ if (env && env[key] !== undefined && String(env[key]).trim() !== '') {
77
+ val = String(env[key]).trim();
78
+ }
79
+ return val;
80
+ };
81
+
82
+ const enableToolSearch = readLayeredEnv('ENABLE_TOOL_SEARCH');
83
+ const rawDisableBetas = readLayeredEnv('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS');
84
+ const baseUrl = readLayeredEnv('ANTHROPIC_BASE_URL');
85
+
86
+ const isCustomGateway = Boolean(baseUrl && !/^https:\/\/api\.anthropic\.com(?:\/|$)/i.test(baseUrl));
87
+ const disableExperimentalBetas = /^(1|true)$/i.test(String(rawDisableBetas || '').trim());
88
+ const toolSearchDisabled = /^(false|0)$/i.test(String(enableToolSearch || '').trim());
89
+ const toolSearchForcedOn = /^(true|1)$/i.test(String(enableToolSearch || '').trim());
90
+ const versionCmp = claudeCodeVersion ? compareSemver(claudeCodeVersion, '2.1.304') : null;
91
+ const versionBelow21304 = Boolean(versionCmp !== null && versionCmp < 0);
92
+
93
+ const discovered = collectClaudeMcpServers({ workspacePath: paths.cwd, claudeJsonParsed });
94
+ const isSshSession = Boolean(
95
+ (env?.SSH_CONNECTION && String(env.SSH_CONNECTION).trim()) ||
96
+ (env?.SSH_TTY && String(env.SSH_TTY).trim()) ||
97
+ (env?.SSH_CLIENT && String(env.SSH_CLIENT).trim())
98
+ );
99
+ const gatewayVerified =
100
+ gatewaySupportsToolSearch === true ||
101
+ /^(1|true)$/i.test(
102
+ String(
103
+ readLayeredEnv('BURNOFF_GATEWAY_VERIFIED_TOOL_SEARCH') ||
104
+ readLayeredEnv('CLAUDE_CODE_GATEWAY_VERIFIED_TOOL_SEARCH') ||
105
+ ''
106
+ ).trim()
107
+ );
108
+
109
+ const gateReasons = [];
110
+ if (toolSearchDisabled) gateReasons.push('ENABLE_TOOL_SEARCH=false');
111
+ if (disableExperimentalBetas) gateReasons.push('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1');
112
+ if (isSshSession && (discovered.length > 0 || toolSearchForcedOn)) {
113
+ gateReasons.push('ssh_forced_disable_experimental_betas');
114
+ }
115
+ if (isCustomGateway && !gatewayVerified && discovered.length > 0) {
116
+ if (versionBelow21304 && !toolSearchForcedOn) {
117
+ gateReasons.push('custom_gateway_claude_code_lt_2.1.304');
118
+ } else {
119
+ gateReasons.push('custom_gateway_toolsearch_fallback');
120
+ }
121
+ }
122
+
123
+ if (gateReasons.length === 0) {
124
+ return {
125
+ eagerGateActive: false,
126
+ gateReasons: [],
127
+ enableToolSearch,
128
+ toolSearchDisabled,
129
+ disableExperimentalBetas,
130
+ isCustomGateway,
131
+ baseUrl: baseUrl || null,
132
+ isLocalhostProxy: Boolean(baseUrl && isLocalhostBaseUrl(baseUrl)),
133
+ isSshSession,
134
+ gatewayVerified,
135
+ configuredServerCount: discovered.length,
136
+ configuredServerNames: discovered.map((s) => s.name),
137
+ claudeCodeVersion: claudeCodeVersion || null,
138
+ startupTaxTokensPerTurn: 0,
139
+ summaryLine: 'MCP startup tax: 0 tok/turn (deferred loading active)',
140
+ unusedEagerServers: []
141
+ };
142
+ }
143
+
144
+ const unusedEagerServers = [];
145
+ let startupTaxTokensPerTurn = 0;
146
+
147
+ for (const srv of discovered) {
148
+ const telemetryTokens = Number(schemaTokensByServer[srv.name] || 0);
149
+ const tokensEst = telemetryTokens > 0 ? telemetryTokens : srv.hintTokens > 0 ? srv.hintTokens : 3200;
150
+ const calls7d = Number(mcpToolCalls7d[srv.name] || 0);
151
+ startupTaxTokensPerTurn += tokensEst;
152
+ if (calls7d === 0) {
153
+ unusedEagerServers.push({
154
+ name: srv.name,
155
+ sourceFile: srv.sourceFile,
156
+ tokensEst,
157
+ isEstimated: !(telemetryTokens > 0 || srv.hintTokens > 0),
158
+ calls7d
159
+ });
160
+ }
161
+ }
162
+
163
+ return {
164
+ eagerGateActive: true,
165
+ gateReasons,
166
+ enableToolSearch,
167
+ toolSearchDisabled,
168
+ disableExperimentalBetas,
169
+ isCustomGateway,
170
+ baseUrl: baseUrl || null,
171
+ isLocalhostProxy: Boolean(baseUrl && isLocalhostBaseUrl(baseUrl)),
172
+ isSshSession,
173
+ gatewayVerified,
174
+ configuredServerCount: discovered.length,
175
+ configuredServerNames: discovered.map((s) => s.name),
176
+ claudeCodeVersion: claudeCodeVersion || null,
177
+ startupTaxTokensPerTurn,
178
+ summaryLine: `MCP startup tax: ~${startupTaxTokensPerTurn.toLocaleString('en-US')} tok/turn (${discovered.length} eager server${discovered.length === 1 ? '' : 's'})`,
179
+ unusedEagerServers
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Returns true if `rawUrl` points to a loopback / localhost proxy endpoint.
185
+ */
186
+ export function isLocalhostBaseUrl(rawUrl) {
187
+ const s = String(rawUrl || '').trim();
188
+ if (!s) return false;
189
+ try {
190
+ const u = new URL(s);
191
+ const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
192
+ return (
193
+ host === 'localhost' ||
194
+ host === '127.0.0.1' ||
195
+ host === '::1' ||
196
+ host === '0.0.0.0' ||
197
+ host === 'host.docker.internal' ||
198
+ host.endsWith('.localhost')
199
+ );
200
+ } catch {
201
+ return false; // ignore: malformed ANTHROPIC_BASE_URL is not treated as localhost proxy
202
+ }
203
+ }
204
+
205
+ /**
206
+ * BO-MCP-10: Eager-only coarse meta-tool coaching + local `ANTHROPIC_BASE_URL`
207
+ * MCP proxy `CACHE-BACKFIRE TRAP` lint. Never emits coarse meta-tool advice when
208
+ * native deferred `ToolSearch` loading is healthy (`eagerGateActive === false`).
209
+ */
210
+ export function evaluateMcpProxyAndMetaToolCoaching({
211
+ harness = 'claude-code',
212
+ eagerGateActive = false,
213
+ baseUrl = null,
214
+ isLocalhostProxy = isLocalhostBaseUrl(baseUrl),
215
+ gatewayVerified = false,
216
+ toolSearchDisabled = false,
217
+ disableExperimentalBetas = false,
218
+ isSshSession = false,
219
+ configuredServerCount = 0,
220
+ configuredServerNames = [],
221
+ startupTaxTokensPerTurn = 0,
222
+ file = 'env'
223
+ } = {}) {
224
+ const proxyLooksLikeMcpGateway = /mcp|proxy|gateway|router/i.test(String(baseUrl || ''));
225
+ const proxyCacheBackfireTrap = Boolean(
226
+ harness === 'claude-code' &&
227
+ isLocalhostProxy &&
228
+ !gatewayVerified &&
229
+ !toolSearchDisabled &&
230
+ !disableExperimentalBetas &&
231
+ !isSshSession &&
232
+ (configuredServerCount > 0 || proxyLooksLikeMcpGateway)
233
+ );
234
+
235
+ const meetsCoarseThreshold =
236
+ configuredServerCount >= COARSE_META_TOOL_MIN_SERVERS ||
237
+ Number(startupTaxTokensPerTurn || 0) >= COARSE_META_TOOL_MIN_TOKENS;
238
+ const coarseMetaToolCoaching = Boolean(eagerGateActive && !proxyCacheBackfireTrap && meetsCoarseThreshold);
239
+
240
+ const lints = [];
241
+ let coachingNote = null;
242
+
243
+ if (proxyCacheBackfireTrap) {
244
+ coachingNote =
245
+ `CACHE-BACKFIRE TRAP (BO-MCP-10): Localhost ANTHROPIC_BASE_URL proxy (${baseUrl}) wraps an otherwise native-deferred Claude Code setup, risking #95087 beta-header stripping (forcing eager MCP fallback) and extra proxy latency. Unset ANTHROPIC_BASE_URL to restore native ToolSearch deferral, or set BURNOFF_GATEWAY_VERIFIED_TOOL_SEARCH=1 if verified.`;
246
+ lints.push({
247
+ ruleId: 'BO-MCP-10',
248
+ kind: 'proxy_cache_backfire',
249
+ severity: 'warn',
250
+ harness,
251
+ file,
252
+ message: coachingNote,
253
+ remediation:
254
+ 'Remove unnecessary local ANTHROPIC_BASE_URL MCP proxies when native Claude Code ToolSearch deferral is available.'
255
+ });
256
+ } else if (coarseMetaToolCoaching) {
257
+ coachingNote =
258
+ `Eager MCP Coarse Meta-Tool Coaching (BO-MCP-10): Eager schema loading active (${configuredServerCount} servers, ~${Number(startupTaxTokensPerTurn || 0).toLocaleString('en-US')} est. tok/turn). Consolidate fine-grained MCP tools into coarse progressive-disclosure meta-tools or disable unused servers between sessions.`;
259
+ lints.push({
260
+ ruleId: 'BO-MCP-10',
261
+ kind: 'eager_coarse_meta_tool',
262
+ severity: 'info',
263
+ harness,
264
+ file,
265
+ configuredServers: configuredServerNames,
266
+ message: coachingNote,
267
+ remediation:
268
+ 'Consolidate chatty fine-grained MCP tools behind coarse domain actions only while eager loading is unavoidable, or re-enable native ToolSearch deferral.'
269
+ });
270
+ }
271
+
272
+ return {
273
+ status: proxyCacheBackfireTrap ? 'warn' : coarseMetaToolCoaching ? 'info' : 'pass',
274
+ eagerGateActive: Boolean(eagerGateActive),
275
+ isLocalhostProxy: Boolean(isLocalhostProxy),
276
+ baseUrl: baseUrl || null,
277
+ proxyCacheBackfireTrap,
278
+ coarseMetaToolCoaching,
279
+ coachingNote,
280
+ lints
281
+ };
282
+ }
283
+
284
+ /**
285
+ * BO-MCP-05 (#97616): Scans configured MCP tool definitions and observed Claude Code
286
+ * MCP tool names for `mcp__<server>__<tool>` identifiers exceeding 64 characters.
287
+ */
288
+ export function scanMcpToolNameLengthViolations({
289
+ homeDir = getHomeDir(),
290
+ workspacePath = process.cwd(),
291
+ observedToolNames = [],
292
+ manifestDirs = [],
293
+ maxLength = 64,
294
+ repoOnly = false,
295
+ includeClaudeDefaults = true,
296
+ extraMcpFiles = []
297
+ } = {}) {
298
+ const disabledServers = new Set();
299
+ const violationsByFullName = new Map();
300
+
301
+ const recordViolation = (fullName, serverName, toolName, source) => {
302
+ if (!fullName || fullName.length <= maxLength) return;
303
+ if (disabledServers.has(serverName)) return;
304
+ if (violationsByFullName.has(fullName)) return;
305
+ violationsByFullName.set(fullName, {
306
+ fullName,
307
+ serverName,
308
+ toolName,
309
+ length: fullName.length,
310
+ source
311
+ });
312
+ };
313
+
314
+ const inspectServerMap = (serversMap, source) => {
315
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
316
+ for (const [serverName, cfg] of Object.entries(serversMap)) {
317
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
318
+ if (cfg.disabled === true || cfg.enabled === false) {
319
+ disabledServers.add(serverName);
320
+ continue;
321
+ }
322
+ disabledServers.delete(serverName);
323
+ for (const field of ['tools', 'eagerTools']) {
324
+ if (!Array.isArray(cfg[field])) continue;
325
+ for (const item of cfg[field]) {
326
+ const toolName =
327
+ typeof item === 'string'
328
+ ? item.trim()
329
+ : item && typeof item === 'object' && typeof item.name === 'string'
330
+ ? item.name.trim()
331
+ : '';
332
+ if (toolName) {
333
+ recordViolation(`mcp__${serverName}__${toolName}`, serverName, toolName, source);
334
+ }
335
+ }
336
+ }
337
+ }
338
+ };
339
+
340
+ if (includeClaudeDefaults) {
341
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
342
+ if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
343
+ inspectServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path.replace(/\\/g, '/'));
344
+ }
345
+
346
+ const claudeJson = repoOnly
347
+ ? { parseOk: false, parsed: null }
348
+ : parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
349
+ if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
350
+ inspectServerMap(claudeJson.parsed.mcpServers, '~/.claude.json');
351
+ const projects = claudeJson.parsed.projects;
352
+ if (projects && typeof projects === 'object') {
353
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
354
+ for (const [projKey, projCfg] of Object.entries(projects)) {
355
+ if (!projCfg || typeof projCfg !== 'object') continue;
356
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
357
+ if (normKey === normWs && projCfg.mcpServers) {
358
+ inspectServerMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
359
+ }
360
+ }
361
+ }
362
+ }
363
+ }
364
+
365
+ for (const extraPath of Array.isArray(extraMcpFiles) ? extraMcpFiles : []) {
366
+ if (!extraPath) continue;
367
+ const extraMcp = parseJsoncReadOnly(extraPath);
368
+ if (extraMcp.parseOk && extraMcp.parsed && typeof extraMcp.parsed === 'object') {
369
+ inspectServerMap(
370
+ extraMcp.parsed.mcpServers || extraMcp.parsed.servers || extraMcp.parsed,
371
+ extraMcp.path.replace(/\\/g, '/')
372
+ );
373
+ }
374
+ }
375
+
376
+ for (const mDir of Array.isArray(manifestDirs) ? manifestDirs : []) {
377
+ if (!mDir || !fs.existsSync(mDir)) continue;
378
+ let serverEntries = [];
379
+ try {
380
+ serverEntries = fs.readdirSync(mDir, { withFileTypes: true });
381
+ } catch {
382
+ serverEntries = []; // ignore: unreadable MCP manifest directory
383
+ }
384
+ for (const ent of serverEntries) {
385
+ if (!ent.isDirectory()) continue;
386
+ const serverName = ent.name;
387
+ if (disabledServers.has(serverName)) continue;
388
+ const srvDir = path.join(mDir, serverName);
389
+ let files = [];
390
+ try {
391
+ files = fs.readdirSync(srvDir, { withFileTypes: true });
392
+ } catch {
393
+ continue; // ignore: unreadable MCP server manifest directory
394
+ }
395
+ for (const f of files) {
396
+ if (!f.isFile() || !/\.json$/i.test(f.name)) continue;
397
+ const filePath = path.join(srvDir, f.name);
398
+ const res = parseJsoncReadOnly(filePath);
399
+ if (!res.parseOk || !res.parsed || typeof res.parsed !== 'object') continue;
400
+ const lowerFile = f.name.toLowerCase();
401
+ const isMetaFile = lowerFile === 'server.json' || lowerFile === 'capabilities.json';
402
+ const toolNames = new Set();
403
+ if (!isMetaFile && typeof res.parsed.name === 'string' && res.parsed.name.trim()) {
404
+ toolNames.add(res.parsed.name.trim());
405
+ }
406
+ if (Array.isArray(res.parsed.tools)) {
407
+ for (const item of res.parsed.tools) {
408
+ if (typeof item === 'string' && item.trim()) toolNames.add(item.trim());
409
+ else if (item && typeof item === 'object' && typeof item.name === 'string' && item.name.trim()) {
410
+ toolNames.add(item.name.trim());
411
+ }
412
+ }
413
+ } else if (!isMetaFile && typeof res.parsed.name !== 'string') {
414
+ const stem = f.name.replace(/\.json$/i, '').trim();
415
+ if (stem) toolNames.add(stem);
416
+ }
417
+ const source = filePath.replace(/\\/g, '/');
418
+ for (const toolName of toolNames) {
419
+ recordViolation(`mcp__${serverName}__${toolName}`, serverName, toolName, source);
420
+ }
421
+ }
422
+ }
423
+ }
424
+
425
+ if (Array.isArray(observedToolNames)) {
426
+ for (const rawName of observedToolNames) {
427
+ const name = String(rawName || '').trim();
428
+ const match = name.match(/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/);
429
+ if (!match) continue;
430
+ recordViolation(name, match[1], match[2], 'transcript');
431
+ }
432
+ }
433
+
434
+ return {
435
+ maxLength,
436
+ violations: Array.from(violationsByFullName.values())
437
+ };
438
+ }
439
+
440
+ function collectDisabledMcpServers({
441
+ homeDir = getHomeDir(),
442
+ workspacePath = process.cwd(),
443
+ includeClaudeDefaults = true,
444
+ extraMcpFiles = []
445
+ } = {}) {
446
+ const disabledServers = new Set();
447
+ const trackServerMap = (serversMap) => {
448
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
449
+ for (const [name, cfg] of Object.entries(serversMap)) {
450
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
451
+ if (cfg.disabled === true || cfg.enabled === false) {
452
+ disabledServers.add(name);
453
+ } else {
454
+ disabledServers.delete(name);
455
+ }
456
+ }
457
+ };
458
+
459
+ if (includeClaudeDefaults) {
460
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
461
+ if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
462
+ trackServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed);
463
+ }
464
+
465
+ const claudeJson = homeDir ? parseJsoncReadOnly(path.join(homeDir, '.claude.json')) : { parseOk: false, parsed: null };
466
+ if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
467
+ trackServerMap(claudeJson.parsed.mcpServers);
468
+ const projects = claudeJson.parsed.projects;
469
+ if (projects && typeof projects === 'object') {
470
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
471
+ for (const [projKey, projCfg] of Object.entries(projects)) {
472
+ if (!projCfg || typeof projCfg !== 'object') continue;
473
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
474
+ if (normKey === normWs && projCfg.mcpServers) {
475
+ trackServerMap(projCfg.mcpServers);
476
+ }
477
+ }
478
+ }
479
+ }
480
+ }
481
+
482
+ for (const extraPath of Array.isArray(extraMcpFiles) ? extraMcpFiles : []) {
483
+ if (!extraPath) continue;
484
+ const extraMcp = parseJsoncReadOnly(extraPath);
485
+ if (extraMcp.parseOk && extraMcp.parsed && typeof extraMcp.parsed === 'object') {
486
+ trackServerMap(extraMcp.parsed.mcpServers || extraMcp.parsed.servers || extraMcp.parsed);
487
+ }
488
+ }
489
+ return disabledServers;
490
+ }
491
+
492
+ function hasListChangedFlag(doc) {
493
+ if (!doc || typeof doc !== 'object') return false;
494
+ return Boolean(
495
+ doc.capabilities?.tools?.listChanged === true ||
496
+ doc.result?.capabilities?.tools?.listChanged === true ||
497
+ doc.tools?.listChanged === true ||
498
+ doc.listChanged === true
499
+ );
500
+ }
501
+
502
+ /**
503
+ * BO-MCP-06 (#2812, #1923): Scans MCP configs, optional manifest dirs,
504
+ * and runtime notifications for `tools.listChanged: true` / `notifications/tools/list_changed`,
505
+ * guarding suppression when observed prefix <= 20k tokens.
506
+ */
507
+ export function scanMcpListChangedCapabilities({
508
+ homeDir = getHomeDir(),
509
+ workspacePath = process.cwd(),
510
+ manifestDirs = [],
511
+ runtimeListChangedServers = [],
512
+ maxObservedCachedPrefixTokens = null,
513
+ cachedPrefixThreshold = LIST_CHANGED_PREFIX_THRESHOLD,
514
+ repoOnly = false,
515
+ includeClaudeDefaults = true,
516
+ extraMcpFiles = []
517
+ } = {}) {
518
+ const disabledServers = collectDisabledMcpServers({
519
+ homeDir: repoOnly ? null : homeDir,
520
+ workspacePath,
521
+ includeClaudeDefaults,
522
+ extraMcpFiles
523
+ });
524
+ const flaggedByServer = new Map();
525
+
526
+ const recordFlagged = (serverName, reason, source) => {
527
+ const name = String(serverName || '').trim();
528
+ if (!name || disabledServers.has(name) || flaggedByServer.has(name)) return;
529
+ flaggedByServer.set(name, {
530
+ serverName: name,
531
+ reason,
532
+ source: String(source || '').replace(/\\/g, '/')
533
+ });
534
+ };
535
+
536
+ const inspectConfigMap = (serversMap, source) => {
537
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
538
+ for (const [name, cfg] of Object.entries(serversMap)) {
539
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
540
+ if (cfg.disabled === true || cfg.enabled === false) continue;
541
+ if (hasListChangedFlag(cfg)) {
542
+ recordFlagged(name, 'tools.listChanged: true', source);
543
+ }
544
+ }
545
+ };
546
+
547
+ if (includeClaudeDefaults) {
548
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
549
+ if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
550
+ inspectConfigMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
551
+ }
552
+
553
+ const claudeJson = repoOnly
554
+ ? { parseOk: false, parsed: null }
555
+ : parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
556
+ if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
557
+ inspectConfigMap(claudeJson.parsed.mcpServers, '~/.claude.json');
558
+ const projects = claudeJson.parsed.projects;
559
+ if (projects && typeof projects === 'object') {
560
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
561
+ for (const [projKey, projCfg] of Object.entries(projects)) {
562
+ if (!projCfg || typeof projCfg !== 'object') continue;
563
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
564
+ if (normKey === normWs && projCfg.mcpServers) {
565
+ inspectConfigMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
566
+ }
567
+ }
568
+ }
569
+ }
570
+ }
571
+
572
+ for (const extraPath of Array.isArray(extraMcpFiles) ? extraMcpFiles : []) {
573
+ if (!extraPath) continue;
574
+ const extraMcp = parseJsoncReadOnly(extraPath);
575
+ if (extraMcp.parseOk && extraMcp.parsed && typeof extraMcp.parsed === 'object') {
576
+ inspectConfigMap(
577
+ extraMcp.parsed.mcpServers || extraMcp.parsed.servers || extraMcp.parsed,
578
+ extraMcp.path
579
+ );
580
+ }
581
+ }
582
+
583
+ for (const mDir of Array.isArray(manifestDirs) ? manifestDirs : []) {
584
+ if (!mDir || !fs.existsSync(mDir)) continue;
585
+ let serverEntries = [];
586
+ try {
587
+ serverEntries = fs.readdirSync(mDir, { withFileTypes: true });
588
+ } catch {
589
+ serverEntries = []; // ignore: unreadable MCP manifest directory
590
+ }
591
+ for (const ent of serverEntries) {
592
+ if (!ent.isDirectory()) continue;
593
+ const serverName = ent.name;
594
+ if (disabledServers.has(serverName)) continue;
595
+ const srvDir = path.join(mDir, serverName);
596
+ let files = [];
597
+ try {
598
+ files = fs.readdirSync(srvDir, { withFileTypes: true });
599
+ } catch {
600
+ continue; // ignore: unreadable MCP server manifest directory
601
+ }
602
+ for (const f of files) {
603
+ if (!f.isFile() || !/\.json$/i.test(f.name)) continue;
604
+ const filePath = path.join(srvDir, f.name);
605
+ const res = parseJsoncReadOnly(filePath);
606
+ if (!res.parseOk || !res.parsed || typeof res.parsed !== 'object') continue;
607
+ if (hasListChangedFlag(res.parsed)) {
608
+ recordFlagged(serverName, 'tools.listChanged: true', filePath);
609
+ }
610
+ }
611
+ }
612
+ }
613
+
614
+ if (Array.isArray(runtimeListChangedServers)) {
615
+ for (const item of runtimeListChangedServers) {
616
+ if (typeof item === 'string') {
617
+ recordFlagged(item, 'notifications/tools/list_changed', 'transcript');
618
+ } else if (item && typeof item === 'object' && item.serverName) {
619
+ recordFlagged(item.serverName, item.reason || 'notifications/tools/list_changed', item.source || 'transcript');
620
+ }
621
+ }
622
+ }
623
+
624
+ const flaggedServers = Array.from(flaggedByServer.values());
625
+ const hasTelemetryPrefix =
626
+ typeof maxObservedCachedPrefixTokens === 'number' && Number.isFinite(maxObservedCachedPrefixTokens);
627
+ const suppressedByPrefixGuard =
628
+ flaggedServers.length > 0 && hasTelemetryPrefix && maxObservedCachedPrefixTokens <= cachedPrefixThreshold;
629
+ const status = flaggedServers.length === 0 ? 'pass' : suppressedByPrefixGuard ? 'info' : 'warn';
630
+
631
+ return {
632
+ status,
633
+ flaggedServers,
634
+ suppressedByPrefixGuard,
635
+ maxObservedCachedPrefixTokens: hasTelemetryPrefix ? maxObservedCachedPrefixTokens : null,
636
+ cachedPrefixThreshold
637
+ };
638
+ }
639
+
640
+ /**
641
+ * BO-MCP-09 (#104791, #98438): Estimates per-subagent `mcp_instructions_delta` tax
642
+ * when > 5 connected MCP servers coexist with spawned or defined subagents.
643
+ */
644
+ export function estimateSubagentMcpInstructionsTax({
645
+ connectedServerNames = [],
646
+ subagentCount = 0,
647
+ observedMcpInstructionsDeltaChars = 0,
648
+ minServers = SUBAGENT_MCP_MIN_SERVERS,
649
+ tokensPerServerFallback = DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER
650
+ } = {}) {
651
+ const uniqueServers = [];
652
+ const seen = new Set();
653
+ for (const raw of Array.isArray(connectedServerNames) ? connectedServerNames : []) {
654
+ const name = String(raw || '').trim();
655
+ if (!name || seen.has(name)) continue;
656
+ seen.add(name);
657
+ uniqueServers.push(name);
658
+ }
659
+
660
+ const connectedServerCount = uniqueServers.length;
661
+ const count = Math.max(0, Number(subagentCount) || 0);
662
+ const triggered = connectedServerCount > minServers && count > 0;
663
+
664
+ if (!triggered) {
665
+ return {
666
+ status: 'pass',
667
+ triggered: false,
668
+ connectedServerCount,
669
+ minServers,
670
+ subagentCount: count,
671
+ perSubagentTokensEst: 0,
672
+ totalTaxTokens: 0,
673
+ isEstimated: true
674
+ };
675
+ }
676
+
677
+ const observedChars = Number(observedMcpInstructionsDeltaChars) || 0;
678
+ const isEstimated = !(observedChars > 0);
679
+ const perSubagentTokensEst =
680
+ observedChars > 0 ? Math.ceil(observedChars / 4) : connectedServerCount * tokensPerServerFallback;
681
+
682
+ return {
683
+ status: 'warn',
684
+ triggered: true,
685
+ connectedServerCount,
686
+ minServers,
687
+ subagentCount: count,
688
+ perSubagentTokensEst,
689
+ totalTaxTokens: perSubagentTokensEst * count,
690
+ isEstimated
691
+ };
692
+ }
693
+
694
+
695
+ function collectAntigravityCommandSources({ cwd, projectHooks, userHooks, acpAgentCommand = null } = {}) {
696
+ const sources = [];
697
+ if (typeof acpAgentCommand === 'string' && acpAgentCommand.trim()) {
698
+ sources.push({ source: 'cli:acpAgentCommand', cmd: acpAgentCommand.trim() });
699
+ }
700
+ const pkg = parseJsoncReadOnly(path.join(cwd, 'package.json'));
701
+ if (pkg.parseOk && pkg.parsed?.scripts && typeof pkg.parsed.scripts === 'object') {
702
+ for (const [name, cmd] of Object.entries(pkg.parsed.scripts)) {
703
+ if (typeof cmd === 'string' && cmd.trim()) {
704
+ sources.push({ source: `package.json#scripts.${name}`, cmd: cmd.trim() });
705
+ }
706
+ }
707
+ }
708
+ for (const hookLayer of [projectHooks, userHooks]) {
709
+ const hooksObj = hookLayer?.parsed?.hooks;
710
+ const hookFile = String(hookLayer?.path || 'hooks.json').replace(/\\/g, '/');
711
+ if (!hooksObj || typeof hooksObj !== 'object') continue;
712
+ for (const entries of Object.values(hooksObj)) {
713
+ if (!Array.isArray(entries)) continue;
714
+ for (const ent of entries) {
715
+ const list = Array.isArray(ent?.hooks) ? ent.hooks : [ent];
716
+ for (const item of list) {
717
+ if (typeof item?.command === 'string' && item.command.trim()) {
718
+ sources.push({ source: hookFile, cmd: item.command.trim() });
719
+ }
720
+ }
721
+ }
722
+ }
723
+ }
724
+ return sources;
725
+ }
726
+
727
+ /**
728
+ * Runs Turn-0 startup config, rules-count, and MCP config audit for Google Antigravity.
729
+ */
730
+
731
+ export {
732
+ collectClaudeMcpServers,
733
+ evaluateClaudeEagerMcpGate,
734
+ collectAntigravityCommandSources
735
+ };