burnoff 1.4.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/burnoff-pr-gate.yml +5 -3
- package/.github/workflows/burnoff-startup-lint.yml +2 -2
- package/CHANGELOG.md +74 -0
- package/README.md +187 -213
- package/SECURITY.md +38 -0
- package/bin/burnoff.mjs +307 -32
- package/commands/burnoff.md +6 -4
- package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
- package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
- package/hooks/hook-io.mjs +216 -11
- package/hooks/hooks.json +44 -0
- package/hooks/post-tool-use.mjs +3 -1
- package/hooks/pre-tool-use.mjs +47 -8
- package/hooks/session-lifecycle.mjs +24 -3
- package/hooks/user-prompt-submit.mjs +98 -0
- package/package.json +6 -4
- package/scripts/bench-hooks.mjs +34 -3
- package/scripts/bench-savings.mjs +318 -0
- package/scripts/burnoff-statusline.mjs +138 -6
- package/src/ci/ci-gate.mjs +199 -13
- package/src/ci/pr-cost.mjs +417 -45
- package/src/ci/pr-summary.mjs +467 -0
- package/src/cli/audit.mjs +179 -28
- package/src/cli/doctor.mjs +32 -6
- package/src/cli/hook-health.mjs +9 -1
- package/src/cli/init.mjs +226 -39
- package/src/cli/preview.mjs +299 -0
- package/src/cli/startup-audit/formatter.mjs +248 -0
- package/src/cli/startup-audit/jsonc.mjs +601 -0
- package/src/cli/startup-audit/mcp-audit.mjs +735 -0
- package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
- package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
- package/src/cli/startup-audit.mjs +451 -2471
- package/src/clients/claude-code.mjs +41 -4
- package/src/config/catalog.json +295 -0
- package/src/config/effort.mjs +145 -0
- package/src/config/harness-quirks.mjs +340 -0
- package/src/config/loader.mjs +27 -2
- package/src/config/policy.mjs +81 -9
- package/src/config/pricing.mjs +247 -19
- package/src/config/semver.mjs +25 -0
- package/src/config/uncached-attribution.mjs +280 -41
- package/src/guards/compaction-baton.mjs +248 -0
- package/src/guards/loop-breaker.mjs +328 -47
- package/src/guards/model-switch-hook.mjs +126 -0
- package/src/guards/phase5-detectors.mjs +275 -21
- package/src/guards/post-tool-engine.mjs +333 -11
- package/src/guards/pre-tool-engine.mjs +607 -45
- package/src/guards/prefix-guard.mjs +609 -0
- package/src/guards/prompt-guard.mjs +309 -0
- package/src/guards/read-clamp.mjs +192 -8
- package/src/guards/session-hook.mjs +149 -7
- package/src/guards/shell-guard.mjs +56 -5
- package/src/guards/snooze.mjs +169 -5
- package/src/ipc/daemon.mjs +76 -0
- package/src/ipc/fast-client.mjs +165 -4
- package/src/ipc/protocol.mjs +16 -3
- package/src/storage/antigravity-parser.mjs +16 -2
- package/src/storage/file-lock.mjs +16 -3
- package/src/storage/jsonl-parser.mjs +133 -22
- package/src/storage/telemetry-metrics.mjs +254 -4
|
@@ -1,19 +1,82 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @file src/cli/startup-audit.mjs
|
|
3
|
-
* Standalone Claude Code Turn-0 startup config, rules
|
|
3
|
+
* Standalone Claude Code & Google Antigravity Turn-0 startup config, rules, and MCP auditor
|
|
4
4
|
* (`burnoff audit --startup`).
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import path from 'node:path';
|
|
9
|
-
import {
|
|
9
|
+
import { compareSemver } from '../config/semver.mjs';
|
|
10
|
+
import { SUBSCRIPTION_QUOTA_CONSTANTS } from '../config/pricing.mjs';
|
|
10
11
|
import {
|
|
11
12
|
getHomeDir,
|
|
12
13
|
canonicalizePath,
|
|
13
14
|
resolveClaudeConfigPaths,
|
|
14
15
|
resolveAntigravityConfigPaths
|
|
15
16
|
} from '../config/paths.mjs';
|
|
16
|
-
import {
|
|
17
|
+
import {
|
|
18
|
+
VERIFIED_CLAUDE_FLAGS,
|
|
19
|
+
FORBIDDEN_WORKAROUND_FLAGS,
|
|
20
|
+
formatJsonCliArg,
|
|
21
|
+
validateClaudeCliCommand,
|
|
22
|
+
buildClaudeCliCommand,
|
|
23
|
+
inspectJsoncSyntax,
|
|
24
|
+
parseJsoncString,
|
|
25
|
+
parseJsoncReadOnly,
|
|
26
|
+
estimateWeeklySavingsUsd,
|
|
27
|
+
formatConfigStatus,
|
|
28
|
+
collectStrictJsonLints,
|
|
29
|
+
auditMisplacedChromeKey,
|
|
30
|
+
auditLocalSettingsSecrets,
|
|
31
|
+
makeMissingJsoncStub,
|
|
32
|
+
filterFilesWithinCwd
|
|
33
|
+
} from './startup-audit/jsonc.mjs';
|
|
34
|
+
import {
|
|
35
|
+
RULES_THRESHOLDS,
|
|
36
|
+
SKILL_DESCRIPTION_MAX_CHARS,
|
|
37
|
+
countDiscreteRules,
|
|
38
|
+
detectRuleContradictions,
|
|
39
|
+
auditRulesFiles,
|
|
40
|
+
scanVolatilePromptPatterns,
|
|
41
|
+
auditVolatilePromptPrefix,
|
|
42
|
+
parseSkillFrontmatter,
|
|
43
|
+
auditSkillFrontmatterLimits,
|
|
44
|
+
listMarkdownFilesInDir,
|
|
45
|
+
auditAntigravityRulesFiles
|
|
46
|
+
} from './startup-audit/rules-hygiene.mjs';
|
|
47
|
+
import {
|
|
48
|
+
LIST_CHANGED_PREFIX_THRESHOLD,
|
|
49
|
+
SUBAGENT_MCP_MIN_SERVERS,
|
|
50
|
+
DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER,
|
|
51
|
+
COARSE_META_TOOL_MIN_SERVERS,
|
|
52
|
+
COARSE_META_TOOL_MIN_TOKENS,
|
|
53
|
+
evaluateClaudeEagerMcpGate,
|
|
54
|
+
isLocalhostBaseUrl,
|
|
55
|
+
evaluateMcpProxyAndMetaToolCoaching,
|
|
56
|
+
scanMcpToolNameLengthViolations,
|
|
57
|
+
scanMcpListChangedCapabilities,
|
|
58
|
+
estimateSubagentMcpInstructionsTax,
|
|
59
|
+
collectAntigravityCommandSources
|
|
60
|
+
} from './startup-audit/mcp-audit.mjs';
|
|
61
|
+
import {
|
|
62
|
+
DEFAULT_TELEMETRY_MAX_FILES,
|
|
63
|
+
DEFAULT_TELEMETRY_MAX_BYTES,
|
|
64
|
+
IDLE_COMPACTION_MIN_VERSION,
|
|
65
|
+
DEFAULT_IDLE_COMPACT_MIN_TOKENS,
|
|
66
|
+
RETIRED_MODELS_SPEC,
|
|
67
|
+
scanClaudeTelemetrySummary,
|
|
68
|
+
scanClaudeCustomAgentSpecs,
|
|
69
|
+
detectAnthropicSdkMarkers,
|
|
70
|
+
auditRetiredModelsAndDeprecatedFlags,
|
|
71
|
+
auditIdleCompactionConfig,
|
|
72
|
+
createEmptyClaudeTelemetryStub
|
|
73
|
+
} from './startup-audit/telemetry-scan.mjs';
|
|
74
|
+
import {
|
|
75
|
+
formatClaudeStartupAuditReport,
|
|
76
|
+
formatAntigravityStartupAuditReport,
|
|
77
|
+
formatStartupAuditReport,
|
|
78
|
+
evaluateStartupAuditCi
|
|
79
|
+
} from './startup-audit/formatter.mjs';
|
|
17
80
|
|
|
18
81
|
export const CALIBRATION_MANIFEST = Object.freeze({
|
|
19
82
|
claudeCodeTurn0: Object.freeze({
|
|
@@ -44,2147 +107,53 @@ export const CALIBRATION_MANIFEST = Object.freeze({
|
|
|
44
107
|
})
|
|
45
108
|
});
|
|
46
109
|
|
|
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
|
-
export const COARSE_META_TOOL_MIN_SERVERS = 3;
|
|
60
|
-
export const COARSE_META_TOOL_MIN_TOKENS = 10000;
|
|
61
|
-
|
|
62
|
-
export const VERIFIED_CLAUDE_FLAGS = Object.freeze([
|
|
63
|
-
'--chrome',
|
|
64
|
-
'--no-chrome',
|
|
65
|
-
'--disallowedTools',
|
|
66
|
-
'--settings',
|
|
67
|
-
'--mcp-config',
|
|
68
|
-
'--strict-mcp-config',
|
|
69
|
-
'--model'
|
|
70
|
-
]);
|
|
71
|
-
|
|
72
|
-
export const FORBIDDEN_WORKAROUND_FLAGS = Object.freeze(['--tools']);
|
|
73
|
-
|
|
74
|
-
const VERIFIED_SET = new Set(VERIFIED_CLAUDE_FLAGS);
|
|
75
|
-
const FORBIDDEN_SET = new Set(FORBIDDEN_WORKAROUND_FLAGS);
|
|
76
|
-
const CHARS_PER_TOKEN = 4;
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Formats a JSON object as a shell-safe CLI argument for win32 PowerShell or POSIX shells.
|
|
80
|
-
*/
|
|
81
|
-
export function formatJsonCliArg(obj, platform = process.platform) {
|
|
82
|
-
const json = JSON.stringify(obj);
|
|
83
|
-
if (platform === 'win32') {
|
|
84
|
-
return `'${json.replace(/"/g, '\\"')}'`;
|
|
85
|
-
}
|
|
86
|
-
return `'${json.replace(/'/g, "'\\''")}'`;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Validates a `claude ...` command against verified flags, forbidden `--tools`, and zero em dashes.
|
|
91
|
-
*/
|
|
92
|
-
export function validateClaudeCliCommand(cmd) {
|
|
93
|
-
const str = String(cmd || '');
|
|
94
|
-
const hasEmDash = str.includes('\u2014');
|
|
95
|
-
const stripped = str
|
|
96
|
-
.replace(/'(?:\\.|[^'\\])*'/g, ' ')
|
|
97
|
-
.replace(/"(?:\\.|[^"\\])*"/g, ' ');
|
|
98
|
-
|
|
99
|
-
const flags = [];
|
|
100
|
-
const unverifiedFlags = [];
|
|
101
|
-
const forbiddenFlags = [];
|
|
102
|
-
|
|
103
|
-
for (const m of stripped.matchAll(/(?:^|\s)(--[A-Za-z0-9-]+)(?:=|\s|$)/g)) {
|
|
104
|
-
const flag = m[1];
|
|
105
|
-
flags.push(flag);
|
|
106
|
-
if (FORBIDDEN_SET.has(flag)) {
|
|
107
|
-
forbiddenFlags.push(flag);
|
|
108
|
-
} else if (!VERIFIED_SET.has(flag)) {
|
|
109
|
-
unverifiedFlags.push(flag);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
return {
|
|
114
|
-
ok: unverifiedFlags.length === 0 && forbiddenFlags.length === 0 && !hasEmDash,
|
|
115
|
-
flags,
|
|
116
|
-
unverifiedFlags,
|
|
117
|
-
forbiddenFlags,
|
|
118
|
-
hasEmDash
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function buildClaudeCliCommand(parts = [], { platform = process.platform } = {}) {
|
|
123
|
-
const tokens = ['claude'];
|
|
124
|
-
for (const part of parts) {
|
|
125
|
-
if (part === null || part === undefined) continue;
|
|
126
|
-
if (typeof part === 'object' && !Array.isArray(part)) {
|
|
127
|
-
tokens.push(formatJsonCliArg(part, platform));
|
|
128
|
-
} else {
|
|
129
|
-
const s = String(part).trim();
|
|
130
|
-
if (!s) continue;
|
|
131
|
-
if (FORBIDDEN_SET.has(s)) {
|
|
132
|
-
throw new Error(`Forbidden Claude CLI flag "${s}" cannot be emitted in fix templates.`);
|
|
133
|
-
}
|
|
134
|
-
if (s.startsWith('--') && !VERIFIED_SET.has(s)) {
|
|
135
|
-
throw new Error(`Unverified Claude CLI flag "${s}" is not in VERIFIED_CLAUDE_FLAGS.`);
|
|
136
|
-
}
|
|
137
|
-
tokens.push(s);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
const cmd = tokens.join(' ');
|
|
141
|
-
const check = validateClaudeCliCommand(cmd);
|
|
142
|
-
if (!check.ok) {
|
|
143
|
-
throw new Error(`Invalid Claude CLI command: ${cmd}`);
|
|
144
|
-
}
|
|
145
|
-
return cmd;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Inspects raw JSON/JSONC text outside string literals to detect non-strict JSON syntax
|
|
150
|
-
* (`//` line comments, `/* ... *\/` block comments, or trailing commas).
|
|
151
|
-
*/
|
|
152
|
-
export function inspectJsoncSyntax(raw) {
|
|
153
|
-
const input = String(raw ?? '');
|
|
154
|
-
let out = '';
|
|
155
|
-
let inString = false;
|
|
156
|
-
let escaped = false;
|
|
157
|
-
let inLineComment = false;
|
|
158
|
-
let inBlockComment = false;
|
|
159
|
-
let hasLineComment = false;
|
|
160
|
-
let hasBlockComment = false;
|
|
161
|
-
let hasTrailingComma = false;
|
|
162
|
-
|
|
163
|
-
for (let i = 0; i < input.length; i++) {
|
|
164
|
-
const ch = input[i];
|
|
165
|
-
const next = input[i + 1];
|
|
166
|
-
|
|
167
|
-
if (inLineComment) {
|
|
168
|
-
if (ch === '\n' || ch === '\r') {
|
|
169
|
-
inLineComment = false;
|
|
170
|
-
out += ch;
|
|
171
|
-
}
|
|
172
|
-
continue;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
if (inBlockComment) {
|
|
176
|
-
if (ch === '*' && next === '/') {
|
|
177
|
-
inBlockComment = false;
|
|
178
|
-
i += 1;
|
|
179
|
-
} else if (ch === '\n' || ch === '\r') {
|
|
180
|
-
out += ch;
|
|
181
|
-
}
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
if (inString) {
|
|
186
|
-
out += ch;
|
|
187
|
-
if (escaped) {
|
|
188
|
-
escaped = false;
|
|
189
|
-
} else if (ch === '\\') {
|
|
190
|
-
escaped = true;
|
|
191
|
-
} else if (ch === '"') {
|
|
192
|
-
inString = false;
|
|
193
|
-
}
|
|
194
|
-
continue;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
if (ch === '"') {
|
|
198
|
-
inString = true;
|
|
199
|
-
out += ch;
|
|
200
|
-
continue;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
if (ch === '/' && next === '/') {
|
|
204
|
-
hasLineComment = true;
|
|
205
|
-
inLineComment = true;
|
|
206
|
-
i += 1;
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
if (ch === '/' && next === '*') {
|
|
211
|
-
hasBlockComment = true;
|
|
212
|
-
inBlockComment = true;
|
|
213
|
-
i += 1;
|
|
214
|
-
continue;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
out += ch;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
inString = false;
|
|
221
|
-
escaped = false;
|
|
222
|
-
for (let i = 0; i < out.length; i++) {
|
|
223
|
-
const ch = out[i];
|
|
224
|
-
if (inString) {
|
|
225
|
-
if (escaped) escaped = false;
|
|
226
|
-
else if (ch === '\\') escaped = true;
|
|
227
|
-
else if (ch === '"') inString = false;
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
if (ch === '"') {
|
|
231
|
-
inString = true;
|
|
232
|
-
continue;
|
|
233
|
-
}
|
|
234
|
-
if (ch === ',') {
|
|
235
|
-
let j = i + 1;
|
|
236
|
-
while (j < out.length && /\s/.test(out[j])) j++;
|
|
237
|
-
if (out[j] === '}' || out[j] === ']') {
|
|
238
|
-
hasTrailingComma = true;
|
|
239
|
-
break;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
return {
|
|
245
|
-
hasLineComment,
|
|
246
|
-
hasBlockComment,
|
|
247
|
-
hasTrailingComma,
|
|
248
|
-
hasNonStrictSyntax: hasLineComment || hasBlockComment || hasTrailingComma
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Strips JSONC comments (`//` and `/* ... *\/`) and trailing commas outside strings.
|
|
254
|
-
*/
|
|
255
|
-
export function parseJsoncString(raw) {
|
|
256
|
-
const input = String(raw ?? '');
|
|
257
|
-
let out = '';
|
|
258
|
-
let inString = false;
|
|
259
|
-
let escaped = false;
|
|
260
|
-
let inLineComment = false;
|
|
261
|
-
let inBlockComment = false;
|
|
262
|
-
|
|
263
|
-
for (let i = 0; i < input.length; i++) {
|
|
264
|
-
const ch = input[i];
|
|
265
|
-
const next = input[i + 1];
|
|
266
|
-
|
|
267
|
-
if (inLineComment) {
|
|
268
|
-
if (ch === '\n' || ch === '\r') {
|
|
269
|
-
inLineComment = false;
|
|
270
|
-
out += ch;
|
|
271
|
-
}
|
|
272
|
-
continue;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
if (inBlockComment) {
|
|
276
|
-
if (ch === '*' && next === '/') {
|
|
277
|
-
inBlockComment = false;
|
|
278
|
-
i += 1;
|
|
279
|
-
} else if (ch === '\n' || ch === '\r') {
|
|
280
|
-
out += ch;
|
|
281
|
-
}
|
|
282
|
-
continue;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
if (inString) {
|
|
286
|
-
out += ch;
|
|
287
|
-
if (escaped) {
|
|
288
|
-
escaped = false;
|
|
289
|
-
} else if (ch === '\\') {
|
|
290
|
-
escaped = true;
|
|
291
|
-
} else if (ch === '"') {
|
|
292
|
-
inString = false;
|
|
293
|
-
}
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
if (ch === '"') {
|
|
298
|
-
inString = true;
|
|
299
|
-
out += ch;
|
|
300
|
-
continue;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
if (ch === '/' && next === '/') {
|
|
304
|
-
inLineComment = true;
|
|
305
|
-
i += 1;
|
|
306
|
-
continue;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
if (ch === '/' && next === '*') {
|
|
310
|
-
inBlockComment = true;
|
|
311
|
-
i += 1;
|
|
312
|
-
continue;
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
out += ch;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
let cleaned = '';
|
|
319
|
-
inString = false;
|
|
320
|
-
escaped = false;
|
|
321
|
-
for (let i = 0; i < out.length; i++) {
|
|
322
|
-
const ch = out[i];
|
|
323
|
-
if (inString) {
|
|
324
|
-
cleaned += ch;
|
|
325
|
-
if (escaped) escaped = false;
|
|
326
|
-
else if (ch === '\\') escaped = true;
|
|
327
|
-
else if (ch === '"') inString = false;
|
|
328
|
-
continue;
|
|
329
|
-
}
|
|
330
|
-
if (ch === '"') {
|
|
331
|
-
inString = true;
|
|
332
|
-
cleaned += ch;
|
|
333
|
-
continue;
|
|
334
|
-
}
|
|
335
|
-
if (ch === ',') {
|
|
336
|
-
let j = i + 1;
|
|
337
|
-
while (j < out.length && /\s/.test(out[j])) j++;
|
|
338
|
-
if (out[j] === '}' || out[j] === ']') {
|
|
339
|
-
continue;
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
cleaned += ch;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
return JSON.parse(cleaned);
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/**
|
|
349
|
-
* Reads and parses a JSON/JSONC file strictly read-only without throwing.
|
|
350
|
-
*/
|
|
351
|
-
export function parseJsoncReadOnly(filePath) {
|
|
352
|
-
if (!filePath || !fs.existsSync(filePath)) {
|
|
353
|
-
return {
|
|
354
|
-
path: filePath || '',
|
|
355
|
-
exists: false,
|
|
356
|
-
parseOk: false,
|
|
357
|
-
parsed: null,
|
|
358
|
-
strictJsonValid: false,
|
|
359
|
-
strict_json_syntax_warning: null,
|
|
360
|
-
error: null
|
|
361
|
-
};
|
|
362
|
-
}
|
|
363
|
-
try {
|
|
364
|
-
const raw = fs.readFileSync(filePath, 'utf8');
|
|
365
|
-
if (!raw || !raw.trim()) {
|
|
366
|
-
return {
|
|
367
|
-
path: filePath,
|
|
368
|
-
exists: true,
|
|
369
|
-
parseOk: false,
|
|
370
|
-
parsed: null,
|
|
371
|
-
strictJsonValid: false,
|
|
372
|
-
strict_json_syntax_warning: null,
|
|
373
|
-
error: 'empty file'
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
const parsed = parseJsoncString(raw);
|
|
377
|
-
const syntax = inspectJsoncSyntax(raw);
|
|
378
|
-
const displayPath = String(filePath).replace(/\\/g, '/');
|
|
379
|
-
const strictJsonValid = !syntax.hasNonStrictSyntax;
|
|
380
|
-
const strict_json_syntax_warning = syntax.hasNonStrictSyntax
|
|
381
|
-
? `Strict JSON warning: comments or trailing commas in ${displayPath} fail harnesses using strict JSON.parse(). Strip comments for cross-tool portability.`
|
|
382
|
-
: null;
|
|
383
|
-
return {
|
|
384
|
-
path: filePath,
|
|
385
|
-
exists: true,
|
|
386
|
-
parseOk: true,
|
|
387
|
-
parsed,
|
|
388
|
-
strictJsonValid,
|
|
389
|
-
strict_json_syntax_warning,
|
|
390
|
-
error: null
|
|
391
|
-
};
|
|
392
|
-
} catch (err) {
|
|
393
|
-
return {
|
|
394
|
-
path: filePath,
|
|
395
|
-
exists: true,
|
|
396
|
-
parseOk: false,
|
|
397
|
-
parsed: null,
|
|
398
|
-
strictJsonValid: false,
|
|
399
|
-
strict_json_syntax_warning: null,
|
|
400
|
-
error: err?.message || 'parse error'
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* Counts discrete imperative bullets and numbered rules in markdown, ignoring fenced code blocks
|
|
407
|
-
* and markdown table separator rows.
|
|
408
|
-
*/
|
|
409
|
-
export function countDiscreteRules(markdown) {
|
|
410
|
-
const lines = String(markdown || '').split(/\r?\n/);
|
|
411
|
-
let inFence = false;
|
|
412
|
-
let fenceChar = '';
|
|
413
|
-
let count = 0;
|
|
414
|
-
|
|
415
|
-
for (const line of lines) {
|
|
416
|
-
const fenceMatch = line.match(/^\s*(```+|~~~+)/);
|
|
417
|
-
if (fenceMatch) {
|
|
418
|
-
const markerChar = fenceMatch[1][0];
|
|
419
|
-
if (!inFence) {
|
|
420
|
-
inFence = true;
|
|
421
|
-
fenceChar = markerChar;
|
|
422
|
-
} else if (markerChar === fenceChar) {
|
|
423
|
-
inFence = false;
|
|
424
|
-
fenceChar = '';
|
|
425
|
-
}
|
|
426
|
-
continue;
|
|
427
|
-
}
|
|
428
|
-
if (inFence) continue;
|
|
429
|
-
if (/^\s*\|?(?:\s*:?-+:?\s*\|)+\s*$/.test(line)) continue;
|
|
430
|
-
if (/^\s*(?:[-*+]|\d+\.)\s+\S/.test(line)) {
|
|
431
|
-
count += 1;
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
return count;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
function compareSemver(a, b) {
|
|
438
|
-
const parse = (v) => {
|
|
439
|
-
const m = String(v || '').trim().match(/^v?(\d+)\.(\d+)\.(\d+)/);
|
|
440
|
-
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
441
|
-
};
|
|
442
|
-
const pa = parse(a);
|
|
443
|
-
const pb = parse(b);
|
|
444
|
-
if (!pa || !pb) return null;
|
|
445
|
-
for (let i = 0; i < 3; i++) {
|
|
446
|
-
if (pa[i] < pb[i]) return -1;
|
|
447
|
-
if (pa[i] > pb[i]) return 1;
|
|
448
|
-
}
|
|
449
|
-
return 0;
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
function auditRulesFiles(filePaths = []) {
|
|
453
|
-
const seen = new Set();
|
|
454
|
-
const files = [];
|
|
455
|
-
let totalTokensEst = 0;
|
|
456
|
-
let totalRuleCount = 0;
|
|
457
|
-
|
|
458
|
-
for (const fp of filePaths) {
|
|
459
|
-
if (!fp || !fs.existsSync(fp)) continue;
|
|
460
|
-
let dedupeKey = canonicalizePath(fp);
|
|
461
|
-
try {
|
|
462
|
-
dedupeKey = canonicalizePath(fs.realpathSync(fp));
|
|
463
|
-
} catch {
|
|
464
|
-
// ignore: fallback to canonicalized path when realpath fails
|
|
465
|
-
}
|
|
466
|
-
if (seen.has(dedupeKey)) continue;
|
|
467
|
-
seen.add(dedupeKey);
|
|
468
|
-
|
|
469
|
-
try {
|
|
470
|
-
const text = fs.readFileSync(fp, 'utf8');
|
|
471
|
-
const chars = text.length;
|
|
472
|
-
const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
|
|
473
|
-
const ruleCount = countDiscreteRules(text);
|
|
474
|
-
files.push({
|
|
475
|
-
path: String(fp).replace(/\\/g, '/'),
|
|
476
|
-
chars,
|
|
477
|
-
tokensEst,
|
|
478
|
-
ruleCount
|
|
479
|
-
});
|
|
480
|
-
totalTokensEst += tokensEst;
|
|
481
|
-
totalRuleCount += ruleCount;
|
|
482
|
-
} catch {
|
|
483
|
-
// ignore: unreadable rules markdown file
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
let status = 'pass';
|
|
488
|
-
const advisories = [];
|
|
489
|
-
if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
|
|
490
|
-
status = 'warn';
|
|
491
|
-
advisories.push(
|
|
492
|
-
`IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} rules); move domain rules into on-demand SKILL.md files.`
|
|
493
|
-
);
|
|
494
|
-
} else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
|
|
495
|
-
status = 'caution';
|
|
496
|
-
advisories.push(
|
|
497
|
-
`Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} rules).`
|
|
498
|
-
);
|
|
499
|
-
}
|
|
500
|
-
if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
|
|
501
|
-
status = 'warn';
|
|
502
|
-
advisories.push(
|
|
503
|
-
`Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across active rules files).`
|
|
504
|
-
);
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
return { files, totalTokensEst, totalRuleCount, status, advisories };
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
function collectJsonlFiles(rootDir, cutoffMs) {
|
|
511
|
-
const out = [];
|
|
512
|
-
if (!rootDir || !fs.existsSync(rootDir)) return out;
|
|
513
|
-
const walk = (dir) => {
|
|
514
|
-
let entries = [];
|
|
515
|
-
try {
|
|
516
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
517
|
-
} catch {
|
|
518
|
-
return; // ignore: unreadable projects subdirectory
|
|
519
|
-
}
|
|
520
|
-
for (const ent of entries) {
|
|
521
|
-
const full = path.join(dir, ent.name);
|
|
522
|
-
if (ent.isDirectory()) {
|
|
523
|
-
walk(full);
|
|
524
|
-
} else if (ent.isFile() && ent.name.endsWith('.jsonl')) {
|
|
525
|
-
try {
|
|
526
|
-
const st = fs.statSync(full);
|
|
527
|
-
if (!cutoffMs || st.mtimeMs >= cutoffMs) {
|
|
528
|
-
out.push({ path: full, mtimeMs: st.mtimeMs });
|
|
529
|
-
}
|
|
530
|
-
} catch {
|
|
531
|
-
// ignore: unreadable JSONL stat
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
};
|
|
536
|
-
walk(rootDir);
|
|
537
|
-
out.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
538
|
-
return out;
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
export const DEFAULT_TELEMETRY_MAX_FILES = 50;
|
|
542
|
-
export const DEFAULT_TELEMETRY_MAX_BYTES = 16 * 1024 * 1024;
|
|
543
|
-
const TELEMETRY_READ_CHUNK_BYTES = 64 * 1024;
|
|
544
|
-
|
|
545
|
-
function scanJsonlFileChunked(filePath, { maxBytesRemaining = Infinity, onLine } = {}) {
|
|
546
|
-
let fd = null;
|
|
547
|
-
let bytesRead = 0;
|
|
548
|
-
let truncated = false;
|
|
549
|
-
const decoder = new StringDecoder('utf8');
|
|
550
|
-
let carry = '';
|
|
551
|
-
try {
|
|
552
|
-
fd = fs.openSync(filePath, 'r');
|
|
553
|
-
const buf = Buffer.allocUnsafe(TELEMETRY_READ_CHUNK_BYTES);
|
|
554
|
-
while (bytesRead < maxBytesRemaining) {
|
|
555
|
-
const toRead = Math.min(TELEMETRY_READ_CHUNK_BYTES, Math.max(0, maxBytesRemaining - bytesRead));
|
|
556
|
-
if (toRead <= 0) {
|
|
557
|
-
truncated = true;
|
|
558
|
-
break;
|
|
559
|
-
}
|
|
560
|
-
const n = fs.readSync(fd, buf, 0, toRead, null);
|
|
561
|
-
if (n <= 0) break;
|
|
562
|
-
bytesRead += n;
|
|
563
|
-
const chunkText = carry + decoder.write(buf.subarray(0, n));
|
|
564
|
-
const parts = chunkText.split(/\r?\n/);
|
|
565
|
-
carry = parts.pop() || '';
|
|
566
|
-
for (const line of parts) {
|
|
567
|
-
if (line.trim()) onLine(line);
|
|
568
|
-
}
|
|
569
|
-
if (bytesRead >= maxBytesRemaining) {
|
|
570
|
-
truncated = true;
|
|
571
|
-
break;
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
if (!truncated) {
|
|
575
|
-
const tail = carry + decoder.end();
|
|
576
|
-
if (tail.trim()) onLine(tail);
|
|
577
|
-
}
|
|
578
|
-
} catch {
|
|
579
|
-
// ignore: unreadable JSONL transcript
|
|
580
|
-
} finally {
|
|
581
|
-
if (fd !== null) {
|
|
582
|
-
try {
|
|
583
|
-
fs.closeSync(fd);
|
|
584
|
-
} catch {
|
|
585
|
-
// ignore: fd close cleanup
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
return { bytesRead, truncated };
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
function scanClaudeTelemetrySummary({
|
|
593
|
-
projectsDir,
|
|
594
|
-
days = 7,
|
|
595
|
-
nowMs = Date.now(),
|
|
596
|
-
maxFiles = DEFAULT_TELEMETRY_MAX_FILES,
|
|
597
|
-
maxTotalBytes = DEFAULT_TELEMETRY_MAX_BYTES
|
|
598
|
-
} = {}) {
|
|
599
|
-
const cutoffMs = days > 0 ? nowMs - days * 86_400_000 : 0;
|
|
600
|
-
const files = collectJsonlFiles(projectsDir, cutoffMs);
|
|
601
|
-
const fileCap = Math.max(1, Number(maxFiles) || DEFAULT_TELEMETRY_MAX_FILES);
|
|
602
|
-
const byteCap = Math.max(1024, Number(maxTotalBytes) || DEFAULT_TELEMETRY_MAX_BYTES);
|
|
603
|
-
const filesToScan = files.slice(0, fileCap);
|
|
604
|
-
let scanTruncated = files.length > filesToScan.length;
|
|
605
|
-
let bytesScanned = 0;
|
|
606
|
-
let sessionsScanned = 0;
|
|
607
|
-
|
|
608
|
-
let latestVersion = null;
|
|
609
|
-
let latestVersionMtime = -1;
|
|
610
|
-
const entrypoints = new Set();
|
|
611
|
-
let browserToolCalls7d = 0;
|
|
612
|
-
let artifactCalls7d = 0;
|
|
613
|
-
const mcpToolCalls7d = {};
|
|
614
|
-
const schemaTokensByServer = {};
|
|
615
|
-
const observedMcpToolNames = new Set();
|
|
616
|
-
let maxCachedPrefixTokens = null;
|
|
617
|
-
const runtimeListChangedServers = new Set();
|
|
618
|
-
let subagentSpawns7d = 0;
|
|
619
|
-
let sidechainTurns7d = 0;
|
|
620
|
-
let observedMcpInstructionsDeltaChars = 0;
|
|
621
|
-
const observedModels = new Set();
|
|
622
|
-
let sdkCliSessions7d = 0;
|
|
623
|
-
|
|
624
|
-
for (const fileInfo of filesToScan) {
|
|
625
|
-
if (bytesScanned >= byteCap) {
|
|
626
|
-
scanTruncated = true;
|
|
627
|
-
break;
|
|
628
|
-
}
|
|
629
|
-
let fileHasSdkCli = false;
|
|
630
|
-
const res = scanJsonlFileChunked(fileInfo.path, {
|
|
631
|
-
maxBytesRemaining: byteCap - bytesScanned,
|
|
632
|
-
onLine: (line) => {
|
|
633
|
-
let row;
|
|
634
|
-
try {
|
|
635
|
-
row = JSON.parse(line);
|
|
636
|
-
} catch {
|
|
637
|
-
return; // ignore: partial trailing JSONL line
|
|
638
|
-
}
|
|
639
|
-
if (row.version && fileInfo.mtimeMs >= latestVersionMtime) {
|
|
640
|
-
latestVersion = String(row.version).trim();
|
|
641
|
-
latestVersionMtime = fileInfo.mtimeMs;
|
|
642
|
-
}
|
|
643
|
-
if (row.entrypoint) {
|
|
644
|
-
const ep = String(row.entrypoint).trim();
|
|
645
|
-
entrypoints.add(ep);
|
|
646
|
-
if (ep === 'sdk-cli') fileHasSdkCli = true;
|
|
647
|
-
}
|
|
648
|
-
if (row.isSidechain === true) {
|
|
649
|
-
sidechainTurns7d += 1;
|
|
650
|
-
}
|
|
651
|
-
if (row.type === 'assistant') {
|
|
652
|
-
if (row.message?.model) {
|
|
653
|
-
observedModels.add(String(row.message.model).trim());
|
|
654
|
-
}
|
|
655
|
-
const u = row.message?.usage;
|
|
656
|
-
if (
|
|
657
|
-
u &&
|
|
658
|
-
typeof u === 'object' &&
|
|
659
|
-
(u.cache_read_input_tokens !== undefined || u.cache_creation_input_tokens !== undefined)
|
|
660
|
-
) {
|
|
661
|
-
const prefixTok = Number(u.cache_read_input_tokens || 0) + Number(u.cache_creation_input_tokens || 0);
|
|
662
|
-
if (Number.isFinite(prefixTok) && prefixTok >= 0) {
|
|
663
|
-
maxCachedPrefixTokens = maxCachedPrefixTokens === null ? prefixTok : Math.max(maxCachedPrefixTokens, prefixTok);
|
|
664
|
-
}
|
|
665
|
-
}
|
|
666
|
-
if (Array.isArray(row.message?.content)) {
|
|
667
|
-
for (const blk of row.message.content) {
|
|
668
|
-
if (blk?.type !== 'tool_use' || !blk.name) continue;
|
|
669
|
-
const toolName = String(blk.name);
|
|
670
|
-
if (toolName === 'Artifact') artifactCalls7d += 1;
|
|
671
|
-
if (toolName === 'Agent' || toolName === 'Task' || toolName === 'invoke_subagent') {
|
|
672
|
-
subagentSpawns7d += 1;
|
|
673
|
-
}
|
|
674
|
-
if (/^mcp__claude-in-chrome__/i.test(toolName) || /(?:^|__)chrome(?:__|$)/i.test(toolName)) {
|
|
675
|
-
browserToolCalls7d += 1;
|
|
676
|
-
}
|
|
677
|
-
if (toolName.startsWith('mcp__')) {
|
|
678
|
-
observedMcpToolNames.add(toolName);
|
|
679
|
-
}
|
|
680
|
-
const mcpMatch = toolName.match(/^mcp__([^_]+)__/);
|
|
681
|
-
if (mcpMatch) {
|
|
682
|
-
const srv = mcpMatch[1];
|
|
683
|
-
mcpToolCalls7d[srv] = (mcpToolCalls7d[srv] || 0) + 1;
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
const sysText =
|
|
689
|
-
typeof row.text === 'string'
|
|
690
|
-
? row.text
|
|
691
|
-
: typeof row.content === 'string'
|
|
692
|
-
? row.content
|
|
693
|
-
: typeof row.attachment?.text === 'string'
|
|
694
|
-
? row.attachment.text
|
|
695
|
-
: typeof row.attachment?.content === 'string'
|
|
696
|
-
? row.attachment.content
|
|
697
|
-
: '';
|
|
698
|
-
if (
|
|
699
|
-
row.method === 'notifications/tools/list_changed' ||
|
|
700
|
-
row.subtype === 'mcp_tools_list_changed' ||
|
|
701
|
-
((row.type === 'system' || row.type === 'attachment') && sysText.includes('notifications/tools/list_changed'))
|
|
702
|
-
) {
|
|
703
|
-
const srvName = String(row.server || row.serverName || row.params?.server || 'unknown').trim() || 'unknown';
|
|
704
|
-
runtimeListChangedServers.add(srvName);
|
|
705
|
-
}
|
|
706
|
-
if (
|
|
707
|
-
(row.type === 'attachment' && row.attachment?.type === 'mcp_instructions_delta') ||
|
|
708
|
-
row.subtype === 'mcp_instructions_delta'
|
|
709
|
-
) {
|
|
710
|
-
const payload = row.attachment?.content ?? row.attachment?.text ?? row.content ?? row.text ?? row.attachment ?? row;
|
|
711
|
-
const charLen = typeof payload === 'string' ? payload.length : JSON.stringify(payload || '').length;
|
|
712
|
-
if (charLen > observedMcpInstructionsDeltaChars) {
|
|
713
|
-
observedMcpInstructionsDeltaChars = charLen;
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
if (row.type === 'tools-used') {
|
|
717
|
-
if (Array.isArray(row.tools)) {
|
|
718
|
-
for (const t of row.tools) {
|
|
719
|
-
const name = typeof t === 'string' ? t : t && typeof t === 'object' ? t.name : null;
|
|
720
|
-
if (typeof name === 'string' && name.startsWith('mcp__')) {
|
|
721
|
-
observedMcpToolNames.add(name);
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
if (row.serverSchemas && typeof row.serverSchemas === 'object') {
|
|
726
|
-
for (const [srv, tok] of Object.entries(row.serverSchemas)) {
|
|
727
|
-
const n = Number(tok);
|
|
728
|
-
if (Number.isFinite(n) && n > 0) schemaTokensByServer[srv] = n;
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
});
|
|
734
|
-
sessionsScanned += 1;
|
|
735
|
-
bytesScanned += res.bytesRead;
|
|
736
|
-
if (res.truncated) scanTruncated = true;
|
|
737
|
-
if (fileHasSdkCli) sdkCliSessions7d += 1;
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
return {
|
|
741
|
-
sessionsScanned,
|
|
742
|
-
bytesScanned,
|
|
743
|
-
scanTruncated,
|
|
744
|
-
claudeCodeVersion: latestVersion,
|
|
745
|
-
entrypoints: Array.from(entrypoints),
|
|
746
|
-
browserToolCalls7d,
|
|
747
|
-
artifactCalls7d,
|
|
748
|
-
mcpToolCalls7d,
|
|
749
|
-
schemaTokensByServer,
|
|
750
|
-
observedMcpToolNames: Array.from(observedMcpToolNames),
|
|
751
|
-
maxCachedPrefixTokens,
|
|
752
|
-
runtimeListChangedServers: Array.from(runtimeListChangedServers),
|
|
753
|
-
subagentSpawns7d,
|
|
754
|
-
sidechainTurns7d,
|
|
755
|
-
observedMcpInstructionsDeltaChars,
|
|
756
|
-
observedModels: Array.from(observedModels),
|
|
757
|
-
sdkCliSessions7d
|
|
758
|
-
};
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
/**
|
|
762
|
-
* Strictly read-only scan of `~/.claude/agents/*.md` and `<cwd>/.claude/agents/*.md`
|
|
763
|
-
* to count custom subagent definitions and narrow frontmatter `tools:` allowlists.
|
|
764
|
-
*/
|
|
765
|
-
export function scanClaudeCustomAgentSpecs({ homeDir = getHomeDir(), cwd = process.cwd(), repoOnly = false } = {}) {
|
|
766
|
-
const dirs = repoOnly
|
|
767
|
-
? [path.join(cwd, '.claude', 'agents')]
|
|
768
|
-
: [path.join(homeDir, '.claude', 'agents'), path.join(cwd, '.claude', 'agents')];
|
|
769
|
-
const seen = new Set();
|
|
770
|
-
const agents = [];
|
|
771
|
-
let narrowToolsAgents = 0;
|
|
772
|
-
|
|
773
|
-
for (const dir of dirs) {
|
|
774
|
-
if (!fs.existsSync(dir)) continue;
|
|
775
|
-
let entries = [];
|
|
776
|
-
try {
|
|
777
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
778
|
-
} catch {
|
|
779
|
-
continue; // ignore: unreadable Claude agents directory
|
|
780
|
-
}
|
|
781
|
-
for (const ent of entries) {
|
|
782
|
-
if (!ent.isFile() || !/\.md$/i.test(ent.name)) continue;
|
|
783
|
-
const fullPath = path.join(dir, ent.name);
|
|
784
|
-
let key = canonicalizePath(fullPath);
|
|
785
|
-
try {
|
|
786
|
-
key = canonicalizePath(fs.realpathSync(fullPath));
|
|
787
|
-
} catch {
|
|
788
|
-
// ignore: fallback to canonicalized path when realpath fails
|
|
789
|
-
}
|
|
790
|
-
if (seen.has(key)) continue;
|
|
791
|
-
seen.add(key);
|
|
792
|
-
|
|
793
|
-
let hasNarrowTools = false;
|
|
794
|
-
try {
|
|
795
|
-
const raw = fs.readFileSync(fullPath, 'utf8');
|
|
796
|
-
const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
797
|
-
if (fmMatch && /(?:^|\r?\n)tools\s*:/i.test(fmMatch[1])) {
|
|
798
|
-
hasNarrowTools = true;
|
|
799
|
-
narrowToolsAgents += 1;
|
|
800
|
-
}
|
|
801
|
-
} catch {
|
|
802
|
-
// ignore: unreadable custom agent markdown file
|
|
803
|
-
}
|
|
804
|
-
agents.push({
|
|
805
|
-
name: ent.name.replace(/\.md$/i, ''),
|
|
806
|
-
path: fullPath.replace(/\\/g, '/'),
|
|
807
|
-
hasNarrowTools
|
|
808
|
-
});
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
return {
|
|
813
|
-
totalAgents: agents.length,
|
|
814
|
-
narrowToolsAgents,
|
|
815
|
-
agents
|
|
816
|
-
};
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
function detectAnthropicSdkMarkers(cwd) {
|
|
820
|
-
const pkg = parseJsoncReadOnly(path.join(cwd, 'package.json'));
|
|
821
|
-
if (pkg.parseOk && pkg.parsed && typeof pkg.parsed === 'object') {
|
|
822
|
-
const allDeps = {
|
|
823
|
-
...(pkg.parsed.dependencies || {}),
|
|
824
|
-
...(pkg.parsed.devDependencies || {}),
|
|
825
|
-
...(pkg.parsed.peerDependencies || {})
|
|
826
|
-
};
|
|
827
|
-
for (const depName of Object.keys(allDeps)) {
|
|
828
|
-
if (depName === '@anthropic-ai/sdk' || /^@anthropic-ai\//i.test(depName) || /^claude-/i.test(depName)) {
|
|
829
|
-
return true;
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
for (const docName of ['README.md', 'readme.md']) {
|
|
834
|
-
const fp = path.join(cwd, docName);
|
|
835
|
-
if (!fs.existsSync(fp)) continue;
|
|
836
|
-
try {
|
|
837
|
-
const head = fs.readFileSync(fp, 'utf8').slice(0, 16384);
|
|
838
|
-
if (/@anthropic-ai\/sdk|cache_control|prompt caching/i.test(head)) return true;
|
|
839
|
-
} catch {
|
|
840
|
-
// ignore: unreadable README.md
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
return false;
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
function collectClaudeMcpServers({ workspacePath, claudeJsonParsed }) {
|
|
847
|
-
const servers = new Map();
|
|
848
|
-
const addMap = (serversMap, sourceFile) => {
|
|
849
|
-
if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
|
|
850
|
-
for (const [name, cfg] of Object.entries(serversMap)) {
|
|
851
|
-
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
|
|
852
|
-
if (cfg.disabled === true || cfg.enabled === false) continue;
|
|
853
|
-
const hint = Number(cfg.estimatedTokens ?? cfg.schemaTokens ?? cfg.tokenCount ?? 0);
|
|
854
|
-
servers.set(name, {
|
|
855
|
-
name,
|
|
856
|
-
sourceFile,
|
|
857
|
-
hintTokens: Number.isFinite(hint) && hint > 0 ? hint : 0
|
|
858
|
-
});
|
|
859
|
-
}
|
|
860
|
-
};
|
|
861
|
-
|
|
862
|
-
const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
|
|
863
|
-
if (projMcp.parseOk && projMcp.parsed) {
|
|
864
|
-
addMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
if (claudeJsonParsed && typeof claudeJsonParsed === 'object') {
|
|
868
|
-
addMap(claudeJsonParsed.mcpServers, '~/.claude.json');
|
|
869
|
-
const projects = claudeJsonParsed.projects;
|
|
870
|
-
if (projects && typeof projects === 'object') {
|
|
871
|
-
const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
|
|
872
|
-
for (const [projKey, projCfg] of Object.entries(projects)) {
|
|
873
|
-
if (!projCfg || typeof projCfg !== 'object') continue;
|
|
874
|
-
const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
|
|
875
|
-
if (normKey === normWs && projCfg.mcpServers) {
|
|
876
|
-
addMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
|
|
882
|
-
return Array.from(servers.values());
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
function evaluateClaudeEagerMcpGate({
|
|
886
|
-
paths,
|
|
887
|
-
env = process.env,
|
|
888
|
-
claudeCodeVersion = null,
|
|
889
|
-
claudeJsonParsed = null,
|
|
890
|
-
userSettingsParsed = null,
|
|
891
|
-
projSettingsParsed = null,
|
|
892
|
-
projLocalSettingsParsed = null,
|
|
893
|
-
mcpToolCalls7d = {},
|
|
894
|
-
schemaTokensByServer = {},
|
|
895
|
-
gatewaySupportsToolSearch = false
|
|
896
|
-
}) {
|
|
897
|
-
const readLayeredEnv = (key) => {
|
|
898
|
-
let val = null;
|
|
899
|
-
for (const doc of [userSettingsParsed, projSettingsParsed, projLocalSettingsParsed]) {
|
|
900
|
-
if (doc?.env && doc.env[key] !== undefined && String(doc.env[key]).trim() !== '') {
|
|
901
|
-
val = String(doc.env[key]).trim();
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
if (env && env[key] !== undefined && String(env[key]).trim() !== '') {
|
|
905
|
-
val = String(env[key]).trim();
|
|
906
|
-
}
|
|
907
|
-
return val;
|
|
908
|
-
};
|
|
909
|
-
|
|
910
|
-
const enableToolSearch = readLayeredEnv('ENABLE_TOOL_SEARCH');
|
|
911
|
-
const rawDisableBetas = readLayeredEnv('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS');
|
|
912
|
-
const baseUrl = readLayeredEnv('ANTHROPIC_BASE_URL');
|
|
913
|
-
|
|
914
|
-
const isCustomGateway = Boolean(baseUrl && !/^https:\/\/api\.anthropic\.com(?:\/|$)/i.test(baseUrl));
|
|
915
|
-
const disableExperimentalBetas = /^(1|true)$/i.test(String(rawDisableBetas || '').trim());
|
|
916
|
-
const toolSearchDisabled = /^(false|0)$/i.test(String(enableToolSearch || '').trim());
|
|
917
|
-
const toolSearchForcedOn = /^(true|1)$/i.test(String(enableToolSearch || '').trim());
|
|
918
|
-
const versionCmp = claudeCodeVersion ? compareSemver(claudeCodeVersion, '2.1.304') : null;
|
|
919
|
-
const versionBelow21304 = Boolean(versionCmp !== null && versionCmp < 0);
|
|
920
|
-
|
|
921
|
-
const discovered = collectClaudeMcpServers({ workspacePath: paths.cwd, claudeJsonParsed });
|
|
922
|
-
const isSshSession = Boolean(
|
|
923
|
-
(env?.SSH_CONNECTION && String(env.SSH_CONNECTION).trim()) ||
|
|
924
|
-
(env?.SSH_TTY && String(env.SSH_TTY).trim()) ||
|
|
925
|
-
(env?.SSH_CLIENT && String(env.SSH_CLIENT).trim())
|
|
926
|
-
);
|
|
927
|
-
const gatewayVerified =
|
|
928
|
-
gatewaySupportsToolSearch === true ||
|
|
929
|
-
/^(1|true)$/i.test(
|
|
930
|
-
String(
|
|
931
|
-
readLayeredEnv('BURNOFF_GATEWAY_VERIFIED_TOOL_SEARCH') ||
|
|
932
|
-
readLayeredEnv('CLAUDE_CODE_GATEWAY_VERIFIED_TOOL_SEARCH') ||
|
|
933
|
-
''
|
|
934
|
-
).trim()
|
|
935
|
-
);
|
|
936
|
-
|
|
937
|
-
const gateReasons = [];
|
|
938
|
-
if (toolSearchDisabled) gateReasons.push('ENABLE_TOOL_SEARCH=false');
|
|
939
|
-
if (disableExperimentalBetas) gateReasons.push('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1');
|
|
940
|
-
if (isSshSession && (discovered.length > 0 || toolSearchForcedOn)) {
|
|
941
|
-
gateReasons.push('ssh_forced_disable_experimental_betas');
|
|
942
|
-
}
|
|
943
|
-
if (isCustomGateway && !gatewayVerified && discovered.length > 0) {
|
|
944
|
-
if (versionBelow21304 && !toolSearchForcedOn) {
|
|
945
|
-
gateReasons.push('custom_gateway_claude_code_lt_2.1.304');
|
|
946
|
-
} else {
|
|
947
|
-
gateReasons.push('custom_gateway_toolsearch_fallback');
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
if (gateReasons.length === 0) {
|
|
952
|
-
return {
|
|
953
|
-
eagerGateActive: false,
|
|
954
|
-
gateReasons: [],
|
|
955
|
-
enableToolSearch,
|
|
956
|
-
toolSearchDisabled,
|
|
957
|
-
disableExperimentalBetas,
|
|
958
|
-
isCustomGateway,
|
|
959
|
-
baseUrl: baseUrl || null,
|
|
960
|
-
isLocalhostProxy: Boolean(baseUrl && isLocalhostBaseUrl(baseUrl)),
|
|
961
|
-
isSshSession,
|
|
962
|
-
gatewayVerified,
|
|
963
|
-
configuredServerCount: discovered.length,
|
|
964
|
-
configuredServerNames: discovered.map((s) => s.name),
|
|
965
|
-
claudeCodeVersion: claudeCodeVersion || null,
|
|
966
|
-
startupTaxTokensPerTurn: 0,
|
|
967
|
-
summaryLine: 'MCP startup tax: 0 tok/turn (deferred loading active)',
|
|
968
|
-
unusedEagerServers: []
|
|
969
|
-
};
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
const unusedEagerServers = [];
|
|
973
|
-
let startupTaxTokensPerTurn = 0;
|
|
974
|
-
|
|
975
|
-
for (const srv of discovered) {
|
|
976
|
-
const telemetryTokens = Number(schemaTokensByServer[srv.name] || 0);
|
|
977
|
-
const tokensEst = telemetryTokens > 0 ? telemetryTokens : srv.hintTokens > 0 ? srv.hintTokens : 3200;
|
|
978
|
-
const calls7d = Number(mcpToolCalls7d[srv.name] || 0);
|
|
979
|
-
startupTaxTokensPerTurn += tokensEst;
|
|
980
|
-
if (calls7d === 0) {
|
|
981
|
-
unusedEagerServers.push({
|
|
982
|
-
name: srv.name,
|
|
983
|
-
sourceFile: srv.sourceFile,
|
|
984
|
-
tokensEst,
|
|
985
|
-
isEstimated: !(telemetryTokens > 0 || srv.hintTokens > 0),
|
|
986
|
-
calls7d
|
|
987
|
-
});
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
return {
|
|
992
|
-
eagerGateActive: true,
|
|
993
|
-
gateReasons,
|
|
994
|
-
enableToolSearch,
|
|
995
|
-
toolSearchDisabled,
|
|
996
|
-
disableExperimentalBetas,
|
|
997
|
-
isCustomGateway,
|
|
998
|
-
baseUrl: baseUrl || null,
|
|
999
|
-
isLocalhostProxy: Boolean(baseUrl && isLocalhostBaseUrl(baseUrl)),
|
|
1000
|
-
isSshSession,
|
|
1001
|
-
gatewayVerified,
|
|
1002
|
-
configuredServerCount: discovered.length,
|
|
1003
|
-
configuredServerNames: discovered.map((s) => s.name),
|
|
1004
|
-
claudeCodeVersion: claudeCodeVersion || null,
|
|
1005
|
-
startupTaxTokensPerTurn,
|
|
1006
|
-
summaryLine: `MCP startup tax: ~${startupTaxTokensPerTurn.toLocaleString('en-US')} tok/turn (${discovered.length} eager server${discovered.length === 1 ? '' : 's'})`,
|
|
1007
|
-
unusedEagerServers
|
|
1008
|
-
};
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
/**
|
|
1012
|
-
* Returns true if `rawUrl` points to a loopback / localhost proxy endpoint.
|
|
1013
|
-
*/
|
|
1014
|
-
export function isLocalhostBaseUrl(rawUrl) {
|
|
1015
|
-
const s = String(rawUrl || '').trim();
|
|
1016
|
-
if (!s) return false;
|
|
1017
|
-
try {
|
|
1018
|
-
const u = new URL(s);
|
|
1019
|
-
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
1020
|
-
return (
|
|
1021
|
-
host === 'localhost' ||
|
|
1022
|
-
host === '127.0.0.1' ||
|
|
1023
|
-
host === '::1' ||
|
|
1024
|
-
host === '0.0.0.0' ||
|
|
1025
|
-
host === 'host.docker.internal' ||
|
|
1026
|
-
host.endsWith('.localhost')
|
|
1027
|
-
);
|
|
1028
|
-
} catch {
|
|
1029
|
-
return false; // ignore: malformed ANTHROPIC_BASE_URL is not treated as localhost proxy
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
/**
|
|
1034
|
-
* BO-MCP-10: Eager-only coarse meta-tool coaching + local `ANTHROPIC_BASE_URL`
|
|
1035
|
-
* MCP proxy `CACHE-BACKFIRE TRAP` lint. Never emits coarse meta-tool advice when
|
|
1036
|
-
* native deferred `ToolSearch` loading is healthy (`eagerGateActive === false`).
|
|
1037
|
-
*/
|
|
1038
|
-
export function evaluateMcpProxyAndMetaToolCoaching({
|
|
1039
|
-
harness = 'claude-code',
|
|
1040
|
-
eagerGateActive = false,
|
|
1041
|
-
baseUrl = null,
|
|
1042
|
-
isLocalhostProxy = isLocalhostBaseUrl(baseUrl),
|
|
1043
|
-
gatewayVerified = false,
|
|
1044
|
-
toolSearchDisabled = false,
|
|
1045
|
-
disableExperimentalBetas = false,
|
|
1046
|
-
isSshSession = false,
|
|
1047
|
-
configuredServerCount = 0,
|
|
1048
|
-
configuredServerNames = [],
|
|
1049
|
-
startupTaxTokensPerTurn = 0,
|
|
1050
|
-
file = 'env'
|
|
1051
|
-
} = {}) {
|
|
1052
|
-
const proxyLooksLikeMcpGateway = /mcp|proxy|gateway|router/i.test(String(baseUrl || ''));
|
|
1053
|
-
const proxyCacheBackfireTrap = Boolean(
|
|
1054
|
-
harness === 'claude-code' &&
|
|
1055
|
-
isLocalhostProxy &&
|
|
1056
|
-
!gatewayVerified &&
|
|
1057
|
-
!toolSearchDisabled &&
|
|
1058
|
-
!disableExperimentalBetas &&
|
|
1059
|
-
!isSshSession &&
|
|
1060
|
-
(configuredServerCount > 0 || proxyLooksLikeMcpGateway)
|
|
1061
|
-
);
|
|
1062
|
-
|
|
1063
|
-
const meetsCoarseThreshold =
|
|
1064
|
-
configuredServerCount >= COARSE_META_TOOL_MIN_SERVERS ||
|
|
1065
|
-
Number(startupTaxTokensPerTurn || 0) >= COARSE_META_TOOL_MIN_TOKENS;
|
|
1066
|
-
const coarseMetaToolCoaching = Boolean(eagerGateActive && !proxyCacheBackfireTrap && meetsCoarseThreshold);
|
|
1067
|
-
|
|
1068
|
-
const lints = [];
|
|
1069
|
-
let coachingNote = null;
|
|
1070
|
-
|
|
1071
|
-
if (proxyCacheBackfireTrap) {
|
|
1072
|
-
coachingNote =
|
|
1073
|
-
`CACHE-BACKFIRE TRAP (BO-MCP-10): Localhost ANTHROPIC_BASE_URL proxy (${baseUrl}) wraps an otherwise native-deferred Claude Code setup, risking #95087 beta-header stripping (forcing eager MCP fallback) and extra proxy latency. Unset ANTHROPIC_BASE_URL to restore native ToolSearch deferral, or set BURNOFF_GATEWAY_VERIFIED_TOOL_SEARCH=1 if verified.`;
|
|
1074
|
-
lints.push({
|
|
1075
|
-
ruleId: 'BO-MCP-10',
|
|
1076
|
-
kind: 'proxy_cache_backfire',
|
|
1077
|
-
severity: 'warn',
|
|
1078
|
-
harness,
|
|
1079
|
-
file,
|
|
1080
|
-
message: coachingNote,
|
|
1081
|
-
remediation:
|
|
1082
|
-
'Remove unnecessary local ANTHROPIC_BASE_URL MCP proxies when native Claude Code ToolSearch deferral is available.'
|
|
1083
|
-
});
|
|
1084
|
-
} else if (coarseMetaToolCoaching) {
|
|
1085
|
-
coachingNote =
|
|
1086
|
-
`Eager MCP Coarse Meta-Tool Coaching (BO-MCP-10): Eager schema loading active (${configuredServerCount} servers, ~${Number(startupTaxTokensPerTurn || 0).toLocaleString('en-US')} est. tok/turn). Consolidate fine-grained MCP tools into coarse progressive-disclosure meta-tools or disable unused servers between sessions.`;
|
|
1087
|
-
lints.push({
|
|
1088
|
-
ruleId: 'BO-MCP-10',
|
|
1089
|
-
kind: 'eager_coarse_meta_tool',
|
|
1090
|
-
severity: 'info',
|
|
1091
|
-
harness,
|
|
1092
|
-
file,
|
|
1093
|
-
configuredServers: configuredServerNames,
|
|
1094
|
-
message: coachingNote,
|
|
1095
|
-
remediation:
|
|
1096
|
-
'Consolidate chatty fine-grained MCP tools behind coarse domain actions only while eager loading is unavoidable, or re-enable native ToolSearch deferral.'
|
|
1097
|
-
});
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
return {
|
|
1101
|
-
status: proxyCacheBackfireTrap ? 'warn' : coarseMetaToolCoaching ? 'info' : 'pass',
|
|
1102
|
-
eagerGateActive: Boolean(eagerGateActive),
|
|
1103
|
-
isLocalhostProxy: Boolean(isLocalhostProxy),
|
|
1104
|
-
baseUrl: baseUrl || null,
|
|
1105
|
-
proxyCacheBackfireTrap,
|
|
1106
|
-
coarseMetaToolCoaching,
|
|
1107
|
-
coachingNote,
|
|
1108
|
-
lints
|
|
1109
|
-
};
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
/**
|
|
1113
|
-
* BO-MCP-05 (#97616): Scans configured MCP tool definitions and observed Claude Code
|
|
1114
|
-
* MCP tool names for `mcp__<server>__<tool>` identifiers exceeding 64 characters.
|
|
1115
|
-
*/
|
|
1116
|
-
export function scanMcpToolNameLengthViolations({
|
|
1117
|
-
homeDir = getHomeDir(),
|
|
1118
|
-
workspacePath = process.cwd(),
|
|
1119
|
-
observedToolNames = [],
|
|
1120
|
-
manifestDirs = [],
|
|
1121
|
-
maxLength = 64,
|
|
1122
|
-
repoOnly = false
|
|
1123
|
-
} = {}) {
|
|
1124
|
-
const disabledServers = new Set();
|
|
1125
|
-
const violationsByFullName = new Map();
|
|
1126
|
-
|
|
1127
|
-
const recordViolation = (fullName, serverName, toolName, source) => {
|
|
1128
|
-
if (!fullName || fullName.length <= maxLength) return;
|
|
1129
|
-
if (disabledServers.has(serverName)) return;
|
|
1130
|
-
if (violationsByFullName.has(fullName)) return;
|
|
1131
|
-
violationsByFullName.set(fullName, {
|
|
1132
|
-
fullName,
|
|
1133
|
-
serverName,
|
|
1134
|
-
toolName,
|
|
1135
|
-
length: fullName.length,
|
|
1136
|
-
source
|
|
1137
|
-
});
|
|
1138
|
-
};
|
|
1139
|
-
|
|
1140
|
-
const inspectServerMap = (serversMap, source) => {
|
|
1141
|
-
if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
|
|
1142
|
-
for (const [serverName, cfg] of Object.entries(serversMap)) {
|
|
1143
|
-
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
|
|
1144
|
-
if (cfg.disabled === true || cfg.enabled === false) {
|
|
1145
|
-
disabledServers.add(serverName);
|
|
1146
|
-
continue;
|
|
1147
|
-
}
|
|
1148
|
-
disabledServers.delete(serverName);
|
|
1149
|
-
for (const field of ['tools', 'eagerTools']) {
|
|
1150
|
-
if (!Array.isArray(cfg[field])) continue;
|
|
1151
|
-
for (const item of cfg[field]) {
|
|
1152
|
-
const toolName =
|
|
1153
|
-
typeof item === 'string'
|
|
1154
|
-
? item.trim()
|
|
1155
|
-
: item && typeof item === 'object' && typeof item.name === 'string'
|
|
1156
|
-
? item.name.trim()
|
|
1157
|
-
: '';
|
|
1158
|
-
if (toolName) {
|
|
1159
|
-
recordViolation(`mcp__${serverName}__${toolName}`, serverName, toolName, source);
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
};
|
|
1165
|
-
|
|
1166
|
-
const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
|
|
1167
|
-
if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
|
|
1168
|
-
inspectServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path.replace(/\\/g, '/'));
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
const claudeJson = repoOnly
|
|
1172
|
-
? { parseOk: false, parsed: null }
|
|
1173
|
-
: parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
|
|
1174
|
-
if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
|
|
1175
|
-
inspectServerMap(claudeJson.parsed.mcpServers, '~/.claude.json');
|
|
1176
|
-
const projects = claudeJson.parsed.projects;
|
|
1177
|
-
if (projects && typeof projects === 'object') {
|
|
1178
|
-
const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
|
|
1179
|
-
for (const [projKey, projCfg] of Object.entries(projects)) {
|
|
1180
|
-
if (!projCfg || typeof projCfg !== 'object') continue;
|
|
1181
|
-
const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
|
|
1182
|
-
if (normKey === normWs && projCfg.mcpServers) {
|
|
1183
|
-
inspectServerMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
for (const mDir of Array.isArray(manifestDirs) ? manifestDirs : []) {
|
|
1190
|
-
if (!mDir || !fs.existsSync(mDir)) continue;
|
|
1191
|
-
let serverEntries = [];
|
|
1192
|
-
try {
|
|
1193
|
-
serverEntries = fs.readdirSync(mDir, { withFileTypes: true });
|
|
1194
|
-
} catch {
|
|
1195
|
-
serverEntries = []; // ignore: unreadable MCP manifest directory
|
|
1196
|
-
}
|
|
1197
|
-
for (const ent of serverEntries) {
|
|
1198
|
-
if (!ent.isDirectory()) continue;
|
|
1199
|
-
const serverName = ent.name;
|
|
1200
|
-
if (disabledServers.has(serverName)) continue;
|
|
1201
|
-
const srvDir = path.join(mDir, serverName);
|
|
1202
|
-
let files = [];
|
|
1203
|
-
try {
|
|
1204
|
-
files = fs.readdirSync(srvDir, { withFileTypes: true });
|
|
1205
|
-
} catch {
|
|
1206
|
-
continue; // ignore: unreadable MCP server manifest directory
|
|
1207
|
-
}
|
|
1208
|
-
for (const f of files) {
|
|
1209
|
-
if (!f.isFile() || !/\.json$/i.test(f.name)) continue;
|
|
1210
|
-
const filePath = path.join(srvDir, f.name);
|
|
1211
|
-
const res = parseJsoncReadOnly(filePath);
|
|
1212
|
-
if (!res.parseOk || !res.parsed || typeof res.parsed !== 'object') continue;
|
|
1213
|
-
const lowerFile = f.name.toLowerCase();
|
|
1214
|
-
const isMetaFile = lowerFile === 'server.json' || lowerFile === 'capabilities.json';
|
|
1215
|
-
const toolNames = new Set();
|
|
1216
|
-
if (!isMetaFile && typeof res.parsed.name === 'string' && res.parsed.name.trim()) {
|
|
1217
|
-
toolNames.add(res.parsed.name.trim());
|
|
1218
|
-
}
|
|
1219
|
-
if (Array.isArray(res.parsed.tools)) {
|
|
1220
|
-
for (const item of res.parsed.tools) {
|
|
1221
|
-
if (typeof item === 'string' && item.trim()) toolNames.add(item.trim());
|
|
1222
|
-
else if (item && typeof item === 'object' && typeof item.name === 'string' && item.name.trim()) {
|
|
1223
|
-
toolNames.add(item.name.trim());
|
|
1224
|
-
}
|
|
1225
|
-
}
|
|
1226
|
-
} else if (!isMetaFile && typeof res.parsed.name !== 'string') {
|
|
1227
|
-
const stem = f.name.replace(/\.json$/i, '').trim();
|
|
1228
|
-
if (stem) toolNames.add(stem);
|
|
1229
|
-
}
|
|
1230
|
-
const source = filePath.replace(/\\/g, '/');
|
|
1231
|
-
for (const toolName of toolNames) {
|
|
1232
|
-
recordViolation(`mcp__${serverName}__${toolName}`, serverName, toolName, source);
|
|
1233
|
-
}
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
if (Array.isArray(observedToolNames)) {
|
|
1239
|
-
for (const rawName of observedToolNames) {
|
|
1240
|
-
const name = String(rawName || '').trim();
|
|
1241
|
-
const match = name.match(/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/);
|
|
1242
|
-
if (!match) continue;
|
|
1243
|
-
recordViolation(name, match[1], match[2], 'transcript');
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
return {
|
|
1248
|
-
maxLength,
|
|
1249
|
-
violations: Array.from(violationsByFullName.values())
|
|
1250
|
-
};
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
function collectDisabledClaudeMcpServers({ homeDir = getHomeDir(), workspacePath = process.cwd() } = {}) {
|
|
1254
|
-
const disabledServers = new Set();
|
|
1255
|
-
const trackServerMap = (serversMap) => {
|
|
1256
|
-
if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
|
|
1257
|
-
for (const [name, cfg] of Object.entries(serversMap)) {
|
|
1258
|
-
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
|
|
1259
|
-
if (cfg.disabled === true || cfg.enabled === false) {
|
|
1260
|
-
disabledServers.add(name);
|
|
1261
|
-
} else {
|
|
1262
|
-
disabledServers.delete(name);
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1265
|
-
};
|
|
1266
|
-
|
|
1267
|
-
const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
|
|
1268
|
-
if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
|
|
1269
|
-
trackServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed);
|
|
1270
|
-
}
|
|
1271
|
-
|
|
1272
|
-
const claudeJson = homeDir ? parseJsoncReadOnly(path.join(homeDir, '.claude.json')) : { parseOk: false, parsed: null };
|
|
1273
|
-
if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
|
|
1274
|
-
trackServerMap(claudeJson.parsed.mcpServers);
|
|
1275
|
-
const projects = claudeJson.parsed.projects;
|
|
1276
|
-
if (projects && typeof projects === 'object') {
|
|
1277
|
-
const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
|
|
1278
|
-
for (const [projKey, projCfg] of Object.entries(projects)) {
|
|
1279
|
-
if (!projCfg || typeof projCfg !== 'object') continue;
|
|
1280
|
-
const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
|
|
1281
|
-
if (normKey === normWs && projCfg.mcpServers) {
|
|
1282
|
-
trackServerMap(projCfg.mcpServers);
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
return disabledServers;
|
|
1288
|
-
}
|
|
1289
|
-
|
|
1290
|
-
function hasListChangedFlag(doc) {
|
|
1291
|
-
if (!doc || typeof doc !== 'object') return false;
|
|
1292
|
-
return Boolean(
|
|
1293
|
-
doc.capabilities?.tools?.listChanged === true ||
|
|
1294
|
-
doc.result?.capabilities?.tools?.listChanged === true ||
|
|
1295
|
-
doc.tools?.listChanged === true ||
|
|
1296
|
-
doc.listChanged === true
|
|
1297
|
-
);
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
/**
|
|
1301
|
-
* BO-MCP-06 (#2812, #1923): Scans Claude Code MCP configs, optional manifest dirs,
|
|
1302
|
-
* and runtime notifications for `tools.listChanged: true` / `notifications/tools/list_changed`,
|
|
1303
|
-
* guarding suppression when observed prefix <= 20k tokens.
|
|
1304
|
-
*/
|
|
1305
|
-
export function scanMcpListChangedCapabilities({
|
|
1306
|
-
homeDir = getHomeDir(),
|
|
1307
|
-
workspacePath = process.cwd(),
|
|
1308
|
-
manifestDirs = [],
|
|
1309
|
-
runtimeListChangedServers = [],
|
|
1310
|
-
maxObservedCachedPrefixTokens = null,
|
|
1311
|
-
cachedPrefixThreshold = LIST_CHANGED_PREFIX_THRESHOLD,
|
|
1312
|
-
repoOnly = false
|
|
1313
|
-
} = {}) {
|
|
1314
|
-
const disabledServers = collectDisabledClaudeMcpServers({ homeDir: repoOnly ? null : homeDir, workspacePath });
|
|
1315
|
-
const flaggedByServer = new Map();
|
|
1316
|
-
|
|
1317
|
-
const recordFlagged = (serverName, reason, source) => {
|
|
1318
|
-
const name = String(serverName || '').trim();
|
|
1319
|
-
if (!name || disabledServers.has(name) || flaggedByServer.has(name)) return;
|
|
1320
|
-
flaggedByServer.set(name, {
|
|
1321
|
-
serverName: name,
|
|
1322
|
-
reason,
|
|
1323
|
-
source: String(source || '').replace(/\\/g, '/')
|
|
1324
|
-
});
|
|
1325
|
-
};
|
|
1326
|
-
|
|
1327
|
-
const inspectConfigMap = (serversMap, source) => {
|
|
1328
|
-
if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return;
|
|
1329
|
-
for (const [name, cfg] of Object.entries(serversMap)) {
|
|
1330
|
-
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
|
|
1331
|
-
if (cfg.disabled === true || cfg.enabled === false) continue;
|
|
1332
|
-
if (hasListChangedFlag(cfg)) {
|
|
1333
|
-
recordFlagged(name, 'tools.listChanged: true', source);
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
};
|
|
1337
|
-
|
|
1338
|
-
const projMcp = parseJsoncReadOnly(path.join(workspacePath, '.mcp.json'));
|
|
1339
|
-
if (projMcp.parseOk && projMcp.parsed && typeof projMcp.parsed === 'object') {
|
|
1340
|
-
inspectConfigMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
const claudeJson = repoOnly
|
|
1344
|
-
? { parseOk: false, parsed: null }
|
|
1345
|
-
: parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
|
|
1346
|
-
if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
|
|
1347
|
-
inspectConfigMap(claudeJson.parsed.mcpServers, '~/.claude.json');
|
|
1348
|
-
const projects = claudeJson.parsed.projects;
|
|
1349
|
-
if (projects && typeof projects === 'object') {
|
|
1350
|
-
const normWs = path.resolve(workspacePath).replace(/\\/g, '/').toLowerCase();
|
|
1351
|
-
for (const [projKey, projCfg] of Object.entries(projects)) {
|
|
1352
|
-
if (!projCfg || typeof projCfg !== 'object') continue;
|
|
1353
|
-
const normKey = String(projKey || '').replace(/\\/g, '/').toLowerCase();
|
|
1354
|
-
if (normKey === normWs && projCfg.mcpServers) {
|
|
1355
|
-
inspectConfigMap(projCfg.mcpServers, `~/.claude.json#projects[${projKey}]`);
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
for (const mDir of Array.isArray(manifestDirs) ? manifestDirs : []) {
|
|
1362
|
-
if (!mDir || !fs.existsSync(mDir)) continue;
|
|
1363
|
-
let serverEntries = [];
|
|
1364
|
-
try {
|
|
1365
|
-
serverEntries = fs.readdirSync(mDir, { withFileTypes: true });
|
|
1366
|
-
} catch {
|
|
1367
|
-
serverEntries = []; // ignore: unreadable MCP manifest directory
|
|
1368
|
-
}
|
|
1369
|
-
for (const ent of serverEntries) {
|
|
1370
|
-
if (!ent.isDirectory()) continue;
|
|
1371
|
-
const serverName = ent.name;
|
|
1372
|
-
if (disabledServers.has(serverName)) continue;
|
|
1373
|
-
const srvDir = path.join(mDir, serverName);
|
|
1374
|
-
let files = [];
|
|
1375
|
-
try {
|
|
1376
|
-
files = fs.readdirSync(srvDir, { withFileTypes: true });
|
|
1377
|
-
} catch {
|
|
1378
|
-
continue; // ignore: unreadable MCP server manifest directory
|
|
1379
|
-
}
|
|
1380
|
-
for (const f of files) {
|
|
1381
|
-
if (!f.isFile() || !/\.json$/i.test(f.name)) continue;
|
|
1382
|
-
const filePath = path.join(srvDir, f.name);
|
|
1383
|
-
const res = parseJsoncReadOnly(filePath);
|
|
1384
|
-
if (!res.parseOk || !res.parsed || typeof res.parsed !== 'object') continue;
|
|
1385
|
-
if (hasListChangedFlag(res.parsed)) {
|
|
1386
|
-
recordFlagged(serverName, 'tools.listChanged: true', filePath);
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
if (Array.isArray(runtimeListChangedServers)) {
|
|
1393
|
-
for (const item of runtimeListChangedServers) {
|
|
1394
|
-
if (typeof item === 'string') {
|
|
1395
|
-
recordFlagged(item, 'notifications/tools/list_changed', 'transcript');
|
|
1396
|
-
} else if (item && typeof item === 'object' && item.serverName) {
|
|
1397
|
-
recordFlagged(item.serverName, item.reason || 'notifications/tools/list_changed', item.source || 'transcript');
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
}
|
|
1401
|
-
|
|
1402
|
-
const flaggedServers = Array.from(flaggedByServer.values());
|
|
1403
|
-
const hasTelemetryPrefix =
|
|
1404
|
-
typeof maxObservedCachedPrefixTokens === 'number' && Number.isFinite(maxObservedCachedPrefixTokens);
|
|
1405
|
-
const suppressedByPrefixGuard =
|
|
1406
|
-
flaggedServers.length > 0 && hasTelemetryPrefix && maxObservedCachedPrefixTokens <= cachedPrefixThreshold;
|
|
1407
|
-
const status = flaggedServers.length === 0 ? 'pass' : suppressedByPrefixGuard ? 'info' : 'warn';
|
|
1408
|
-
|
|
1409
|
-
return {
|
|
1410
|
-
status,
|
|
1411
|
-
flaggedServers,
|
|
1412
|
-
suppressedByPrefixGuard,
|
|
1413
|
-
maxObservedCachedPrefixTokens: hasTelemetryPrefix ? maxObservedCachedPrefixTokens : null,
|
|
1414
|
-
cachedPrefixThreshold
|
|
1415
|
-
};
|
|
1416
|
-
}
|
|
1417
|
-
|
|
1418
|
-
/**
|
|
1419
|
-
* BO-MCP-09 (#104791, #98438): Estimates per-subagent `mcp_instructions_delta` tax
|
|
1420
|
-
* when > 5 connected MCP servers coexist with spawned or defined subagents.
|
|
1421
|
-
*/
|
|
1422
|
-
export function estimateSubagentMcpInstructionsTax({
|
|
1423
|
-
connectedServerNames = [],
|
|
1424
|
-
subagentCount = 0,
|
|
1425
|
-
observedMcpInstructionsDeltaChars = 0,
|
|
1426
|
-
minServers = SUBAGENT_MCP_MIN_SERVERS,
|
|
1427
|
-
tokensPerServerFallback = DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER
|
|
1428
|
-
} = {}) {
|
|
1429
|
-
const uniqueServers = [];
|
|
1430
|
-
const seen = new Set();
|
|
1431
|
-
for (const raw of Array.isArray(connectedServerNames) ? connectedServerNames : []) {
|
|
1432
|
-
const name = String(raw || '').trim();
|
|
1433
|
-
if (!name || seen.has(name)) continue;
|
|
1434
|
-
seen.add(name);
|
|
1435
|
-
uniqueServers.push(name);
|
|
1436
|
-
}
|
|
1437
|
-
|
|
1438
|
-
const connectedServerCount = uniqueServers.length;
|
|
1439
|
-
const count = Math.max(0, Number(subagentCount) || 0);
|
|
1440
|
-
const triggered = connectedServerCount > minServers && count > 0;
|
|
1441
|
-
|
|
1442
|
-
if (!triggered) {
|
|
1443
|
-
return {
|
|
1444
|
-
status: 'pass',
|
|
1445
|
-
triggered: false,
|
|
1446
|
-
connectedServerCount,
|
|
1447
|
-
minServers,
|
|
1448
|
-
subagentCount: count,
|
|
1449
|
-
perSubagentTokensEst: 0,
|
|
1450
|
-
totalTaxTokens: 0,
|
|
1451
|
-
isEstimated: true
|
|
1452
|
-
};
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
const observedChars = Number(observedMcpInstructionsDeltaChars) || 0;
|
|
1456
|
-
const isEstimated = !(observedChars > 0);
|
|
1457
|
-
const perSubagentTokensEst =
|
|
1458
|
-
observedChars > 0 ? Math.ceil(observedChars / 4) : connectedServerCount * tokensPerServerFallback;
|
|
1459
|
-
|
|
1460
|
-
return {
|
|
1461
|
-
status: 'warn',
|
|
1462
|
-
triggered: true,
|
|
1463
|
-
connectedServerCount,
|
|
1464
|
-
minServers,
|
|
1465
|
-
subagentCount: count,
|
|
1466
|
-
perSubagentTokensEst,
|
|
1467
|
-
totalTaxTokens: perSubagentTokensEst * count,
|
|
1468
|
-
isEstimated
|
|
1469
|
-
};
|
|
1470
|
-
}
|
|
1471
|
-
|
|
1472
|
-
function estimateWeeklySavingsUsd(turn0ReclaimableTokens, nowMs) {
|
|
1473
|
-
if (!turn0ReclaimableTokens || turn0ReclaimableTokens <= 0) return 0;
|
|
1474
|
-
const rateCard = resolveModelRateCard({
|
|
1475
|
-
model: 'claude-sonnet-5-5',
|
|
1476
|
-
timestampMs: nowMs
|
|
1477
|
-
});
|
|
1478
|
-
const inputPer1M = Number(rateCard?.inputPer1M || 2.0);
|
|
1479
|
-
const cachedWeight = Number(rateCard?.cachedReadWeight || 0.05);
|
|
1480
|
-
const uncachedEquivUnits = turn0ReclaimableTokens * (10 + 500 * cachedWeight);
|
|
1481
|
-
return Number(((uncachedEquivUnits / 1_000_000) * inputPer1M).toFixed(2));
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
function formatConfigStatus(res) {
|
|
1485
|
-
return {
|
|
1486
|
-
path: String(res.path || '').replace(/\\/g, '/'),
|
|
1487
|
-
exists: Boolean(res.exists),
|
|
1488
|
-
parseOk: Boolean(res.parseOk),
|
|
1489
|
-
strictJsonValid: Boolean(res.strictJsonValid),
|
|
1490
|
-
strict_json_syntax_warning: res.strict_json_syntax_warning || null
|
|
1491
|
-
};
|
|
1492
|
-
}
|
|
1493
|
-
|
|
1494
|
-
const SECRET_ALLOW_PATTERNS = Object.freeze([
|
|
1495
|
-
{ name: 'password_flag', regex: /--password(?:=|\s+)([^\s]+)/i, captureGroup: 1 },
|
|
1496
|
-
{ name: 'bearer_token', regex: /\bBearer\s+([A-Za-z0-9._-]{8,})/i, captureGroup: 1 },
|
|
1497
|
-
{ name: 'api_key_sk', regex: /\b(sk-[A-Za-z0-9_-]{12,})\b/, captureGroup: 1 },
|
|
1498
|
-
{ name: 'google_api_key', regex: /\b(AIza[0-9A-Za-z_-]{20,})\b/, captureGroup: 1 },
|
|
1499
|
-
{ name: 'github_pat', regex: /\b((?:ghp_|gho_|github_pat_)[A-Za-z0-9_]{16,})\b/, captureGroup: 1 },
|
|
1500
|
-
{ name: 'url_credentials', regex: /[a-z][a-z0-9+.-]*:\/\/[^:\s/]+:([^@\s/]+)@/i, captureGroup: 1 }
|
|
1501
|
-
]);
|
|
1502
|
-
|
|
1503
|
-
const RETIRED_MODELS_SPEC = Object.freeze({
|
|
1504
|
-
'gemini-3.8-flash': { sunsetUtc: '2026-11-30T00:00:00Z', replacement: 'gemini-4-hydrogen' },
|
|
1505
|
-
'gemini-4-argon': { sunsetUtc: '2026-11-30T00:00:00Z', replacement: 'gemini-4-hydrogen' },
|
|
1506
|
-
'claude-opus-4-6': { sunsetUtc: '2026-11-18T00:00:00Z', replacement: 'claude-opus-5-5' },
|
|
1507
|
-
'claude-sonnet-4-6': { sunsetUtc: '2026-11-18T00:00:00Z', replacement: 'claude-sonnet-5-5' },
|
|
1508
|
-
'gpt-oss-120b': { sunsetUtc: '2026-11-18T00:00:00Z', replacement: 'gemini-4-hydrogen' }
|
|
1509
|
-
});
|
|
1510
|
-
|
|
1511
|
-
function isPlaceholderSecretValue(val) {
|
|
1512
|
-
const s = String(val || '').trim();
|
|
1513
|
-
if (!s) return true;
|
|
1514
|
-
if (/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/.test(s)) return true;
|
|
1515
|
-
if (/^<[A-Za-z0-9_-]+>$/.test(s)) return true;
|
|
1516
|
-
if (/^\*{3,}$/.test(s)) return true;
|
|
1517
|
-
return false;
|
|
1518
|
-
}
|
|
1519
|
-
|
|
1520
|
-
function collectStrictJsonLints(entries = []) {
|
|
1521
|
-
const warnings = [];
|
|
1522
|
-
const lints = [];
|
|
1523
|
-
for (const entry of entries) {
|
|
1524
|
-
const res = entry?.res;
|
|
1525
|
-
if (!res?.exists || !res?.parseOk || !res?.strict_json_syntax_warning) continue;
|
|
1526
|
-
const file = String(res.path || '').replace(/\\/g, '/');
|
|
1527
|
-
warnings.push({ file, warning: res.strict_json_syntax_warning });
|
|
1528
|
-
lints.push({
|
|
1529
|
-
ruleId: 'BO-CFG-01',
|
|
1530
|
-
severity: 'warn',
|
|
1531
|
-
harness: 'claude-code',
|
|
1532
|
-
file,
|
|
1533
|
-
message: res.strict_json_syntax_warning,
|
|
1534
|
-
remediation: res.strict_json_syntax_warning
|
|
1535
|
-
});
|
|
1536
|
-
}
|
|
1537
|
-
return {
|
|
1538
|
-
status: warnings.length > 0 ? 'warn' : 'pass',
|
|
1539
|
-
warnings,
|
|
1540
|
-
lints
|
|
1541
|
-
};
|
|
1542
|
-
}
|
|
1543
|
-
|
|
1544
|
-
function auditMisplacedChromeKey(settingsEntries = []) {
|
|
1545
|
-
const misplaced = [];
|
|
1546
|
-
const lints = [];
|
|
1547
|
-
for (const entry of settingsEntries) {
|
|
1548
|
-
const doc = entry?.doc;
|
|
1549
|
-
if (!doc?.parseOk || !doc.parsed || typeof doc.parsed !== 'object') continue;
|
|
1550
|
-
if (!Object.prototype.hasOwnProperty.call(doc.parsed, 'claudeInChromeDefaultEnabled')) continue;
|
|
1551
|
-
const file = String(doc.path || '').replace(/\\/g, '/');
|
|
1552
|
-
const label = entry.label || file;
|
|
1553
|
-
misplaced.push({ file, label });
|
|
1554
|
-
lints.push({
|
|
1555
|
-
ruleId: 'BO-CFG-02',
|
|
1556
|
-
severity: 'warn',
|
|
1557
|
-
harness: 'claude-code',
|
|
1558
|
-
file,
|
|
1559
|
-
message: `Misplaced key: claudeInChromeDefaultEnabled in ${label} is ignored by Claude Code. Move to ~/.claude.json or launch with --no-chrome.`,
|
|
1560
|
-
remediation: 'Move claudeInChromeDefaultEnabled to ~/.claude.json or launch with --no-chrome.'
|
|
1561
|
-
});
|
|
1562
|
-
}
|
|
1563
|
-
return {
|
|
1564
|
-
status: misplaced.length > 0 ? 'warn' : 'pass',
|
|
1565
|
-
misplacedFiles: misplaced.map((x) => x.file),
|
|
1566
|
-
lints
|
|
1567
|
-
};
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
function resolveGitDir(cwd) {
|
|
1571
|
-
const repoDir = path.resolve(cwd || process.cwd());
|
|
1572
|
-
const dotGit = path.join(repoDir, '.git');
|
|
1573
|
-
if (!fs.existsSync(dotGit)) return null;
|
|
1574
|
-
try {
|
|
1575
|
-
const st = fs.statSync(dotGit);
|
|
1576
|
-
if (st.isDirectory()) return dotGit;
|
|
1577
|
-
if (st.isFile()) {
|
|
1578
|
-
const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/im);
|
|
1579
|
-
if (m && m[1]) {
|
|
1580
|
-
const target = m[1].trim();
|
|
1581
|
-
return path.isAbsolute(target) ? target : path.resolve(repoDir, target);
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
} catch {
|
|
1585
|
-
// ignore: unreadable .git pointer falls back to .gitignore check only
|
|
1586
|
-
}
|
|
1587
|
-
return null;
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
function hasSettingsLocalIgnoreEntry(ignoreFilePath) {
|
|
1591
|
-
if (!ignoreFilePath || !fs.existsSync(ignoreFilePath)) return false;
|
|
1592
|
-
let raw = '';
|
|
1593
|
-
try {
|
|
1594
|
-
raw = fs.readFileSync(ignoreFilePath, 'utf8');
|
|
1595
|
-
} catch {
|
|
1596
|
-
return false; // ignore: unreadable ignore file
|
|
1597
|
-
}
|
|
1598
|
-
for (const rawLine of raw.split(/\r?\n/)) {
|
|
1599
|
-
const line = rawLine.trim();
|
|
1600
|
-
if (!line || line.startsWith('#') || line.startsWith('!')) continue;
|
|
1601
|
-
const norm = line.replace(/^\/+/, '').replace(/\/+$/, '');
|
|
1602
|
-
if (
|
|
1603
|
-
norm === 'settings.local.json' ||
|
|
1604
|
-
norm === '.claude/settings.local.json' ||
|
|
1605
|
-
norm === '.claude/*.local.json' ||
|
|
1606
|
-
norm === '*.local.json' ||
|
|
1607
|
-
norm === '.claude' ||
|
|
1608
|
-
norm === '.claude/*' ||
|
|
1609
|
-
norm === '**/.claude/settings.local.json' ||
|
|
1610
|
-
norm === '**/settings.local.json'
|
|
1611
|
-
) {
|
|
1612
|
-
return true;
|
|
1613
|
-
}
|
|
1614
|
-
}
|
|
1615
|
-
return false;
|
|
1616
|
-
}
|
|
1617
|
-
|
|
1618
|
-
function isSettingsLocalGitignored(cwd) {
|
|
1619
|
-
if (hasSettingsLocalIgnoreEntry(path.join(cwd, '.gitignore'))) return true;
|
|
1620
|
-
const gitDir = resolveGitDir(cwd);
|
|
1621
|
-
if (gitDir && hasSettingsLocalIgnoreEntry(path.join(gitDir, 'info', 'exclude'))) {
|
|
1622
|
-
return true;
|
|
1623
|
-
}
|
|
1624
|
-
return false;
|
|
1625
|
-
}
|
|
1626
|
-
|
|
1627
|
-
function auditLocalSettingsSecrets(projectLocalSettings, cwd) {
|
|
1628
|
-
const allowRules = Array.isArray(projectLocalSettings?.parsed?.permissions?.allow)
|
|
1629
|
-
? projectLocalSettings.parsed.permissions.allow
|
|
1630
|
-
: [];
|
|
1631
|
-
const matches = [];
|
|
1632
|
-
|
|
1633
|
-
for (let i = 0; i < allowRules.length; i++) {
|
|
1634
|
-
const rule = allowRules[i];
|
|
1635
|
-
if (typeof rule !== 'string' || !rule) continue;
|
|
1636
|
-
for (const pat of SECRET_ALLOW_PATTERNS) {
|
|
1637
|
-
const m = rule.match(pat.regex);
|
|
1638
|
-
if (!m) continue;
|
|
1639
|
-
const captured = m[pat.captureGroup] || '';
|
|
1640
|
-
if (isPlaceholderSecretValue(captured)) continue;
|
|
1641
|
-
matches.push({
|
|
1642
|
-
ruleIndex: i,
|
|
1643
|
-
patternName: pat.name,
|
|
1644
|
-
preview: '[redacted]'
|
|
1645
|
-
});
|
|
1646
|
-
}
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
const gitignored = isSettingsLocalGitignored(cwd);
|
|
1650
|
-
const missingGitignore = Boolean(projectLocalSettings?.exists && allowRules.length > 0 && !gitignored);
|
|
1651
|
-
const status = matches.length > 0 || missingGitignore ? 'warn' : 'pass';
|
|
1652
|
-
const file = String(projectLocalSettings?.path || path.join(cwd, '.claude', 'settings.local.json')).replace(/\\/g, '/');
|
|
1653
|
-
|
|
1654
|
-
const lints = [];
|
|
1655
|
-
if (status === 'warn') {
|
|
1656
|
-
const message =
|
|
1657
|
-
matches.length > 0
|
|
1658
|
-
? `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.`
|
|
1659
|
-
: `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.`;
|
|
1660
|
-
lints.push({
|
|
1661
|
-
ruleId: 'BO-SEC-08',
|
|
1662
|
-
severity: 'warn',
|
|
1663
|
-
harness: 'claude-code',
|
|
1664
|
-
file,
|
|
1665
|
-
message,
|
|
1666
|
-
remediation:
|
|
1667
|
-
matches.length > 0
|
|
1668
|
-
? '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.'
|
|
1669
|
-
: 'Run `burnoff init` or add .claude/settings.local.json to .gitignore or .git/info/exclude.'
|
|
1670
|
-
});
|
|
1671
|
-
}
|
|
1672
|
-
|
|
1673
|
-
return {
|
|
1674
|
-
status,
|
|
1675
|
-
fileExists: Boolean(projectLocalSettings?.exists),
|
|
1676
|
-
allowRuleCount: allowRules.length,
|
|
1677
|
-
secretMatchCount: matches.length,
|
|
1678
|
-
matches,
|
|
1679
|
-
gitignored,
|
|
1680
|
-
lints
|
|
1681
|
-
};
|
|
1682
|
-
}
|
|
1683
|
-
|
|
1684
|
-
function normalizeRetiredModelCandidate(raw) {
|
|
1685
|
-
let s = String(raw || '').trim().toLowerCase();
|
|
1686
|
-
if (!s) return '';
|
|
1687
|
-
s = s.replace(/^claude-(opus|sonnet|haiku)-4\.6/, 'claude-$1-4-6');
|
|
1688
|
-
s = s.replace(/^gemini-3-8-flash/, 'gemini-3.8-flash');
|
|
1689
|
-
let prev = '';
|
|
1690
|
-
while (s !== prev) {
|
|
1691
|
-
prev = s;
|
|
1692
|
-
s = s.replace(/-(?:\d{8}|low|medium|med|high|xhigh|extra-high|tiered-high|tiered-medium|tiered-low)$/, '');
|
|
1693
|
-
}
|
|
1694
|
-
return s;
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
function auditRetiredModelsAndDeprecatedFlags({
|
|
1698
|
-
cwd,
|
|
1699
|
-
env = process.env,
|
|
1700
|
-
settingsLayers = [],
|
|
1701
|
-
nowMs = Date.now()
|
|
1702
|
-
} = {}) {
|
|
1703
|
-
const findings = [];
|
|
1704
|
-
const lints = [];
|
|
1705
|
-
const seenKeys = new Set();
|
|
1706
|
-
|
|
1707
|
-
const addModelFinding = (rawModel, source) => {
|
|
1708
|
-
const normalized = normalizeRetiredModelCandidate(rawModel);
|
|
1709
|
-
const spec = RETIRED_MODELS_SPEC[normalized];
|
|
1710
|
-
if (!spec) return;
|
|
1711
|
-
const dedupeKey = `model:${normalized}:${source}`;
|
|
1712
|
-
if (seenKeys.has(dedupeKey)) return;
|
|
1713
|
-
seenKeys.add(dedupeKey);
|
|
1714
|
-
|
|
1715
|
-
const sunsetMs = Date.parse(spec.sunsetUtc);
|
|
1716
|
-
const retired = Number.isFinite(sunsetMs) && nowMs >= sunsetMs;
|
|
1717
|
-
const severity = retired ? 'error' : 'warn';
|
|
1718
|
-
const sunsetDate = spec.sunsetUtc.slice(0, 10);
|
|
1719
|
-
const message = `Deprecated / Retired Model or Flag: Replace retired model ${rawModel} (sunset ${sunsetDate}) with ${spec.replacement} (found in ${source}).`;
|
|
1720
|
-
findings.push({
|
|
1721
|
-
kind: 'retired_model',
|
|
1722
|
-
modelId: normalized,
|
|
1723
|
-
rawModel: String(rawModel),
|
|
1724
|
-
sunsetUtc: spec.sunsetUtc,
|
|
1725
|
-
replacement: spec.replacement,
|
|
1726
|
-
severity,
|
|
1727
|
-
source
|
|
1728
|
-
});
|
|
1729
|
-
lints.push({
|
|
1730
|
-
ruleId: 'BO-CFG-09',
|
|
1731
|
-
severity,
|
|
1732
|
-
harness: 'claude-code',
|
|
1733
|
-
file: source,
|
|
1734
|
-
message,
|
|
1735
|
-
remediation: `Migrate ${rawModel} to ${spec.replacement} before ${sunsetDate}.`
|
|
1736
|
-
});
|
|
1737
|
-
};
|
|
1738
|
-
|
|
1739
|
-
for (const layerEntry of settingsLayers) {
|
|
1740
|
-
const doc = layerEntry?.doc?.parsed;
|
|
1741
|
-
const source = layerEntry?.label || layerEntry?.doc?.path || 'settings.json';
|
|
1742
|
-
if (!doc || typeof doc !== 'object') continue;
|
|
1743
|
-
for (const k of ['model', 'defaultModel']) {
|
|
1744
|
-
if (typeof doc[k] === 'string' && doc[k].trim()) {
|
|
1745
|
-
addModelFinding(doc[k].trim(), source);
|
|
1746
|
-
}
|
|
1747
|
-
}
|
|
1748
|
-
if (doc.env && typeof doc.env === 'object') {
|
|
1749
|
-
for (const ek of [
|
|
1750
|
-
'ANTHROPIC_MODEL',
|
|
1751
|
-
'CLAUDE_MODEL',
|
|
1752
|
-
'ANTHROPIC_DEFAULT_OPUS_MODEL',
|
|
1753
|
-
'ANTHROPIC_DEFAULT_SONNET_MODEL',
|
|
1754
|
-
'ANTHROPIC_DEFAULT_HAIKU_MODEL'
|
|
1755
|
-
]) {
|
|
1756
|
-
if (typeof doc.env[ek] === 'string' && doc.env[ek].trim()) {
|
|
1757
|
-
addModelFinding(doc.env[ek].trim(), `${source}#env.${ek}`);
|
|
1758
|
-
}
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
if (doc.disableArtifact === true) {
|
|
1762
|
-
const dedupeKey = `flag:disableArtifact:${source}`;
|
|
1763
|
-
if (!seenKeys.has(dedupeKey)) {
|
|
1764
|
-
seenKeys.add(dedupeKey);
|
|
1765
|
-
findings.push({
|
|
1766
|
-
kind: 'deprecated_flag',
|
|
1767
|
-
flag: 'disableArtifact',
|
|
1768
|
-
severity: 'warn',
|
|
1769
|
-
source
|
|
1770
|
-
});
|
|
1771
|
-
lints.push({
|
|
1772
|
-
ruleId: 'BO-CFG-09',
|
|
1773
|
-
severity: 'warn',
|
|
1774
|
-
harness: 'claude-code',
|
|
1775
|
-
file: source,
|
|
1776
|
-
message: `Deprecated / Retired Model or Flag: Migrate deprecated "disableArtifact": true in ${source} to "enableArtifact": false or --disallowedTools Artifact.`,
|
|
1777
|
-
remediation: 'Replace "disableArtifact": true with "enableArtifact": false or pass --disallowedTools Artifact.'
|
|
1778
|
-
});
|
|
1779
|
-
}
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
for (const ek of ['ANTHROPIC_MODEL', 'CLAUDE_MODEL', 'GEMINI_MODEL']) {
|
|
1784
|
-
if (env && typeof env[ek] === 'string' && env[ek].trim()) {
|
|
1785
|
-
addModelFinding(env[ek].trim(), `env:${ek}`);
|
|
1786
|
-
}
|
|
1787
|
-
}
|
|
1788
|
-
|
|
1789
|
-
const pkg = parseJsoncReadOnly(path.join(cwd, 'package.json'));
|
|
1790
|
-
if (pkg.parseOk && pkg.parsed && typeof pkg.parsed === 'object' && pkg.parsed.scripts && typeof pkg.parsed.scripts === 'object') {
|
|
1791
|
-
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;
|
|
1792
|
-
for (const [scriptName, scriptCmd] of Object.entries(pkg.parsed.scripts)) {
|
|
1793
|
-
if (typeof scriptCmd !== 'string') continue;
|
|
1794
|
-
for (const m of scriptCmd.matchAll(retiredPattern)) {
|
|
1795
|
-
addModelFinding(m[0], `package.json#scripts.${scriptName}`);
|
|
1796
|
-
}
|
|
1797
|
-
if (/\bclaude\b[^\n]*\s--tools(?:\s|=|$)/.test(scriptCmd)) {
|
|
1798
|
-
const source = `package.json#scripts.${scriptName}`;
|
|
1799
|
-
const dedupeKey = `flag:--tools:${source}`;
|
|
1800
|
-
if (!seenKeys.has(dedupeKey)) {
|
|
1801
|
-
seenKeys.add(dedupeKey);
|
|
1802
|
-
findings.push({
|
|
1803
|
-
kind: 'forbidden_flag',
|
|
1804
|
-
flag: '--tools',
|
|
1805
|
-
severity: 'warn',
|
|
1806
|
-
source
|
|
1807
|
-
});
|
|
1808
|
-
lints.push({
|
|
1809
|
-
ruleId: 'BO-CFG-09',
|
|
1810
|
-
severity: 'warn',
|
|
1811
|
-
harness: 'claude-code',
|
|
1812
|
-
file: source,
|
|
1813
|
-
message: `Deprecated / Retired Model or Flag: Never use strict allowlist --tools in ${source}; use --disallowedTools Artifact instead.`,
|
|
1814
|
-
remediation: 'Replace --tools with --disallowedTools Artifact.'
|
|
1815
|
-
});
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
}
|
|
1820
|
-
|
|
1821
|
-
const hasError = lints.some((l) => l.severity === 'error');
|
|
1822
|
-
return {
|
|
1823
|
-
status: lints.length > 0 ? (hasError ? 'error' : 'warn') : 'pass',
|
|
1824
|
-
findings,
|
|
1825
|
-
lints
|
|
1826
|
-
};
|
|
1827
|
-
}
|
|
1828
|
-
|
|
1829
|
-
/**
|
|
1830
|
-
* Audits Claude Code `idleCompaction` (~54m idle) vs `autoCompactEnabled` ROI tradeoffs,
|
|
1831
|
-
* gating `idleCompaction` checks strictly on `claudeCodeVersion >= 2.1.290`.
|
|
1832
|
-
*/
|
|
1833
|
-
export function auditIdleCompactionConfig({
|
|
1834
|
-
settingsLayers = [],
|
|
1835
|
-
env = {},
|
|
1836
|
-
claudeCodeVersion = null,
|
|
1837
|
-
observedModels = [],
|
|
1838
|
-
maxObservedPrefixTokens = null
|
|
1839
|
-
} = {}) {
|
|
1840
|
-
let idleCompaction = null;
|
|
1841
|
-
let idleCompactionSource = null;
|
|
1842
|
-
let autoCompactEnabled = null;
|
|
1843
|
-
let autoCompactSource = null;
|
|
1844
|
-
let envMinTokensRaw = env?.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS;
|
|
1845
|
-
const configuredModels = [];
|
|
1846
|
-
|
|
1847
|
-
for (const layerEntry of settingsLayers) {
|
|
1848
|
-
const doc = layerEntry?.doc?.parsed;
|
|
1849
|
-
const source = layerEntry?.label || layerEntry?.doc?.path || 'settings.json';
|
|
1850
|
-
if (!doc || typeof doc !== 'object') continue;
|
|
1851
|
-
if (typeof doc.idleCompaction === 'boolean') {
|
|
1852
|
-
idleCompaction = doc.idleCompaction;
|
|
1853
|
-
idleCompactionSource = source;
|
|
1854
|
-
}
|
|
1855
|
-
if (typeof doc.autoCompactEnabled === 'boolean') {
|
|
1856
|
-
autoCompactEnabled = doc.autoCompactEnabled;
|
|
1857
|
-
autoCompactSource = source;
|
|
1858
|
-
}
|
|
1859
|
-
if (typeof doc.model === 'string' && doc.model.trim()) configuredModels.push(doc.model.trim());
|
|
1860
|
-
if (typeof doc.defaultModel === 'string' && doc.defaultModel.trim()) configuredModels.push(doc.defaultModel.trim());
|
|
1861
|
-
if (doc.env && typeof doc.env === 'object') {
|
|
1862
|
-
if (doc.env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS !== undefined) {
|
|
1863
|
-
envMinTokensRaw = doc.env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS;
|
|
1864
|
-
}
|
|
1865
|
-
for (const mk of ['ANTHROPIC_MODEL', 'CLAUDE_MODEL']) {
|
|
1866
|
-
if (typeof doc.env[mk] === 'string' && doc.env[mk].trim()) configuredModels.push(doc.env[mk].trim());
|
|
1867
|
-
}
|
|
1868
|
-
}
|
|
1869
|
-
}
|
|
1870
|
-
if (env?.ANTHROPIC_MODEL) configuredModels.push(String(env.ANTHROPIC_MODEL).trim());
|
|
1871
|
-
if (env?.CLAUDE_MODEL) configuredModels.push(String(env.CLAUDE_MODEL).trim());
|
|
1872
|
-
|
|
1873
|
-
const parsedMinTok = Number(envMinTokensRaw);
|
|
1874
|
-
const idleCompactMinTokens =
|
|
1875
|
-
Number.isFinite(parsedMinTok) && parsedMinTok > 0
|
|
1876
|
-
? Math.round(parsedMinTok)
|
|
1877
|
-
: DEFAULT_IDLE_COMPACT_MIN_TOKENS;
|
|
1878
|
-
|
|
1879
|
-
const versionSupported = Boolean(
|
|
1880
|
-
claudeCodeVersion && compareSemver(String(claudeCodeVersion), IDLE_COMPACTION_MIN_VERSION) >= 0
|
|
1881
|
-
);
|
|
1882
|
-
const allModels = [...configuredModels, ...(Array.isArray(observedModels) ? observedModels : [])];
|
|
1883
|
-
const claude55Active = allModels.some((m) => /claude-(?:opus|sonnet)-5[.-]5/i.test(String(m || '')));
|
|
1884
|
-
|
|
1885
|
-
if (autoCompactEnabled === false) {
|
|
1886
|
-
const file = autoCompactSource || '~/.claude/settings.json';
|
|
1887
|
-
const message =
|
|
1888
|
-
'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.';
|
|
1889
|
-
return {
|
|
1890
|
-
status: 'warn',
|
|
1891
|
-
versionSupported,
|
|
1892
|
-
claudeCodeVersion: claudeCodeVersion || null,
|
|
1893
|
-
idleCompaction,
|
|
1894
|
-
autoCompactEnabled,
|
|
1895
|
-
idleCompactMinTokens,
|
|
1896
|
-
claude55Active,
|
|
1897
|
-
idleCompactionAlert: false,
|
|
1898
|
-
coachingMode: 'restore_auto_compact_use_surgical_idle_disable',
|
|
1899
|
-
coachingNote: message,
|
|
1900
|
-
fix: { autoCompactEnabled: true, idleCompaction: false },
|
|
1901
|
-
lints: [
|
|
1902
|
-
{
|
|
1903
|
-
ruleId: 'BO-CFG-10',
|
|
1904
|
-
severity: 'warn',
|
|
1905
|
-
harness: 'claude-code',
|
|
1906
|
-
file,
|
|
1907
|
-
message,
|
|
1908
|
-
remediation: 'Set "autoCompactEnabled": true and use "idleCompaction": false surgically instead.'
|
|
1909
|
-
}
|
|
1910
|
-
]
|
|
1911
|
-
};
|
|
1912
|
-
}
|
|
1913
|
-
|
|
1914
|
-
if (!versionSupported) {
|
|
1915
|
-
return {
|
|
1916
|
-
status: 'pass',
|
|
1917
|
-
versionSupported: false,
|
|
1918
|
-
claudeCodeVersion: claudeCodeVersion || null,
|
|
1919
|
-
idleCompaction,
|
|
1920
|
-
autoCompactEnabled,
|
|
1921
|
-
idleCompactMinTokens,
|
|
1922
|
-
claude55Active,
|
|
1923
|
-
idleCompactionAlert: false,
|
|
1924
|
-
coachingMode: 'unsupported_version',
|
|
1925
|
-
coachingNote: null,
|
|
1926
|
-
fix: null,
|
|
1927
|
-
lints: []
|
|
1928
|
-
};
|
|
1929
|
-
}
|
|
1930
|
-
|
|
1931
|
-
if (idleCompaction === false) {
|
|
1932
|
-
return {
|
|
1933
|
-
status: 'pass',
|
|
1934
|
-
versionSupported: true,
|
|
1935
|
-
claudeCodeVersion,
|
|
1936
|
-
idleCompaction: false,
|
|
1937
|
-
autoCompactEnabled,
|
|
1938
|
-
idleCompactMinTokens,
|
|
1939
|
-
claude55Active,
|
|
1940
|
-
idleCompactionAlert: false,
|
|
1941
|
-
coachingMode: 'surgical_idle_disabled_overflow_protected',
|
|
1942
|
-
coachingNote: 'Surgical "idleCompaction": false preserves reasoning nuance past 54m idle while keeping autoCompactEnabled active.',
|
|
1943
|
-
fix: null,
|
|
1944
|
-
lints: []
|
|
1945
|
-
};
|
|
1946
|
-
}
|
|
1947
|
-
|
|
1948
|
-
const hasLargePrefix = Number.isFinite(maxObservedPrefixTokens) && maxObservedPrefixTokens >= idleCompactMinTokens;
|
|
1949
|
-
const loweredThreshold = idleCompactMinTokens < DEFAULT_IDLE_COMPACT_MIN_TOKENS;
|
|
1950
|
-
const triggerRoiAlert = Boolean(claude55Active || loweredThreshold || hasLargePrefix);
|
|
1951
|
-
|
|
1952
|
-
if (triggerRoiAlert) {
|
|
1953
|
-
const coachingMode = claude55Active ? 'claude55_compact_miss_backfire_risk' : 'idle_compaction_roi_tradeoff';
|
|
1954
|
-
const file = idleCompactionSource || '~/.claude/settings.json';
|
|
1955
|
-
const message = claude55Active
|
|
1956
|
-
? `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.`
|
|
1957
|
-
: `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.`;
|
|
1958
|
-
return {
|
|
1959
|
-
status: 'warn',
|
|
1960
|
-
versionSupported: true,
|
|
1961
|
-
claudeCodeVersion,
|
|
1962
|
-
idleCompaction,
|
|
1963
|
-
autoCompactEnabled,
|
|
1964
|
-
idleCompactMinTokens,
|
|
1965
|
-
claude55Active,
|
|
1966
|
-
idleCompactionAlert: true,
|
|
1967
|
-
coachingMode,
|
|
1968
|
-
coachingNote: message,
|
|
1969
|
-
fix: { idleCompaction: false, autoCompactEnabled: true },
|
|
1970
|
-
lints: [
|
|
1971
|
-
{
|
|
1972
|
-
ruleId: 'BO-CFG-10',
|
|
1973
|
-
severity: 'warn',
|
|
1974
|
-
harness: 'claude-code',
|
|
1975
|
-
file,
|
|
1976
|
-
message,
|
|
1977
|
-
remediation: 'Set "idleCompaction": false surgically in settings.json while keeping "autoCompactEnabled": true.'
|
|
1978
|
-
}
|
|
1979
|
-
]
|
|
1980
|
-
};
|
|
1981
|
-
}
|
|
1982
|
-
|
|
1983
|
-
return {
|
|
1984
|
-
status: 'info',
|
|
1985
|
-
versionSupported: true,
|
|
1986
|
-
claudeCodeVersion,
|
|
1987
|
-
idleCompaction,
|
|
1988
|
-
autoCompactEnabled,
|
|
1989
|
-
idleCompactMinTokens,
|
|
1990
|
-
claude55Active,
|
|
1991
|
-
idleCompactionAlert: false,
|
|
1992
|
-
coachingMode: 'default_idle_compaction_active',
|
|
1993
|
-
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.`,
|
|
1994
|
-
fix: null,
|
|
1995
|
-
lints: []
|
|
1996
|
-
};
|
|
1997
|
-
}
|
|
1998
|
-
|
|
1999
|
-
const VOLATILE_NEGATION_RE =
|
|
2000
|
-
/\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;
|
|
2001
|
-
const VOLATILE_TEMPLATE_RE =
|
|
2002
|
-
/(\{\{\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;
|
|
2003
|
-
const VOLATILE_INSTRUCTION_RE =
|
|
2004
|
-
/\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;
|
|
2005
|
-
const SESSION_START_VOLATILE_CMD_RE =
|
|
2006
|
-
/\b(?:date\s+(?:\+|-[uIr])|Get-Date\b|uuidgen\b|New-Guid\b|Date\.now\(\)|randomUUID\(\))/i;
|
|
2007
|
-
|
|
2008
|
-
/**
|
|
2009
|
-
* Scans markdown rule text (outside fenced code blocks) for volatile timestamp/UUID
|
|
2010
|
-
* prompt-prefix patterns that invalidate KV prefix caches every turn.
|
|
2011
|
-
*/
|
|
2012
|
-
export function scanVolatilePromptPatterns(markdown = '') {
|
|
2013
|
-
const lines = String(markdown || '').split(/\r?\n/);
|
|
2014
|
-
const findings = [];
|
|
2015
|
-
let inFence = false;
|
|
2016
|
-
|
|
2017
|
-
for (let i = 0; i < lines.length; i++) {
|
|
2018
|
-
const line = lines[i];
|
|
2019
|
-
if (/^\s*(?:```|~~~)/.test(line)) {
|
|
2020
|
-
inFence = !inFence;
|
|
2021
|
-
continue;
|
|
2022
|
-
}
|
|
2023
|
-
if (inFence) continue;
|
|
2024
|
-
const trimmed = line.trim();
|
|
2025
|
-
if (!trimmed) continue;
|
|
2026
|
-
if (VOLATILE_NEGATION_RE.test(trimmed)) continue;
|
|
2027
|
-
|
|
2028
|
-
if (VOLATILE_TEMPLATE_RE.test(trimmed)) {
|
|
2029
|
-
findings.push({
|
|
2030
|
-
lineNumber: i + 1,
|
|
2031
|
-
patternKind: 'volatile_template',
|
|
2032
|
-
snippet: trimmed.slice(0, 140)
|
|
2033
|
-
});
|
|
2034
|
-
continue;
|
|
2035
|
-
}
|
|
2036
|
-
if (VOLATILE_INSTRUCTION_RE.test(trimmed)) {
|
|
2037
|
-
findings.push({
|
|
2038
|
-
lineNumber: i + 1,
|
|
2039
|
-
patternKind: 'volatile_instruction',
|
|
2040
|
-
snippet: trimmed.slice(0, 140)
|
|
2041
|
-
});
|
|
2042
|
-
}
|
|
2043
|
-
}
|
|
2044
|
-
|
|
2045
|
-
return {
|
|
2046
|
-
matched: findings.length > 0,
|
|
2047
|
-
findings
|
|
2048
|
-
};
|
|
2049
|
-
}
|
|
2050
|
-
|
|
2051
|
-
/**
|
|
2052
|
-
* BO-CFG-11: Audits active always-on rules files and `SessionStart` hook commands
|
|
2053
|
-
* for volatile timestamps, dates, or UUIDs that bust the token-0 prompt prefix.
|
|
2054
|
-
*/
|
|
2055
|
-
export function auditVolatilePromptPrefix({
|
|
2056
|
-
ruleFilePaths = [],
|
|
2057
|
-
settingsLayers = [],
|
|
2058
|
-
harness = 'claude-code'
|
|
2059
|
-
} = {}) {
|
|
2060
|
-
const seen = new Set();
|
|
2061
|
-
const findings = [];
|
|
2062
|
-
const lints = [];
|
|
2063
|
-
const remediation =
|
|
2064
|
-
'Remove dynamic timestamps/UUIDs from static rules or SessionStart hooks; append turn-specific metadata at the tail of user turns if needed.';
|
|
2065
|
-
|
|
2066
|
-
for (const fp of ruleFilePaths) {
|
|
2067
|
-
if (!fp || !fs.existsSync(fp)) continue;
|
|
2068
|
-
let dedupeKey = canonicalizePath(fp);
|
|
2069
|
-
try {
|
|
2070
|
-
dedupeKey = canonicalizePath(fs.realpathSync(fp));
|
|
2071
|
-
} catch {
|
|
2072
|
-
// ignore: fallback to canonicalized path when realpath fails
|
|
2073
|
-
}
|
|
2074
|
-
if (seen.has(dedupeKey)) continue;
|
|
2075
|
-
seen.add(dedupeKey);
|
|
2076
|
-
|
|
2077
|
-
try {
|
|
2078
|
-
const text = fs.readFileSync(fp, 'utf8');
|
|
2079
|
-
if (harness === 'antigravity') {
|
|
2080
|
-
const triggerMode = parseRuleTriggerMode(text);
|
|
2081
|
-
if (triggerMode === 'model_decision' || triggerMode === 'manual') continue;
|
|
2082
|
-
}
|
|
2083
|
-
const scan = scanVolatilePromptPatterns(text);
|
|
2084
|
-
if (scan.matched) {
|
|
2085
|
-
const normFile = String(fp).replace(/\\/g, '/');
|
|
2086
|
-
const first = scan.findings[0];
|
|
2087
|
-
findings.push({
|
|
2088
|
-
file: normFile,
|
|
2089
|
-
sourceType: 'rules_file',
|
|
2090
|
-
matches: scan.findings
|
|
2091
|
-
});
|
|
2092
|
-
lints.push({
|
|
2093
|
-
ruleId: 'BO-CFG-11',
|
|
2094
|
-
severity: 'warn',
|
|
2095
|
-
harness,
|
|
2096
|
-
file: normFile,
|
|
2097
|
-
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.`,
|
|
2098
|
-
remediation
|
|
2099
|
-
});
|
|
2100
|
-
}
|
|
2101
|
-
} catch {
|
|
2102
|
-
// ignore: unreadable rules markdown file
|
|
2103
|
-
}
|
|
2104
|
-
}
|
|
2105
|
-
|
|
2106
|
-
for (const layerEntry of settingsLayers) {
|
|
2107
|
-
const doc = layerEntry?.doc?.parsed;
|
|
2108
|
-
if (!doc || typeof doc !== 'object') continue;
|
|
2109
|
-
const fileLabel = String(layerEntry?.label || layerEntry?.doc?.path || 'settings.json').replace(/\\/g, '/');
|
|
2110
|
-
const sessionStartHooks = doc?.hooks?.SessionStart;
|
|
2111
|
-
if (!Array.isArray(sessionStartHooks)) continue;
|
|
2112
|
-
const matchedCmds = [];
|
|
2113
|
-
for (const entry of sessionStartHooks) {
|
|
2114
|
-
const hookList = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
|
|
2115
|
-
for (const h of hookList) {
|
|
2116
|
-
const cmd = typeof h?.command === 'string' ? h.command.trim() : '';
|
|
2117
|
-
if (cmd && SESSION_START_VOLATILE_CMD_RE.test(cmd)) {
|
|
2118
|
-
matchedCmds.push(cmd.slice(0, 140));
|
|
2119
|
-
}
|
|
2120
|
-
}
|
|
2121
|
-
}
|
|
2122
|
-
if (matchedCmds.length > 0) {
|
|
2123
|
-
findings.push({
|
|
2124
|
-
file: fileLabel,
|
|
2125
|
-
sourceType: 'session_start_hook',
|
|
2126
|
-
commands: matchedCmds
|
|
2127
|
-
});
|
|
2128
|
-
lints.push({
|
|
2129
|
-
ruleId: 'BO-CFG-11',
|
|
2130
|
-
severity: 'warn',
|
|
2131
|
-
harness,
|
|
2132
|
-
file: fileLabel,
|
|
2133
|
-
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.`,
|
|
2134
|
-
remediation
|
|
2135
|
-
});
|
|
2136
|
-
}
|
|
2137
|
-
}
|
|
2138
|
-
|
|
2139
|
-
return {
|
|
2140
|
-
status: lints.length > 0 ? 'warn' : 'pass',
|
|
2141
|
-
findings,
|
|
2142
|
-
lints
|
|
2143
|
-
};
|
|
2144
|
-
}
|
|
2145
|
-
|
|
2146
|
-
function makeMissingJsoncStub(filePath = '') {
|
|
2147
|
-
return {
|
|
2148
|
-
path: filePath,
|
|
2149
|
-
exists: false,
|
|
2150
|
-
parseOk: false,
|
|
2151
|
-
parsed: null,
|
|
2152
|
-
strictJsonValid: false,
|
|
2153
|
-
strict_json_syntax_warning: null,
|
|
2154
|
-
error: null
|
|
2155
|
-
};
|
|
2156
|
-
}
|
|
2157
110
|
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
});
|
|
2165
|
-
}
|
|
111
|
+
export const CLAUDE_WORKTREE_DEDUP_MIN_VERSION = '2.1.332';
|
|
112
|
+
export const CLAUDE_CACHE_RESUME_MIN_VERSION = '2.1.331';
|
|
113
|
+
export const CLAUDE_OMIT_CLAUDE_MD_MIN_VERSION = '2.1.271';
|
|
114
|
+
export const OMIT_CLAUDE_MD_MIN_ROOT_TOKENS = 1500;
|
|
115
|
+
export const SDK_CLI_QUOTA_MULTIPLIER_HEURISTIC = 1.8;
|
|
116
|
+
export const ANTIGRAVITY_ACP_STDIO_MANIFEST_MAX_BYTES = 16384;
|
|
2166
117
|
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
118
|
+
export {
|
|
119
|
+
RULES_THRESHOLDS,
|
|
120
|
+
LIST_CHANGED_PREFIX_THRESHOLD,
|
|
121
|
+
SUBAGENT_MCP_MIN_SERVERS,
|
|
122
|
+
DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER,
|
|
123
|
+
IDLE_COMPACTION_MIN_VERSION,
|
|
124
|
+
SKILL_DESCRIPTION_MAX_CHARS,
|
|
125
|
+
DEFAULT_IDLE_COMPACT_MIN_TOKENS,
|
|
126
|
+
COARSE_META_TOOL_MIN_SERVERS,
|
|
127
|
+
COARSE_META_TOOL_MIN_TOKENS,
|
|
128
|
+
VERIFIED_CLAUDE_FLAGS,
|
|
129
|
+
FORBIDDEN_WORKAROUND_FLAGS,
|
|
130
|
+
DEFAULT_TELEMETRY_MAX_FILES,
|
|
131
|
+
DEFAULT_TELEMETRY_MAX_BYTES,
|
|
132
|
+
RETIRED_MODELS_SPEC,
|
|
133
|
+
formatJsonCliArg,
|
|
134
|
+
validateClaudeCliCommand,
|
|
135
|
+
inspectJsoncSyntax,
|
|
136
|
+
parseJsoncString,
|
|
137
|
+
parseJsoncReadOnly,
|
|
138
|
+
countDiscreteRules,
|
|
139
|
+
detectRuleContradictions,
|
|
140
|
+
auditRulesFiles,
|
|
141
|
+
scanClaudeCustomAgentSpecs,
|
|
142
|
+
isLocalhostBaseUrl,
|
|
143
|
+
evaluateMcpProxyAndMetaToolCoaching,
|
|
144
|
+
scanMcpToolNameLengthViolations,
|
|
145
|
+
scanMcpListChangedCapabilities,
|
|
146
|
+
estimateSubagentMcpInstructionsTax,
|
|
147
|
+
auditIdleCompactionConfig,
|
|
148
|
+
scanVolatilePromptPatterns,
|
|
149
|
+
auditVolatilePromptPrefix,
|
|
150
|
+
parseSkillFrontmatter,
|
|
151
|
+
auditSkillFrontmatterLimits,
|
|
152
|
+
formatClaudeStartupAuditReport,
|
|
153
|
+
formatAntigravityStartupAuditReport,
|
|
154
|
+
formatStartupAuditReport,
|
|
155
|
+
evaluateStartupAuditCi
|
|
156
|
+
};
|
|
2188
157
|
|
|
2189
158
|
/**
|
|
2190
159
|
* Runs Turn-0 startup config, rules-count, and eager-only MCP audit for Claude Code.
|
|
@@ -2389,9 +358,13 @@ export function runClaudeStartupAudit({
|
|
|
2389
358
|
});
|
|
2390
359
|
const deprecatedModelsAndFlags = auditRetiredModelsAndDeprecatedFlags({
|
|
2391
360
|
cwd: paths.cwd,
|
|
361
|
+
homeDir: paths.homeDir,
|
|
2392
362
|
env,
|
|
2393
363
|
settingsLayers,
|
|
2394
|
-
nowMs
|
|
364
|
+
nowMs,
|
|
365
|
+
harness: 'claude-code',
|
|
366
|
+
isCustomGateway: mcpStartupTax.isCustomGateway,
|
|
367
|
+
repoOnly: isRepoOnly
|
|
2395
368
|
});
|
|
2396
369
|
const idleCompactionRoi = auditIdleCompactionConfig({
|
|
2397
370
|
settingsLayers,
|
|
@@ -2439,6 +412,16 @@ export function runClaudeStartupAudit({
|
|
|
2439
412
|
...idleCompactionRoi.lints,
|
|
2440
413
|
...volatilePrefix.lints
|
|
2441
414
|
];
|
|
415
|
+
for (const conflict of rulesBucket.contradictions || []) {
|
|
416
|
+
lints.push({
|
|
417
|
+
ruleId: 'BO-CFG-12',
|
|
418
|
+
severity: 'warn',
|
|
419
|
+
harness: 'claude-code',
|
|
420
|
+
file: conflict.file || 'CLAUDE.md',
|
|
421
|
+
message: `Rule contradiction (BO-CFG-12): conflicting directives on L${conflict.linePos} ("${conflict.textPos}") vs L${conflict.lineNeg} ("${conflict.textNeg}").`,
|
|
422
|
+
remediation: 'Resolve or delete conflicting Always/NEVER directives in rules markdown files.'
|
|
423
|
+
});
|
|
424
|
+
}
|
|
2442
425
|
if (mcpStartupTax.gateReasons.includes('ssh_forced_disable_experimental_betas')) {
|
|
2443
426
|
lints.push({
|
|
2444
427
|
ruleId: 'BO-CFG-03',
|
|
@@ -2503,6 +486,126 @@ export function runClaudeStartupAudit({
|
|
|
2503
486
|
lints.push(...deprecatedModelsAndFlags.lints);
|
|
2504
487
|
lints.push(...mcpProxyAndMetaTool.lints);
|
|
2505
488
|
|
|
489
|
+
const worktreesDirPath = path.join(paths.cwd, '.claude', 'worktrees');
|
|
490
|
+
let emittedWorktreeUpgradeWarn = false;
|
|
491
|
+
if (
|
|
492
|
+
detectedClaudeVersion &&
|
|
493
|
+
compareSemver(String(detectedClaudeVersion), CLAUDE_WORKTREE_DEDUP_MIN_VERSION) < 0 &&
|
|
494
|
+
fs.existsSync(worktreesDirPath)
|
|
495
|
+
) {
|
|
496
|
+
emittedWorktreeUpgradeWarn = true;
|
|
497
|
+
const alsoNeeds331 = compareSemver(String(detectedClaudeVersion), CLAUDE_CACHE_RESUME_MIN_VERSION) < 0;
|
|
498
|
+
lints.push({
|
|
499
|
+
ruleId: 'BO-CFG-13',
|
|
500
|
+
severity: 'warn',
|
|
501
|
+
harness: 'claude-code',
|
|
502
|
+
file: worktreesDirPath.replace(/\\/g, '/'),
|
|
503
|
+
message: `Worktree Duplicate CLAUDE.md/Rules Injection (< v${CLAUDE_WORKTREE_DEDUP_MIN_VERSION}): Claude Code v${detectedClaudeVersion} with ".claude/worktrees" re-injects CLAUDE.md and rules files on worktree transition.`,
|
|
504
|
+
remediation: alsoNeeds331
|
|
505
|
+
? `Upgrade Claude Code to >= ${CLAUDE_WORKTREE_DEDUP_MIN_VERSION} (fixes duplicate worktree context injection plus v2.1.330/v${CLAUDE_CACHE_RESUME_MIN_VERSION} Code Mode --resume cache drops, post-compaction freezes, and 30-minute MCP hangs).`
|
|
506
|
+
: `Upgrade Claude Code to >= ${CLAUDE_WORKTREE_DEDUP_MIN_VERSION}, which fixes duplicate worktree context injection.`
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
if (
|
|
511
|
+
!emittedWorktreeUpgradeWarn &&
|
|
512
|
+
detectedClaudeVersion &&
|
|
513
|
+
compareSemver(String(detectedClaudeVersion), CLAUDE_CACHE_RESUME_MIN_VERSION) < 0
|
|
514
|
+
) {
|
|
515
|
+
lints.push({
|
|
516
|
+
ruleId: 'BO-CFG-17',
|
|
517
|
+
severity: 'info',
|
|
518
|
+
harness: 'claude-code',
|
|
519
|
+
file: paths.userSettings.replace(/\\/g, '/'),
|
|
520
|
+
message: `Claude Code Upgrade Available (< v${CLAUDE_CACHE_RESUME_MIN_VERSION}): Claude Code v${detectedClaudeVersion} precedes v2.1.330/v${CLAUDE_CACHE_RESUME_MIN_VERSION} fixes for Code Mode --resume cache drops, post-compaction freezes, and 30-minute malformed MCP hangs.`,
|
|
521
|
+
remediation: `Upgrade Claude Code to >= ${CLAUDE_WORKTREE_DEDUP_MIN_VERSION} for resume cache fixes, compaction stability, and PreSkillShellCommand hook support.`
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const hasExplicitCleanupPeriod = layers.some(
|
|
526
|
+
(layer) => typeof layer?.cleanupPeriodDays === 'number' && Number.isFinite(layer.cleanupPeriodDays)
|
|
527
|
+
);
|
|
528
|
+
if (!isRepoOnly && userSettings.exists && !hasExplicitCleanupPeriod) {
|
|
529
|
+
lints.push({
|
|
530
|
+
ruleId: 'BO-CFG-14',
|
|
531
|
+
severity: 'info',
|
|
532
|
+
harness: 'claude-code',
|
|
533
|
+
file: paths.userSettings.replace(/\\/g, '/'),
|
|
534
|
+
message:
|
|
535
|
+
'Transcript Retention Window Unset (BO-CFG-14): cleanupPeriodDays is unset, so Claude Code defaults to deleting JSONL transcripts after 30 days.',
|
|
536
|
+
remediation:
|
|
537
|
+
'Set "cleanupPeriodDays" explicitly in ~/.claude/settings.json if you want longer burnoff audit history.'
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const hasTsLspPlugin = layers.some((layer) => {
|
|
542
|
+
const enabledMap =
|
|
543
|
+
layer?.enabledPlugins && typeof layer.enabledPlugins === 'object' ? layer.enabledPlugins : null;
|
|
544
|
+
if (
|
|
545
|
+
enabledMap &&
|
|
546
|
+
Object.entries(enabledMap).some(([name, val]) => Boolean(val) && /typescript-lsp/i.test(String(name)))
|
|
547
|
+
) {
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
if (Array.isArray(layer?.plugins)) {
|
|
551
|
+
return layer.plugins.some((entry) => {
|
|
552
|
+
if (typeof entry === 'string') return /typescript-lsp/i.test(entry);
|
|
553
|
+
if (entry && typeof entry === 'object') {
|
|
554
|
+
return entry.enabled !== false && /typescript-lsp/i.test(String(entry.name || entry.id || entry.plugin || ''));
|
|
555
|
+
}
|
|
556
|
+
return false;
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
return false;
|
|
560
|
+
});
|
|
561
|
+
const hasTsEditHook = layers.some((layer) => {
|
|
562
|
+
const hooksObj = layer?.hooks && typeof layer.hooks === 'object' ? layer.hooks : null;
|
|
563
|
+
if (!hooksObj) return false;
|
|
564
|
+
for (const ev of ['PreToolUse', 'PostToolUse']) {
|
|
565
|
+
const groups = Array.isArray(hooksObj[ev]) ? hooksObj[ev] : [];
|
|
566
|
+
for (const group of groups) {
|
|
567
|
+
if (!/Edit|Write/i.test(String(group?.matcher || ''))) continue;
|
|
568
|
+
const inner = Array.isArray(group?.hooks) ? group.hooks : [];
|
|
569
|
+
if (inner.some((h) => /typescript-lsp|\btsc\b/i.test(String(h?.command || '')))) {
|
|
570
|
+
return true;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return false;
|
|
575
|
+
});
|
|
576
|
+
if (hasTsLspPlugin && hasTsEditHook) {
|
|
577
|
+
lints.push({
|
|
578
|
+
ruleId: 'BO-CFG-15',
|
|
579
|
+
severity: 'info',
|
|
580
|
+
harness: 'claude-code',
|
|
581
|
+
file: paths.projectSettings.replace(/\\/g, '/'),
|
|
582
|
+
message:
|
|
583
|
+
'TypeScript LSP + Edit Hook Overlap (BO-CFG-15): both a typescript-lsp plugin and an Edit/Write tsc/LSP hook are configured. Validate on your repo, as Evil Martians (n=13 benchmark) observed a pass-rate drop when stacking plugin + edit hook.',
|
|
584
|
+
remediation:
|
|
585
|
+
'Benchmark task accuracy and token spend with the plugin alone vs edit hook alone in this repository.'
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
lints.push(...auditSkillFrontmatterLimits({ cwd: paths.cwd, harness: 'claude-code' }));
|
|
590
|
+
|
|
591
|
+
if (
|
|
592
|
+
detectedClaudeVersion &&
|
|
593
|
+
compareSemver(String(detectedClaudeVersion), CLAUDE_OMIT_CLAUDE_MD_MIN_VERSION) >= 0 &&
|
|
594
|
+
Number(rulesBucket?.totalTokensEst || 0) >= OMIT_CLAUDE_MD_MIN_ROOT_TOKENS &&
|
|
595
|
+
Array.isArray(customAgents?.omitClaudeMdCandidates) &&
|
|
596
|
+
customAgents.omitClaudeMdCandidates.length > 0
|
|
597
|
+
) {
|
|
598
|
+
const names = customAgents.omitClaudeMdCandidates.map((a) => a.name).join(', ');
|
|
599
|
+
lints.push({
|
|
600
|
+
ruleId: 'BO-CFG-18',
|
|
601
|
+
severity: 'info',
|
|
602
|
+
harness: 'claude-code',
|
|
603
|
+
file: customAgents.omitClaudeMdCandidates[0].path,
|
|
604
|
+
message: `Subagent omitClaudeMd Opportunity (BO-CFG-18): Lookup/search/log-reading agent(s) [${names}] inherit root CLAUDE.md (~${Number(rulesBucket.totalTokensEst).toLocaleString('en-US')} tokens) on spawn.`,
|
|
605
|
+
remediation: `On Claude Code >= v${CLAUDE_OMIT_CLAUDE_MD_MIN_VERSION}, add "omitClaudeMd: true" in .claude/agents/*.md frontmatter for narrow search/lookup/log subagents whose delegation prompt is self-contained (managed policies still load; built-in Explore/Plan already skip CLAUDE.md; ignored when run via --agent).`
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
|
|
2506
609
|
let issueCount = 0;
|
|
2507
610
|
let estimatedTurn0ReclaimableTokens = 0;
|
|
2508
611
|
for (const chk of [chromeDefaultEnabled, artifactTool, bundledSkillsAndWorkflows]) {
|
|
@@ -2587,179 +690,6 @@ export function runClaudeStartupAudit({
|
|
|
2587
690
|
/**
|
|
2588
691
|
* Formats `runClaudeStartupAudit()` for terminal output with zero em dashes.
|
|
2589
692
|
*/
|
|
2590
|
-
export function formatClaudeStartupAuditReport(report) {
|
|
2591
|
-
if (!report?.ok) return 'Burnoff Startup Audit failed\n';
|
|
2592
|
-
const s = report.summary || {};
|
|
2593
|
-
const c = report.claudeCode?.checks;
|
|
2594
|
-
const r = report.rulesAudit?.byHarness?.claudeCode;
|
|
2595
|
-
const lines = [
|
|
2596
|
-
`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)`
|
|
2597
|
-
];
|
|
2598
|
-
|
|
2599
|
-
if (c) {
|
|
2600
|
-
lines.push(` - ${c.mcpStartupTax.summaryLine}`);
|
|
2601
|
-
if (c.mcpStartupTax.unusedEagerServers?.length) {
|
|
2602
|
-
lines.push(
|
|
2603
|
-
` Unused eager servers (7d): ${c.mcpStartupTax.unusedEagerServers.map((x) => `${x.name} (~${x.tokensEst} tok)`).join(', ')}`
|
|
2604
|
-
);
|
|
2605
|
-
}
|
|
2606
|
-
if (c.chromeDefaultEnabled.status === 'warn') {
|
|
2607
|
-
lines.push(
|
|
2608
|
-
` - [warn] Chrome default enabled in ~/.claude.json with 0 browser calls in 7d (~${c.chromeDefaultEnabled.reclaimableTokensPerTurn} tok/turn est.)`
|
|
2609
|
-
);
|
|
2610
|
-
lines.push(` Fix: ${c.chromeDefaultEnabled.fix}`);
|
|
2611
|
-
} else {
|
|
2612
|
-
lines.push(' - [pass] Chrome default disabled (or actively used)');
|
|
2613
|
-
}
|
|
2614
|
-
if (c.artifactTool.status === 'warn') {
|
|
2615
|
-
lines.push(
|
|
2616
|
-
` - [warn] Artifact built-in tool active (${c.artifactTool.entrypoint}, 0 calls in 7d, ~${c.artifactTool.reclaimableTokensPerTurn} tok/turn est.)`
|
|
2617
|
-
);
|
|
2618
|
-
lines.push(` Note: ${c.artifactTool.oneWayLockWarning}`);
|
|
2619
|
-
if (c.artifactTool.fixes?.migrateDeprecated) {
|
|
2620
|
-
lines.push(` Fix (migrate): ${c.artifactTool.fixes.migrateDeprecated}`);
|
|
2621
|
-
}
|
|
2622
|
-
if (c.artifactTool.fixes?.neverUseArtifacts) {
|
|
2623
|
-
lines.push(` Fix (never use): ${c.artifactTool.fixes.neverUseArtifacts}`);
|
|
2624
|
-
}
|
|
2625
|
-
if (c.artifactTool.fixes?.occasionalArtifacts) {
|
|
2626
|
-
lines.push(` Fix (occasional): ${c.artifactTool.fixes.occasionalArtifacts}`);
|
|
2627
|
-
}
|
|
2628
|
-
} else {
|
|
2629
|
-
lines.push(` - [pass] Artifact tool (${c.artifactTool.entrypoint})`);
|
|
2630
|
-
}
|
|
2631
|
-
if (c.bundledSkillsAndWorkflows.status === 'warn' && c.bundledSkillsAndWorkflows.fix) {
|
|
2632
|
-
const prio = c.bundledSkillsAndWorkflows.priority === 'high' ? ' [HIGH: Anthropic SDK markers detected]' : '';
|
|
2633
|
-
lines.push(
|
|
2634
|
-
` - [warn] Bundled skills/workflows enabled${prio} (~${c.bundledSkillsAndWorkflows.reclaimableTokensPerTurn} tok/turn est.)`
|
|
2635
|
-
);
|
|
2636
|
-
lines.push(` Fix: ${c.bundledSkillsAndWorkflows.fix}`);
|
|
2637
|
-
} else {
|
|
2638
|
-
lines.push(' - [pass] Repo-local Turn-0 focus (no unverified global settings keys recommended)');
|
|
2639
|
-
}
|
|
2640
|
-
if (c.subagentMcpInstructionsTax?.triggered) {
|
|
2641
|
-
lines.push(
|
|
2642
|
-
` - [warn] Subagent mcp_instructions_delta tax (#104791): ~${c.subagentMcpInstructionsTax.perSubagentTokensEst.toLocaleString('en-US')} tok/subagent across ${c.subagentMcpInstructionsTax.subagentCount} subagents (${c.subagentMcpInstructionsTax.connectedServerCount} servers)`
|
|
2643
|
-
);
|
|
2644
|
-
}
|
|
2645
|
-
if (c.idleCompactionRoi?.status === 'warn' && c.idleCompactionRoi.coachingNote) {
|
|
2646
|
-
lines.push(` - [warn] ${c.idleCompactionRoi.coachingNote}`);
|
|
2647
|
-
} else if (c.idleCompactionRoi?.coachingMode === 'surgical_idle_disabled_overflow_protected') {
|
|
2648
|
-
lines.push(` - [pass] ${c.idleCompactionRoi.coachingNote}`);
|
|
2649
|
-
}
|
|
2650
|
-
if (c.sdkCliQuotaHeuristic?.detected && c.sdkCliQuotaHeuristic.message) {
|
|
2651
|
-
lines.push(` - [info] ${c.sdkCliQuotaHeuristic.message}`);
|
|
2652
|
-
}
|
|
2653
|
-
if (c.mcpProxyAndMetaTool?.coachingNote) {
|
|
2654
|
-
lines.push(` - [${c.mcpProxyAndMetaTool.status}] ${c.mcpProxyAndMetaTool.coachingNote}`);
|
|
2655
|
-
}
|
|
2656
|
-
}
|
|
2657
|
-
|
|
2658
|
-
if (r) {
|
|
2659
|
-
lines.push(
|
|
2660
|
-
` - Rules [${r.status}]: ${r.files.length} file(s), ${r.totalRuleCount} discrete rules, ~${r.totalTokensEst.toLocaleString('en-US')} est. tokens`
|
|
2661
|
-
);
|
|
2662
|
-
for (const adv of r.advisories || []) {
|
|
2663
|
-
lines.push(` Advisories: ${adv}`);
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
|
|
2667
|
-
if (Array.isArray(report.lints) && report.lints.length > 0) {
|
|
2668
|
-
lines.push(' Silent-Failure & Security Lints:');
|
|
2669
|
-
for (const l of report.lints) {
|
|
2670
|
-
lines.push(` - [${l.severity}] ${l.ruleId}: ${l.message}`);
|
|
2671
|
-
}
|
|
2672
|
-
}
|
|
2673
|
-
|
|
2674
|
-
return lines.join('\n') + '\n';
|
|
2675
|
-
}
|
|
2676
|
-
|
|
2677
|
-
function listMarkdownFilesInDir(dirPath) {
|
|
2678
|
-
if (!dirPath || !fs.existsSync(dirPath)) return [];
|
|
2679
|
-
try {
|
|
2680
|
-
return fs
|
|
2681
|
-
.readdirSync(dirPath, { withFileTypes: true })
|
|
2682
|
-
.filter((e) => e.isFile() && /\.md$/i.test(e.name))
|
|
2683
|
-
.map((e) => path.join(dirPath, e.name));
|
|
2684
|
-
} catch {
|
|
2685
|
-
return []; // ignore: unreadable rules directory
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
2688
|
-
|
|
2689
|
-
function parseRuleTriggerMode(markdown = '') {
|
|
2690
|
-
const m = String(markdown || '').match(/^---\s*\r?\n([\s\S]*?)\r?\n---/);
|
|
2691
|
-
if (!m) return 'always_on';
|
|
2692
|
-
const trig = m[1].match(/^\s*trigger\s*:\s*([^\r\n#]+)/im);
|
|
2693
|
-
if (!trig) return 'always_on';
|
|
2694
|
-
return trig[1].trim().toLowerCase() || 'always_on';
|
|
2695
|
-
}
|
|
2696
|
-
|
|
2697
|
-
function auditAntigravityRulesFiles(filePaths = []) {
|
|
2698
|
-
const seen = new Set();
|
|
2699
|
-
const files = [];
|
|
2700
|
-
let totalTokensEst = 0;
|
|
2701
|
-
let totalRuleCount = 0;
|
|
2702
|
-
let onDemandCount = 0;
|
|
2703
|
-
|
|
2704
|
-
for (const fp of filePaths) {
|
|
2705
|
-
if (!fp || !fs.existsSync(fp)) continue;
|
|
2706
|
-
let dedupeKey = canonicalizePath(fp);
|
|
2707
|
-
try {
|
|
2708
|
-
dedupeKey = canonicalizePath(fs.realpathSync(fp));
|
|
2709
|
-
} catch {
|
|
2710
|
-
// ignore: fallback to canonicalized path when realpath fails
|
|
2711
|
-
}
|
|
2712
|
-
if (seen.has(dedupeKey)) continue;
|
|
2713
|
-
seen.add(dedupeKey);
|
|
2714
|
-
|
|
2715
|
-
try {
|
|
2716
|
-
const text = fs.readFileSync(fp, 'utf8');
|
|
2717
|
-
const triggerMode = parseRuleTriggerMode(text);
|
|
2718
|
-
const chars = text.length;
|
|
2719
|
-
const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
|
|
2720
|
-
const ruleCount = countDiscreteRules(text);
|
|
2721
|
-
const isAlwaysOn = triggerMode !== 'model_decision' && triggerMode !== 'manual';
|
|
2722
|
-
files.push({
|
|
2723
|
-
path: String(fp).replace(/\\/g, '/'),
|
|
2724
|
-
triggerMode,
|
|
2725
|
-
alwaysOn: isAlwaysOn,
|
|
2726
|
-
chars,
|
|
2727
|
-
tokensEst,
|
|
2728
|
-
ruleCount
|
|
2729
|
-
});
|
|
2730
|
-
if (isAlwaysOn) {
|
|
2731
|
-
totalTokensEst += tokensEst;
|
|
2732
|
-
totalRuleCount += ruleCount;
|
|
2733
|
-
} else {
|
|
2734
|
-
onDemandCount += 1;
|
|
2735
|
-
}
|
|
2736
|
-
} catch {
|
|
2737
|
-
// ignore: unreadable Antigravity rule markdown
|
|
2738
|
-
}
|
|
2739
|
-
}
|
|
2740
|
-
|
|
2741
|
-
let status = 'pass';
|
|
2742
|
-
const advisories = [];
|
|
2743
|
-
if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
|
|
2744
|
-
status = 'warn';
|
|
2745
|
-
advisories.push(
|
|
2746
|
-
`IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} always-on rules); set trigger: model_decision or move domain rules into skills.`
|
|
2747
|
-
);
|
|
2748
|
-
} else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
|
|
2749
|
-
status = 'caution';
|
|
2750
|
-
advisories.push(
|
|
2751
|
-
`Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} always-on rules).`
|
|
2752
|
-
);
|
|
2753
|
-
}
|
|
2754
|
-
if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
|
|
2755
|
-
status = 'warn';
|
|
2756
|
-
advisories.push(
|
|
2757
|
-
`Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across always-on Antigravity rules).`
|
|
2758
|
-
);
|
|
2759
|
-
}
|
|
2760
|
-
|
|
2761
|
-
return { files, totalTokensEst, totalRuleCount, onDemandCount, status, advisories };
|
|
2762
|
-
}
|
|
2763
693
|
|
|
2764
694
|
/**
|
|
2765
695
|
* Runs Turn-0 startup config, rules-count, and MCP config audit for Google Antigravity.
|
|
@@ -2770,7 +700,11 @@ export function runAntigravityStartupAudit({
|
|
|
2770
700
|
hostPlatform = process.platform,
|
|
2771
701
|
nowMs = Date.now(),
|
|
2772
702
|
repoOnly = false,
|
|
2773
|
-
ci = false
|
|
703
|
+
ci = false,
|
|
704
|
+
env = process.env,
|
|
705
|
+
manifestDirs = [],
|
|
706
|
+
acpStdio = false,
|
|
707
|
+
acpAgentCommand = null
|
|
2774
708
|
} = {}) {
|
|
2775
709
|
const isRepoOnly = Boolean(repoOnly || ci);
|
|
2776
710
|
const paths = resolveAntigravityConfigPaths({ homeDir, cwd, platform: hostPlatform });
|
|
@@ -2782,6 +716,10 @@ export function runAntigravityStartupAudit({
|
|
|
2782
716
|
const userMcp = isRepoOnly
|
|
2783
717
|
? makeMissingJsoncStub(paths.userMcpJson)
|
|
2784
718
|
: parseJsoncReadOnly(paths.userMcpJson);
|
|
719
|
+
const projectSettings = parseJsoncReadOnly(path.join(paths.projectAgentsDir, 'settings.json'));
|
|
720
|
+
const userSettings = isRepoOnly
|
|
721
|
+
? makeMissingJsoncStub(path.join(paths.geminiConfigDir, 'settings.json'))
|
|
722
|
+
: parseJsoncReadOnly(path.join(paths.geminiConfigDir, 'settings.json'));
|
|
2785
723
|
|
|
2786
724
|
const ruleFiles = isRepoOnly
|
|
2787
725
|
? filterFilesWithinCwd([...paths.rulesFiles, ...listMarkdownFilesInDir(paths.projectRulesDir)], cwd)
|
|
@@ -2793,13 +731,16 @@ export function runAntigravityStartupAudit({
|
|
|
2793
731
|
const rulesBucket = auditAntigravityRulesFiles(ruleFiles);
|
|
2794
732
|
const strictJsonSyntax = collectStrictJsonLints(
|
|
2795
733
|
isRepoOnly
|
|
2796
|
-
? [{ res: projectHooks }, { res: projectMcp }]
|
|
734
|
+
? [{ res: projectHooks }, { res: projectMcp }, { res: projectSettings }]
|
|
2797
735
|
: [
|
|
2798
736
|
{ res: projectHooks },
|
|
2799
737
|
{ res: userHooks },
|
|
2800
738
|
{ res: projectMcp },
|
|
2801
|
-
{ res: userMcp }
|
|
2802
|
-
|
|
739
|
+
{ res: userMcp },
|
|
740
|
+
{ res: projectSettings },
|
|
741
|
+
{ res: userSettings }
|
|
742
|
+
],
|
|
743
|
+
{ harness: 'antigravity' }
|
|
2803
744
|
);
|
|
2804
745
|
const volatilePrefix = auditVolatilePromptPrefix({
|
|
2805
746
|
ruleFilePaths: ruleFiles,
|
|
@@ -2813,35 +754,200 @@ export function runAntigravityStartupAudit({
|
|
|
2813
754
|
});
|
|
2814
755
|
|
|
2815
756
|
const configuredServers = [];
|
|
757
|
+
const activeServersMap = {};
|
|
758
|
+
let hasExplicitEagerServer = false;
|
|
2816
759
|
for (const src of [userMcp.parsed, projectMcp.parsed]) {
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
760
|
+
const serversMap = src && typeof src === 'object' ? src.mcpServers || src.servers : null;
|
|
761
|
+
if (serversMap && typeof serversMap === 'object' && !Array.isArray(serversMap)) {
|
|
762
|
+
for (const [name, cfg] of Object.entries(serversMap)) {
|
|
763
|
+
if (!cfg || typeof cfg !== 'object' || cfg.disabled === true || cfg.enabled === false) continue;
|
|
764
|
+
configuredServers.push(name);
|
|
765
|
+
activeServersMap[name] = cfg;
|
|
766
|
+
if (cfg.eager === true || String(cfg.loading || '').toLowerCase() === 'eager') {
|
|
767
|
+
hasExplicitEagerServer = true;
|
|
2821
768
|
}
|
|
2822
769
|
}
|
|
2823
770
|
}
|
|
2824
771
|
}
|
|
2825
772
|
const uniqueServers = [...new Set(configuredServers)];
|
|
2826
|
-
|
|
2827
|
-
const
|
|
773
|
+
|
|
774
|
+
const cmdSources = collectAntigravityCommandSources({
|
|
775
|
+
cwd: paths.cwd,
|
|
776
|
+
projectHooks,
|
|
777
|
+
userHooks,
|
|
778
|
+
acpAgentCommand
|
|
779
|
+
});
|
|
780
|
+
const acpStdioSources = cmdSources
|
|
781
|
+
.filter((item) => /\bacp\b[^\n]*--stdio\b/i.test(item.cmd))
|
|
782
|
+
.map((item) => item.source);
|
|
783
|
+
const acpStdioDetected = Boolean(
|
|
784
|
+
acpStdio ||
|
|
785
|
+
/^(1|true)$/i.test(String(env?.ANTIGRAVITY_ACP_STDIO || '').trim()) ||
|
|
786
|
+
acpStdioSources.length > 0
|
|
787
|
+
);
|
|
788
|
+
|
|
789
|
+
const eagerGateActive = hasExplicitEagerServer || (acpStdioDetected && uniqueServers.length > 0);
|
|
790
|
+
const mcpTaxTokens = eagerGateActive ? uniqueServers.length * DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER : 0;
|
|
791
|
+
const mcpStatus = eagerGateActive && uniqueServers.length >= SUBAGENT_MCP_MIN_SERVERS ? 'warn' : 'pass';
|
|
2828
792
|
const mcpCheck = {
|
|
2829
793
|
status: mcpStatus,
|
|
794
|
+
eagerGateActive,
|
|
795
|
+
hasExplicitEagerServer,
|
|
796
|
+
acpStdioDetected,
|
|
2830
797
|
configuredServerNames: uniqueServers,
|
|
2831
798
|
startupTaxTokensPerTurn: mcpTaxTokens,
|
|
2832
799
|
isEstimated: true,
|
|
2833
|
-
summaryLine:
|
|
800
|
+
summaryLine: eagerGateActive
|
|
801
|
+
? `Antigravity MCP servers active: ${uniqueServers.length} (~${mcpTaxTokens} est. tok/turn)`
|
|
802
|
+
: `Antigravity MCP servers active: ${uniqueServers.length} (lazy IDE loading active; 0 eager Turn-0 tok/turn)`
|
|
2834
803
|
};
|
|
2835
804
|
const mcpProxyAndMetaTool = evaluateMcpProxyAndMetaToolCoaching({
|
|
2836
805
|
harness: 'antigravity',
|
|
2837
|
-
eagerGateActive
|
|
806
|
+
eagerGateActive,
|
|
2838
807
|
configuredServerCount: uniqueServers.length,
|
|
2839
808
|
configuredServerNames: uniqueServers,
|
|
2840
809
|
startupTaxTokensPerTurn: mcpTaxTokens,
|
|
2841
810
|
file: paths.projectMcpJson.replace(/\\/g, '/')
|
|
2842
811
|
});
|
|
2843
812
|
|
|
2844
|
-
const
|
|
813
|
+
const agMcpFiles = isRepoOnly ? [paths.projectMcpJson] : [paths.projectMcpJson, paths.userMcpJson];
|
|
814
|
+
const mcpToolViolations = scanMcpToolNameLengthViolations({
|
|
815
|
+
homeDir: paths.homeDir,
|
|
816
|
+
workspacePath: paths.cwd,
|
|
817
|
+
manifestDirs,
|
|
818
|
+
repoOnly: isRepoOnly,
|
|
819
|
+
includeClaudeDefaults: false,
|
|
820
|
+
extraMcpFiles: agMcpFiles
|
|
821
|
+
});
|
|
822
|
+
const mcpToolNameLength = {
|
|
823
|
+
status: mcpToolViolations.violations.length > 0 ? 'warn' : 'pass',
|
|
824
|
+
maxLength: mcpToolViolations.maxLength,
|
|
825
|
+
violations: mcpToolViolations.violations
|
|
826
|
+
};
|
|
827
|
+
const mcpListChanged = scanMcpListChangedCapabilities({
|
|
828
|
+
homeDir: paths.homeDir,
|
|
829
|
+
workspacePath: paths.cwd,
|
|
830
|
+
manifestDirs,
|
|
831
|
+
repoOnly: isRepoOnly,
|
|
832
|
+
includeClaudeDefaults: false,
|
|
833
|
+
extraMcpFiles: agMcpFiles
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
const totalMcpManifestBytes = Object.keys(activeServersMap).length > 0
|
|
837
|
+
? Buffer.byteLength(JSON.stringify({ mcpServers: activeServersMap }), 'utf8')
|
|
838
|
+
: 0;
|
|
839
|
+
let installedPluginCount = 0;
|
|
840
|
+
if (!isRepoOnly) {
|
|
841
|
+
const pluginsDir = path.join(paths.geminiConfigDir, 'plugins');
|
|
842
|
+
if (fs.existsSync(pluginsDir)) {
|
|
843
|
+
try {
|
|
844
|
+
installedPluginCount = fs.readdirSync(pluginsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).length;
|
|
845
|
+
} catch {
|
|
846
|
+
installedPluginCount = 0; // ignore: unreadable Antigravity plugins dir
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const acpManifestOverflow = Boolean(
|
|
851
|
+
acpStdioDetected && totalMcpManifestBytes > ANTIGRAVITY_ACP_STDIO_MANIFEST_MAX_BYTES
|
|
852
|
+
);
|
|
853
|
+
const acpStdioManifest = {
|
|
854
|
+
status: acpManifestOverflow ? 'warn' : 'pass',
|
|
855
|
+
acpStdioDetected,
|
|
856
|
+
totalMcpManifestBytes,
|
|
857
|
+
thresholdBytes: ANTIGRAVITY_ACP_STDIO_MANIFEST_MAX_BYTES,
|
|
858
|
+
installedPluginCount
|
|
859
|
+
};
|
|
860
|
+
|
|
861
|
+
const customAgentMatches = [];
|
|
862
|
+
const customAgentRe = new RegExp(`\\b(acp|${'a'}gy)\\b[^\\n]*--agent(?:\\s+|=)([^\\s"']+)`, 'i');
|
|
863
|
+
for (const item of cmdSources) {
|
|
864
|
+
const m = item.cmd.match(customAgentRe);
|
|
865
|
+
if (m && m[2]) {
|
|
866
|
+
customAgentMatches.push({
|
|
867
|
+
source: item.source,
|
|
868
|
+
cliForm: m[1].toLowerCase(),
|
|
869
|
+
agentName: m[2]
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
const acpCustomAgent = {
|
|
874
|
+
status: customAgentMatches.length > 0 ? 'warn' : 'pass',
|
|
875
|
+
multiplierEst: SUBSCRIPTION_QUOTA_CONSTANTS.ACP_CUSTOM_AGENT_MULTIPLIER,
|
|
876
|
+
matches: customAgentMatches
|
|
877
|
+
};
|
|
878
|
+
|
|
879
|
+
const deprecatedModelsAndFlags = auditRetiredModelsAndDeprecatedFlags({
|
|
880
|
+
cwd: paths.cwd,
|
|
881
|
+
homeDir: paths.homeDir,
|
|
882
|
+
env,
|
|
883
|
+
nowMs,
|
|
884
|
+
harness: 'antigravity',
|
|
885
|
+
antigravityConfigFiles: [
|
|
886
|
+
{ label: paths.projectMcpJson, doc: projectMcp },
|
|
887
|
+
{ label: paths.userMcpJson, doc: userMcp },
|
|
888
|
+
{ label: paths.projectHooksJson, doc: projectHooks },
|
|
889
|
+
{ label: paths.userHooksJson, doc: userHooks },
|
|
890
|
+
{ label: projectSettings.path, doc: projectSettings },
|
|
891
|
+
{ label: userSettings.path, doc: userSettings }
|
|
892
|
+
],
|
|
893
|
+
antigravityRuleFiles: ruleFiles,
|
|
894
|
+
repoOnly: isRepoOnly
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
const lints = [
|
|
898
|
+
...strictJsonSyntax.lints,
|
|
899
|
+
...volatilePrefix.lints,
|
|
900
|
+
...mcpProxyAndMetaTool.lints,
|
|
901
|
+
...deprecatedModelsAndFlags.lints
|
|
902
|
+
];
|
|
903
|
+
for (const v of mcpToolViolations.violations) {
|
|
904
|
+
lints.push({
|
|
905
|
+
ruleId: 'BO-MCP-05',
|
|
906
|
+
severity: 'warn',
|
|
907
|
+
harness: 'antigravity',
|
|
908
|
+
file: v.source,
|
|
909
|
+
message: `MCP 64-Char Tool Name Risk (#97616): Tool ${v.fullName} (${v.length} chars > 64) risks provider validation failures. Shorten the MCP server alias in config.`,
|
|
910
|
+
remediation: `Shorten MCP server alias "${v.serverName}" so mcp__<server>__<tool> <= 64 chars.`
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
if (mcpListChanged.status === 'warn') {
|
|
914
|
+
for (const fsrv of mcpListChanged.flaggedServers) {
|
|
915
|
+
lints.push({
|
|
916
|
+
ruleId: 'BO-MCP-06',
|
|
917
|
+
severity: 'warn',
|
|
918
|
+
harness: 'antigravity',
|
|
919
|
+
file: fsrv.source,
|
|
920
|
+
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.`,
|
|
921
|
+
remediation: `Pin tools statically or disconnect "${fsrv.serverName}" between sessions when not needed.`
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
if (acpManifestOverflow) {
|
|
926
|
+
const primaryMcpFile = (projectMcp.exists ? paths.projectMcpJson : paths.userMcpJson).replace(/\\/g, '/');
|
|
927
|
+
const pluginNote =
|
|
928
|
+
installedPluginCount > 0
|
|
929
|
+
? ` and may evict skills across ${installedPluginCount} plugin(s) in ~/.gemini/config/plugins/`
|
|
930
|
+
: '';
|
|
931
|
+
lints.push({
|
|
932
|
+
ruleId: 'BO-MCP-07',
|
|
933
|
+
severity: 'warn',
|
|
934
|
+
harness: 'antigravity',
|
|
935
|
+
file: primaryMcpFile,
|
|
936
|
+
message: `ACP --stdio ForceAllToolsEager Manifest Overflow (#1530): Active MCP manifest (${totalMcpManifestBytes.toLocaleString('en-US')} bytes > ${ANTIGRAVITY_ACP_STDIO_MANIFEST_MAX_BYTES.toLocaleString('en-US')} bytes) risks truncation/tool eviction under ACP --stdio${pluginNote}.`,
|
|
937
|
+
remediation: 'Prune unused MCP servers or trim schema descriptions before running ACP --stdio.'
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
for (const hit of customAgentMatches) {
|
|
941
|
+
lints.push({
|
|
942
|
+
ruleId: 'BO-CFG-19',
|
|
943
|
+
severity: 'warn',
|
|
944
|
+
harness: 'antigravity',
|
|
945
|
+
file: hit.source,
|
|
946
|
+
message: `Antigravity Custom Agent Quota Multiplier (#1890): Antigravity 1.5.17/1.5.18 "${hit.cliForm || 'acp'} --agent ${hit.agentName}" incurs ~${SUBSCRIPTION_QUOTA_CONSTANTS.ACP_CUSTOM_AGENT_MULTIPLIER.toFixed(1)}x (est.) quota burn vs default workspace agent.`,
|
|
947
|
+
remediation: 'Prefer standard workspace sessions unless custom agent isolation is required.'
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
|
|
2845
951
|
let issueCount = lints.filter((l) => l.severity !== 'info').length;
|
|
2846
952
|
let estimatedTurn0ReclaimableTokens = 0;
|
|
2847
953
|
if (mcpStatus === 'warn') {
|
|
@@ -2867,6 +973,11 @@ export function runAntigravityStartupAudit({
|
|
|
2867
973
|
checks: {
|
|
2868
974
|
mcpCheck,
|
|
2869
975
|
mcpProxyAndMetaTool,
|
|
976
|
+
mcpToolNameLength,
|
|
977
|
+
mcpListChanged,
|
|
978
|
+
acpStdioManifest,
|
|
979
|
+
acpCustomAgent,
|
|
980
|
+
deprecatedModelsAndFlags,
|
|
2870
981
|
strictJsonSyntax,
|
|
2871
982
|
volatilePrefix
|
|
2872
983
|
}
|
|
@@ -2889,36 +1000,6 @@ export function runAntigravityStartupAudit({
|
|
|
2889
1000
|
/**
|
|
2890
1001
|
* Formats `runAntigravityStartupAudit()` for terminal output.
|
|
2891
1002
|
*/
|
|
2892
|
-
export function formatAntigravityStartupAuditReport(report) {
|
|
2893
|
-
if (!report?.ok) return 'Burnoff Antigravity Startup Audit failed\n';
|
|
2894
|
-
const s = report.summary || {};
|
|
2895
|
-
const c = report.antigravity?.checks;
|
|
2896
|
-
const r = report.rulesAudit?.byHarness?.antigravity;
|
|
2897
|
-
const lines = [
|
|
2898
|
-
`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)`
|
|
2899
|
-
];
|
|
2900
|
-
if (c?.mcpCheck) {
|
|
2901
|
-
lines.push(` - [${c.mcpCheck.status}] ${c.mcpCheck.summaryLine}`);
|
|
2902
|
-
}
|
|
2903
|
-
if (c?.mcpProxyAndMetaTool?.coachingNote) {
|
|
2904
|
-
lines.push(` - [${c.mcpProxyAndMetaTool.status}] ${c.mcpProxyAndMetaTool.coachingNote}`);
|
|
2905
|
-
}
|
|
2906
|
-
if (r) {
|
|
2907
|
-
lines.push(
|
|
2908
|
-
` - Rules [${r.status}]: ${r.files.length} file(s), ${r.totalRuleCount} always-on rules (${r.onDemandCount} on-demand), ~${r.totalTokensEst.toLocaleString('en-US')} est. tokens`
|
|
2909
|
-
);
|
|
2910
|
-
for (const adv of r.advisories || []) {
|
|
2911
|
-
lines.push(` Advisories: ${adv}`);
|
|
2912
|
-
}
|
|
2913
|
-
}
|
|
2914
|
-
if (Array.isArray(report.lints) && report.lints.length > 0) {
|
|
2915
|
-
lines.push(' JSON & Config Lints:');
|
|
2916
|
-
for (const l of report.lints) {
|
|
2917
|
-
lines.push(` - [${l.severity}] ${l.ruleId}: ${l.message}`);
|
|
2918
|
-
}
|
|
2919
|
-
}
|
|
2920
|
-
return lines.join('\n') + '\n';
|
|
2921
|
-
}
|
|
2922
1003
|
|
|
2923
1004
|
/**
|
|
2924
1005
|
* Unified startup audit supporting `--client claude|antigravity|both|auto`.
|
|
@@ -2990,118 +1071,6 @@ export function runStartupAudit(options = {}) {
|
|
|
2990
1071
|
return runClaudeStartupAudit(options);
|
|
2991
1072
|
}
|
|
2992
1073
|
|
|
2993
|
-
export function formatStartupAuditReport(report) {
|
|
2994
|
-
if (report?.harnessesAudited?.length === 1 && report.harnessesAudited[0] === 'antigravity') {
|
|
2995
|
-
return formatAntigravityStartupAuditReport(report);
|
|
2996
|
-
}
|
|
2997
|
-
if (report?.harnessesAudited?.includes('antigravity') && report?.claudeCode) {
|
|
2998
|
-
const claudeSummary = report.summaryByHarness?.['claude-code'] || report.summary;
|
|
2999
|
-
const agSummary = report.summaryByHarness?.antigravity || report.summary;
|
|
3000
|
-
const claudeLints =
|
|
3001
|
-
report.lintsByHarness?.['claude-code'] ||
|
|
3002
|
-
(report.lints || []).filter((l) => !(l.file?.includes('.agents') || l.file?.includes('.gemini')));
|
|
3003
|
-
const agLints =
|
|
3004
|
-
report.lintsByHarness?.antigravity ||
|
|
3005
|
-
(report.lints || []).filter((l) => l.file?.includes('.agents') || l.file?.includes('.gemini'));
|
|
3006
|
-
return (
|
|
3007
|
-
formatClaudeStartupAuditReport({
|
|
3008
|
-
...report,
|
|
3009
|
-
lints: claudeLints,
|
|
3010
|
-
summary: claudeSummary
|
|
3011
|
-
}) +
|
|
3012
|
-
'\n' +
|
|
3013
|
-
formatAntigravityStartupAuditReport({
|
|
3014
|
-
ok: report.ok,
|
|
3015
|
-
antigravity: report.antigravity,
|
|
3016
|
-
rulesAudit: report.rulesAudit,
|
|
3017
|
-
lints: agLints,
|
|
3018
|
-
summary: agSummary
|
|
3019
|
-
})
|
|
3020
|
-
);
|
|
3021
|
-
}
|
|
3022
|
-
return formatClaudeStartupAuditReport(report);
|
|
3023
|
-
}
|
|
3024
|
-
|
|
3025
|
-
function escapeGhAnnotationValue(text = '') {
|
|
3026
|
-
return String(text || '')
|
|
3027
|
-
.replace(/%/g, '%25')
|
|
3028
|
-
.replace(/\r/g, '%0D')
|
|
3029
|
-
.replace(/\n/g, '%0A');
|
|
3030
|
-
}
|
|
3031
|
-
|
|
3032
|
-
function toRepoRelativePath(filePath, cwd = process.cwd()) {
|
|
3033
|
-
const raw = String(filePath || '').trim();
|
|
3034
|
-
if (!raw) return '.';
|
|
3035
|
-
if (!path.isAbsolute(raw)) return raw.replace(/\\/g, '/');
|
|
3036
|
-
const resolvedCwd = path.resolve(cwd);
|
|
3037
|
-
const rel = path.relative(resolvedCwd, path.resolve(raw));
|
|
3038
|
-
if (rel && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)) {
|
|
3039
|
-
return rel.replace(/\\/g, '/');
|
|
3040
|
-
}
|
|
3041
|
-
return raw.replace(/\\/g, '/');
|
|
3042
|
-
}
|
|
3043
|
-
|
|
3044
|
-
/**
|
|
3045
|
-
* Evaluates a `runStartupAudit({ ci: true })` report for CI pass/warn/fail exit codes
|
|
3046
|
-
* and formats GitHub Actions `::error` / `::warning` workflow annotations.
|
|
3047
|
-
*/
|
|
3048
|
-
export function evaluateStartupAuditCi(report = {}, { strict = false, cwd = process.cwd() } = {}) {
|
|
3049
|
-
const lints = Array.isArray(report?.lints) ? report.lints : [];
|
|
3050
|
-
let errorCount = 0;
|
|
3051
|
-
let warnCount = 0;
|
|
3052
|
-
let infoCount = 0;
|
|
3053
|
-
const annotations = [];
|
|
3054
|
-
|
|
3055
|
-
for (const l of lints) {
|
|
3056
|
-
const sev = String(l?.severity || 'warn').toLowerCase();
|
|
3057
|
-
const rel = toRepoRelativePath(l?.file || '.', cwd);
|
|
3058
|
-
const ruleId = String(l?.ruleId || 'BO-CFG');
|
|
3059
|
-
const msg = escapeGhAnnotationValue(l?.message || ruleId);
|
|
3060
|
-
if (sev === 'error') {
|
|
3061
|
-
errorCount += 1;
|
|
3062
|
-
annotations.push(`::error file=${rel},title=${ruleId}::${msg}`);
|
|
3063
|
-
} else if (sev === 'info') {
|
|
3064
|
-
infoCount += 1;
|
|
3065
|
-
} else {
|
|
3066
|
-
warnCount += 1;
|
|
3067
|
-
annotations.push(`::warning file=${rel},title=${ruleId}::${msg}`);
|
|
3068
|
-
}
|
|
3069
|
-
}
|
|
3070
|
-
|
|
3071
|
-
for (const harnessKey of ['claudeCode', 'antigravity']) {
|
|
3072
|
-
const bucket = report?.rulesAudit?.byHarness?.[harnessKey];
|
|
3073
|
-
if (bucket && bucket.status === 'warn') {
|
|
3074
|
-
warnCount += 1;
|
|
3075
|
-
const firstFile = bucket.files?.[0]?.path || '.';
|
|
3076
|
-
const rel = toRepoRelativePath(firstFile, cwd);
|
|
3077
|
-
const adv = (bucket.advisories || []).join('; ') || 'Static Turn-0 rule threshold exceeded.';
|
|
3078
|
-
annotations.push(`::warning file=${rel},title=BO-RULE-01::${escapeGhAnnotationValue(adv)}`);
|
|
3079
|
-
}
|
|
3080
|
-
}
|
|
3081
|
-
|
|
3082
|
-
const issueCount = Number(report?.summary?.issueCount || 0);
|
|
3083
|
-
let verdict = 'PASS';
|
|
3084
|
-
let exitCode = 0;
|
|
3085
|
-
if (errorCount > 0 || (Boolean(strict) && (warnCount > 0 || issueCount > 0))) {
|
|
3086
|
-
verdict = 'FAIL';
|
|
3087
|
-
exitCode = 1;
|
|
3088
|
-
} else if (warnCount > 0 || issueCount > 0) {
|
|
3089
|
-
verdict = 'WARN';
|
|
3090
|
-
exitCode = 0;
|
|
3091
|
-
}
|
|
3092
|
-
|
|
3093
|
-
return {
|
|
3094
|
-
verdict,
|
|
3095
|
-
exitCode,
|
|
3096
|
-
strict: Boolean(strict),
|
|
3097
|
-
repoOnly: true,
|
|
3098
|
-
errorCount,
|
|
3099
|
-
warnCount,
|
|
3100
|
-
infoCount,
|
|
3101
|
-
issueCount,
|
|
3102
|
-
annotations
|
|
3103
|
-
};
|
|
3104
|
-
}
|
|
3105
1074
|
|
|
3106
1075
|
export default {
|
|
3107
1076
|
CALIBRATION_MANIFEST,
|
|
@@ -3112,10 +1081,17 @@ export default {
|
|
|
3112
1081
|
SUBAGENT_MCP_MIN_SERVERS,
|
|
3113
1082
|
DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER,
|
|
3114
1083
|
IDLE_COMPACTION_MIN_VERSION,
|
|
1084
|
+
CLAUDE_WORKTREE_DEDUP_MIN_VERSION,
|
|
1085
|
+
CLAUDE_CACHE_RESUME_MIN_VERSION,
|
|
1086
|
+
CLAUDE_OMIT_CLAUDE_MD_MIN_VERSION,
|
|
1087
|
+
OMIT_CLAUDE_MD_MIN_ROOT_TOKENS,
|
|
1088
|
+
SKILL_DESCRIPTION_MAX_CHARS,
|
|
3115
1089
|
DEFAULT_IDLE_COMPACT_MIN_TOKENS,
|
|
3116
1090
|
SDK_CLI_QUOTA_MULTIPLIER_HEURISTIC,
|
|
3117
1091
|
COARSE_META_TOOL_MIN_SERVERS,
|
|
3118
1092
|
COARSE_META_TOOL_MIN_TOKENS,
|
|
1093
|
+
ANTIGRAVITY_ACP_STDIO_MANIFEST_MAX_BYTES,
|
|
1094
|
+
RETIRED_MODELS_SPEC,
|
|
3119
1095
|
VERIFIED_CLAUDE_FLAGS,
|
|
3120
1096
|
FORBIDDEN_WORKAROUND_FLAGS,
|
|
3121
1097
|
isLocalhostBaseUrl,
|
|
@@ -3126,6 +1102,8 @@ export default {
|
|
|
3126
1102
|
parseJsoncString,
|
|
3127
1103
|
parseJsoncReadOnly,
|
|
3128
1104
|
countDiscreteRules,
|
|
1105
|
+
detectRuleContradictions,
|
|
1106
|
+
auditRulesFiles,
|
|
3129
1107
|
scanClaudeCustomAgentSpecs,
|
|
3130
1108
|
scanMcpToolNameLengthViolations,
|
|
3131
1109
|
scanMcpListChangedCapabilities,
|
|
@@ -3133,6 +1111,8 @@ export default {
|
|
|
3133
1111
|
auditIdleCompactionConfig,
|
|
3134
1112
|
scanVolatilePromptPatterns,
|
|
3135
1113
|
auditVolatilePromptPrefix,
|
|
1114
|
+
parseSkillFrontmatter,
|
|
1115
|
+
auditSkillFrontmatterLimits,
|
|
3136
1116
|
runClaudeStartupAudit,
|
|
3137
1117
|
formatClaudeStartupAuditReport,
|
|
3138
1118
|
runAntigravityStartupAudit,
|