burnoff 1.1.0 → 1.3.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 (45) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +37 -0
  4. package/README.md +90 -75
  5. package/bin/burnoff.mjs +185 -24
  6. package/commands/burnoff.md +16 -0
  7. package/docs/CLAUDE_CODE_PLUGIN.md +67 -0
  8. package/docs/DESIGN_PARTNER_INTAKE.md +44 -0
  9. package/hooks/hook-io.mjs +19 -7
  10. package/hooks/post-tool-use.mjs +33 -26
  11. package/hooks/pre-tool-use.mjs +43 -41
  12. package/hooks/session-lifecycle.mjs +40 -0
  13. package/package.json +15 -7
  14. package/scripts/burnoff-statusline.mjs +84 -0
  15. package/src/ci/ci-gate.mjs +22 -0
  16. package/src/ci/pr-cost.mjs +42 -10
  17. package/src/ci/team-digest.mjs +5 -3
  18. package/src/cli/audit.mjs +103 -18
  19. package/src/cli/doctor.mjs +209 -14
  20. package/src/cli/init.mjs +349 -96
  21. package/src/cli/startup-audit.mjs +712 -62
  22. package/src/clients/antigravity.mjs +285 -0
  23. package/src/clients/claude-code.mjs +180 -0
  24. package/src/clients/detect.mjs +64 -0
  25. package/src/config/loader.mjs +11 -4
  26. package/src/config/paths.mjs +62 -2
  27. package/src/config/policy.mjs +34 -5
  28. package/src/config/pricing.mjs +16 -5
  29. package/src/guards/loop-breaker.mjs +198 -13
  30. package/src/guards/post-tool-engine.mjs +289 -29
  31. package/src/guards/pre-tool-engine.mjs +382 -151
  32. package/src/guards/read-clamp.mjs +78 -18
  33. package/src/guards/session-hook.mjs +207 -0
  34. package/src/guards/shell-guard.mjs +583 -73
  35. package/src/guards/snooze.mjs +360 -0
  36. package/src/ipc/daemon.mjs +50 -8
  37. package/src/ipc/fast-client.mjs +62 -5
  38. package/src/ipc/protocol.mjs +1 -1
  39. package/src/storage/antigravity-parser.mjs +258 -0
  40. package/src/storage/file-lock.mjs +13 -4
  41. package/src/storage/fts5-archive.mjs +4 -4
  42. package/src/storage/jsonl-parser.mjs +7 -1
  43. package/src/storage/ledger.mjs +10 -3
  44. package/src/storage/sqlite-client.mjs +4 -2
  45. 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({
@@ -755,11 +760,10 @@ function scanClaudeTelemetrySummary({
755
760
  * Strictly read-only scan of `~/.claude/agents/*.md` and `<cwd>/.claude/agents/*.md`
756
761
  * to count custom subagent definitions and narrow frontmatter `tools:` allowlists.
757
762
  */
758
- export function scanClaudeCustomAgentSpecs({ homeDir = getHomeDir(), cwd = process.cwd() } = {}) {
759
- const dirs = [
760
- path.join(homeDir, '.claude', 'agents'),
761
- path.join(cwd, '.claude', 'agents')
762
- ];
763
+ export function scanClaudeCustomAgentSpecs({ homeDir = getHomeDir(), cwd = process.cwd(), repoOnly = false } = {}) {
764
+ const dirs = repoOnly
765
+ ? [path.join(cwd, '.claude', 'agents')]
766
+ : [path.join(homeDir, '.claude', 'agents'), path.join(cwd, '.claude', 'agents')];
763
767
  const seen = new Set();
764
768
  const agents = [];
765
769
  let narrowToolsAgents = 0;
@@ -1005,7 +1009,8 @@ export function scanMcpToolNameLengthViolations({
1005
1009
  workspacePath = process.cwd(),
1006
1010
  observedToolNames = [],
1007
1011
  manifestDirs = [],
1008
- maxLength = 64
1012
+ maxLength = 64,
1013
+ repoOnly = false
1009
1014
  } = {}) {
1010
1015
  const disabledServers = new Set();
1011
1016
  const violationsByFullName = new Map();
@@ -1054,7 +1059,9 @@ export function scanMcpToolNameLengthViolations({
1054
1059
  inspectServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path.replace(/\\/g, '/'));
1055
1060
  }
1056
1061
 
1057
- const claudeJson = parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1062
+ const claudeJson = repoOnly
1063
+ ? { parseOk: false, parsed: null }
1064
+ : parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1058
1065
  if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
1059
1066
  inspectServerMap(claudeJson.parsed.mcpServers, '~/.claude.json');
1060
1067
  const projects = claudeJson.parsed.projects;
@@ -1153,7 +1160,7 @@ function collectDisabledClaudeMcpServers({ homeDir = getHomeDir(), workspacePath
1153
1160
  trackServerMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed);
1154
1161
  }
1155
1162
 
1156
- const claudeJson = parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1163
+ const claudeJson = homeDir ? parseJsoncReadOnly(path.join(homeDir, '.claude.json')) : { parseOk: false, parsed: null };
1157
1164
  if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
1158
1165
  trackServerMap(claudeJson.parsed.mcpServers);
1159
1166
  const projects = claudeJson.parsed.projects;
@@ -1192,9 +1199,10 @@ export function scanMcpListChangedCapabilities({
1192
1199
  manifestDirs = [],
1193
1200
  runtimeListChangedServers = [],
1194
1201
  maxObservedCachedPrefixTokens = null,
1195
- cachedPrefixThreshold = LIST_CHANGED_PREFIX_THRESHOLD
1202
+ cachedPrefixThreshold = LIST_CHANGED_PREFIX_THRESHOLD,
1203
+ repoOnly = false
1196
1204
  } = {}) {
1197
- const disabledServers = collectDisabledClaudeMcpServers({ homeDir, workspacePath });
1205
+ const disabledServers = collectDisabledClaudeMcpServers({ homeDir: repoOnly ? null : homeDir, workspacePath });
1198
1206
  const flaggedByServer = new Map();
1199
1207
 
1200
1208
  const recordFlagged = (serverName, reason, source) => {
@@ -1223,7 +1231,9 @@ export function scanMcpListChangedCapabilities({
1223
1231
  inspectConfigMap(projMcp.parsed.mcpServers || projMcp.parsed.servers || projMcp.parsed, projMcp.path);
1224
1232
  }
1225
1233
 
1226
- const claudeJson = parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1234
+ const claudeJson = repoOnly
1235
+ ? { parseOk: false, parsed: null }
1236
+ : parseJsoncReadOnly(path.join(homeDir, '.claude.json'));
1227
1237
  if (claudeJson.parseOk && claudeJson.parsed && typeof claudeJson.parsed === 'object') {
1228
1238
  inspectConfigMap(claudeJson.parsed.mcpServers, '~/.claude.json');
1229
1239
  const projects = claudeJson.parsed.projects;
@@ -1877,6 +1887,196 @@ export function auditIdleCompactionConfig({
1877
1887
  };
1878
1888
  }
1879
1889
 
1890
+ const VOLATILE_NEGATION_RE =
1891
+ /\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;
1892
+ const VOLATILE_TEMPLATE_RE =
1893
+ /(\{\{\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;
1894
+ const VOLATILE_INSTRUCTION_RE =
1895
+ /\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;
1896
+ const SESSION_START_VOLATILE_CMD_RE =
1897
+ /\b(?:date\s+(?:\+|-[uIr])|Get-Date\b|uuidgen\b|New-Guid\b|Date\.now\(\)|randomUUID\(\))/i;
1898
+
1899
+ /**
1900
+ * Scans markdown rule text (outside fenced code blocks) for volatile timestamp/UUID
1901
+ * prompt-prefix patterns that invalidate KV prefix caches every turn.
1902
+ */
1903
+ export function scanVolatilePromptPatterns(markdown = '') {
1904
+ const lines = String(markdown || '').split(/\r?\n/);
1905
+ const findings = [];
1906
+ let inFence = false;
1907
+
1908
+ for (let i = 0; i < lines.length; i++) {
1909
+ const line = lines[i];
1910
+ if (/^\s*(?:```|~~~)/.test(line)) {
1911
+ inFence = !inFence;
1912
+ continue;
1913
+ }
1914
+ if (inFence) continue;
1915
+ const trimmed = line.trim();
1916
+ if (!trimmed) continue;
1917
+ if (VOLATILE_NEGATION_RE.test(trimmed)) continue;
1918
+
1919
+ if (VOLATILE_TEMPLATE_RE.test(trimmed)) {
1920
+ findings.push({
1921
+ lineNumber: i + 1,
1922
+ patternKind: 'volatile_template',
1923
+ snippet: trimmed.slice(0, 140)
1924
+ });
1925
+ continue;
1926
+ }
1927
+ if (VOLATILE_INSTRUCTION_RE.test(trimmed)) {
1928
+ findings.push({
1929
+ lineNumber: i + 1,
1930
+ patternKind: 'volatile_instruction',
1931
+ snippet: trimmed.slice(0, 140)
1932
+ });
1933
+ }
1934
+ }
1935
+
1936
+ return {
1937
+ matched: findings.length > 0,
1938
+ findings
1939
+ };
1940
+ }
1941
+
1942
+ /**
1943
+ * BO-CFG-11: Audits active always-on rules files and `SessionStart` hook commands
1944
+ * for volatile timestamps, dates, or UUIDs that bust the token-0 prompt prefix.
1945
+ */
1946
+ export function auditVolatilePromptPrefix({
1947
+ ruleFilePaths = [],
1948
+ settingsLayers = [],
1949
+ harness = 'claude-code'
1950
+ } = {}) {
1951
+ const seen = new Set();
1952
+ const findings = [];
1953
+ const lints = [];
1954
+ const remediation =
1955
+ 'Remove dynamic timestamps/UUIDs from static rules or SessionStart hooks; append turn-specific metadata at the tail of user turns if needed.';
1956
+
1957
+ for (const fp of ruleFilePaths) {
1958
+ if (!fp || !fs.existsSync(fp)) continue;
1959
+ let dedupeKey = canonicalizePath(fp);
1960
+ try {
1961
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
1962
+ } catch {
1963
+ // ignore: fallback to canonicalized path when realpath fails
1964
+ }
1965
+ if (seen.has(dedupeKey)) continue;
1966
+ seen.add(dedupeKey);
1967
+
1968
+ try {
1969
+ const text = fs.readFileSync(fp, 'utf8');
1970
+ if (harness === 'antigravity') {
1971
+ const triggerMode = parseRuleTriggerMode(text);
1972
+ if (triggerMode === 'model_decision' || triggerMode === 'manual') continue;
1973
+ }
1974
+ const scan = scanVolatilePromptPatterns(text);
1975
+ if (scan.matched) {
1976
+ const normFile = String(fp).replace(/\\/g, '/');
1977
+ const first = scan.findings[0];
1978
+ findings.push({
1979
+ file: normFile,
1980
+ sourceType: 'rules_file',
1981
+ matches: scan.findings
1982
+ });
1983
+ lints.push({
1984
+ ruleId: 'BO-CFG-11',
1985
+ severity: 'warn',
1986
+ harness,
1987
+ file: normFile,
1988
+ 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.`,
1989
+ remediation
1990
+ });
1991
+ }
1992
+ } catch {
1993
+ // ignore: unreadable rules markdown file
1994
+ }
1995
+ }
1996
+
1997
+ for (const layerEntry of settingsLayers) {
1998
+ const doc = layerEntry?.doc?.parsed;
1999
+ if (!doc || typeof doc !== 'object') continue;
2000
+ const fileLabel = String(layerEntry?.label || layerEntry?.doc?.path || 'settings.json').replace(/\\/g, '/');
2001
+ const sessionStartHooks = doc?.hooks?.SessionStart;
2002
+ if (!Array.isArray(sessionStartHooks)) continue;
2003
+ const matchedCmds = [];
2004
+ for (const entry of sessionStartHooks) {
2005
+ const hookList = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
2006
+ for (const h of hookList) {
2007
+ const cmd = typeof h?.command === 'string' ? h.command.trim() : '';
2008
+ if (cmd && SESSION_START_VOLATILE_CMD_RE.test(cmd)) {
2009
+ matchedCmds.push(cmd.slice(0, 140));
2010
+ }
2011
+ }
2012
+ }
2013
+ if (matchedCmds.length > 0) {
2014
+ findings.push({
2015
+ file: fileLabel,
2016
+ sourceType: 'session_start_hook',
2017
+ commands: matchedCmds
2018
+ });
2019
+ lints.push({
2020
+ ruleId: 'BO-CFG-11',
2021
+ severity: 'warn',
2022
+ harness,
2023
+ file: fileLabel,
2024
+ 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.`,
2025
+ remediation
2026
+ });
2027
+ }
2028
+ }
2029
+
2030
+ return {
2031
+ status: lints.length > 0 ? 'warn' : 'pass',
2032
+ findings,
2033
+ lints
2034
+ };
2035
+ }
2036
+
2037
+ function makeMissingJsoncStub(filePath = '') {
2038
+ return {
2039
+ path: filePath,
2040
+ exists: false,
2041
+ parseOk: false,
2042
+ parsed: null,
2043
+ strictJsonValid: false,
2044
+ strict_json_syntax_warning: null,
2045
+ error: null
2046
+ };
2047
+ }
2048
+
2049
+ function filterFilesWithinCwd(filePaths = [], cwd = process.cwd()) {
2050
+ const resolvedCwd = path.resolve(cwd);
2051
+ return (Array.isArray(filePaths) ? filePaths : []).filter((fp) => {
2052
+ if (!fp) return false;
2053
+ const rel = path.relative(resolvedCwd, path.resolve(fp));
2054
+ return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
2055
+ });
2056
+ }
2057
+
2058
+ function createEmptyClaudeTelemetryStub() {
2059
+ return {
2060
+ sessionsScanned: 0,
2061
+ bytesScanned: 0,
2062
+ scanTruncated: false,
2063
+ browserToolCalls7d: 0,
2064
+ artifactCalls7d: 0,
2065
+ mcpToolCalls7d: {},
2066
+ schemaTokensByServer: {},
2067
+ observedMcpToolNames: [],
2068
+ runtimeListChangedServers: [],
2069
+ maxCachedPrefixTokens: 0,
2070
+ subagentSpawns7d: 0,
2071
+ sidechainTurns7d: 0,
2072
+ observedMcpInstructionsDeltaChars: 0,
2073
+ observedModels: [],
2074
+ entrypoints: ['cli'],
2075
+ sdkCliSessions7d: 0,
2076
+ claudeCodeVersion: null
2077
+ };
2078
+ }
2079
+
1880
2080
  /**
1881
2081
  * Runs Turn-0 startup config, rules-count, and eager-only MCP audit for Claude Code.
1882
2082
  */
@@ -1890,16 +2090,21 @@ export function runClaudeStartupAudit({
1890
2090
  nowMs = Date.now(),
1891
2091
  manifestDirs = [],
1892
2092
  maxTelemetryFiles = DEFAULT_TELEMETRY_MAX_FILES,
1893
- maxTelemetryBytes = DEFAULT_TELEMETRY_MAX_BYTES
2093
+ maxTelemetryBytes = DEFAULT_TELEMETRY_MAX_BYTES,
2094
+ repoOnly = false,
2095
+ ci = false
1894
2096
  } = {}) {
2097
+ const isRepoOnly = Boolean(repoOnly || ci);
1895
2098
  const paths = resolveClaudeConfigPaths({ homeDir, cwd, platform: hostPlatform });
1896
- const telemetry = scanClaudeTelemetrySummary({
1897
- projectsDir: paths.projectsDir,
1898
- days,
1899
- nowMs,
1900
- maxFiles: maxTelemetryFiles,
1901
- maxTotalBytes: maxTelemetryBytes
1902
- });
2099
+ const telemetry = isRepoOnly
2100
+ ? createEmptyClaudeTelemetryStub()
2101
+ : scanClaudeTelemetrySummary({
2102
+ projectsDir: paths.projectsDir,
2103
+ days,
2104
+ nowMs,
2105
+ maxFiles: maxTelemetryFiles,
2106
+ maxTotalBytes: maxTelemetryBytes
2107
+ });
1903
2108
 
1904
2109
  const detectedClaudeVersion = claudeCodeVersion || telemetry.claudeCodeVersion || null;
1905
2110
  const observedEntrypoint =
@@ -1907,24 +2112,32 @@ export function runClaudeStartupAudit({
1907
2112
  ? 'sdk-ts'
1908
2113
  : telemetry.entrypoints[0] || 'cli';
1909
2114
 
1910
- const claudeJson = parseJsoncReadOnly(paths.claudeJson);
1911
- const userSettings = parseJsoncReadOnly(paths.userSettings);
2115
+ const claudeJson = isRepoOnly
2116
+ ? makeMissingJsoncStub(paths.claudeJson)
2117
+ : parseJsoncReadOnly(paths.claudeJson);
2118
+ const userSettings = isRepoOnly
2119
+ ? makeMissingJsoncStub(paths.userSettings)
2120
+ : parseJsoncReadOnly(paths.userSettings);
1912
2121
  const projectSettings = parseJsoncReadOnly(paths.projectSettings);
1913
2122
  const projectLocalSettings = parseJsoncReadOnly(paths.projectLocalSettings);
1914
2123
  const projectMcp = parseJsoncReadOnly(paths.projectMcpJson);
1915
- const settingsLayers = [
1916
- { doc: userSettings, label: '~/.claude/settings.json' },
1917
- { doc: projectSettings, label: '.claude/settings.json' },
1918
- { doc: projectLocalSettings, label: '.claude/settings.local.json' }
1919
- ];
1920
- const layers = [userSettings.parsed, projectSettings.parsed, projectLocalSettings.parsed].filter(Boolean);
2124
+ const settingsLayers = isRepoOnly
2125
+ ? [
2126
+ { doc: projectSettings, label: '.claude/settings.json' },
2127
+ { doc: projectLocalSettings, label: '.claude/settings.local.json' }
2128
+ ]
2129
+ : [
2130
+ { doc: userSettings, label: '~/.claude/settings.json' },
2131
+ { doc: projectSettings, label: '.claude/settings.json' },
2132
+ { doc: projectLocalSettings, label: '.claude/settings.local.json' }
2133
+ ];
2134
+ const layers = isRepoOnly
2135
+ ? [projectSettings.parsed, projectLocalSettings.parsed].filter(Boolean)
2136
+ : [userSettings.parsed, projectSettings.parsed, projectLocalSettings.parsed].filter(Boolean);
2137
+ const scopedRulesFiles = isRepoOnly ? filterFilesWithinCwd(paths.rulesFiles, paths.cwd) : paths.rulesFiles;
1921
2138
 
1922
2139
  const chromeOnDemandCmd = buildClaudeCliCommand(['--chrome'], { platform: hostPlatform });
1923
2140
  const artifactDisallowedCmd = buildClaudeCliCommand(['--disallowedTools', 'Artifact'], { platform: hostPlatform });
1924
- const bundledSessionCmd = buildClaudeCliCommand(
1925
- ['--settings', { disableBundledSkills: true, disableWorkflows: true }],
1926
- { platform: hostPlatform }
1927
- );
1928
2141
 
1929
2142
  // Check 1: Chrome default enabled strictly in ~/.claude.json
1930
2143
  const chromeVal = claudeJson.parsed?.claudeInChromeDefaultEnabled === true;
@@ -1944,6 +2157,7 @@ export function runClaudeStartupAudit({
1944
2157
  };
1945
2158
 
1946
2159
  // Check 2: Artifact built-in tool & one-way global lock
2160
+ // Only warn when explicitly configured with deprecated `disableArtifact: true` or backed by observed local telemetry.
1947
2161
  let enableArtifactValue = null;
1948
2162
  let deprecatedDisableArtifactPresent = false;
1949
2163
  for (const layer of layers) {
@@ -1952,13 +2166,14 @@ export function runClaudeStartupAudit({
1952
2166
  }
1953
2167
  const sdkTsDropsArtifact =
1954
2168
  observedEntrypoint === 'sdk-ts' && String(env?.CLAUDE_CODE_ARTIFACT || '').trim() !== '1';
2169
+ const hasObservedTelemetry = telemetry.sessionsScanned > 0;
1955
2170
  let artifactStatus = 'pass';
1956
2171
  let artifactReclaimable = 0;
1957
2172
  if (deprecatedDisableArtifactPresent) {
1958
2173
  artifactStatus = 'warn';
1959
2174
  artifactReclaimable =
1960
2175
  enableArtifactValue === false ? 0 : CALIBRATION_MANIFEST.claudeCodeTurn0.artifactTool.tokens;
1961
- } else if (!sdkTsDropsArtifact && enableArtifactValue !== false && telemetry.artifactCalls7d === 0) {
2176
+ } else if (hasObservedTelemetry && !sdkTsDropsArtifact && enableArtifactValue !== false && telemetry.artifactCalls7d === 0) {
1962
2177
  artifactStatus = 'warn';
1963
2178
  artifactReclaimable = CALIBRATION_MANIFEST.claudeCodeTurn0.artifactTool.tokens;
1964
2179
  }
@@ -1979,13 +2194,12 @@ export function runClaudeStartupAudit({
1979
2194
  ...(deprecatedDisableArtifactPresent
1980
2195
  ? { migrateDeprecated: 'Replace deprecated "disableArtifact": true with "enableArtifact": false in ~/.claude/settings.json.' }
1981
2196
  : {}),
1982
- neverUseArtifacts: 'Set "enableArtifact": false in ~/.claude/settings.json (permanent one-way global lock).',
1983
2197
  occasionalArtifacts: `Leave "enableArtifact" unset and run terminal coding with: ${artifactDisallowedCmd}`
1984
2198
  }
1985
2199
  : null
1986
2200
  };
1987
2201
 
1988
- // Check 3: Bundled skills & workflows
2202
+ // Check 3: Repo-local Turn-0 focus (suppress speculative global findings & unverified global keys)
1989
2203
  let disableBundledSkills = false;
1990
2204
  let workflowsDisabled = false;
1991
2205
  for (const layer of layers) {
@@ -1993,22 +2207,16 @@ export function runClaudeStartupAudit({
1993
2207
  if (layer.disableWorkflows === true || layer.enableWorkflows === false) workflowsDisabled = true;
1994
2208
  }
1995
2209
  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
2210
  const bundledSkillsAndWorkflows = {
2001
- status: bundledStatus,
2211
+ status: 'pass',
2002
2212
  disableBundledSkills,
2003
2213
  workflowsDisabled,
2004
2214
  repoMentionsAnthropicSdk,
2005
2215
  priority: repoMentionsAnthropicSdk ? 'high' : 'normal',
2006
- reclaimableTokensPerTurn: bundledReclaimable,
2216
+ reclaimableTokensPerTurn: 0,
2007
2217
  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
2218
+ unverifiedGlobalKeysRemoved: true,
2219
+ fix: null
2012
2220
  };
2013
2221
 
2014
2222
  // Check 4: Eager-only MCP gate
@@ -2024,19 +2232,24 @@ export function runClaudeStartupAudit({
2024
2232
  schemaTokensByServer: telemetry.schemaTokensByServer
2025
2233
  });
2026
2234
 
2027
- const rulesBucket = auditRulesFiles(paths.rulesFiles);
2028
- const strictJsonSyntax = collectStrictJsonLints([
2029
- { res: claudeJson },
2030
- { res: userSettings },
2031
- { res: projectSettings },
2032
- { res: projectLocalSettings },
2033
- { res: projectMcp }
2034
- ]);
2235
+ const rulesBucket = auditRulesFiles(scopedRulesFiles);
2236
+ const strictJsonSyntax = collectStrictJsonLints(
2237
+ isRepoOnly
2238
+ ? [{ res: projectSettings }, { res: projectLocalSettings }, { res: projectMcp }]
2239
+ : [
2240
+ { res: claudeJson },
2241
+ { res: userSettings },
2242
+ { res: projectSettings },
2243
+ { res: projectLocalSettings },
2244
+ { res: projectMcp }
2245
+ ]
2246
+ );
2035
2247
  const localSettingsSecrets = auditLocalSettingsSecrets(projectLocalSettings, paths.cwd);
2036
2248
  const mcpToolViolations = scanMcpToolNameLengthViolations({
2037
2249
  homeDir: paths.homeDir,
2038
2250
  workspacePath: paths.cwd,
2039
- observedToolNames: telemetry.observedMcpToolNames || []
2251
+ observedToolNames: telemetry.observedMcpToolNames || [],
2252
+ repoOnly: isRepoOnly
2040
2253
  });
2041
2254
  const mcpToolNameLength = {
2042
2255
  status: mcpToolViolations.violations.length > 0 ? 'warn' : 'pass',
@@ -2048,11 +2261,13 @@ export function runClaudeStartupAudit({
2048
2261
  workspacePath: paths.cwd,
2049
2262
  manifestDirs,
2050
2263
  runtimeListChangedServers: telemetry.runtimeListChangedServers,
2051
- maxObservedCachedPrefixTokens: telemetry.maxCachedPrefixTokens
2264
+ maxObservedCachedPrefixTokens: telemetry.maxCachedPrefixTokens,
2265
+ repoOnly: isRepoOnly
2052
2266
  });
2053
2267
  const customAgents = scanClaudeCustomAgentSpecs({
2054
2268
  homeDir: paths.homeDir,
2055
- cwd: paths.cwd
2269
+ cwd: paths.cwd,
2270
+ repoOnly: isRepoOnly
2056
2271
  });
2057
2272
  const subagentCount =
2058
2273
  telemetry.subagentSpawns7d ||
@@ -2076,6 +2291,11 @@ export function runClaudeStartupAudit({
2076
2291
  observedModels: telemetry.observedModels || [],
2077
2292
  maxObservedPrefixTokens: telemetry.maxCachedPrefixTokens
2078
2293
  });
2294
+ const volatilePrefix = auditVolatilePromptPrefix({
2295
+ ruleFilePaths: scopedRulesFiles,
2296
+ settingsLayers,
2297
+ harness: 'claude-code'
2298
+ });
2079
2299
  const sdkCliDetected = telemetry.entrypoints.includes('sdk-cli');
2080
2300
  const sdkCliSessionsCount = telemetry.sdkCliSessions7d || (sdkCliDetected ? 1 : 0);
2081
2301
  const sdkCliQuotaHeuristic = {
@@ -2093,7 +2313,8 @@ export function runClaudeStartupAudit({
2093
2313
  ...strictJsonSyntax.lints,
2094
2314
  ...misplacedChromeKey.lints,
2095
2315
  ...localSettingsSecrets.lints,
2096
- ...idleCompactionRoi.lints
2316
+ ...idleCompactionRoi.lints,
2317
+ ...volatilePrefix.lints
2097
2318
  ];
2098
2319
  if (mcpStartupTax.gateReasons.includes('ssh_forced_disable_experimental_betas')) {
2099
2320
  lints.push({
@@ -2218,6 +2439,7 @@ export function runClaudeStartupAudit({
2218
2439
  localSettingsSecrets,
2219
2440
  deprecatedModelsAndFlags,
2220
2441
  idleCompactionRoi,
2442
+ volatilePrefix,
2221
2443
  sdkCliQuotaHeuristic
2222
2444
  }
2223
2445
  },
@@ -2271,19 +2493,23 @@ export function formatClaudeStartupAuditReport(report) {
2271
2493
  if (c.artifactTool.fixes?.migrateDeprecated) {
2272
2494
  lines.push(` Fix (migrate): ${c.artifactTool.fixes.migrateDeprecated}`);
2273
2495
  }
2274
- lines.push(` Fix (never use): ${c.artifactTool.fixes?.neverUseArtifacts}`);
2275
- lines.push(` Fix (occasional): ${c.artifactTool.fixes?.occasionalArtifacts}`);
2496
+ if (c.artifactTool.fixes?.neverUseArtifacts) {
2497
+ lines.push(` Fix (never use): ${c.artifactTool.fixes.neverUseArtifacts}`);
2498
+ }
2499
+ if (c.artifactTool.fixes?.occasionalArtifacts) {
2500
+ lines.push(` Fix (occasional): ${c.artifactTool.fixes.occasionalArtifacts}`);
2501
+ }
2276
2502
  } else {
2277
2503
  lines.push(` - [pass] Artifact tool (${c.artifactTool.entrypoint})`);
2278
2504
  }
2279
- if (c.bundledSkillsAndWorkflows.status === 'warn') {
2505
+ if (c.bundledSkillsAndWorkflows.status === 'warn' && c.bundledSkillsAndWorkflows.fix) {
2280
2506
  const prio = c.bundledSkillsAndWorkflows.priority === 'high' ? ' [HIGH: Anthropic SDK markers detected]' : '';
2281
2507
  lines.push(
2282
2508
  ` - [warn] Bundled skills/workflows enabled${prio} (~${c.bundledSkillsAndWorkflows.reclaimableTokensPerTurn} tok/turn est.)`
2283
2509
  );
2284
2510
  lines.push(` Fix: ${c.bundledSkillsAndWorkflows.fix}`);
2285
2511
  } else {
2286
- lines.push(' - [pass] Bundled skills & workflows disabled');
2512
+ lines.push(' - [pass] Repo-local Turn-0 focus (no unverified global settings keys recommended)');
2287
2513
  }
2288
2514
  if (c.subagentMcpInstructionsTax?.triggered) {
2289
2515
  lines.push(
@@ -2319,6 +2545,423 @@ export function formatClaudeStartupAuditReport(report) {
2319
2545
  return lines.join('\n') + '\n';
2320
2546
  }
2321
2547
 
2548
+ function listMarkdownFilesInDir(dirPath) {
2549
+ if (!dirPath || !fs.existsSync(dirPath)) return [];
2550
+ try {
2551
+ return fs
2552
+ .readdirSync(dirPath, { withFileTypes: true })
2553
+ .filter((e) => e.isFile() && /\.md$/i.test(e.name))
2554
+ .map((e) => path.join(dirPath, e.name));
2555
+ } catch {
2556
+ return []; // ignore: unreadable rules directory
2557
+ }
2558
+ }
2559
+
2560
+ function parseRuleTriggerMode(markdown = '') {
2561
+ const m = String(markdown || '').match(/^---\s*\r?\n([\s\S]*?)\r?\n---/);
2562
+ if (!m) return 'always_on';
2563
+ const trig = m[1].match(/^\s*trigger\s*:\s*([^\r\n#]+)/im);
2564
+ if (!trig) return 'always_on';
2565
+ return trig[1].trim().toLowerCase() || 'always_on';
2566
+ }
2567
+
2568
+ function auditAntigravityRulesFiles(filePaths = []) {
2569
+ const seen = new Set();
2570
+ const files = [];
2571
+ let totalTokensEst = 0;
2572
+ let totalRuleCount = 0;
2573
+ let onDemandCount = 0;
2574
+
2575
+ for (const fp of filePaths) {
2576
+ if (!fp || !fs.existsSync(fp)) continue;
2577
+ let dedupeKey = canonicalizePath(fp);
2578
+ try {
2579
+ dedupeKey = canonicalizePath(fs.realpathSync(fp));
2580
+ } catch {
2581
+ // ignore: fallback to canonicalized path when realpath fails
2582
+ }
2583
+ if (seen.has(dedupeKey)) continue;
2584
+ seen.add(dedupeKey);
2585
+
2586
+ try {
2587
+ const text = fs.readFileSync(fp, 'utf8');
2588
+ const triggerMode = parseRuleTriggerMode(text);
2589
+ const chars = text.length;
2590
+ const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
2591
+ const ruleCount = countDiscreteRules(text);
2592
+ const isAlwaysOn = triggerMode !== 'model_decision' && triggerMode !== 'manual';
2593
+ files.push({
2594
+ path: String(fp).replace(/\\/g, '/'),
2595
+ triggerMode,
2596
+ alwaysOn: isAlwaysOn,
2597
+ chars,
2598
+ tokensEst,
2599
+ ruleCount
2600
+ });
2601
+ if (isAlwaysOn) {
2602
+ totalTokensEst += tokensEst;
2603
+ totalRuleCount += ruleCount;
2604
+ } else {
2605
+ onDemandCount += 1;
2606
+ }
2607
+ } catch {
2608
+ // ignore: unreadable Antigravity rule markdown
2609
+ }
2610
+ }
2611
+
2612
+ let status = 'pass';
2613
+ const advisories = [];
2614
+ if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
2615
+ status = 'warn';
2616
+ advisories.push(
2617
+ `IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} always-on rules); set trigger: model_decision or move domain rules into skills.`
2618
+ );
2619
+ } else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
2620
+ status = 'caution';
2621
+ advisories.push(
2622
+ `Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} always-on rules).`
2623
+ );
2624
+ }
2625
+ if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
2626
+ status = 'warn';
2627
+ advisories.push(
2628
+ `Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across always-on Antigravity rules).`
2629
+ );
2630
+ }
2631
+
2632
+ return { files, totalTokensEst, totalRuleCount, onDemandCount, status, advisories };
2633
+ }
2634
+
2635
+ /**
2636
+ * Runs Turn-0 startup config, rules-count, and MCP config audit for Google Antigravity.
2637
+ */
2638
+ export function runAntigravityStartupAudit({
2639
+ homeDir = getHomeDir(),
2640
+ cwd = process.cwd(),
2641
+ hostPlatform = process.platform,
2642
+ nowMs = Date.now(),
2643
+ repoOnly = false,
2644
+ ci = false
2645
+ } = {}) {
2646
+ const isRepoOnly = Boolean(repoOnly || ci);
2647
+ const paths = resolveAntigravityConfigPaths({ homeDir, cwd, platform: hostPlatform });
2648
+ const projectHooks = parseJsoncReadOnly(paths.projectHooksJson);
2649
+ const userHooks = isRepoOnly
2650
+ ? makeMissingJsoncStub(paths.userHooksJson)
2651
+ : parseJsoncReadOnly(paths.userHooksJson);
2652
+ const projectMcp = parseJsoncReadOnly(paths.projectMcpJson);
2653
+ const userMcp = isRepoOnly
2654
+ ? makeMissingJsoncStub(paths.userMcpJson)
2655
+ : parseJsoncReadOnly(paths.userMcpJson);
2656
+
2657
+ const ruleFiles = isRepoOnly
2658
+ ? filterFilesWithinCwd([...paths.rulesFiles, ...listMarkdownFilesInDir(paths.projectRulesDir)], cwd)
2659
+ : [
2660
+ ...paths.rulesFiles,
2661
+ ...listMarkdownFilesInDir(paths.projectRulesDir),
2662
+ ...listMarkdownFilesInDir(paths.globalRulesDir)
2663
+ ];
2664
+ const rulesBucket = auditAntigravityRulesFiles(ruleFiles);
2665
+ const strictJsonSyntax = collectStrictJsonLints(
2666
+ isRepoOnly
2667
+ ? [{ res: projectHooks }, { res: projectMcp }]
2668
+ : [
2669
+ { res: projectHooks },
2670
+ { res: userHooks },
2671
+ { res: projectMcp },
2672
+ { res: userMcp }
2673
+ ]
2674
+ );
2675
+ const volatilePrefix = auditVolatilePromptPrefix({
2676
+ ruleFilePaths: ruleFiles,
2677
+ settingsLayers: isRepoOnly
2678
+ ? [{ label: paths.projectHooksJson, doc: projectHooks }]
2679
+ : [
2680
+ { label: paths.projectHooksJson, doc: projectHooks },
2681
+ { label: paths.userHooksJson, doc: userHooks }
2682
+ ],
2683
+ harness: 'antigravity'
2684
+ });
2685
+
2686
+ const configuredServers = [];
2687
+ for (const src of [userMcp.parsed, projectMcp.parsed]) {
2688
+ if (src && typeof src.mcpServers === 'object' && !Array.isArray(src.mcpServers)) {
2689
+ for (const [name, cfg] of Object.entries(src.mcpServers)) {
2690
+ if (cfg && cfg.disabled !== true) {
2691
+ configuredServers.push(name);
2692
+ }
2693
+ }
2694
+ }
2695
+ }
2696
+ const uniqueServers = [...new Set(configuredServers)];
2697
+ const mcpTaxTokens = uniqueServers.length * DEFAULT_MCP_INSTRUCTIONS_TOKENS_PER_SERVER;
2698
+ const mcpStatus = uniqueServers.length >= SUBAGENT_MCP_MIN_SERVERS ? 'warn' : 'pass';
2699
+ const mcpCheck = {
2700
+ status: mcpStatus,
2701
+ configuredServerNames: uniqueServers,
2702
+ startupTaxTokensPerTurn: mcpTaxTokens,
2703
+ isEstimated: true,
2704
+ summaryLine: `Antigravity MCP servers active: ${uniqueServers.length} (~${mcpTaxTokens} est. tok/turn)`
2705
+ };
2706
+
2707
+ const lints = [...strictJsonSyntax.lints, ...volatilePrefix.lints];
2708
+ let issueCount = lints.length;
2709
+ let estimatedTurn0ReclaimableTokens = 0;
2710
+ if (mcpStatus === 'warn') {
2711
+ issueCount += 1;
2712
+ estimatedTurn0ReclaimableTokens += mcpTaxTokens;
2713
+ }
2714
+ if (rulesBucket.status === 'warn' || rulesBucket.status === 'caution') {
2715
+ issueCount += 1;
2716
+ }
2717
+
2718
+ return {
2719
+ ok: true,
2720
+ schemaVersion: '1.0.0',
2721
+ platform: hostPlatform,
2722
+ harnessesAudited: ['antigravity'],
2723
+ antigravity: {
2724
+ configFiles: {
2725
+ projectHooks: formatConfigStatus(projectHooks),
2726
+ userHooks: formatConfigStatus(userHooks),
2727
+ projectMcp: formatConfigStatus(projectMcp),
2728
+ userMcp: formatConfigStatus(userMcp)
2729
+ },
2730
+ checks: {
2731
+ mcpCheck,
2732
+ strictJsonSyntax,
2733
+ volatilePrefix
2734
+ }
2735
+ },
2736
+ rulesAudit: {
2737
+ thresholds: RULES_THRESHOLDS,
2738
+ byHarness: {
2739
+ antigravity: rulesBucket
2740
+ }
2741
+ },
2742
+ lints,
2743
+ summary: {
2744
+ issueCount,
2745
+ estimatedTurn0ReclaimableTokens,
2746
+ estimatedWeeklySavingsUsd: estimateWeeklySavingsUsd(estimatedTurn0ReclaimableTokens, nowMs)
2747
+ }
2748
+ };
2749
+ }
2750
+
2751
+ /**
2752
+ * Formats `runAntigravityStartupAudit()` for terminal output.
2753
+ */
2754
+ export function formatAntigravityStartupAuditReport(report) {
2755
+ if (!report?.ok) return 'Burnoff Antigravity Startup Audit failed\n';
2756
+ const s = report.summary || {};
2757
+ const c = report.antigravity?.checks;
2758
+ const r = report.rulesAudit?.byHarness?.antigravity;
2759
+ const lines = [
2760
+ `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)`
2761
+ ];
2762
+ if (c?.mcpCheck) {
2763
+ lines.push(` - [${c.mcpCheck.status}] ${c.mcpCheck.summaryLine}`);
2764
+ }
2765
+ if (r) {
2766
+ lines.push(
2767
+ ` - Rules [${r.status}]: ${r.files.length} file(s), ${r.totalRuleCount} always-on rules (${r.onDemandCount} on-demand), ~${r.totalTokensEst.toLocaleString('en-US')} est. tokens`
2768
+ );
2769
+ for (const adv of r.advisories || []) {
2770
+ lines.push(` Advisories: ${adv}`);
2771
+ }
2772
+ }
2773
+ if (Array.isArray(report.lints) && report.lints.length > 0) {
2774
+ lines.push(' JSON & Config Lints:');
2775
+ for (const l of report.lints) {
2776
+ lines.push(` - [${l.severity}] ${l.ruleId}: ${l.message}`);
2777
+ }
2778
+ }
2779
+ return lines.join('\n') + '\n';
2780
+ }
2781
+
2782
+ /**
2783
+ * Unified startup audit supporting `--client claude|antigravity|both|auto`.
2784
+ */
2785
+ export function runStartupAudit(options = {}) {
2786
+ const cwd = path.resolve(options.cwd || process.cwd());
2787
+ const homeDir = options.homeDir || getHomeDir();
2788
+ const isRepoOnly = Boolean(options.repoOnly || options.ci);
2789
+ const rawClient = String(options.client || 'auto').trim().toLowerCase();
2790
+
2791
+ let target = rawClient;
2792
+ if (rawClient === 'auto') {
2793
+ const hasAg = isRepoOnly
2794
+ ? fs.existsSync(path.join(cwd, '.agents')) || fs.existsSync(path.join(cwd, 'GEMINI.md'))
2795
+ : fs.existsSync(path.join(cwd, '.agents')) ||
2796
+ fs.existsSync(path.join(cwd, 'GEMINI.md')) ||
2797
+ fs.existsSync(path.join(homeDir, '.gemini', 'config', 'hooks.json'));
2798
+ const hasClaude = isRepoOnly
2799
+ ? fs.existsSync(path.join(cwd, '.claude')) ||
2800
+ fs.existsSync(path.join(cwd, 'CLAUDE.md')) ||
2801
+ fs.existsSync(path.join(cwd, '.mcp.json'))
2802
+ : fs.existsSync(path.join(cwd, '.claude')) || fs.existsSync(path.join(homeDir, '.claude'));
2803
+ if (hasAg && hasClaude) target = 'both';
2804
+ else if (hasAg) target = 'antigravity';
2805
+ else target = 'claude';
2806
+ }
2807
+
2808
+ const forwardedOpts = { ...options, repoOnly: isRepoOnly };
2809
+ if (target === 'antigravity' || target === 'ag') {
2810
+ return runAntigravityStartupAudit(forwardedOpts);
2811
+ }
2812
+ if (target === 'both') {
2813
+ const claudeReport = runClaudeStartupAudit(forwardedOpts);
2814
+ const agReport = runAntigravityStartupAudit(forwardedOpts);
2815
+ const claudeLints = claudeReport.lints || [];
2816
+ const agLints = agReport.lints || [];
2817
+ return {
2818
+ ...claudeReport,
2819
+ harnessesAudited: ['claude-code', 'antigravity'],
2820
+ antigravity: agReport.antigravity,
2821
+ rulesAudit: {
2822
+ thresholds: RULES_THRESHOLDS,
2823
+ byHarness: {
2824
+ ...claudeReport.rulesAudit.byHarness,
2825
+ ...agReport.rulesAudit.byHarness
2826
+ }
2827
+ },
2828
+ lints: [...claudeLints, ...agLints],
2829
+ lintsByHarness: {
2830
+ 'claude-code': claudeLints,
2831
+ antigravity: agLints
2832
+ },
2833
+ summaryByHarness: {
2834
+ 'claude-code': claudeReport.summary,
2835
+ antigravity: agReport.summary
2836
+ },
2837
+ summary: {
2838
+ issueCount: (claudeReport.summary?.issueCount || 0) + (agReport.summary?.issueCount || 0),
2839
+ estimatedTurn0ReclaimableTokens:
2840
+ (claudeReport.summary?.estimatedTurn0ReclaimableTokens || 0) +
2841
+ (agReport.summary?.estimatedTurn0ReclaimableTokens || 0),
2842
+ estimatedWeeklySavingsUsd: Number(
2843
+ ((claudeReport.summary?.estimatedWeeklySavingsUsd || 0) +
2844
+ (agReport.summary?.estimatedWeeklySavingsUsd || 0)).toFixed(2)
2845
+ )
2846
+ }
2847
+ };
2848
+ }
2849
+ return runClaudeStartupAudit(options);
2850
+ }
2851
+
2852
+ export function formatStartupAuditReport(report) {
2853
+ if (report?.harnessesAudited?.length === 1 && report.harnessesAudited[0] === 'antigravity') {
2854
+ return formatAntigravityStartupAuditReport(report);
2855
+ }
2856
+ if (report?.harnessesAudited?.includes('antigravity') && report?.claudeCode) {
2857
+ const claudeSummary = report.summaryByHarness?.['claude-code'] || report.summary;
2858
+ const agSummary = report.summaryByHarness?.antigravity || report.summary;
2859
+ const claudeLints =
2860
+ report.lintsByHarness?.['claude-code'] ||
2861
+ (report.lints || []).filter((l) => !(l.file?.includes('.agents') || l.file?.includes('.gemini')));
2862
+ const agLints =
2863
+ report.lintsByHarness?.antigravity ||
2864
+ (report.lints || []).filter((l) => l.file?.includes('.agents') || l.file?.includes('.gemini'));
2865
+ return (
2866
+ formatClaudeStartupAuditReport({
2867
+ ...report,
2868
+ lints: claudeLints,
2869
+ summary: claudeSummary
2870
+ }) +
2871
+ '\n' +
2872
+ formatAntigravityStartupAuditReport({
2873
+ ok: report.ok,
2874
+ antigravity: report.antigravity,
2875
+ rulesAudit: report.rulesAudit,
2876
+ lints: agLints,
2877
+ summary: agSummary
2878
+ })
2879
+ );
2880
+ }
2881
+ return formatClaudeStartupAuditReport(report);
2882
+ }
2883
+
2884
+ function escapeGhAnnotationValue(text = '') {
2885
+ return String(text || '')
2886
+ .replace(/%/g, '%25')
2887
+ .replace(/\r/g, '%0D')
2888
+ .replace(/\n/g, '%0A');
2889
+ }
2890
+
2891
+ function toRepoRelativePath(filePath, cwd = process.cwd()) {
2892
+ const raw = String(filePath || '').trim();
2893
+ if (!raw) return '.';
2894
+ if (!path.isAbsolute(raw)) return raw.replace(/\\/g, '/');
2895
+ const resolvedCwd = path.resolve(cwd);
2896
+ const rel = path.relative(resolvedCwd, path.resolve(raw));
2897
+ if (rel && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)) {
2898
+ return rel.replace(/\\/g, '/');
2899
+ }
2900
+ return raw.replace(/\\/g, '/');
2901
+ }
2902
+
2903
+ /**
2904
+ * Evaluates a `runStartupAudit({ ci: true })` report for CI pass/warn/fail exit codes
2905
+ * and formats GitHub Actions `::error` / `::warning` workflow annotations.
2906
+ */
2907
+ export function evaluateStartupAuditCi(report = {}, { strict = false, cwd = process.cwd() } = {}) {
2908
+ const lints = Array.isArray(report?.lints) ? report.lints : [];
2909
+ let errorCount = 0;
2910
+ let warnCount = 0;
2911
+ let infoCount = 0;
2912
+ const annotations = [];
2913
+
2914
+ for (const l of lints) {
2915
+ const sev = String(l?.severity || 'warn').toLowerCase();
2916
+ const rel = toRepoRelativePath(l?.file || '.', cwd);
2917
+ const ruleId = String(l?.ruleId || 'BO-CFG');
2918
+ const msg = escapeGhAnnotationValue(l?.message || ruleId);
2919
+ if (sev === 'error') {
2920
+ errorCount += 1;
2921
+ annotations.push(`::error file=${rel},title=${ruleId}::${msg}`);
2922
+ } else if (sev === 'info') {
2923
+ infoCount += 1;
2924
+ } else {
2925
+ warnCount += 1;
2926
+ annotations.push(`::warning file=${rel},title=${ruleId}::${msg}`);
2927
+ }
2928
+ }
2929
+
2930
+ for (const harnessKey of ['claudeCode', 'antigravity']) {
2931
+ const bucket = report?.rulesAudit?.byHarness?.[harnessKey];
2932
+ if (bucket && bucket.status === 'warn') {
2933
+ warnCount += 1;
2934
+ const firstFile = bucket.files?.[0]?.path || '.';
2935
+ const rel = toRepoRelativePath(firstFile, cwd);
2936
+ const adv = (bucket.advisories || []).join('; ') || 'Static Turn-0 rule threshold exceeded.';
2937
+ annotations.push(`::warning file=${rel},title=BO-RULE-01::${escapeGhAnnotationValue(adv)}`);
2938
+ }
2939
+ }
2940
+
2941
+ const issueCount = Number(report?.summary?.issueCount || 0);
2942
+ let verdict = 'PASS';
2943
+ let exitCode = 0;
2944
+ if (errorCount > 0 || (Boolean(strict) && (warnCount > 0 || issueCount > 0))) {
2945
+ verdict = 'FAIL';
2946
+ exitCode = 1;
2947
+ } else if (warnCount > 0 || issueCount > 0) {
2948
+ verdict = 'WARN';
2949
+ exitCode = 0;
2950
+ }
2951
+
2952
+ return {
2953
+ verdict,
2954
+ exitCode,
2955
+ strict: Boolean(strict),
2956
+ repoOnly: true,
2957
+ errorCount,
2958
+ warnCount,
2959
+ infoCount,
2960
+ issueCount,
2961
+ annotations
2962
+ };
2963
+ }
2964
+
2322
2965
  export default {
2323
2966
  CALIBRATION_MANIFEST,
2324
2967
  RULES_THRESHOLDS,
@@ -2343,6 +2986,13 @@ export default {
2343
2986
  scanMcpListChangedCapabilities,
2344
2987
  estimateSubagentMcpInstructionsTax,
2345
2988
  auditIdleCompactionConfig,
2989
+ scanVolatilePromptPatterns,
2990
+ auditVolatilePromptPrefix,
2346
2991
  runClaudeStartupAudit,
2347
- formatClaudeStartupAuditReport
2992
+ formatClaudeStartupAuditReport,
2993
+ runAntigravityStartupAudit,
2994
+ formatAntigravityStartupAuditReport,
2995
+ runStartupAudit,
2996
+ formatStartupAuditReport,
2997
+ evaluateStartupAuditCi
2348
2998
  };