burnoff 1.0.0 → 1.2.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 (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
@@ -0,0 +1,2824 @@
1
+ /**
2
+ * @file src/cli/startup-audit.mjs
3
+ * Standalone Claude Code Turn-0 startup config, rules-count, and eager-only MCP auditor
4
+ * (`burnoff audit --startup`).
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { StringDecoder } from 'node:string_decoder';
10
+ import {
11
+ getHomeDir,
12
+ canonicalizePath,
13
+ resolveClaudeConfigPaths,
14
+ resolveAntigravityConfigPaths
15
+ } from '../config/paths.mjs';
16
+ import { resolveModelRateCard } from '../config/pricing.mjs';
17
+
18
+ export const CALIBRATION_MANIFEST = Object.freeze({
19
+ claudeCodeTurn0: Object.freeze({
20
+ artifactTool: Object.freeze({
21
+ tokens: 8500,
22
+ measuredOnVersion: '2.1.325',
23
+ measuredDate: '2026-11-27',
24
+ source: 'est.'
25
+ }),
26
+ bundledSkills: Object.freeze({
27
+ tokens: 3500,
28
+ measuredOnVersion: '2.1.325',
29
+ measuredDate: '2026-11-27',
30
+ source: 'est.'
31
+ }),
32
+ workflows: Object.freeze({
33
+ tokens: 2500,
34
+ measuredOnVersion: '2.1.325',
35
+ measuredDate: '2026-11-27',
36
+ source: 'est.'
37
+ }),
38
+ chromeTools: Object.freeze({
39
+ tokens: 12000,
40
+ measuredOnVersion: '2.1.325',
41
+ measuredDate: '2026-11-27',
42
+ source: 'est.'
43
+ })
44
+ })
45
+ });
46
+
47
+ export const RULES_THRESHOLDS = Object.freeze({
48
+ cautionRuleCount: 100,
49
+ ifScaleCliffRuleCount: 200,
50
+ tokenWarning: 8000
51
+ });
52
+
53
+ export const LIST_CHANGED_PREFIX_THRESHOLD = 20000;
54
+ export const SUBAGENT_MCP_MIN_SERVERS = 5;
55
+ export const DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER = 600;
56
+ export const IDLE_COMPACTION_MIN_VERSION = '2.1.290';
57
+ export const DEFAULT_IDLE_COMPACT_MIN_TOKENS = 200000;
58
+ export const SDK_CLI_QUOTA_MULTIPLIER_HEURISTIC = 1.8;
59
+
60
+ export const VERIFIED_CLAUDE_FLAGS = Object.freeze([
61
+ '--chrome',
62
+ '--no-chrome',
63
+ '--disallowedTools',
64
+ '--settings',
65
+ '--mcp-config',
66
+ '--strict-mcp-config',
67
+ '--model'
68
+ ]);
69
+
70
+ export const FORBIDDEN_WORKAROUND_FLAGS = Object.freeze(['--tools']);
71
+
72
+ const VERIFIED_SET = new Set(VERIFIED_CLAUDE_FLAGS);
73
+ const FORBIDDEN_SET = new Set(FORBIDDEN_WORKAROUND_FLAGS);
74
+ const CHARS_PER_TOKEN = 4;
75
+
76
+ /**
77
+ * Formats a JSON object as a shell-safe CLI argument for win32 PowerShell or POSIX shells.
78
+ */
79
+ export function formatJsonCliArg(obj, platform = process.platform) {
80
+ const json = JSON.stringify(obj);
81
+ if (platform === 'win32') {
82
+ return `'${json.replace(/"/g, '\\"')}'`;
83
+ }
84
+ return `'${json.replace(/'/g, "'\\''")}'`;
85
+ }
86
+
87
+ /**
88
+ * Validates a `claude ...` command against verified flags, forbidden `--tools`, and zero em dashes.
89
+ */
90
+ export function validateClaudeCliCommand(cmd) {
91
+ const str = String(cmd || '');
92
+ const hasEmDash = str.includes('\u2014');
93
+ const stripped = str
94
+ .replace(/'(?:\\.|[^'\\])*'/g, ' ')
95
+ .replace(/"(?:\\.|[^"\\])*"/g, ' ');
96
+
97
+ const flags = [];
98
+ const unverifiedFlags = [];
99
+ const forbiddenFlags = [];
100
+
101
+ for (const m of stripped.matchAll(/(?:^|\s)(--[A-Za-z0-9-]+)(?:=|\s|$)/g)) {
102
+ const flag = m[1];
103
+ flags.push(flag);
104
+ if (FORBIDDEN_SET.has(flag)) {
105
+ forbiddenFlags.push(flag);
106
+ } else if (!VERIFIED_SET.has(flag)) {
107
+ unverifiedFlags.push(flag);
108
+ }
109
+ }
110
+
111
+ return {
112
+ ok: unverifiedFlags.length === 0 && forbiddenFlags.length === 0 && !hasEmDash,
113
+ flags,
114
+ unverifiedFlags,
115
+ forbiddenFlags,
116
+ hasEmDash
117
+ };
118
+ }
119
+
120
+ function buildClaudeCliCommand(parts = [], { platform = process.platform } = {}) {
121
+ const tokens = ['claude'];
122
+ for (const part of parts) {
123
+ if (part === null || part === undefined) continue;
124
+ if (typeof part === 'object' && !Array.isArray(part)) {
125
+ tokens.push(formatJsonCliArg(part, platform));
126
+ } else {
127
+ const s = String(part).trim();
128
+ if (!s) continue;
129
+ if (FORBIDDEN_SET.has(s)) {
130
+ throw new Error(`Forbidden Claude CLI flag "${s}" cannot be emitted in fix templates.`);
131
+ }
132
+ if (s.startsWith('--') && !VERIFIED_SET.has(s)) {
133
+ throw new Error(`Unverified Claude CLI flag "${s}" is not in VERIFIED_CLAUDE_FLAGS.`);
134
+ }
135
+ tokens.push(s);
136
+ }
137
+ }
138
+ const cmd = tokens.join(' ');
139
+ const check = validateClaudeCliCommand(cmd);
140
+ if (!check.ok) {
141
+ throw new Error(`Invalid Claude CLI command: ${cmd}`);
142
+ }
143
+ return cmd;
144
+ }
145
+
146
+ /**
147
+ * Inspects raw JSON/JSONC text outside string literals to detect non-strict JSON syntax
148
+ * (`//` line comments, `/* ... *\/` block comments, or trailing commas).
149
+ */
150
+ export function inspectJsoncSyntax(raw) {
151
+ const input = String(raw ?? '');
152
+ let out = '';
153
+ let inString = false;
154
+ let escaped = false;
155
+ let inLineComment = false;
156
+ let inBlockComment = false;
157
+ let hasLineComment = false;
158
+ let hasBlockComment = false;
159
+ let hasTrailingComma = false;
160
+
161
+ for (let i = 0; i < input.length; i++) {
162
+ const ch = input[i];
163
+ const next = input[i + 1];
164
+
165
+ if (inLineComment) {
166
+ if (ch === '\n' || ch === '\r') {
167
+ inLineComment = false;
168
+ out += ch;
169
+ }
170
+ continue;
171
+ }
172
+
173
+ if (inBlockComment) {
174
+ if (ch === '*' && next === '/') {
175
+ inBlockComment = false;
176
+ i += 1;
177
+ } else if (ch === '\n' || ch === '\r') {
178
+ out += ch;
179
+ }
180
+ continue;
181
+ }
182
+
183
+ if (inString) {
184
+ out += ch;
185
+ if (escaped) {
186
+ escaped = false;
187
+ } else if (ch === '\\') {
188
+ escaped = true;
189
+ } else if (ch === '"') {
190
+ inString = false;
191
+ }
192
+ continue;
193
+ }
194
+
195
+ if (ch === '"') {
196
+ inString = true;
197
+ out += ch;
198
+ continue;
199
+ }
200
+
201
+ if (ch === '/' && next === '/') {
202
+ hasLineComment = true;
203
+ inLineComment = true;
204
+ i += 1;
205
+ continue;
206
+ }
207
+
208
+ if (ch === '/' && next === '*') {
209
+ hasBlockComment = true;
210
+ inBlockComment = true;
211
+ i += 1;
212
+ continue;
213
+ }
214
+
215
+ out += ch;
216
+ }
217
+
218
+ inString = false;
219
+ escaped = false;
220
+ for (let i = 0; i < out.length; i++) {
221
+ const ch = out[i];
222
+ if (inString) {
223
+ if (escaped) escaped = false;
224
+ else if (ch === '\\') escaped = true;
225
+ else if (ch === '"') inString = false;
226
+ continue;
227
+ }
228
+ if (ch === '"') {
229
+ inString = true;
230
+ continue;
231
+ }
232
+ if (ch === ',') {
233
+ let j = i + 1;
234
+ while (j < out.length && /\s/.test(out[j])) j++;
235
+ if (out[j] === '}' || out[j] === ']') {
236
+ hasTrailingComma = true;
237
+ break;
238
+ }
239
+ }
240
+ }
241
+
242
+ return {
243
+ hasLineComment,
244
+ hasBlockComment,
245
+ hasTrailingComma,
246
+ hasNonStrictSyntax: hasLineComment || hasBlockComment || hasTrailingComma
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Strips JSONC comments (`//` and `/* ... *\/`) and trailing commas outside strings.
252
+ */
253
+ export function parseJsoncString(raw) {
254
+ const input = String(raw ?? '');
255
+ let out = '';
256
+ let inString = false;
257
+ let escaped = false;
258
+ let inLineComment = false;
259
+ let inBlockComment = false;
260
+
261
+ for (let i = 0; i < input.length; i++) {
262
+ const ch = input[i];
263
+ const next = input[i + 1];
264
+
265
+ if (inLineComment) {
266
+ if (ch === '\n' || ch === '\r') {
267
+ inLineComment = false;
268
+ out += ch;
269
+ }
270
+ continue;
271
+ }
272
+
273
+ if (inBlockComment) {
274
+ if (ch === '*' && next === '/') {
275
+ inBlockComment = false;
276
+ i += 1;
277
+ } else if (ch === '\n' || ch === '\r') {
278
+ out += ch;
279
+ }
280
+ continue;
281
+ }
282
+
283
+ if (inString) {
284
+ out += ch;
285
+ if (escaped) {
286
+ escaped = false;
287
+ } else if (ch === '\\') {
288
+ escaped = true;
289
+ } else if (ch === '"') {
290
+ inString = false;
291
+ }
292
+ continue;
293
+ }
294
+
295
+ if (ch === '"') {
296
+ inString = true;
297
+ out += ch;
298
+ continue;
299
+ }
300
+
301
+ if (ch === '/' && next === '/') {
302
+ inLineComment = true;
303
+ i += 1;
304
+ continue;
305
+ }
306
+
307
+ if (ch === '/' && next === '*') {
308
+ inBlockComment = true;
309
+ i += 1;
310
+ continue;
311
+ }
312
+
313
+ out += ch;
314
+ }
315
+
316
+ let cleaned = '';
317
+ inString = false;
318
+ escaped = false;
319
+ for (let i = 0; i < out.length; i++) {
320
+ const ch = out[i];
321
+ if (inString) {
322
+ cleaned += ch;
323
+ if (escaped) escaped = false;
324
+ else if (ch === '\\') escaped = true;
325
+ else if (ch === '"') inString = false;
326
+ continue;
327
+ }
328
+ if (ch === '"') {
329
+ inString = true;
330
+ cleaned += ch;
331
+ continue;
332
+ }
333
+ if (ch === ',') {
334
+ let j = i + 1;
335
+ while (j < out.length && /\s/.test(out[j])) j++;
336
+ if (out[j] === '}' || out[j] === ']') {
337
+ continue;
338
+ }
339
+ }
340
+ cleaned += ch;
341
+ }
342
+
343
+ return JSON.parse(cleaned);
344
+ }
345
+
346
+ /**
347
+ * Reads and parses a JSON/JSONC file strictly read-only without throwing.
348
+ */
349
+ export function parseJsoncReadOnly(filePath) {
350
+ if (!filePath || !fs.existsSync(filePath)) {
351
+ return {
352
+ path: filePath || '',
353
+ exists: false,
354
+ parseOk: false,
355
+ parsed: null,
356
+ strictJsonValid: false,
357
+ strict_json_syntax_warning: null,
358
+ error: null
359
+ };
360
+ }
361
+ try {
362
+ const raw = fs.readFileSync(filePath, 'utf8');
363
+ if (!raw || !raw.trim()) {
364
+ return {
365
+ path: filePath,
366
+ exists: true,
367
+ parseOk: false,
368
+ parsed: null,
369
+ strictJsonValid: false,
370
+ strict_json_syntax_warning: null,
371
+ error: 'empty file'
372
+ };
373
+ }
374
+ const parsed = parseJsoncString(raw);
375
+ const syntax = inspectJsoncSyntax(raw);
376
+ const displayPath = String(filePath).replace(/\\/g, '/');
377
+ const strictJsonValid = !syntax.hasNonStrictSyntax;
378
+ const strict_json_syntax_warning = syntax.hasNonStrictSyntax
379
+ ? `Strict JSON warning: comments or trailing commas in ${displayPath} fail harnesses using strict JSON.parse(). Strip comments for cross-tool portability.`
380
+ : null;
381
+ return {
382
+ path: filePath,
383
+ exists: true,
384
+ parseOk: true,
385
+ parsed,
386
+ strictJsonValid,
387
+ strict_json_syntax_warning,
388
+ error: null
389
+ };
390
+ } catch (err) {
391
+ return {
392
+ path: filePath,
393
+ exists: true,
394
+ parseOk: false,
395
+ parsed: null,
396
+ strictJsonValid: false,
397
+ strict_json_syntax_warning: null,
398
+ error: err?.message || 'parse error'
399
+ };
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Counts discrete imperative bullets and numbered rules in markdown, ignoring fenced code blocks
405
+ * and markdown table separator rows.
406
+ */
407
+ export function countDiscreteRules(markdown) {
408
+ const lines = String(markdown || '').split(/\r?\n/);
409
+ let inFence = false;
410
+ let fenceChar = '';
411
+ let count = 0;
412
+
413
+ for (const line of lines) {
414
+ const fenceMatch = line.match(/^\s*(```+|~~~+)/);
415
+ if (fenceMatch) {
416
+ const markerChar = fenceMatch[1][0];
417
+ if (!inFence) {
418
+ inFence = true;
419
+ fenceChar = markerChar;
420
+ } else if (markerChar === fenceChar) {
421
+ inFence = false;
422
+ fenceChar = '';
423
+ }
424
+ continue;
425
+ }
426
+ if (inFence) continue;
427
+ if (/^\s*\|?(?:\s*:?-+:?\s*\|)+\s*$/.test(line)) continue;
428
+ if (/^\s*(?:[-*+]|\d+\.)\s+\S/.test(line)) {
429
+ count += 1;
430
+ }
431
+ }
432
+ return count;
433
+ }
434
+
435
+ function compareSemver(a, b) {
436
+ const parse = (v) => {
437
+ const m = String(v || '').trim().match(/^v?(\d+)\.(\d+)\.(\d+)/);
438
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
439
+ };
440
+ const pa = parse(a);
441
+ const pb = parse(b);
442
+ if (!pa || !pb) return null;
443
+ for (let i = 0; i < 3; i++) {
444
+ if (pa[i] < pb[i]) return -1;
445
+ if (pa[i] > pb[i]) return 1;
446
+ }
447
+ return 0;
448
+ }
449
+
450
+ function auditRulesFiles(filePaths = []) {
451
+ const seen = new Set();
452
+ const files = [];
453
+ let totalTokensEst = 0;
454
+ let totalRuleCount = 0;
455
+
456
+ for (const fp of filePaths) {
457
+ if (!fp || !fs.existsSync(fp)) continue;
458
+ let dedupeKey = canonicalizePath(fp);
459
+ try {
460
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
461
+ } catch {
462
+ // ignore: fallback to canonicalized path when realpath fails
463
+ }
464
+ if (seen.has(dedupeKey)) continue;
465
+ seen.add(dedupeKey);
466
+
467
+ try {
468
+ const text = fs.readFileSync(fp, 'utf8');
469
+ const chars = text.length;
470
+ const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
471
+ const ruleCount = countDiscreteRules(text);
472
+ files.push({
473
+ path: String(fp).replace(/\\/g, '/'),
474
+ chars,
475
+ tokensEst,
476
+ ruleCount
477
+ });
478
+ totalTokensEst += tokensEst;
479
+ totalRuleCount += ruleCount;
480
+ } catch {
481
+ // ignore: unreadable rules markdown file
482
+ }
483
+ }
484
+
485
+ let status = 'pass';
486
+ const advisories = [];
487
+ if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
488
+ status = 'warn';
489
+ advisories.push(
490
+ `IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} rules); move domain rules into on-demand SKILL.md files.`
491
+ );
492
+ } else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
493
+ status = 'caution';
494
+ advisories.push(
495
+ `Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} rules).`
496
+ );
497
+ }
498
+ if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
499
+ status = 'warn';
500
+ advisories.push(
501
+ `Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across active rules files).`
502
+ );
503
+ }
504
+
505
+ return { files, totalTokensEst, totalRuleCount, status, advisories };
506
+ }
507
+
508
+ function collectJsonlFiles(rootDir, cutoffMs) {
509
+ const out = [];
510
+ if (!rootDir || !fs.existsSync(rootDir)) return out;
511
+ const walk = (dir) => {
512
+ let entries = [];
513
+ try {
514
+ entries = fs.readdirSync(dir, { withFileTypes: true });
515
+ } catch {
516
+ return; // ignore: unreadable projects subdirectory
517
+ }
518
+ for (const ent of entries) {
519
+ const full = path.join(dir, ent.name);
520
+ if (ent.isDirectory()) {
521
+ walk(full);
522
+ } else if (ent.isFile() && ent.name.endsWith('.jsonl')) {
523
+ try {
524
+ const st = fs.statSync(full);
525
+ if (!cutoffMs || st.mtimeMs >= cutoffMs) {
526
+ out.push({ path: full, mtimeMs: st.mtimeMs });
527
+ }
528
+ } catch {
529
+ // ignore: unreadable JSONL stat
530
+ }
531
+ }
532
+ }
533
+ };
534
+ walk(rootDir);
535
+ out.sort((a, b) => b.mtimeMs - a.mtimeMs);
536
+ return out;
537
+ }
538
+
539
+ export const DEFAULT_TELEMETRY_MAX_FILES = 50;
540
+ export const DEFAULT_TELEMETRY_MAX_BYTES = 16 * 1024 * 1024;
541
+ const TELEMETRY_READ_CHUNK_BYTES = 64 * 1024;
542
+
543
+ function scanJsonlFileChunked(filePath, { maxBytesRemaining = Infinity, onLine } = {}) {
544
+ let fd = null;
545
+ let bytesRead = 0;
546
+ let truncated = false;
547
+ const decoder = new StringDecoder('utf8');
548
+ let carry = '';
549
+ try {
550
+ fd = fs.openSync(filePath, 'r');
551
+ const buf = Buffer.allocUnsafe(TELEMETRY_READ_CHUNK_BYTES);
552
+ while (bytesRead < maxBytesRemaining) {
553
+ const toRead = Math.min(TELEMETRY_READ_CHUNK_BYTES, Math.max(0, maxBytesRemaining - bytesRead));
554
+ if (toRead <= 0) {
555
+ truncated = true;
556
+ break;
557
+ }
558
+ const n = fs.readSync(fd, buf, 0, toRead, null);
559
+ if (n <= 0) break;
560
+ bytesRead += n;
561
+ const chunkText = carry + decoder.write(buf.subarray(0, n));
562
+ const parts = chunkText.split(/\r?\n/);
563
+ carry = parts.pop() || '';
564
+ for (const line of parts) {
565
+ if (line.trim()) onLine(line);
566
+ }
567
+ if (bytesRead >= maxBytesRemaining) {
568
+ truncated = true;
569
+ break;
570
+ }
571
+ }
572
+ if (!truncated) {
573
+ const tail = carry + decoder.end();
574
+ if (tail.trim()) onLine(tail);
575
+ }
576
+ } catch {
577
+ // ignore: unreadable JSONL transcript
578
+ } finally {
579
+ if (fd !== null) {
580
+ try {
581
+ fs.closeSync(fd);
582
+ } catch {
583
+ // ignore: fd close cleanup
584
+ }
585
+ }
586
+ }
587
+ return { bytesRead, truncated };
588
+ }
589
+
590
+ function scanClaudeTelemetrySummary({
591
+ projectsDir,
592
+ days = 7,
593
+ nowMs = Date.now(),
594
+ maxFiles = DEFAULT_TELEMETRY_MAX_FILES,
595
+ maxTotalBytes = DEFAULT_TELEMETRY_MAX_BYTES
596
+ } = {}) {
597
+ const cutoffMs = days > 0 ? nowMs - days * 86_400_000 : 0;
598
+ const files = collectJsonlFiles(projectsDir, cutoffMs);
599
+ const fileCap = Math.max(1, Number(maxFiles) || DEFAULT_TELEMETRY_MAX_FILES);
600
+ const byteCap = Math.max(1024, Number(maxTotalBytes) || DEFAULT_TELEMETRY_MAX_BYTES);
601
+ const filesToScan = files.slice(0, fileCap);
602
+ let scanTruncated = files.length > filesToScan.length;
603
+ let bytesScanned = 0;
604
+ let sessionsScanned = 0;
605
+
606
+ let latestVersion = null;
607
+ let latestVersionMtime = -1;
608
+ const entrypoints = new Set();
609
+ let browserToolCalls7d = 0;
610
+ let artifactCalls7d = 0;
611
+ const mcpToolCalls7d = {};
612
+ const schemaTokensByServer = {};
613
+ const observedMcpToolNames = new Set();
614
+ let maxCachedPrefixTokens = null;
615
+ const runtimeListChangedServers = new Set();
616
+ let subagentSpawns7d = 0;
617
+ let sidechainTurns7d = 0;
618
+ let observedMcpInstructionsDeltaChars = 0;
619
+ const observedModels = new Set();
620
+ let sdkCliSessions7d = 0;
621
+
622
+ for (const fileInfo of filesToScan) {
623
+ if (bytesScanned >= byteCap) {
624
+ scanTruncated = true;
625
+ break;
626
+ }
627
+ let fileHasSdkCli = false;
628
+ const res = scanJsonlFileChunked(fileInfo.path, {
629
+ maxBytesRemaining: byteCap - bytesScanned,
630
+ onLine: (line) => {
631
+ let row;
632
+ try {
633
+ row = JSON.parse(line);
634
+ } catch {
635
+ return; // ignore: partial trailing JSONL line
636
+ }
637
+ if (row.version && fileInfo.mtimeMs >= latestVersionMtime) {
638
+ latestVersion = String(row.version).trim();
639
+ latestVersionMtime = fileInfo.mtimeMs;
640
+ }
641
+ if (row.entrypoint) {
642
+ const ep = String(row.entrypoint).trim();
643
+ entrypoints.add(ep);
644
+ if (ep === 'sdk-cli') fileHasSdkCli = true;
645
+ }
646
+ if (row.isSidechain === true) {
647
+ sidechainTurns7d += 1;
648
+ }
649
+ if (row.type === 'assistant') {
650
+ if (row.message?.model) {
651
+ observedModels.add(String(row.message.model).trim());
652
+ }
653
+ const u = row.message?.usage;
654
+ if (
655
+ u &&
656
+ typeof u === 'object' &&
657
+ (u.cache_read_input_tokens !== undefined || u.cache_creation_input_tokens !== undefined)
658
+ ) {
659
+ const prefixTok = Number(u.cache_read_input_tokens || 0) + Number(u.cache_creation_input_tokens || 0);
660
+ if (Number.isFinite(prefixTok) && prefixTok >= 0) {
661
+ maxCachedPrefixTokens = maxCachedPrefixTokens === null ? prefixTok : Math.max(maxCachedPrefixTokens, prefixTok);
662
+ }
663
+ }
664
+ if (Array.isArray(row.message?.content)) {
665
+ for (const blk of row.message.content) {
666
+ if (blk?.type !== 'tool_use' || !blk.name) continue;
667
+ const toolName = String(blk.name);
668
+ if (toolName === 'Artifact') artifactCalls7d += 1;
669
+ if (toolName === 'Agent' || toolName === 'Task' || toolName === 'invoke_subagent') {
670
+ subagentSpawns7d += 1;
671
+ }
672
+ if (/^mcp__claude-in-chrome__/i.test(toolName) || /(?:^|__)chrome(?:__|$)/i.test(toolName)) {
673
+ browserToolCalls7d += 1;
674
+ }
675
+ if (toolName.startsWith('mcp__')) {
676
+ observedMcpToolNames.add(toolName);
677
+ }
678
+ const mcpMatch = toolName.match(/^mcp__([^_]+)__/);
679
+ if (mcpMatch) {
680
+ const srv = mcpMatch[1];
681
+ mcpToolCalls7d[srv] = (mcpToolCalls7d[srv] || 0) + 1;
682
+ }
683
+ }
684
+ }
685
+ }
686
+ const sysText =
687
+ typeof row.text === 'string'
688
+ ? row.text
689
+ : typeof row.content === 'string'
690
+ ? row.content
691
+ : typeof row.attachment?.text === 'string'
692
+ ? row.attachment.text
693
+ : typeof row.attachment?.content === 'string'
694
+ ? row.attachment.content
695
+ : '';
696
+ if (
697
+ row.method === 'notifications/tools/list_changed' ||
698
+ row.subtype === 'mcp_tools_list_changed' ||
699
+ ((row.type === 'system' || row.type === 'attachment') && sysText.includes('notifications/tools/list_changed'))
700
+ ) {
701
+ const srvName = String(row.server || row.serverName || row.params?.server || 'unknown').trim() || 'unknown';
702
+ runtimeListChangedServers.add(srvName);
703
+ }
704
+ if (
705
+ (row.type === 'attachment' && row.attachment?.type === 'mcp_instructions_delta') ||
706
+ row.subtype === 'mcp_instructions_delta'
707
+ ) {
708
+ const payload = row.attachment?.content ?? row.attachment?.text ?? row.content ?? row.text ?? row.attachment ?? row;
709
+ const charLen = typeof payload === 'string' ? payload.length : JSON.stringify(payload || '').length;
710
+ if (charLen > observedMcpInstructionsDeltaChars) {
711
+ observedMcpInstructionsDeltaChars = charLen;
712
+ }
713
+ }
714
+ if (row.type === 'tools-used') {
715
+ if (Array.isArray(row.tools)) {
716
+ for (const t of row.tools) {
717
+ const name = typeof t === 'string' ? t : t && typeof t === 'object' ? t.name : null;
718
+ if (typeof name === 'string' && name.startsWith('mcp__')) {
719
+ observedMcpToolNames.add(name);
720
+ }
721
+ }
722
+ }
723
+ if (row.serverSchemas && typeof row.serverSchemas === 'object') {
724
+ for (const [srv, tok] of Object.entries(row.serverSchemas)) {
725
+ const n = Number(tok);
726
+ if (Number.isFinite(n) && n > 0) schemaTokensByServer[srv] = n;
727
+ }
728
+ }
729
+ }
730
+ }
731
+ });
732
+ sessionsScanned += 1;
733
+ bytesScanned += res.bytesRead;
734
+ if (res.truncated) scanTruncated = true;
735
+ if (fileHasSdkCli) sdkCliSessions7d += 1;
736
+ }
737
+
738
+ return {
739
+ sessionsScanned,
740
+ bytesScanned,
741
+ scanTruncated,
742
+ claudeCodeVersion: latestVersion,
743
+ entrypoints: Array.from(entrypoints),
744
+ browserToolCalls7d,
745
+ artifactCalls7d,
746
+ mcpToolCalls7d,
747
+ schemaTokensByServer,
748
+ observedMcpToolNames: Array.from(observedMcpToolNames),
749
+ maxCachedPrefixTokens,
750
+ runtimeListChangedServers: Array.from(runtimeListChangedServers),
751
+ subagentSpawns7d,
752
+ sidechainTurns7d,
753
+ observedMcpInstructionsDeltaChars,
754
+ observedModels: Array.from(observedModels),
755
+ sdkCliSessions7d
756
+ };
757
+ }
758
+
759
+ /**
760
+ * Strictly read-only scan of `~/.claude/agents/*.md` and `<cwd>/.claude/agents/*.md`
761
+ * to count custom subagent definitions and narrow frontmatter `tools:` allowlists.
762
+ */
763
+ export function scanClaudeCustomAgentSpecs({ homeDir = getHomeDir(), cwd = process.cwd() } = {}) {
764
+ const dirs = [
765
+ path.join(homeDir, '.claude', 'agents'),
766
+ path.join(cwd, '.claude', 'agents')
767
+ ];
768
+ const seen = new Set();
769
+ const agents = [];
770
+ let narrowToolsAgents = 0;
771
+
772
+ for (const dir of dirs) {
773
+ if (!fs.existsSync(dir)) continue;
774
+ let entries = [];
775
+ try {
776
+ entries = fs.readdirSync(dir, { withFileTypes: true });
777
+ } catch {
778
+ continue; // ignore: unreadable Claude agents directory
779
+ }
780
+ for (const ent of entries) {
781
+ if (!ent.isFile() || !/\.md$/i.test(ent.name)) continue;
782
+ const fullPath = path.join(dir, ent.name);
783
+ let key = canonicalizePath(fullPath);
784
+ try {
785
+ key = canonicalizePath(fs.realpathSync(fullPath));
786
+ } catch {
787
+ // ignore: fallback to canonicalized path when realpath fails
788
+ }
789
+ if (seen.has(key)) continue;
790
+ seen.add(key);
791
+
792
+ let hasNarrowTools = false;
793
+ try {
794
+ const raw = fs.readFileSync(fullPath, 'utf8');
795
+ const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
796
+ if (fmMatch && /(?:^|\r?\n)tools\s*:/i.test(fmMatch[1])) {
797
+ hasNarrowTools = true;
798
+ narrowToolsAgents += 1;
799
+ }
800
+ } catch {
801
+ // ignore: unreadable custom agent markdown file
802
+ }
803
+ agents.push({
804
+ name: ent.name.replace(/\.md$/i, ''),
805
+ path: fullPath.replace(/\\/g, '/'),
806
+ hasNarrowTools
807
+ });
808
+ }
809
+ }
810
+
811
+ return {
812
+ totalAgents: agents.length,
813
+ narrowToolsAgents,
814
+ agents
815
+ };
816
+ }
817
+
818
+ function detectAnthropicSdkMarkers(cwd) {
819
+ const pkg = parseJsoncReadOnly(path.join(cwd, 'package.json'));
820
+ if (pkg.parseOk && pkg.parsed && typeof pkg.parsed === 'object') {
821
+ const allDeps = {
822
+ ...(pkg.parsed.dependencies || {}),
823
+ ...(pkg.parsed.devDependencies || {}),
824
+ ...(pkg.parsed.peerDependencies || {})
825
+ };
826
+ for (const depName of Object.keys(allDeps)) {
827
+ if (depName === '@anthropic-ai/sdk' || /^@anthropic-ai\//i.test(depName) || /^claude-/i.test(depName)) {
828
+ return true;
829
+ }
830
+ }
831
+ }
832
+ for (const docName of ['README.md', 'readme.md']) {
833
+ const fp = path.join(cwd, docName);
834
+ if (!fs.existsSync(fp)) continue;
835
+ try {
836
+ const head = fs.readFileSync(fp, 'utf8').slice(0, 16384);
837
+ if (/@anthropic-ai\/sdk|cache_control|prompt caching/i.test(head)) return true;
838
+ } catch {
839
+ // ignore: unreadable README.md
840
+ }
841
+ }
842
+ return false;
843
+ }
844
+
845
+ function collectClaudeMcpServers({ workspacePath, claudeJsonParsed }) {
846
+ const servers = new Map();
847
+ const addMap = (serversMap, sourceFile) => {
848
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
849
+ for (const [name, cfg] of Object.entries(serversMap)) {
850
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
851
+ if (cfg.disabled === true || cfg.enabled === false) continue;
852
+ const hint = Number(cfg.estimatedTokens ?? cfg.schemaTokens ?? cfg.tokenCount ?? 0);
853
+ servers.set(name, {
854
+ name,
855
+ sourceFile,
856
+ hintTokens: Number.isFinite(hint) && hint > 0 ? hint : 0
857
+ });
858
+ }
859
+ };
860
+
861
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
862
+ if (projMcp.parseOk && projMcp.parsed) {
863
+ addMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
864
+ }
865
+
866
+ if (claudeJsonParsed && typeof claudeJsonParsed === 'object') {
867
+ addMap(claudeJsonParsed.mcpServers, '~/.claude.json');
868
+ const projects = claudeJsonParsed.projects;
869
+ if (projects && typeof projects === 'object') {
870
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
871
+ for (const [projKey, projCfg] of Object.entries(projects)) {
872
+ if (!projCfg || typeof projCfg !== 'object') continue;
873
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
874
+ if (normKey === normWs && projCfg.mcpServers) {
875
+ addMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
876
+ }
877
+ }
878
+ }
879
+ }
880
+
881
+ return Array.from(servers.values());
882
+ }
883
+
884
+ function evaluateClaudeEagerMcpGate({
885
+ paths,
886
+ env = process.env,
887
+ claudeCodeVersion = null,
888
+ claudeJsonParsed = null,
889
+ userSettingsParsed = null,
890
+ projSettingsParsed = null,
891
+ projLocalSettingsParsed = null,
892
+ mcpToolCalls7d = {},
893
+ schemaTokensByServer = {},
894
+ gatewaySupportsToolSearch = false
895
+ }) {
896
+ const readLayeredEnv = (key) => {
897
+ let val = null;
898
+ for (const doc of [userSettingsParsed, projSettingsParsed, projLocalSettingsParsed]) {
899
+ if (doc?.env && doc.env[key] !== undefined && String(doc.env[key]).trim() !== '') {
900
+ val = String(doc.env[key]).trim();
901
+ }
902
+ }
903
+ if (env && env[key] !== undefined && String(env[key]).trim() !== '') {
904
+ val = String(env[key]).trim();
905
+ }
906
+ return val;
907
+ };
908
+
909
+ const enableToolSearch = readLayeredEnv('ENABLE_TOOL_SEARCH');
910
+ const rawDisableBetas = readLayeredEnv('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS');
911
+ const baseUrl = readLayeredEnv('ANTHROPIC_BASE_URL');
912
+
913
+ const isCustomGateway = Boolean(baseUrl && !/^https:\/\/api\.anthropic\.com(?:\/|$)/i.test(baseUrl));
914
+ const disableExperimentalBetas = /^(1|true)$/i.test(String(rawDisableBetas || '').trim());
915
+ const toolSearchDisabled = /^(false|0)$/i.test(String(enableToolSearch || '').trim());
916
+ const toolSearchForcedOn = /^(true|1)$/i.test(String(enableToolSearch || '').trim());
917
+ const versionCmp = claudeCodeVersion ? compareSemver(claudeCodeVersion, '2.1.304') : null;
918
+ const versionBelow21304 = Boolean(versionCmp !== null && versionCmp < 0);
919
+
920
+ const discovered = collectClaudeMcpServers({ workspacePath: paths.cwd, claudeJsonParsed });
921
+ const isSshSession = Boolean(
922
+ (env?.SSH_CONNECTION && String(env.SSH_CONNECTION).trim()) ||
923
+ (env?.SSH_TTY && String(env.SSH_TTY).trim()) ||
924
+ (env?.SSH_CLIENT && String(env.SSH_CLIENT).trim())
925
+ );
926
+ const gatewayVerified =
927
+ gatewaySupportsToolSearch === true ||
928
+ /^(1|true)$/i.test(
929
+ String(
930
+ readLayeredEnv('BURNOFF_GATEWAY_VERIFIED_TOOL_SEARCH') ||
931
+ readLayeredEnv('CLAUDE_CODE_GATEWAY_VERIFIED_TOOL_SEARCH') ||
932
+ ''
933
+ ).trim()
934
+ );
935
+
936
+ const gateReasons = [];
937
+ if (toolSearchDisabled) gateReasons.push('ENABLE_TOOL_SEARCH=false');
938
+ if (disableExperimentalBetas) gateReasons.push('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1');
939
+ if (isSshSession && (discovered.length > 0 || toolSearchForcedOn)) {
940
+ gateReasons.push('ssh_forced_disable_experimental_betas');
941
+ }
942
+ if (isCustomGateway && !gatewayVerified && discovered.length > 0) {
943
+ if (versionBelow21304 && !toolSearchForcedOn) {
944
+ gateReasons.push('custom_gateway_claude_code_lt_2.1.304');
945
+ } else {
946
+ gateReasons.push('custom_gateway_toolsearch_fallback');
947
+ }
948
+ }
949
+
950
+ if (gateReasons.length === 0) {
951
+ return {
952
+ eagerGateActive: false,
953
+ gateReasons: [],
954
+ enableToolSearch,
955
+ disableExperimentalBetas,
956
+ isCustomGateway,
957
+ isSshSession,
958
+ gatewayVerified,
959
+ configuredServerCount: discovered.length,
960
+ configuredServerNames: discovered.map((s) => s.name),
961
+ claudeCodeVersion: claudeCodeVersion || null,
962
+ startupTaxTokensPerTurn: 0,
963
+ summaryLine: 'MCP startup tax: 0 tok/turn (deferred loading active)',
964
+ unusedEagerServers: []
965
+ };
966
+ }
967
+
968
+ const unusedEagerServers = [];
969
+ let startupTaxTokensPerTurn = 0;
970
+
971
+ for (const srv of discovered) {
972
+ const telemetryTokens = Number(schemaTokensByServer[srv.name] || 0);
973
+ const tokensEst = telemetryTokens > 0 ? telemetryTokens : srv.hintTokens > 0 ? srv.hintTokens : 3200;
974
+ const calls7d = Number(mcpToolCalls7d[srv.name] || 0);
975
+ startupTaxTokensPerTurn += tokensEst;
976
+ if (calls7d === 0) {
977
+ unusedEagerServers.push({
978
+ name: srv.name,
979
+ sourceFile: srv.sourceFile,
980
+ tokensEst,
981
+ isEstimated: !(telemetryTokens > 0 || srv.hintTokens > 0),
982
+ calls7d
983
+ });
984
+ }
985
+ }
986
+
987
+ return {
988
+ eagerGateActive: true,
989
+ gateReasons,
990
+ enableToolSearch,
991
+ disableExperimentalBetas,
992
+ isCustomGateway,
993
+ isSshSession,
994
+ gatewayVerified,
995
+ configuredServerCount: discovered.length,
996
+ configuredServerNames: discovered.map((s) => s.name),
997
+ claudeCodeVersion: claudeCodeVersion || null,
998
+ startupTaxTokensPerTurn,
999
+ summaryLine: `MCP startup tax: ~${startupTaxTokensPerTurn.toLocaleString('en-US')} tok/turn (${discovered.length} eager server${discovered.length === 1 ? '' : 's'})`,
1000
+ unusedEagerServers
1001
+ };
1002
+ }
1003
+
1004
+ /**
1005
+ * BO-MCP-05 (#97616): Scans configured MCP tool definitions and observed Claude Code
1006
+ * MCP tool names for `mcp__<server>__<tool>` identifiers exceeding 64 characters.
1007
+ */
1008
+ export function scanMcpToolNameLengthViolations({
1009
+ homeDir = getHomeDir(),
1010
+ workspacePath = process.cwd(),
1011
+ observedToolNames = [],
1012
+ manifestDirs = [],
1013
+ maxLength = 64
1014
+ } = {}) {
1015
+ const disabledServers = new Set();
1016
+ const violationsByFullName = new Map();
1017
+
1018
+ const recordViolation = (fullName, serverName, toolName, source) => {
1019
+ if (!fullName || fullName.length <= maxLength) return;
1020
+ if (disabledServers.has(serverName)) return;
1021
+ if (violationsByFullName.has(fullName)) return;
1022
+ violationsByFullName.set(fullName, {
1023
+ fullName,
1024
+ serverName,
1025
+ toolName,
1026
+ length: fullName.length,
1027
+ source
1028
+ });
1029
+ };
1030
+
1031
+ const inspectServerMap = (serversMap, source) => {
1032
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
1033
+ for (const [serverName, cfg] of Object.entries(serversMap)) {
1034
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
1035
+ if (cfg.disabled === true || cfg.enabled === false) {
1036
+ disabledServers.add(serverName);
1037
+ continue;
1038
+ }
1039
+ disabledServers.delete(serverName);
1040
+ for (const field of ['tools', 'eagerTools']) {
1041
+ if (!Array.isArray(cfg[field])) continue;
1042
+ for (const item of cfg[field]) {
1043
+ const toolName =
1044
+ typeof item === 'string'
1045
+ ? item.trim()
1046
+ : item && typeof item === 'object' && typeof item.name === 'string'
1047
+ ? item.name.trim()
1048
+ : '';
1049
+ if (toolName) {
1050
+ recordViolation(`mcp__${serverName}__${toolName}`, serverName, toolName, source);
1051
+ }
1052
+ }
1053
+ }
1054
+ }
1055
+ };
1056
+
1057
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
1058
+ if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
1059
+ inspectServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path.replace(/\\/g, '/'));
1060
+ }
1061
+
1062
+ const claudeJson = parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1063
+ if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
1064
+ inspectServerMap(claudeJson.parsed.mcpServers, '~/.claude.json');
1065
+ const projects = claudeJson.parsed.projects;
1066
+ if (projects && typeof projects === 'object') {
1067
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
1068
+ for (const [projKey, projCfg] of Object.entries(projects)) {
1069
+ if (!projCfg || typeof projCfg !== 'object') continue;
1070
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
1071
+ if (normKey === normWs && projCfg.mcpServers) {
1072
+ inspectServerMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
1073
+ }
1074
+ }
1075
+ }
1076
+ }
1077
+
1078
+ for (const mDir of Array.isArray(manifestDirs) ? manifestDirs : []) {
1079
+ if (!mDir || !fs.existsSync(mDir)) continue;
1080
+ let serverEntries = [];
1081
+ try {
1082
+ serverEntries = fs.readdirSync(mDir, { withFileTypes: true });
1083
+ } catch {
1084
+ serverEntries = []; // ignore: unreadable MCP manifest directory
1085
+ }
1086
+ for (const ent of serverEntries) {
1087
+ if (!ent.isDirectory()) continue;
1088
+ const serverName = ent.name;
1089
+ if (disabledServers.has(serverName)) continue;
1090
+ const srvDir = path.join(mDir, serverName);
1091
+ let files = [];
1092
+ try {
1093
+ files = fs.readdirSync(srvDir, { withFileTypes: true });
1094
+ } catch {
1095
+ continue; // ignore: unreadable MCP server manifest directory
1096
+ }
1097
+ for (const f of files) {
1098
+ if (!f.isFile() || !/\.json$/i.test(f.name)) continue;
1099
+ const filePath = path.join(srvDir, f.name);
1100
+ const res = parseJsoncReadOnly(filePath);
1101
+ if (!res.parseOk || !res.parsed || typeof res.parsed !== 'object') continue;
1102
+ const lowerFile = f.name.toLowerCase();
1103
+ const isMetaFile = lowerFile === 'server.json' || lowerFile === 'capabilities.json';
1104
+ const toolNames = new Set();
1105
+ if (!isMetaFile && typeof res.parsed.name === 'string' && res.parsed.name.trim()) {
1106
+ toolNames.add(res.parsed.name.trim());
1107
+ }
1108
+ if (Array.isArray(res.parsed.tools)) {
1109
+ for (const item of res.parsed.tools) {
1110
+ if (typeof item === 'string' && item.trim()) toolNames.add(item.trim());
1111
+ else if (item && typeof item === 'object' && typeof item.name === 'string' && item.name.trim()) {
1112
+ toolNames.add(item.name.trim());
1113
+ }
1114
+ }
1115
+ } else if (!isMetaFile && typeof res.parsed.name !== 'string') {
1116
+ const stem = f.name.replace(/\.json$/i, '').trim();
1117
+ if (stem) toolNames.add(stem);
1118
+ }
1119
+ const source = filePath.replace(/\\/g, '/');
1120
+ for (const toolName of toolNames) {
1121
+ recordViolation(`mcp__${serverName}__${toolName}`, serverName, toolName, source);
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ if (Array.isArray(observedToolNames)) {
1128
+ for (const rawName of observedToolNames) {
1129
+ const name = String(rawName || '').trim();
1130
+ const match = name.match(/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/);
1131
+ if (!match) continue;
1132
+ recordViolation(name, match[1], match[2], 'transcript');
1133
+ }
1134
+ }
1135
+
1136
+ return {
1137
+ maxLength,
1138
+ violations: Array.from(violationsByFullName.values())
1139
+ };
1140
+ }
1141
+
1142
+ function collectDisabledClaudeMcpServers({ homeDir = getHomeDir(), workspacePath = process.cwd() } = {}) {
1143
+ const disabledServers = new Set();
1144
+ const trackServerMap = (serversMap) => {
1145
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
1146
+ for (const [name, cfg] of Object.entries(serversMap)) {
1147
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
1148
+ if (cfg.disabled === true || cfg.enabled === false) {
1149
+ disabledServers.add(name);
1150
+ } else {
1151
+ disabledServers.delete(name);
1152
+ }
1153
+ }
1154
+ };
1155
+
1156
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
1157
+ if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
1158
+ trackServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed);
1159
+ }
1160
+
1161
+ const claudeJson = parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1162
+ if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
1163
+ trackServerMap(claudeJson.parsed.mcpServers);
1164
+ const projects = claudeJson.parsed.projects;
1165
+ if (projects && typeof projects === 'object') {
1166
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
1167
+ for (const [projKey, projCfg] of Object.entries(projects)) {
1168
+ if (!projCfg || typeof projCfg !== 'object') continue;
1169
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
1170
+ if (normKey === normWs && projCfg.mcpServers) {
1171
+ trackServerMap(projCfg.mcpServers);
1172
+ }
1173
+ }
1174
+ }
1175
+ }
1176
+ return disabledServers;
1177
+ }
1178
+
1179
+ function hasListChangedFlag(doc) {
1180
+ if (!doc || typeof doc !== 'object') return false;
1181
+ return Boolean(
1182
+ doc.capabilities?.tools?.listChanged === true ||
1183
+ doc.result?.capabilities?.tools?.listChanged === true ||
1184
+ doc.tools?.listChanged === true ||
1185
+ doc.listChanged === true
1186
+ );
1187
+ }
1188
+
1189
+ /**
1190
+ * BO-MCP-06 (#2812, #1923): Scans Claude Code MCP configs, optional manifest dirs,
1191
+ * and runtime notifications for `tools.listChanged: true` / `notifications/tools/list_changed`,
1192
+ * guarding suppression when observed prefix <= 20k tokens.
1193
+ */
1194
+ export function scanMcpListChangedCapabilities({
1195
+ homeDir = getHomeDir(),
1196
+ workspacePath = process.cwd(),
1197
+ manifestDirs = [],
1198
+ runtimeListChangedServers = [],
1199
+ maxObservedCachedPrefixTokens = null,
1200
+ cachedPrefixThreshold = LIST_CHANGED_PREFIX_THRESHOLD
1201
+ } = {}) {
1202
+ const disabledServers = collectDisabledClaudeMcpServers({ homeDir, workspacePath });
1203
+ const flaggedByServer = new Map();
1204
+
1205
+ const recordFlagged = (serverName, reason, source) => {
1206
+ const name = String(serverName || '').trim();
1207
+ if (!name || disabledServers.has(name) || flaggedByServer.has(name)) return;
1208
+ flaggedByServer.set(name, {
1209
+ serverName: name,
1210
+ reason,
1211
+ source: String(source || '').replace(/\\/g, '/')
1212
+ });
1213
+ };
1214
+
1215
+ const inspectConfigMap = (serversMap, source) => {
1216
+ if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
1217
+ for (const [name, cfg] of Object.entries(serversMap)) {
1218
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
1219
+ if (cfg.disabled === true || cfg.enabled === false) continue;
1220
+ if (hasListChangedFlag(cfg)) {
1221
+ recordFlagged(name, 'tools.listChanged: true', source);
1222
+ }
1223
+ }
1224
+ };
1225
+
1226
+ const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
1227
+ if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
1228
+ inspectConfigMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
1229
+ }
1230
+
1231
+ const claudeJson = parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1232
+ if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
1233
+ inspectConfigMap(claudeJson.parsed.mcpServers, '~/.claude.json');
1234
+ const projects = claudeJson.parsed.projects;
1235
+ if (projects && typeof projects === 'object') {
1236
+ const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
1237
+ for (const [projKey, projCfg] of Object.entries(projects)) {
1238
+ if (!projCfg || typeof projCfg !== 'object') continue;
1239
+ const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
1240
+ if (normKey === normWs && projCfg.mcpServers) {
1241
+ inspectConfigMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
1242
+ }
1243
+ }
1244
+ }
1245
+ }
1246
+
1247
+ for (const mDir of Array.isArray(manifestDirs) ? manifestDirs : []) {
1248
+ if (!mDir || !fs.existsSync(mDir)) continue;
1249
+ let serverEntries = [];
1250
+ try {
1251
+ serverEntries = fs.readdirSync(mDir, { withFileTypes: true });
1252
+ } catch {
1253
+ serverEntries = []; // ignore: unreadable MCP manifest directory
1254
+ }
1255
+ for (const ent of serverEntries) {
1256
+ if (!ent.isDirectory()) continue;
1257
+ const serverName = ent.name;
1258
+ if (disabledServers.has(serverName)) continue;
1259
+ const srvDir = path.join(mDir, serverName);
1260
+ let files = [];
1261
+ try {
1262
+ files = fs.readdirSync(srvDir, { withFileTypes: true });
1263
+ } catch {
1264
+ continue; // ignore: unreadable MCP server manifest directory
1265
+ }
1266
+ for (const f of files) {
1267
+ if (!f.isFile() || !/\.json$/i.test(f.name)) continue;
1268
+ const filePath = path.join(srvDir, f.name);
1269
+ const res = parseJsoncReadOnly(filePath);
1270
+ if (!res.parseOk || !res.parsed || typeof res.parsed !== 'object') continue;
1271
+ if (hasListChangedFlag(res.parsed)) {
1272
+ recordFlagged(serverName, 'tools.listChanged: true', filePath);
1273
+ }
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ if (Array.isArray(runtimeListChangedServers)) {
1279
+ for (const item of runtimeListChangedServers) {
1280
+ if (typeof item === 'string') {
1281
+ recordFlagged(item, 'notifications/tools/list_changed', 'transcript');
1282
+ } else if (item && typeof item === 'object' && item.serverName) {
1283
+ recordFlagged(item.serverName, item.reason || 'notifications/tools/list_changed', item.source || 'transcript');
1284
+ }
1285
+ }
1286
+ }
1287
+
1288
+ const flaggedServers = Array.from(flaggedByServer.values());
1289
+ const hasTelemetryPrefix =
1290
+ typeof maxObservedCachedPrefixTokens === 'number' && Number.isFinite(maxObservedCachedPrefixTokens);
1291
+ const suppressedByPrefixGuard =
1292
+ flaggedServers.length > 0 && hasTelemetryPrefix && maxObservedCachedPrefixTokens <= cachedPrefixThreshold;
1293
+ const status = flaggedServers.length === 0 ? 'pass' : suppressedByPrefixGuard ? 'info' : 'warn';
1294
+
1295
+ return {
1296
+ status,
1297
+ flaggedServers,
1298
+ suppressedByPrefixGuard,
1299
+ maxObservedCachedPrefixTokens: hasTelemetryPrefix ? maxObservedCachedPrefixTokens : null,
1300
+ cachedPrefixThreshold
1301
+ };
1302
+ }
1303
+
1304
+ /**
1305
+ * BO-MCP-09 (#104791, #98438): Estimates per-subagent `mcp_instructions_delta` tax
1306
+ * when > 5 connected MCP servers coexist with spawned or defined subagents.
1307
+ */
1308
+ export function estimateSubagentMcpInstructionsTax({
1309
+ connectedServerNames = [],
1310
+ subagentCount = 0,
1311
+ observedMcpInstructionsDeltaChars = 0,
1312
+ minServers = SUBAGENT_MCP_MIN_SERVERS,
1313
+ tokensPerServerFallback = DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER
1314
+ } = {}) {
1315
+ const uniqueServers = [];
1316
+ const seen = new Set();
1317
+ for (const raw of Array.isArray(connectedServerNames) ? connectedServerNames : []) {
1318
+ const name = String(raw || '').trim();
1319
+ if (!name || seen.has(name)) continue;
1320
+ seen.add(name);
1321
+ uniqueServers.push(name);
1322
+ }
1323
+
1324
+ const connectedServerCount = uniqueServers.length;
1325
+ const count = Math.max(0, Number(subagentCount) || 0);
1326
+ const triggered = connectedServerCount > minServers && count > 0;
1327
+
1328
+ if (!triggered) {
1329
+ return {
1330
+ status: 'pass',
1331
+ triggered: false,
1332
+ connectedServerCount,
1333
+ minServers,
1334
+ subagentCount: count,
1335
+ perSubagentTokensEst: 0,
1336
+ totalTaxTokens: 0,
1337
+ isEstimated: true
1338
+ };
1339
+ }
1340
+
1341
+ const observedChars = Number(observedMcpInstructionsDeltaChars) || 0;
1342
+ const isEstimated = !(observedChars > 0);
1343
+ const perSubagentTokensEst =
1344
+ observedChars > 0 ? Math.ceil(observedChars / 4) : connectedServerCount * tokensPerServerFallback;
1345
+
1346
+ return {
1347
+ status: 'warn',
1348
+ triggered: true,
1349
+ connectedServerCount,
1350
+ minServers,
1351
+ subagentCount: count,
1352
+ perSubagentTokensEst,
1353
+ totalTaxTokens: perSubagentTokensEst * count,
1354
+ isEstimated
1355
+ };
1356
+ }
1357
+
1358
+ function estimateWeeklySavingsUsd(turn0ReclaimableTokens, nowMs) {
1359
+ if (!turn0ReclaimableTokens || turn0ReclaimableTokens <= 0) return 0;
1360
+ const rateCard = resolveModelRateCard({
1361
+ model: 'claude-sonnet-5-5',
1362
+ timestampMs: nowMs
1363
+ });
1364
+ const inputPer1M = Number(rateCard?.inputPer1M || 2.0);
1365
+ const cachedWeight = Number(rateCard?.cachedReadWeight || 0.05);
1366
+ const uncachedEquivUnits = turn0ReclaimableTokens * (10 + 500 * cachedWeight);
1367
+ return Number(((uncachedEquivUnits / 1_000_000) * inputPer1M).toFixed(2));
1368
+ }
1369
+
1370
+ function formatConfigStatus(res) {
1371
+ return {
1372
+ path: String(res.path || '').replace(/\\/g, '/'),
1373
+ exists: Boolean(res.exists),
1374
+ parseOk: Boolean(res.parseOk),
1375
+ strictJsonValid: Boolean(res.strictJsonValid),
1376
+ strict_json_syntax_warning: res.strict_json_syntax_warning || null
1377
+ };
1378
+ }
1379
+
1380
+ const SECRET_ALLOW_PATTERNS = Object.freeze([
1381
+ { name: 'password_flag', regex: /--password(?:=|\s+)([^\s]+)/i, captureGroup: 1 },
1382
+ { name: 'bearer_token', regex: /\bBearer\s+([A-Za-z0-9._-]{8,})/i, captureGroup: 1 },
1383
+ { name: 'api_key_sk', regex: /\b(sk-[A-Za-z0-9_-]{12,})\b/, captureGroup: 1 },
1384
+ { name: 'google_api_key', regex: /\b(AIza[0-9A-Za-z_-]{20,})\b/, captureGroup: 1 },
1385
+ { name: 'github_pat', regex: /\b((?:ghp_|gho_|github_pat_)[A-Za-z0-9_]{16,})\b/, captureGroup: 1 },
1386
+ { name: 'url_credentials', regex: /[a-z][a-z0-9+.-]*:\/\/[^:\s/]+:([^@\s/]+)@/i, captureGroup: 1 }
1387
+ ]);
1388
+
1389
+ const RETIRED_MODELS_SPEC = Object.freeze({
1390
+ 'gemini-3.8-flash': { sunsetUtc: '2026-11-30T00:00:00Z', replacement: 'gemini-4-hydrogen' },
1391
+ 'gemini-4-argon': { sunsetUtc: '2026-11-30T00:00:00Z', replacement: 'gemini-4-hydrogen' },
1392
+ 'claude-opus-4-6': { sunsetUtc: '2026-11-18T00:00:00Z', replacement: 'claude-opus-5-5' },
1393
+ 'claude-sonnet-4-6': { sunsetUtc: '2026-11-18T00:00:00Z', replacement: 'claude-sonnet-5-5' },
1394
+ 'gpt-oss-120b': { sunsetUtc: '2026-11-18T00:00:00Z', replacement: 'gemini-4-hydrogen' }
1395
+ });
1396
+
1397
+ function isPlaceholderSecretValue(val) {
1398
+ const s = String(val || '').trim();
1399
+ if (!s) return true;
1400
+ if (/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/.test(s)) return true;
1401
+ if (/^<[A-Za-z0-9_-]+>$/.test(s)) return true;
1402
+ if (/^\*{3,}$/.test(s)) return true;
1403
+ return false;
1404
+ }
1405
+
1406
+ function collectStrictJsonLints(entries = []) {
1407
+ const warnings = [];
1408
+ const lints = [];
1409
+ for (const entry of entries) {
1410
+ const res = entry?.res;
1411
+ if (!res?.exists || !res?.parseOk || !res?.strict_json_syntax_warning) continue;
1412
+ const file = String(res.path || '').replace(/\\/g, '/');
1413
+ warnings.push({ file, warning: res.strict_json_syntax_warning });
1414
+ lints.push({
1415
+ ruleId: 'BO-CFG-01',
1416
+ severity: 'warn',
1417
+ harness: 'claude-code',
1418
+ file,
1419
+ message: res.strict_json_syntax_warning,
1420
+ remediation: res.strict_json_syntax_warning
1421
+ });
1422
+ }
1423
+ return {
1424
+ status: warnings.length > 0 ? 'warn' : 'pass',
1425
+ warnings,
1426
+ lints
1427
+ };
1428
+ }
1429
+
1430
+ function auditMisplacedChromeKey(settingsEntries = []) {
1431
+ const misplaced = [];
1432
+ const lints = [];
1433
+ for (const entry of settingsEntries) {
1434
+ const doc = entry?.doc;
1435
+ if (!doc?.parseOk || !doc.parsed || typeof doc.parsed !== 'object') continue;
1436
+ if (!Object.prototype.hasOwnProperty.call(doc.parsed, 'claudeInChromeDefaultEnabled')) continue;
1437
+ const file = String(doc.path || '').replace(/\\/g, '/');
1438
+ const label = entry.label || file;
1439
+ misplaced.push({ file, label });
1440
+ lints.push({
1441
+ ruleId: 'BO-CFG-02',
1442
+ severity: 'warn',
1443
+ harness: 'claude-code',
1444
+ file,
1445
+ message: `Misplaced key: claudeInChromeDefaultEnabled in ${label} is ignored by Claude Code. Move to ~/.claude.json or launch with --no-chrome.`,
1446
+ remediation: 'Move claudeInChromeDefaultEnabled to ~/.claude.json or launch with --no-chrome.'
1447
+ });
1448
+ }
1449
+ return {
1450
+ status: misplaced.length > 0 ? 'warn' : 'pass',
1451
+ misplacedFiles: misplaced.map((x) => x.file),
1452
+ lints
1453
+ };
1454
+ }
1455
+
1456
+ function resolveGitDir(cwd) {
1457
+ const repoDir = path.resolve(cwd || process.cwd());
1458
+ const dotGit = path.join(repoDir, '.git');
1459
+ if (!fs.existsSync(dotGit)) return null;
1460
+ try {
1461
+ const st = fs.statSync(dotGit);
1462
+ if (st.isDirectory()) return dotGit;
1463
+ if (st.isFile()) {
1464
+ const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/im);
1465
+ if (m && m[1]) {
1466
+ const target = m[1].trim();
1467
+ return path.isAbsolute(target) ? target : path.resolve(repoDir, target);
1468
+ }
1469
+ }
1470
+ } catch {
1471
+ // ignore: unreadable .git pointer falls back to .gitignore check only
1472
+ }
1473
+ return null;
1474
+ }
1475
+
1476
+ function hasSettingsLocalIgnoreEntry(ignoreFilePath) {
1477
+ if (!ignoreFilePath || !fs.existsSync(ignoreFilePath)) return false;
1478
+ let raw = '';
1479
+ try {
1480
+ raw = fs.readFileSync(ignoreFilePath, 'utf8');
1481
+ } catch {
1482
+ return false; // ignore: unreadable ignore file
1483
+ }
1484
+ for (const rawLine of raw.split(/\r?\n/)) {
1485
+ const line = rawLine.trim();
1486
+ if (!line || line.startsWith('#') || line.startsWith('!')) continue;
1487
+ const norm = line.replace(/^\/+/, '').replace(/\/+$/, '');
1488
+ if (
1489
+ norm === 'settings.local.json' ||
1490
+ norm === '.claude/settings.local.json' ||
1491
+ norm === '.claude/*.local.json' ||
1492
+ norm === '*.local.json' ||
1493
+ norm === '.claude' ||
1494
+ norm === '.claude/*' ||
1495
+ norm === '**/.claude/settings.local.json' ||
1496
+ norm === '**/settings.local.json'
1497
+ ) {
1498
+ return true;
1499
+ }
1500
+ }
1501
+ return false;
1502
+ }
1503
+
1504
+ function isSettingsLocalGitignored(cwd) {
1505
+ if (hasSettingsLocalIgnoreEntry(path.join(cwd, '.gitignore'))) return true;
1506
+ const gitDir = resolveGitDir(cwd);
1507
+ if (gitDir && hasSettingsLocalIgnoreEntry(path.join(gitDir, 'info', 'exclude'))) {
1508
+ return true;
1509
+ }
1510
+ return false;
1511
+ }
1512
+
1513
+ function auditLocalSettingsSecrets(projectLocalSettings, cwd) {
1514
+ const allowRules = Array.isArray(projectLocalSettings?.parsed?.permissions?.allow)
1515
+ ? projectLocalSettings.parsed.permissions.allow
1516
+ : [];
1517
+ const matches = [];
1518
+
1519
+ for (let i = 0; i < allowRules.length; i++) {
1520
+ const rule = allowRules[i];
1521
+ if (typeof rule !== 'string' || !rule) continue;
1522
+ for (const pat of SECRET_ALLOW_PATTERNS) {
1523
+ const m = rule.match(pat.regex);
1524
+ if (!m) continue;
1525
+ const captured = m[pat.captureGroup] || '';
1526
+ if (isPlaceholderSecretValue(captured)) continue;
1527
+ matches.push({
1528
+ ruleIndex: i,
1529
+ patternName: pat.name,
1530
+ preview: '[redacted]'
1531
+ });
1532
+ }
1533
+ }
1534
+
1535
+ const gitignored = isSettingsLocalGitignored(cwd);
1536
+ const missingGitignore = Boolean(projectLocalSettings?.exists && allowRules.length > 0 && !gitignored);
1537
+ const status = matches.length > 0 || missingGitignore ? 'warn' : 'pass';
1538
+ const file = String(projectLocalSettings?.path || path.join(cwd, '.claude', 'settings.local.json')).replace(/\\/g, '/');
1539
+
1540
+ const lints = [];
1541
+ if (status === 'warn') {
1542
+ const message =
1543
+ matches.length > 0
1544
+ ? `Credential Leak Risk in settings.local.json: Literal command allow-rules contain ${matches.length} credential pattern(s) [redacted]${!gitignored ? ' and file is missing from .gitignore or .git/info/exclude' : ''}. Replace inline secrets with env vars.`
1545
+ : `Unignored settings.local.json: .claude/settings.local.json defines ${allowRules.length} permissions.allow rule(s) and is missing from .gitignore and .git/info/exclude. Add it so local approvals are never committed.`;
1546
+ lints.push({
1547
+ ruleId: 'BO-SEC-08',
1548
+ severity: 'warn',
1549
+ harness: 'claude-code',
1550
+ file,
1551
+ message,
1552
+ remediation:
1553
+ matches.length > 0
1554
+ ? 'Remove inline secrets from .claude/settings.local.json permissions.allow, use env vars, and exclude .claude/settings.local.json in .gitignore or .git/info/exclude.'
1555
+ : 'Run `burnoff init` or add .claude/settings.local.json to .gitignore or .git/info/exclude.'
1556
+ });
1557
+ }
1558
+
1559
+ return {
1560
+ status,
1561
+ fileExists: Boolean(projectLocalSettings?.exists),
1562
+ allowRuleCount: allowRules.length,
1563
+ secretMatchCount: matches.length,
1564
+ matches,
1565
+ gitignored,
1566
+ lints
1567
+ };
1568
+ }
1569
+
1570
+ function normalizeRetiredModelCandidate(raw) {
1571
+ let s = String(raw || '').trim().toLowerCase();
1572
+ if (!s) return '';
1573
+ s = s.replace(/^claude-(opus|sonnet|haiku)-4\.6/, 'claude-$1-4-6');
1574
+ s = s.replace(/^gemini-3-8-flash/, 'gemini-3.8-flash');
1575
+ let prev = '';
1576
+ while (s !== prev) {
1577
+ prev = s;
1578
+ s = s.replace(/-(?:\d{8}|low|medium|med|high|xhigh|extra-high|tiered-high|tiered-medium|tiered-low)$/, '');
1579
+ }
1580
+ return s;
1581
+ }
1582
+
1583
+ function auditRetiredModelsAndDeprecatedFlags({
1584
+ cwd,
1585
+ env = process.env,
1586
+ settingsLayers = [],
1587
+ nowMs = Date.now()
1588
+ } = {}) {
1589
+ const findings = [];
1590
+ const lints = [];
1591
+ const seenKeys = new Set();
1592
+
1593
+ const addModelFinding = (rawModel, source) => {
1594
+ const normalized = normalizeRetiredModelCandidate(rawModel);
1595
+ const spec = RETIRED_MODELS_SPEC[normalized];
1596
+ if (!spec) return;
1597
+ const dedupeKey = `model:${normalized}:${source}`;
1598
+ if (seenKeys.has(dedupeKey)) return;
1599
+ seenKeys.add(dedupeKey);
1600
+
1601
+ const sunsetMs = Date.parse(spec.sunsetUtc);
1602
+ const retired = Number.isFinite(sunsetMs) && nowMs >= sunsetMs;
1603
+ const severity = retired ? 'error' : 'warn';
1604
+ const sunsetDate = spec.sunsetUtc.slice(0, 10);
1605
+ const message = `Deprecated / Retired Model or Flag: Replace retired model ${rawModel} (sunset ${sunsetDate}) with ${spec.replacement} (found in ${source}).`;
1606
+ findings.push({
1607
+ kind: 'retired_model',
1608
+ modelId: normalized,
1609
+ rawModel: String(rawModel),
1610
+ sunsetUtc: spec.sunsetUtc,
1611
+ replacement: spec.replacement,
1612
+ severity,
1613
+ source
1614
+ });
1615
+ lints.push({
1616
+ ruleId: 'BO-CFG-09',
1617
+ severity,
1618
+ harness: 'claude-code',
1619
+ file: source,
1620
+ message,
1621
+ remediation: `Migrate ${rawModel} to ${spec.replacement} before ${sunsetDate}.`
1622
+ });
1623
+ };
1624
+
1625
+ for (const layerEntry of settingsLayers) {
1626
+ const doc = layerEntry?.doc?.parsed;
1627
+ const source = layerEntry?.label || layerEntry?.doc?.path || 'settings.json';
1628
+ if (!doc || typeof doc !== 'object') continue;
1629
+ for (const k of ['model', 'defaultModel']) {
1630
+ if (typeof doc[k] === 'string' && doc[k].trim()) {
1631
+ addModelFinding(doc[k].trim(), source);
1632
+ }
1633
+ }
1634
+ if (doc.env && typeof doc.env === 'object') {
1635
+ for (const ek of [
1636
+ 'ANTHROPIC_MODEL',
1637
+ 'CLAUDE_MODEL',
1638
+ 'ANTHROPIC_DEFAULT_OPUS_MODEL',
1639
+ 'ANTHROPIC_DEFAULT_SONNET_MODEL',
1640
+ 'ANTHROPIC_DEFAULT_HAIKU_MODEL'
1641
+ ]) {
1642
+ if (typeof doc.env[ek] === 'string' && doc.env[ek].trim()) {
1643
+ addModelFinding(doc.env[ek].trim(), `${source}#env.${ek}`);
1644
+ }
1645
+ }
1646
+ }
1647
+ if (doc.disableArtifact === true) {
1648
+ const dedupeKey = `flag:disableArtifact:${source}`;
1649
+ if (!seenKeys.has(dedupeKey)) {
1650
+ seenKeys.add(dedupeKey);
1651
+ findings.push({
1652
+ kind: 'deprecated_flag',
1653
+ flag: 'disableArtifact',
1654
+ severity: 'warn',
1655
+ source
1656
+ });
1657
+ lints.push({
1658
+ ruleId: 'BO-CFG-09',
1659
+ severity: 'warn',
1660
+ harness: 'claude-code',
1661
+ file: source,
1662
+ message: `Deprecated / Retired Model or Flag: Migrate deprecated "disableArtifact": true in ${source} to "enableArtifact": false or --disallowedTools Artifact.`,
1663
+ remediation: 'Replace "disableArtifact": true with "enableArtifact": false or pass --disallowedTools Artifact.'
1664
+ });
1665
+ }
1666
+ }
1667
+ }
1668
+
1669
+ for (const ek of ['ANTHROPIC_MODEL', 'CLAUDE_MODEL', 'GEMINI_MODEL']) {
1670
+ if (env && typeof env[ek] === 'string' && env[ek].trim()) {
1671
+ addModelFinding(env[ek].trim(), `env:${ek}`);
1672
+ }
1673
+ }
1674
+
1675
+ const pkg = parseJsoncReadOnly(path.join(cwd, 'package.json'));
1676
+ if (pkg.parseOk && pkg.parsed && typeof pkg.parsed === 'object' && pkg.parsed.scripts && typeof pkg.parsed.scripts === 'object') {
1677
+ const retiredPattern = /\b(gemini-3[.-]8-flash|gemini-4-argon|claude-opus-4[.-]6|claude-sonnet-4[.-]6|gpt-oss-120b)(?:-[a-z0-9-]+)?\b/gi;
1678
+ for (const [scriptName, scriptCmd] of Object.entries(pkg.parsed.scripts)) {
1679
+ if (typeof scriptCmd !== 'string') continue;
1680
+ for (const m of scriptCmd.matchAll(retiredPattern)) {
1681
+ addModelFinding(m[0], `package.json#scripts.${scriptName}`);
1682
+ }
1683
+ if (/\bclaude\b[^\n]*\s--tools(?:\s|=|$)/.test(scriptCmd)) {
1684
+ const source = `package.json#scripts.${scriptName}`;
1685
+ const dedupeKey = `flag:--tools:${source}`;
1686
+ if (!seenKeys.has(dedupeKey)) {
1687
+ seenKeys.add(dedupeKey);
1688
+ findings.push({
1689
+ kind: 'forbidden_flag',
1690
+ flag: '--tools',
1691
+ severity: 'warn',
1692
+ source
1693
+ });
1694
+ lints.push({
1695
+ ruleId: 'BO-CFG-09',
1696
+ severity: 'warn',
1697
+ harness: 'claude-code',
1698
+ file: source,
1699
+ message: `Deprecated / Retired Model or Flag: Never use strict allowlist --tools in ${source}; use --disallowedTools Artifact instead.`,
1700
+ remediation: 'Replace --tools with --disallowedTools Artifact.'
1701
+ });
1702
+ }
1703
+ }
1704
+ }
1705
+ }
1706
+
1707
+ const hasError = lints.some((l) => l.severity === 'error');
1708
+ return {
1709
+ status: lints.length > 0 ? (hasError ? 'error' : 'warn') : 'pass',
1710
+ findings,
1711
+ lints
1712
+ };
1713
+ }
1714
+
1715
+ /**
1716
+ * Audits Claude Code `idleCompaction` (~54m idle) vs `autoCompactEnabled` ROI tradeoffs,
1717
+ * gating `idleCompaction` checks strictly on `claudeCodeVersion >= 2.1.290`.
1718
+ */
1719
+ export function auditIdleCompactionConfig({
1720
+ settingsLayers = [],
1721
+ env = {},
1722
+ claudeCodeVersion = null,
1723
+ observedModels = [],
1724
+ maxObservedPrefixTokens = null
1725
+ } = {}) {
1726
+ let idleCompaction = null;
1727
+ let idleCompactionSource = null;
1728
+ let autoCompactEnabled = null;
1729
+ let autoCompactSource = null;
1730
+ let envMinTokensRaw = env?.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS;
1731
+ const configuredModels = [];
1732
+
1733
+ for (const layerEntry of settingsLayers) {
1734
+ const doc = layerEntry?.doc?.parsed;
1735
+ const source = layerEntry?.label || layerEntry?.doc?.path || 'settings.json';
1736
+ if (!doc || typeof doc !== 'object') continue;
1737
+ if (typeof doc.idleCompaction === 'boolean') {
1738
+ idleCompaction = doc.idleCompaction;
1739
+ idleCompactionSource = source;
1740
+ }
1741
+ if (typeof doc.autoCompactEnabled === 'boolean') {
1742
+ autoCompactEnabled = doc.autoCompactEnabled;
1743
+ autoCompactSource = source;
1744
+ }
1745
+ if (typeof doc.model === 'string' && doc.model.trim()) configuredModels.push(doc.model.trim());
1746
+ if (typeof doc.defaultModel === 'string' && doc.defaultModel.trim()) configuredModels.push(doc.defaultModel.trim());
1747
+ if (doc.env && typeof doc.env === 'object') {
1748
+ if (doc.env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS !== undefined) {
1749
+ envMinTokensRaw = doc.env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS;
1750
+ }
1751
+ for (const mk of ['ANTHROPIC_MODEL', 'CLAUDE_MODEL']) {
1752
+ if (typeof doc.env[mk] === 'string' && doc.env[mk].trim()) configuredModels.push(doc.env[mk].trim());
1753
+ }
1754
+ }
1755
+ }
1756
+ if (env?.ANTHROPIC_MODEL) configuredModels.push(String(env.ANTHROPIC_MODEL).trim());
1757
+ if (env?.CLAUDE_MODEL) configuredModels.push(String(env.CLAUDE_MODEL).trim());
1758
+
1759
+ const parsedMinTok = Number(envMinTokensRaw);
1760
+ const idleCompactMinTokens =
1761
+ Number.isFinite(parsedMinTok) && parsedMinTok > 0
1762
+ ? Math.round(parsedMinTok)
1763
+ : DEFAULT_IDLE_COMPACT_MIN_TOKENS;
1764
+
1765
+ const versionSupported = Boolean(
1766
+ claudeCodeVersion && compareSemver(String(claudeCodeVersion), IDLE_COMPACTION_MIN_VERSION) >= 0
1767
+ );
1768
+ const allModels = [...configuredModels, ...(Array.isArray(observedModels) ? observedModels : [])];
1769
+ const claude55Active = allModels.some((m) => /claude-(?:opus|sonnet)-5[.-]5/i.test(String(m || '')));
1770
+
1771
+ if (autoCompactEnabled === false) {
1772
+ const file = autoCompactSource || '~/.claude/settings.json';
1773
+ const message =
1774
+ 'Global autoCompactEnabled: false disables hard overflow protection. Re-enable "autoCompactEnabled": true and set "idleCompaction": false surgically if you want to skip ~54m idle compaction without risking context overflow.';
1775
+ return {
1776
+ status: 'warn',
1777
+ versionSupported,
1778
+ claudeCodeVersion: claudeCodeVersion || null,
1779
+ idleCompaction,
1780
+ autoCompactEnabled,
1781
+ idleCompactMinTokens,
1782
+ claude55Active,
1783
+ idleCompactionAlert: false,
1784
+ coachingMode: 'restore_auto_compact_use_surgical_idle_disable',
1785
+ coachingNote: message,
1786
+ fix: { autoCompactEnabled: true, idleCompaction: false },
1787
+ lints: [
1788
+ {
1789
+ ruleId: 'BO-CFG-10',
1790
+ severity: 'warn',
1791
+ harness: 'claude-code',
1792
+ file,
1793
+ message,
1794
+ remediation: 'Set "autoCompactEnabled": true and use "idleCompaction": false surgically instead.'
1795
+ }
1796
+ ]
1797
+ };
1798
+ }
1799
+
1800
+ if (!versionSupported) {
1801
+ return {
1802
+ status: 'pass',
1803
+ versionSupported: false,
1804
+ claudeCodeVersion: claudeCodeVersion || null,
1805
+ idleCompaction,
1806
+ autoCompactEnabled,
1807
+ idleCompactMinTokens,
1808
+ claude55Active,
1809
+ idleCompactionAlert: false,
1810
+ coachingMode: 'unsupported_version',
1811
+ coachingNote: null,
1812
+ fix: null,
1813
+ lints: []
1814
+ };
1815
+ }
1816
+
1817
+ if (idleCompaction === false) {
1818
+ return {
1819
+ status: 'pass',
1820
+ versionSupported: true,
1821
+ claudeCodeVersion,
1822
+ idleCompaction: false,
1823
+ autoCompactEnabled,
1824
+ idleCompactMinTokens,
1825
+ claude55Active,
1826
+ idleCompactionAlert: false,
1827
+ coachingMode: 'surgical_idle_disabled_overflow_protected',
1828
+ coachingNote: 'Surgical "idleCompaction": false preserves reasoning nuance past 54m idle while keeping autoCompactEnabled active.',
1829
+ fix: null,
1830
+ lints: []
1831
+ };
1832
+ }
1833
+
1834
+ const hasLargePrefix = Number.isFinite(maxObservedPrefixTokens) && maxObservedPrefixTokens >= idleCompactMinTokens;
1835
+ const loweredThreshold = idleCompactMinTokens < DEFAULT_IDLE_COMPACT_MIN_TOKENS;
1836
+ const triggerRoiAlert = Boolean(claude55Active || loweredThreshold || hasLargePrefix);
1837
+
1838
+ if (triggerRoiAlert) {
1839
+ const coachingMode = claude55Active ? 'claude55_compact_miss_backfire_risk' : 'idle_compaction_roi_tradeoff';
1840
+ const file = idleCompactionSource || '~/.claude/settings.json';
1841
+ const message = claude55Active
1842
+ ? `Idle Compaction ROI Risk (v2.1.290+ & #99624): idleCompaction auto-compacts >=${idleCompactMinTokens.toLocaleString('en-US')} tok sessions at ~54m idle, which on Claude 5.5 can miss the warm cache and bill a full cache write while losing reasoning nuance. Set "idleCompaction": false surgically while keeping "autoCompactEnabled": true for hard overflow protection.`
1843
+ : `Idle Compaction ROI Advisory (v2.1.290+): idleCompaction triggers around ~54m idle (threshold ${idleCompactMinTokens.toLocaleString('en-US')} tok) before 1h cache TTL. If preserving multi-step reasoning nuance outweighs cold-resume cost, set "idleCompaction": false surgically and keep "autoCompactEnabled": true for hard overflow protection.`;
1844
+ return {
1845
+ status: 'warn',
1846
+ versionSupported: true,
1847
+ claudeCodeVersion,
1848
+ idleCompaction,
1849
+ autoCompactEnabled,
1850
+ idleCompactMinTokens,
1851
+ claude55Active,
1852
+ idleCompactionAlert: true,
1853
+ coachingMode,
1854
+ coachingNote: message,
1855
+ fix: { idleCompaction: false, autoCompactEnabled: true },
1856
+ lints: [
1857
+ {
1858
+ ruleId: 'BO-CFG-10',
1859
+ severity: 'warn',
1860
+ harness: 'claude-code',
1861
+ file,
1862
+ message,
1863
+ remediation: 'Set "idleCompaction": false surgically in settings.json while keeping "autoCompactEnabled": true.'
1864
+ }
1865
+ ]
1866
+ };
1867
+ }
1868
+
1869
+ return {
1870
+ status: 'info',
1871
+ versionSupported: true,
1872
+ claudeCodeVersion,
1873
+ idleCompaction,
1874
+ autoCompactEnabled,
1875
+ idleCompactMinTokens,
1876
+ claude55Active,
1877
+ idleCompactionAlert: false,
1878
+ coachingMode: 'default_idle_compaction_active',
1879
+ coachingNote: `v2.1.290+ idleCompaction (~54m idle, min ${idleCompactMinTokens.toLocaleString('en-US')} tok) active. Only set "idleCompaction": false surgically when reasoning nuance outweighs cold-resume cost; keep "autoCompactEnabled": true.`,
1880
+ fix: null,
1881
+ lints: []
1882
+ };
1883
+ }
1884
+
1885
+ const VOLATILE_NEGATION_RE =
1886
+ /\b(?:never|do\s+not|don't|avoid|forbid|forbidden|prohibit|anti-pattern|breaks?\s+(?:the\s+)?(?:kv\s+|prompt\s+)?cache|invalidat(?:e|es|ing)\s+(?:the\s+)?(?:kv\s+|prompt\s+)?cache)\b/i;
1887
+ const VOLATILE_TEMPLATE_RE =
1888
+ /(\{\{\s*(?:timestamp|now|current_time|current_date|date|time|uuid|request_id|session_uuid)\s*\}\}|\$\{\s*(?:Date\.now\(\)|new\s+Date\(|crypto\.randomUUID\()|\$\(\s*(?:date\b|uuidgen\b))/i;
1889
+ const VOLATILE_INSTRUCTION_RE =
1890
+ /\b(?:always|must|every\s+(?:turn|request|prompt)|prepend|inject|include|embed|insert|put)\b.{0,70}\b(?:current\s+(?:timestamp|time|date(?:\s+and\s+time)?)|live\s+timestamp|unix\s+timestamp|epoch\s+time|random\s+uuid|uuidv4|unique\s+request[_\s-]?id)\b/i;
1891
+ const SESSION_START_VOLATILE_CMD_RE =
1892
+ /\b(?:date\s+(?:\+|-[uIr])|Get-Date\b|uuidgen\b|New-Guid\b|Date\.now\(\)|randomUUID\(\))/i;
1893
+
1894
+ /**
1895
+ * Scans markdown rule text (outside fenced code blocks) for volatile timestamp/UUID
1896
+ * prompt-prefix patterns that invalidate KV prefix caches every turn.
1897
+ */
1898
+ export function scanVolatilePromptPatterns(markdown = '') {
1899
+ const lines = String(markdown || '').split(/\r?\n/);
1900
+ const findings = [];
1901
+ let inFence = false;
1902
+
1903
+ for (let i = 0; i < lines.length; i++) {
1904
+ const line = lines[i];
1905
+ if (/^\s*(?:```|~~~)/.test(line)) {
1906
+ inFence = !inFence;
1907
+ continue;
1908
+ }
1909
+ if (inFence) continue;
1910
+ const trimmed = line.trim();
1911
+ if (!trimmed) continue;
1912
+ if (VOLATILE_NEGATION_RE.test(trimmed)) continue;
1913
+
1914
+ if (VOLATILE_TEMPLATE_RE.test(trimmed)) {
1915
+ findings.push({
1916
+ lineNumber: i + 1,
1917
+ patternKind: 'volatile_template',
1918
+ snippet: trimmed.slice(0, 140)
1919
+ });
1920
+ continue;
1921
+ }
1922
+ if (VOLATILE_INSTRUCTION_RE.test(trimmed)) {
1923
+ findings.push({
1924
+ lineNumber: i + 1,
1925
+ patternKind: 'volatile_instruction',
1926
+ snippet: trimmed.slice(0, 140)
1927
+ });
1928
+ }
1929
+ }
1930
+
1931
+ return {
1932
+ matched: findings.length > 0,
1933
+ findings
1934
+ };
1935
+ }
1936
+
1937
+ /**
1938
+ * BO-CFG-11: Audits active always-on rules files and `SessionStart` hook commands
1939
+ * for volatile timestamps, dates, or UUIDs that bust the token-0 prompt prefix.
1940
+ */
1941
+ export function auditVolatilePromptPrefix({
1942
+ ruleFilePaths = [],
1943
+ settingsLayers = [],
1944
+ harness = 'claude-code'
1945
+ } = {}) {
1946
+ const seen = new Set();
1947
+ const findings = [];
1948
+ const lints = [];
1949
+ const remediation =
1950
+ 'Remove dynamic timestamps/UUIDs from static rules or SessionStart hooks; append turn-specific metadata at the tail of user turns if needed.';
1951
+
1952
+ for (const fp of ruleFilePaths) {
1953
+ if (!fp || !fs.existsSync(fp)) continue;
1954
+ let dedupeKey = canonicalizePath(fp);
1955
+ try {
1956
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
1957
+ } catch {
1958
+ // ignore: fallback to canonicalized path when realpath fails
1959
+ }
1960
+ if (seen.has(dedupeKey)) continue;
1961
+ seen.add(dedupeKey);
1962
+
1963
+ try {
1964
+ const text = fs.readFileSync(fp, 'utf8');
1965
+ if (harness === 'antigravity') {
1966
+ const triggerMode = parseRuleTriggerMode(text);
1967
+ if (triggerMode === 'model_decision' || triggerMode === 'manual') continue;
1968
+ }
1969
+ const scan = scanVolatilePromptPatterns(text);
1970
+ if (scan.matched) {
1971
+ const normFile = String(fp).replace(/\\/g, '/');
1972
+ const first = scan.findings[0];
1973
+ findings.push({
1974
+ file: normFile,
1975
+ sourceType: 'rules_file',
1976
+ matches: scan.findings
1977
+ });
1978
+ lints.push({
1979
+ ruleId: 'BO-CFG-11',
1980
+ severity: 'warn',
1981
+ harness,
1982
+ file: normFile,
1983
+ message: `Volatile Prompt Prefix Risk (BO-CFG-11): ${normFile}:${first.lineNumber} injects dynamic timestamp/UUID (${first.patternKind}), mutating the token-0 prefix each turn, collapsing KV cache reuse and triggering 1.25x cache-write surcharges.`,
1984
+ remediation
1985
+ });
1986
+ }
1987
+ } catch {
1988
+ // ignore: unreadable rules markdown file
1989
+ }
1990
+ }
1991
+
1992
+ for (const layerEntry of settingsLayers) {
1993
+ const doc = layerEntry?.doc?.parsed;
1994
+ if (!doc || typeof doc !== 'object') continue;
1995
+ const fileLabel = String(layerEntry?.label || layerEntry?.doc?.path || 'settings.json').replace(/\\/g, '/');
1996
+ const sessionStartHooks = doc?.hooks?.SessionStart;
1997
+ if (!Array.isArray(sessionStartHooks)) continue;
1998
+ const matchedCmds = [];
1999
+ for (const entry of sessionStartHooks) {
2000
+ const hookList = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
2001
+ for (const h of hookList) {
2002
+ const cmd = typeof h?.command === 'string' ? h.command.trim() : '';
2003
+ if (cmd && SESSION_START_VOLATILE_CMD_RE.test(cmd)) {
2004
+ matchedCmds.push(cmd.slice(0, 140));
2005
+ }
2006
+ }
2007
+ }
2008
+ if (matchedCmds.length > 0) {
2009
+ findings.push({
2010
+ file: fileLabel,
2011
+ sourceType: 'session_start_hook',
2012
+ commands: matchedCmds
2013
+ });
2014
+ lints.push({
2015
+ ruleId: 'BO-CFG-11',
2016
+ severity: 'warn',
2017
+ harness,
2018
+ file: fileLabel,
2019
+ message: `Volatile Prompt Prefix Risk (BO-CFG-11): SessionStart hook in ${fileLabel} runs "${matchedCmds[0]}", mutating the token-0 prefix each turn, collapsing KV cache reuse and triggering 1.25x cache-write surcharges.`,
2020
+ remediation
2021
+ });
2022
+ }
2023
+ }
2024
+
2025
+ return {
2026
+ status: lints.length > 0 ? 'warn' : 'pass',
2027
+ findings,
2028
+ lints
2029
+ };
2030
+ }
2031
+
2032
+ /**
2033
+ * Runs Turn-0 startup config, rules-count, and eager-only MCP audit for Claude Code.
2034
+ */
2035
+ export function runClaudeStartupAudit({
2036
+ homeDir = getHomeDir(),
2037
+ cwd = process.cwd(),
2038
+ hostPlatform = process.platform,
2039
+ days = 7,
2040
+ env = process.env,
2041
+ claudeCodeVersion = null,
2042
+ nowMs = Date.now(),
2043
+ manifestDirs = [],
2044
+ maxTelemetryFiles = DEFAULT_TELEMETRY_MAX_FILES,
2045
+ maxTelemetryBytes = DEFAULT_TELEMETRY_MAX_BYTES
2046
+ } = {}) {
2047
+ const paths = resolveClaudeConfigPaths({ homeDir, cwd, platform: hostPlatform });
2048
+ const telemetry = scanClaudeTelemetrySummary({
2049
+ projectsDir: paths.projectsDir,
2050
+ days,
2051
+ nowMs,
2052
+ maxFiles: maxTelemetryFiles,
2053
+ maxTotalBytes: maxTelemetryBytes
2054
+ });
2055
+
2056
+ const detectedClaudeVersion = claudeCodeVersion || telemetry.claudeCodeVersion || null;
2057
+ const observedEntrypoint =
2058
+ telemetry.entrypoints.length === 1 && telemetry.entrypoints[0] === 'sdk-ts'
2059
+ ? 'sdk-ts'
2060
+ : telemetry.entrypoints[0] || 'cli';
2061
+
2062
+ const claudeJson = parseJsoncReadOnly(paths.claudeJson);
2063
+ const userSettings = parseJsoncReadOnly(paths.userSettings);
2064
+ const projectSettings = parseJsoncReadOnly(paths.projectSettings);
2065
+ const projectLocalSettings = parseJsoncReadOnly(paths.projectLocalSettings);
2066
+ const projectMcp = parseJsoncReadOnly(paths.projectMcpJson);
2067
+ const settingsLayers = [
2068
+ { doc: userSettings, label: '~/.claude/settings.json' },
2069
+ { doc: projectSettings, label: '.claude/settings.json' },
2070
+ { doc: projectLocalSettings, label: '.claude/settings.local.json' }
2071
+ ];
2072
+ const layers = [userSettings.parsed, projectSettings.parsed, projectLocalSettings.parsed].filter(Boolean);
2073
+
2074
+ const chromeOnDemandCmd = buildClaudeCliCommand(['--chrome'], { platform: hostPlatform });
2075
+ const artifactDisallowedCmd = buildClaudeCliCommand(['--disallowedTools', 'Artifact'], { platform: hostPlatform });
2076
+
2077
+ // Check 1: Chrome default enabled strictly in ~/.claude.json
2078
+ const chromeVal = claudeJson.parsed?.claudeInChromeDefaultEnabled === true;
2079
+ const chromeWarn = chromeVal && telemetry.browserToolCalls7d === 0;
2080
+ const misplacedChromeKey = auditMisplacedChromeKey(settingsLayers);
2081
+ const chromeDefaultEnabled = {
2082
+ status: chromeWarn ? 'warn' : 'pass',
2083
+ keyLocation: '~/.claude.json',
2084
+ value: Boolean(claudeJson.parsed?.claudeInChromeDefaultEnabled),
2085
+ browserToolCalls7d: telemetry.browserToolCalls7d,
2086
+ misplacedInSettingsFiles: misplacedChromeKey.misplacedFiles,
2087
+ reclaimableTokensPerTurn: chromeWarn ? CALIBRATION_MANIFEST.claudeCodeTurn0.chromeTools.tokens : 0,
2088
+ isEstimated: true,
2089
+ fix: chromeWarn
2090
+ ? `Set "claudeInChromeDefaultEnabled": false in ~/.claude.json and launch browser sessions on demand with: ${chromeOnDemandCmd}`
2091
+ : null
2092
+ };
2093
+
2094
+ // Check 2: Artifact built-in tool & one-way global lock
2095
+ // Only warn when explicitly configured with deprecated `disableArtifact: true` or backed by observed local telemetry.
2096
+ let enableArtifactValue = null;
2097
+ let deprecatedDisableArtifactPresent = false;
2098
+ for (const layer of layers) {
2099
+ if (layer.enableArtifact !== undefined) enableArtifactValue = layer.enableArtifact;
2100
+ if (layer.disableArtifact === true) deprecatedDisableArtifactPresent = true;
2101
+ }
2102
+ const sdkTsDropsArtifact =
2103
+ observedEntrypoint === 'sdk-ts' && String(env?.CLAUDE_CODE_ARTIFACT || '').trim() !== '1';
2104
+ const hasObservedTelemetry = telemetry.sessionsScanned > 0;
2105
+ let artifactStatus = 'pass';
2106
+ let artifactReclaimable = 0;
2107
+ if (deprecatedDisableArtifactPresent) {
2108
+ artifactStatus = 'warn';
2109
+ artifactReclaimable =
2110
+ enableArtifactValue === false ? 0 : CALIBRATION_MANIFEST.claudeCodeTurn0.artifactTool.tokens;
2111
+ } else if (hasObservedTelemetry && !sdkTsDropsArtifact && enableArtifactValue !== false && telemetry.artifactCalls7d === 0) {
2112
+ artifactStatus = 'warn';
2113
+ artifactReclaimable = CALIBRATION_MANIFEST.claudeCodeTurn0.artifactTool.tokens;
2114
+ }
2115
+
2116
+ const artifactTool = {
2117
+ status: artifactStatus,
2118
+ enableArtifactValue,
2119
+ deprecatedDisableArtifactPresent,
2120
+ entrypoint: observedEntrypoint,
2121
+ artifactCalls7d: telemetry.artifactCalls7d,
2122
+ oneWayLockWarning:
2123
+ 'Setting enableArtifact: false in settings.json is a one-way global lock and cannot be re-enabled per session with --settings.',
2124
+ reclaimableTokensPerTurn: artifactReclaimable,
2125
+ isEstimated: true,
2126
+ fixes:
2127
+ artifactStatus === 'warn'
2128
+ ? {
2129
+ ...(deprecatedDisableArtifactPresent
2130
+ ? { migrateDeprecated: 'Replace deprecated "disableArtifact": true with "enableArtifact": false in ~/.claude/settings.json.' }
2131
+ : {}),
2132
+ occasionalArtifacts: `Leave "enableArtifact" unset and run terminal coding with: ${artifactDisallowedCmd}`
2133
+ }
2134
+ : null
2135
+ };
2136
+
2137
+ // Check 3: Repo-local Turn-0 focus (suppress speculative global findings & unverified global keys)
2138
+ let disableBundledSkills = false;
2139
+ let workflowsDisabled = false;
2140
+ for (const layer of layers) {
2141
+ if (layer.disableBundledSkills === true) disableBundledSkills = true;
2142
+ if (layer.disableWorkflows === true || layer.enableWorkflows === false) workflowsDisabled = true;
2143
+ }
2144
+ const repoMentionsAnthropicSdk = detectAnthropicSdkMarkers(paths.cwd);
2145
+ const bundledSkillsAndWorkflows = {
2146
+ status: 'pass',
2147
+ disableBundledSkills,
2148
+ workflowsDisabled,
2149
+ repoMentionsAnthropicSdk,
2150
+ priority: repoMentionsAnthropicSdk ? 'high' : 'normal',
2151
+ reclaimableTokensPerTurn: 0,
2152
+ isEstimated: true,
2153
+ unverifiedGlobalKeysRemoved: true,
2154
+ fix: null
2155
+ };
2156
+
2157
+ // Check 4: Eager-only MCP gate
2158
+ const mcpStartupTax = evaluateClaudeEagerMcpGate({
2159
+ paths,
2160
+ env,
2161
+ claudeCodeVersion: detectedClaudeVersion,
2162
+ claudeJsonParsed: claudeJson.parsed,
2163
+ userSettingsParsed: userSettings.parsed,
2164
+ projSettingsParsed: projectSettings.parsed,
2165
+ projLocalSettingsParsed: projectLocalSettings.parsed,
2166
+ mcpToolCalls7d: telemetry.mcpToolCalls7d,
2167
+ schemaTokensByServer: telemetry.schemaTokensByServer
2168
+ });
2169
+
2170
+ const rulesBucket = auditRulesFiles(paths.rulesFiles);
2171
+ const strictJsonSyntax = collectStrictJsonLints([
2172
+ { res: claudeJson },
2173
+ { res: userSettings },
2174
+ { res: projectSettings },
2175
+ { res: projectLocalSettings },
2176
+ { res: projectMcp }
2177
+ ]);
2178
+ const localSettingsSecrets = auditLocalSettingsSecrets(projectLocalSettings, paths.cwd);
2179
+ const mcpToolViolations = scanMcpToolNameLengthViolations({
2180
+ homeDir: paths.homeDir,
2181
+ workspacePath: paths.cwd,
2182
+ observedToolNames: telemetry.observedMcpToolNames || []
2183
+ });
2184
+ const mcpToolNameLength = {
2185
+ status: mcpToolViolations.violations.length > 0 ? 'warn' : 'pass',
2186
+ maxLength: mcpToolViolations.maxLength,
2187
+ violations: mcpToolViolations.violations
2188
+ };
2189
+ const mcpListChanged = scanMcpListChangedCapabilities({
2190
+ homeDir: paths.homeDir,
2191
+ workspacePath: paths.cwd,
2192
+ manifestDirs,
2193
+ runtimeListChangedServers: telemetry.runtimeListChangedServers,
2194
+ maxObservedCachedPrefixTokens: telemetry.maxCachedPrefixTokens
2195
+ });
2196
+ const customAgents = scanClaudeCustomAgentSpecs({
2197
+ homeDir: paths.homeDir,
2198
+ cwd: paths.cwd
2199
+ });
2200
+ const subagentCount =
2201
+ telemetry.subagentSpawns7d ||
2202
+ (telemetry.sidechainTurns7d > 0 ? 1 : 0) ||
2203
+ customAgents.totalAgents;
2204
+ const subagentMcpInstructionsTax = estimateSubagentMcpInstructionsTax({
2205
+ connectedServerNames: mcpStartupTax.configuredServerNames,
2206
+ subagentCount,
2207
+ observedMcpInstructionsDeltaChars: telemetry.observedMcpInstructionsDeltaChars
2208
+ });
2209
+ const deprecatedModelsAndFlags = auditRetiredModelsAndDeprecatedFlags({
2210
+ cwd: paths.cwd,
2211
+ env,
2212
+ settingsLayers,
2213
+ nowMs
2214
+ });
2215
+ const idleCompactionRoi = auditIdleCompactionConfig({
2216
+ settingsLayers,
2217
+ env,
2218
+ claudeCodeVersion: detectedClaudeVersion,
2219
+ observedModels: telemetry.observedModels || [],
2220
+ maxObservedPrefixTokens: telemetry.maxCachedPrefixTokens
2221
+ });
2222
+ const volatilePrefix = auditVolatilePromptPrefix({
2223
+ ruleFilePaths: paths.rulesFiles,
2224
+ settingsLayers,
2225
+ harness: 'claude-code'
2226
+ });
2227
+ const sdkCliDetected = telemetry.entrypoints.includes('sdk-cli');
2228
+ const sdkCliSessionsCount = telemetry.sdkCliSessions7d || (sdkCliDetected ? 1 : 0);
2229
+ const sdkCliQuotaHeuristic = {
2230
+ detected: sdkCliDetected,
2231
+ sessions7d: telemetry.sdkCliSessions7d || 0,
2232
+ multiplier: SDK_CLI_QUOTA_MULTIPLIER_HEURISTIC,
2233
+ isHeuristic: true,
2234
+ status: sdkCliDetected ? 'info' : 'pass',
2235
+ message: sdkCliDetected
2236
+ ? `Headless claude -p (sdk-cli) observed in ${sdkCliSessionsCount} session(s): observational telemetry indicates ~1.8x 5h quota burn per token vs interactive CLI (#97074; heuristic estimate, not a guaranteed constant).`
2237
+ : null
2238
+ };
2239
+
2240
+ const lints = [
2241
+ ...strictJsonSyntax.lints,
2242
+ ...misplacedChromeKey.lints,
2243
+ ...localSettingsSecrets.lints,
2244
+ ...idleCompactionRoi.lints,
2245
+ ...volatilePrefix.lints
2246
+ ];
2247
+ if (mcpStartupTax.gateReasons.includes('ssh_forced_disable_experimental_betas')) {
2248
+ lints.push({
2249
+ ruleId: 'BO-CFG-03',
2250
+ severity: 'warn',
2251
+ harness: 'claude-code',
2252
+ file: 'env',
2253
+ message:
2254
+ 'SSH ToolSearch Override (#112307): Desktop/SSH sessions force CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1, disabling ToolSearch deferral (~15k-70k eager leak). Disable unused MCP servers before starting SSH sessions.',
2255
+ remediation: 'Disable unused MCP servers before starting SSH sessions.'
2256
+ });
2257
+ }
2258
+ if (
2259
+ mcpStartupTax.gateReasons.includes('custom_gateway_toolsearch_fallback') ||
2260
+ mcpStartupTax.gateReasons.includes('custom_gateway_claude_code_lt_2.1.304')
2261
+ ) {
2262
+ lints.push({
2263
+ ruleId: 'BO-CFG-04',
2264
+ severity: 'warn',
2265
+ harness: 'claude-code',
2266
+ file: 'env',
2267
+ message:
2268
+ 'Gateway ToolSearch Fallback (#95087): Custom ANTHROPIC_BASE_URL gateways rejecting beta headers trigger v2.1.305+ silent retry without ToolSearch, dumping full MCP schemas on every turn. Audit /context to confirm deferral.',
2269
+ remediation: 'Audit /context to confirm deferral or verify gateway beta header support.'
2270
+ });
2271
+ }
2272
+ for (const v of mcpToolViolations.violations) {
2273
+ lints.push({
2274
+ ruleId: 'BO-MCP-05',
2275
+ severity: 'warn',
2276
+ harness: 'claude-code',
2277
+ file: v.source,
2278
+ message: `ToolSearch 64-Char Session Brick Risk (#97616): Tool ${v.fullName} (${v.length} chars > 64) causes permanent API 400 errors on ToolSearch load. Shorten the MCP server alias in config.`,
2279
+ remediation: `Shorten MCP server alias "${v.serverName}" so mcp__<server>__<tool> <= 64 chars.`
2280
+ });
2281
+ }
2282
+ if (mcpListChanged.status === 'warn') {
2283
+ for (const fsrv of mcpListChanged.flaggedServers) {
2284
+ lints.push({
2285
+ ruleId: 'BO-MCP-06',
2286
+ severity: 'warn',
2287
+ harness: 'claude-code',
2288
+ file: fsrv.source,
2289
+ message: `Dynamic MCP Cache Bust Risk (#2812): Server "${fsrv.serverName}" advertises ${fsrv.reason}, which mutates the tool prefix and invalidates KV prompt caches mid-session.`,
2290
+ remediation: `Pin tools statically or disconnect "${fsrv.serverName}" between sessions when not needed.`
2291
+ });
2292
+ }
2293
+ }
2294
+ if (subagentMcpInstructionsTax.triggered) {
2295
+ const allowNote =
2296
+ customAgents.narrowToolsAgents > 0
2297
+ ? ` (${customAgents.narrowToolsAgents} custom agent(s) use narrow tools: allowlists that do not filter MCP instructions)`
2298
+ : '';
2299
+ lints.push({
2300
+ ruleId: 'BO-MCP-09',
2301
+ severity: 'warn',
2302
+ harness: 'claude-code',
2303
+ file: paths.projectMcpJson.replace(/\\/g, '/'),
2304
+ message: `Subagent mcp_instructions_delta Multiplication (#104791): ${subagentMcpInstructionsTax.connectedServerCount} connected MCP servers x ${subagentMcpInstructionsTax.subagentCount} subagents inject ~${subagentMcpInstructionsTax.perSubagentTokensEst.toLocaleString('en-US')} tok/subagent (~${subagentMcpInstructionsTax.totalTaxTokens.toLocaleString('en-US')} tok total)${allowNote}.`,
2305
+ remediation: 'Disconnect unused MCP servers between sessions before spawning subagents.'
2306
+ });
2307
+ }
2308
+ lints.push(...deprecatedModelsAndFlags.lints);
2309
+
2310
+ let issueCount = 0;
2311
+ let estimatedTurn0ReclaimableTokens = 0;
2312
+ for (const chk of [chromeDefaultEnabled, artifactTool, bundledSkillsAndWorkflows]) {
2313
+ if (chk.status === 'warn') {
2314
+ issueCount += 1;
2315
+ estimatedTurn0ReclaimableTokens += Number(chk.reclaimableTokensPerTurn || 0);
2316
+ }
2317
+ }
2318
+ const disableArtifactAlreadyCounted =
2319
+ artifactTool.status === 'warn' && artifactTool.deprecatedDisableArtifactPresent === true;
2320
+ let mcpTaxCounted = false;
2321
+ if (mcpStartupTax.eagerGateActive && mcpStartupTax.startupTaxTokensPerTurn > 0) {
2322
+ issueCount += 1;
2323
+ estimatedTurn0ReclaimableTokens += mcpStartupTax.startupTaxTokensPerTurn;
2324
+ mcpTaxCounted = true;
2325
+ }
2326
+ if (rulesBucket.status === 'warn' || rulesBucket.status === 'caution') {
2327
+ issueCount += 1;
2328
+ }
2329
+ for (const l of lints) {
2330
+ if ((l.ruleId === 'BO-CFG-03' || l.ruleId === 'BO-CFG-04') && mcpTaxCounted) continue;
2331
+ if (l.ruleId === 'BO-CFG-09' && disableArtifactAlreadyCounted && l.message.includes('"disableArtifact"')) continue;
2332
+ issueCount += 1;
2333
+ }
2334
+
2335
+ return {
2336
+ ok: true,
2337
+ schemaVersion: '1.0.0',
2338
+ platform: hostPlatform,
2339
+ harnessesAudited: ['claude-code'],
2340
+ calibration: {
2341
+ claudeCodeVersion: detectedClaudeVersion,
2342
+ entrypointObserved: observedEntrypoint,
2343
+ valuesAreEstimated: true,
2344
+ telemetrySessionsScanned: telemetry.sessionsScanned,
2345
+ telemetryBytesScanned: telemetry.bytesScanned,
2346
+ telemetryScanTruncated: telemetry.scanTruncated
2347
+ },
2348
+ claudeCode: {
2349
+ configFiles: {
2350
+ claudeJson: formatConfigStatus(claudeJson),
2351
+ userSettings: formatConfigStatus(userSettings),
2352
+ projectSettings: formatConfigStatus(projectSettings),
2353
+ projectLocalSettings: formatConfigStatus(projectLocalSettings),
2354
+ projectMcp: formatConfigStatus(projectMcp)
2355
+ },
2356
+ checks: {
2357
+ chromeDefaultEnabled,
2358
+ artifactTool,
2359
+ bundledSkillsAndWorkflows,
2360
+ mcpStartupTax,
2361
+ strictJsonSyntax,
2362
+ misplacedChromeKey,
2363
+ mcpToolNameLength,
2364
+ mcpListChanged,
2365
+ subagentMcpInstructionsTax,
2366
+ customAgents,
2367
+ localSettingsSecrets,
2368
+ deprecatedModelsAndFlags,
2369
+ idleCompactionRoi,
2370
+ volatilePrefix,
2371
+ sdkCliQuotaHeuristic
2372
+ }
2373
+ },
2374
+ rulesAudit: {
2375
+ thresholds: RULES_THRESHOLDS,
2376
+ byHarness: {
2377
+ claudeCode: rulesBucket
2378
+ }
2379
+ },
2380
+ lints,
2381
+ summary: {
2382
+ issueCount,
2383
+ estimatedTurn0ReclaimableTokens,
2384
+ estimatedWeeklySavingsUsd: estimateWeeklySavingsUsd(estimatedTurn0ReclaimableTokens, nowMs)
2385
+ }
2386
+ };
2387
+ }
2388
+
2389
+ /**
2390
+ * Formats `runClaudeStartupAudit()` for terminal output with zero em dashes.
2391
+ */
2392
+ export function formatClaudeStartupAuditReport(report) {
2393
+ if (!report?.ok) return 'Burnoff Startup Audit failed\n';
2394
+ const s = report.summary || {};
2395
+ const c = report.claudeCode?.checks;
2396
+ const r = report.rulesAudit?.byHarness?.claudeCode;
2397
+ const lines = [
2398
+ `Burnoff Claude Code Turn-0 Startup Audit | Findings: ${s.issueCount ?? 0} | Reclaimable: ~${Number(s.estimatedTurn0ReclaimableTokens || 0).toLocaleString('en-US')} tok/turn (est.) (~$${Number(s.estimatedWeeklySavingsUsd || 0).toFixed(2)}/wk)`
2399
+ ];
2400
+
2401
+ if (c) {
2402
+ lines.push(` - ${c.mcpStartupTax.summaryLine}`);
2403
+ if (c.mcpStartupTax.unusedEagerServers?.length) {
2404
+ lines.push(
2405
+ ` Unused eager servers (7d): ${c.mcpStartupTax.unusedEagerServers.map((x) => `${x.name} (~${x.tokensEst} tok)`).join(', ')}`
2406
+ );
2407
+ }
2408
+ if (c.chromeDefaultEnabled.status === 'warn') {
2409
+ lines.push(
2410
+ ` - [warn] Chrome default enabled in ~/.claude.json with 0 browser calls in 7d (~${c.chromeDefaultEnabled.reclaimableTokensPerTurn} tok/turn est.)`
2411
+ );
2412
+ lines.push(` Fix: ${c.chromeDefaultEnabled.fix}`);
2413
+ } else {
2414
+ lines.push(' - [pass] Chrome default disabled (or actively used)');
2415
+ }
2416
+ if (c.artifactTool.status === 'warn') {
2417
+ lines.push(
2418
+ ` - [warn] Artifact built-in tool active (${c.artifactTool.entrypoint}, 0 calls in 7d, ~${c.artifactTool.reclaimableTokensPerTurn} tok/turn est.)`
2419
+ );
2420
+ lines.push(` Note: ${c.artifactTool.oneWayLockWarning}`);
2421
+ if (c.artifactTool.fixes?.migrateDeprecated) {
2422
+ lines.push(` Fix (migrate): ${c.artifactTool.fixes.migrateDeprecated}`);
2423
+ }
2424
+ if (c.artifactTool.fixes?.neverUseArtifacts) {
2425
+ lines.push(` Fix (never use): ${c.artifactTool.fixes.neverUseArtifacts}`);
2426
+ }
2427
+ if (c.artifactTool.fixes?.occasionalArtifacts) {
2428
+ lines.push(` Fix (occasional): ${c.artifactTool.fixes.occasionalArtifacts}`);
2429
+ }
2430
+ } else {
2431
+ lines.push(` - [pass] Artifact tool (${c.artifactTool.entrypoint})`);
2432
+ }
2433
+ if (c.bundledSkillsAndWorkflows.status === 'warn' && c.bundledSkillsAndWorkflows.fix) {
2434
+ const prio = c.bundledSkillsAndWorkflows.priority === 'high' ? ' [HIGH: Anthropic SDK markers detected]' : '';
2435
+ lines.push(
2436
+ ` - [warn] Bundled skills/workflows enabled${prio} (~${c.bundledSkillsAndWorkflows.reclaimableTokensPerTurn} tok/turn est.)`
2437
+ );
2438
+ lines.push(` Fix: ${c.bundledSkillsAndWorkflows.fix}`);
2439
+ } else {
2440
+ lines.push(' - [pass] Repo-local Turn-0 focus (no unverified global settings keys recommended)');
2441
+ }
2442
+ if (c.subagentMcpInstructionsTax?.triggered) {
2443
+ lines.push(
2444
+ ` - [warn] Subagent mcp_instructions_delta tax (#104791): ~${c.subagentMcpInstructionsTax.perSubagentTokensEst.toLocaleString('en-US')} tok/subagent across ${c.subagentMcpInstructionsTax.subagentCount} subagents (${c.subagentMcpInstructionsTax.connectedServerCount} servers)`
2445
+ );
2446
+ }
2447
+ if (c.idleCompactionRoi?.status === 'warn' && c.idleCompactionRoi.coachingNote) {
2448
+ lines.push(` - [warn] ${c.idleCompactionRoi.coachingNote}`);
2449
+ } else if (c.idleCompactionRoi?.coachingMode === 'surgical_idle_disabled_overflow_protected') {
2450
+ lines.push(` - [pass] ${c.idleCompactionRoi.coachingNote}`);
2451
+ }
2452
+ if (c.sdkCliQuotaHeuristic?.detected && c.sdkCliQuotaHeuristic.message) {
2453
+ lines.push(` - [info] ${c.sdkCliQuotaHeuristic.message}`);
2454
+ }
2455
+ }
2456
+
2457
+ if (r) {
2458
+ lines.push(
2459
+ ` - Rules [${r.status}]: ${r.files.length} file(s), ${r.totalRuleCount} discrete rules, ~${r.totalTokensEst.toLocaleString('en-US')} est. tokens`
2460
+ );
2461
+ for (const adv of r.advisories || []) {
2462
+ lines.push(` Advisories: ${adv}`);
2463
+ }
2464
+ }
2465
+
2466
+ if (Array.isArray(report.lints) && report.lints.length > 0) {
2467
+ lines.push(' Silent-Failure & Security Lints:');
2468
+ for (const l of report.lints) {
2469
+ lines.push(` - [${l.severity}] ${l.ruleId}: ${l.message}`);
2470
+ }
2471
+ }
2472
+
2473
+ return lines.join('\n') + '\n';
2474
+ }
2475
+
2476
+ function listMarkdownFilesInDir(dirPath) {
2477
+ if (!dirPath || !fs.existsSync(dirPath)) return [];
2478
+ try {
2479
+ return fs
2480
+ .readdirSync(dirPath, { withFileTypes: true })
2481
+ .filter((e) => e.isFile() && /\.md$/i.test(e.name))
2482
+ .map((e) => path.join(dirPath, e.name));
2483
+ } catch {
2484
+ return []; // ignore: unreadable rules directory
2485
+ }
2486
+ }
2487
+
2488
+ function parseRuleTriggerMode(markdown = '') {
2489
+ const m = String(markdown || '').match(/^---\s*\r?\n([\s\S]*?)\r?\n---/);
2490
+ if (!m) return 'always_on';
2491
+ const trig = m[1].match(/^\s*trigger\s*:\s*([^\r\n#]+)/im);
2492
+ if (!trig) return 'always_on';
2493
+ return trig[1].trim().toLowerCase() || 'always_on';
2494
+ }
2495
+
2496
+ function auditAntigravityRulesFiles(filePaths = []) {
2497
+ const seen = new Set();
2498
+ const files = [];
2499
+ let totalTokensEst = 0;
2500
+ let totalRuleCount = 0;
2501
+ let onDemandCount = 0;
2502
+
2503
+ for (const fp of filePaths) {
2504
+ if (!fp || !fs.existsSync(fp)) continue;
2505
+ let dedupeKey = canonicalizePath(fp);
2506
+ try {
2507
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
2508
+ } catch {
2509
+ // ignore: fallback to canonicalized path when realpath fails
2510
+ }
2511
+ if (seen.has(dedupeKey)) continue;
2512
+ seen.add(dedupeKey);
2513
+
2514
+ try {
2515
+ const text = fs.readFileSync(fp, 'utf8');
2516
+ const triggerMode = parseRuleTriggerMode(text);
2517
+ const chars = text.length;
2518
+ const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
2519
+ const ruleCount = countDiscreteRules(text);
2520
+ const isAlwaysOn = triggerMode !== 'model_decision' && triggerMode !== 'manual';
2521
+ files.push({
2522
+ path: String(fp).replace(/\\/g, '/'),
2523
+ triggerMode,
2524
+ alwaysOn: isAlwaysOn,
2525
+ chars,
2526
+ tokensEst,
2527
+ ruleCount
2528
+ });
2529
+ if (isAlwaysOn) {
2530
+ totalTokensEst += tokensEst;
2531
+ totalRuleCount += ruleCount;
2532
+ } else {
2533
+ onDemandCount += 1;
2534
+ }
2535
+ } catch {
2536
+ // ignore: unreadable Antigravity rule markdown
2537
+ }
2538
+ }
2539
+
2540
+ let status = 'pass';
2541
+ const advisories = [];
2542
+ if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
2543
+ status = 'warn';
2544
+ advisories.push(
2545
+ `IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} always-on rules); set trigger: model_decision or move domain rules into skills.`
2546
+ );
2547
+ } else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
2548
+ status = 'caution';
2549
+ advisories.push(
2550
+ `Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} always-on rules).`
2551
+ );
2552
+ }
2553
+ if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
2554
+ status = 'warn';
2555
+ advisories.push(
2556
+ `Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across always-on Antigravity rules).`
2557
+ );
2558
+ }
2559
+
2560
+ return { files, totalTokensEst, totalRuleCount, onDemandCount, status, advisories };
2561
+ }
2562
+
2563
+ /**
2564
+ * Runs Turn-0 startup config, rules-count, and MCP config audit for Google Antigravity.
2565
+ */
2566
+ export function runAntigravityStartupAudit({
2567
+ homeDir = getHomeDir(),
2568
+ cwd = process.cwd(),
2569
+ hostPlatform = process.platform,
2570
+ nowMs = Date.now()
2571
+ } = {}) {
2572
+ const paths = resolveAntigravityConfigPaths({ homeDir, cwd, platform: hostPlatform });
2573
+ const projectHooks = parseJsoncReadOnly(paths.projectHooksJson);
2574
+ const userHooks = parseJsoncReadOnly(paths.userHooksJson);
2575
+ const projectMcp = parseJsoncReadOnly(paths.projectMcpJson);
2576
+ const userMcp = parseJsoncReadOnly(paths.userMcpJson);
2577
+
2578
+ const ruleFiles = [
2579
+ ...paths.rulesFiles,
2580
+ ...listMarkdownFilesInDir(paths.projectRulesDir),
2581
+ ...listMarkdownFilesInDir(paths.globalRulesDir)
2582
+ ];
2583
+ const rulesBucket = auditAntigravityRulesFiles(ruleFiles);
2584
+ const strictJsonSyntax = collectStrictJsonLints([
2585
+ { res: projectHooks },
2586
+ { res: userHooks },
2587
+ { res: projectMcp },
2588
+ { res: userMcp }
2589
+ ]);
2590
+ const volatilePrefix = auditVolatilePromptPrefix({
2591
+ ruleFilePaths: ruleFiles,
2592
+ settingsLayers: [
2593
+ { label: paths.projectHooksJson, doc: projectHooks },
2594
+ { label: paths.userHooksJson, doc: userHooks }
2595
+ ],
2596
+ harness: 'antigravity'
2597
+ });
2598
+
2599
+ const configuredServers = [];
2600
+ for (const src of [userMcp.parsed, projectMcp.parsed]) {
2601
+ if (src && typeof src.mcpServers === 'object' && !Array.isArray(src.mcpServers)) {
2602
+ for (const [name, cfg] of Object.entries(src.mcpServers)) {
2603
+ if (cfg && cfg.disabled !== true) {
2604
+ configuredServers.push(name);
2605
+ }
2606
+ }
2607
+ }
2608
+ }
2609
+ const uniqueServers = [...new Set(configuredServers)];
2610
+ const mcpTaxTokens = uniqueServers.length * DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER;
2611
+ const mcpStatus = uniqueServers.length >= SUBAGENT_MCP_MIN_SERVERS ? 'warn' : 'pass';
2612
+ const mcpCheck = {
2613
+ status: mcpStatus,
2614
+ configuredServerNames: uniqueServers,
2615
+ startupTaxTokensPerTurn: mcpTaxTokens,
2616
+ isEstimated: true,
2617
+ summaryLine: `Antigravity MCP servers active: ${uniqueServers.length} (~${mcpTaxTokens} est. tok/turn)`
2618
+ };
2619
+
2620
+ const lints = [...strictJsonSyntax.lints, ...volatilePrefix.lints];
2621
+ let issueCount = lints.length;
2622
+ let estimatedTurn0ReclaimableTokens = 0;
2623
+ if (mcpStatus === 'warn') {
2624
+ issueCount += 1;
2625
+ estimatedTurn0ReclaimableTokens += mcpTaxTokens;
2626
+ }
2627
+ if (rulesBucket.status === 'warn' || rulesBucket.status === 'caution') {
2628
+ issueCount += 1;
2629
+ }
2630
+
2631
+ return {
2632
+ ok: true,
2633
+ schemaVersion: '1.0.0',
2634
+ platform: hostPlatform,
2635
+ harnessesAudited: ['antigravity'],
2636
+ antigravity: {
2637
+ configFiles: {
2638
+ projectHooks: formatConfigStatus(projectHooks),
2639
+ userHooks: formatConfigStatus(userHooks),
2640
+ projectMcp: formatConfigStatus(projectMcp),
2641
+ userMcp: formatConfigStatus(userMcp)
2642
+ },
2643
+ checks: {
2644
+ mcpCheck,
2645
+ strictJsonSyntax,
2646
+ volatilePrefix
2647
+ }
2648
+ },
2649
+ rulesAudit: {
2650
+ thresholds: RULES_THRESHOLDS,
2651
+ byHarness: {
2652
+ antigravity: rulesBucket
2653
+ }
2654
+ },
2655
+ lints,
2656
+ summary: {
2657
+ issueCount,
2658
+ estimatedTurn0ReclaimableTokens,
2659
+ estimatedWeeklySavingsUsd: estimateWeeklySavingsUsd(estimatedTurn0ReclaimableTokens, nowMs)
2660
+ }
2661
+ };
2662
+ }
2663
+
2664
+ /**
2665
+ * Formats `runAntigravityStartupAudit()` for terminal output.
2666
+ */
2667
+ export function formatAntigravityStartupAuditReport(report) {
2668
+ if (!report?.ok) return 'Burnoff Antigravity Startup Audit failed\n';
2669
+ const s = report.summary || {};
2670
+ const c = report.antigravity?.checks;
2671
+ const r = report.rulesAudit?.byHarness?.antigravity;
2672
+ const lines = [
2673
+ `Burnoff Antigravity Turn-0 Startup Audit | Findings: ${s.issueCount ?? 0} | Reclaimable: ~${Number(s.estimatedTurn0ReclaimableTokens || 0).toLocaleString('en-US')} tok/turn (est.) (~$${Number(s.estimatedWeeklySavingsUsd || 0).toFixed(2)}/wk)`
2674
+ ];
2675
+ if (c?.mcpCheck) {
2676
+ lines.push(` - [${c.mcpCheck.status}] ${c.mcpCheck.summaryLine}`);
2677
+ }
2678
+ if (r) {
2679
+ lines.push(
2680
+ ` - Rules [${r.status}]: ${r.files.length} file(s), ${r.totalRuleCount} always-on rules (${r.onDemandCount} on-demand), ~${r.totalTokensEst.toLocaleString('en-US')} est. tokens`
2681
+ );
2682
+ for (const adv of r.advisories || []) {
2683
+ lines.push(` Advisories: ${adv}`);
2684
+ }
2685
+ }
2686
+ if (Array.isArray(report.lints) && report.lints.length > 0) {
2687
+ lines.push(' JSON & Config Lints:');
2688
+ for (const l of report.lints) {
2689
+ lines.push(` - [${l.severity}] ${l.ruleId}: ${l.message}`);
2690
+ }
2691
+ }
2692
+ return lines.join('\n') + '\n';
2693
+ }
2694
+
2695
+ /**
2696
+ * Unified startup audit supporting `--client claude|antigravity|both|auto`.
2697
+ */
2698
+ export function runStartupAudit(options = {}) {
2699
+ const cwd = path.resolve(options.cwd || process.cwd());
2700
+ const homeDir = options.homeDir || getHomeDir();
2701
+ const rawClient = String(options.client || 'auto').trim().toLowerCase();
2702
+
2703
+ let target = rawClient;
2704
+ if (rawClient === 'auto') {
2705
+ const hasAg =
2706
+ fs.existsSync(path.join(cwd, '.agents')) ||
2707
+ fs.existsSync(path.join(cwd, 'GEMINI.md')) ||
2708
+ fs.existsSync(path.join(homeDir, '.gemini', 'config', 'hooks.json'));
2709
+ const hasClaude =
2710
+ fs.existsSync(path.join(cwd, '.claude')) ||
2711
+ fs.existsSync(path.join(homeDir, '.claude'));
2712
+ if (hasAg && hasClaude) target = 'both';
2713
+ else if (hasAg) target = 'antigravity';
2714
+ else target = 'claude';
2715
+ }
2716
+
2717
+ if (target === 'antigravity' || target === 'ag') {
2718
+ return runAntigravityStartupAudit(options);
2719
+ }
2720
+ if (target === 'both') {
2721
+ const claudeReport = runClaudeStartupAudit(options);
2722
+ const agReport = runAntigravityStartupAudit(options);
2723
+ const claudeLints = claudeReport.lints || [];
2724
+ const agLints = agReport.lints || [];
2725
+ return {
2726
+ ...claudeReport,
2727
+ harnessesAudited: ['claude-code', 'antigravity'],
2728
+ antigravity: agReport.antigravity,
2729
+ rulesAudit: {
2730
+ thresholds: RULES_THRESHOLDS,
2731
+ byHarness: {
2732
+ ...claudeReport.rulesAudit.byHarness,
2733
+ ...agReport.rulesAudit.byHarness
2734
+ }
2735
+ },
2736
+ lints: [...claudeLints, ...agLints],
2737
+ lintsByHarness: {
2738
+ 'claude-code': claudeLints,
2739
+ antigravity: agLints
2740
+ },
2741
+ summaryByHarness: {
2742
+ 'claude-code': claudeReport.summary,
2743
+ antigravity: agReport.summary
2744
+ },
2745
+ summary: {
2746
+ issueCount: (claudeReport.summary?.issueCount || 0) + (agReport.summary?.issueCount || 0),
2747
+ estimatedTurn0ReclaimableTokens:
2748
+ (claudeReport.summary?.estimatedTurn0ReclaimableTokens || 0) +
2749
+ (agReport.summary?.estimatedTurn0ReclaimableTokens || 0),
2750
+ estimatedWeeklySavingsUsd: Number(
2751
+ ((claudeReport.summary?.estimatedWeeklySavingsUsd || 0) +
2752
+ (agReport.summary?.estimatedWeeklySavingsUsd || 0)).toFixed(2)
2753
+ )
2754
+ }
2755
+ };
2756
+ }
2757
+ return runClaudeStartupAudit(options);
2758
+ }
2759
+
2760
+ export function formatStartupAuditReport(report) {
2761
+ if (report?.harnessesAudited?.length === 1 && report.harnessesAudited[0] === 'antigravity') {
2762
+ return formatAntigravityStartupAuditReport(report);
2763
+ }
2764
+ if (report?.harnessesAudited?.includes('antigravity') && report?.claudeCode) {
2765
+ const claudeSummary = report.summaryByHarness?.['claude-code'] || report.summary;
2766
+ const agSummary = report.summaryByHarness?.antigravity || report.summary;
2767
+ const claudeLints =
2768
+ report.lintsByHarness?.['claude-code'] ||
2769
+ (report.lints || []).filter((l) => !(l.file?.includes('.agents') || l.file?.includes('.gemini')));
2770
+ const agLints =
2771
+ report.lintsByHarness?.antigravity ||
2772
+ (report.lints || []).filter((l) => l.file?.includes('.agents') || l.file?.includes('.gemini'));
2773
+ return (
2774
+ formatClaudeStartupAuditReport({
2775
+ ...report,
2776
+ lints: claudeLints,
2777
+ summary: claudeSummary
2778
+ }) +
2779
+ '\n' +
2780
+ formatAntigravityStartupAuditReport({
2781
+ ok: report.ok,
2782
+ antigravity: report.antigravity,
2783
+ rulesAudit: report.rulesAudit,
2784
+ lints: agLints,
2785
+ summary: agSummary
2786
+ })
2787
+ );
2788
+ }
2789
+ return formatClaudeStartupAuditReport(report);
2790
+ }
2791
+
2792
+ export default {
2793
+ CALIBRATION_MANIFEST,
2794
+ RULES_THRESHOLDS,
2795
+ DEFAULT_TELEMETRY_MAX_FILES,
2796
+ DEFAULT_TELEMETRY_MAX_BYTES,
2797
+ LIST_CHANGED_PREFIX_THRESHOLD,
2798
+ SUBAGENT_MCP_MIN_SERVERS,
2799
+ DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER,
2800
+ IDLE_COMPACTION_MIN_VERSION,
2801
+ DEFAULT_IDLE_COMPACT_MIN_TOKENS,
2802
+ SDK_CLI_QUOTA_MULTIPLIER_HEURISTIC,
2803
+ VERIFIED_CLAUDE_FLAGS,
2804
+ FORBIDDEN_WORKAROUND_FLAGS,
2805
+ formatJsonCliArg,
2806
+ validateClaudeCliCommand,
2807
+ inspectJsoncSyntax,
2808
+ parseJsoncString,
2809
+ parseJsoncReadOnly,
2810
+ countDiscreteRules,
2811
+ scanClaudeCustomAgentSpecs,
2812
+ scanMcpToolNameLengthViolations,
2813
+ scanMcpListChangedCapabilities,
2814
+ estimateSubagentMcpInstructionsTax,
2815
+ auditIdleCompactionConfig,
2816
+ scanVolatilePromptPatterns,
2817
+ auditVolatilePromptPrefix,
2818
+ runClaudeStartupAudit,
2819
+ formatClaudeStartupAuditReport,
2820
+ runAntigravityStartupAudit,
2821
+ formatAntigravityStartupAuditReport,
2822
+ runStartupAudit,
2823
+ formatStartupAuditReport
2824
+ };