burnoff 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  2. package/README.md +66 -78
  3. package/bin/burnoff.mjs +67 -23
  4. package/hooks/hook-io.mjs +19 -7
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +7 -5
  9. package/src/ci/ci-gate.mjs +22 -0
  10. package/src/ci/pr-cost.mjs +42 -10
  11. package/src/ci/team-digest.mjs +5 -3
  12. package/src/cli/audit.mjs +103 -18
  13. package/src/cli/doctor.mjs +209 -14
  14. package/src/cli/init.mjs +349 -96
  15. package/src/cli/startup-audit.mjs +500 -24
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/loader.mjs +11 -4
  20. package/src/config/paths.mjs +62 -2
  21. package/src/config/policy.mjs +34 -5
  22. package/src/config/pricing.mjs +16 -5
  23. package/src/guards/loop-breaker.mjs +198 -13
  24. package/src/guards/post-tool-engine.mjs +289 -29
  25. package/src/guards/pre-tool-engine.mjs +336 -129
  26. package/src/guards/read-clamp.mjs +78 -18
  27. package/src/guards/session-hook.mjs +207 -0
  28. package/src/guards/shell-guard.mjs +583 -73
  29. package/src/ipc/daemon.mjs +50 -8
  30. package/src/ipc/fast-client.mjs +62 -5
  31. package/src/ipc/protocol.mjs +1 -1
  32. package/src/storage/antigravity-parser.mjs +258 -0
  33. package/src/storage/file-lock.mjs +13 -4
  34. package/src/storage/fts5-archive.mjs +4 -4
  35. package/src/storage/jsonl-parser.mjs +7 -1
  36. package/src/storage/ledger.mjs +10 -3
  37. package/src/storage/sqlite-client.mjs +4 -2
  38. package/hooks/hooks.json +0 -12
@@ -7,7 +7,12 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { StringDecoder } from 'node:string_decoder';
10
- import { getHomeDir, canonicalizePath, resolveClaudeConfigPaths } from '../config/paths.mjs';
10
+ import {
11
+ getHomeDir,
12
+ canonicalizePath,
13
+ resolveClaudeConfigPaths,
14
+ resolveAntigravityConfigPaths
15
+ } from '../config/paths.mjs';
11
16
  import { resolveModelRateCard } from '../config/pricing.mjs';
12
17
 
13
18
  export const CALIBRATION_MANIFEST = Object.freeze({
@@ -1877,6 +1882,153 @@ export function auditIdleCompactionConfig({
1877
1882
  };
1878
1883
  }
1879
1884
 
1885
+ const VOLATILE_NEGATION_RE =
1886
+ /\b(?:never|do\s+not|don't|avoid|forbid|forbidden|prohibit|anti-pattern|breaks?\s+(?:the\s+)?(?:kv\s+|prompt\s+)?cache|invalidat(?:e|es|ing)\s+(?:the\s+)?(?:kv\s+|prompt\s+)?cache)\b/i;
1887
+ const VOLATILE_TEMPLATE_RE =
1888
+ /(\{\{\s*(?:timestamp|now|current_time|current_date|date|time|uuid|request_id|session_uuid)\s*\}\}|\$\{\s*(?:Date\.now\(\)|new\s+Date\(|crypto\.randomUUID\()|\$\(\s*(?:date\b|uuidgen\b))/i;
1889
+ const VOLATILE_INSTRUCTION_RE =
1890
+ /\b(?:always|must|every\s+(?:turn|request|prompt)|prepend|inject|include|embed|insert|put)\b.{0,70}\b(?:current\s+(?:timestamp|time|date(?:\s+and\s+time)?)|live\s+timestamp|unix\s+timestamp|epoch\s+time|random\s+uuid|uuidv4|unique\s+request[_\s-]?id)\b/i;
1891
+ const SESSION_START_VOLATILE_CMD_RE =
1892
+ /\b(?:date\s+(?:\+|-[uIr])|Get-Date\b|uuidgen\b|New-Guid\b|Date\.now\(\)|randomUUID\(\))/i;
1893
+
1894
+ /**
1895
+ * Scans markdown rule text (outside fenced code blocks) for volatile timestamp/UUID
1896
+ * prompt-prefix patterns that invalidate KV prefix caches every turn.
1897
+ */
1898
+ export function scanVolatilePromptPatterns(markdown = '') {
1899
+ const lines = String(markdown || '').split(/\r?\n/);
1900
+ const findings = [];
1901
+ let inFence = false;
1902
+
1903
+ for (let i = 0; i < lines.length; i++) {
1904
+ const line = lines[i];
1905
+ if (/^\s*(?:```|~~~)/.test(line)) {
1906
+ inFence = !inFence;
1907
+ continue;
1908
+ }
1909
+ if (inFence) continue;
1910
+ const trimmed = line.trim();
1911
+ if (!trimmed) continue;
1912
+ if (VOLATILE_NEGATION_RE.test(trimmed)) continue;
1913
+
1914
+ if (VOLATILE_TEMPLATE_RE.test(trimmed)) {
1915
+ findings.push({
1916
+ lineNumber: i + 1,
1917
+ patternKind: 'volatile_template',
1918
+ snippet: trimmed.slice(0, 140)
1919
+ });
1920
+ continue;
1921
+ }
1922
+ if (VOLATILE_INSTRUCTION_RE.test(trimmed)) {
1923
+ findings.push({
1924
+ lineNumber: i + 1,
1925
+ patternKind: 'volatile_instruction',
1926
+ snippet: trimmed.slice(0, 140)
1927
+ });
1928
+ }
1929
+ }
1930
+
1931
+ return {
1932
+ matched: findings.length > 0,
1933
+ findings
1934
+ };
1935
+ }
1936
+
1937
+ /**
1938
+ * BO-CFG-11: Audits active always-on rules files and `SessionStart` hook commands
1939
+ * for volatile timestamps, dates, or UUIDs that bust the token-0 prompt prefix.
1940
+ */
1941
+ export function auditVolatilePromptPrefix({
1942
+ ruleFilePaths = [],
1943
+ settingsLayers = [],
1944
+ harness = 'claude-code'
1945
+ } = {}) {
1946
+ const seen = new Set();
1947
+ const findings = [];
1948
+ const lints = [];
1949
+ const remediation =
1950
+ 'Remove dynamic timestamps/UUIDs from static rules or SessionStart hooks; append turn-specific metadata at the tail of user turns if needed.';
1951
+
1952
+ for (const fp of ruleFilePaths) {
1953
+ if (!fp || !fs.existsSync(fp)) continue;
1954
+ let dedupeKey = canonicalizePath(fp);
1955
+ try {
1956
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
1957
+ } catch {
1958
+ // ignore: fallback to canonicalized path when realpath fails
1959
+ }
1960
+ if (seen.has(dedupeKey)) continue;
1961
+ seen.add(dedupeKey);
1962
+
1963
+ try {
1964
+ const text = fs.readFileSync(fp, 'utf8');
1965
+ if (harness === 'antigravity') {
1966
+ const triggerMode = parseRuleTriggerMode(text);
1967
+ if (triggerMode === 'model_decision' || triggerMode === 'manual') continue;
1968
+ }
1969
+ const scan = scanVolatilePromptPatterns(text);
1970
+ if (scan.matched) {
1971
+ const normFile = String(fp).replace(/\\/g, '/');
1972
+ const first = scan.findings[0];
1973
+ findings.push({
1974
+ file: normFile,
1975
+ sourceType: 'rules_file',
1976
+ matches: scan.findings
1977
+ });
1978
+ lints.push({
1979
+ ruleId: 'BO-CFG-11',
1980
+ severity: 'warn',
1981
+ harness,
1982
+ file: normFile,
1983
+ message: `Volatile Prompt Prefix Risk (BO-CFG-11): ${normFile}:${first.lineNumber} injects dynamic timestamp/UUID (${first.patternKind}), mutating the token-0 prefix each turn, collapsing KV cache reuse and triggering 1.25x cache-write surcharges.`,
1984
+ remediation
1985
+ });
1986
+ }
1987
+ } catch {
1988
+ // ignore: unreadable rules markdown file
1989
+ }
1990
+ }
1991
+
1992
+ for (const layerEntry of settingsLayers) {
1993
+ const doc = layerEntry?.doc?.parsed;
1994
+ if (!doc || typeof doc !== 'object') continue;
1995
+ const fileLabel = String(layerEntry?.label || layerEntry?.doc?.path || 'settings.json').replace(/\\/g, '/');
1996
+ const sessionStartHooks = doc?.hooks?.SessionStart;
1997
+ if (!Array.isArray(sessionStartHooks)) continue;
1998
+ const matchedCmds = [];
1999
+ for (const entry of sessionStartHooks) {
2000
+ const hookList = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
2001
+ for (const h of hookList) {
2002
+ const cmd = typeof h?.command === 'string' ? h.command.trim() : '';
2003
+ if (cmd && SESSION_START_VOLATILE_CMD_RE.test(cmd)) {
2004
+ matchedCmds.push(cmd.slice(0, 140));
2005
+ }
2006
+ }
2007
+ }
2008
+ if (matchedCmds.length > 0) {
2009
+ findings.push({
2010
+ file: fileLabel,
2011
+ sourceType: 'session_start_hook',
2012
+ commands: matchedCmds
2013
+ });
2014
+ lints.push({
2015
+ ruleId: 'BO-CFG-11',
2016
+ severity: 'warn',
2017
+ harness,
2018
+ file: fileLabel,
2019
+ message: `Volatile Prompt Prefix Risk (BO-CFG-11): SessionStart hook in ${fileLabel} runs "${matchedCmds[0]}", mutating the token-0 prefix each turn, collapsing KV cache reuse and triggering 1.25x cache-write surcharges.`,
2020
+ remediation
2021
+ });
2022
+ }
2023
+ }
2024
+
2025
+ return {
2026
+ status: lints.length > 0 ? 'warn' : 'pass',
2027
+ findings,
2028
+ lints
2029
+ };
2030
+ }
2031
+
1880
2032
  /**
1881
2033
  * Runs Turn-0 startup config, rules-count, and eager-only MCP audit for Claude Code.
1882
2034
  */
@@ -1921,10 +2073,6 @@ export function runClaudeStartupAudit({
1921
2073
 
1922
2074
  const chromeOnDemandCmd = buildClaudeCliCommand(['--chrome'], { platform: hostPlatform });
1923
2075
  const artifactDisallowedCmd = buildClaudeCliCommand(['--disallowedTools', 'Artifact'], { platform: hostPlatform });
1924
- const bundledSessionCmd = buildClaudeCliCommand(
1925
- ['--settings', { disableBundledSkills: true, disableWorkflows: true }],
1926
- { platform: hostPlatform }
1927
- );
1928
2076
 
1929
2077
  // Check 1: Chrome default enabled strictly in ~/.claude.json
1930
2078
  const chromeVal = claudeJson.parsed?.claudeInChromeDefaultEnabled === true;
@@ -1944,6 +2092,7 @@ export function runClaudeStartupAudit({
1944
2092
  };
1945
2093
 
1946
2094
  // Check 2: Artifact built-in tool & one-way global lock
2095
+ // Only warn when explicitly configured with deprecated `disableArtifact: true` or backed by observed local telemetry.
1947
2096
  let enableArtifactValue = null;
1948
2097
  let deprecatedDisableArtifactPresent = false;
1949
2098
  for (const layer of layers) {
@@ -1952,13 +2101,14 @@ export function runClaudeStartupAudit({
1952
2101
  }
1953
2102
  const sdkTsDropsArtifact =
1954
2103
  observedEntrypoint === 'sdk-ts' && String(env?.CLAUDE_CODE_ARTIFACT || '').trim() !== '1';
2104
+ const hasObservedTelemetry = telemetry.sessionsScanned > 0;
1955
2105
  let artifactStatus = 'pass';
1956
2106
  let artifactReclaimable = 0;
1957
2107
  if (deprecatedDisableArtifactPresent) {
1958
2108
  artifactStatus = 'warn';
1959
2109
  artifactReclaimable =
1960
2110
  enableArtifactValue === false ? 0 : CALIBRATION_MANIFEST.claudeCodeTurn0.artifactTool.tokens;
1961
- } else if (!sdkTsDropsArtifact && enableArtifactValue !== false && telemetry.artifactCalls7d === 0) {
2111
+ } else if (hasObservedTelemetry && !sdkTsDropsArtifact && enableArtifactValue !== false && telemetry.artifactCalls7d === 0) {
1962
2112
  artifactStatus = 'warn';
1963
2113
  artifactReclaimable = CALIBRATION_MANIFEST.claudeCodeTurn0.artifactTool.tokens;
1964
2114
  }
@@ -1979,13 +2129,12 @@ export function runClaudeStartupAudit({
1979
2129
  ...(deprecatedDisableArtifactPresent
1980
2130
  ? { migrateDeprecated: 'Replace deprecated "disableArtifact": true with "enableArtifact": false in ~/.claude/settings.json.' }
1981
2131
  : {}),
1982
- neverUseArtifacts: 'Set "enableArtifact": false in ~/.claude/settings.json (permanent one-way global lock).',
1983
2132
  occasionalArtifacts: `Leave "enableArtifact" unset and run terminal coding with: ${artifactDisallowedCmd}`
1984
2133
  }
1985
2134
  : null
1986
2135
  };
1987
2136
 
1988
- // Check 3: Bundled skills & workflows
2137
+ // Check 3: Repo-local Turn-0 focus (suppress speculative global findings & unverified global keys)
1989
2138
  let disableBundledSkills = false;
1990
2139
  let workflowsDisabled = false;
1991
2140
  for (const layer of layers) {
@@ -1993,22 +2142,16 @@ export function runClaudeStartupAudit({
1993
2142
  if (layer.disableWorkflows === true || layer.enableWorkflows === false) workflowsDisabled = true;
1994
2143
  }
1995
2144
  const repoMentionsAnthropicSdk = detectAnthropicSdkMarkers(paths.cwd);
1996
- const bundledReclaimable =
1997
- (disableBundledSkills ? 0 : CALIBRATION_MANIFEST.claudeCodeTurn0.bundledSkills.tokens) +
1998
- (workflowsDisabled ? 0 : CALIBRATION_MANIFEST.claudeCodeTurn0.workflows.tokens);
1999
- const bundledStatus = bundledReclaimable > 0 ? 'warn' : 'pass';
2000
2145
  const bundledSkillsAndWorkflows = {
2001
- status: bundledStatus,
2146
+ status: 'pass',
2002
2147
  disableBundledSkills,
2003
2148
  workflowsDisabled,
2004
2149
  repoMentionsAnthropicSdk,
2005
2150
  priority: repoMentionsAnthropicSdk ? 'high' : 'normal',
2006
- reclaimableTokensPerTurn: bundledReclaimable,
2151
+ reclaimableTokensPerTurn: 0,
2007
2152
  isEstimated: true,
2008
- fix:
2009
- bundledStatus === 'warn'
2010
- ? `Set "disableBundledSkills": true and "disableWorkflows": true in ~/.claude/settings.json (or pass per-session: ${bundledSessionCmd}).`
2011
- : null
2153
+ unverifiedGlobalKeysRemoved: true,
2154
+ fix: null
2012
2155
  };
2013
2156
 
2014
2157
  // Check 4: Eager-only MCP gate
@@ -2076,6 +2219,11 @@ export function runClaudeStartupAudit({
2076
2219
  observedModels: telemetry.observedModels || [],
2077
2220
  maxObservedPrefixTokens: telemetry.maxCachedPrefixTokens
2078
2221
  });
2222
+ const volatilePrefix = auditVolatilePromptPrefix({
2223
+ ruleFilePaths: paths.rulesFiles,
2224
+ settingsLayers,
2225
+ harness: 'claude-code'
2226
+ });
2079
2227
  const sdkCliDetected = telemetry.entrypoints.includes('sdk-cli');
2080
2228
  const sdkCliSessionsCount = telemetry.sdkCliSessions7d || (sdkCliDetected ? 1 : 0);
2081
2229
  const sdkCliQuotaHeuristic = {
@@ -2093,7 +2241,8 @@ export function runClaudeStartupAudit({
2093
2241
  ...strictJsonSyntax.lints,
2094
2242
  ...misplacedChromeKey.lints,
2095
2243
  ...localSettingsSecrets.lints,
2096
- ...idleCompactionRoi.lints
2244
+ ...idleCompactionRoi.lints,
2245
+ ...volatilePrefix.lints
2097
2246
  ];
2098
2247
  if (mcpStartupTax.gateReasons.includes('ssh_forced_disable_experimental_betas')) {
2099
2248
  lints.push({
@@ -2218,6 +2367,7 @@ export function runClaudeStartupAudit({
2218
2367
  localSettingsSecrets,
2219
2368
  deprecatedModelsAndFlags,
2220
2369
  idleCompactionRoi,
2370
+ volatilePrefix,
2221
2371
  sdkCliQuotaHeuristic
2222
2372
  }
2223
2373
  },
@@ -2271,19 +2421,23 @@ export function formatClaudeStartupAuditReport(report) {
2271
2421
  if (c.artifactTool.fixes?.migrateDeprecated) {
2272
2422
  lines.push(` Fix (migrate): ${c.artifactTool.fixes.migrateDeprecated}`);
2273
2423
  }
2274
- lines.push(` Fix (never use): ${c.artifactTool.fixes?.neverUseArtifacts}`);
2275
- lines.push(` Fix (occasional): ${c.artifactTool.fixes?.occasionalArtifacts}`);
2424
+ if (c.artifactTool.fixes?.neverUseArtifacts) {
2425
+ lines.push(` Fix (never use): ${c.artifactTool.fixes.neverUseArtifacts}`);
2426
+ }
2427
+ if (c.artifactTool.fixes?.occasionalArtifacts) {
2428
+ lines.push(` Fix (occasional): ${c.artifactTool.fixes.occasionalArtifacts}`);
2429
+ }
2276
2430
  } else {
2277
2431
  lines.push(` - [pass] Artifact tool (${c.artifactTool.entrypoint})`);
2278
2432
  }
2279
- if (c.bundledSkillsAndWorkflows.status === 'warn') {
2433
+ if (c.bundledSkillsAndWorkflows.status === 'warn' && c.bundledSkillsAndWorkflows.fix) {
2280
2434
  const prio = c.bundledSkillsAndWorkflows.priority === 'high' ? ' [HIGH: Anthropic SDK markers detected]' : '';
2281
2435
  lines.push(
2282
2436
  ` - [warn] Bundled skills/workflows enabled${prio} (~${c.bundledSkillsAndWorkflows.reclaimableTokensPerTurn} tok/turn est.)`
2283
2437
  );
2284
2438
  lines.push(` Fix: ${c.bundledSkillsAndWorkflows.fix}`);
2285
2439
  } else {
2286
- lines.push(' - [pass] Bundled skills & workflows disabled');
2440
+ lines.push(' - [pass] Repo-local Turn-0 focus (no unverified global settings keys recommended)');
2287
2441
  }
2288
2442
  if (c.subagentMcpInstructionsTax?.triggered) {
2289
2443
  lines.push(
@@ -2319,6 +2473,322 @@ export function formatClaudeStartupAuditReport(report) {
2319
2473
  return lines.join('\n') + '\n';
2320
2474
  }
2321
2475
 
2476
+ function listMarkdownFilesInDir(dirPath) {
2477
+ if (!dirPath || !fs.existsSync(dirPath)) return [];
2478
+ try {
2479
+ return fs
2480
+ .readdirSync(dirPath, { withFileTypes: true })
2481
+ .filter((e) => e.isFile() && /\.md$/i.test(e.name))
2482
+ .map((e) => path.join(dirPath, e.name));
2483
+ } catch {
2484
+ return []; // ignore: unreadable rules directory
2485
+ }
2486
+ }
2487
+
2488
+ function parseRuleTriggerMode(markdown = '') {
2489
+ const m = String(markdown || '').match(/^---\s*\r?\n([\s\S]*?)\r?\n---/);
2490
+ if (!m) return 'always_on';
2491
+ const trig = m[1].match(/^\s*trigger\s*:\s*([^\r\n#]+)/im);
2492
+ if (!trig) return 'always_on';
2493
+ return trig[1].trim().toLowerCase() || 'always_on';
2494
+ }
2495
+
2496
+ function auditAntigravityRulesFiles(filePaths = []) {
2497
+ const seen = new Set();
2498
+ const files = [];
2499
+ let totalTokensEst = 0;
2500
+ let totalRuleCount = 0;
2501
+ let onDemandCount = 0;
2502
+
2503
+ for (const fp of filePaths) {
2504
+ if (!fp || !fs.existsSync(fp)) continue;
2505
+ let dedupeKey = canonicalizePath(fp);
2506
+ try {
2507
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
2508
+ } catch {
2509
+ // ignore: fallback to canonicalized path when realpath fails
2510
+ }
2511
+ if (seen.has(dedupeKey)) continue;
2512
+ seen.add(dedupeKey);
2513
+
2514
+ try {
2515
+ const text = fs.readFileSync(fp, 'utf8');
2516
+ const triggerMode = parseRuleTriggerMode(text);
2517
+ const chars = text.length;
2518
+ const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
2519
+ const ruleCount = countDiscreteRules(text);
2520
+ const isAlwaysOn = triggerMode !== 'model_decision' && triggerMode !== 'manual';
2521
+ files.push({
2522
+ path: String(fp).replace(/\\/g, '/'),
2523
+ triggerMode,
2524
+ alwaysOn: isAlwaysOn,
2525
+ chars,
2526
+ tokensEst,
2527
+ ruleCount
2528
+ });
2529
+ if (isAlwaysOn) {
2530
+ totalTokensEst += tokensEst;
2531
+ totalRuleCount += ruleCount;
2532
+ } else {
2533
+ onDemandCount += 1;
2534
+ }
2535
+ } catch {
2536
+ // ignore: unreadable Antigravity rule markdown
2537
+ }
2538
+ }
2539
+
2540
+ let status = 'pass';
2541
+ const advisories = [];
2542
+ if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
2543
+ status = 'warn';
2544
+ advisories.push(
2545
+ `IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} always-on rules); set trigger: model_decision or move domain rules into skills.`
2546
+ );
2547
+ } else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
2548
+ status = 'caution';
2549
+ advisories.push(
2550
+ `Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} always-on rules).`
2551
+ );
2552
+ }
2553
+ if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
2554
+ status = 'warn';
2555
+ advisories.push(
2556
+ `Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across always-on Antigravity rules).`
2557
+ );
2558
+ }
2559
+
2560
+ return { files, totalTokensEst, totalRuleCount, onDemandCount, status, advisories };
2561
+ }
2562
+
2563
+ /**
2564
+ * Runs Turn-0 startup config, rules-count, and MCP config audit for Google Antigravity.
2565
+ */
2566
+ export function runAntigravityStartupAudit({
2567
+ homeDir = getHomeDir(),
2568
+ cwd = process.cwd(),
2569
+ hostPlatform = process.platform,
2570
+ nowMs = Date.now()
2571
+ } = {}) {
2572
+ const paths = resolveAntigravityConfigPaths({ homeDir, cwd, platform: hostPlatform });
2573
+ const projectHooks = parseJsoncReadOnly(paths.projectHooksJson);
2574
+ const userHooks = parseJsoncReadOnly(paths.userHooksJson);
2575
+ const projectMcp = parseJsoncReadOnly(paths.projectMcpJson);
2576
+ const userMcp = parseJsoncReadOnly(paths.userMcpJson);
2577
+
2578
+ const ruleFiles = [
2579
+ ...paths.rulesFiles,
2580
+ ...listMarkdownFilesInDir(paths.projectRulesDir),
2581
+ ...listMarkdownFilesInDir(paths.globalRulesDir)
2582
+ ];
2583
+ const rulesBucket = auditAntigravityRulesFiles(ruleFiles);
2584
+ const strictJsonSyntax = collectStrictJsonLints([
2585
+ { res: projectHooks },
2586
+ { res: userHooks },
2587
+ { res: projectMcp },
2588
+ { res: userMcp }
2589
+ ]);
2590
+ const volatilePrefix = auditVolatilePromptPrefix({
2591
+ ruleFilePaths: ruleFiles,
2592
+ settingsLayers: [
2593
+ { label: paths.projectHooksJson, doc: projectHooks },
2594
+ { label: paths.userHooksJson, doc: userHooks }
2595
+ ],
2596
+ harness: 'antigravity'
2597
+ });
2598
+
2599
+ const configuredServers = [];
2600
+ for (const src of [userMcp.parsed, projectMcp.parsed]) {
2601
+ if (src && typeof src.mcpServers === 'object' && !Array.isArray(src.mcpServers)) {
2602
+ for (const [name, cfg] of Object.entries(src.mcpServers)) {
2603
+ if (cfg && cfg.disabled !== true) {
2604
+ configuredServers.push(name);
2605
+ }
2606
+ }
2607
+ }
2608
+ }
2609
+ const uniqueServers = [...new Set(configuredServers)];
2610
+ const mcpTaxTokens = uniqueServers.length * DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER;
2611
+ const mcpStatus = uniqueServers.length >= SUBAGENT_MCP_MIN_SERVERS ? 'warn' : 'pass';
2612
+ const mcpCheck = {
2613
+ status: mcpStatus,
2614
+ configuredServerNames: uniqueServers,
2615
+ startupTaxTokensPerTurn: mcpTaxTokens,
2616
+ isEstimated: true,
2617
+ summaryLine: `Antigravity MCP servers active: ${uniqueServers.length} (~${mcpTaxTokens} est. tok/turn)`
2618
+ };
2619
+
2620
+ const lints = [...strictJsonSyntax.lints, ...volatilePrefix.lints];
2621
+ let issueCount = lints.length;
2622
+ let estimatedTurn0ReclaimableTokens = 0;
2623
+ if (mcpStatus === 'warn') {
2624
+ issueCount += 1;
2625
+ estimatedTurn0ReclaimableTokens += mcpTaxTokens;
2626
+ }
2627
+ if (rulesBucket.status === 'warn' || rulesBucket.status === 'caution') {
2628
+ issueCount += 1;
2629
+ }
2630
+
2631
+ return {
2632
+ ok: true,
2633
+ schemaVersion: '1.0.0',
2634
+ platform: hostPlatform,
2635
+ harnessesAudited: ['antigravity'],
2636
+ antigravity: {
2637
+ configFiles: {
2638
+ projectHooks: formatConfigStatus(projectHooks),
2639
+ userHooks: formatConfigStatus(userHooks),
2640
+ projectMcp: formatConfigStatus(projectMcp),
2641
+ userMcp: formatConfigStatus(userMcp)
2642
+ },
2643
+ checks: {
2644
+ mcpCheck,
2645
+ strictJsonSyntax,
2646
+ volatilePrefix
2647
+ }
2648
+ },
2649
+ rulesAudit: {
2650
+ thresholds: RULES_THRESHOLDS,
2651
+ byHarness: {
2652
+ antigravity: rulesBucket
2653
+ }
2654
+ },
2655
+ lints,
2656
+ summary: {
2657
+ issueCount,
2658
+ estimatedTurn0ReclaimableTokens,
2659
+ estimatedWeeklySavingsUsd: estimateWeeklySavingsUsd(estimatedTurn0ReclaimableTokens, nowMs)
2660
+ }
2661
+ };
2662
+ }
2663
+
2664
+ /**
2665
+ * Formats `runAntigravityStartupAudit()` for terminal output.
2666
+ */
2667
+ export function formatAntigravityStartupAuditReport(report) {
2668
+ if (!report?.ok) return 'Burnoff Antigravity Startup Audit failed\n';
2669
+ const s = report.summary || {};
2670
+ const c = report.antigravity?.checks;
2671
+ const r = report.rulesAudit?.byHarness?.antigravity;
2672
+ const lines = [
2673
+ `Burnoff Antigravity Turn-0 Startup Audit | Findings: ${s.issueCount ?? 0} | Reclaimable: ~${Number(s.estimatedTurn0ReclaimableTokens || 0).toLocaleString('en-US')} tok/turn (est.) (~$${Number(s.estimatedWeeklySavingsUsd || 0).toFixed(2)}/wk)`
2674
+ ];
2675
+ if (c?.mcpCheck) {
2676
+ lines.push(` - [${c.mcpCheck.status}] ${c.mcpCheck.summaryLine}`);
2677
+ }
2678
+ if (r) {
2679
+ lines.push(
2680
+ ` - Rules [${r.status}]: ${r.files.length} file(s), ${r.totalRuleCount} always-on rules (${r.onDemandCount} on-demand), ~${r.totalTokensEst.toLocaleString('en-US')} est. tokens`
2681
+ );
2682
+ for (const adv of r.advisories || []) {
2683
+ lines.push(` Advisories: ${adv}`);
2684
+ }
2685
+ }
2686
+ if (Array.isArray(report.lints) && report.lints.length > 0) {
2687
+ lines.push(' JSON & Config Lints:');
2688
+ for (const l of report.lints) {
2689
+ lines.push(` - [${l.severity}] ${l.ruleId}: ${l.message}`);
2690
+ }
2691
+ }
2692
+ return lines.join('\n') + '\n';
2693
+ }
2694
+
2695
+ /**
2696
+ * Unified startup audit supporting `--client claude|antigravity|both|auto`.
2697
+ */
2698
+ export function runStartupAudit(options = {}) {
2699
+ const cwd = path.resolve(options.cwd || process.cwd());
2700
+ const homeDir = options.homeDir || getHomeDir();
2701
+ const rawClient = String(options.client || 'auto').trim().toLowerCase();
2702
+
2703
+ let target = rawClient;
2704
+ if (rawClient === 'auto') {
2705
+ const hasAg =
2706
+ fs.existsSync(path.join(cwd, '.agents')) ||
2707
+ fs.existsSync(path.join(cwd, 'GEMINI.md')) ||
2708
+ fs.existsSync(path.join(homeDir, '.gemini', 'config', 'hooks.json'));
2709
+ const hasClaude =
2710
+ fs.existsSync(path.join(cwd, '.claude')) ||
2711
+ fs.existsSync(path.join(homeDir, '.claude'));
2712
+ if (hasAg && hasClaude) target = 'both';
2713
+ else if (hasAg) target = 'antigravity';
2714
+ else target = 'claude';
2715
+ }
2716
+
2717
+ if (target === 'antigravity' || target === 'ag') {
2718
+ return runAntigravityStartupAudit(options);
2719
+ }
2720
+ if (target === 'both') {
2721
+ const claudeReport = runClaudeStartupAudit(options);
2722
+ const agReport = runAntigravityStartupAudit(options);
2723
+ const claudeLints = claudeReport.lints || [];
2724
+ const agLints = agReport.lints || [];
2725
+ return {
2726
+ ...claudeReport,
2727
+ harnessesAudited: ['claude-code', 'antigravity'],
2728
+ antigravity: agReport.antigravity,
2729
+ rulesAudit: {
2730
+ thresholds: RULES_THRESHOLDS,
2731
+ byHarness: {
2732
+ ...claudeReport.rulesAudit.byHarness,
2733
+ ...agReport.rulesAudit.byHarness
2734
+ }
2735
+ },
2736
+ lints: [...claudeLints, ...agLints],
2737
+ lintsByHarness: {
2738
+ 'claude-code': claudeLints,
2739
+ antigravity: agLints
2740
+ },
2741
+ summaryByHarness: {
2742
+ 'claude-code': claudeReport.summary,
2743
+ antigravity: agReport.summary
2744
+ },
2745
+ summary: {
2746
+ issueCount: (claudeReport.summary?.issueCount || 0) + (agReport.summary?.issueCount || 0),
2747
+ estimatedTurn0ReclaimableTokens:
2748
+ (claudeReport.summary?.estimatedTurn0ReclaimableTokens || 0) +
2749
+ (agReport.summary?.estimatedTurn0ReclaimableTokens || 0),
2750
+ estimatedWeeklySavingsUsd: Number(
2751
+ ((claudeReport.summary?.estimatedWeeklySavingsUsd || 0) +
2752
+ (agReport.summary?.estimatedWeeklySavingsUsd || 0)).toFixed(2)
2753
+ )
2754
+ }
2755
+ };
2756
+ }
2757
+ return runClaudeStartupAudit(options);
2758
+ }
2759
+
2760
+ export function formatStartupAuditReport(report) {
2761
+ if (report?.harnessesAudited?.length === 1 && report.harnessesAudited[0] === 'antigravity') {
2762
+ return formatAntigravityStartupAuditReport(report);
2763
+ }
2764
+ if (report?.harnessesAudited?.includes('antigravity') && report?.claudeCode) {
2765
+ const claudeSummary = report.summaryByHarness?.['claude-code'] || report.summary;
2766
+ const agSummary = report.summaryByHarness?.antigravity || report.summary;
2767
+ const claudeLints =
2768
+ report.lintsByHarness?.['claude-code'] ||
2769
+ (report.lints || []).filter((l) => !(l.file?.includes('.agents') || l.file?.includes('.gemini')));
2770
+ const agLints =
2771
+ report.lintsByHarness?.antigravity ||
2772
+ (report.lints || []).filter((l) => l.file?.includes('.agents') || l.file?.includes('.gemini'));
2773
+ return (
2774
+ formatClaudeStartupAuditReport({
2775
+ ...report,
2776
+ lints: claudeLints,
2777
+ summary: claudeSummary
2778
+ }) +
2779
+ '\n' +
2780
+ formatAntigravityStartupAuditReport({
2781
+ ok: report.ok,
2782
+ antigravity: report.antigravity,
2783
+ rulesAudit: report.rulesAudit,
2784
+ lints: agLints,
2785
+ summary: agSummary
2786
+ })
2787
+ );
2788
+ }
2789
+ return formatClaudeStartupAuditReport(report);
2790
+ }
2791
+
2322
2792
  export default {
2323
2793
  CALIBRATION_MANIFEST,
2324
2794
  RULES_THRESHOLDS,
@@ -2343,6 +2813,12 @@ export default {
2343
2813
  scanMcpListChangedCapabilities,
2344
2814
  estimateSubagentMcpInstructionsTax,
2345
2815
  auditIdleCompactionConfig,
2816
+ scanVolatilePromptPatterns,
2817
+ auditVolatilePromptPrefix,
2346
2818
  runClaudeStartupAudit,
2347
- formatClaudeStartupAuditReport
2819
+ formatClaudeStartupAuditReport,
2820
+ runAntigravityStartupAudit,
2821
+ formatAntigravityStartupAuditReport,
2822
+ runStartupAudit,
2823
+ formatStartupAuditReport
2348
2824
  };