chompyy 0.4.7 → 0.6.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/README.md +40 -6
- package/dist/advice.js +2 -1
- package/dist/agentlimits.js +77 -0
- package/dist/agentusage.js +96 -0
- package/dist/appstate.js +72 -5
- package/dist/away.js +44 -5
- package/dist/blueprint.js +3 -7
- package/dist/board.js +4 -0
- package/dist/cli.js +328 -15
- package/dist/codexquota.js +106 -0
- package/dist/codexusage.js +10 -0
- package/dist/config.js +2 -0
- package/dist/context.js +30 -0
- package/dist/costs.js +1 -0
- package/dist/daytime.js +68 -0
- package/dist/demon.js +20 -0
- package/dist/didwork.js +46 -0
- package/dist/label.js +33 -0
- package/dist/learning.js +35 -0
- package/dist/menu.js +17 -0
- package/dist/nightcap.js +60 -0
- package/dist/nudge.js +47 -18
- package/dist/pacing.js +16 -1
- package/dist/questions.js +71 -0
- package/dist/recap.js +74 -0
- package/dist/receipt.js +48 -0
- package/dist/recipe.js +79 -0
- package/dist/send.js +46 -20
- package/dist/stamps.js +14 -0
- package/dist/taste.js +67 -7
- package/dist/triggers.js +5 -0
- package/dist/unkeep.js +220 -0
- package/dist/usage.js +21 -1
- package/dist/vendor/codeburn/antigravity.js +309 -0
- package/dist/vendor/codeburn/codex.js +429 -0
- package/dist/vendor/codeburn/copilot.js +292 -0
- package/dist/vendor/codeburn/gemini.js +195 -0
- package/dist/vendor/codeburn/grokbot.js +182 -0
- package/dist/vendor/codeburn/kimi.js +178 -0
- package/dist/vendor/codeburn/shims/chalk.js +14 -0
- package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
- package/dist/vendor/codeburn/src/act/backup.js +83 -0
- package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
- package/dist/vendor/codeburn/src/act/types.js +37 -0
- package/dist/vendor/codeburn/src/bash-utils.js +204 -0
- package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
- package/dist/vendor/codeburn/src/cache-dir.js +26 -0
- package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
- package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
- package/dist/vendor/codeburn/src/classifier.js +209 -0
- package/dist/vendor/codeburn/src/claude-identity.js +223 -0
- package/dist/vendor/codeburn/src/codex-cache.js +377 -0
- package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
- package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
- package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
- package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
- package/dist/vendor/codeburn/src/compare-stats.js +405 -0
- package/dist/vendor/codeburn/src/config.js +145 -0
- package/dist/vendor/codeburn/src/content-utils.js +56 -0
- package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
- package/dist/vendor/codeburn/src/context-tree.js +664 -0
- package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
- package/dist/vendor/codeburn/src/currency.js +189 -0
- package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
- package/dist/vendor/codeburn/src/cursor-import.js +402 -0
- package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
- package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
- package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
- package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
- package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
- package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
- package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
- package/dist/vendor/codeburn/src/format.js +118 -0
- package/dist/vendor/codeburn/src/fs-utils.js +270 -0
- package/dist/vendor/codeburn/src/git-origin.js +334 -0
- package/dist/vendor/codeburn/src/granular-history.js +328 -0
- package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
- package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
- package/dist/vendor/codeburn/src/live-sessions.js +358 -0
- package/dist/vendor/codeburn/src/math-utils.js +8 -0
- package/dist/vendor/codeburn/src/menubar-json.js +294 -0
- package/dist/vendor/codeburn/src/models.js +1879 -0
- package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
- package/dist/vendor/codeburn/src/optimize.js +4110 -0
- package/dist/vendor/codeburn/src/parse-workers.js +219 -0
- package/dist/vendor/codeburn/src/parser.js +6953 -0
- package/dist/vendor/codeburn/src/path-privacy.js +26 -0
- package/dist/vendor/codeburn/src/plans.js +135 -0
- package/dist/vendor/codeburn/src/pr-signals.js +132 -0
- package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
- package/dist/vendor/codeburn/src/provider-issues.js +30 -0
- package/dist/vendor/codeburn/src/providers/amp.js +286 -0
- package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
- package/dist/vendor/codeburn/src/providers/claude.js +551 -0
- package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
- package/dist/vendor/codeburn/src/providers/cline.js +63 -0
- package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
- package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
- package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
- package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
- package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
- package/dist/vendor/codeburn/src/providers/crush.js +226 -0
- package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
- package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
- package/dist/vendor/codeburn/src/providers/devin.js +569 -0
- package/dist/vendor/codeburn/src/providers/droid.js +324 -0
- package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
- package/dist/vendor/codeburn/src/providers/forge.js +245 -0
- package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
- package/dist/vendor/codeburn/src/providers/goose.js +252 -0
- package/dist/vendor/codeburn/src/providers/grok.js +581 -0
- package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
- package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
- package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
- package/dist/vendor/codeburn/src/providers/index.js +360 -0
- package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
- package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
- package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
- package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
- package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
- package/dist/vendor/codeburn/src/providers/mux.js +242 -0
- package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
- package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
- package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
- package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
- package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
- package/dist/vendor/codeburn/src/providers/pi.js +429 -0
- package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
- package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
- package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
- package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
- package/dist/vendor/codeburn/src/providers/types.js +5 -0
- package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
- package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
- package/dist/vendor/codeburn/src/providers/warp.js +575 -0
- package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
- package/dist/vendor/codeburn/src/providers/zed.js +187 -0
- package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
- package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
- package/dist/vendor/codeburn/src/quota/claude.js +244 -0
- package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
- package/dist/vendor/codeburn/src/quota/security.js +299 -0
- package/dist/vendor/codeburn/src/quota/types.js +1 -0
- package/dist/vendor/codeburn/src/scan-facts.js +99 -0
- package/dist/vendor/codeburn/src/session-cache.js +3040 -0
- package/dist/vendor/codeburn/src/session-count-label.js +14 -0
- package/dist/vendor/codeburn/src/session-output.js +139 -0
- package/dist/vendor/codeburn/src/session-population.js +30 -0
- package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
- package/dist/vendor/codeburn/src/sqlite.js +528 -0
- package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
- package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
- package/dist/vendor/codeburn/src/token-estimate.js +5 -0
- package/dist/vendor/codeburn/src/types.js +16 -0
- package/dist/vendor/codeburn/src/work-units.js +126 -0
- package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
- package/dist/vendor/codeburn/src/wsl.js +198 -0
- package/dist/vendor/codeburn/src/yield.js +666 -0
- package/package.json +11 -3
|
@@ -0,0 +1,4110 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import chalk from '../shims/chalk.js';
|
|
3
|
+
import stripAnsi from '../shims/strip-ansi.js';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { readdir, stat } from 'fs/promises';
|
|
6
|
+
import { existsSync, statSync } from 'fs';
|
|
7
|
+
import { basename, join } from 'path';
|
|
8
|
+
import { homedir } from 'os';
|
|
9
|
+
import { isReadShapedBashCommand } from './bash-utils.js';
|
|
10
|
+
import { fileFacts } from './scan-facts.js';
|
|
11
|
+
import { EDIT_TOOLS } from './classifier.js';
|
|
12
|
+
import { foldParsedLine, readSessionLines, readSessionFileSync } from './fs-utils.js';
|
|
13
|
+
import { discoverAllSessions, providerDisplayName } from './providers/index.js';
|
|
14
|
+
import { parseJsonlLine } from './parser.js';
|
|
15
|
+
import { billableOutputTokens, cacheWriteCostPerToken, calculateCost, getModelCosts, getShortModelName, pricingModelAt } from './models.js';
|
|
16
|
+
import { formatCost } from './currency.js';
|
|
17
|
+
import { formatTokens } from './format.js';
|
|
18
|
+
import { detectOneHourCacheUnused } from './optimize-one-hour-cache.js';
|
|
19
|
+
import { recommendModelDefault } from './act/model-defaults.js';
|
|
20
|
+
import { appliedFixGlyph, formatAppliedFix } from './act/types.js';
|
|
21
|
+
import { isUserStartedSession, userStartedProjects } from './session-population.js';
|
|
22
|
+
import { countSessions, inferSessionProvider, sessionBillableOutputTokens } from './session-output.js';
|
|
23
|
+
import { sessionCacheHitPercent } from './sessions-report.js';
|
|
24
|
+
import { aggregateFileChurn, buildCoachingNotes, scanUserCorrections, medianTimeToFirstEditMs, worstOneShotCategory } from './workflow-insights.js';
|
|
25
|
+
// ============================================================================
|
|
26
|
+
// Display constants
|
|
27
|
+
// ============================================================================
|
|
28
|
+
const ORANGE = '#FF8C42';
|
|
29
|
+
const DIM = '#666666';
|
|
30
|
+
const GOLD = '#FFD700';
|
|
31
|
+
const CYAN = '#5BF5E0';
|
|
32
|
+
const GREEN = '#5BF5A0';
|
|
33
|
+
const RED = '#F55B5B';
|
|
34
|
+
// ============================================================================
|
|
35
|
+
// Token estimation constants
|
|
36
|
+
// ============================================================================
|
|
37
|
+
export const AVG_TOKENS_PER_READ = 600;
|
|
38
|
+
export const TOKENS_PER_MCP_TOOL = 400;
|
|
39
|
+
// A deferred MCP tool sits in the prompt as its name line only (measured
|
|
40
|
+
// median 32 chars), not its schema.
|
|
41
|
+
export const TOKENS_PER_DEFERRED_MCP_TOOL = 9;
|
|
42
|
+
export const TOOLS_PER_MCP_SERVER = 5;
|
|
43
|
+
export const TOKENS_PER_AGENT_DEF = 80;
|
|
44
|
+
export const TOKENS_PER_SKILL_DEF = 80;
|
|
45
|
+
export const TOKENS_PER_COMMAND_DEF = 60;
|
|
46
|
+
const CLAUDEMD_TOKENS_PER_LINE = 13;
|
|
47
|
+
const BASH_TOKENS_PER_CHAR = 0.25;
|
|
48
|
+
// ============================================================================
|
|
49
|
+
// Detector thresholds
|
|
50
|
+
// ============================================================================
|
|
51
|
+
const CLAUDEMD_HEALTHY_LINES = 200;
|
|
52
|
+
const CLAUDEMD_HIGH_THRESHOLD_LINES = 400;
|
|
53
|
+
const MIN_JUNK_READS_TO_FLAG = 3;
|
|
54
|
+
const JUNK_READS_HIGH_THRESHOLD = 20;
|
|
55
|
+
const JUNK_READS_MEDIUM_THRESHOLD = 5;
|
|
56
|
+
const MIN_DUPLICATE_READS_TO_FLAG = 5;
|
|
57
|
+
const DUPLICATE_READS_HIGH_THRESHOLD = 30;
|
|
58
|
+
const DUPLICATE_READS_MEDIUM_THRESHOLD = 10;
|
|
59
|
+
const MIN_EDITS_FOR_RATIO = 10;
|
|
60
|
+
export const HEALTHY_READ_EDIT_RATIO = 4;
|
|
61
|
+
const LOW_RATIO_HIGH_THRESHOLD = 2;
|
|
62
|
+
const LOW_RATIO_MEDIUM_THRESHOLD = 3;
|
|
63
|
+
const MIN_API_CALLS_FOR_CACHE = 10;
|
|
64
|
+
const CACHE_EXCESS_HIGH_THRESHOLD = 15000;
|
|
65
|
+
const UNUSED_MCP_HIGH_THRESHOLD = 3;
|
|
66
|
+
// MCP tool coverage detector thresholds. A server only earns a finding when
|
|
67
|
+
// every condition holds: the inventory is large enough to matter, real-world
|
|
68
|
+
// usage is poor, and we observed it in enough sessions to trust the signal.
|
|
69
|
+
const MCP_COVERAGE_MIN_TOOLS = 10;
|
|
70
|
+
const MCP_COVERAGE_MIN_SESSIONS = 2;
|
|
71
|
+
const MCP_COVERAGE_LOW_THRESHOLD = 0.20;
|
|
72
|
+
const MCP_COVERAGE_HIGH_IMPACT_TOKENS = 200_000;
|
|
73
|
+
const MCP_PROFILE_MIN_PROJECTS = 3;
|
|
74
|
+
const MCP_PROFILE_MIN_HOT_INVOCATIONS = 2;
|
|
75
|
+
const MCP_PROFILE_HOT_INVOCATION_SHARE = 0.80;
|
|
76
|
+
const MCP_PROFILE_MIN_COLD_LOADED_SESSIONS = 2;
|
|
77
|
+
const MCP_PROFILE_HIGH_IMPACT_TOKENS = 200_000;
|
|
78
|
+
const MCP_PROFILE_PREVIEW = 3;
|
|
79
|
+
// Anthropic prices cache writes at 125% of base input and cache reads at
|
|
80
|
+
// roughly 10% of base input. We use these to keep overhead estimates honest:
|
|
81
|
+
// most MCP schema bytes live in the cached prefix and only get charged at
|
|
82
|
+
// the discount rate after the first turn of a session.
|
|
83
|
+
const CACHE_WRITE_MULTIPLIER = 1.25;
|
|
84
|
+
const CACHE_READ_DISCOUNT = 0.10;
|
|
85
|
+
const GHOST_AGENTS_HIGH_THRESHOLD = 5;
|
|
86
|
+
const GHOST_AGENTS_MEDIUM_THRESHOLD = 2;
|
|
87
|
+
const GHOST_SKILLS_HIGH_THRESHOLD = 10;
|
|
88
|
+
const GHOST_SKILLS_MEDIUM_THRESHOLD = 5;
|
|
89
|
+
const GHOST_COMMANDS_MEDIUM_THRESHOLD = 10;
|
|
90
|
+
const MCP_NEW_CONFIG_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
91
|
+
const BASH_DEFAULT_LIMIT = 30000;
|
|
92
|
+
const BASH_RECOMMENDED_LIMIT = 15000;
|
|
93
|
+
const MIN_SESSIONS_FOR_OUTLIER = 3;
|
|
94
|
+
// A project is still bootstrapping until it has twice the minimum sessions
|
|
95
|
+
// needed to evaluate outliers; below that, its peer average is too thin to
|
|
96
|
+
// distinguish founding work from waste.
|
|
97
|
+
const YOUNG_PROJECT_SESSION_LIMIT = 2 * MIN_SESSIONS_FOR_OUTLIER;
|
|
98
|
+
const SESSION_OUTLIER_MULTIPLIER = 2;
|
|
99
|
+
const MIN_SESSION_OUTLIER_COST_USD = 1;
|
|
100
|
+
const SESSION_OUTLIER_PREVIEW = 5;
|
|
101
|
+
const CONTEXT_BLOAT_MIN_INPUT_TOKENS = 75_000;
|
|
102
|
+
const CONTEXT_BLOAT_MIN_RATIO = 25;
|
|
103
|
+
const CONTEXT_BLOAT_TARGET_RATIO = 15;
|
|
104
|
+
const CONTEXT_BLOAT_PREVIEW = 5;
|
|
105
|
+
const CONTEXT_BLOAT_LOW_INPUT_TOKENS = 200_000;
|
|
106
|
+
const CONTEXT_BLOAT_HIGH_INPUT_TOKENS = 500_000;
|
|
107
|
+
const CONTEXT_BLOAT_LOW_MAX_CANDIDATES = 2;
|
|
108
|
+
const CONTEXT_BLOAT_HIGH_MIN_CANDIDATES = 10;
|
|
109
|
+
const CONTEXT_BLOAT_GROWTH_RATIO = 2;
|
|
110
|
+
const CONTEXT_BLOAT_GROWTH_MAX_GAP_MS = 7 * 24 * 60 * 60 * 1000;
|
|
111
|
+
const CONTEXT_BLOAT_RATIO_DISPLAY_CAP = 1000;
|
|
112
|
+
const LOW_CACHE_HIT_TARGET_PERCENT = 80;
|
|
113
|
+
const LOW_CACHE_HIT_MIN_INPUT_TOKENS = CONTEXT_BLOAT_MIN_INPUT_TOKENS;
|
|
114
|
+
const LOW_CACHE_HIT_MIN_CALLS = 5;
|
|
115
|
+
const LOW_CACHE_HIT_PREVIEW = 5;
|
|
116
|
+
const WORTH_IT_MIN_COST_USD = 2;
|
|
117
|
+
const PREMIUM_MIN_USD = 1;
|
|
118
|
+
const PREMIUM_HIGH_USD = 20;
|
|
119
|
+
const PREMIUM_MEDIUM_USD = 5;
|
|
120
|
+
const WORTH_IT_NO_EDIT_MIN_COST_USD = 3;
|
|
121
|
+
// A zero-edit session's full cost is an upper bound on recoverable waste, not
|
|
122
|
+
// a point estimate, so use a bounded fraction for honest savings numbers.
|
|
123
|
+
const WORTH_IT_NO_EDIT_RECOVERY_FRACTION = 0.5;
|
|
124
|
+
const WORTH_IT_MIN_RETRIES = 3;
|
|
125
|
+
const WORTH_IT_RETRY_WITH_EDIT_MIN_RETRIES = 2;
|
|
126
|
+
const WORTH_IT_PREVIEW = 5;
|
|
127
|
+
const WORTH_IT_LOW_MAX_CANDIDATES = 2;
|
|
128
|
+
const WORTH_IT_LOW_MAX_TOTAL_COST_USD = 10;
|
|
129
|
+
const WORTH_IT_HIGH_MIN_CANDIDATES = 10;
|
|
130
|
+
const WORTH_IT_HIGH_TOTAL_COST_USD = 50;
|
|
131
|
+
const CAPABILITY_RELIABILITY_MIN_EDIT_TURNS = 5;
|
|
132
|
+
const CAPABILITY_RELIABILITY_MIN_RETRY_TURNS = 3;
|
|
133
|
+
const CAPABILITY_RELIABILITY_MIN_RETRY_RATE = 0.50;
|
|
134
|
+
const CAPABILITY_RELIABILITY_RECOVERY_FRACTION = 0.50;
|
|
135
|
+
const CAPABILITY_RELIABILITY_PREVIEW = 5;
|
|
136
|
+
const CAPABILITY_RELIABILITY_LOW_MAX_CANDIDATES = 1;
|
|
137
|
+
const CAPABILITY_RELIABILITY_LOW_MAX_TOKENS = 50_000;
|
|
138
|
+
const CAPABILITY_RELIABILITY_HIGH_MIN_CANDIDATES = 5;
|
|
139
|
+
const CAPABILITY_RELIABILITY_HIGH_IMPACT_TOKENS = 200_000;
|
|
140
|
+
// "mcp-deferral-gaps" finding family (#614): MCP tool schemas that sit in the
|
|
141
|
+
// prefix because tool search / deferral is off, overridden, or mistuned.
|
|
142
|
+
// Claude Code's tool search tool is literally named "ToolSearch"; seeing it
|
|
143
|
+
// invoked is direct transcript evidence that deferral was active.
|
|
144
|
+
const TOOL_SEARCH_TOOL_NAME = 'ToolSearch';
|
|
145
|
+
// Exported: the defer-enable / defer-threshold plan builders in
|
|
146
|
+
// src/act/plans.ts edit exactly this settings env key.
|
|
147
|
+
export const ENABLE_TOOL_SEARCH_VAR = 'ENABLE_TOOL_SEARCH';
|
|
148
|
+
const ANTHROPIC_BASE_URL_VAR = 'ANTHROPIC_BASE_URL';
|
|
149
|
+
const CLAUDE_CODE_USE_VERTEX_VAR = 'CLAUDE_CODE_USE_VERTEX';
|
|
150
|
+
// The only first-party API host. An unset ANTHROPIC_BASE_URL counts as
|
|
151
|
+
// first-party; any other host is an *unknown* proxy — deferral auto-disables
|
|
152
|
+
// there because most proxies don't forward tool_reference blocks, but we
|
|
153
|
+
// never claim the proxy is incapable, only unknown.
|
|
154
|
+
const FIRST_PARTY_API_HOST = 'api.anthropic.com';
|
|
155
|
+
// Claude Code changelog v2.1.7: "Enabled MCP tool search auto mode by
|
|
156
|
+
// default for all users." Sessions produced entirely by older versions
|
|
157
|
+
// could not have had deferral on without explicit opt-in.
|
|
158
|
+
const TOOL_SEARCH_DEFAULT_ON_VERSION = '2.1.7';
|
|
159
|
+
const DEFERRAL_OFF_MIN_MCP_SESSIONS = 2;
|
|
160
|
+
const DEFERRAL_OFF_HIGH_IMPACT_TOKENS = 200_000;
|
|
161
|
+
// Conservative: flag alwaysLoad servers only when strictly below one call
|
|
162
|
+
// per five sessions.
|
|
163
|
+
const ALWAYSLOAD_MAX_CALLS_PER_SESSION = 0.2;
|
|
164
|
+
// Server-level alwaysLoad shipped in Claude Code v2.1.121; on older
|
|
165
|
+
// versions the key is inert and the server's tools defer normally, so the
|
|
166
|
+
// pin costs nothing there. Exported: the defer-alwaysload plan builder
|
|
167
|
+
// (src/act/plans.ts) gates on the same boundary against the INSTALLED
|
|
168
|
+
// version before offering to remove the pin.
|
|
169
|
+
export const ALWAYSLOAD_MIN_VERSION = '2.1.121';
|
|
170
|
+
const ALWAYSLOAD_HIGH_IMPACT_TOKENS = 200_000;
|
|
171
|
+
// alwaysLoad blocks session startup on the server's connection, capped at 5s.
|
|
172
|
+
// Exported so the defer-alwaysload plan preview quotes the same cap.
|
|
173
|
+
export const ALWAYSLOAD_STARTUP_CAP_SECONDS = 5;
|
|
174
|
+
// ENABLE_TOOL_SEARCH=auto:N defers only when defs exceed N% of the context
|
|
175
|
+
// window (default 10). Tuning advice is only worth emitting when the
|
|
176
|
+
// upfront-loaded defs are substantial.
|
|
177
|
+
const DEFER_THRESHOLD_CONTEXT_WINDOW_TOKENS = 200_000;
|
|
178
|
+
const DEFER_THRESHOLD_DEFAULT_PERCENT = 10;
|
|
179
|
+
// auto:N is documented for N 0-100; larger values clamp rather than reject
|
|
180
|
+
// so a nonsense override still gets tuning advice instead of silence.
|
|
181
|
+
const DEFER_THRESHOLD_MAX_PERCENT = 100;
|
|
182
|
+
const DEFER_THRESHOLD_MIN_TOKENS_PER_SESSION = 5_000;
|
|
183
|
+
const DEFER_THRESHOLD_MEDIUM_IMPACT_TOKENS = 200_000;
|
|
184
|
+
// Idle compaction only fires once the context reaches this threshold, so a window at or below it blocks it: https://code.claude.com/docs/en/settings-reference.md#idlecompaction
|
|
185
|
+
const IDLE_COMPACT_DEFAULT_MIN_TOKENS = 200_000;
|
|
186
|
+
const IDLE_COMPACT_FLOOR_TOKENS = 100_000;
|
|
187
|
+
const IDLE_COMPACTION_MIN_VERSION = '2.1.290';
|
|
188
|
+
const AUTO_COMPACT_WINDOW_MAX_TOKENS = 1_000_000;
|
|
189
|
+
const AUTO_COMPACT_WINDOW_VAR = 'CLAUDE_CODE_AUTO_COMPACT_WINDOW';
|
|
190
|
+
const IDLE_COMPACT_MIN_TOKENS_VAR = 'CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS';
|
|
191
|
+
// "recurring-context": the same block opening session after session. 1.5 KB
|
|
192
|
+
// is roughly 400 tokens at BASH_TOKENS_PER_CHAR — below that a repeated
|
|
193
|
+
// opener costs too little to be worth a habit change, and five sessions is
|
|
194
|
+
// where "I keep pasting this" stops looking like coincidence.
|
|
195
|
+
const RECURRING_CONTEXT_MIN_CHARS = 1_500;
|
|
196
|
+
const RECURRING_CONTEXT_MIN_SESSIONS = 5;
|
|
197
|
+
const RECURRING_CONTEXT_NORMALIZE_SLACK = 4;
|
|
198
|
+
const RECURRING_CONTEXT_PREVIEW = 3;
|
|
199
|
+
const RECURRING_CONTEXT_PREVIEW_CHARS = 80;
|
|
200
|
+
const RECURRING_CONTEXT_MEDIUM_IMPACT_TOKENS = 50_000;
|
|
201
|
+
const RECURRING_CONTEXT_HIGH_IMPACT_TOKENS = 200_000;
|
|
202
|
+
// ============================================================================
|
|
203
|
+
// Scoring constants
|
|
204
|
+
// ============================================================================
|
|
205
|
+
const HEALTH_WEIGHT_HIGH = 15;
|
|
206
|
+
const HEALTH_WEIGHT_MEDIUM = 7;
|
|
207
|
+
const HEALTH_WEIGHT_LOW = 3;
|
|
208
|
+
const HEALTH_MAX_PENALTY = 80;
|
|
209
|
+
const GRADE_A_MIN = 90;
|
|
210
|
+
const GRADE_B_MIN = 75;
|
|
211
|
+
const GRADE_C_MIN = 55;
|
|
212
|
+
const GRADE_D_MIN = 30;
|
|
213
|
+
// Rebalanced so a high-impact finding with zero observed tokens (e.g.
|
|
214
|
+
// detectGhostAgents firing on five files but tokensSaved=400) cannot
|
|
215
|
+
// outrank a medium-impact finding with many millions of tokens.
|
|
216
|
+
// Old: 0.7/0.3 → high+0 = 0.70, medium+1B = 0.65 (high+0 won).
|
|
217
|
+
// New: 0.5/0.5 → high+0 = 0.50, medium+1B = 0.75 (medium+1B wins).
|
|
218
|
+
// Token normalize lifted to 5M so the rank scales over a realistic range.
|
|
219
|
+
const URGENCY_IMPACT_WEIGHT = 0.5;
|
|
220
|
+
const URGENCY_TOKEN_WEIGHT = 0.5;
|
|
221
|
+
const URGENCY_TOKEN_NORMALIZE = 5_000_000;
|
|
222
|
+
// ============================================================================
|
|
223
|
+
// File system constants
|
|
224
|
+
// ============================================================================
|
|
225
|
+
const MAX_IMPORT_DEPTH = 5;
|
|
226
|
+
const IMPORT_PATTERN = /^@(\.\.?\/[^\s]+|\/[^\s]+)/gm;
|
|
227
|
+
const COMMAND_PATTERN = /<command-name>([^<]+)<\/command-name>|(?:^|\s)\/([a-zA-Z][\w-]*)/gm;
|
|
228
|
+
const JUNK_DIRS = [
|
|
229
|
+
'node_modules', '.git', 'dist', 'build', '__pycache__', '.next',
|
|
230
|
+
'.nuxt', '.output', 'coverage', '.cache', '.tsbuildinfo',
|
|
231
|
+
'.venv', 'venv', '.svn', '.hg',
|
|
232
|
+
];
|
|
233
|
+
const JUNK_PATTERN = new RegExp(`/(?:${JUNK_DIRS.join('|')})/`);
|
|
234
|
+
const SHELL_PROFILES = ['.zshrc', '.bashrc', '.bash_profile', '.profile'];
|
|
235
|
+
const TOP_ITEMS_PREVIEW = 3;
|
|
236
|
+
const GHOST_NAMES_PREVIEW = 5;
|
|
237
|
+
const GHOST_CLEANUP_COMMANDS_LIMIT = 10;
|
|
238
|
+
const OPTIMIZE_TEXT_CAP = 2000;
|
|
239
|
+
const OPTIMIZE_FIELD_CAP = 500;
|
|
240
|
+
const REMEDIATION_INSTRUCTION_FILES = {
|
|
241
|
+
claude: 'CLAUDE.md',
|
|
242
|
+
codex: 'AGENTS.md',
|
|
243
|
+
};
|
|
244
|
+
export function isDefaultClaudeProvider(provider) {
|
|
245
|
+
return !provider || provider === 'all' || provider === 'claude';
|
|
246
|
+
}
|
|
247
|
+
export function optimizeRemediationCopy(provider) {
|
|
248
|
+
const key = !provider || provider === 'all' ? 'claude' : provider.toLowerCase();
|
|
249
|
+
return {
|
|
250
|
+
agent: providerDisplayName(key),
|
|
251
|
+
instructionFile: REMEDIATION_INSTRUCTION_FILES[key] ?? 'project instructions',
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
export function sessionOpenerLabel(copy) {
|
|
255
|
+
return `Paste at the start of your NEXT expensive thread (one-time, do not add to ${copy.instructionFile}):`;
|
|
256
|
+
}
|
|
257
|
+
export function askAgentLabel(copy, rest) {
|
|
258
|
+
return `Ask ${copy.agent} to ${rest}:`;
|
|
259
|
+
}
|
|
260
|
+
export function optimizePasteHeader(destination, copy) {
|
|
261
|
+
switch (destination) {
|
|
262
|
+
case 'claude-md': return `Suggested ${copy.instructionFile} addition (permanent rule)`;
|
|
263
|
+
case 'session-opener': return `One-time session opener (do NOT add to ${copy.instructionFile})`;
|
|
264
|
+
case 'prompt': return `Ask ${copy.agent} in the current session`;
|
|
265
|
+
case 'shell-config': return 'Add to your shell config';
|
|
266
|
+
case 'manual': return 'Manual action';
|
|
267
|
+
default: return 'Suggested action';
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/// Exact pre-#1049 TUI strings for unset/`all`/`claude`. Non-Claude providers
|
|
271
|
+
/// reuse the CLI header table so the two surfaces cannot drift on new copy.
|
|
272
|
+
export function optimizeTuiPasteHeader(destination, provider) {
|
|
273
|
+
if (isDefaultClaudeProvider(provider)) {
|
|
274
|
+
switch (destination) {
|
|
275
|
+
case 'claude-md': return '── Suggested CLAUDE.md addition (permanent rule) '.padEnd(64, '─');
|
|
276
|
+
case 'session-opener': return '── One-time session opener (do not add to CLAUDE.md) '.padEnd(64, '─');
|
|
277
|
+
case 'prompt': return '── Ask Claude in the current session '.padEnd(64, '─');
|
|
278
|
+
case 'shell-config': return '── Add to your shell config '.padEnd(64, '─');
|
|
279
|
+
case 'manual': return '── Manual action '.padEnd(64, '─');
|
|
280
|
+
default: return '── Suggested action '.padEnd(64, '─');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return `── ${optimizePasteHeader(destination, optimizeRemediationCopy(provider))} `.padEnd(64, '─');
|
|
284
|
+
}
|
|
285
|
+
export function optimizeEmptyScanLines(provider) {
|
|
286
|
+
if (isDefaultClaudeProvider(provider)) {
|
|
287
|
+
return [
|
|
288
|
+
'CodeBurn optimize scans your Claude Code sessions and config for',
|
|
289
|
+
'token waste: junk directory reads, duplicate file reads, unused',
|
|
290
|
+
'agents/skills/MCP servers, bloated CLAUDE.md, and more.',
|
|
291
|
+
];
|
|
292
|
+
}
|
|
293
|
+
const copy = optimizeRemediationCopy(provider);
|
|
294
|
+
// scanSessions is Claude-only. Naming the provider's instruction file here
|
|
295
|
+
// would claim a scan that did not run (Health A / 100 under --provider
|
|
296
|
+
// codex with every listed detector claudeOnly-disabled).
|
|
297
|
+
return [
|
|
298
|
+
`Session-scan detectors do not cover ${copy.agent} yet.`,
|
|
299
|
+
'junk directory reads, duplicate file reads, unused agents/skills/MCP,',
|
|
300
|
+
'and bloated instruction files currently scan Claude Code only.',
|
|
301
|
+
];
|
|
302
|
+
}
|
|
303
|
+
/// Static class per finding id. `fix` entries are exactly the ids `buildPlan`
|
|
304
|
+
/// (src/act/plans.ts) routes to a plan builder; tests assert the two lists
|
|
305
|
+
/// stay equal. Instances that lack the payload their builder needs fall back
|
|
306
|
+
/// to `nudge` via `findingClass`.
|
|
307
|
+
export const FINDING_CLASS = {
|
|
308
|
+
'read-edit-ratio': 'fix', // CLAUDE.md rule block
|
|
309
|
+
'build-folder-reads': 'fix', // CLAUDE.md rule block
|
|
310
|
+
'redundant-rereads': 'nudge',
|
|
311
|
+
'warmup-heavy': 'nudge',
|
|
312
|
+
'unused-mcp': 'fix',
|
|
313
|
+
'mcp-low-coverage': 'fix',
|
|
314
|
+
'mcp-project-scope': 'fix',
|
|
315
|
+
'mcp-deferral-off': 'fix',
|
|
316
|
+
'mcp-alwaysload-hygiene': 'fix',
|
|
317
|
+
'mcp-defer-threshold': 'fix',
|
|
318
|
+
'retry-heavy-capabilities': 'nudge',
|
|
319
|
+
'low-worth-sessions': 'nudge',
|
|
320
|
+
'context-heavy-sessions': 'keep', // context-heavy work is often load-bearing
|
|
321
|
+
'cost-outliers': 'nudge',
|
|
322
|
+
'low-cache-hit-sessions': 'nudge',
|
|
323
|
+
'one-hour-cache-unused': 'nudge',
|
|
324
|
+
'claude-md-too-long': 'nudge', // trimming is a judgement call, not a rule block
|
|
325
|
+
'bash-output-cap': 'fix',
|
|
326
|
+
'unused-agents': 'fix',
|
|
327
|
+
'unused-skills': 'fix',
|
|
328
|
+
'unused-commands': 'fix',
|
|
329
|
+
'recurring-context': 'nudge',
|
|
330
|
+
'fast-mode-background': 'nudge', // some runs pay for speed on purpose
|
|
331
|
+
'long-context-premium': 'keep', // the context may be needed
|
|
332
|
+
'idle-compaction-blocked': 'nudge',
|
|
333
|
+
};
|
|
334
|
+
/// Ids whose plan is built from the `apply` payload: without it the plan
|
|
335
|
+
/// builder returns null, so the finding is only a nudge.
|
|
336
|
+
const CLASS_NEEDS_APPLY = new Set([
|
|
337
|
+
'unused-mcp',
|
|
338
|
+
'mcp-low-coverage',
|
|
339
|
+
'mcp-project-scope',
|
|
340
|
+
'mcp-deferral-off',
|
|
341
|
+
'mcp-alwaysload-hygiene',
|
|
342
|
+
'mcp-defer-threshold',
|
|
343
|
+
'unused-agents',
|
|
344
|
+
'unused-skills',
|
|
345
|
+
'unused-commands',
|
|
346
|
+
]);
|
|
347
|
+
/// Static basis per finding id. Only the two session-level detectors sum
|
|
348
|
+
/// provider-counted tokens end to end; everything else multiplies a modelled
|
|
349
|
+
/// per-unit size or a recovery fraction.
|
|
350
|
+
export const FINDING_BASIS = {
|
|
351
|
+
'read-edit-ratio': 'estimated', // reads x AVG_TOKENS_PER_READ
|
|
352
|
+
'build-folder-reads': 'estimated', // reads x AVG_TOKENS_PER_READ
|
|
353
|
+
'redundant-rereads': 'estimated', // reads x AVG_TOKENS_PER_READ
|
|
354
|
+
'warmup-heavy': 'estimated', // observed median minus a modelled baseline
|
|
355
|
+
'unused-mcp': 'estimated', // tools x TOKENS_PER_MCP_TOOL x sessions
|
|
356
|
+
'mcp-low-coverage': 'estimated', // schema-size model, only capped by observed cache tokens
|
|
357
|
+
'mcp-project-scope': 'estimated', // same schema-size model
|
|
358
|
+
'mcp-deferral-off': 'estimated', // schema-size model x affected sessions
|
|
359
|
+
'mcp-alwaysload-hygiene': 'estimated', // tools x TOKENS_PER_MCP_TOOL x loaded sessions
|
|
360
|
+
'mcp-defer-threshold': 'estimated', // definition-size model x sessions
|
|
361
|
+
'retry-heavy-capabilities': 'estimated', // real turn tokens x recovery fraction
|
|
362
|
+
'low-worth-sessions': 'estimated', // real session tokens x recovery fraction
|
|
363
|
+
'context-heavy-sessions': 'measured', // counted input/cache tokens above the target ratio
|
|
364
|
+
'cost-outliers': 'measured', // counted session tokens above the peer average
|
|
365
|
+
'low-cache-hit-sessions': 'estimated', // counted tokens below the target hit ratio x read discount
|
|
366
|
+
'one-hour-cache-unused': 'measured', // counted one-hour write tokens x their own 60% premium
|
|
367
|
+
'claude-md-too-long': 'estimated', // lines x CLAUDEMD_TOKENS_PER_LINE
|
|
368
|
+
'bash-output-cap': 'estimated', // chars x BASH_TOKENS_PER_CHAR
|
|
369
|
+
'unused-agents': 'estimated', // count x TOKENS_PER_AGENT_DEF
|
|
370
|
+
'unused-skills': 'estimated', // count x TOKENS_PER_SKILL_DEF
|
|
371
|
+
'unused-commands': 'estimated', // count x TOKENS_PER_COMMAND_DEF
|
|
372
|
+
// Provider usage is per API call: the first turn's input tokens mix the
|
|
373
|
+
// system prompt, tool schemas and CLAUDE.md in with the pasted block, so
|
|
374
|
+
// nothing counted isolates the block. Its size is modelled from its bytes.
|
|
375
|
+
'recurring-context': 'estimated', // block chars x BASH_TOKENS_PER_CHAR x repeats
|
|
376
|
+
'fast-mode-background': 'measured', // priced calls, fast minus standard
|
|
377
|
+
'long-context-premium': 'measured', // priced calls, tier minus base rates
|
|
378
|
+
'idle-compaction-blocked': 'estimated', // config conflict, no tokens counted
|
|
379
|
+
};
|
|
380
|
+
/// Scope label for a setting that lives in ~/.zshrc / ~/.bashrc. The MCP
|
|
381
|
+
/// deferral plans (defer-enable, defer-threshold) refuse to rewrite an
|
|
382
|
+
/// override found there and report it instead; bash-output-cap does append
|
|
383
|
+
/// its own marker block to the shell rc.
|
|
384
|
+
export const SHELL_PROFILE_SCOPE = 'shell profile';
|
|
385
|
+
export function findingClass(f) {
|
|
386
|
+
const base = FINDING_CLASS[f.id];
|
|
387
|
+
if (base !== 'fix')
|
|
388
|
+
return base;
|
|
389
|
+
if (CLASS_NEEDS_APPLY.has(f.id) && !f.apply)
|
|
390
|
+
return 'nudge';
|
|
391
|
+
const apply = f.apply;
|
|
392
|
+
if ((apply?.kind === 'defer-enable' || apply?.kind === 'defer-threshold') && apply.settingScope === SHELL_PROFILE_SCOPE) {
|
|
393
|
+
return 'nudge';
|
|
394
|
+
}
|
|
395
|
+
// Of the deferral causes only these two have a plan; the rest are manual
|
|
396
|
+
// advice (Vertex policy, an outdated Claude Code, an unverified proxy).
|
|
397
|
+
if (apply?.kind === 'defer-enable' && apply.cause !== 'env-false' && apply.cause !== 'proxy-verified')
|
|
398
|
+
return 'nudge';
|
|
399
|
+
return 'fix';
|
|
400
|
+
}
|
|
401
|
+
export function findingBasis(f) {
|
|
402
|
+
return f.basis ?? FINDING_BASIS[f.id];
|
|
403
|
+
}
|
|
404
|
+
const CLASS_ORDER = { fix: 0, nudge: 1, keep: 2 };
|
|
405
|
+
export const CLASS_HEADERS = {
|
|
406
|
+
fix: 'Fix now (apply-able)',
|
|
407
|
+
nudge: 'Habits',
|
|
408
|
+
keep: 'FYI',
|
|
409
|
+
};
|
|
410
|
+
/// A finding's dollars for `tokens` of its `tokensSaved` (the whole finding by
|
|
411
|
+
/// default): its own `savingsUSD` scaled to that share, else the blended rate.
|
|
412
|
+
export function findingUSD(f, costRate, tokens = f.tokensSaved) {
|
|
413
|
+
if (f.savingsUSD === undefined)
|
|
414
|
+
return tokens * costRate;
|
|
415
|
+
if (tokens === f.tokensSaved)
|
|
416
|
+
return f.savingsUSD;
|
|
417
|
+
return f.tokensSaved > 0 ? f.savingsUSD * (tokens / f.tokensSaved) : 0;
|
|
418
|
+
}
|
|
419
|
+
export function classTotals(findings, costRate) {
|
|
420
|
+
const totals = {
|
|
421
|
+
fix: { tokensSaved: 0, savingsUSD: 0, count: 0 },
|
|
422
|
+
nudge: { tokensSaved: 0, savingsUSD: 0, count: 0 },
|
|
423
|
+
keep: { tokensSaved: 0, savingsUSD: 0, count: 0 },
|
|
424
|
+
};
|
|
425
|
+
for (const f of findings) {
|
|
426
|
+
const cls = findingClass(f);
|
|
427
|
+
// A `fix` whose plan owns only part of its estimate (a mixed local +
|
|
428
|
+
// claude.ai connector MCP finding) contributes only the apply-able
|
|
429
|
+
// subset, so this subtotal and the "apply-able" headline never promise
|
|
430
|
+
// what `--apply` cannot recover. The finding keeps the whole
|
|
431
|
+
// opportunity in its own `tokensSaved`, so the fix subtotal can be
|
|
432
|
+
// smaller than the findings listed under it.
|
|
433
|
+
const tokens = cls === 'fix' ? f.applyTokensSaved ?? f.tokensSaved : f.tokensSaved;
|
|
434
|
+
const t = totals[cls];
|
|
435
|
+
t.tokensSaved += tokens;
|
|
436
|
+
t.savingsUSD += findingUSD(f, costRate, tokens);
|
|
437
|
+
t.count++;
|
|
438
|
+
}
|
|
439
|
+
return totals;
|
|
440
|
+
}
|
|
441
|
+
/// Group header with its own subtotal, shared by the CLI and the TUI so the
|
|
442
|
+
/// two never drift apart.
|
|
443
|
+
export function classHeaderLine(cls, totals, costRate) {
|
|
444
|
+
const cost = costRate > 0 ? ` (~${formatCost(totals.savingsUSD)})` : '';
|
|
445
|
+
const suffix = cls === 'fix' ? ' — codeburn optimize --apply' : '';
|
|
446
|
+
const figure = totals.tokensSaved > 0 || totals.savingsUSD > 0 ? ` · ~${formatTokens(totals.tokensSaved)} tokens${cost}` : '';
|
|
447
|
+
return `${CLASS_HEADERS[cls]}${figure} · ${totals.count} finding${totals.count === 1 ? '' : 's'}${suffix}`;
|
|
448
|
+
}
|
|
449
|
+
// ============================================================================
|
|
450
|
+
// JSONL scanner
|
|
451
|
+
// ============================================================================
|
|
452
|
+
function cappedString(value, cap = OPTIMIZE_FIELD_CAP) {
|
|
453
|
+
return typeof value === 'string' ? value.slice(0, cap) : undefined;
|
|
454
|
+
}
|
|
455
|
+
export function compactOptimizeInput(name, input) {
|
|
456
|
+
if (!input || typeof input !== 'object')
|
|
457
|
+
return {};
|
|
458
|
+
const raw = input;
|
|
459
|
+
if (isReadTool(name)) {
|
|
460
|
+
const filePath = cappedString(raw['file_path'], OPTIMIZE_TEXT_CAP);
|
|
461
|
+
return filePath ? { file_path: filePath } : {};
|
|
462
|
+
}
|
|
463
|
+
// Only whether the command reads is ever asked of it, so that is all a call
|
|
464
|
+
// keeps: the command text was most of what a scan held.
|
|
465
|
+
if (BASH_TOOL_NAMES.has(name)) {
|
|
466
|
+
const command = cappedString(raw['command'], OPTIMIZE_TEXT_CAP);
|
|
467
|
+
return command && isReadShapedBashCommand(command) ? { readShaped: true } : {};
|
|
468
|
+
}
|
|
469
|
+
if (name === 'Agent' || name === 'Task') {
|
|
470
|
+
const subagentType = cappedString(raw['subagent_type']);
|
|
471
|
+
return subagentType ? { subagent_type: subagentType } : {};
|
|
472
|
+
}
|
|
473
|
+
if (name === 'Skill') {
|
|
474
|
+
const skill = cappedString(raw['skill']);
|
|
475
|
+
const skillName = cappedString(raw['name']);
|
|
476
|
+
return {
|
|
477
|
+
...(skill ? { skill } : {}),
|
|
478
|
+
...(skillName ? { name: skillName } : {}),
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
return {};
|
|
482
|
+
}
|
|
483
|
+
const FILE_READ_CONCURRENCY = 4;
|
|
484
|
+
const RESULT_CACHE_TTL_MS = 60_000;
|
|
485
|
+
const RECENT_WINDOW_HOURS = 48;
|
|
486
|
+
const RECENT_WINDOW_MS = RECENT_WINDOW_HOURS * 60 * 60 * 1000;
|
|
487
|
+
const DEFAULT_TREND_PERIOD_DAYS = 30;
|
|
488
|
+
const DEFAULT_TREND_PERIOD_MS = DEFAULT_TREND_PERIOD_DAYS * 24 * 60 * 60 * 1000;
|
|
489
|
+
const IMPROVING_THRESHOLD = 0.5;
|
|
490
|
+
async function collectJsonlFiles(dirPath) {
|
|
491
|
+
const files = await readdir(dirPath).catch(() => []);
|
|
492
|
+
const result = files.filter(f => f.endsWith('.jsonl')).map(f => join(dirPath, f));
|
|
493
|
+
for (const entry of files) {
|
|
494
|
+
if (entry.endsWith('.jsonl'))
|
|
495
|
+
continue;
|
|
496
|
+
const subPath = join(dirPath, entry, 'subagents');
|
|
497
|
+
const subFiles = await readdir(subPath).catch(() => []);
|
|
498
|
+
for (const sf of subFiles) {
|
|
499
|
+
if (sf.endsWith('.jsonl'))
|
|
500
|
+
result.push(join(subPath, sf));
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return result;
|
|
504
|
+
}
|
|
505
|
+
/// Size and last write, the pair a scan memo keys on. Null when the file cannot
|
|
506
|
+
/// be stat'd, which is how the scan already treats a file it cannot read.
|
|
507
|
+
async function fileIdentity(filePath) {
|
|
508
|
+
try {
|
|
509
|
+
const s = await stat(filePath);
|
|
510
|
+
return { size: s.size, mtimeMs: s.mtimeMs };
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
async function runWithConcurrency(items, limit, worker) {
|
|
517
|
+
let idx = 0;
|
|
518
|
+
async function next() {
|
|
519
|
+
while (idx < items.length) {
|
|
520
|
+
const current = idx++;
|
|
521
|
+
await worker(items[current]);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => next()));
|
|
525
|
+
}
|
|
526
|
+
/// Whitespace-insensitive so the same block reflowed by a different paste
|
|
527
|
+
/// still groups, and ANSI-free so terminal output pasted twice matches.
|
|
528
|
+
function normalizeOpener(text) {
|
|
529
|
+
return stripAnsi(text).replace(/\s+/g, ' ').trim();
|
|
530
|
+
}
|
|
531
|
+
/// True when a program wrote this prompt rather than a person pasting it: an
|
|
532
|
+
/// SDK caller, or a parent agent writing a subagent's task. Either repeats by
|
|
533
|
+
/// design and has no home in CLAUDE.md. Both flags survive the parser's
|
|
534
|
+
/// large-line path, which is where generated prompts routinely land.
|
|
535
|
+
function isMachineWrittenPrompt(entry) {
|
|
536
|
+
return entry['promptSource'] === 'sdk' || entry['isSidechain'] === true;
|
|
537
|
+
}
|
|
538
|
+
/// A session's opening block, or null when it is too small to matter or is
|
|
539
|
+
/// not a paste at all: system reminders carry CLAUDE.md and hook output,
|
|
540
|
+
/// slash command wrappers refer to a file that already exists. `chars` is a
|
|
541
|
+
/// floor: the parser caps the text of a very large user entry, so a huge
|
|
542
|
+
/// block is sized at that cap rather than its true length.
|
|
543
|
+
function toSessionOpener(text, project) {
|
|
544
|
+
if (text.length < RECURRING_CONTEXT_MIN_CHARS)
|
|
545
|
+
return null;
|
|
546
|
+
const head = text.trimStart();
|
|
547
|
+
if (head.startsWith('<system-reminder>') || head.startsWith('<command-name>') || head.startsWith('<command-message>'))
|
|
548
|
+
return null;
|
|
549
|
+
// Normalizing before the cap is what lets a re-flowed paste hash the same;
|
|
550
|
+
// the pre-slice keeps the work per session bounded however long the block
|
|
551
|
+
// is, with slack for whitespace that expands under re-flow.
|
|
552
|
+
const normalized = normalizeOpener(text.slice(0, OPTIMIZE_TEXT_CAP * RECURRING_CONTEXT_NORMALIZE_SLACK))
|
|
553
|
+
.slice(0, OPTIMIZE_TEXT_CAP);
|
|
554
|
+
return {
|
|
555
|
+
hash: createHash('sha1').update(normalized).digest('hex'),
|
|
556
|
+
chars: text.length,
|
|
557
|
+
project,
|
|
558
|
+
preview: normalized.slice(0, RECURRING_CONTEXT_PREVIEW_CHARS),
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
function inRange(timestamp, range) {
|
|
562
|
+
if (!range)
|
|
563
|
+
return true;
|
|
564
|
+
if (!timestamp)
|
|
565
|
+
return false;
|
|
566
|
+
const ts = new Date(timestamp);
|
|
567
|
+
return ts >= range.start && ts <= range.end;
|
|
568
|
+
}
|
|
569
|
+
// An absent or unparseable timestamp is not recent: NaN >= cutoff is false.
|
|
570
|
+
function isRecentAt(tsMs, cutoff) {
|
|
571
|
+
return tsMs !== undefined && tsMs >= cutoff;
|
|
572
|
+
}
|
|
573
|
+
export async function scanJsonlFile(filePath, project, dateRange, recentCutoffMs = Date.now() - RECENT_WINDOW_MS) {
|
|
574
|
+
const { record } = await scanFileRecord(filePath, project);
|
|
575
|
+
return useProjection(projectRecord(record, dateRange), recentCutoffMs);
|
|
576
|
+
}
|
|
577
|
+
const emptyCarry = () => ({ version: '' });
|
|
578
|
+
const emptyRecord = () => ({
|
|
579
|
+
calls: [], cwds: [], apiCalls: [], users: [], versionEvents: [],
|
|
580
|
+
sidechainAlways: false, sidechainMaxTs: null,
|
|
581
|
+
});
|
|
582
|
+
/// Can the range filter skip this line outright? Mirrors shouldSkipLine: only a
|
|
583
|
+
/// user or assistant line carrying a usable timestamp is ever skipped, and then
|
|
584
|
+
/// only for a threshold above it.
|
|
585
|
+
function skipTimestampOf(entry) {
|
|
586
|
+
const type = entry.type;
|
|
587
|
+
if (type !== 'user' && type !== 'assistant')
|
|
588
|
+
return null;
|
|
589
|
+
const ts = entry.timestamp;
|
|
590
|
+
return typeof ts === 'string' && ts.length >= 10 ? ts : null;
|
|
591
|
+
}
|
|
592
|
+
async function scanFileRecord(filePath, project,
|
|
593
|
+
// Continue an earlier read of this same file: start at the byte after the
|
|
594
|
+
// last complete line it consumed, append into the record it produced, and
|
|
595
|
+
// carry the state the loop had reached. The caller proves the bytes below
|
|
596
|
+
// that offset have not changed before passing this.
|
|
597
|
+
resume) {
|
|
598
|
+
const record = resume?.into ?? emptyRecord();
|
|
599
|
+
const carry = resume ? { ...resume.carry } : emptyCarry();
|
|
600
|
+
const sessionId = basename(filePath, '.jsonl');
|
|
601
|
+
// Tracks the byte after the last line folded, where the next read resumes
|
|
602
|
+
// (see foldParsedLine for a last line still missing its newline).
|
|
603
|
+
const tracker = { lastCompleteLineOffset: resume?.fromOffset ?? 0 };
|
|
604
|
+
const lines = readSessionLines(filePath, undefined, {
|
|
605
|
+
largeLineAsBuffer: true,
|
|
606
|
+
byteOffsetTracker: tracker,
|
|
607
|
+
...(resume ? { startByteOffset: resume.fromOffset } : {}),
|
|
608
|
+
});
|
|
609
|
+
for await (const line of lines) {
|
|
610
|
+
if (typeof line === 'string' && !line.trim())
|
|
611
|
+
continue;
|
|
612
|
+
if (Buffer.isBuffer(line) && line.length === 0)
|
|
613
|
+
continue;
|
|
614
|
+
const parsed = parseJsonlLine(line);
|
|
615
|
+
if (!parsed || !foldParsedLine(tracker, parsed))
|
|
616
|
+
continue;
|
|
617
|
+
const entry = parsed;
|
|
618
|
+
const skipTs = skipTimestampOf(entry);
|
|
619
|
+
if (entry.isSidechain === true) {
|
|
620
|
+
if (skipTs === null)
|
|
621
|
+
record.sidechainAlways = true;
|
|
622
|
+
else if (record.sidechainMaxTs === null || skipTs > record.sidechainMaxTs)
|
|
623
|
+
record.sidechainMaxTs = skipTs;
|
|
624
|
+
}
|
|
625
|
+
if (entry.version && typeof entry.version === 'string') {
|
|
626
|
+
const last = record.versionEvents[record.versionEvents.length - 1];
|
|
627
|
+
if (last && last.version === entry.version) {
|
|
628
|
+
// Same version again: keep whichever of the run a range is likeliest to
|
|
629
|
+
// still see - an unskippable line beats any timestamp, otherwise the
|
|
630
|
+
// latest one.
|
|
631
|
+
if (skipTs === null)
|
|
632
|
+
last.anchor = null;
|
|
633
|
+
else if (last.anchor !== null && skipTs > last.anchor)
|
|
634
|
+
last.anchor = skipTs;
|
|
635
|
+
}
|
|
636
|
+
else {
|
|
637
|
+
record.versionEvents.push({ version: entry.version, anchor: skipTs });
|
|
638
|
+
}
|
|
639
|
+
carry.version = entry.version;
|
|
640
|
+
}
|
|
641
|
+
const ts = typeof entry.timestamp === 'string' ? entry.timestamp : undefined;
|
|
642
|
+
const tsMs = ts === undefined ? Number.NaN : Date.parse(ts);
|
|
643
|
+
if (entry.cwd && typeof entry.cwd === 'string') {
|
|
644
|
+
const run = record.cwds[record.cwds.length - 1];
|
|
645
|
+
if (run && run.value === entry.cwd)
|
|
646
|
+
run.tsMs.push(tsMs);
|
|
647
|
+
else
|
|
648
|
+
record.cwds.push({ value: entry.cwd, tsMs: [tsMs] });
|
|
649
|
+
}
|
|
650
|
+
if (entry.type === 'user') {
|
|
651
|
+
const msg = entry.message;
|
|
652
|
+
const msgContent = msg?.content;
|
|
653
|
+
const messages = [];
|
|
654
|
+
let opener = null;
|
|
655
|
+
let sawText = false;
|
|
656
|
+
if (typeof msgContent === 'string') {
|
|
657
|
+
messages.push(msgContent.slice(0, OPTIMIZE_TEXT_CAP));
|
|
658
|
+
sawText = true;
|
|
659
|
+
opener = isMachineWrittenPrompt(entry) ? null : toSessionOpener(msgContent, project);
|
|
660
|
+
}
|
|
661
|
+
else if (Array.isArray(msgContent)) {
|
|
662
|
+
let remaining = OPTIMIZE_TEXT_CAP;
|
|
663
|
+
for (const block of msgContent) {
|
|
664
|
+
if (remaining <= 0)
|
|
665
|
+
break;
|
|
666
|
+
if (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
|
|
667
|
+
const text = block.text.slice(0, remaining);
|
|
668
|
+
messages.push(text);
|
|
669
|
+
remaining -= text.length;
|
|
670
|
+
if (!sawText) {
|
|
671
|
+
sawText = true;
|
|
672
|
+
opener = isMachineWrittenPrompt(entry) ? null : toSessionOpener(block.text, project);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
// An entry with no text at all is not recorded: the opening block is the
|
|
678
|
+
// first user message that carries text, and this one never claims it.
|
|
679
|
+
if (messages.length > 0)
|
|
680
|
+
record.users.push({ tsMs, commands: messages.flatMap(commandNames), opener });
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
if (entry.type !== 'assistant')
|
|
684
|
+
continue;
|
|
685
|
+
const msg = entry.message;
|
|
686
|
+
const usage = msg?.usage;
|
|
687
|
+
if (usage) {
|
|
688
|
+
const cacheCreate = usage.cache_creation_input_tokens ?? 0;
|
|
689
|
+
if (cacheCreate > 0) {
|
|
690
|
+
record.apiCalls.push({
|
|
691
|
+
call: { cacheCreationTokens: cacheCreate, version: carry.version, sessionId, tsMs },
|
|
692
|
+
versionIndex: record.versionEvents.length,
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const blocks = msg?.content;
|
|
697
|
+
if (!Array.isArray(blocks))
|
|
698
|
+
continue;
|
|
699
|
+
for (const block of blocks) {
|
|
700
|
+
if (block.type !== 'tool_use')
|
|
701
|
+
continue;
|
|
702
|
+
const name = typeof block.name === 'string' ? block.name : '';
|
|
703
|
+
record.calls.push({
|
|
704
|
+
name,
|
|
705
|
+
input: compactOptimizeInput(name, block.input),
|
|
706
|
+
sessionId,
|
|
707
|
+
project,
|
|
708
|
+
tsMs,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return { record, carry, offset: tracker.lastCompleteLineOffset };
|
|
713
|
+
}
|
|
714
|
+
function useProjection(projection, recentCutoffMs) {
|
|
715
|
+
// One pass for all three range-or-clock derived stamps. Walking the selected
|
|
716
|
+
// items twice - once to place the range's verdicts, once for recency - was
|
|
717
|
+
// the larger half of what a warm scan cost.
|
|
718
|
+
for (const call of projection.result.calls) {
|
|
719
|
+
call.isSidechain = projection.sidechain;
|
|
720
|
+
call.recent = isRecentAt(call.tsMs, recentCutoffMs);
|
|
721
|
+
}
|
|
722
|
+
const apiCalls = projection.result.apiCalls;
|
|
723
|
+
for (let i = 0; i < apiCalls.length; i++) {
|
|
724
|
+
const call = apiCalls[i];
|
|
725
|
+
call.version = projection.versions[i];
|
|
726
|
+
call.recent = isRecentAt(call.tsMs, recentCutoffMs);
|
|
727
|
+
}
|
|
728
|
+
return projection.result;
|
|
729
|
+
}
|
|
730
|
+
/// Narrow one scanned file to a query range, reproducing exactly what a scan
|
|
731
|
+
/// that had carried the range would have collected: the same items, the same
|
|
732
|
+
/// order, the same carried version and sidechain verdict.
|
|
733
|
+
function projectRecord(record, dateRange) {
|
|
734
|
+
// No range means everything, exactly as the range test did; with a range, an
|
|
735
|
+
// absent or unparseable instant is NaN and compares false, as it did.
|
|
736
|
+
const startMs = dateRange ? dateRange.start.getTime() : 0;
|
|
737
|
+
const endMs = dateRange ? dateRange.end.getTime() : 0;
|
|
738
|
+
const within = dateRange
|
|
739
|
+
? (tsMs) => tsMs >= startMs && tsMs <= endMs
|
|
740
|
+
: () => true;
|
|
741
|
+
// The threshold the line-level skip used, as the same ISO string it compared.
|
|
742
|
+
const threshold = dateRange ? new Date(dateRange.start.getTime() - 86_400_000).toISOString() : null;
|
|
743
|
+
const qualifies = (skipTs) => threshold === null || skipTs === null || skipTs >= threshold;
|
|
744
|
+
const isSidechain = record.sidechainAlways || (record.sidechainMaxTs !== null && qualifies(record.sidechainMaxTs));
|
|
745
|
+
// Stamped in place rather than copied, on the same terms as the recency flag
|
|
746
|
+
// below: the record is owned by one serialized request at a time, and every
|
|
747
|
+
// reader of these objects is downstream of this projection. Copying each call
|
|
748
|
+
// instead cost more per request than re-reading the file had.
|
|
749
|
+
const calls = [];
|
|
750
|
+
for (const call of record.calls) {
|
|
751
|
+
if (!within(call.tsMs))
|
|
752
|
+
continue;
|
|
753
|
+
calls.push(call);
|
|
754
|
+
}
|
|
755
|
+
const cwds = [];
|
|
756
|
+
for (const run of record.cwds)
|
|
757
|
+
for (const tsMs of run.tsMs)
|
|
758
|
+
if (within(tsMs))
|
|
759
|
+
cwds.push(run.value);
|
|
760
|
+
const apiCalls = [];
|
|
761
|
+
// The version a call carried is the last version line before it that the
|
|
762
|
+
// range's own skip threshold would have left in place. Resolved for every
|
|
763
|
+
// position once, in one forward pass, rather than walked back per call: a
|
|
764
|
+
// range that skips every version line in a file would otherwise re-walk the
|
|
765
|
+
// whole list for each of that file's calls.
|
|
766
|
+
const versionBefore = new Array(record.versionEvents.length + 1);
|
|
767
|
+
versionBefore[0] = '';
|
|
768
|
+
for (let i = 0; i < record.versionEvents.length; i++) {
|
|
769
|
+
const event = record.versionEvents[i];
|
|
770
|
+
versionBefore[i + 1] = qualifies(event.anchor) ? event.version : versionBefore[i];
|
|
771
|
+
}
|
|
772
|
+
const versions = [];
|
|
773
|
+
for (const entry of record.apiCalls) {
|
|
774
|
+
if (!within(entry.call.tsMs))
|
|
775
|
+
continue;
|
|
776
|
+
versions.push(versionBefore[entry.versionIndex]);
|
|
777
|
+
apiCalls.push(entry.call);
|
|
778
|
+
}
|
|
779
|
+
const commandNamesInRange = [];
|
|
780
|
+
const openers = [];
|
|
781
|
+
let sawUserText = false;
|
|
782
|
+
for (const user of record.users) {
|
|
783
|
+
if (!within(user.tsMs))
|
|
784
|
+
continue;
|
|
785
|
+
for (const name of user.commands)
|
|
786
|
+
commandNamesInRange.push(name);
|
|
787
|
+
if (!sawUserText) {
|
|
788
|
+
sawUserText = true;
|
|
789
|
+
if (user.opener)
|
|
790
|
+
openers.push(user.opener);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
return { result: { calls, cwds, apiCalls, commandNames: commandNamesInRange, openers }, sidechain: isSidechain, versions };
|
|
794
|
+
}
|
|
795
|
+
// The session scan reads Claude Code transcripts only, so a `--provider` that
|
|
796
|
+
// excludes Claude leaves nothing for it to do. Callers must also skip the
|
|
797
|
+
// detectors it feeds (see `claudeOnly` in scanAndDetect) — the empty scan
|
|
798
|
+
// returned here is an absence of measurement, not a measurement of absence.
|
|
799
|
+
export function providerCoversClaude(provider) {
|
|
800
|
+
return !provider || provider === 'all' || provider === 'claude';
|
|
801
|
+
}
|
|
802
|
+
// Session files a resident process (codeburn serve) has already scanned for the
|
|
803
|
+
// optimize detectors, keyed by the file's identity and the range it was scanned
|
|
804
|
+
// for. The scan re-read every Claude transcript overlapping the period on every
|
|
805
|
+
// request - about six of the seven seconds a desktop period switch cost - while
|
|
806
|
+
// all but the handful of files written since the last request produce exactly
|
|
807
|
+
// the same result. An unchanged file is served as it is; any other comes from
|
|
808
|
+
// the stored record (scan-facts.ts), which reads only what a file appended since
|
|
809
|
+
// it was stored, so a live transcript does not cost its whole length on every
|
|
810
|
+
// request, and a new process does not re-read the corpus. The recency flag is stamped
|
|
811
|
+
// afterwards, so a kept result is not pinned to the cutoff it was first scanned
|
|
812
|
+
// under. Bounded by bytes with age and least-recently-used eviction, like the
|
|
813
|
+
// shard memo.
|
|
814
|
+
// Held heap, not text: measured against a live heap on a 7GB corpus, the
|
|
815
|
+
// objects a scanned file retains cost about 1.8x the text they carry, so a
|
|
816
|
+
// budget counted in text alone lets the memo grow past the resident-set guard -
|
|
817
|
+
// which then drops every memo and hands the next request a cold scan.
|
|
818
|
+
const SCAN_RETAINED_FACTOR = 1.8;
|
|
819
|
+
const CALL_SAMPLE_STRIDE = 16;
|
|
820
|
+
// The desktop rotates through six named periods; holding a selection for each
|
|
821
|
+
// of them per file is references only, and past that the oldest is dropped.
|
|
822
|
+
const MAX_PROJECTIONS_PER_FILE = 6;
|
|
823
|
+
const SCAN_MEMO_MAX_BYTES = 160 * 1024 * 1024;
|
|
824
|
+
const SCAN_MEMO_MAX_AGE_MS = 10 * 60 * 1000;
|
|
825
|
+
const scanFileMemo = new Map();
|
|
826
|
+
let scanFileMemoBytes = 0;
|
|
827
|
+
export function clearScanFileMemo() {
|
|
828
|
+
scanFileMemo.clear();
|
|
829
|
+
scanFileMemoBytes = 0;
|
|
830
|
+
}
|
|
831
|
+
export function scanFileMemoStats() {
|
|
832
|
+
return { entries: scanFileMemo.size, bytes: scanFileMemoBytes };
|
|
833
|
+
}
|
|
834
|
+
/// Drop entries unused past the age bound, then least-recently-used entries
|
|
835
|
+
/// until the byte budget holds. `now` is injected so the rule is testable.
|
|
836
|
+
export function evictScanFileMemo(now, maxBytes = SCAN_MEMO_MAX_BYTES) {
|
|
837
|
+
// The map is held in least-recently-used order - a hit reinserts its entry at
|
|
838
|
+
// the back - so the oldest and the least recently used are the same walk from
|
|
839
|
+
// the front, and it stops at the first entry that is both fresh and within
|
|
840
|
+
// budget. Sorting the whole map per insertion instead made a scan whose
|
|
841
|
+
// working set does not fit cost more than having no memo at all.
|
|
842
|
+
for (const [key, entry] of scanFileMemo) {
|
|
843
|
+
if (scanFileMemoBytes <= maxBytes && now - entry.usedAt <= SCAN_MEMO_MAX_AGE_MS)
|
|
844
|
+
break;
|
|
845
|
+
scanFileMemo.delete(key);
|
|
846
|
+
scanFileMemoBytes -= entry.bytes;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/// What one scanned file costs to keep, in held heap. Tool inputs are already
|
|
850
|
+
/// compacted by the scanner and user messages are capped, so the text they hold
|
|
851
|
+
/// plus a flat per-record overhead, scaled by the measured retention factor,
|
|
852
|
+
/// tracks the real footprint closely enough to bound it.
|
|
853
|
+
function scanResultBytes(record) {
|
|
854
|
+
let bytes = record.apiCalls.length * 96;
|
|
855
|
+
for (const run of record.cwds)
|
|
856
|
+
bytes += 80 + run.tsMs.length * 8;
|
|
857
|
+
// Sampled, not exhaustive: measuring every tool input meant serializing the
|
|
858
|
+
// whole corpus on every scan, which cost more than the memo saved.
|
|
859
|
+
let sampled = 0;
|
|
860
|
+
let sampledBytes = 0;
|
|
861
|
+
for (let i = 0; i < record.calls.length; i += CALL_SAMPLE_STRIDE) {
|
|
862
|
+
sampledBytes += JSON.stringify(record.calls[i].input).length;
|
|
863
|
+
sampled++;
|
|
864
|
+
}
|
|
865
|
+
const averageInput = sampled > 0 ? sampledBytes / sampled : 0;
|
|
866
|
+
bytes += record.calls.length * (128 + averageInput);
|
|
867
|
+
for (const user of record.users) {
|
|
868
|
+
bytes += 96;
|
|
869
|
+
for (const name of user.commands)
|
|
870
|
+
bytes += name.length;
|
|
871
|
+
if (user.opener)
|
|
872
|
+
bytes += user.opener.preview.length + 96;
|
|
873
|
+
}
|
|
874
|
+
return Math.round(bytes * SCAN_RETAINED_FACTOR);
|
|
875
|
+
}
|
|
876
|
+
/// What one range's selection costs to keep: slots holding references, not the
|
|
877
|
+
/// items themselves, which is the whole reason a period can have its own.
|
|
878
|
+
function projectionBytes(projection) {
|
|
879
|
+
const { calls, cwds, apiCalls, commandNames, openers } = projection.result;
|
|
880
|
+
const slots = calls.length + cwds.length + apiCalls.length + commandNames.length
|
|
881
|
+
+ openers.length + projection.versions.length;
|
|
882
|
+
return slots * 24;
|
|
883
|
+
}
|
|
884
|
+
/// The view of a stored file for one range, built once and kept. Selections are
|
|
885
|
+
/// held least-recently-used, so a period the desktop has moved on from is the
|
|
886
|
+
/// one dropped; the record itself stays, and rebuilding a selection is a walk,
|
|
887
|
+
/// not a read.
|
|
888
|
+
function rangeProjection(entry, dateRange, recentCutoffMs) {
|
|
889
|
+
const rangeKey = dateRange ? `${dateRange.start.getTime()}-${dateRange.end.getTime()}` : 'all';
|
|
890
|
+
const existing = entry.projections.get(rangeKey);
|
|
891
|
+
if (existing) {
|
|
892
|
+
entry.projections.delete(rangeKey);
|
|
893
|
+
entry.projections.set(rangeKey, existing);
|
|
894
|
+
return useProjection(existing, recentCutoffMs);
|
|
895
|
+
}
|
|
896
|
+
const projection = projectRecord(entry.record, dateRange);
|
|
897
|
+
while (entry.projections.size >= MAX_PROJECTIONS_PER_FILE) {
|
|
898
|
+
const oldest = entry.projections.entries().next().value;
|
|
899
|
+
if (oldest === undefined)
|
|
900
|
+
break;
|
|
901
|
+
entry.projections.delete(oldest[0]);
|
|
902
|
+
const freed = projectionBytes(oldest[1]);
|
|
903
|
+
entry.bytes -= freed;
|
|
904
|
+
scanFileMemoBytes -= freed;
|
|
905
|
+
}
|
|
906
|
+
entry.projections.set(rangeKey, projection);
|
|
907
|
+
const held = projectionBytes(projection);
|
|
908
|
+
entry.bytes += held;
|
|
909
|
+
scanFileMemoBytes += held;
|
|
910
|
+
return useProjection(projection, recentCutoffMs);
|
|
911
|
+
}
|
|
912
|
+
const storedMs = (tsMs) => tsMs === undefined || Number.isNaN(tsMs) ? null : tsMs;
|
|
913
|
+
const loadedMs = (tsMs) => tsMs === null ? Number.NaN : tsMs;
|
|
914
|
+
function storeScan(project, pass) {
|
|
915
|
+
const { record, carry } = pass;
|
|
916
|
+
return {
|
|
917
|
+
offset: pass.offset,
|
|
918
|
+
facts: {
|
|
919
|
+
project,
|
|
920
|
+
carry,
|
|
921
|
+
sidechainAlways: record.sidechainAlways,
|
|
922
|
+
sidechainMaxTs: record.sidechainMaxTs,
|
|
923
|
+
versionEvents: record.versionEvents,
|
|
924
|
+
calls: record.calls.map(c => [c.name, c.input, storedMs(c.tsMs)]),
|
|
925
|
+
cwds: record.cwds.map(run => [run.value, run.tsMs.map(storedMs)]),
|
|
926
|
+
apiCalls: record.apiCalls.map(a => [a.call.cacheCreationTokens, storedMs(a.call.tsMs), a.versionIndex]),
|
|
927
|
+
users: record.users.map(u => [storedMs(u.tsMs), u.commands, u.opener]),
|
|
928
|
+
},
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
function loadScan(filePath, stored) {
|
|
932
|
+
const sessionId = basename(filePath, '.jsonl');
|
|
933
|
+
const { project } = stored;
|
|
934
|
+
return {
|
|
935
|
+
carry: { ...stored.carry },
|
|
936
|
+
record: {
|
|
937
|
+
calls: stored.calls.map(([name, input, tsMs]) => ({ name, input, sessionId, project, tsMs: loadedMs(tsMs) })),
|
|
938
|
+
cwds: stored.cwds.map(([value, tsMs]) => ({ value, tsMs: tsMs.map(loadedMs) })),
|
|
939
|
+
apiCalls: stored.apiCalls.map(([cacheCreationTokens, tsMs, versionIndex]) => ({
|
|
940
|
+
call: { cacheCreationTokens, version: '', sessionId, tsMs: loadedMs(tsMs) },
|
|
941
|
+
versionIndex,
|
|
942
|
+
})),
|
|
943
|
+
versionEvents: stored.versionEvents.map(e => ({ ...e })),
|
|
944
|
+
users: stored.users.map(([tsMs, commands, opener]) => ({ tsMs: loadedMs(tsMs), commands, opener })),
|
|
945
|
+
sidechainAlways: stored.sidechainAlways,
|
|
946
|
+
sidechainMaxTs: stored.sidechainMaxTs,
|
|
947
|
+
},
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
/// A file's record from the facts store, scanned (or resumed) only when the
|
|
951
|
+
/// stored one no longer matches the file. Always read back through the stored
|
|
952
|
+
/// form, so a record served from disk is the very one a fresh scan would use.
|
|
953
|
+
async function storedRecord(filePath, project) {
|
|
954
|
+
const stored = await fileFacts('optimize', filePath, async (resume) => {
|
|
955
|
+
if (resume && resume.facts.project === project) {
|
|
956
|
+
const { record, carry } = loadScan(filePath, resume.facts);
|
|
957
|
+
return storeScan(project, await scanFileRecord(filePath, project, { fromOffset: resume.fromOffset, carry, into: record }));
|
|
958
|
+
}
|
|
959
|
+
return storeScan(project, await scanFileRecord(filePath, project));
|
|
960
|
+
});
|
|
961
|
+
if (stored.project !== project)
|
|
962
|
+
return (await scanFileRecord(filePath, project)).record;
|
|
963
|
+
return loadScan(filePath, stored).record;
|
|
964
|
+
}
|
|
965
|
+
export async function scanJsonlFileMemoized(filePath, project, dateRange, identity, recentCutoffMs = Date.now() - RECENT_WINDOW_MS) {
|
|
966
|
+
if (identity === null)
|
|
967
|
+
return useProjection(projectRecord((await scanFileRecord(filePath, project)).record, dateRange), recentCutoffMs);
|
|
968
|
+
// No range in the key: the record is what the file holds, not what one period
|
|
969
|
+
// asked of it, so one entry answers every period the desktop rotates through.
|
|
970
|
+
const key = `${filePath}\0${project}`;
|
|
971
|
+
const now = Date.now();
|
|
972
|
+
const hit = scanFileMemo.get(key);
|
|
973
|
+
if (hit && hit.size === identity.size && hit.mtimeMs === identity.mtimeMs) {
|
|
974
|
+
hit.usedAt = now;
|
|
975
|
+
scanFileMemo.delete(key);
|
|
976
|
+
scanFileMemo.set(key, hit);
|
|
977
|
+
return rangeProjection(hit, dateRange, recentCutoffMs);
|
|
978
|
+
}
|
|
979
|
+
if (hit) {
|
|
980
|
+
scanFileMemo.delete(key);
|
|
981
|
+
scanFileMemoBytes -= hit.bytes;
|
|
982
|
+
}
|
|
983
|
+
const record = await storedRecord(filePath, project);
|
|
984
|
+
const bytes = scanResultBytes(record);
|
|
985
|
+
const entry = {
|
|
986
|
+
record,
|
|
987
|
+
projections: new Map(),
|
|
988
|
+
size: identity.size,
|
|
989
|
+
mtimeMs: identity.mtimeMs,
|
|
990
|
+
bytes,
|
|
991
|
+
usedAt: now,
|
|
992
|
+
};
|
|
993
|
+
scanFileMemo.set(key, entry);
|
|
994
|
+
scanFileMemoBytes += bytes;
|
|
995
|
+
evictScanFileMemo(now);
|
|
996
|
+
return rangeProjection(entry, dateRange, recentCutoffMs);
|
|
997
|
+
}
|
|
998
|
+
async function scanSessions(dateRange, provider) {
|
|
999
|
+
if (!providerCoversClaude(provider)) {
|
|
1000
|
+
return { toolCalls: [], projectCwds: new Set(), apiCalls: [], commandNames: [], openers: [] };
|
|
1001
|
+
}
|
|
1002
|
+
const sources = await discoverAllSessions('claude');
|
|
1003
|
+
const allCalls = [];
|
|
1004
|
+
const allCwds = new Set();
|
|
1005
|
+
const allApiCalls = [];
|
|
1006
|
+
const allCommandNames = [];
|
|
1007
|
+
const allOpeners = [];
|
|
1008
|
+
const tasks = [];
|
|
1009
|
+
for (const source of sources) {
|
|
1010
|
+
const files = await collectJsonlFiles(source.path);
|
|
1011
|
+
for (const file of files) {
|
|
1012
|
+
const identity = await fileIdentity(file);
|
|
1013
|
+
// A file that cannot be stat'd is still scanned, as it always was; it
|
|
1014
|
+
// just has no identity to memoize under.
|
|
1015
|
+
if (identity && dateRange && identity.mtimeMs < dateRange.start.getTime())
|
|
1016
|
+
continue;
|
|
1017
|
+
tasks.push({ file, project: source.project, identity });
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
// One cutoff for the whole scan rather than one per file, so every detector
|
|
1021
|
+
// reads the same window and a memoized file is stamped with the same verdict
|
|
1022
|
+
// a freshly read one would get.
|
|
1023
|
+
const recentCutoffMs = Date.now() - RECENT_WINDOW_MS;
|
|
1024
|
+
// Joined in discovery order, not in the order the reads finish: sums, ties in
|
|
1025
|
+
// the previews and which settings file wins all follow this order, so a join
|
|
1026
|
+
// by completion made two runs over the same files disagree.
|
|
1027
|
+
const results = new Array(tasks.length);
|
|
1028
|
+
await runWithConcurrency(tasks.map((task, slot) => ({ ...task, slot })), FILE_READ_CONCURRENCY, async ({ file, project, identity, slot }) => {
|
|
1029
|
+
results[slot] = await scanJsonlFileMemoized(file, project, dateRange, identity, recentCutoffMs);
|
|
1030
|
+
});
|
|
1031
|
+
for (const { calls, cwds, apiCalls, commandNames, openers } of results) {
|
|
1032
|
+
allCalls.push(...calls);
|
|
1033
|
+
for (const cwd of cwds)
|
|
1034
|
+
allCwds.add(cwd);
|
|
1035
|
+
allApiCalls.push(...apiCalls);
|
|
1036
|
+
allCommandNames.push(...commandNames);
|
|
1037
|
+
allOpeners.push(...openers);
|
|
1038
|
+
}
|
|
1039
|
+
return { toolCalls: allCalls, projectCwds: allCwds, apiCalls: allApiCalls, commandNames: allCommandNames, openers: allOpeners };
|
|
1040
|
+
}
|
|
1041
|
+
// ============================================================================
|
|
1042
|
+
// Shared helpers
|
|
1043
|
+
// ============================================================================
|
|
1044
|
+
function readJsonFile(path) {
|
|
1045
|
+
const raw = readSessionFileSync(path);
|
|
1046
|
+
if (raw === null)
|
|
1047
|
+
return null;
|
|
1048
|
+
try {
|
|
1049
|
+
return JSON.parse(raw);
|
|
1050
|
+
}
|
|
1051
|
+
catch {
|
|
1052
|
+
return null;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
function shortHomePath(absPath) {
|
|
1056
|
+
const home = homedir();
|
|
1057
|
+
return absPath.startsWith(home) ? '~' + absPath.slice(home.length) : absPath;
|
|
1058
|
+
}
|
|
1059
|
+
function isReadTool(name) {
|
|
1060
|
+
return name === 'Read' || name === 'FileReadTool';
|
|
1061
|
+
}
|
|
1062
|
+
/// A server's name as Claude Code writes it into tool names (mcp__<name>__tool):
|
|
1063
|
+
/// every character outside letters, digits, "_" and "-" becomes "_".
|
|
1064
|
+
export function mcpNamespace(name) {
|
|
1065
|
+
return name.replace(/[^A-Za-z0-9_-]/g, '_');
|
|
1066
|
+
}
|
|
1067
|
+
/// The server half of an mcp__<server>__<tool> name. Either half may contain
|
|
1068
|
+
/// "__", so the longest known server namespace wins; an unknown server falls
|
|
1069
|
+
/// back to the first segment, the way the parser keys its MCP breakdown.
|
|
1070
|
+
/// With servers "a" and "a__b" both configured, mcp__a__b__c is ambiguous in
|
|
1071
|
+
/// Claude Code's own encoding (it joins with "__" and escapes nothing).
|
|
1072
|
+
export function mcpServerOf(toolName, known) {
|
|
1073
|
+
const rest = toolName.slice('mcp__'.length);
|
|
1074
|
+
let best;
|
|
1075
|
+
for (const ns of known) {
|
|
1076
|
+
if (rest.startsWith(ns + '__') && ns.length > (best?.length ?? 0))
|
|
1077
|
+
best = ns;
|
|
1078
|
+
}
|
|
1079
|
+
return best ?? toolName.split('__')[1];
|
|
1080
|
+
}
|
|
1081
|
+
// Claude Code does not read mcpServers from ~/.claude/settings*.json (user
|
|
1082
|
+
// servers live in ~/.claude.json), and the remove plan never edits them.
|
|
1083
|
+
export function loadMcpConfigs(projectCwds) {
|
|
1084
|
+
const servers = new Map();
|
|
1085
|
+
const configPaths = [];
|
|
1086
|
+
for (const cwd of projectCwds) {
|
|
1087
|
+
configPaths.push(join(cwd, '.mcp.json'));
|
|
1088
|
+
configPaths.push(join(cwd, '.claude', 'settings.json'));
|
|
1089
|
+
configPaths.push(join(cwd, '.claude', 'settings.local.json'));
|
|
1090
|
+
}
|
|
1091
|
+
for (const p of configPaths) {
|
|
1092
|
+
if (!existsSync(p))
|
|
1093
|
+
continue;
|
|
1094
|
+
const config = readJsonFile(p);
|
|
1095
|
+
if (!config)
|
|
1096
|
+
continue;
|
|
1097
|
+
let mtime = 0;
|
|
1098
|
+
try {
|
|
1099
|
+
mtime = statSync(p).mtimeMs;
|
|
1100
|
+
}
|
|
1101
|
+
catch { }
|
|
1102
|
+
const serversObj = (config.mcpServers ?? {});
|
|
1103
|
+
for (const [name, rawEntry] of Object.entries(serversObj)) {
|
|
1104
|
+
const normalized = mcpNamespace(name);
|
|
1105
|
+
const existing = servers.get(normalized);
|
|
1106
|
+
if (!existing || existing.mtime < mtime) {
|
|
1107
|
+
servers.set(normalized, {
|
|
1108
|
+
normalized,
|
|
1109
|
+
originals: existing?.originals ?? [],
|
|
1110
|
+
mtime,
|
|
1111
|
+
alwaysLoadPaths: existing?.alwaysLoadPaths ?? [],
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
const server = servers.get(normalized);
|
|
1115
|
+
if (!server.originals.includes(name))
|
|
1116
|
+
server.originals.push(name);
|
|
1117
|
+
const entry = rawEntry;
|
|
1118
|
+
if (entry && typeof entry === 'object' && entry.alwaysLoad === true) {
|
|
1119
|
+
servers.get(normalized).alwaysLoadPaths.push(p);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
return servers;
|
|
1124
|
+
}
|
|
1125
|
+
/// Server names owned by readable local MCP config, normalized the way
|
|
1126
|
+
/// transcript namespaces are (mcpNamespace). `loadMcpConfigs` covers
|
|
1127
|
+
/// project settings and .mcp.json; `~/.claude.json` adds the top-level and
|
|
1128
|
+
/// per-project `mcpServers` containers the remove plan also edits.
|
|
1129
|
+
///
|
|
1130
|
+
/// A `claude_ai_*` namespace listed here is a local server that happens to
|
|
1131
|
+
/// carry the connector prefix, not a claude.ai connector. Config we cannot
|
|
1132
|
+
/// read simply contributes no names, which leaves those namespaces on the
|
|
1133
|
+
/// conservative connector path.
|
|
1134
|
+
export function localMcpServerNames(projectCwds, homeDir = homedir()) {
|
|
1135
|
+
const names = new Set(loadMcpConfigs(projectCwds).keys());
|
|
1136
|
+
const userJson = readJsonFile(join(homeDir, '.claude.json'));
|
|
1137
|
+
const projects = (userJson?.['projects'] ?? {});
|
|
1138
|
+
const containers = [userJson?.['mcpServers'], ...Object.values(projects).map(entry => entry?.mcpServers)];
|
|
1139
|
+
for (const container of containers) {
|
|
1140
|
+
if (!container || typeof container !== 'object')
|
|
1141
|
+
continue;
|
|
1142
|
+
for (const name of Object.keys(container))
|
|
1143
|
+
names.add(mcpNamespace(name));
|
|
1144
|
+
}
|
|
1145
|
+
return names;
|
|
1146
|
+
}
|
|
1147
|
+
// ============================================================================
|
|
1148
|
+
// Detectors
|
|
1149
|
+
// ============================================================================
|
|
1150
|
+
export function detectJunkReads(calls, dateRange, pricing) {
|
|
1151
|
+
const dirCounts = new Map();
|
|
1152
|
+
let totalJunkReads = 0;
|
|
1153
|
+
let recentJunkReads = 0;
|
|
1154
|
+
let savingsUSD = 0;
|
|
1155
|
+
for (const call of calls) {
|
|
1156
|
+
if (!isReadTool(call.name))
|
|
1157
|
+
continue;
|
|
1158
|
+
const filePath = call.input.file_path;
|
|
1159
|
+
if (!filePath || !JUNK_PATTERN.test(filePath))
|
|
1160
|
+
continue;
|
|
1161
|
+
totalJunkReads++;
|
|
1162
|
+
if (call.recent)
|
|
1163
|
+
recentJunkReads++;
|
|
1164
|
+
if (pricing)
|
|
1165
|
+
savingsUSD += sessionTokensUSD(pricing, call.sessionId, AVG_TOKENS_PER_READ, 'input');
|
|
1166
|
+
for (const dir of JUNK_DIRS) {
|
|
1167
|
+
if (filePath.includes(`/${dir}/`)) {
|
|
1168
|
+
dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + 1);
|
|
1169
|
+
break;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
if (totalJunkReads < MIN_JUNK_READS_TO_FLAG)
|
|
1174
|
+
return null;
|
|
1175
|
+
const hasRecentActivity = calls.some(c => c.recent);
|
|
1176
|
+
const trend = sessionTrend(recentJunkReads, totalJunkReads, dateRange, hasRecentActivity);
|
|
1177
|
+
if (trend === 'resolved')
|
|
1178
|
+
return null;
|
|
1179
|
+
const sorted = [...dirCounts.entries()].sort((a, b) => b[1] - a[1]);
|
|
1180
|
+
const dirList = sorted.slice(0, TOP_ITEMS_PREVIEW).map(([d, n]) => `${d}/ (${n}x)`).join(', ');
|
|
1181
|
+
const tokensSaved = totalJunkReads * AVG_TOKENS_PER_READ;
|
|
1182
|
+
const detected = sorted.map(([d]) => d);
|
|
1183
|
+
const commonDefaults = ['node_modules', '.git', 'dist', '__pycache__'];
|
|
1184
|
+
const extras = commonDefaults.filter(d => !dirCounts.has(d)).slice(0, Math.max(0, 6 - detected.length));
|
|
1185
|
+
const dirsToAvoid = [...detected, ...extras].join(', ');
|
|
1186
|
+
return {
|
|
1187
|
+
id: 'build-folder-reads',
|
|
1188
|
+
title: 'Claude is reading build/dependency folders',
|
|
1189
|
+
explanation: `Claude read into ${dirList} (${totalJunkReads} reads). These are generated or dependency directories, not your code. Tell Claude in CLAUDE.md to avoid them.`,
|
|
1190
|
+
impact: totalJunkReads > JUNK_READS_HIGH_THRESHOLD ? 'high' : totalJunkReads > JUNK_READS_MEDIUM_THRESHOLD ? 'medium' : 'low',
|
|
1191
|
+
tokensSaved,
|
|
1192
|
+
...(pricing ? { savingsUSD } : {}),
|
|
1193
|
+
fix: {
|
|
1194
|
+
type: 'paste',
|
|
1195
|
+
destination: 'claude-md',
|
|
1196
|
+
label: 'Append to your project CLAUDE.md:',
|
|
1197
|
+
text: `Do not read or search files under these directories unless I explicitly ask: ${dirsToAvoid}.`,
|
|
1198
|
+
},
|
|
1199
|
+
trend,
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
export function detectDuplicateReads(calls, dateRange, pricing) {
|
|
1203
|
+
// A sidechain re-reading what its parent read is not a repeat: a subagent
|
|
1204
|
+
// starts on a fresh context and has to read it. Junk reads and the
|
|
1205
|
+
// read:edit ratio keep the full call population - that waste is waste
|
|
1206
|
+
// whoever does it, and the CLAUDE.md rule they suggest binds subagents too.
|
|
1207
|
+
calls = calls.filter(call => call.isSidechain !== true);
|
|
1208
|
+
const sessionFiles = new Map();
|
|
1209
|
+
for (const call of calls) {
|
|
1210
|
+
if (!isReadTool(call.name))
|
|
1211
|
+
continue;
|
|
1212
|
+
const filePath = call.input.file_path;
|
|
1213
|
+
if (!filePath || JUNK_PATTERN.test(filePath))
|
|
1214
|
+
continue;
|
|
1215
|
+
const key = `${call.project}:${call.sessionId}`;
|
|
1216
|
+
if (!sessionFiles.has(key))
|
|
1217
|
+
sessionFiles.set(key, { sessionId: call.sessionId, files: new Map() });
|
|
1218
|
+
const fm = sessionFiles.get(key).files;
|
|
1219
|
+
const entry = fm.get(filePath) ?? { count: 0, recent: 0 };
|
|
1220
|
+
entry.count++;
|
|
1221
|
+
if (call.recent)
|
|
1222
|
+
entry.recent++;
|
|
1223
|
+
fm.set(filePath, entry);
|
|
1224
|
+
}
|
|
1225
|
+
let totalDuplicates = 0;
|
|
1226
|
+
let recentDuplicates = 0;
|
|
1227
|
+
let savingsUSD = 0;
|
|
1228
|
+
const fileDupes = new Map();
|
|
1229
|
+
for (const { sessionId, files } of sessionFiles.values()) {
|
|
1230
|
+
for (const [file, entry] of files) {
|
|
1231
|
+
if (entry.count <= 1)
|
|
1232
|
+
continue;
|
|
1233
|
+
const extra = entry.count - 1;
|
|
1234
|
+
totalDuplicates += extra;
|
|
1235
|
+
if (pricing)
|
|
1236
|
+
savingsUSD += sessionTokensUSD(pricing, sessionId, extra * AVG_TOKENS_PER_READ, 'input');
|
|
1237
|
+
if (entry.recent > 1)
|
|
1238
|
+
recentDuplicates += entry.recent - 1;
|
|
1239
|
+
const name = basename(file);
|
|
1240
|
+
fileDupes.set(name, (fileDupes.get(name) ?? 0) + extra);
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
if (totalDuplicates < MIN_DUPLICATE_READS_TO_FLAG)
|
|
1244
|
+
return null;
|
|
1245
|
+
const hasRecentActivity = calls.some(c => c.recent);
|
|
1246
|
+
const trend = sessionTrend(recentDuplicates, totalDuplicates, dateRange, hasRecentActivity);
|
|
1247
|
+
if (trend === 'resolved')
|
|
1248
|
+
return null;
|
|
1249
|
+
const worst = [...fileDupes.entries()]
|
|
1250
|
+
.sort((a, b) => b[1] - a[1])
|
|
1251
|
+
.slice(0, TOP_ITEMS_PREVIEW)
|
|
1252
|
+
.map(([name, n]) => `${name} (${n + 1}x)`)
|
|
1253
|
+
.join(', ');
|
|
1254
|
+
const tokensSaved = totalDuplicates * AVG_TOKENS_PER_READ;
|
|
1255
|
+
return {
|
|
1256
|
+
id: 'redundant-rereads',
|
|
1257
|
+
title: 'Claude is re-reading the same files',
|
|
1258
|
+
explanation: `${totalDuplicates} redundant re-reads across sessions. Top repeats: ${worst}. Each re-read loads the same content into context again.`,
|
|
1259
|
+
impact: totalDuplicates > DUPLICATE_READS_HIGH_THRESHOLD ? 'high' : totalDuplicates > DUPLICATE_READS_MEDIUM_THRESHOLD ? 'medium' : 'low',
|
|
1260
|
+
tokensSaved,
|
|
1261
|
+
...(pricing ? { savingsUSD } : {}),
|
|
1262
|
+
fix: {
|
|
1263
|
+
type: 'paste',
|
|
1264
|
+
destination: 'prompt',
|
|
1265
|
+
label: 'Point Claude at exact locations in your prompt, for example:',
|
|
1266
|
+
text: 'In <file> lines <start>-<end>, look at the <function> function.',
|
|
1267
|
+
},
|
|
1268
|
+
trend,
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Aggregate MCP inventory and invocations across the projects in scope.
|
|
1273
|
+
*
|
|
1274
|
+
* Returns one entry per `mcp__<server>__*` namespace observed in any
|
|
1275
|
+
* session's `mcpInventory`. Counts of invocations come from
|
|
1276
|
+
* `session.mcpBreakdown` (per-server call totals already maintained by the
|
|
1277
|
+
* parser).
|
|
1278
|
+
*/
|
|
1279
|
+
export function aggregateMcpCoverage(projects) {
|
|
1280
|
+
const servers = new Map();
|
|
1281
|
+
function getOrInit(server) {
|
|
1282
|
+
let acc = servers.get(server);
|
|
1283
|
+
if (!acc) {
|
|
1284
|
+
acc = { inventory: new Set(), invokedTools: new Set(), invocations: 0, loadedSessions: 0 };
|
|
1285
|
+
servers.set(server, acc);
|
|
1286
|
+
}
|
|
1287
|
+
return acc;
|
|
1288
|
+
}
|
|
1289
|
+
for (const project of projects) {
|
|
1290
|
+
for (const session of project.sessions) {
|
|
1291
|
+
// Only sessions with an observed inventory count toward `loadedSessions`.
|
|
1292
|
+
// Pure invocation-only sessions (server seen via `call.mcpTools` or
|
|
1293
|
+
// `session.mcpBreakdown` without any matching `deferred_tools_delta`)
|
|
1294
|
+
// could otherwise satisfy the `MCP_COVERAGE_MIN_SESSIONS` threshold
|
|
1295
|
+
// without giving us evidence that the schema was actually loaded.
|
|
1296
|
+
const inventoriedServers = new Set();
|
|
1297
|
+
const sessionInvoked = new Map();
|
|
1298
|
+
// Inventory: union of tools observed available in this session.
|
|
1299
|
+
for (const fqn of session.mcpInventory ?? []) {
|
|
1300
|
+
const parts = fqn.split('__');
|
|
1301
|
+
if (parts.length < 3 || parts[0] !== 'mcp')
|
|
1302
|
+
continue;
|
|
1303
|
+
const server = parts[1];
|
|
1304
|
+
if (!server)
|
|
1305
|
+
continue;
|
|
1306
|
+
const tool = parts.slice(2).join('__');
|
|
1307
|
+
if (!tool)
|
|
1308
|
+
continue;
|
|
1309
|
+
const acc = getOrInit(server);
|
|
1310
|
+
acc.inventory.add(fqn);
|
|
1311
|
+
inventoriedServers.add(server);
|
|
1312
|
+
}
|
|
1313
|
+
// Invoked tools: walk turns to collect per-tool invocations. We can't
|
|
1314
|
+
// get this from session.mcpBreakdown alone because that's keyed by
|
|
1315
|
+
// server, not tool.
|
|
1316
|
+
for (const turn of session.turns) {
|
|
1317
|
+
for (const call of turn.assistantCalls) {
|
|
1318
|
+
for (const fqn of call.mcpTools) {
|
|
1319
|
+
const parts = fqn.split('__');
|
|
1320
|
+
if (parts.length < 3 || parts[0] !== 'mcp')
|
|
1321
|
+
continue;
|
|
1322
|
+
const server = parts[1];
|
|
1323
|
+
if (!server)
|
|
1324
|
+
continue;
|
|
1325
|
+
let invoked = sessionInvoked.get(server);
|
|
1326
|
+
if (!invoked) {
|
|
1327
|
+
invoked = new Set();
|
|
1328
|
+
sessionInvoked.set(server, invoked);
|
|
1329
|
+
}
|
|
1330
|
+
invoked.add(fqn);
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
// Invocation totals: trust mcpBreakdown which was already aggregated
|
|
1335
|
+
// turn-by-turn, including any invocations the inventory pass missed.
|
|
1336
|
+
for (const [server, data] of Object.entries(session.mcpBreakdown)) {
|
|
1337
|
+
const acc = getOrInit(server);
|
|
1338
|
+
acc.invocations += data.calls;
|
|
1339
|
+
}
|
|
1340
|
+
for (const [server, invoked] of sessionInvoked) {
|
|
1341
|
+
const acc = getOrInit(server);
|
|
1342
|
+
for (const fqn of invoked)
|
|
1343
|
+
acc.invokedTools.add(fqn);
|
|
1344
|
+
}
|
|
1345
|
+
for (const server of inventoriedServers) {
|
|
1346
|
+
getOrInit(server).loadedSessions += 1;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
const result = [];
|
|
1351
|
+
for (const [server, acc] of servers) {
|
|
1352
|
+
if (acc.inventory.size === 0)
|
|
1353
|
+
continue;
|
|
1354
|
+
// Coverage is only meaningful against tools we actually observed in the
|
|
1355
|
+
// inventory: invocations of tools never inventoried (older config, typo,
|
|
1356
|
+
// etc.) would otherwise inflate the numerator and could even drive
|
|
1357
|
+
// `unusedCount` negative.
|
|
1358
|
+
const invokedInInventory = new Set();
|
|
1359
|
+
for (const fqn of acc.invokedTools) {
|
|
1360
|
+
if (acc.inventory.has(fqn))
|
|
1361
|
+
invokedInInventory.add(fqn);
|
|
1362
|
+
}
|
|
1363
|
+
const unusedTools = Array.from(acc.inventory).filter(t => !invokedInInventory.has(t)).sort();
|
|
1364
|
+
const toolsInvoked = acc.inventory.size - unusedTools.length;
|
|
1365
|
+
result.push({
|
|
1366
|
+
server,
|
|
1367
|
+
toolsAvailable: acc.inventory.size,
|
|
1368
|
+
toolsInvoked,
|
|
1369
|
+
unusedTools,
|
|
1370
|
+
invocations: acc.invocations,
|
|
1371
|
+
loadedSessions: acc.loadedSessions,
|
|
1372
|
+
coverageRatio: acc.inventory.size === 0 ? 0 : toolsInvoked / acc.inventory.size,
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
result.sort((a, b) => b.toolsAvailable - a.toolsAvailable);
|
|
1376
|
+
return result;
|
|
1377
|
+
}
|
|
1378
|
+
export function estimateMcpSchemaCost(unusedToolCounts, projects, serverOrServers) {
|
|
1379
|
+
let servers;
|
|
1380
|
+
let counts;
|
|
1381
|
+
if (typeof unusedToolCounts === 'number') {
|
|
1382
|
+
if (typeof serverOrServers !== 'string') {
|
|
1383
|
+
throw new TypeError('single-server MCP cost estimates require a string server name');
|
|
1384
|
+
}
|
|
1385
|
+
servers = [serverOrServers];
|
|
1386
|
+
counts = { [serverOrServers]: unusedToolCounts };
|
|
1387
|
+
}
|
|
1388
|
+
else {
|
|
1389
|
+
if (!Array.isArray(serverOrServers)) {
|
|
1390
|
+
throw new TypeError('multi-server MCP cost estimates require a string[] server list');
|
|
1391
|
+
}
|
|
1392
|
+
servers = serverOrServers;
|
|
1393
|
+
counts = unusedToolCounts;
|
|
1394
|
+
}
|
|
1395
|
+
const attributed = estimateMcpSchemaCostAttributed(counts, projects, servers);
|
|
1396
|
+
return {
|
|
1397
|
+
cacheWriteTokens: attributed.cacheWriteTokens,
|
|
1398
|
+
cacheReadTokens: attributed.cacheReadTokens,
|
|
1399
|
+
effectiveInputTokens: attributed.effectiveInputTokens,
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
function estimateMcpSchemaCostAttributed(unusedToolsByServer, projects, servers, pricing) {
|
|
1403
|
+
servers = [...new Set(servers)];
|
|
1404
|
+
const byServer = {};
|
|
1405
|
+
for (const server of servers) {
|
|
1406
|
+
byServer[server] = { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0 };
|
|
1407
|
+
}
|
|
1408
|
+
const addBucket = (loaded, bucket, key) => {
|
|
1409
|
+
if (bucket <= 0)
|
|
1410
|
+
return 0;
|
|
1411
|
+
const totalSchemaTokens = loaded.reduce((sum, entry) => sum + entry.schemaTokens, 0);
|
|
1412
|
+
if (totalSchemaTokens <= 0)
|
|
1413
|
+
return 0;
|
|
1414
|
+
const charged = Math.min(totalSchemaTokens, bucket);
|
|
1415
|
+
for (const entry of loaded) {
|
|
1416
|
+
byServer[entry.server][key] += charged * (entry.schemaTokens / totalSchemaTokens);
|
|
1417
|
+
}
|
|
1418
|
+
return charged;
|
|
1419
|
+
};
|
|
1420
|
+
let usd = 0;
|
|
1421
|
+
for (const project of projects) {
|
|
1422
|
+
for (const session of project.sessions) {
|
|
1423
|
+
const inventory = new Set(session.mcpInventory ?? []);
|
|
1424
|
+
const inventoryCounts = new Map();
|
|
1425
|
+
for (const fqn of inventory) {
|
|
1426
|
+
const parts = fqn.split('__');
|
|
1427
|
+
if (parts[0] !== 'mcp' || !parts[1] || parts.length < 3)
|
|
1428
|
+
continue;
|
|
1429
|
+
inventoryCounts.set(parts[1], (inventoryCounts.get(parts[1]) ?? 0) + 1);
|
|
1430
|
+
}
|
|
1431
|
+
const loaded = [];
|
|
1432
|
+
for (const server of servers) {
|
|
1433
|
+
const unused = unusedToolsByServer[server];
|
|
1434
|
+
const toolCount = typeof unused === 'number'
|
|
1435
|
+
? Math.min(unused, inventoryCounts.get(server) ?? 0)
|
|
1436
|
+
: [...new Set(unused ?? [])].reduce((count, fqn) => count + (inventory.has(fqn) ? 1 : 0), 0);
|
|
1437
|
+
if (toolCount > 0)
|
|
1438
|
+
loaded.push({ server, schemaTokens: toolCount * TOKENS_PER_DEFERRED_MCP_TOOL });
|
|
1439
|
+
}
|
|
1440
|
+
if (loaded.length === 0)
|
|
1441
|
+
continue;
|
|
1442
|
+
for (const turn of session.turns) {
|
|
1443
|
+
for (const call of turn.assistantCalls) {
|
|
1444
|
+
// A cache bucket is shared by every flagged schema loaded on this
|
|
1445
|
+
// call. Charge it once, then attribute the capped amount in
|
|
1446
|
+
// proportion to each server's unused schema. This conserves the
|
|
1447
|
+
// combined total and makes any local-only subset additive.
|
|
1448
|
+
// The tool lines sit in the prefix: a call that read cache read
|
|
1449
|
+
// them; only a call with no cache read wrote them.
|
|
1450
|
+
if (call.usage.cacheReadInputTokens > 0) {
|
|
1451
|
+
const charged = addBucket(loaded, call.usage.cacheReadInputTokens, 'cacheReadTokens');
|
|
1452
|
+
if (pricing && charged > 0)
|
|
1453
|
+
usd += schemaChargeUSD(pricing, call.model, charged, 'cacheRead');
|
|
1454
|
+
}
|
|
1455
|
+
else {
|
|
1456
|
+
const charged = addBucket(loaded, call.usage.cacheCreationInputTokens, 'cacheWriteTokens');
|
|
1457
|
+
if (pricing && charged > 0)
|
|
1458
|
+
usd += schemaChargeUSD(pricing, call.model, charged, 'cacheWrite');
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
let cacheWriteTokens = 0;
|
|
1465
|
+
let cacheReadTokens = 0;
|
|
1466
|
+
for (const estimate of Object.values(byServer)) {
|
|
1467
|
+
estimate.effectiveInputTokens = estimate.cacheWriteTokens * CACHE_WRITE_MULTIPLIER
|
|
1468
|
+
+ estimate.cacheReadTokens * CACHE_READ_DISCOUNT;
|
|
1469
|
+
cacheWriteTokens += estimate.cacheWriteTokens;
|
|
1470
|
+
cacheReadTokens += estimate.cacheReadTokens;
|
|
1471
|
+
}
|
|
1472
|
+
return {
|
|
1473
|
+
cacheWriteTokens,
|
|
1474
|
+
cacheReadTokens,
|
|
1475
|
+
effectiveInputTokens: cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT,
|
|
1476
|
+
byServer,
|
|
1477
|
+
usd,
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
/// The effective schema tokens per loaded session that mcp-low-coverage
|
|
1481
|
+
/// charges each of `servers`, from the same per-call attribution as the finding.
|
|
1482
|
+
export function mcpLowCoverageSchemaPerSession(projects, coverage, servers) {
|
|
1483
|
+
const covByServer = new Map(coverage.filter(c => servers.includes(c.server)).map(c => [c.server, c]));
|
|
1484
|
+
const unused = Object.fromEntries([...covByServer].map(([server, c]) => [server, c.unusedTools]));
|
|
1485
|
+
const cost = estimateMcpSchemaCostAttributed(unused, projects, servers);
|
|
1486
|
+
return Object.fromEntries(servers.map(server => {
|
|
1487
|
+
const loaded = covByServer.get(server)?.loadedSessions ?? 0;
|
|
1488
|
+
return [server, loaded > 0 ? (cost.byServer[server]?.effectiveInputTokens ?? 0) / loaded : 0];
|
|
1489
|
+
}));
|
|
1490
|
+
}
|
|
1491
|
+
/// Cached schema tokens at the call model's own cache rate; unpriced models
|
|
1492
|
+
/// keep the effective-input weighting at the blended rate.
|
|
1493
|
+
function schemaChargeUSD(pricing, model, tokens, kind) {
|
|
1494
|
+
const rate = modelRate(pricing, model, kind)
|
|
1495
|
+
?? pricing.fallbackRate * (kind === 'cacheWrite' ? CACHE_WRITE_MULTIPLIER : CACHE_READ_DISCOUNT);
|
|
1496
|
+
return tokens * rate;
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Find MCP servers whose tool inventory is largely unused. Replaces the
|
|
1500
|
+
* older server-only `detectUnusedMcp` (which only flagged servers with
|
|
1501
|
+
* literal zero invocations).
|
|
1502
|
+
*
|
|
1503
|
+
* A server is flagged when, taken together:
|
|
1504
|
+
* - it exposed more than `MCP_COVERAGE_MIN_TOOLS` tools,
|
|
1505
|
+
* - we saw it loaded in at least `MCP_COVERAGE_MIN_SESSIONS` sessions,
|
|
1506
|
+
* - the coverage ratio is below `MCP_COVERAGE_LOW_THRESHOLD`.
|
|
1507
|
+
*
|
|
1508
|
+
* Token-savings estimates use the cache-aware accounting from
|
|
1509
|
+
* `estimateMcpSchemaCost` so we don't mistake cached-prefix carry-over for
|
|
1510
|
+
* fresh-input billing.
|
|
1511
|
+
*/
|
|
1512
|
+
export function detectMcpToolCoverage(projects, coverage = aggregateMcpCoverage(projects), localServerNames = new Set(), pricing) {
|
|
1513
|
+
if (coverage.length === 0)
|
|
1514
|
+
return null;
|
|
1515
|
+
const flagged = coverage.filter(c => c.toolsAvailable > MCP_COVERAGE_MIN_TOOLS
|
|
1516
|
+
&& c.loadedSessions >= MCP_COVERAGE_MIN_SESSIONS
|
|
1517
|
+
&& c.coverageRatio < MCP_COVERAGE_LOW_THRESHOLD);
|
|
1518
|
+
if (flagged.length === 0)
|
|
1519
|
+
return null;
|
|
1520
|
+
flagged.sort((a, b) => (b.toolsAvailable - b.toolsInvoked) - (a.toolsAvailable - a.toolsInvoked));
|
|
1521
|
+
const lines = [];
|
|
1522
|
+
const removeCommands = [];
|
|
1523
|
+
const unusedToolsByServer = {};
|
|
1524
|
+
const flaggedServers = [];
|
|
1525
|
+
const localServers = [];
|
|
1526
|
+
const connectorServers = [];
|
|
1527
|
+
// Local, but named like a connector: the transcript cannot tell the two
|
|
1528
|
+
// apart, so the removal targets the config entry and the guidance warns
|
|
1529
|
+
// about a possible same-name connector instead of asserting one.
|
|
1530
|
+
const ambiguousServers = [];
|
|
1531
|
+
for (const c of flagged) {
|
|
1532
|
+
unusedToolsByServer[c.server] = c.unusedTools;
|
|
1533
|
+
flaggedServers.push(c.server);
|
|
1534
|
+
const pct = Math.round(c.coverageRatio * 100);
|
|
1535
|
+
lines.push(`${c.server}: ${c.toolsInvoked}/${c.toolsAvailable} tools used (${pct}% coverage) across ${c.loadedSessions} session${c.loadedSessions === 1 ? '' : 's'}`);
|
|
1536
|
+
if (c.server.startsWith('claude_ai_') && !localServerNames.has(c.server)) {
|
|
1537
|
+
connectorServers.push(c.server);
|
|
1538
|
+
}
|
|
1539
|
+
else {
|
|
1540
|
+
if (c.server.startsWith('claude_ai_'))
|
|
1541
|
+
ambiguousServers.push(c.server);
|
|
1542
|
+
localServers.push(c.server);
|
|
1543
|
+
removeCommands.push(`claude mcp remove '${c.server}'`);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
// Single combined cost pass: caps each call's contribution at the
|
|
1547
|
+
// total unused-schema budget across all flagged servers, so two
|
|
1548
|
+
// flagged servers cannot independently claim the same call's cache
|
|
1549
|
+
// bucket and overstate `tokensSaved`.
|
|
1550
|
+
const cost = estimateMcpSchemaCostAttributed(unusedToolsByServer, projects, flaggedServers, pricing);
|
|
1551
|
+
const tokensSaved = Math.round(cost.effectiveInputTokens);
|
|
1552
|
+
const applyTokensSavedByServer = Object.fromEntries(localServers.map(server => [
|
|
1553
|
+
server,
|
|
1554
|
+
cost.byServer[server]?.effectiveInputTokens ?? 0,
|
|
1555
|
+
]));
|
|
1556
|
+
const localTokensSaved = Object.values(applyTokensSavedByServer).reduce((sum, value) => sum + value, 0);
|
|
1557
|
+
const applyTokensSaved = localServers.length > 0 && connectorServers.length > 0
|
|
1558
|
+
? Math.round(localTokensSaved)
|
|
1559
|
+
: undefined;
|
|
1560
|
+
const impact = tokensSaved >= MCP_COVERAGE_HIGH_IMPACT_TOKENS
|
|
1561
|
+
? 'high'
|
|
1562
|
+
: flagged.length >= UNUSED_MCP_HIGH_THRESHOLD
|
|
1563
|
+
? 'high'
|
|
1564
|
+
: 'medium';
|
|
1565
|
+
// `claude_ai_*` is Claude Code's transcript namespace for server-side
|
|
1566
|
+
// claude.ai connectors, which are not local mcpServers entries, so
|
|
1567
|
+
// `claude mcp remove` and the file-editing apply plan cannot own them --
|
|
1568
|
+
// unless readable local config claims the exact name (`ambiguousServers`).
|
|
1569
|
+
// Coverage is aggregate here; project-level config attribution is deliberately
|
|
1570
|
+
// out of scope, hence the instruction to inspect /mcp per affected project.
|
|
1571
|
+
const one = connectorServers.length === 1;
|
|
1572
|
+
const connectorLabels = connectorServers.map(server => `claude.ai ${server.slice('claude_ai_'.length).replaceAll('_', ' ')}`);
|
|
1573
|
+
const connectorEvidence = connectorServers.map((server, index) => `${connectorLabels[index]} (${server})`);
|
|
1574
|
+
const connectorGuidance = connectorServers.length > 0
|
|
1575
|
+
? ` ${connectorEvidence.join(', ')} ${one ? 'is a claude.ai connector namespace' : 'are claude.ai connector namespaces'}, separate from any similarly named local MCP server. Transcript inventory is aggregated across the selected projects; use /mcp in each project where ${one ? 'it loads' : 'they load'}, or manage ${one ? 'it' : 'them'} in claude.ai Settings > Connectors.`
|
|
1576
|
+
: '';
|
|
1577
|
+
const oneAmbiguous = ambiguousServers.length === 1;
|
|
1578
|
+
const ambiguousNote = ambiguousServers.length > 0
|
|
1579
|
+
? `If you also use ${oneAmbiguous ? 'a claude.ai connector' : 'claude.ai connectors'} named ${ambiguousServers.join(', ')}, manage ${oneAmbiguous ? 'it' : 'them'} with /mcp or in claude.ai Settings > Connectors.`
|
|
1580
|
+
: '';
|
|
1581
|
+
const ambiguousGuidance = ambiguousServers.length > 0
|
|
1582
|
+
? ` ${ambiguousServers.join(', ')} ${oneAmbiguous ? 'is a local MCP config entry whose name matches' : 'are local MCP config entries whose names match'} the claude.ai connector namespace, so the removal below edits local config only. ${ambiguousNote}`
|
|
1583
|
+
: '';
|
|
1584
|
+
const connectorText = [
|
|
1585
|
+
connectorServers.length > 0
|
|
1586
|
+
? `Open /mcp in each affected project and disable ${connectorLabels.join(', ')}, or manage ${one ? 'it' : 'them'} in claude.ai Settings > Connectors.`
|
|
1587
|
+
: '',
|
|
1588
|
+
ambiguousNote,
|
|
1589
|
+
].filter(Boolean).join(' ');
|
|
1590
|
+
const connectorAction = connectorText
|
|
1591
|
+
? {
|
|
1592
|
+
label: connectorServers.length === 0
|
|
1593
|
+
? 'Check for a same-name claude.ai connector:'
|
|
1594
|
+
: one ? 'Manage the underused claude.ai connector where it loads:'
|
|
1595
|
+
: 'Manage the underused claude.ai connectors where they load:',
|
|
1596
|
+
text: connectorText,
|
|
1597
|
+
}
|
|
1598
|
+
: undefined;
|
|
1599
|
+
const fix = localServers.length > 0
|
|
1600
|
+
? {
|
|
1601
|
+
type: 'command',
|
|
1602
|
+
label: localServers.length === 1
|
|
1603
|
+
? 'Remove the underused local server, or trim its tools in your MCP config:'
|
|
1604
|
+
: 'Remove underused local servers, or trim their tools in your MCP config:',
|
|
1605
|
+
text: removeCommands.join('\n'),
|
|
1606
|
+
}
|
|
1607
|
+
: {
|
|
1608
|
+
type: 'paste',
|
|
1609
|
+
destination: 'manual',
|
|
1610
|
+
label: connectorAction.label,
|
|
1611
|
+
text: connectorAction.text,
|
|
1612
|
+
};
|
|
1613
|
+
return {
|
|
1614
|
+
id: 'mcp-low-coverage',
|
|
1615
|
+
title: `${flagged.length} MCP server${flagged.length === 1 ? '' : 's'} with low tool coverage`,
|
|
1616
|
+
explanation: `Each unused tool adds a deferred name line to every session's prompt, ` +
|
|
1617
|
+
`carried in the cached prefix on every turn. ` +
|
|
1618
|
+
`${lines.join('; ')}.${connectorGuidance}${ambiguousGuidance}`,
|
|
1619
|
+
impact,
|
|
1620
|
+
tokensSaved,
|
|
1621
|
+
...(pricing ? { savingsUSD: cost.usd } : {}),
|
|
1622
|
+
...(applyTokensSaved !== undefined ? { applyTokensSaved } : {}),
|
|
1623
|
+
...(localServers.length > 0 ? { applyTokensSavedByServer } : {}),
|
|
1624
|
+
...(localServers.length > 0 && connectorAction ? { manualFollowUp: connectorAction } : {}),
|
|
1625
|
+
fix,
|
|
1626
|
+
...(localServers.length > 0
|
|
1627
|
+
? { apply: { kind: 'mcp-remove', servers: localServers } }
|
|
1628
|
+
: {}),
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
function projectProfileLabel(project) {
|
|
1632
|
+
return project.projectPath || project.project;
|
|
1633
|
+
}
|
|
1634
|
+
function projectProfileKey(project) {
|
|
1635
|
+
return projectProfileLabel(project);
|
|
1636
|
+
}
|
|
1637
|
+
function sessionLoadedMcpServer(session, server) {
|
|
1638
|
+
for (const fqn of session.mcpInventory ?? []) {
|
|
1639
|
+
const parts = fqn.split('__');
|
|
1640
|
+
if (parts.length >= 3 && parts[0] === 'mcp' && parts[1] === server)
|
|
1641
|
+
return true;
|
|
1642
|
+
}
|
|
1643
|
+
return false;
|
|
1644
|
+
}
|
|
1645
|
+
function lowCoverageMcpServers(coverage) {
|
|
1646
|
+
return new Set(coverage
|
|
1647
|
+
.filter(c => c.toolsAvailable > MCP_COVERAGE_MIN_TOOLS
|
|
1648
|
+
&& c.loadedSessions >= MCP_COVERAGE_MIN_SESSIONS
|
|
1649
|
+
&& c.coverageRatio < MCP_COVERAGE_LOW_THRESHOLD)
|
|
1650
|
+
.map(c => c.server));
|
|
1651
|
+
}
|
|
1652
|
+
function estimateMcpProfileColdSchemaCost(projects, serverToolCounts, coldProjectKeysByServer, pricing) {
|
|
1653
|
+
if (serverToolCounts.size === 0 || coldProjectKeysByServer.size === 0) {
|
|
1654
|
+
return { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0, usd: 0 };
|
|
1655
|
+
}
|
|
1656
|
+
let cacheWriteTokens = 0;
|
|
1657
|
+
let cacheReadTokens = 0;
|
|
1658
|
+
let usd = 0;
|
|
1659
|
+
for (const project of projects) {
|
|
1660
|
+
const projectKey = projectProfileKey(project);
|
|
1661
|
+
for (const session of project.sessions) {
|
|
1662
|
+
let schemaTokens = 0;
|
|
1663
|
+
for (const [server, toolsAvailable] of serverToolCounts) {
|
|
1664
|
+
if (!coldProjectKeysByServer.get(server)?.has(projectKey))
|
|
1665
|
+
continue;
|
|
1666
|
+
if (!sessionLoadedMcpServer(session, server))
|
|
1667
|
+
continue;
|
|
1668
|
+
schemaTokens += toolsAvailable * TOKENS_PER_DEFERRED_MCP_TOOL;
|
|
1669
|
+
}
|
|
1670
|
+
if (schemaTokens === 0)
|
|
1671
|
+
continue;
|
|
1672
|
+
for (const turn of session.turns) {
|
|
1673
|
+
for (const call of turn.assistantCalls) {
|
|
1674
|
+
if (call.usage.cacheReadInputTokens > 0) {
|
|
1675
|
+
const charged = Math.min(schemaTokens, call.usage.cacheReadInputTokens);
|
|
1676
|
+
cacheReadTokens += charged;
|
|
1677
|
+
if (pricing)
|
|
1678
|
+
usd += schemaChargeUSD(pricing, call.model, charged, 'cacheRead');
|
|
1679
|
+
}
|
|
1680
|
+
else if (call.usage.cacheCreationInputTokens > 0) {
|
|
1681
|
+
const charged = Math.min(schemaTokens, call.usage.cacheCreationInputTokens);
|
|
1682
|
+
cacheWriteTokens += charged;
|
|
1683
|
+
if (pricing)
|
|
1684
|
+
usd += schemaChargeUSD(pricing, call.model, charged, 'cacheWrite');
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
const effectiveInputTokens = cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT;
|
|
1691
|
+
return { cacheWriteTokens, cacheReadTokens, effectiveInputTokens, usd };
|
|
1692
|
+
}
|
|
1693
|
+
/// The effective cold-project schema tokens per cold loaded session that
|
|
1694
|
+
/// mcp-project-scope charges each scoped server, from the finding's own pass.
|
|
1695
|
+
export function mcpProjectScopeSchemaPerSession(projects, coverage, scoped) {
|
|
1696
|
+
const tools = new Map(coverage.map(c => [c.server, c.toolsAvailable]));
|
|
1697
|
+
return Object.fromEntries(scoped.map(({ server, removeProjects }) => {
|
|
1698
|
+
const cold = new Set(removeProjects);
|
|
1699
|
+
const cost = estimateMcpProfileColdSchemaCost(projects, new Map([[server, tools.get(server) ?? 0]]), new Map([[server, cold]]));
|
|
1700
|
+
const sessions = projects
|
|
1701
|
+
.filter(p => cold.has(projectProfileKey(p)))
|
|
1702
|
+
.reduce((n, p) => n + p.sessions.filter(s => sessionLoadedMcpServer(s, server)).length, 0);
|
|
1703
|
+
return [server, sessions > 0 ? cost.effectiveInputTokens / sessions : 0];
|
|
1704
|
+
}));
|
|
1705
|
+
}
|
|
1706
|
+
function collectMcpProjectProfiles(projects, coverage) {
|
|
1707
|
+
const suppressedServers = lowCoverageMcpServers(coverage);
|
|
1708
|
+
const coverageByServer = new Map(coverage.map(c => [c.server, c]));
|
|
1709
|
+
const byServer = new Map();
|
|
1710
|
+
function getProjectStats(server, project) {
|
|
1711
|
+
let serverProjects = byServer.get(server);
|
|
1712
|
+
if (!serverProjects) {
|
|
1713
|
+
serverProjects = new Map();
|
|
1714
|
+
byServer.set(server, serverProjects);
|
|
1715
|
+
}
|
|
1716
|
+
const key = projectProfileKey(project);
|
|
1717
|
+
let stats = serverProjects.get(key);
|
|
1718
|
+
if (!stats) {
|
|
1719
|
+
stats = {
|
|
1720
|
+
project: project.project,
|
|
1721
|
+
projectKey: key,
|
|
1722
|
+
projectPath: projectProfileLabel(project),
|
|
1723
|
+
loadedSessions: 0,
|
|
1724
|
+
invocations: 0,
|
|
1725
|
+
};
|
|
1726
|
+
serverProjects.set(key, stats);
|
|
1727
|
+
}
|
|
1728
|
+
return stats;
|
|
1729
|
+
}
|
|
1730
|
+
for (const project of projects) {
|
|
1731
|
+
for (const session of project.sessions) {
|
|
1732
|
+
const loadedServers = new Set();
|
|
1733
|
+
for (const fqn of session.mcpInventory ?? []) {
|
|
1734
|
+
const parts = fqn.split('__');
|
|
1735
|
+
if (parts.length >= 3 && parts[0] === 'mcp' && parts[1])
|
|
1736
|
+
loadedServers.add(parts[1]);
|
|
1737
|
+
}
|
|
1738
|
+
for (const server of loadedServers) {
|
|
1739
|
+
getProjectStats(server, project).loadedSessions++;
|
|
1740
|
+
}
|
|
1741
|
+
for (const [server, data] of Object.entries(session.mcpBreakdown)) {
|
|
1742
|
+
getProjectStats(server, project).invocations += data.calls;
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
const candidates = [];
|
|
1747
|
+
for (const [server, projectStats] of byServer) {
|
|
1748
|
+
if (suppressedServers.has(server))
|
|
1749
|
+
continue;
|
|
1750
|
+
const coverageStats = coverageByServer.get(server);
|
|
1751
|
+
if (!coverageStats)
|
|
1752
|
+
continue;
|
|
1753
|
+
if (coverageStats.toolsAvailable === 0)
|
|
1754
|
+
continue;
|
|
1755
|
+
const loaded = Array.from(projectStats.values()).filter(p => p.loadedSessions > 0);
|
|
1756
|
+
if (loaded.length < MCP_PROFILE_MIN_PROJECTS)
|
|
1757
|
+
continue;
|
|
1758
|
+
const invocations = loaded.reduce((sum, p) => sum + p.invocations, 0);
|
|
1759
|
+
if (invocations < MCP_PROFILE_MIN_HOT_INVOCATIONS)
|
|
1760
|
+
continue;
|
|
1761
|
+
loaded.sort((a, b) => b.invocations - a.invocations
|
|
1762
|
+
|| b.loadedSessions - a.loadedSessions
|
|
1763
|
+
|| a.projectPath.localeCompare(b.projectPath));
|
|
1764
|
+
const invokedProjects = loaded.filter(p => p.invocations > 0);
|
|
1765
|
+
if (invokedProjects.length === 0)
|
|
1766
|
+
continue;
|
|
1767
|
+
const hotProjects = invokedProjects.slice(0, 2);
|
|
1768
|
+
const hotInvocations = hotProjects.reduce((sum, p) => sum + p.invocations, 0);
|
|
1769
|
+
const hotShare = hotInvocations / invocations;
|
|
1770
|
+
if (hotShare < MCP_PROFILE_HOT_INVOCATION_SHARE)
|
|
1771
|
+
continue;
|
|
1772
|
+
const coldProjects = loaded.filter(p => p.invocations === 0);
|
|
1773
|
+
const coldLoadedSessions = coldProjects.reduce((sum, p) => sum + p.loadedSessions, 0);
|
|
1774
|
+
if (coldLoadedSessions < MCP_PROFILE_MIN_COLD_LOADED_SESSIONS)
|
|
1775
|
+
continue;
|
|
1776
|
+
const coldProjectKeys = new Set(coldProjects.map(project => project.projectKey));
|
|
1777
|
+
const cost = estimateMcpProfileColdSchemaCost(projects, new Map([[server, coverageStats.toolsAvailable]]), new Map([[server, coldProjectKeys]]));
|
|
1778
|
+
candidates.push({
|
|
1779
|
+
server,
|
|
1780
|
+
toolsAvailable: coverageStats.toolsAvailable,
|
|
1781
|
+
hotProjects,
|
|
1782
|
+
coldProjects,
|
|
1783
|
+
coldProjectKeys,
|
|
1784
|
+
loadedProjects: loaded.length,
|
|
1785
|
+
loadedSessions: loaded.reduce((sum, p) => sum + p.loadedSessions, 0),
|
|
1786
|
+
invocations,
|
|
1787
|
+
hotShare,
|
|
1788
|
+
estimatedTokensSaved: Math.round(cost.effectiveInputTokens),
|
|
1789
|
+
});
|
|
1790
|
+
}
|
|
1791
|
+
candidates.sort((a, b) => b.estimatedTokensSaved - a.estimatedTokensSaved
|
|
1792
|
+
|| b.coldProjects.length - a.coldProjects.length
|
|
1793
|
+
|| b.loadedSessions - a.loadedSessions
|
|
1794
|
+
|| a.server.localeCompare(b.server));
|
|
1795
|
+
return candidates;
|
|
1796
|
+
}
|
|
1797
|
+
export function detectMcpProfileAdvisor(projects, coverage = aggregateMcpCoverage(projects), provider, pricing) {
|
|
1798
|
+
const candidates = collectMcpProjectProfiles(projects, coverage);
|
|
1799
|
+
if (candidates.length === 0)
|
|
1800
|
+
return null;
|
|
1801
|
+
const preview = candidates.slice(0, MCP_PROFILE_PREVIEW);
|
|
1802
|
+
const lines = preview.map(candidate => {
|
|
1803
|
+
const hot = candidate.hotProjects
|
|
1804
|
+
.slice(0, 2)
|
|
1805
|
+
.map(p => `${p.projectPath} (${p.invocations} call${p.invocations === 1 ? '' : 's'})`)
|
|
1806
|
+
.join(', ');
|
|
1807
|
+
const cold = candidate.coldProjects
|
|
1808
|
+
.slice(0, 3)
|
|
1809
|
+
.map(p => `${p.projectPath} (${p.loadedSessions} loaded session${p.loadedSessions === 1 ? '' : 's'})`)
|
|
1810
|
+
.join(', ');
|
|
1811
|
+
const coldExtra = candidate.coldProjects.length > 3 ? `, +${candidate.coldProjects.length - 3} more` : '';
|
|
1812
|
+
return `${candidate.server}: ${Math.round(candidate.hotShare * 100)}% of ${candidate.invocations} calls in ${hot}; loaded but unused in ${cold}${coldExtra}`;
|
|
1813
|
+
});
|
|
1814
|
+
const extra = candidates.length > preview.length ? `; +${candidates.length - preview.length} more` : '';
|
|
1815
|
+
const serverToolCounts = new Map(candidates.map(c => [c.server, c.toolsAvailable]));
|
|
1816
|
+
const coldProjectKeysByServer = new Map(candidates.map(c => [c.server, c.coldProjectKeys]));
|
|
1817
|
+
const combinedCost = estimateMcpProfileColdSchemaCost(projects, serverToolCounts, coldProjectKeysByServer, pricing);
|
|
1818
|
+
const tokensSaved = Math.round(combinedCost.effectiveInputTokens);
|
|
1819
|
+
const impact = tokensSaved >= MCP_PROFILE_HIGH_IMPACT_TOKENS
|
|
1820
|
+
|| candidates.length >= UNUSED_MCP_HIGH_THRESHOLD
|
|
1821
|
+
? 'high'
|
|
1822
|
+
: 'medium';
|
|
1823
|
+
return {
|
|
1824
|
+
id: 'mcp-project-scope',
|
|
1825
|
+
title: `${candidates.length} MCP server${candidates.length === 1 ? '' : 's'} should be project-scoped`,
|
|
1826
|
+
explanation: `These MCP servers look useful in a small set of projects but are loaded into other projects where they are not invoked. ` +
|
|
1827
|
+
`Project-scoping them keeps the hot-project workflow while avoiding their tool lines elsewhere. ${lines.join('; ')}${extra}.`,
|
|
1828
|
+
impact,
|
|
1829
|
+
tokensSaved,
|
|
1830
|
+
...(pricing ? { savingsUSD: combinedCost.usd } : {}),
|
|
1831
|
+
fix: {
|
|
1832
|
+
type: 'paste',
|
|
1833
|
+
destination: 'prompt',
|
|
1834
|
+
label: askAgentLabel(optimizeRemediationCopy(provider), 'turn this into a project-scoped MCP profile'),
|
|
1835
|
+
text: [
|
|
1836
|
+
`Review these MCP profile recommendations before changing config (${preview.length} of ${candidates.length} shown):`,
|
|
1837
|
+
...preview.map(candidate => {
|
|
1838
|
+
const hot = candidate.hotProjects.map(p => p.projectPath).join(', ');
|
|
1839
|
+
const cold = candidate.coldProjects.slice(0, 3).map(p => p.projectPath).join(', ');
|
|
1840
|
+
return `- Keep ${candidate.server} available for ${hot}; remove or project-scope it away from ${cold}. Re-add it only in projects that actually need it.`;
|
|
1841
|
+
}),
|
|
1842
|
+
].join('\n'),
|
|
1843
|
+
},
|
|
1844
|
+
apply: {
|
|
1845
|
+
kind: 'mcp-project-scope',
|
|
1846
|
+
servers: candidates.map(c => ({
|
|
1847
|
+
server: c.server,
|
|
1848
|
+
keepProjects: c.hotProjects.map(p => p.projectPath),
|
|
1849
|
+
removeProjects: c.coldProjects.map(p => p.projectPath),
|
|
1850
|
+
})),
|
|
1851
|
+
},
|
|
1852
|
+
};
|
|
1853
|
+
}
|
|
1854
|
+
function capabilityKey(ref) {
|
|
1855
|
+
return `${ref.kind}:${ref.name}`;
|
|
1856
|
+
}
|
|
1857
|
+
function formatCapabilityKind(kind) {
|
|
1858
|
+
return kind === 'mcp' ? 'MCP server' : 'skill';
|
|
1859
|
+
}
|
|
1860
|
+
function mcpServerFromToolName(fqn) {
|
|
1861
|
+
const parts = fqn.split('__');
|
|
1862
|
+
if (parts.length < 3 || parts[0] !== 'mcp')
|
|
1863
|
+
return null;
|
|
1864
|
+
return parts[1] || null;
|
|
1865
|
+
}
|
|
1866
|
+
function collectReliabilityCapabilities(turn) {
|
|
1867
|
+
const capabilities = new Map();
|
|
1868
|
+
for (const call of turn.assistantCalls) {
|
|
1869
|
+
for (const fqn of call.mcpTools) {
|
|
1870
|
+
const server = mcpServerFromToolName(fqn);
|
|
1871
|
+
if (!server)
|
|
1872
|
+
continue;
|
|
1873
|
+
const ref = { kind: 'mcp', name: server };
|
|
1874
|
+
capabilities.set(capabilityKey(ref), ref);
|
|
1875
|
+
}
|
|
1876
|
+
for (const rawSkill of call.skills ?? []) {
|
|
1877
|
+
const skill = rawSkill.trim();
|
|
1878
|
+
if (!skill)
|
|
1879
|
+
continue;
|
|
1880
|
+
const ref = { kind: 'skill', name: skill };
|
|
1881
|
+
capabilities.set(capabilityKey(ref), ref);
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
return capabilities;
|
|
1885
|
+
}
|
|
1886
|
+
function turnEffectiveTokenTotal(turn) {
|
|
1887
|
+
return Math.round(turn.assistantCalls.reduce((sum, call) => sum
|
|
1888
|
+
+ call.usage.inputTokens
|
|
1889
|
+
+ call.usage.outputTokens
|
|
1890
|
+
+ call.usage.cacheCreationInputTokens * CACHE_WRITE_MULTIPLIER
|
|
1891
|
+
+ call.usage.cacheReadInputTokens * CACHE_READ_DISCOUNT, 0));
|
|
1892
|
+
}
|
|
1893
|
+
function reliabilityTurnKey(project, session, turn, turnIndex) {
|
|
1894
|
+
return `${project.projectPath || project.project}:${session.sessionId}:${turn.timestamp}:${turnIndex}`;
|
|
1895
|
+
}
|
|
1896
|
+
function getReliabilityAccumulator(stats, ref) {
|
|
1897
|
+
const key = capabilityKey(ref);
|
|
1898
|
+
let acc = stats.get(key);
|
|
1899
|
+
if (!acc) {
|
|
1900
|
+
acc = {
|
|
1901
|
+
...ref,
|
|
1902
|
+
editTurns: 0,
|
|
1903
|
+
retryTurns: 0,
|
|
1904
|
+
oneShotTurns: 0,
|
|
1905
|
+
retries: 0,
|
|
1906
|
+
tokensTouched: 0,
|
|
1907
|
+
projects: new Set(),
|
|
1908
|
+
retryTurnSavings: new Map(),
|
|
1909
|
+
};
|
|
1910
|
+
stats.set(key, acc);
|
|
1911
|
+
}
|
|
1912
|
+
return acc;
|
|
1913
|
+
}
|
|
1914
|
+
function findCapabilityReliabilityCandidates(projects) {
|
|
1915
|
+
const stats = new Map();
|
|
1916
|
+
for (const project of projects) {
|
|
1917
|
+
for (const session of project.sessions) {
|
|
1918
|
+
for (let turnIndex = 0; turnIndex < session.turns.length; turnIndex++) {
|
|
1919
|
+
const turn = session.turns[turnIndex];
|
|
1920
|
+
if (!turn.hasEdits)
|
|
1921
|
+
continue;
|
|
1922
|
+
const capabilities = collectReliabilityCapabilities(turn);
|
|
1923
|
+
if (capabilities.size === 0)
|
|
1924
|
+
continue;
|
|
1925
|
+
const turnTokens = turnEffectiveTokenTotal(turn);
|
|
1926
|
+
const turnKey = reliabilityTurnKey(project, session, turn, turnIndex);
|
|
1927
|
+
const recoverableTokens = turn.retries > 0
|
|
1928
|
+
? Math.round(turnTokens * CAPABILITY_RELIABILITY_RECOVERY_FRACTION)
|
|
1929
|
+
: 0;
|
|
1930
|
+
for (const ref of capabilities.values()) {
|
|
1931
|
+
const acc = getReliabilityAccumulator(stats, ref);
|
|
1932
|
+
acc.editTurns++;
|
|
1933
|
+
acc.tokensTouched += turnTokens;
|
|
1934
|
+
acc.projects.add(project.project);
|
|
1935
|
+
if (turn.retries > 0) {
|
|
1936
|
+
acc.retryTurns++;
|
|
1937
|
+
acc.retries += turn.retries;
|
|
1938
|
+
acc.retryTurnSavings.set(turnKey, recoverableTokens);
|
|
1939
|
+
}
|
|
1940
|
+
else {
|
|
1941
|
+
acc.oneShotTurns++;
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
const candidates = [];
|
|
1948
|
+
for (const acc of stats.values()) {
|
|
1949
|
+
if (acc.editTurns < CAPABILITY_RELIABILITY_MIN_EDIT_TURNS)
|
|
1950
|
+
continue;
|
|
1951
|
+
if (acc.retryTurns < CAPABILITY_RELIABILITY_MIN_RETRY_TURNS)
|
|
1952
|
+
continue;
|
|
1953
|
+
const retryRate = acc.retryTurns / acc.editTurns;
|
|
1954
|
+
if (retryRate < CAPABILITY_RELIABILITY_MIN_RETRY_RATE)
|
|
1955
|
+
continue;
|
|
1956
|
+
candidates.push({
|
|
1957
|
+
kind: acc.kind,
|
|
1958
|
+
name: acc.name,
|
|
1959
|
+
editTurns: acc.editTurns,
|
|
1960
|
+
retryTurns: acc.retryTurns,
|
|
1961
|
+
oneShotTurns: acc.oneShotTurns,
|
|
1962
|
+
retries: acc.retries,
|
|
1963
|
+
retryRate,
|
|
1964
|
+
tokensTouched: acc.tokensTouched,
|
|
1965
|
+
tokensSaved: Array.from(acc.retryTurnSavings.values()).reduce((sum, tokens) => sum + tokens, 0),
|
|
1966
|
+
projects: Array.from(acc.projects).sort(),
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
candidates.sort((a, b) => b.retryRate - a.retryRate
|
|
1970
|
+
|| b.retries - a.retries
|
|
1971
|
+
|| b.tokensSaved - a.tokensSaved
|
|
1972
|
+
|| a.kind.localeCompare(b.kind)
|
|
1973
|
+
|| a.name.localeCompare(b.name));
|
|
1974
|
+
return candidates;
|
|
1975
|
+
}
|
|
1976
|
+
export function detectCapabilityReliability(projects, provider) {
|
|
1977
|
+
projects = userStartedProjects(projects);
|
|
1978
|
+
const candidates = findCapabilityReliabilityCandidates(projects);
|
|
1979
|
+
if (candidates.length === 0)
|
|
1980
|
+
return null;
|
|
1981
|
+
const candidateKeys = new Set(candidates.map(c => capabilityKey(c)));
|
|
1982
|
+
const uniqueRetryTurnSavings = new Map();
|
|
1983
|
+
const retryTurnUSD = new Map();
|
|
1984
|
+
for (const project of projects) {
|
|
1985
|
+
for (const session of project.sessions) {
|
|
1986
|
+
for (let turnIndex = 0; turnIndex < session.turns.length; turnIndex++) {
|
|
1987
|
+
const turn = session.turns[turnIndex];
|
|
1988
|
+
if (!turn.hasEdits || turn.retries <= 0)
|
|
1989
|
+
continue;
|
|
1990
|
+
const capabilities = collectReliabilityCapabilities(turn);
|
|
1991
|
+
if (capabilities.size === 0)
|
|
1992
|
+
continue;
|
|
1993
|
+
const hasFlaggedCapability = Array.from(capabilities.keys()).some(key => candidateKeys.has(key));
|
|
1994
|
+
if (!hasFlaggedCapability)
|
|
1995
|
+
continue;
|
|
1996
|
+
const key = reliabilityTurnKey(project, session, turn, turnIndex);
|
|
1997
|
+
const tokens = Math.round(turnEffectiveTokenTotal(turn) * CAPABILITY_RELIABILITY_RECOVERY_FRACTION);
|
|
1998
|
+
uniqueRetryTurnSavings.set(key, Math.max(uniqueRetryTurnSavings.get(key) ?? 0, tokens));
|
|
1999
|
+
const turnCost = turn.assistantCalls.reduce((sum, call) => sum + call.costUSD, 0);
|
|
2000
|
+
retryTurnUSD.set(key, turnCost * CAPABILITY_RELIABILITY_RECOVERY_FRACTION);
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
const tokensSaved = Array.from(uniqueRetryTurnSavings.values()).reduce((sum, tokens) => sum + tokens, 0);
|
|
2005
|
+
const savingsUSD = Array.from(retryTurnUSD.values()).reduce((sum, usd) => sum + usd, 0);
|
|
2006
|
+
const preview = candidates.slice(0, CAPABILITY_RELIABILITY_PREVIEW);
|
|
2007
|
+
const list = preview.map(c => {
|
|
2008
|
+
const percent = Math.round(c.retryRate * 100);
|
|
2009
|
+
const projects = c.projects.length > 1 ? ` across ${c.projects.length} projects` : ` in ${c.projects[0] ?? 'one project'}`;
|
|
2010
|
+
return `${formatCapabilityKind(c.kind)} ${c.name}: ${c.retryTurns}/${c.editTurns} edit turns retried (${percent}%), ${c.retries} retries${projects}`;
|
|
2011
|
+
}).join('; ');
|
|
2012
|
+
const extra = candidates.length > preview.length ? `; +${candidates.length - preview.length} more` : '';
|
|
2013
|
+
const names = preview
|
|
2014
|
+
.map(c => `${formatCapabilityKind(c.kind)} ${c.name}`)
|
|
2015
|
+
.join(', ');
|
|
2016
|
+
let impact;
|
|
2017
|
+
if (candidates.length >= CAPABILITY_RELIABILITY_HIGH_MIN_CANDIDATES || tokensSaved >= CAPABILITY_RELIABILITY_HIGH_IMPACT_TOKENS) {
|
|
2018
|
+
impact = 'high';
|
|
2019
|
+
}
|
|
2020
|
+
else if (candidates.length <= CAPABILITY_RELIABILITY_LOW_MAX_CANDIDATES && tokensSaved < CAPABILITY_RELIABILITY_LOW_MAX_TOKENS) {
|
|
2021
|
+
impact = 'low';
|
|
2022
|
+
}
|
|
2023
|
+
else {
|
|
2024
|
+
impact = 'medium';
|
|
2025
|
+
}
|
|
2026
|
+
const kindSet = new Set(candidates.map(c => c.kind));
|
|
2027
|
+
const noun = kindSet.size === 1
|
|
2028
|
+
? (kindSet.has('mcp') ? 'MCP server' : 'skill')
|
|
2029
|
+
: 'MCP/skill capability';
|
|
2030
|
+
const pluralNoun = noun === 'MCP/skill capability' ? 'MCP/skill capabilities' : `${noun}s`;
|
|
2031
|
+
const verb = candidates.length === 1 ? 'correlates' : 'correlate';
|
|
2032
|
+
return {
|
|
2033
|
+
id: 'retry-heavy-capabilities',
|
|
2034
|
+
title: `${candidates.length} ${candidates.length === 1 ? noun : pluralNoun} ${verb} with retry-heavy edits`,
|
|
2035
|
+
explanation: `Edit turns using these capabilities are retry-heavy: ${list}${extra}. This is a correlation report, not proof of causation; compare the retry-heavy turns with one-shot turns before changing MCP scope or skill instructions.`,
|
|
2036
|
+
impact,
|
|
2037
|
+
tokensSaved,
|
|
2038
|
+
savingsUSD,
|
|
2039
|
+
fix: {
|
|
2040
|
+
type: 'paste',
|
|
2041
|
+
destination: 'prompt',
|
|
2042
|
+
label: askAgentLabel(optimizeRemediationCopy(provider), 'audit the retry-heavy capability before changing config'),
|
|
2043
|
+
text: `Investigate these retry-correlated capabilities: ${names}. Compare edit turns with retries against one-shot edit turns, identify whether the MCP server or skill actually caused rework, then propose a scoped MCP config or skill-instruction change with session evidence. Do not remove a capability solely because it appears in this report.`,
|
|
2044
|
+
},
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
export function detectUnusedMcp(calls, projects, projectCwds, mcpCoverage = aggregateMcpCoverage(projects), pricing) {
|
|
2048
|
+
const configured = loadMcpConfigs(projectCwds);
|
|
2049
|
+
if (configured.size === 0)
|
|
2050
|
+
return null;
|
|
2051
|
+
const calledServers = new Set();
|
|
2052
|
+
for (const call of calls) {
|
|
2053
|
+
if (!call.name.startsWith('mcp__'))
|
|
2054
|
+
continue;
|
|
2055
|
+
const seg = mcpServerOf(call.name, configured.keys());
|
|
2056
|
+
if (seg)
|
|
2057
|
+
calledServers.add(seg);
|
|
2058
|
+
}
|
|
2059
|
+
for (const p of projects) {
|
|
2060
|
+
for (const s of p.sessions) {
|
|
2061
|
+
for (const server of Object.keys(s.mcpBreakdown))
|
|
2062
|
+
calledServers.add(server);
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
// Servers that the new coverage detector will flag fall under its
|
|
2066
|
+
// jurisdiction (per-tool granularity, cache-aware costing) and we
|
|
2067
|
+
// suppress them here to avoid double-flagging. Importantly, we suppress
|
|
2068
|
+
// only the servers that actually clear the coverage detector's
|
|
2069
|
+
// thresholds — a small, inventoried-but-uninvoked server that the
|
|
2070
|
+
// coverage detector skips would otherwise become a blind spot.
|
|
2071
|
+
const coverageReportedServers = new Set(mcpCoverage
|
|
2072
|
+
.filter(c => c.toolsAvailable > MCP_COVERAGE_MIN_TOOLS
|
|
2073
|
+
&& c.loadedSessions >= MCP_COVERAGE_MIN_SESSIONS
|
|
2074
|
+
&& c.coverageRatio < MCP_COVERAGE_LOW_THRESHOLD)
|
|
2075
|
+
.map(c => c.server));
|
|
2076
|
+
const now = Date.now();
|
|
2077
|
+
const unused = [];
|
|
2078
|
+
for (const entry of configured.values()) {
|
|
2079
|
+
if (calledServers.has(entry.normalized))
|
|
2080
|
+
continue;
|
|
2081
|
+
if (coverageReportedServers.has(entry.normalized))
|
|
2082
|
+
continue;
|
|
2083
|
+
if (entry.mtime > 0 && now - entry.mtime < MCP_NEW_CONFIG_GRACE_MS)
|
|
2084
|
+
continue;
|
|
2085
|
+
unused.push(...entry.originals);
|
|
2086
|
+
}
|
|
2087
|
+
if (unused.length === 0)
|
|
2088
|
+
return null;
|
|
2089
|
+
// The servers come from Claude Code config, so only Claude sessions load them.
|
|
2090
|
+
const claudeProjects = projects.map(p => ({ sessions: p.sessions.filter(isClaudeSession) }));
|
|
2091
|
+
const totalSessions = countSessions(claudeProjects);
|
|
2092
|
+
const schemaTokensPerSession = unused.length * TOOLS_PER_MCP_SERVER * TOKENS_PER_MCP_TOOL;
|
|
2093
|
+
const tokensSaved = schemaTokensPerSession * Math.max(totalSessions, 1);
|
|
2094
|
+
return {
|
|
2095
|
+
id: 'unused-mcp',
|
|
2096
|
+
title: `${unused.length} MCP server${unused.length > 1 ? 's' : ''} configured but never used`,
|
|
2097
|
+
explanation: `Never called in this period: ${unused.join(', ')}. Each server loads ~${TOOLS_PER_MCP_SERVER * TOKENS_PER_MCP_TOOL} tokens of tool schema into every session.`,
|
|
2098
|
+
impact: unused.length >= UNUSED_MCP_HIGH_THRESHOLD ? 'high' : 'medium',
|
|
2099
|
+
tokensSaved,
|
|
2100
|
+
...(pricing ? { savingsUSD: perSessionSchemaUSD(pricing, claudeProjects.flatMap(p => p.sessions), tokensSaved) } : {}),
|
|
2101
|
+
apply: { kind: 'mcp-remove', servers: unused },
|
|
2102
|
+
fix: {
|
|
2103
|
+
type: 'command',
|
|
2104
|
+
label: `Remove unused server${unused.length > 1 ? 's' : ''}:`,
|
|
2105
|
+
text: unused.map(s => `claude mcp remove ${s}`).join('\n'),
|
|
2106
|
+
},
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
// Settings scopes are searched most-specific first (project local >
|
|
2110
|
+
// project > user local > user), matching Claude Code's effective settings
|
|
2111
|
+
// precedence, so the hit we report is the value that actually takes
|
|
2112
|
+
// effect. Shell profiles come last: settings "env" entries override the
|
|
2113
|
+
// inherited environment. `homeDir` is injectable for tests (PlanContext
|
|
2114
|
+
// style in src/act/plans.ts).
|
|
2115
|
+
function claudeSettingsScopes(projectCwds, homeDir) {
|
|
2116
|
+
const scopes = [];
|
|
2117
|
+
for (const cwd of projectCwds) {
|
|
2118
|
+
scopes.push({ scope: 'project local settings', path: join(cwd, '.claude', 'settings.local.json') });
|
|
2119
|
+
scopes.push({ scope: 'project settings', path: join(cwd, '.claude', 'settings.json') });
|
|
2120
|
+
}
|
|
2121
|
+
scopes.push({ scope: 'user local settings', path: join(homeDir, '.claude', 'settings.local.json') });
|
|
2122
|
+
scopes.push({ scope: 'user settings', path: join(homeDir, '.claude', 'settings.json') });
|
|
2123
|
+
return scopes;
|
|
2124
|
+
}
|
|
2125
|
+
function findClaudeSetting(key, projectCwds, homeDir) {
|
|
2126
|
+
for (const { scope, path } of claudeSettingsScopes(projectCwds, homeDir)) {
|
|
2127
|
+
if (!existsSync(path))
|
|
2128
|
+
continue;
|
|
2129
|
+
const value = readJsonFile(path)?.[key];
|
|
2130
|
+
if (value !== undefined)
|
|
2131
|
+
return { value, scope, path };
|
|
2132
|
+
}
|
|
2133
|
+
return null;
|
|
2134
|
+
}
|
|
2135
|
+
export function findDeferralEnvSetting(name, projectCwds, homeDir = homedir()) {
|
|
2136
|
+
for (const { scope, path } of claudeSettingsScopes(projectCwds, homeDir)) {
|
|
2137
|
+
if (!existsSync(path))
|
|
2138
|
+
continue;
|
|
2139
|
+
const config = readJsonFile(path);
|
|
2140
|
+
const env = config?.env;
|
|
2141
|
+
const value = env?.[name];
|
|
2142
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
2143
|
+
return { value: String(value), scope, path };
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
// Callers only pass the three *_VAR constants today, but the function is
|
|
2147
|
+
// exported — escape regex metacharacters so a future caller can't
|
|
2148
|
+
// silently mis-match.
|
|
2149
|
+
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
2150
|
+
const linePattern = new RegExp(`^\\s*(?:export\\s+)?${escapedName}\\s*=\\s*['"]?([^'"\\s]+)['"]?`, 'm');
|
|
2151
|
+
for (const profile of SHELL_PROFILES) {
|
|
2152
|
+
const path = join(homeDir, profile);
|
|
2153
|
+
if (!existsSync(path))
|
|
2154
|
+
continue;
|
|
2155
|
+
const content = readSessionFileSync(path);
|
|
2156
|
+
if (content === null)
|
|
2157
|
+
continue;
|
|
2158
|
+
const match = content.match(linePattern);
|
|
2159
|
+
if (match)
|
|
2160
|
+
return { value: match[1], scope: SHELL_PROFILE_SCOPE, path };
|
|
2161
|
+
}
|
|
2162
|
+
return null;
|
|
2163
|
+
}
|
|
2164
|
+
function isEnvValueFalse(value) {
|
|
2165
|
+
return value.toLowerCase() === 'false' || value === '0';
|
|
2166
|
+
}
|
|
2167
|
+
// Unset counts as first-party; only a URL whose host resolves to
|
|
2168
|
+
// api.anthropic.com does too. Anything else — including an unparseable
|
|
2169
|
+
// value — is an unknown proxy and we never assume its capability.
|
|
2170
|
+
function isFirstPartyBaseUrl(value) {
|
|
2171
|
+
try {
|
|
2172
|
+
return new URL(value).hostname === FIRST_PARTY_API_HOST;
|
|
2173
|
+
}
|
|
2174
|
+
catch {
|
|
2175
|
+
return false;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
// Both exported: the defer-alwaysload plan builder (src/act/plans.ts) gates
|
|
2179
|
+
// on the installed Claude Code version with the same comparison the detector
|
|
2180
|
+
// uses on observed versions. versionPredates returns false for unparseable
|
|
2181
|
+
// input, so gates that must fail closed check parseVersion separately.
|
|
2182
|
+
export function parseVersion(version) {
|
|
2183
|
+
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
|
|
2184
|
+
if (!match)
|
|
2185
|
+
return null;
|
|
2186
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
2187
|
+
}
|
|
2188
|
+
export function versionPredates(version, reference) {
|
|
2189
|
+
const v = parseVersion(version);
|
|
2190
|
+
const ref = parseVersion(reference);
|
|
2191
|
+
if (!v || !ref)
|
|
2192
|
+
return false;
|
|
2193
|
+
for (let i = 0; i < 3; i++) {
|
|
2194
|
+
if (v[i] !== ref[i])
|
|
2195
|
+
return v[i] < ref[i];
|
|
2196
|
+
}
|
|
2197
|
+
return false;
|
|
2198
|
+
}
|
|
2199
|
+
function anySessionHasMcpInventory(projects) {
|
|
2200
|
+
return projects.some(p => p.sessions.some(s => (s.mcpInventory?.length ?? 0) > 0));
|
|
2201
|
+
}
|
|
2202
|
+
// Deferral is a Claude Code mechanism, and both suppression signals for this
|
|
2203
|
+
// family (ToolSearch calls, mcpInventory) exist only in Claude Code
|
|
2204
|
+
// transcripts. Usage evidence must therefore be Claude-scoped too: the
|
|
2205
|
+
// Codex/Copilot/opencode/Hermes parsers also normalize MCP calls into
|
|
2206
|
+
// mcpBreakdown, but those sessions can never carry the counter-evidence, so
|
|
2207
|
+
// counting them would flag a "deferral gap" Claude Code never had.
|
|
2208
|
+
function isClaudeSession(session) {
|
|
2209
|
+
return session.turns.some(t => t.assistantCalls.some(c => c.provider === 'claude'));
|
|
2210
|
+
}
|
|
2211
|
+
/**
|
|
2212
|
+
* mcp-deferral-off: MCP tool definitions are being loaded upfront in every
|
|
2213
|
+
* session because tool search / deferral is inactive.
|
|
2214
|
+
*
|
|
2215
|
+
* Signal: MCP overhead exists (configured servers and/or observed mcp__
|
|
2216
|
+
* invocations), yet across the whole window there is not a single ToolSearch
|
|
2217
|
+
* invocation and not a single session with an mcpInventory — which
|
|
2218
|
+
* deferral-active sessions always produce (see family invariant above).
|
|
2219
|
+
*
|
|
2220
|
+
* Cause attribution probes config in a fixed order, each producing a
|
|
2221
|
+
* distinct explanation: ENABLE_TOOL_SEARCH=false override, non-first-party
|
|
2222
|
+
* ANTHROPIC_BASE_URL (unknown proxy: deferral auto-disables because most
|
|
2223
|
+
* proxies don't forward tool_reference blocks), CLAUDE_CODE_USE_VERTEX
|
|
2224
|
+
* (tool search is disabled by default on Vertex AI, changelog v2.1.119),
|
|
2225
|
+
* every observed Claude Code version predating v2.1.7 (when tool search
|
|
2226
|
+
* auto mode became on by default), else a generic transcript-evidence
|
|
2227
|
+
* message.
|
|
2228
|
+
*/
|
|
2229
|
+
// Cause attribution for mcp-deferral-off. Probes config in a fixed order —
|
|
2230
|
+
// false override, unknown proxy, Vertex, stale version, explicit-but-
|
|
2231
|
+
// ineffective override, generic — each producing a distinct explanation and
|
|
2232
|
+
// fix. Split out so the detector stays focused on evidence gathering.
|
|
2233
|
+
function attributeDeferralOffCause(enableToolSearch, projectCwds, apiCalls, homeDir) {
|
|
2234
|
+
if (enableToolSearch && isEnvValueFalse(enableToolSearch.value)) {
|
|
2235
|
+
return {
|
|
2236
|
+
cause: `Cause: ${ENABLE_TOOL_SEARCH_VAR}=${enableToolSearch.value} is set in ${enableToolSearch.scope} (${shortHomePath(enableToolSearch.path)}), forcing all tool definitions upfront.`,
|
|
2237
|
+
fix: {
|
|
2238
|
+
type: 'paste',
|
|
2239
|
+
destination: 'prompt',
|
|
2240
|
+
label: 'Ask Claude to remove the stale override:',
|
|
2241
|
+
text: `Remove the ${ENABLE_TOOL_SEARCH_VAR}=${enableToolSearch.value} setting from ${enableToolSearch.path}. Tool search is on by default on first-party endpoints, so deleting the override re-enables MCP tool deferral.`,
|
|
2242
|
+
},
|
|
2243
|
+
apply: { kind: 'defer-enable', cause: 'env-false', settingPath: enableToolSearch.path, settingScope: enableToolSearch.scope, value: enableToolSearch.value },
|
|
2244
|
+
};
|
|
2245
|
+
}
|
|
2246
|
+
const baseUrl = findDeferralEnvSetting(ANTHROPIC_BASE_URL_VAR, projectCwds, homeDir);
|
|
2247
|
+
if (baseUrl && !isFirstPartyBaseUrl(baseUrl.value)) {
|
|
2248
|
+
return {
|
|
2249
|
+
cause: `Cause: ${ANTHROPIC_BASE_URL_VAR} points at a non-first-party host in ${baseUrl.scope} (${shortHomePath(baseUrl.path)}). Tool deferral silently auto-disables behind proxies because most don't forward tool_reference blocks; whether this proxy can is unknown.`,
|
|
2250
|
+
fix: {
|
|
2251
|
+
type: 'paste',
|
|
2252
|
+
destination: 'shell-config',
|
|
2253
|
+
label: `Verify your proxy forwards tool_reference blocks first (an explicit override fails on proxies that don't), then force tool search back on with:`,
|
|
2254
|
+
text: `export ${ENABLE_TOOL_SEARCH_VAR}=true`,
|
|
2255
|
+
},
|
|
2256
|
+
apply: { kind: 'defer-enable', cause: 'proxy-unknown', settingPath: baseUrl.path, settingScope: baseUrl.scope, value: baseUrl.value },
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
const vertex = findDeferralEnvSetting(CLAUDE_CODE_USE_VERTEX_VAR, projectCwds, homeDir);
|
|
2260
|
+
if (vertex && !isEnvValueFalse(vertex.value)) {
|
|
2261
|
+
return {
|
|
2262
|
+
cause: `Cause: ${CLAUDE_CODE_USE_VERTEX_VAR} is set in ${vertex.scope} (${shortHomePath(vertex.path)}), and tool search is disabled by default on Vertex AI.`,
|
|
2263
|
+
fix: {
|
|
2264
|
+
type: 'paste',
|
|
2265
|
+
destination: 'shell-config',
|
|
2266
|
+
label: 'Opt in to tool search on Vertex (disabled by default there):',
|
|
2267
|
+
text: `export ${ENABLE_TOOL_SEARCH_VAR}=true`,
|
|
2268
|
+
},
|
|
2269
|
+
apply: { kind: 'defer-enable', cause: 'vertex', settingPath: vertex.path, settingScope: vertex.scope, value: vertex.value },
|
|
2270
|
+
};
|
|
2271
|
+
}
|
|
2272
|
+
const versions = apiCalls.map(c => c.version).filter(v => v.length > 0);
|
|
2273
|
+
if (versions.length > 0 && versions.every(v => versionPredates(v, TOOL_SEARCH_DEFAULT_ON_VERSION))) {
|
|
2274
|
+
return {
|
|
2275
|
+
cause: `Cause: every observed Claude Code version in this period predates v${TOOL_SEARCH_DEFAULT_ON_VERSION}, where MCP tool search became on by default.`,
|
|
2276
|
+
fix: {
|
|
2277
|
+
type: 'command',
|
|
2278
|
+
label: 'Update Claude Code to get default-on MCP tool deferral:',
|
|
2279
|
+
text: 'claude update',
|
|
2280
|
+
},
|
|
2281
|
+
apply: { kind: 'defer-enable', cause: 'old-version' },
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
// false and auto values were handled earlier, so a hit here is an explicit
|
|
2285
|
+
// truthy override that is already applied — re-suggesting the same export
|
|
2286
|
+
// would be redundant.
|
|
2287
|
+
if (enableToolSearch) {
|
|
2288
|
+
return {
|
|
2289
|
+
cause: `Cause: none determinable — ${ENABLE_TOOL_SEARCH_VAR}=${enableToolSearch.value} is already set in ${enableToolSearch.scope} (${shortHomePath(enableToolSearch.path)}), yet transcripts show no deferral activity.`,
|
|
2290
|
+
fix: {
|
|
2291
|
+
type: 'paste',
|
|
2292
|
+
destination: 'prompt',
|
|
2293
|
+
label: 'The override is already on; ask Claude to investigate why deferral is still inactive:',
|
|
2294
|
+
text: `${ENABLE_TOOL_SEARCH_VAR}=${enableToolSearch.value} is set in ${enableToolSearch.path}, but sessions show no ToolSearch calls and no deferred-tool inventory. Check whether requests pass through a proxy that strips tool_reference blocks and whether the running Claude Code version supports tool search.`,
|
|
2295
|
+
},
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
return {
|
|
2299
|
+
cause: `Cause: none determinable from config — no disabling override, proxy, or Vertex setting found.`,
|
|
2300
|
+
fix: {
|
|
2301
|
+
type: 'paste',
|
|
2302
|
+
destination: 'shell-config',
|
|
2303
|
+
label: 'Deferral is on by default on first-party endpoints; to force it explicitly, add:',
|
|
2304
|
+
text: `export ${ENABLE_TOOL_SEARCH_VAR}=true`,
|
|
2305
|
+
},
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
export function detectMcpDeferralOff(calls, projects, projectCwds, apiCalls, homeDir = homedir(), pricing, unusedMcpServers = new Set()) {
|
|
2309
|
+
// Deferral-active evidence anywhere in the window suppresses the finding.
|
|
2310
|
+
if (calls.some(c => c.name === TOOL_SEARCH_TOOL_NAME))
|
|
2311
|
+
return null;
|
|
2312
|
+
if (anySessionHasMcpInventory(projects))
|
|
2313
|
+
return null;
|
|
2314
|
+
const configured = loadMcpConfigs(projectCwds);
|
|
2315
|
+
// Servers pinned with alwaysLoad load upfront BY DESIGN: they are never
|
|
2316
|
+
// deferred (so their missing inventory is not evidence deferral is
|
|
2317
|
+
// broken), and their schema cost is mcp-alwaysload-hygiene's jurisdiction
|
|
2318
|
+
// — charging it here too would double-count the same tokens.
|
|
2319
|
+
const pinnedServers = new Set([...configured.values()].filter(e => e.alwaysLoadPaths.length > 0).map(e => e.normalized));
|
|
2320
|
+
// unused-mcp already charges a never-called server's schema.
|
|
2321
|
+
const configuredUnpinned = [...configured.keys()].filter(s => !pinnedServers.has(s) && !unusedMcpServers.has(s));
|
|
2322
|
+
// `calls` comes from scanSessions, which reads Claude Code JSONL only, so
|
|
2323
|
+
// it is already Claude-scoped (see isClaudeSession for why that matters).
|
|
2324
|
+
const observedServers = new Set();
|
|
2325
|
+
for (const call of calls) {
|
|
2326
|
+
if (!call.name.startsWith('mcp__'))
|
|
2327
|
+
continue;
|
|
2328
|
+
const seg = mcpServerOf(call.name, configured.keys());
|
|
2329
|
+
if (seg && !pinnedServers.has(seg))
|
|
2330
|
+
observedServers.add(seg);
|
|
2331
|
+
}
|
|
2332
|
+
let invocations = 0;
|
|
2333
|
+
const claudeSessions = [];
|
|
2334
|
+
const mcpCallSessions = [];
|
|
2335
|
+
for (const project of projects) {
|
|
2336
|
+
for (const session of project.sessions) {
|
|
2337
|
+
if (!isClaudeSession(session))
|
|
2338
|
+
continue;
|
|
2339
|
+
claudeSessions.push(session);
|
|
2340
|
+
let sessionCalls = 0;
|
|
2341
|
+
for (const [server, data] of Object.entries(session.mcpBreakdown)) {
|
|
2342
|
+
if (pinnedServers.has(server))
|
|
2343
|
+
continue;
|
|
2344
|
+
observedServers.add(server);
|
|
2345
|
+
sessionCalls += data.calls;
|
|
2346
|
+
}
|
|
2347
|
+
if (sessionCalls > 0)
|
|
2348
|
+
mcpCallSessions.push(session);
|
|
2349
|
+
invocations += sessionCalls;
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
const servers = new Set([...configuredUnpinned, ...observedServers]);
|
|
2353
|
+
if (servers.size === 0)
|
|
2354
|
+
return null;
|
|
2355
|
+
// Configured servers load their schemas into every session; with only
|
|
2356
|
+
// invocation evidence we can vouch just for the sessions that called MCP.
|
|
2357
|
+
const affected = configuredUnpinned.length > 0 ? claudeSessions : mcpCallSessions;
|
|
2358
|
+
const affectedSessions = affected.length;
|
|
2359
|
+
if (affectedSessions < DEFERRAL_OFF_MIN_MCP_SESSIONS)
|
|
2360
|
+
return null;
|
|
2361
|
+
const enableToolSearch = findDeferralEnvSetting(ENABLE_TOOL_SEARCH_VAR, projectCwds, homeDir);
|
|
2362
|
+
// auto / auto:N overrides — including out-of-range N, which the threshold
|
|
2363
|
+
// detector clamps — are the defer-threshold detector's jurisdiction (it
|
|
2364
|
+
// can compute the tuned N); reporting them here too would double-flag the
|
|
2365
|
+
// same schema overhead. This regex must stay identical to the one in
|
|
2366
|
+
// detectMcpDeferThreshold or values could slip through both detectors.
|
|
2367
|
+
if (enableToolSearch && /^auto(?::\d+)?$/.test(enableToolSearch.value))
|
|
2368
|
+
return null;
|
|
2369
|
+
// Without deferral there is never an inventory, so per-server tool counts
|
|
2370
|
+
// are unknown — follow detectUnusedMcp's convention of 5 tools x 400
|
|
2371
|
+
// tokens per server.
|
|
2372
|
+
const perServerSchemaTokens = TOOLS_PER_MCP_SERVER * TOKENS_PER_MCP_TOOL;
|
|
2373
|
+
const perSessionSchemaTokens = servers.size * perServerSchemaTokens;
|
|
2374
|
+
const tokensSaved = perSessionSchemaTokens * affectedSessions;
|
|
2375
|
+
const callRate = affectedSessions > 0 ? invocations / affectedSessions : 0;
|
|
2376
|
+
// Pluralize on the rendered value so 0.98 and 1.0 read consistently.
|
|
2377
|
+
const callRateText = callRate.toFixed(1);
|
|
2378
|
+
const evidence = `~${formatTokens(perSessionSchemaTokens)} tokens of MCP tool schema ` +
|
|
2379
|
+
`(${servers.size} server${servers.size === 1 ? '' : 's'} at ~${formatTokens(perServerSchemaTokens)} tokens/server) sit in the prompt prefix of ` +
|
|
2380
|
+
`${affectedSessions} session${affectedSessions === 1 ? '' : 's'} at ` +
|
|
2381
|
+
`${callRateText} MCP call${callRateText === '1.0' ? '' : 's'}/session, with zero ToolSearch calls ` +
|
|
2382
|
+
`and no deferred-tool inventory observed — tool deferral appears inactive. ` +
|
|
2383
|
+
`Deferral would move ~all of that schema out of the prefix.`;
|
|
2384
|
+
const { cause, fix, apply } = attributeDeferralOffCause(enableToolSearch, projectCwds, apiCalls, homeDir);
|
|
2385
|
+
return {
|
|
2386
|
+
id: 'mcp-deferral-off',
|
|
2387
|
+
title: 'MCP tool deferral appears inactive',
|
|
2388
|
+
explanation: `${evidence} ${cause}`,
|
|
2389
|
+
impact: tokensSaved >= DEFERRAL_OFF_HIGH_IMPACT_TOKENS ? 'high' : 'medium',
|
|
2390
|
+
tokensSaved,
|
|
2391
|
+
...(pricing ? { savingsUSD: perSessionSchemaUSD(pricing, affected, tokensSaved) } : {}),
|
|
2392
|
+
fix,
|
|
2393
|
+
...(apply ? { apply } : {}),
|
|
2394
|
+
};
|
|
2395
|
+
}
|
|
2396
|
+
/**
|
|
2397
|
+
* mcp-alwaysload-hygiene: servers pinned with `"alwaysLoad": true` (an
|
|
2398
|
+
* .mcp.json / settings mcpServers sibling of type/url, Claude Code
|
|
2399
|
+
* v2.1.121+) whose observed call rate doesn't justify exempting them from
|
|
2400
|
+
* deferral. alwaysLoad puts the server's full tool schema in every
|
|
2401
|
+
* session's prefix even though deferral is available, and additionally
|
|
2402
|
+
* blocks session startup on that server's connection (capped at
|
|
2403
|
+
* ALWAYSLOAD_STARTUP_CAP_SECONDS).
|
|
2404
|
+
*/
|
|
2405
|
+
export function detectMcpAlwaysLoadHygiene(projects, projectCwds, apiCalls = [], mcpCoverage = aggregateMcpCoverage(projects), pricing, unusedMcpServers = new Set()) {
|
|
2406
|
+
const configured = loadMcpConfigs(projectCwds);
|
|
2407
|
+
const pinned = [...configured.values()].filter(e => e.alwaysLoadPaths.length > 0 && !unusedMcpServers.has(e.normalized));
|
|
2408
|
+
if (pinned.length === 0)
|
|
2409
|
+
return null;
|
|
2410
|
+
// When every observed Claude Code version predates server-level
|
|
2411
|
+
// alwaysLoad support, the key is inert — the tools defer normally, so
|
|
2412
|
+
// the pin costs nothing and the finding's claim would be false.
|
|
2413
|
+
const versions = apiCalls.map(c => c.version).filter(v => v.length > 0);
|
|
2414
|
+
if (versions.length > 0 && versions.every(v => versionPredates(v, ALWAYSLOAD_MIN_VERSION)))
|
|
2415
|
+
return null;
|
|
2416
|
+
const totalSessions = countSessions(projects);
|
|
2417
|
+
if (totalSessions === 0)
|
|
2418
|
+
return null;
|
|
2419
|
+
const coverageByServer = new Map(mcpCoverage.map(c => [c.server, c]));
|
|
2420
|
+
const invocationsByServer = new Map();
|
|
2421
|
+
for (const project of projects) {
|
|
2422
|
+
for (const session of project.sessions) {
|
|
2423
|
+
for (const [server, data] of Object.entries(session.mcpBreakdown)) {
|
|
2424
|
+
invocationsByServer.set(server, (invocationsByServer.get(server) ?? 0) + data.calls);
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
const lines = [];
|
|
2429
|
+
const fixLines = [];
|
|
2430
|
+
const applyServers = [];
|
|
2431
|
+
let tokensSaved = 0;
|
|
2432
|
+
let savingsUSD = 0;
|
|
2433
|
+
const allSessions = projects.flatMap(p => p.sessions);
|
|
2434
|
+
for (const entry of pinned) {
|
|
2435
|
+
const invocations = invocationsByServer.get(entry.normalized) ?? 0;
|
|
2436
|
+
const callRate = invocations / totalSessions;
|
|
2437
|
+
if (callRate >= ALWAYSLOAD_MAX_CALLS_PER_SESSION)
|
|
2438
|
+
continue;
|
|
2439
|
+
// Prefer real inventory numbers when a session observed them; without
|
|
2440
|
+
// an inventory fall back to the 5 tools x 400 tokens convention, and
|
|
2441
|
+
// charge every session since alwaysLoad forces the load unconditionally.
|
|
2442
|
+
const coverage = coverageByServer.get(entry.normalized);
|
|
2443
|
+
const toolsAvailable = coverage?.toolsAvailable ?? TOOLS_PER_MCP_SERVER;
|
|
2444
|
+
const loadedSessions = coverage?.loadedSessions ?? totalSessions;
|
|
2445
|
+
const serverTokens = toolsAvailable * TOKENS_PER_MCP_TOOL * loadedSessions;
|
|
2446
|
+
tokensSaved += serverTokens;
|
|
2447
|
+
if (pricing) {
|
|
2448
|
+
const sessions = coverage ? allSessions.filter(s => sessionLoadedMcpServer(s, entry.normalized)) : allSessions;
|
|
2449
|
+
savingsUSD += perSessionSchemaUSD(pricing, sessions, serverTokens);
|
|
2450
|
+
}
|
|
2451
|
+
lines.push(`${entry.originals.join(', ')}: ${invocations} call${invocations === 1 ? '' : 's'} across ${totalSessions} session${totalSessions === 1 ? '' : 's'}`);
|
|
2452
|
+
fixLines.push(`- Remove "alwaysLoad": true from ${entry.originals.join(', ')} in ${entry.alwaysLoadPaths.map(shortHomePath).join(', ')}.`);
|
|
2453
|
+
// Original (config-key) name plus the exact files carrying the pin, so
|
|
2454
|
+
// the defer-alwaysload plan edits precisely what was observed.
|
|
2455
|
+
for (const server of entry.originals)
|
|
2456
|
+
applyServers.push({ server, paths: entry.alwaysLoadPaths });
|
|
2457
|
+
}
|
|
2458
|
+
if (lines.length === 0)
|
|
2459
|
+
return null;
|
|
2460
|
+
return {
|
|
2461
|
+
id: 'mcp-alwaysload-hygiene',
|
|
2462
|
+
title: `${lines.length} alwaysLoad MCP server${lines.length === 1 ? '' : 's'} rarely used`,
|
|
2463
|
+
explanation: `These servers are pinned with alwaysLoad, so their tool schemas sit in every session's prefix ` +
|
|
2464
|
+
`despite deferral being available, and session startup blocks on each server's connection ` +
|
|
2465
|
+
`(up to ${ALWAYSLOAD_STARTUP_CAP_SECONDS}s). Usage doesn't justify the pin: ${lines.join('; ')}.`,
|
|
2466
|
+
impact: tokensSaved >= ALWAYSLOAD_HIGH_IMPACT_TOKENS ? 'high' : 'medium',
|
|
2467
|
+
tokensSaved,
|
|
2468
|
+
...(pricing ? { savingsUSD } : {}),
|
|
2469
|
+
apply: { kind: 'defer-alwaysload', servers: applyServers },
|
|
2470
|
+
fix: {
|
|
2471
|
+
type: 'paste',
|
|
2472
|
+
destination: 'prompt',
|
|
2473
|
+
label: 'Ask Claude to unpin the rarely-used servers (tool search still discovers their tools on demand):',
|
|
2474
|
+
text: fixLines.join('\n'),
|
|
2475
|
+
},
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
/**
|
|
2479
|
+
* mcp-defer-threshold: an explicit ENABLE_TOOL_SEARCH=auto or auto:N
|
|
2480
|
+
* override whose threshold the configured MCP definitions never reach —
|
|
2481
|
+
* auto defers only when defs exceed N% of the context window (default 10),
|
|
2482
|
+
* so everything still loads upfront while carrying substantial per-session
|
|
2483
|
+
* cost. Lowest priority of the family; emitted only on a substantial gap.
|
|
2484
|
+
*/
|
|
2485
|
+
export function detectMcpDeferThreshold(projects, projectCwds, homeDir = homedir(), pricing) {
|
|
2486
|
+
const setting = findDeferralEnvSetting(ENABLE_TOOL_SEARCH_VAR, projectCwds, homeDir);
|
|
2487
|
+
if (!setting)
|
|
2488
|
+
return null;
|
|
2489
|
+
// Must accept exactly what detectMcpDeferralOff yields to this detector
|
|
2490
|
+
// (any auto:N, N unbounded), or an out-of-range N would silently slip
|
|
2491
|
+
// through both detectors. Oversized values clamp to 100% — a threshold
|
|
2492
|
+
// that can never trigger, the strongest form of this finding.
|
|
2493
|
+
const match = /^auto(?::(\d+))?$/.exec(setting.value);
|
|
2494
|
+
if (!match)
|
|
2495
|
+
return null;
|
|
2496
|
+
const percent = match[1] !== undefined
|
|
2497
|
+
? Math.min(DEFER_THRESHOLD_MAX_PERCENT, parseInt(match[1], 10))
|
|
2498
|
+
: DEFER_THRESHOLD_DEFAULT_PERCENT;
|
|
2499
|
+
// Inventory anywhere in the window means the auto threshold did trigger
|
|
2500
|
+
// and deferral is working; nothing to tune.
|
|
2501
|
+
if (anySessionHasMcpInventory(projects))
|
|
2502
|
+
return null;
|
|
2503
|
+
const configured = loadMcpConfigs(projectCwds);
|
|
2504
|
+
const servers = new Set(configured.keys());
|
|
2505
|
+
// Claude-scoped for the same reason as detectMcpDeferralOff: other
|
|
2506
|
+
// providers' sessions carry MCP breakdowns but not this override's cost.
|
|
2507
|
+
const claudeSessions = [];
|
|
2508
|
+
for (const project of projects) {
|
|
2509
|
+
for (const session of project.sessions) {
|
|
2510
|
+
if (!isClaudeSession(session))
|
|
2511
|
+
continue;
|
|
2512
|
+
claudeSessions.push(session);
|
|
2513
|
+
for (const server of Object.keys(session.mcpBreakdown))
|
|
2514
|
+
servers.add(server);
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
const totalSessions = claudeSessions.length;
|
|
2518
|
+
if (servers.size === 0)
|
|
2519
|
+
return null;
|
|
2520
|
+
if (totalSessions === 0)
|
|
2521
|
+
return null;
|
|
2522
|
+
// No inventory (see suppression above) means per-server tool counts are
|
|
2523
|
+
// unknown — same 5 tools x 400 tokens convention as detectUnusedMcp.
|
|
2524
|
+
const defsPerSession = servers.size * TOOLS_PER_MCP_SERVER * TOKENS_PER_MCP_TOOL;
|
|
2525
|
+
const onePercent = DEFER_THRESHOLD_CONTEXT_WINDOW_TOKENS / 100;
|
|
2526
|
+
const thresholdTokens = percent * onePercent;
|
|
2527
|
+
// Deferral kicks in only when defs EXCEED the threshold; at or below it,
|
|
2528
|
+
// everything loads upfront.
|
|
2529
|
+
if (defsPerSession > thresholdTokens)
|
|
2530
|
+
return null;
|
|
2531
|
+
if (defsPerSession < DEFER_THRESHOLD_MIN_TOKENS_PER_SESSION)
|
|
2532
|
+
return null;
|
|
2533
|
+
const tokensSaved = defsPerSession * totalSessions;
|
|
2534
|
+
// Largest integer N such that the defs still exceed N% — i.e. the loosest
|
|
2535
|
+
// auto:N at which deferral actually kicks in.
|
|
2536
|
+
const recommendedPercent = Math.max(0, Math.ceil(defsPerSession / onePercent) - 1);
|
|
2537
|
+
// If the defs already exceed the default 10% threshold, the override is
|
|
2538
|
+
// pure downside: removing it restores default auto behavior, which defers.
|
|
2539
|
+
const removeOverride = defsPerSession > DEFER_THRESHOLD_DEFAULT_PERCENT * onePercent;
|
|
2540
|
+
return {
|
|
2541
|
+
id: 'mcp-defer-threshold',
|
|
2542
|
+
title: 'MCP tool search auto threshold never triggers',
|
|
2543
|
+
explanation: `${ENABLE_TOOL_SEARCH_VAR}=${setting.value} is set in ${setting.scope} (${shortHomePath(setting.path)}), ` +
|
|
2544
|
+
`deferring MCP tool definitions only when they exceed ${percent}% of the ${formatTokens(DEFER_THRESHOLD_CONTEXT_WINDOW_TOKENS)}-token context window ` +
|
|
2545
|
+
`(~${formatTokens(thresholdTokens)} tokens). Your estimated ~${formatTokens(defsPerSession)} tokens of definitions per session fit under that, ` +
|
|
2546
|
+
`so every tool still loads upfront in all ${totalSessions} session${totalSessions === 1 ? '' : 's'}.`,
|
|
2547
|
+
impact: tokensSaved >= DEFER_THRESHOLD_MEDIUM_IMPACT_TOKENS ? 'medium' : 'low',
|
|
2548
|
+
tokensSaved,
|
|
2549
|
+
...(pricing ? { savingsUSD: perSessionSchemaUSD(pricing, claudeSessions, tokensSaved) } : {}),
|
|
2550
|
+
apply: {
|
|
2551
|
+
kind: 'defer-threshold',
|
|
2552
|
+
settingPath: setting.path,
|
|
2553
|
+
settingScope: setting.scope,
|
|
2554
|
+
value: setting.value,
|
|
2555
|
+
recommendedPercent,
|
|
2556
|
+
removeOverride,
|
|
2557
|
+
},
|
|
2558
|
+
fix: {
|
|
2559
|
+
type: 'paste',
|
|
2560
|
+
destination: 'prompt',
|
|
2561
|
+
label: 'Ask Claude to tighten the auto threshold:',
|
|
2562
|
+
text: removeOverride
|
|
2563
|
+
? `Remove the ${ENABLE_TOOL_SEARCH_VAR}=${setting.value} override from ${setting.path}; the default auto threshold (${DEFER_THRESHOLD_DEFAULT_PERCENT}%) already defers this volume of tool definitions.`
|
|
2564
|
+
: `In ${setting.path}, change ${ENABLE_TOOL_SEARCH_VAR}=${setting.value} to ${ENABLE_TOOL_SEARCH_VAR}=auto:${recommendedPercent} so ~${formatTokens(defsPerSession)} tokens of MCP tool definitions per session are deferred instead of loaded upfront.`,
|
|
2565
|
+
},
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
function parseAutoCompactWindow(value) {
|
|
2569
|
+
const match = /^(\d+)(k?)$/i.exec(String(value).trim());
|
|
2570
|
+
const tokens = match ? Number(match[1]) * (match[2] ? 1000 : 1) : NaN;
|
|
2571
|
+
return tokens >= IDLE_COMPACT_FLOOR_TOKENS && tokens <= AUTO_COMPACT_WINDOW_MAX_TOKENS ? tokens : null;
|
|
2572
|
+
}
|
|
2573
|
+
export function detectIdleCompactionBlocked(projects, projectCwds, apiCalls, homeDir = homedir()) {
|
|
2574
|
+
const onOneHourCache = projects.some(p => p.sessions.some(s => s.turns.some(t => t.assistantCalls.some(c => c.provider === 'claude' && (c.cacheCreationOneHourTokens ?? 0) > 0))));
|
|
2575
|
+
if (!onOneHourCache)
|
|
2576
|
+
return null;
|
|
2577
|
+
if (!apiCalls.some(c => parseVersion(c.version) && !versionPredates(c.version, IDLE_COMPACTION_MIN_VERSION)))
|
|
2578
|
+
return null;
|
|
2579
|
+
if (findClaudeSetting('idleCompaction', projectCwds, homeDir)?.value === false)
|
|
2580
|
+
return null;
|
|
2581
|
+
if (findClaudeSetting('autoCompactEnabled', projectCwds, homeDir)?.value === false)
|
|
2582
|
+
return null;
|
|
2583
|
+
const disableAuto = findDeferralEnvSetting('DISABLE_AUTO_COMPACT', projectCwds, homeDir);
|
|
2584
|
+
if (disableAuto && !isEnvValueFalse(disableAuto.value))
|
|
2585
|
+
return null;
|
|
2586
|
+
const envWindow = findDeferralEnvSetting(AUTO_COMPACT_WINDOW_VAR, projectCwds, homeDir);
|
|
2587
|
+
const keyWindow = findClaudeSetting('autoCompactWindow', projectCwds, homeDir);
|
|
2588
|
+
const fromEnv = envWindow !== null && parseAutoCompactWindow(envWindow.value) !== null;
|
|
2589
|
+
const windowHit = fromEnv ? envWindow : keyWindow;
|
|
2590
|
+
const window = windowHit ? parseAutoCompactWindow(windowHit.value) : null;
|
|
2591
|
+
if (!windowHit || window === null)
|
|
2592
|
+
return null;
|
|
2593
|
+
const thresholdHit = findDeferralEnvSetting(IDLE_COMPACT_MIN_TOKENS_VAR, projectCwds, homeDir);
|
|
2594
|
+
const thresholdSet = thresholdHit !== null && /^\d+$/.test(thresholdHit.value) && Number(thresholdHit.value) > 0;
|
|
2595
|
+
const threshold = thresholdSet ? Math.max(IDLE_COMPACT_FLOOR_TOKENS, Number(thresholdHit.value)) : IDLE_COMPACT_DEFAULT_MIN_TOKENS;
|
|
2596
|
+
if (window > threshold)
|
|
2597
|
+
return null;
|
|
2598
|
+
const windowSetting = fromEnv ? `${AUTO_COMPACT_WINDOW_VAR}=${windowHit.value}` : `"autoCompactWindow": ${windowHit.value}`;
|
|
2599
|
+
const thresholdWhere = thresholdSet
|
|
2600
|
+
? `${IDLE_COMPACT_MIN_TOKENS_VAR}=${thresholdHit.value} in ${thresholdHit.scope} (${shortHomePath(thresholdHit.path)})`
|
|
2601
|
+
: 'its default';
|
|
2602
|
+
const thresholdFile = thresholdSet && thresholdHit.scope !== SHELL_PROFILE_SCOPE ? shortHomePath(thresholdHit.path) : '~/.claude/settings.json';
|
|
2603
|
+
const lowerThreshold = `"${IDLE_COMPACT_MIN_TOKENS_VAR}": "${IDLE_COMPACT_FLOOR_TOKENS}"`;
|
|
2604
|
+
return {
|
|
2605
|
+
id: 'idle-compaction-blocked',
|
|
2606
|
+
title: 'Auto-compact window blocks idle compaction',
|
|
2607
|
+
explanation: `${windowSetting} in ${windowHit.scope} (${shortHomePath(windowHit.path)}) compacts at ${formatTokens(window)} tokens, ` +
|
|
2608
|
+
`at or below the ${formatTokens(threshold)}-token idle compaction threshold (${thresholdWhere}). ` +
|
|
2609
|
+
`Idle compaction (on by default since Claude Code v${IDLE_COMPACTION_MIN_VERSION}) only runs once the context reaches that threshold, so it never runs: ` +
|
|
2610
|
+
`a conversation left for about an hour is not compacted before its prompt cache expires, and the next message writes the whole context to the cache again. ` +
|
|
2611
|
+
`Unsetting the window does not help on a 200K-context model, which compacts before 200K too; \`/autocompact\` with no argument shows the window in use.`,
|
|
2612
|
+
impact: 'low',
|
|
2613
|
+
tokensSaved: 0,
|
|
2614
|
+
fix: window > IDLE_COMPACT_FLOOR_TOKENS
|
|
2615
|
+
? {
|
|
2616
|
+
type: 'paste',
|
|
2617
|
+
destination: 'manual',
|
|
2618
|
+
label: `Lower the idle compaction threshold below the window, in the "env" block of ${thresholdFile}:`,
|
|
2619
|
+
text: lowerThreshold,
|
|
2620
|
+
}
|
|
2621
|
+
: {
|
|
2622
|
+
type: 'paste',
|
|
2623
|
+
destination: 'manual',
|
|
2624
|
+
label: `The window is at its ${formatTokens(IDLE_COMPACT_FLOOR_TOKENS)} minimum, so no threshold can sit below it. Raise the window in ${shortHomePath(windowHit.path)} and lower the threshold:`,
|
|
2625
|
+
text: fromEnv
|
|
2626
|
+
? `"env": { "${AUTO_COMPACT_WINDOW_VAR}": "150000", ${lowerThreshold} }`
|
|
2627
|
+
: `"autoCompactWindow": 150000,\n"env": { ${lowerThreshold} }`,
|
|
2628
|
+
},
|
|
2629
|
+
};
|
|
2630
|
+
}
|
|
2631
|
+
function expandImports(filePath, seen, depth) {
|
|
2632
|
+
if (depth > MAX_IMPORT_DEPTH || seen.has(filePath))
|
|
2633
|
+
return { totalLines: 0, importedFiles: 0 };
|
|
2634
|
+
seen.add(filePath);
|
|
2635
|
+
const content = readSessionFileSync(filePath);
|
|
2636
|
+
if (content === null)
|
|
2637
|
+
return { totalLines: 0, importedFiles: 0 };
|
|
2638
|
+
let totalLines = content.split('\n').length;
|
|
2639
|
+
let importedFiles = 0;
|
|
2640
|
+
const dir = join(filePath, '..');
|
|
2641
|
+
IMPORT_PATTERN.lastIndex = 0;
|
|
2642
|
+
for (const match of content.matchAll(IMPORT_PATTERN)) {
|
|
2643
|
+
const rawPath = match[1];
|
|
2644
|
+
if (!rawPath)
|
|
2645
|
+
continue;
|
|
2646
|
+
const resolved = rawPath.startsWith('/') ? rawPath : join(dir, rawPath);
|
|
2647
|
+
if (!existsSync(resolved))
|
|
2648
|
+
continue;
|
|
2649
|
+
const nested = expandImports(resolved, seen, depth + 1);
|
|
2650
|
+
totalLines += nested.totalLines;
|
|
2651
|
+
importedFiles += 1 + nested.importedFiles;
|
|
2652
|
+
}
|
|
2653
|
+
return { totalLines, importedFiles };
|
|
2654
|
+
}
|
|
2655
|
+
export function detectBloatedClaudeMd(projectCwds) {
|
|
2656
|
+
const bloated = [];
|
|
2657
|
+
for (const cwd of projectCwds) {
|
|
2658
|
+
for (const name of ['CLAUDE.md', '.claude/CLAUDE.md']) {
|
|
2659
|
+
const fullPath = join(cwd, name);
|
|
2660
|
+
if (!existsSync(fullPath))
|
|
2661
|
+
continue;
|
|
2662
|
+
const { totalLines, importedFiles } = expandImports(fullPath, new Set(), 0);
|
|
2663
|
+
if (totalLines > CLAUDEMD_HEALTHY_LINES) {
|
|
2664
|
+
bloated.push({ path: `${shortHomePath(cwd)}/${name}`, expandedLines: totalLines, imports: importedFiles });
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
if (bloated.length === 0)
|
|
2669
|
+
return null;
|
|
2670
|
+
const sorted = bloated.sort((a, b) => b.expandedLines - a.expandedLines);
|
|
2671
|
+
const worst = sorted[0];
|
|
2672
|
+
const totalExtraLines = sorted.reduce((s, b) => s + (b.expandedLines - CLAUDEMD_HEALTHY_LINES), 0);
|
|
2673
|
+
const tokensSaved = totalExtraLines * CLAUDEMD_TOKENS_PER_LINE;
|
|
2674
|
+
const list = sorted.slice(0, TOP_ITEMS_PREVIEW).map(b => {
|
|
2675
|
+
const importNote = b.imports > 0 ? ` with ${b.imports} @-import${b.imports > 1 ? 's' : ''}` : '';
|
|
2676
|
+
return `${b.path} (${b.expandedLines} lines${importNote})`;
|
|
2677
|
+
}).join(', ');
|
|
2678
|
+
return {
|
|
2679
|
+
id: 'claude-md-too-long',
|
|
2680
|
+
title: `Your CLAUDE.md is too long`,
|
|
2681
|
+
explanation: `${list}. CLAUDE.md plus all @-imported files load into every API call. Trimming below ${CLAUDEMD_HEALTHY_LINES} lines saves ~${formatTokens(tokensSaved)} tokens per call.`,
|
|
2682
|
+
impact: worst.expandedLines > CLAUDEMD_HIGH_THRESHOLD_LINES ? 'high' : 'medium',
|
|
2683
|
+
tokensSaved,
|
|
2684
|
+
fix: {
|
|
2685
|
+
type: 'paste',
|
|
2686
|
+
destination: 'prompt',
|
|
2687
|
+
label: 'Ask Claude in the current session to trim it:',
|
|
2688
|
+
text: `Review CLAUDE.md and all @-imported files. Cut total expanded content to under ${CLAUDEMD_HEALTHY_LINES} lines. Remove anything Claude can figure out from the code itself. Keep only rules, gotchas, and non-obvious conventions.`,
|
|
2689
|
+
},
|
|
2690
|
+
};
|
|
2691
|
+
}
|
|
2692
|
+
export const READ_TOOL_NAMES = new Set(['Read', 'Grep', 'Glob', 'FileReadTool', 'GrepTool', 'GlobTool']);
|
|
2693
|
+
export const EDIT_TOOL_NAMES = new Set(['Edit', 'Write', 'FileEditTool', 'FileWriteTool', 'NotebookEdit']);
|
|
2694
|
+
export const BASH_TOOL_NAMES = new Set(['Bash', 'BashTool', 'PowerShell', 'PowerShellTool']);
|
|
2695
|
+
// Writing a new file has nothing to read first; counting Write flagged subagents
|
|
2696
|
+
// that produce reports as editing blind. Not EDIT_TOOL_NAMES: act report baselines use that.
|
|
2697
|
+
const RATIO_EDIT_TOOL_NAMES = new Set(['Edit', 'FileEditTool', 'NotebookEdit']);
|
|
2698
|
+
export function detectLowReadEditRatio(calls) {
|
|
2699
|
+
let reads = 0;
|
|
2700
|
+
let edits = 0;
|
|
2701
|
+
let recentEdits = 0;
|
|
2702
|
+
let recentReads = 0;
|
|
2703
|
+
for (const call of calls) {
|
|
2704
|
+
if (READ_TOOL_NAMES.has(call.name)) {
|
|
2705
|
+
reads++;
|
|
2706
|
+
if (call.recent)
|
|
2707
|
+
recentReads++;
|
|
2708
|
+
}
|
|
2709
|
+
else if (BASH_TOOL_NAMES.has(call.name) && call.input['readShaped'] === true) {
|
|
2710
|
+
// A session that looks things up with rg/cat/git log IS reading (#941):
|
|
2711
|
+
// ignoring shell reads scored disciplined rg-first workflows as
|
|
2712
|
+
// reckless editors (90%+ of real reads were invisible to this ratio).
|
|
2713
|
+
reads++;
|
|
2714
|
+
if (call.recent)
|
|
2715
|
+
recentReads++;
|
|
2716
|
+
}
|
|
2717
|
+
else if (RATIO_EDIT_TOOL_NAMES.has(call.name)) {
|
|
2718
|
+
edits++;
|
|
2719
|
+
if (call.recent)
|
|
2720
|
+
recentEdits++;
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
if (edits < MIN_EDITS_FOR_RATIO)
|
|
2724
|
+
return null;
|
|
2725
|
+
const ratio = reads / edits;
|
|
2726
|
+
if (ratio >= HEALTHY_READ_EDIT_RATIO)
|
|
2727
|
+
return null;
|
|
2728
|
+
const impact = ratio < LOW_RATIO_HIGH_THRESHOLD ? 'high' : ratio < LOW_RATIO_MEDIUM_THRESHOLD ? 'medium' : 'low';
|
|
2729
|
+
const extraReadsNeeded = Math.max(Math.round(edits * HEALTHY_READ_EDIT_RATIO) - reads, 0);
|
|
2730
|
+
const tokensSaved = extraReadsNeeded * AVG_TOKENS_PER_READ;
|
|
2731
|
+
let trend = 'active';
|
|
2732
|
+
if (recentEdits >= MIN_EDITS_FOR_RATIO) {
|
|
2733
|
+
const recentRatio = recentReads / recentEdits;
|
|
2734
|
+
if (recentRatio >= HEALTHY_READ_EDIT_RATIO)
|
|
2735
|
+
trend = 'resolved';
|
|
2736
|
+
else if (recentRatio > ratio * (1 / IMPROVING_THRESHOLD))
|
|
2737
|
+
trend = 'improving';
|
|
2738
|
+
}
|
|
2739
|
+
if (trend === 'resolved')
|
|
2740
|
+
return null;
|
|
2741
|
+
return {
|
|
2742
|
+
id: 'read-edit-ratio',
|
|
2743
|
+
title: 'Claude edits more than it reads',
|
|
2744
|
+
explanation: `Claude made ${reads} reads and ${edits} edits (ratio ${ratio.toFixed(1)}:1). A healthy ratio is ${HEALTHY_READ_EDIT_RATIO}+ reads per edit. Editing without reading leads to retries and wasted tokens.`,
|
|
2745
|
+
impact,
|
|
2746
|
+
tokensSaved,
|
|
2747
|
+
fix: {
|
|
2748
|
+
type: 'paste',
|
|
2749
|
+
destination: 'claude-md',
|
|
2750
|
+
label: 'Add to your CLAUDE.md:',
|
|
2751
|
+
text: 'Before editing any file, read it first. Before modifying a function, grep for all callers. Research before you edit.',
|
|
2752
|
+
},
|
|
2753
|
+
trend,
|
|
2754
|
+
};
|
|
2755
|
+
}
|
|
2756
|
+
const DEFAULT_CACHE_BASELINE_TOKENS = 50_000;
|
|
2757
|
+
const CACHE_BASELINE_QUANTILE = 0.25;
|
|
2758
|
+
const CACHE_BLOAT_MULTIPLIER = 1.4;
|
|
2759
|
+
const CACHE_VERSION_MIN_SAMPLES = 5;
|
|
2760
|
+
const CACHE_VERSION_DIFF_THRESHOLD = 10_000;
|
|
2761
|
+
function computeBudgetAwareCacheBaseline(projects) {
|
|
2762
|
+
const sessions = projects.flatMap(p => p.sessions);
|
|
2763
|
+
if (sessions.length === 0)
|
|
2764
|
+
return DEFAULT_CACHE_BASELINE_TOKENS;
|
|
2765
|
+
const cacheWrites = sessions.map(s => s.totalCacheWriteTokens).filter(n => n > 0);
|
|
2766
|
+
if (cacheWrites.length < MIN_API_CALLS_FOR_CACHE)
|
|
2767
|
+
return DEFAULT_CACHE_BASELINE_TOKENS;
|
|
2768
|
+
const sorted = cacheWrites.sort((a, b) => a - b);
|
|
2769
|
+
return sorted[Math.floor(sorted.length * CACHE_BASELINE_QUANTILE)] || DEFAULT_CACHE_BASELINE_TOKENS;
|
|
2770
|
+
}
|
|
2771
|
+
export function detectCacheBloat(apiCalls, projects, dateRange, pricing) {
|
|
2772
|
+
if (apiCalls.length < MIN_API_CALLS_FOR_CACHE)
|
|
2773
|
+
return null;
|
|
2774
|
+
const sorted = apiCalls.map(c => c.cacheCreationTokens).sort((a, b) => a - b);
|
|
2775
|
+
const median = sorted[Math.floor(sorted.length / 2)];
|
|
2776
|
+
const baseline = computeBudgetAwareCacheBaseline(projects);
|
|
2777
|
+
const bloatThreshold = baseline * CACHE_BLOAT_MULTIPLIER;
|
|
2778
|
+
if (median < bloatThreshold)
|
|
2779
|
+
return null;
|
|
2780
|
+
const recentCalls = apiCalls.filter(c => c.recent);
|
|
2781
|
+
const totalBloated = apiCalls.filter(c => c.cacheCreationTokens > bloatThreshold).length;
|
|
2782
|
+
const recentBloated = recentCalls.filter(c => c.cacheCreationTokens > bloatThreshold).length;
|
|
2783
|
+
const trend = sessionTrend(recentBloated, totalBloated, dateRange, recentCalls.length > 0);
|
|
2784
|
+
if (trend === 'resolved')
|
|
2785
|
+
return null;
|
|
2786
|
+
const versionCounts = new Map();
|
|
2787
|
+
for (const call of apiCalls) {
|
|
2788
|
+
if (!call.version)
|
|
2789
|
+
continue;
|
|
2790
|
+
const entry = versionCounts.get(call.version) ?? { total: 0, count: 0 };
|
|
2791
|
+
entry.total += call.cacheCreationTokens;
|
|
2792
|
+
entry.count++;
|
|
2793
|
+
versionCounts.set(call.version, entry);
|
|
2794
|
+
}
|
|
2795
|
+
const versionAvgs = [...versionCounts.entries()]
|
|
2796
|
+
.filter(([, d]) => d.count >= CACHE_VERSION_MIN_SAMPLES)
|
|
2797
|
+
.map(([v, d]) => ({ version: v, avg: Math.round(d.total / d.count) }))
|
|
2798
|
+
.sort((a, b) => b.avg - a.avg);
|
|
2799
|
+
const excess = median - baseline;
|
|
2800
|
+
const tokensSaved = excess * apiCalls.length;
|
|
2801
|
+
const savingsUSD = pricing
|
|
2802
|
+
? apiCalls.reduce((sum, call) => sum + sessionTokensUSD(pricing, call.sessionId, excess, 'cacheWrite'), 0)
|
|
2803
|
+
: undefined;
|
|
2804
|
+
let versionNote = '';
|
|
2805
|
+
if (versionAvgs.length >= 2) {
|
|
2806
|
+
const [high, ...rest] = versionAvgs;
|
|
2807
|
+
const low = rest[rest.length - 1];
|
|
2808
|
+
if (high.avg - low.avg > CACHE_VERSION_DIFF_THRESHOLD) {
|
|
2809
|
+
versionNote = ` Version ${high.version} averages ${formatTokens(high.avg)} vs ${low.version} at ${formatTokens(low.avg)}.`;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
return {
|
|
2813
|
+
id: 'warmup-heavy',
|
|
2814
|
+
title: 'Session warmup is unusually large',
|
|
2815
|
+
explanation: `Median cache_creation per call is ${formatTokens(median)} tokens, about ${formatTokens(excess)} above your baseline of ${formatTokens(baseline)}.${versionNote}`,
|
|
2816
|
+
impact: excess > CACHE_EXCESS_HIGH_THRESHOLD ? 'high' : 'medium',
|
|
2817
|
+
tokensSaved,
|
|
2818
|
+
...(savingsUSD !== undefined ? { savingsUSD } : {}),
|
|
2819
|
+
fix: {
|
|
2820
|
+
type: 'paste',
|
|
2821
|
+
destination: 'shell-config',
|
|
2822
|
+
label: 'Check for recent Claude Code updates or heavy MCP/skill additions. As a workaround (not officially supported), add to ~/.zshrc or ~/.bashrc:',
|
|
2823
|
+
text: 'export ANTHROPIC_CUSTOM_HEADERS=\'User-Agent: claude-cli/2.1.98 (external, sdk-cli)\'',
|
|
2824
|
+
},
|
|
2825
|
+
trend,
|
|
2826
|
+
};
|
|
2827
|
+
}
|
|
2828
|
+
async function listMarkdownFiles(dir) {
|
|
2829
|
+
if (!existsSync(dir))
|
|
2830
|
+
return [];
|
|
2831
|
+
try {
|
|
2832
|
+
const entries = await readdir(dir);
|
|
2833
|
+
return entries.filter(e => e.endsWith('.md')).map(e => e.replace(/\.md$/, ''));
|
|
2834
|
+
}
|
|
2835
|
+
catch {
|
|
2836
|
+
return [];
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
async function listSkillDirs(dir) {
|
|
2840
|
+
if (!existsSync(dir))
|
|
2841
|
+
return [];
|
|
2842
|
+
try {
|
|
2843
|
+
const entries = await readdir(dir);
|
|
2844
|
+
const names = [];
|
|
2845
|
+
for (const entry of entries) {
|
|
2846
|
+
if (existsSync(join(dir, entry, 'SKILL.md')))
|
|
2847
|
+
names.push(entry);
|
|
2848
|
+
}
|
|
2849
|
+
return names;
|
|
2850
|
+
}
|
|
2851
|
+
catch {
|
|
2852
|
+
return [];
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
export async function detectGhostAgents(calls) {
|
|
2856
|
+
const defined = await listMarkdownFiles(join(homedir(), '.claude', 'agents'));
|
|
2857
|
+
if (defined.length === 0)
|
|
2858
|
+
return null;
|
|
2859
|
+
const invoked = new Set();
|
|
2860
|
+
for (const call of calls) {
|
|
2861
|
+
if (call.name !== 'Agent' && call.name !== 'Task')
|
|
2862
|
+
continue;
|
|
2863
|
+
const subType = call.input.subagent_type;
|
|
2864
|
+
if (subType)
|
|
2865
|
+
invoked.add(subType);
|
|
2866
|
+
}
|
|
2867
|
+
const ghosts = defined.filter(name => !invoked.has(name));
|
|
2868
|
+
if (ghosts.length === 0)
|
|
2869
|
+
return null;
|
|
2870
|
+
const tokensSaved = ghosts.length * TOKENS_PER_AGENT_DEF;
|
|
2871
|
+
const list = ghosts.slice(0, GHOST_NAMES_PREVIEW).join(', ') + (ghosts.length > GHOST_NAMES_PREVIEW ? `, +${ghosts.length - GHOST_NAMES_PREVIEW} more` : '');
|
|
2872
|
+
return {
|
|
2873
|
+
id: 'unused-agents',
|
|
2874
|
+
title: `${ghosts.length} custom agent${ghosts.length > 1 ? 's' : ''} you never use`,
|
|
2875
|
+
explanation: `Defined in ~/.claude/agents/ but never invoked in this period: ${list}. Each adds ~${TOKENS_PER_AGENT_DEF} tokens to the Task tool schema on every session.`,
|
|
2876
|
+
impact: ghosts.length >= GHOST_AGENTS_HIGH_THRESHOLD ? 'high' : ghosts.length >= GHOST_AGENTS_MEDIUM_THRESHOLD ? 'medium' : 'low',
|
|
2877
|
+
tokensSaved,
|
|
2878
|
+
fix: {
|
|
2879
|
+
type: 'command',
|
|
2880
|
+
label: `Archive unused agent${ghosts.length > 1 ? 's' : ''}:`,
|
|
2881
|
+
text: ghosts.slice(0, GHOST_CLEANUP_COMMANDS_LIMIT).map(name => `mv ~/.claude/agents/${name}.md ~/.claude/agents/.archived/`).join('\n'),
|
|
2882
|
+
},
|
|
2883
|
+
apply: { kind: 'archive', names: ghosts },
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
export async function detectGhostSkills(calls) {
|
|
2887
|
+
const defined = await listSkillDirs(join(homedir(), '.claude', 'skills'));
|
|
2888
|
+
if (defined.length === 0)
|
|
2889
|
+
return null;
|
|
2890
|
+
const invoked = new Set();
|
|
2891
|
+
for (const call of calls) {
|
|
2892
|
+
if (call.name !== 'Skill')
|
|
2893
|
+
continue;
|
|
2894
|
+
const skillName = call.input.skill || call.input.name;
|
|
2895
|
+
if (skillName)
|
|
2896
|
+
invoked.add(skillName);
|
|
2897
|
+
}
|
|
2898
|
+
const ghosts = defined.filter(name => !invoked.has(name));
|
|
2899
|
+
if (ghosts.length === 0)
|
|
2900
|
+
return null;
|
|
2901
|
+
const tokensSaved = ghosts.length * TOKENS_PER_SKILL_DEF;
|
|
2902
|
+
const list = ghosts.slice(0, GHOST_NAMES_PREVIEW).join(', ') + (ghosts.length > GHOST_NAMES_PREVIEW ? `, +${ghosts.length - GHOST_NAMES_PREVIEW} more` : '');
|
|
2903
|
+
return {
|
|
2904
|
+
id: 'unused-skills',
|
|
2905
|
+
title: `${ghosts.length} skill${ghosts.length > 1 ? 's' : ''} you never use`,
|
|
2906
|
+
explanation: `In ~/.claude/skills/ but not invoked this period: ${list}. Each adds ~${TOKENS_PER_SKILL_DEF} tokens of metadata to every session.`,
|
|
2907
|
+
impact: ghosts.length >= GHOST_SKILLS_HIGH_THRESHOLD ? 'high' : ghosts.length >= GHOST_SKILLS_MEDIUM_THRESHOLD ? 'medium' : 'low',
|
|
2908
|
+
tokensSaved,
|
|
2909
|
+
fix: {
|
|
2910
|
+
type: 'command',
|
|
2911
|
+
label: `Archive unused skill${ghosts.length > 1 ? 's' : ''}:`,
|
|
2912
|
+
text: ghosts.slice(0, GHOST_CLEANUP_COMMANDS_LIMIT).map(name => `mv ~/.claude/skills/${name} ~/.claude/skills/.archived/`).join('\n'),
|
|
2913
|
+
},
|
|
2914
|
+
apply: { kind: 'archive', names: ghosts },
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
/// The slash commands a user message names, as the ghost-command detector
|
|
2918
|
+
/// counts them: `<command-name>` tags and `/name` tokens.
|
|
2919
|
+
export function commandNames(text) {
|
|
2920
|
+
const names = [];
|
|
2921
|
+
for (const m of text.matchAll(COMMAND_PATTERN)) {
|
|
2922
|
+
const name = (m[1] || m[2] || '').trim().replace(/^\//, '');
|
|
2923
|
+
if (name)
|
|
2924
|
+
names.push(name);
|
|
2925
|
+
}
|
|
2926
|
+
return names;
|
|
2927
|
+
}
|
|
2928
|
+
export async function detectGhostCommands(names) {
|
|
2929
|
+
const defined = await listMarkdownFiles(join(homedir(), '.claude', 'commands'));
|
|
2930
|
+
if (defined.length === 0)
|
|
2931
|
+
return null;
|
|
2932
|
+
const invoked = new Set(names);
|
|
2933
|
+
const ghosts = defined.filter(name => !invoked.has(name));
|
|
2934
|
+
if (ghosts.length === 0)
|
|
2935
|
+
return null;
|
|
2936
|
+
const tokensSaved = ghosts.length * TOKENS_PER_COMMAND_DEF;
|
|
2937
|
+
const list = ghosts.slice(0, GHOST_NAMES_PREVIEW).join(', ') + (ghosts.length > GHOST_NAMES_PREVIEW ? `, +${ghosts.length - GHOST_NAMES_PREVIEW} more` : '');
|
|
2938
|
+
return {
|
|
2939
|
+
id: 'unused-commands',
|
|
2940
|
+
title: `${ghosts.length} slash command${ghosts.length > 1 ? 's' : ''} you never use`,
|
|
2941
|
+
explanation: `In ~/.claude/commands/ but not referenced this period: ${list}. Each adds ~${TOKENS_PER_COMMAND_DEF} tokens of definition per session.`,
|
|
2942
|
+
impact: ghosts.length >= GHOST_COMMANDS_MEDIUM_THRESHOLD ? 'medium' : 'low',
|
|
2943
|
+
tokensSaved,
|
|
2944
|
+
fix: {
|
|
2945
|
+
type: 'command',
|
|
2946
|
+
label: `Archive unused command${ghosts.length > 1 ? 's' : ''}:`,
|
|
2947
|
+
text: ghosts.slice(0, GHOST_CLEANUP_COMMANDS_LIMIT).map(name => `mv ~/.claude/commands/${name}.md ~/.claude/commands/.archived/`).join('\n'),
|
|
2948
|
+
},
|
|
2949
|
+
apply: { kind: 'archive', names: ghosts },
|
|
2950
|
+
};
|
|
2951
|
+
}
|
|
2952
|
+
export function detectBashBloat(projectCwds = []) {
|
|
2953
|
+
const setting = findDeferralEnvSetting('BASH_MAX_OUTPUT_LENGTH', projectCwds)?.value ?? process.env['BASH_MAX_OUTPUT_LENGTH'];
|
|
2954
|
+
const configured = setting ? parseInt(setting, 10) : null;
|
|
2955
|
+
if (configured !== null && configured <= BASH_RECOMMENDED_LIMIT)
|
|
2956
|
+
return null;
|
|
2957
|
+
const limit = configured ?? BASH_DEFAULT_LIMIT;
|
|
2958
|
+
const extraChars = limit - BASH_RECOMMENDED_LIMIT;
|
|
2959
|
+
const tokensSaved = Math.round(extraChars * BASH_TOKENS_PER_CHAR);
|
|
2960
|
+
return {
|
|
2961
|
+
id: 'bash-output-cap',
|
|
2962
|
+
title: 'Shrink bash output limit',
|
|
2963
|
+
explanation: `Your bash output cap is ${(limit / 1000).toFixed(0)}K chars (${configured ? 'configured' : 'default'}). Most output fits in ${(BASH_RECOMMENDED_LIMIT / 1000).toFixed(0)}K. The extra ~${formatTokens(tokensSaved)} tokens per bash call is trailing noise.`,
|
|
2964
|
+
impact: 'medium',
|
|
2965
|
+
tokensSaved,
|
|
2966
|
+
fix: {
|
|
2967
|
+
type: 'paste',
|
|
2968
|
+
destination: 'shell-config',
|
|
2969
|
+
label: 'Add to ~/.zshrc or ~/.bashrc:',
|
|
2970
|
+
text: `export BASH_MAX_OUTPUT_LENGTH=${BASH_RECOMMENDED_LIMIT}`,
|
|
2971
|
+
},
|
|
2972
|
+
};
|
|
2973
|
+
}
|
|
2974
|
+
/// The same long block opening many sessions: a spec, a repo dump, a standing
|
|
2975
|
+
/// brief. Every repeat is input tokens for context that could live in
|
|
2976
|
+
/// CLAUDE.md or in a file read on demand. The first paste is the honest cost
|
|
2977
|
+
/// of saying it once, so only the repeats count as savings.
|
|
2978
|
+
export function detectRecurringContext(openers) {
|
|
2979
|
+
const groups = new Map();
|
|
2980
|
+
for (const o of openers) {
|
|
2981
|
+
const g = groups.get(o.hash);
|
|
2982
|
+
if (!g) {
|
|
2983
|
+
groups.set(o.hash, { sessions: 1, chars: o.chars, preview: o.preview, projects: new Set([o.project]) });
|
|
2984
|
+
continue;
|
|
2985
|
+
}
|
|
2986
|
+
g.sessions++;
|
|
2987
|
+
// Only the hashed prefix is known to match, so size the block by the
|
|
2988
|
+
// smallest occurrence rather than claiming the longest.
|
|
2989
|
+
g.chars = Math.min(g.chars, o.chars);
|
|
2990
|
+
g.projects.add(o.project);
|
|
2991
|
+
}
|
|
2992
|
+
const repeated = [...groups.values()]
|
|
2993
|
+
.filter(g => g.sessions >= RECURRING_CONTEXT_MIN_SESSIONS)
|
|
2994
|
+
.map(g => ({ ...g, tokens: Math.round((g.sessions - 1) * g.chars * BASH_TOKENS_PER_CHAR) }))
|
|
2995
|
+
.sort((a, b) => b.tokens - a.tokens);
|
|
2996
|
+
if (repeated.length === 0)
|
|
2997
|
+
return null;
|
|
2998
|
+
const tokensSaved = repeated.reduce((sum, g) => sum + g.tokens, 0);
|
|
2999
|
+
const top = repeated[0];
|
|
3000
|
+
const preview = repeated.slice(0, RECURRING_CONTEXT_PREVIEW);
|
|
3001
|
+
const list = preview
|
|
3002
|
+
.map(g => {
|
|
3003
|
+
const where = g.projects.size === 1
|
|
3004
|
+
? [...g.projects][0].split('-').filter(Boolean).pop() ?? [...g.projects][0]
|
|
3005
|
+
: `${g.projects.size} projects`;
|
|
3006
|
+
return `"${g.preview}..." — ${g.sessions} sessions in ${where}, ~${formatTokens(g.tokens)} tokens`;
|
|
3007
|
+
})
|
|
3008
|
+
.join('; ');
|
|
3009
|
+
const extra = repeated.length > preview.length ? `; +${repeated.length - preview.length} more` : '';
|
|
3010
|
+
return {
|
|
3011
|
+
id: 'recurring-context',
|
|
3012
|
+
title: `Same ${(top.chars / 1024).toFixed(1)} KB block pasted at the start of ${top.sessions} sessions`,
|
|
3013
|
+
explanation: `These sessions open with a block you have pasted before, so you pay input tokens for the same context every time: ${list}${extra}. Standing rules belong in CLAUDE.md; reference material belongs in a file Claude reads on demand. Only the repeats are counted, not the first paste.`,
|
|
3014
|
+
impact: tokensSaved >= RECURRING_CONTEXT_HIGH_IMPACT_TOKENS ? 'high' : tokensSaved >= RECURRING_CONTEXT_MEDIUM_IMPACT_TOKENS ? 'medium' : 'low',
|
|
3015
|
+
tokensSaved,
|
|
3016
|
+
fix: {
|
|
3017
|
+
type: 'paste',
|
|
3018
|
+
destination: 'prompt',
|
|
3019
|
+
label: 'Ask Claude to give this block a permanent home:',
|
|
3020
|
+
text: `I open many sessions by pasting this block:\n"${top.preview}..."\nMove it into CLAUDE.md if it is a standing rule, or into a file you read on demand if it is reference material, then tell me the one-line pointer to start sessions with instead.`,
|
|
3021
|
+
},
|
|
3022
|
+
};
|
|
3023
|
+
}
|
|
3024
|
+
function sessionTokenTotal(session) {
|
|
3025
|
+
return session.totalInputTokens
|
|
3026
|
+
+ sessionBillableOutputTokens(session)
|
|
3027
|
+
+ session.totalCacheReadTokens
|
|
3028
|
+
+ session.totalCacheWriteTokens;
|
|
3029
|
+
}
|
|
3030
|
+
// Sidechain transcripts are real usage, so they stay in project totals and in
|
|
3031
|
+
// token/cost calibration. They are not user-started sessions, however, and
|
|
3032
|
+
// should never enter optimize heuristics whose unit is a human work session.
|
|
3033
|
+
// Keep that distinction local to optimize instead of deleting sidechains from
|
|
3034
|
+
// ProjectSummary, which would under-report the work delegated to subagents.
|
|
3035
|
+
function isOptimizeSession(session) {
|
|
3036
|
+
return isUserStartedSession(session);
|
|
3037
|
+
}
|
|
3038
|
+
function optimizeSessionCount(projects) {
|
|
3039
|
+
return projects.reduce((total, project) => total + project.sessions.filter(isOptimizeSession).length, 0);
|
|
3040
|
+
}
|
|
3041
|
+
function sessionEffectiveContextTokens(session) {
|
|
3042
|
+
return session.totalInputTokens
|
|
3043
|
+
+ session.totalCacheReadTokens * CACHE_READ_DISCOUNT
|
|
3044
|
+
+ session.totalCacheWriteTokens * CACHE_WRITE_MULTIPLIER;
|
|
3045
|
+
}
|
|
3046
|
+
function formatContextRatio(ratio) {
|
|
3047
|
+
if (ratio >= CONTEXT_BLOAT_RATIO_DISPLAY_CAP)
|
|
3048
|
+
return `${CONTEXT_BLOAT_RATIO_DISPLAY_CAP}+`;
|
|
3049
|
+
return ratio.toFixed(1);
|
|
3050
|
+
}
|
|
3051
|
+
// ============================================================================
|
|
3052
|
+
// Worth-it / low-worth-session detector helpers
|
|
3053
|
+
// ============================================================================
|
|
3054
|
+
// Use (\s|$|--) instead of \b after commit/push so `git commit-tree` and
|
|
3055
|
+
// `git commit-graph` are not treated as deliveries. The `--` clause keeps
|
|
3056
|
+
// `git commit --amend` matching as a real delivery command. Git's global
|
|
3057
|
+
// options (`git -C dir commit`, `git -c user.name=x commit`) may sit between
|
|
3058
|
+
// `git` and the subcommand.
|
|
3059
|
+
const DELIVERY_COMMAND_PATTERNS = [
|
|
3060
|
+
/(?:^|[;&|(\n]\s*|\b(?:do|then)\s+)git(?:\s+-[Cc]\s+\S+|\s+--[\w-]+(?:=\S+)?)*\s+(?:commit|push)(?=\s|$|--)(?![^;&|\n]*--dry-run)/,
|
|
3061
|
+
/(?:^|[;&|(\n]\s*|\b(?:do|then)\s+)gh\s+pr\s+(?:create|merge)(?=\s|$|--)(?![^;&|\n]*--dry-run)/,
|
|
3062
|
+
];
|
|
3063
|
+
// bashBreakdown keys are base command names (`git`), so delivery is read from
|
|
3064
|
+
// the full command text each call keeps in its tool sequence.
|
|
3065
|
+
function sessionDeliveryCommand(session) {
|
|
3066
|
+
for (const turn of session.turns) {
|
|
3067
|
+
for (const call of turn.assistantCalls) {
|
|
3068
|
+
for (const tool of call.toolSequence?.flat() ?? []) {
|
|
3069
|
+
const command = tool.command;
|
|
3070
|
+
if (command && DELIVERY_COMMAND_PATTERNS.some(pattern => pattern.test(command)))
|
|
3071
|
+
return command;
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
return null;
|
|
3076
|
+
}
|
|
3077
|
+
function hasCategoryBreakdownData(session) {
|
|
3078
|
+
return Object.values(session.categoryBreakdown).some(category => category.turns > 0
|
|
3079
|
+
|| category.costUSD > 0
|
|
3080
|
+
|| category.retries > 0
|
|
3081
|
+
|| category.editTurns > 0
|
|
3082
|
+
|| category.oneShotTurns > 0);
|
|
3083
|
+
}
|
|
3084
|
+
function sessionEditTurns(session) {
|
|
3085
|
+
if (hasCategoryBreakdownData(session)) {
|
|
3086
|
+
return Object.values(session.categoryBreakdown).reduce((sum, c) => sum + c.editTurns, 0);
|
|
3087
|
+
}
|
|
3088
|
+
return session.turns.filter(turn => turn.hasEdits).length;
|
|
3089
|
+
}
|
|
3090
|
+
function sessionOneShotTurns(session) {
|
|
3091
|
+
if (hasCategoryBreakdownData(session)) {
|
|
3092
|
+
return Object.values(session.categoryBreakdown).reduce((sum, c) => sum + c.oneShotTurns, 0);
|
|
3093
|
+
}
|
|
3094
|
+
return session.turns.filter(turn => turn.hasEdits && turn.retries === 0).length;
|
|
3095
|
+
}
|
|
3096
|
+
function sessionRetryCount(session) {
|
|
3097
|
+
if (hasCategoryBreakdownData(session)) {
|
|
3098
|
+
return Object.values(session.categoryBreakdown).reduce((sum, c) => sum + c.retries, 0);
|
|
3099
|
+
}
|
|
3100
|
+
return session.turns.reduce((sum, turn) => sum + turn.retries, 0);
|
|
3101
|
+
}
|
|
3102
|
+
// Counted the way the classifier counts retries: one per edit tool call.
|
|
3103
|
+
function sessionEditSteps(session) {
|
|
3104
|
+
let steps = 0;
|
|
3105
|
+
for (const turn of session.turns) {
|
|
3106
|
+
for (const call of turn.assistantCalls) {
|
|
3107
|
+
const tools = call.toolSequence?.length ? call.toolSequence.flat().map(t => t.tool) : call.tools;
|
|
3108
|
+
steps += tools.filter(tool => EDIT_TOOLS.has(tool)).length;
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
return steps;
|
|
3112
|
+
}
|
|
3113
|
+
// Token-savings estimate for a low-worth candidate. Two regimes:
|
|
3114
|
+
// - No-edit sessions: a bounded fraction of full session tokens is counted
|
|
3115
|
+
// as recoverable. Full cost is an upper bound, not a point estimate:
|
|
3116
|
+
// read-only work may still contain useful exploration or analysis.
|
|
3117
|
+
// - Sessions with edits but with retries / no one-shot: only the retry
|
|
3118
|
+
// fraction is counted as recoverable. Edits may still have been useful;
|
|
3119
|
+
// we credit the model with that and only flag the retry overhead.
|
|
3120
|
+
// A retry is a re-edit, so the fraction is retries over edit steps, not over
|
|
3121
|
+
// user prompts (an agent loop can make dozens of edits per prompt).
|
|
3122
|
+
function lowWorthRecoveryFraction(session, editTurns, retries) {
|
|
3123
|
+
if (editTurns === 0)
|
|
3124
|
+
return WORTH_IT_NO_EDIT_RECOVERY_FRACTION;
|
|
3125
|
+
const editSteps = sessionEditSteps(session);
|
|
3126
|
+
if (editSteps === 0)
|
|
3127
|
+
return 0;
|
|
3128
|
+
return Math.min(1, Math.max(0, retries / editSteps));
|
|
3129
|
+
}
|
|
3130
|
+
// Session-opener texts, the single source of truth shared by the optimize
|
|
3131
|
+
// findings below and by `codeburn guard` (SessionStart hook). Kept as
|
|
3132
|
+
// constants so the two surfaces can never drift.
|
|
3133
|
+
export const LOW_WORTH_OPENER = 'Before continuing, name the deliverable in one sentence (PR title, file changed, command output you expect). Stop and check with me if (a) you spend more than 10 minutes without an edit, or (b) the same approach fails twice. Do not retry past two attempts on any single fix.';
|
|
3134
|
+
export const CONTEXT_HEAVY_OPENER = 'Start fresh before continuing. Use only the current goal, the relevant files, the failing command/output, and the constraints below. Restate the working context in under 10 bullets before editing.';
|
|
3135
|
+
export function findLowWorthCandidates(projects) {
|
|
3136
|
+
const candidates = [];
|
|
3137
|
+
for (const project of projects) {
|
|
3138
|
+
for (const session of project.sessions) {
|
|
3139
|
+
if (!isOptimizeSession(session))
|
|
3140
|
+
continue;
|
|
3141
|
+
if (session.totalCostUSD < WORTH_IT_MIN_COST_USD)
|
|
3142
|
+
continue;
|
|
3143
|
+
if (sessionDeliveryCommand(session))
|
|
3144
|
+
continue;
|
|
3145
|
+
const editTurns = sessionEditTurns(session);
|
|
3146
|
+
const oneShotTurns = sessionOneShotTurns(session);
|
|
3147
|
+
const retries = sessionRetryCount(session);
|
|
3148
|
+
const reasons = [];
|
|
3149
|
+
if (editTurns === 0 && session.totalCostUSD >= WORTH_IT_NO_EDIT_MIN_COST_USD) {
|
|
3150
|
+
reasons.push('no edit turns');
|
|
3151
|
+
}
|
|
3152
|
+
if (retries >= WORTH_IT_MIN_RETRIES) {
|
|
3153
|
+
reasons.push(`${retries} retries`);
|
|
3154
|
+
}
|
|
3155
|
+
if (editTurns > 0
|
|
3156
|
+
&& oneShotTurns === 0
|
|
3157
|
+
&& retries >= WORTH_IT_RETRY_WITH_EDIT_MIN_RETRIES) {
|
|
3158
|
+
reasons.push('no one-shot edit turns');
|
|
3159
|
+
}
|
|
3160
|
+
if (reasons.length === 0)
|
|
3161
|
+
continue;
|
|
3162
|
+
const fraction = lowWorthRecoveryFraction(session, editTurns, retries);
|
|
3163
|
+
candidates.push({
|
|
3164
|
+
project: project.project,
|
|
3165
|
+
sessionId: session.sessionId,
|
|
3166
|
+
date: session.firstTimestamp.slice(0, 10),
|
|
3167
|
+
cost: session.totalCostUSD,
|
|
3168
|
+
tokens: Math.round(sessionTokenTotal(session) * fraction),
|
|
3169
|
+
recoverableUSD: session.totalCostUSD * fraction,
|
|
3170
|
+
reasons,
|
|
3171
|
+
});
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
candidates.sort((a, b) => b.cost - a.cost
|
|
3175
|
+
|| a.date.localeCompare(b.date)
|
|
3176
|
+
|| a.project.localeCompare(b.project)
|
|
3177
|
+
|| a.sessionId.localeCompare(b.sessionId));
|
|
3178
|
+
return candidates;
|
|
3179
|
+
}
|
|
3180
|
+
export function detectLowWorthSessions(projects, provider) {
|
|
3181
|
+
const candidates = findLowWorthCandidates(projects);
|
|
3182
|
+
if (candidates.length === 0)
|
|
3183
|
+
return null;
|
|
3184
|
+
const preview = candidates.slice(0, WORTH_IT_PREVIEW);
|
|
3185
|
+
const list = preview
|
|
3186
|
+
.map(s => `${s.project}/${s.sessionId} on ${s.date}: ${formatCost(s.cost)} (${s.reasons.join(', ')})`)
|
|
3187
|
+
.join('; ');
|
|
3188
|
+
const extra = candidates.length > preview.length ? `; +${candidates.length - preview.length} more` : '';
|
|
3189
|
+
// Per-candidate `tokens` is already the recoverable estimate (bounded
|
|
3190
|
+
// no-edit fraction, retry-fraction for edit-with-retries). Sum across candidates.
|
|
3191
|
+
const tokensSaved = Math.round(candidates.reduce((sum, s) => sum + s.tokens, 0));
|
|
3192
|
+
const savingsUSD = candidates.reduce((sum, s) => sum + s.recoverableUSD, 0);
|
|
3193
|
+
const totalCost = candidates.reduce((sum, s) => sum + s.cost, 0);
|
|
3194
|
+
// Three tiers consistent with detectContextBloat: high at >=10 candidates
|
|
3195
|
+
// or >=$50 total spend at risk; low at <=2 candidates AND <$10 total;
|
|
3196
|
+
// medium in between.
|
|
3197
|
+
let impact;
|
|
3198
|
+
if (candidates.length >= WORTH_IT_HIGH_MIN_CANDIDATES || totalCost >= WORTH_IT_HIGH_TOTAL_COST_USD) {
|
|
3199
|
+
impact = 'high';
|
|
3200
|
+
}
|
|
3201
|
+
else if (candidates.length <= WORTH_IT_LOW_MAX_CANDIDATES && totalCost < WORTH_IT_LOW_MAX_TOTAL_COST_USD) {
|
|
3202
|
+
impact = 'low';
|
|
3203
|
+
}
|
|
3204
|
+
else {
|
|
3205
|
+
impact = 'medium';
|
|
3206
|
+
}
|
|
3207
|
+
return {
|
|
3208
|
+
id: 'low-worth-sessions',
|
|
3209
|
+
title: `${candidates.length} possibly low-worth expensive session${candidates.length === 1 ? '' : 's'}`,
|
|
3210
|
+
explanation: `Sessions with meaningful spend but weak delivery signals: ${list}${extra}. This is a review candidate, not proof of waste: CodeBurn flags missing edit turns, repeated retries, and sessions without git delivery commands so you can decide whether the work was worth its cost before it becomes a habit.`,
|
|
3211
|
+
impact,
|
|
3212
|
+
tokensSaved,
|
|
3213
|
+
savingsUSD,
|
|
3214
|
+
fix: {
|
|
3215
|
+
type: 'paste',
|
|
3216
|
+
destination: 'session-opener',
|
|
3217
|
+
label: sessionOpenerLabel(optimizeRemediationCopy(provider)),
|
|
3218
|
+
text: LOW_WORTH_OPENER,
|
|
3219
|
+
},
|
|
3220
|
+
};
|
|
3221
|
+
}
|
|
3222
|
+
export function findContextBloatCandidates(projects) {
|
|
3223
|
+
const candidates = [];
|
|
3224
|
+
for (const project of projects) {
|
|
3225
|
+
const sessions = project.sessions.filter(isOptimizeSession).sort((a, b) => new Date(a.firstTimestamp).getTime() - new Date(b.firstTimestamp).getTime());
|
|
3226
|
+
let previousInputTokens = null;
|
|
3227
|
+
let previousTimestampMs = null;
|
|
3228
|
+
for (const session of sessions) {
|
|
3229
|
+
const inputTokens = sessionEffectiveContextTokens(session);
|
|
3230
|
+
// Generated tokens: exclusive providers add reasoning; inclusive ones
|
|
3231
|
+
// already folded it into totalOutputTokens (#1078 / #1115).
|
|
3232
|
+
const outputTokens = sessionBillableOutputTokens(session);
|
|
3233
|
+
const ratio = inputTokens / Math.max(outputTokens, 1);
|
|
3234
|
+
const currentMs = new Date(session.firstTimestamp).getTime();
|
|
3235
|
+
const gapMs = previousTimestampMs !== null ? currentMs - previousTimestampMs : null;
|
|
3236
|
+
// Suppress growth ratio when the previous session is too far back to be
|
|
3237
|
+
// a meaningful baseline (e.g. a small test run weeks before a real
|
|
3238
|
+
// working session would otherwise produce alarming "1000x" figures).
|
|
3239
|
+
const growthRatio = previousInputTokens !== null
|
|
3240
|
+
&& previousInputTokens > 0
|
|
3241
|
+
&& gapMs !== null
|
|
3242
|
+
&& gapMs <= CONTEXT_BLOAT_GROWTH_MAX_GAP_MS
|
|
3243
|
+
? inputTokens / previousInputTokens
|
|
3244
|
+
: null;
|
|
3245
|
+
// Anchor growth to the immediately previous project session, even if
|
|
3246
|
+
// that session is below threshold and never becomes a finding.
|
|
3247
|
+
previousInputTokens = inputTokens;
|
|
3248
|
+
previousTimestampMs = currentMs;
|
|
3249
|
+
if (inputTokens < CONTEXT_BLOAT_MIN_INPUT_TOKENS)
|
|
3250
|
+
continue;
|
|
3251
|
+
if (ratio < CONTEXT_BLOAT_MIN_RATIO)
|
|
3252
|
+
continue;
|
|
3253
|
+
candidates.push({
|
|
3254
|
+
project: project.project,
|
|
3255
|
+
sessionId: session.sessionId,
|
|
3256
|
+
date: session.firstTimestamp.slice(0, 10),
|
|
3257
|
+
effectiveInputTokens: inputTokens,
|
|
3258
|
+
outputTokens,
|
|
3259
|
+
ratio,
|
|
3260
|
+
excessInputTokens: Math.max(0, inputTokens - outputTokens * CONTEXT_BLOAT_TARGET_RATIO),
|
|
3261
|
+
growthRatio,
|
|
3262
|
+
});
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
candidates.sort((a, b) => b.excessInputTokens - a.excessInputTokens
|
|
3266
|
+
|| a.date.localeCompare(b.date)
|
|
3267
|
+
|| a.project.localeCompare(b.project)
|
|
3268
|
+
|| a.sessionId.localeCompare(b.sessionId));
|
|
3269
|
+
return candidates;
|
|
3270
|
+
}
|
|
3271
|
+
export function detectContextBloat(projects, excludedSessionIds, provider) {
|
|
3272
|
+
const candidates = findContextBloatCandidates(projects)
|
|
3273
|
+
.filter(c => !excludedSessionIds?.has(c.sessionId));
|
|
3274
|
+
if (candidates.length === 0)
|
|
3275
|
+
return null;
|
|
3276
|
+
const preview = candidates.slice(0, CONTEXT_BLOAT_PREVIEW);
|
|
3277
|
+
const list = preview
|
|
3278
|
+
.map(c => {
|
|
3279
|
+
const growth = c.growthRatio !== null && c.growthRatio >= CONTEXT_BLOAT_GROWTH_RATIO
|
|
3280
|
+
? `, ${c.growthRatio.toFixed(1)}x previous session input`
|
|
3281
|
+
: '';
|
|
3282
|
+
return `${c.project}/${c.sessionId} on ${c.date}: ${formatTokens(c.effectiveInputTokens)} effective input/cache vs ${formatTokens(c.outputTokens)} output (${formatContextRatio(c.ratio)}:1${growth})`;
|
|
3283
|
+
})
|
|
3284
|
+
.join('; ');
|
|
3285
|
+
const extra = candidates.length > preview.length ? `; +${candidates.length - preview.length} more` : '';
|
|
3286
|
+
// Savings estimate only counts context above a healthier 15:1 input-output ratio.
|
|
3287
|
+
// Detection stays stricter at 25:1 so borderline sessions are not shown.
|
|
3288
|
+
const tokensSaved = Math.round(candidates.reduce((sum, c) => sum + c.excessInputTokens, 0));
|
|
3289
|
+
const totalInputTokens = candidates.reduce((sum, c) => sum + c.effectiveInputTokens, 0);
|
|
3290
|
+
// Tier on candidate count first, total context size second. A single 600K
|
|
3291
|
+
// session is "high"; 1-2 modest-sized sessions are "low"; everything in
|
|
3292
|
+
// between is "medium".
|
|
3293
|
+
let impact;
|
|
3294
|
+
if (candidates.length >= CONTEXT_BLOAT_HIGH_MIN_CANDIDATES || totalInputTokens >= CONTEXT_BLOAT_HIGH_INPUT_TOKENS) {
|
|
3295
|
+
impact = 'high';
|
|
3296
|
+
}
|
|
3297
|
+
else if (candidates.length <= CONTEXT_BLOAT_LOW_MAX_CANDIDATES && totalInputTokens < CONTEXT_BLOAT_LOW_INPUT_TOKENS) {
|
|
3298
|
+
impact = 'low';
|
|
3299
|
+
}
|
|
3300
|
+
else {
|
|
3301
|
+
impact = 'medium';
|
|
3302
|
+
}
|
|
3303
|
+
return {
|
|
3304
|
+
id: 'context-heavy-sessions',
|
|
3305
|
+
title: `${candidates.length} context-heavy session${candidates.length === 1 ? '' : 's'}`,
|
|
3306
|
+
explanation: `Effective input/cache tokens swamp output in these sessions: ${list}${extra}. This can come from stale context carryover, inherently context-heavy work, or abandoned runs that loaded too much context; starting fresh with only the current goal and relevant files can cut repeated prompt overhead.`,
|
|
3307
|
+
impact,
|
|
3308
|
+
tokensSaved,
|
|
3309
|
+
fix: {
|
|
3310
|
+
type: 'paste',
|
|
3311
|
+
destination: 'session-opener',
|
|
3312
|
+
label: sessionOpenerLabel(optimizeRemediationCopy(provider)),
|
|
3313
|
+
text: CONTEXT_HEAVY_OPENER,
|
|
3314
|
+
},
|
|
3315
|
+
};
|
|
3316
|
+
}
|
|
3317
|
+
export function detectSessionOutliers(projects, excludedSessionIds, provider) {
|
|
3318
|
+
const outliers = [];
|
|
3319
|
+
// Modelled costs (Kiro, Cursor, some Cline sessions) are not comparable
|
|
3320
|
+
// against provider-reported ones, so they leave the peer math. Providers
|
|
3321
|
+
// that only ever estimate would lose the finding entirely, so those fall
|
|
3322
|
+
// back to the full set and the finding reports itself as estimated.
|
|
3323
|
+
let usedEstimatedCosts = false;
|
|
3324
|
+
for (const project of projects) {
|
|
3325
|
+
const costed = project.sessions.filter(s => isOptimizeSession(s) && s.totalCostUSD > 0);
|
|
3326
|
+
const exact = costed.filter(s => (s.totalEstimatedCostUSD ?? 0) === 0);
|
|
3327
|
+
const sessions = exact.length >= MIN_SESSIONS_FOR_OUTLIER ? exact : costed;
|
|
3328
|
+
const fellBack = sessions.length > exact.length;
|
|
3329
|
+
if (sessions.length < MIN_SESSIONS_FOR_OUTLIER)
|
|
3330
|
+
continue;
|
|
3331
|
+
const totalCost = sessions.reduce((sum, s) => sum + s.totalCostUSD, 0);
|
|
3332
|
+
const totalTokens = sessions.reduce((sum, s) => sum + sessionTokenTotal(s), 0);
|
|
3333
|
+
for (const session of sessions) {
|
|
3334
|
+
const avgCost = (totalCost - session.totalCostUSD) / (sessions.length - 1);
|
|
3335
|
+
const avgTokens = (totalTokens - sessionTokenTotal(session)) / (sessions.length - 1);
|
|
3336
|
+
if (avgCost <= 0)
|
|
3337
|
+
continue;
|
|
3338
|
+
const ratio = session.totalCostUSD / avgCost;
|
|
3339
|
+
if (ratio <= SESSION_OUTLIER_MULTIPLIER)
|
|
3340
|
+
continue;
|
|
3341
|
+
if (session.totalCostUSD < MIN_SESSION_OUTLIER_COST_USD)
|
|
3342
|
+
continue;
|
|
3343
|
+
// Avoid reporting the same session under both this finding and the
|
|
3344
|
+
// context-bloat finding. Context-bloat takes priority because its
|
|
3345
|
+
// suggested fix ("start fresh") is more concrete than the generic
|
|
3346
|
+
// "tighter constraint" advice here.
|
|
3347
|
+
if (excludedSessionIds?.has(session.sessionId))
|
|
3348
|
+
continue;
|
|
3349
|
+
if (fellBack)
|
|
3350
|
+
usedEstimatedCosts = true;
|
|
3351
|
+
outliers.push({
|
|
3352
|
+
project: project.project,
|
|
3353
|
+
sessionId: session.sessionId,
|
|
3354
|
+
date: session.firstTimestamp.slice(0, 10),
|
|
3355
|
+
cost: session.totalCostUSD,
|
|
3356
|
+
avgCost,
|
|
3357
|
+
ratio,
|
|
3358
|
+
tokenExcess: Math.max(0, sessionTokenTotal(session) - avgTokens),
|
|
3359
|
+
});
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
if (outliers.length === 0)
|
|
3363
|
+
return null;
|
|
3364
|
+
outliers.sort((a, b) => b.cost - a.cost);
|
|
3365
|
+
const preview = outliers.slice(0, SESSION_OUTLIER_PREVIEW);
|
|
3366
|
+
const list = preview
|
|
3367
|
+
.map(o => `${o.project}/${o.sessionId} on ${o.date}: ${formatCost(o.cost)} (${o.ratio.toFixed(1)}x avg)`)
|
|
3368
|
+
.join('; ');
|
|
3369
|
+
const extra = outliers.length > preview.length ? `; +${outliers.length - preview.length} more` : '';
|
|
3370
|
+
const tokensSaved = Math.round(outliers.reduce((sum, o) => sum + o.tokenExcess, 0));
|
|
3371
|
+
const totalExcessCost = outliers.reduce((sum, o) => sum + Math.max(0, o.cost - o.avgCost), 0);
|
|
3372
|
+
return {
|
|
3373
|
+
id: 'cost-outliers',
|
|
3374
|
+
title: `${outliers.length} high-cost session outlier${outliers.length === 1 ? '' : 's'}`,
|
|
3375
|
+
explanation: `Sessions costing more than ${SESSION_OUTLIER_MULTIPLIER}x their peer-session average in the same project: ${list}${extra}. These usually come from broad prompts, runaway loops, or context-heavy work that should be split into smaller sessions.`,
|
|
3376
|
+
impact: outliers.length >= 3 || totalExcessCost >= 10 ? 'high' : 'medium',
|
|
3377
|
+
tokensSaved,
|
|
3378
|
+
...(usedEstimatedCosts ? { basis: 'estimated' } : {}),
|
|
3379
|
+
fix: {
|
|
3380
|
+
type: 'paste',
|
|
3381
|
+
destination: 'session-opener',
|
|
3382
|
+
label: sessionOpenerLabel(optimizeRemediationCopy(provider)),
|
|
3383
|
+
text: 'Before making changes, summarize the smallest viable plan. Keep context narrow, avoid broad searches, and stop after the first working patch so I can review before continuing.',
|
|
3384
|
+
},
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
export function detectLowCacheHitSessions(projects) {
|
|
3388
|
+
const candidates = [];
|
|
3389
|
+
for (const project of projects) {
|
|
3390
|
+
for (const session of project.sessions) {
|
|
3391
|
+
if (!isOptimizeSession(session))
|
|
3392
|
+
continue;
|
|
3393
|
+
const reads = session.totalCacheReadTokens;
|
|
3394
|
+
const writes = session.totalCacheWriteTokens;
|
|
3395
|
+
const hitPercent = sessionCacheHitPercent(session.totalInputTokens, reads, writes);
|
|
3396
|
+
if (hitPercent === null)
|
|
3397
|
+
continue;
|
|
3398
|
+
if (session.apiCalls < LOW_CACHE_HIT_MIN_CALLS)
|
|
3399
|
+
continue;
|
|
3400
|
+
const totalInput = session.totalInputTokens + reads + writes;
|
|
3401
|
+
if (totalInput < LOW_CACHE_HIT_MIN_INPUT_TOKENS)
|
|
3402
|
+
continue;
|
|
3403
|
+
if (hitPercent >= LOW_CACHE_HIT_TARGET_PERCENT)
|
|
3404
|
+
continue;
|
|
3405
|
+
candidates.push({
|
|
3406
|
+
project: project.project,
|
|
3407
|
+
sessionId: session.sessionId,
|
|
3408
|
+
provider: inferSessionProvider(session),
|
|
3409
|
+
hitPercent,
|
|
3410
|
+
totalInput,
|
|
3411
|
+
missedReads: totalInput * LOW_CACHE_HIT_TARGET_PERCENT / 100 - reads,
|
|
3412
|
+
});
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
if (candidates.length === 0)
|
|
3416
|
+
return null;
|
|
3417
|
+
candidates.sort((a, b) => b.missedReads - a.missedReads || a.sessionId.localeCompare(b.sessionId));
|
|
3418
|
+
const preview = candidates.slice(0, LOW_CACHE_HIT_PREVIEW);
|
|
3419
|
+
const list = preview
|
|
3420
|
+
.map(c => `${c.project}/${c.sessionId} (${providerDisplayName(c.provider)}): ${c.hitPercent.toFixed(1)}% of ${formatTokens(c.totalInput)} input`)
|
|
3421
|
+
.join('; ');
|
|
3422
|
+
const extra = candidates.length > preview.length ? `; +${candidates.length - preview.length} more` : '';
|
|
3423
|
+
const tokensSaved = Math.round(candidates.reduce((sum, c) => sum + c.missedReads, 0) * (1 - CACHE_READ_DISCOUNT));
|
|
3424
|
+
return {
|
|
3425
|
+
id: 'low-cache-hit-sessions',
|
|
3426
|
+
title: `${candidates.length} session${candidates.length === 1 ? '' : 's'} with a low cache hit rate`,
|
|
3427
|
+
explanation: `These sessions read less than ${LOW_CACHE_HIT_TARGET_PERCENT}% of their input from the prompt cache: ${list}${extra}. Healthy agent sessions usually sit above ${LOW_CACHE_HIT_TARGET_PERCENT}%. Low rates come from switching models or tools mid-session, editing instruction files mid-session, or long pauses that let the cache expire, so the full prompt is paid again.`,
|
|
3428
|
+
impact: candidates.length >= 3 || tokensSaved >= CONTEXT_BLOAT_HIGH_INPUT_TOKENS ? 'high' : 'medium',
|
|
3429
|
+
tokensSaved,
|
|
3430
|
+
fix: {
|
|
3431
|
+
type: 'paste',
|
|
3432
|
+
destination: 'manual',
|
|
3433
|
+
label: 'Keep the prompt cache valid:',
|
|
3434
|
+
text: 'Stay on one model per session, and start a new session after editing instruction files or MCP config instead of continuing the old one.',
|
|
3435
|
+
},
|
|
3436
|
+
};
|
|
3437
|
+
}
|
|
3438
|
+
/// The call's tokens priced again at `speed`; `provider` undefined drops the
|
|
3439
|
+
/// long-context tier, as `tieredCostsFor` applies it only to tiered providers.
|
|
3440
|
+
function repricedCallUSD(call, speed, provider) {
|
|
3441
|
+
const u = call.usage;
|
|
3442
|
+
return calculateCost(pricingModelAt(call.model, call.timestamp), u.inputTokens, billableOutputTokens(call.provider, u.outputTokens, u.reasoningTokens), u.cacheCreationInputTokens, u.cacheReadInputTokens, u.webSearchRequests, speed, call.cacheCreationOneHourTokens ?? 0, provider);
|
|
3443
|
+
}
|
|
3444
|
+
function premiumImpact(usd) {
|
|
3445
|
+
return usd > PREMIUM_HIGH_USD ? 'high' : usd > PREMIUM_MEDIUM_USD ? 'medium' : 'low';
|
|
3446
|
+
}
|
|
3447
|
+
function plural(n, word) {
|
|
3448
|
+
return `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
3449
|
+
}
|
|
3450
|
+
export function detectFastModeBackground(projects) {
|
|
3451
|
+
let calls = 0;
|
|
3452
|
+
let premiumUSD = 0;
|
|
3453
|
+
const models = new Set();
|
|
3454
|
+
for (const project of projects) {
|
|
3455
|
+
for (const session of project.sessions) {
|
|
3456
|
+
if (session.isSidechain !== true)
|
|
3457
|
+
continue;
|
|
3458
|
+
for (const turn of session.turns) {
|
|
3459
|
+
for (const call of turn.assistantCalls) {
|
|
3460
|
+
if (call.speed !== 'fast' || call.supplementaryAccounting)
|
|
3461
|
+
continue;
|
|
3462
|
+
const premium = call.costUSD - repricedCallUSD(call, 'standard', call.provider);
|
|
3463
|
+
if (premium <= 0)
|
|
3464
|
+
continue;
|
|
3465
|
+
calls++;
|
|
3466
|
+
premiumUSD += premium;
|
|
3467
|
+
models.add(getShortModelName(call.model));
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
if (premiumUSD < PREMIUM_MIN_USD)
|
|
3473
|
+
return null;
|
|
3474
|
+
return {
|
|
3475
|
+
id: 'fast-mode-background',
|
|
3476
|
+
title: `Fast mode cost ${formatCost(premiumUSD)} extra on background agents`,
|
|
3477
|
+
explanation: `${plural(calls, 'fast-mode call')} ran inside subagent sessions on ${[...models].sort().join(', ')}, where nobody waits for the reply. At standard speed the same tokens would have cost ${formatCost(premiumUSD)} less. Some background runs need the speed, so this is a habit check, not a rule.`,
|
|
3478
|
+
impact: premiumImpact(premiumUSD),
|
|
3479
|
+
// Standard speed bills the same tokens at a lower rate: dollars saved, no tokens.
|
|
3480
|
+
tokensSaved: 0,
|
|
3481
|
+
savingsUSD: premiumUSD,
|
|
3482
|
+
fix: {
|
|
3483
|
+
type: 'paste',
|
|
3484
|
+
destination: 'manual',
|
|
3485
|
+
label: 'Keep fast mode for interactive work:',
|
|
3486
|
+
text: 'Use fast mode only for interactive work. Turn it off before long subagent or background runs, where nobody waits for the speed.',
|
|
3487
|
+
},
|
|
3488
|
+
};
|
|
3489
|
+
}
|
|
3490
|
+
export function detectLongContextPremium(projects) {
|
|
3491
|
+
let totalCalls = 0;
|
|
3492
|
+
let tokensAbove = 0;
|
|
3493
|
+
let premiumUSD = 0;
|
|
3494
|
+
const sessions = new Set();
|
|
3495
|
+
const byModel = new Map();
|
|
3496
|
+
for (const project of projects) {
|
|
3497
|
+
for (const session of project.sessions) {
|
|
3498
|
+
for (const turn of session.turns) {
|
|
3499
|
+
for (const call of turn.assistantCalls) {
|
|
3500
|
+
if (call.supplementaryAccounting)
|
|
3501
|
+
continue;
|
|
3502
|
+
totalCalls++;
|
|
3503
|
+
const threshold = getModelCosts(pricingModelAt(call.model, call.timestamp))?.longContextTier?.thresholdTokens;
|
|
3504
|
+
if (threshold === undefined)
|
|
3505
|
+
continue;
|
|
3506
|
+
// Priced at the call's speed minus fast, so fast-mode-background owns the fast premium.
|
|
3507
|
+
const speed = call.speed === 'fast' ? 'standard' : call.speed;
|
|
3508
|
+
const premium = repricedCallUSD(call, speed, call.provider) - repricedCallUSD(call, speed, undefined);
|
|
3509
|
+
if (premium <= 0)
|
|
3510
|
+
continue;
|
|
3511
|
+
const u = call.usage;
|
|
3512
|
+
const prompt = u.inputTokens + u.cacheReadInputTokens + Math.max(u.cacheCreationInputTokens, call.cacheCreationOneHourTokens ?? 0);
|
|
3513
|
+
tokensAbove += Math.max(0, prompt - threshold);
|
|
3514
|
+
premiumUSD += premium;
|
|
3515
|
+
sessions.add(`${project.projectPath}\0${session.sessionId}`);
|
|
3516
|
+
const name = getShortModelName(call.model);
|
|
3517
|
+
const entry = byModel.get(name) ?? { threshold, calls: 0 };
|
|
3518
|
+
entry.calls++;
|
|
3519
|
+
byModel.set(name, entry);
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
}
|
|
3524
|
+
if (premiumUSD < PREMIUM_MIN_USD)
|
|
3525
|
+
return null;
|
|
3526
|
+
const crossed = [...byModel.values()].reduce((sum, m) => sum + m.calls, 0);
|
|
3527
|
+
const models = [...byModel.entries()].sort((a, b) => b[1].calls - a[1].calls || a[0].localeCompare(b[0]));
|
|
3528
|
+
const list = models.map(([name, m]) => `${name} above ${formatTokens(m.threshold)}: ${plural(m.calls, 'call')}`).join('; ');
|
|
3529
|
+
const share = ((crossed / totalCalls) * 100).toFixed(1);
|
|
3530
|
+
const limits = models.map(([name, m]) => `${formatTokens(m.threshold)} on ${name}`).join(', ');
|
|
3531
|
+
return {
|
|
3532
|
+
id: 'long-context-premium',
|
|
3533
|
+
title: `${plural(crossed, 'call')} crossed the long-context price line, ${formatCost(premiumUSD)} extra`,
|
|
3534
|
+
explanation: `${crossed} of ${totalCalls} calls (${share}%) in ${plural(sessions.size, 'session')} sent more prompt tokens than the model's long-context threshold (${list}), so each of those requests billed at the higher tier. The context may have been needed; this is what it cost.`,
|
|
3535
|
+
impact: premiumImpact(premiumUSD),
|
|
3536
|
+
tokensSaved: tokensAbove,
|
|
3537
|
+
savingsUSD: premiumUSD,
|
|
3538
|
+
fix: {
|
|
3539
|
+
type: 'paste',
|
|
3540
|
+
destination: 'manual',
|
|
3541
|
+
label: 'Stay under the long-context price line:',
|
|
3542
|
+
text: `Compact or start a fresh session before the prompt passes ${limits}.`,
|
|
3543
|
+
},
|
|
3544
|
+
};
|
|
3545
|
+
}
|
|
3546
|
+
function findYoungProjectFirstSessionIds(projects) {
|
|
3547
|
+
const firstSessionIds = new Set();
|
|
3548
|
+
for (const project of projects) {
|
|
3549
|
+
const costed = project.sessions.filter(s => isOptimizeSession(s) && s.totalCostUSD > 0);
|
|
3550
|
+
if (costed.length >= YOUNG_PROJECT_SESSION_LIMIT)
|
|
3551
|
+
continue;
|
|
3552
|
+
let firstSession = null;
|
|
3553
|
+
for (const session of costed) {
|
|
3554
|
+
if (firstSession === null
|
|
3555
|
+
|| new Date(session.firstTimestamp).getTime() < new Date(firstSession.firstTimestamp).getTime()) {
|
|
3556
|
+
firstSession = session;
|
|
3557
|
+
}
|
|
3558
|
+
}
|
|
3559
|
+
if (firstSession)
|
|
3560
|
+
firstSessionIds.add(firstSession.sessionId);
|
|
3561
|
+
}
|
|
3562
|
+
return firstSessionIds;
|
|
3563
|
+
}
|
|
3564
|
+
// ============================================================================
|
|
3565
|
+
// Scoring
|
|
3566
|
+
// ============================================================================
|
|
3567
|
+
const HEALTH_WEIGHTS = {
|
|
3568
|
+
high: HEALTH_WEIGHT_HIGH,
|
|
3569
|
+
medium: HEALTH_WEIGHT_MEDIUM,
|
|
3570
|
+
low: HEALTH_WEIGHT_LOW,
|
|
3571
|
+
};
|
|
3572
|
+
export function computeHealth(findings) {
|
|
3573
|
+
if (findings.length === 0)
|
|
3574
|
+
return { score: 100, grade: 'A' };
|
|
3575
|
+
let penalty = 0;
|
|
3576
|
+
for (const f of findings)
|
|
3577
|
+
penalty += HEALTH_WEIGHTS[f.impact] ?? 0;
|
|
3578
|
+
const score = Math.max(0, 100 - Math.min(HEALTH_MAX_PENALTY, penalty));
|
|
3579
|
+
const grade = score >= GRADE_A_MIN ? 'A' :
|
|
3580
|
+
score >= GRADE_B_MIN ? 'B' :
|
|
3581
|
+
score >= GRADE_C_MIN ? 'C' :
|
|
3582
|
+
score >= GRADE_D_MIN ? 'D' : 'F';
|
|
3583
|
+
return { score, grade };
|
|
3584
|
+
}
|
|
3585
|
+
const URGENCY_WEIGHTS = { high: 1, medium: 0.5, low: 0.2 };
|
|
3586
|
+
function urgencyScore(f) {
|
|
3587
|
+
const normalizedTokens = Math.min(1, f.tokensSaved / URGENCY_TOKEN_NORMALIZE);
|
|
3588
|
+
return URGENCY_WEIGHTS[f.impact] * URGENCY_IMPACT_WEIGHT + normalizedTokens * URGENCY_TOKEN_WEIGHT;
|
|
3589
|
+
}
|
|
3590
|
+
export function computeTrend(inputs) {
|
|
3591
|
+
const { recentCount, recentWindowMs, baselineCount, baselineWindowMs, hasRecentActivity } = inputs;
|
|
3592
|
+
if (baselineCount === 0)
|
|
3593
|
+
return 'active';
|
|
3594
|
+
if (recentCount === 0 && hasRecentActivity)
|
|
3595
|
+
return 'resolved';
|
|
3596
|
+
if (!hasRecentActivity)
|
|
3597
|
+
return 'active';
|
|
3598
|
+
const baselineRate = baselineCount / baselineWindowMs;
|
|
3599
|
+
const recentRate = recentCount / Math.max(recentWindowMs, 1);
|
|
3600
|
+
if (recentRate < baselineRate * IMPROVING_THRESHOLD)
|
|
3601
|
+
return 'improving';
|
|
3602
|
+
return 'active';
|
|
3603
|
+
}
|
|
3604
|
+
function sessionTrend(recentItemCount, totalItemCount, dateRange, hasRecentActivity) {
|
|
3605
|
+
const now = Date.now();
|
|
3606
|
+
const baselineCount = totalItemCount - recentItemCount;
|
|
3607
|
+
const periodStart = dateRange ? dateRange.start.getTime() : now - DEFAULT_TREND_PERIOD_MS;
|
|
3608
|
+
const recentStart = now - RECENT_WINDOW_MS;
|
|
3609
|
+
const baselineWindowMs = Math.max(recentStart - periodStart, 1);
|
|
3610
|
+
return computeTrend({
|
|
3611
|
+
recentCount: recentItemCount,
|
|
3612
|
+
recentWindowMs: RECENT_WINDOW_MS,
|
|
3613
|
+
baselineCount,
|
|
3614
|
+
baselineWindowMs,
|
|
3615
|
+
hasRecentActivity,
|
|
3616
|
+
});
|
|
3617
|
+
}
|
|
3618
|
+
// ============================================================================
|
|
3619
|
+
// Cost estimation
|
|
3620
|
+
// ============================================================================
|
|
3621
|
+
const INPUT_COST_RATIO = 0.7;
|
|
3622
|
+
const DEFAULT_COST_PER_TOKEN = 0;
|
|
3623
|
+
export function computeInputCostRate(projects) {
|
|
3624
|
+
const sessions = projects.flatMap(p => p.sessions);
|
|
3625
|
+
const totalCost = sessions.reduce((s, sess) => s + sess.totalCostUSD, 0);
|
|
3626
|
+
const totalTokens = sessions.reduce((s, sess) => s + sess.totalInputTokens + sess.totalCacheReadTokens + sess.totalCacheWriteTokens, 0);
|
|
3627
|
+
if (totalTokens === 0 || totalCost === 0)
|
|
3628
|
+
return DEFAULT_COST_PER_TOKEN;
|
|
3629
|
+
return (totalCost * INPUT_COST_RATIO) / totalTokens;
|
|
3630
|
+
}
|
|
3631
|
+
export function findingPricing(projects, fallbackRate) {
|
|
3632
|
+
const sessionModels = new Map();
|
|
3633
|
+
for (const project of projects) {
|
|
3634
|
+
for (const session of project.sessions) {
|
|
3635
|
+
const counts = new Map();
|
|
3636
|
+
let best;
|
|
3637
|
+
let bestCount = 0;
|
|
3638
|
+
for (const turn of session.turns) {
|
|
3639
|
+
for (const call of turn.assistantCalls) {
|
|
3640
|
+
const n = (counts.get(call.model) ?? 0) + 1;
|
|
3641
|
+
counts.set(call.model, n);
|
|
3642
|
+
if (n > bestCount) {
|
|
3643
|
+
best = call.model;
|
|
3644
|
+
bestCount = n;
|
|
3645
|
+
}
|
|
3646
|
+
}
|
|
3647
|
+
}
|
|
3648
|
+
if (best !== undefined)
|
|
3649
|
+
sessionModels.set(session.sessionId, best);
|
|
3650
|
+
}
|
|
3651
|
+
}
|
|
3652
|
+
const memo = new Map();
|
|
3653
|
+
const costs = (model) => {
|
|
3654
|
+
if (!memo.has(model))
|
|
3655
|
+
memo.set(model, getModelCosts(model));
|
|
3656
|
+
return memo.get(model);
|
|
3657
|
+
};
|
|
3658
|
+
return { fallbackRate, sessionModels, costs };
|
|
3659
|
+
}
|
|
3660
|
+
/// One token of `kind` at `model`'s own price; undefined when it has none.
|
|
3661
|
+
function modelRate(pricing, model, kind) {
|
|
3662
|
+
const costs = model === undefined ? null : pricing.costs(model);
|
|
3663
|
+
if (!costs)
|
|
3664
|
+
return undefined;
|
|
3665
|
+
if (kind === 'input')
|
|
3666
|
+
return costs.inputCostPerToken;
|
|
3667
|
+
if (kind === 'cacheWrite')
|
|
3668
|
+
return cacheWriteCostPerToken(model, costs);
|
|
3669
|
+
return costs.cacheReadCostPerToken;
|
|
3670
|
+
}
|
|
3671
|
+
/// `tokens` of one session at its own model's rate, else at the blended rate.
|
|
3672
|
+
export function sessionTokensUSD(pricing, sessionId, tokens, kind) {
|
|
3673
|
+
const model = sessionId === undefined ? undefined : pricing.sessionModels.get(sessionId);
|
|
3674
|
+
return tokens * (modelRate(pricing, model, kind) ?? pricing.fallbackRate);
|
|
3675
|
+
}
|
|
3676
|
+
/// The token kind a measured finding prices its tokens at, so `act report`
|
|
3677
|
+
/// prices that fix's realized tokens the same way. Absent: the blended rate.
|
|
3678
|
+
export const FINDING_TOKEN_KIND = {
|
|
3679
|
+
// Their act baselines store effective tokens (writes x1.25, reads x0.1),
|
|
3680
|
+
// which the input rate prices as the finding's per-call cache rates.
|
|
3681
|
+
'mcp-low-coverage': 'input',
|
|
3682
|
+
'mcp-project-scope': 'input',
|
|
3683
|
+
'unused-mcp': 'input',
|
|
3684
|
+
'mcp-deferral-off': 'input',
|
|
3685
|
+
'mcp-alwaysload-hygiene': 'input',
|
|
3686
|
+
'mcp-defer-threshold': 'input',
|
|
3687
|
+
'redundant-rereads': 'input',
|
|
3688
|
+
'build-folder-reads': 'input',
|
|
3689
|
+
};
|
|
3690
|
+
/// Schema tokens charged once per session, priced at the input rate of each
|
|
3691
|
+
/// session in `sessions`: the token count times their mean rate.
|
|
3692
|
+
function perSessionSchemaUSD(pricing, sessions, tokens) {
|
|
3693
|
+
if (sessions.length === 0)
|
|
3694
|
+
return tokens * pricing.fallbackRate;
|
|
3695
|
+
const meanRate = sessions.reduce((sum, s) => sum + sessionTokensUSD(pricing, s.sessionId, 1, 'input'), 0) / sessions.length;
|
|
3696
|
+
return tokens * meanRate;
|
|
3697
|
+
}
|
|
3698
|
+
const resultCache = new Map();
|
|
3699
|
+
export function cacheKey(projects, dateRange, provider) {
|
|
3700
|
+
const dr = dateRange ? `${dateRange.start.getTime()}-${dateRange.end.getTime()}` : 'all';
|
|
3701
|
+
// Fingerprint enough of the dataset that two materially different inputs
|
|
3702
|
+
// cannot collide onto one cached OptimizeResult. Project count + api-call
|
|
3703
|
+
// sum alone collided any two datasets sharing those two numbers, and served
|
|
3704
|
+
// stale findings when cost/tokens moved (e.g. a re-price) while call count
|
|
3705
|
+
// held - reachable in the long-lived menubar process within the 60s TTL.
|
|
3706
|
+
// Cost is scaled to whole micro-dollars so float jitter cannot thrash the key.
|
|
3707
|
+
let calls = 0, cost = 0, savings = 0, proxied = 0, sidechains = 0;
|
|
3708
|
+
const sessions = countSessions(projects);
|
|
3709
|
+
const sidechainIdentities = [];
|
|
3710
|
+
for (const p of projects) {
|
|
3711
|
+
calls += p.totalApiCalls;
|
|
3712
|
+
cost += p.totalCostUSD;
|
|
3713
|
+
savings += p.totalSavingsUSD;
|
|
3714
|
+
proxied += p.totalProxiedCostUSD;
|
|
3715
|
+
for (const session of p.sessions) {
|
|
3716
|
+
if (session.isSidechain !== true)
|
|
3717
|
+
continue;
|
|
3718
|
+
sidechains++;
|
|
3719
|
+
sidechainIdentities.push(`${p.projectPath}\0${session.sessionId}`);
|
|
3720
|
+
}
|
|
3721
|
+
}
|
|
3722
|
+
const sidechainDigest = createHash('sha256')
|
|
3723
|
+
.update(sidechainIdentities.sort().join('\0'))
|
|
3724
|
+
.digest('base64url');
|
|
3725
|
+
// Costs scaled to whole micro-dollars so float jitter cannot thrash the key.
|
|
3726
|
+
const fingerprint = `${projects.length}:${sessions}:${sidechains}:${sidechainDigest}:${calls}:${Math.round(cost * 1e6)}:${Math.round(savings * 1e6)}:${Math.round(proxied * 1e6)}`;
|
|
3727
|
+
// The provider decides whether the Claude session scan runs at all, so two
|
|
3728
|
+
// filters that happen to share a project fingerprint must not share a result.
|
|
3729
|
+
return `${provider ?? 'all'}:${dr}:${fingerprint}`;
|
|
3730
|
+
}
|
|
3731
|
+
export async function scanAndDetect(projects, dateRange, provider) {
|
|
3732
|
+
if (projects.length === 0) {
|
|
3733
|
+
return { findings: [], costRate: 0, healthScore: 100, healthGrade: 'A', modelRecommendations: [] };
|
|
3734
|
+
}
|
|
3735
|
+
const key = cacheKey(projects, dateRange, provider);
|
|
3736
|
+
const cached = resultCache.get(key);
|
|
3737
|
+
if (cached && Date.now() - cached.ts < RESULT_CACHE_TTL_MS)
|
|
3738
|
+
return cached.data;
|
|
3739
|
+
const costRate = computeInputCostRate(projects);
|
|
3740
|
+
const pricing = findingPricing(projects, costRate);
|
|
3741
|
+
const behavioralProjects = userStartedProjects(projects);
|
|
3742
|
+
const scanCoversClaude = providerCoversClaude(provider);
|
|
3743
|
+
const { toolCalls, projectCwds, apiCalls, commandNames, openers } = await scanSessions(dateRange, provider);
|
|
3744
|
+
const mcpCoverage = aggregateMcpCoverage(projects);
|
|
3745
|
+
const findings = [];
|
|
3746
|
+
// Priority order for the per-session findings: low-worth → context-bloat →
|
|
3747
|
+
// outliers. Each later detector excludes sessions already named by an
|
|
3748
|
+
// earlier one so a single session is not listed in three findings.
|
|
3749
|
+
const lowWorthSessionIds = new Set(findLowWorthCandidates(behavioralProjects).map(c => c.sessionId));
|
|
3750
|
+
const contextBloatVisibleIds = new Set(findContextBloatCandidates(behavioralProjects)
|
|
3751
|
+
.filter(c => !lowWorthSessionIds.has(c.sessionId))
|
|
3752
|
+
.map(c => c.sessionId));
|
|
3753
|
+
const firstSessionIds = findYoungProjectFirstSessionIds(behavioralProjects);
|
|
3754
|
+
const outlierExclusions = new Set([...lowWorthSessionIds, ...contextBloatVisibleIds, ...firstSessionIds]);
|
|
3755
|
+
// Detectors fed by the session scan or by `~/.claude` config only mean
|
|
3756
|
+
// anything when the run covers Claude. Under a different `--provider` they
|
|
3757
|
+
// must be skipped rather than handed an empty scan: emptiness reads as
|
|
3758
|
+
// "never invoked", so every skill, agent and command would be reported as
|
|
3759
|
+
// unused when it was simply not measured.
|
|
3760
|
+
const claudeOnly = (detect) => scanCoversClaude ? detect : () => null;
|
|
3761
|
+
const unusedMcp = scanCoversClaude ? detectUnusedMcp(toolCalls, projects, projectCwds, mcpCoverage, pricing) : null;
|
|
3762
|
+
const unusedMcpServers = new Set(unusedMcp?.apply?.kind === 'mcp-remove' ? unusedMcp.apply.servers.map(mcpNamespace) : []);
|
|
3763
|
+
const syncDetectors = [
|
|
3764
|
+
claudeOnly(() => detectCacheBloat(apiCalls, projects, dateRange, pricing)),
|
|
3765
|
+
claudeOnly(() => detectLowReadEditRatio(toolCalls)),
|
|
3766
|
+
claudeOnly(() => detectJunkReads(toolCalls, dateRange, pricing)),
|
|
3767
|
+
claudeOnly(() => detectDuplicateReads(toolCalls, dateRange, pricing)),
|
|
3768
|
+
() => unusedMcp,
|
|
3769
|
+
() => detectMcpToolCoverage(projects, mcpCoverage, localMcpServerNames(projectCwds), pricing),
|
|
3770
|
+
() => detectMcpProfileAdvisor(projects, mcpCoverage, provider, pricing),
|
|
3771
|
+
// mcp-deferral-gaps family (#614): detection only, no apply plans yet.
|
|
3772
|
+
claudeOnly(() => detectMcpDeferralOff(toolCalls, projects, projectCwds, apiCalls, undefined, pricing, unusedMcpServers)),
|
|
3773
|
+
claudeOnly(() => detectMcpAlwaysLoadHygiene(projects, projectCwds, apiCalls, mcpCoverage, pricing, unusedMcpServers)),
|
|
3774
|
+
claudeOnly(() => detectMcpDeferThreshold(projects, projectCwds, undefined, pricing)),
|
|
3775
|
+
claudeOnly(() => detectIdleCompactionBlocked(projects, projectCwds, apiCalls)),
|
|
3776
|
+
() => detectCapabilityReliability(behavioralProjects, provider),
|
|
3777
|
+
() => detectLowWorthSessions(behavioralProjects, provider),
|
|
3778
|
+
() => detectContextBloat(behavioralProjects, lowWorthSessionIds, provider),
|
|
3779
|
+
() => detectSessionOutliers(behavioralProjects, outlierExclusions, provider),
|
|
3780
|
+
() => detectLowCacheHitSessions(behavioralProjects),
|
|
3781
|
+
() => detectFastModeBackground(projects),
|
|
3782
|
+
() => detectLongContextPremium(projects),
|
|
3783
|
+
() => detectOneHourCacheUnused(projects),
|
|
3784
|
+
claudeOnly(() => detectBloatedClaudeMd(projectCwds)),
|
|
3785
|
+
claudeOnly(() => detectBashBloat(projectCwds)),
|
|
3786
|
+
claudeOnly(() => detectRecurringContext(openers)),
|
|
3787
|
+
];
|
|
3788
|
+
for (const detect of syncDetectors) {
|
|
3789
|
+
const finding = detect();
|
|
3790
|
+
if (finding)
|
|
3791
|
+
findings.push(finding);
|
|
3792
|
+
}
|
|
3793
|
+
const ghostResults = scanCoversClaude
|
|
3794
|
+
? await Promise.all([
|
|
3795
|
+
detectGhostAgents(toolCalls),
|
|
3796
|
+
detectGhostSkills(toolCalls),
|
|
3797
|
+
detectGhostCommands(commandNames),
|
|
3798
|
+
])
|
|
3799
|
+
: [];
|
|
3800
|
+
for (const f of ghostResults)
|
|
3801
|
+
if (f)
|
|
3802
|
+
findings.push(f);
|
|
3803
|
+
// Urgency first, then class: every surface lists the apply-able fixes
|
|
3804
|
+
// before the habit nudges, and orders by urgency inside each group.
|
|
3805
|
+
findings.sort((a, b) => urgencyScore(b) - urgencyScore(a));
|
|
3806
|
+
findings.sort((a, b) => CLASS_ORDER[findingClass(a)] - CLASS_ORDER[findingClass(b)]);
|
|
3807
|
+
const { score, grade } = computeHealth(findings);
|
|
3808
|
+
const modelRecommendations = [];
|
|
3809
|
+
for (const project of behavioralProjects) {
|
|
3810
|
+
const rec = recommendModelDefault(project, { now: dateRange?.end });
|
|
3811
|
+
if (rec)
|
|
3812
|
+
modelRecommendations.push(rec);
|
|
3813
|
+
}
|
|
3814
|
+
const result = { findings, costRate, healthScore: score, healthGrade: grade, modelRecommendations };
|
|
3815
|
+
resultCache.set(key, { data: result, ts: Date.now() });
|
|
3816
|
+
return result;
|
|
3817
|
+
}
|
|
3818
|
+
// ============================================================================
|
|
3819
|
+
// CLI rendering
|
|
3820
|
+
// ============================================================================
|
|
3821
|
+
const PANEL_WIDTH = 62;
|
|
3822
|
+
const SEP = '\u2500';
|
|
3823
|
+
const IMPACT_COLORS = { high: RED, medium: ORANGE, low: DIM };
|
|
3824
|
+
const GRADE_COLORS = { A: GREEN, B: GREEN, C: GOLD, D: ORANGE, F: RED };
|
|
3825
|
+
function wrap(text, width, indent) {
|
|
3826
|
+
const words = text.split(' ');
|
|
3827
|
+
const lines = [];
|
|
3828
|
+
let current = '';
|
|
3829
|
+
for (const word of words) {
|
|
3830
|
+
if (current && current.length + word.length + 1 > width) {
|
|
3831
|
+
lines.push(indent + current);
|
|
3832
|
+
current = word;
|
|
3833
|
+
}
|
|
3834
|
+
else {
|
|
3835
|
+
current = current ? current + ' ' + word : word;
|
|
3836
|
+
}
|
|
3837
|
+
}
|
|
3838
|
+
if (current)
|
|
3839
|
+
lines.push(indent + current);
|
|
3840
|
+
return lines.join('\n');
|
|
3841
|
+
}
|
|
3842
|
+
/// Section header for a finding's fix block, declaring its intended
|
|
3843
|
+
/// destination. Issue #277: users were dropping one-time session openers
|
|
3844
|
+
/// into CLAUDE.md as permanent rules because the prompts had no labeled
|
|
3845
|
+
/// home in the output.
|
|
3846
|
+
function renderActionHeader(action, copy) {
|
|
3847
|
+
const headerWidth = PANEL_WIDTH - 4;
|
|
3848
|
+
const fillTo = (label) => {
|
|
3849
|
+
const inner = ` ${label} `;
|
|
3850
|
+
const trailing = Math.max(2, headerWidth - inner.length - 4);
|
|
3851
|
+
return `--${inner}${SEP.repeat(trailing)}`.padEnd(headerWidth);
|
|
3852
|
+
};
|
|
3853
|
+
switch (action.type) {
|
|
3854
|
+
case 'file-content':
|
|
3855
|
+
return fillTo(`Suggested ${action.path} addition`);
|
|
3856
|
+
case 'command':
|
|
3857
|
+
return fillTo('Run this command');
|
|
3858
|
+
case 'paste':
|
|
3859
|
+
return fillTo(optimizePasteHeader(action.destination, copy));
|
|
3860
|
+
}
|
|
3861
|
+
}
|
|
3862
|
+
function renderFinding(n, f, costRate, copy) {
|
|
3863
|
+
const lines = [];
|
|
3864
|
+
const costSaved = findingUSD(f, costRate);
|
|
3865
|
+
const impactLabel = f.impact.charAt(0).toUpperCase() + f.impact.slice(1);
|
|
3866
|
+
const trendBadge = f.trend === 'improving' ? ' improving \u2193 ' : '';
|
|
3867
|
+
const savings = `~${formatTokens(f.tokensSaved)} tokens (~${formatCost(costSaved)})`;
|
|
3868
|
+
const titlePad = PANEL_WIDTH - f.title.length - impactLabel.length - trendBadge.length - 8;
|
|
3869
|
+
const pad = titlePad > 0 ? ' ' + SEP.repeat(titlePad) + ' ' : ' ';
|
|
3870
|
+
lines.push(chalk.hex(DIM)(` ${SEP}${SEP}${SEP} `) +
|
|
3871
|
+
chalk.bold(`${n}. ${f.title}`) +
|
|
3872
|
+
chalk.hex(DIM)(pad) +
|
|
3873
|
+
chalk.hex(IMPACT_COLORS[f.impact])(impactLabel) +
|
|
3874
|
+
(trendBadge ? chalk.hex(GREEN)(trendBadge) : '') +
|
|
3875
|
+
chalk.hex(DIM)(` ${SEP}${SEP}${SEP}`));
|
|
3876
|
+
lines.push('');
|
|
3877
|
+
lines.push(wrap(f.explanation, PANEL_WIDTH - 4, ' '));
|
|
3878
|
+
lines.push('');
|
|
3879
|
+
if (f.tokensSaved > 0 || costSaved > 0) {
|
|
3880
|
+
lines.push(chalk.hex(GOLD)(` Potential savings: ${savings}`) + chalk.dim(` ${findingBasis(f)}`));
|
|
3881
|
+
lines.push('');
|
|
3882
|
+
}
|
|
3883
|
+
// Destination header — issue #277. Tells the user where each suggestion
|
|
3884
|
+
// belongs (CLAUDE.md / session opener / current chat / shell config) so
|
|
3885
|
+
// permanent rules and one-time prompts are no longer interchangeable in
|
|
3886
|
+
// the output.
|
|
3887
|
+
const a = f.fix;
|
|
3888
|
+
lines.push(chalk.hex(ORANGE)(` ${renderActionHeader(a, copy)}`));
|
|
3889
|
+
lines.push(chalk.hex(DIM)(` ${a.label}`));
|
|
3890
|
+
if (a.type === 'file-content') {
|
|
3891
|
+
for (const line of a.content.split('\n'))
|
|
3892
|
+
lines.push(chalk.hex(CYAN)(` ${line}`));
|
|
3893
|
+
}
|
|
3894
|
+
else if (a.type === 'command') {
|
|
3895
|
+
for (const line of a.text.split('\n'))
|
|
3896
|
+
lines.push(chalk.hex(CYAN)(` ${line}`));
|
|
3897
|
+
}
|
|
3898
|
+
else {
|
|
3899
|
+
for (const line of a.text.split('\n'))
|
|
3900
|
+
lines.push(chalk.hex(CYAN)(` ${line}`));
|
|
3901
|
+
}
|
|
3902
|
+
lines.push('');
|
|
3903
|
+
return lines;
|
|
3904
|
+
}
|
|
3905
|
+
function renderWorkflowSection(reworkedFiles, coachingNotes) {
|
|
3906
|
+
const lines = [];
|
|
3907
|
+
if (reworkedFiles.length > 0) {
|
|
3908
|
+
lines.push(chalk.bold.hex(ORANGE)(' Top reworked files'));
|
|
3909
|
+
lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH)));
|
|
3910
|
+
for (const f of reworkedFiles) {
|
|
3911
|
+
const meta = chalk.dim(`${f.sessions} session${f.sessions === 1 ? '' : 's'}, ${f.edits} edit${f.edits === 1 ? '' : 's'}`);
|
|
3912
|
+
lines.push(` ${f.path} ${meta}`);
|
|
3913
|
+
}
|
|
3914
|
+
lines.push('');
|
|
3915
|
+
}
|
|
3916
|
+
if (coachingNotes.length > 0) {
|
|
3917
|
+
lines.push(chalk.bold.hex(ORANGE)(' Coaching notes'));
|
|
3918
|
+
lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH)));
|
|
3919
|
+
for (const note of coachingNotes) {
|
|
3920
|
+
lines.push(wrap('- ' + note, PANEL_WIDTH, ' '));
|
|
3921
|
+
}
|
|
3922
|
+
lines.push('');
|
|
3923
|
+
}
|
|
3924
|
+
return lines;
|
|
3925
|
+
}
|
|
3926
|
+
const APPLIED_FIX_COLORS = {
|
|
3927
|
+
worked: GREEN,
|
|
3928
|
+
partial: GOLD,
|
|
3929
|
+
'no-effect': RED,
|
|
3930
|
+
pending: DIM,
|
|
3931
|
+
};
|
|
3932
|
+
// Closes the loop after --apply: every still-applied fix gets its measured
|
|
3933
|
+
// verdict back here, on every run.
|
|
3934
|
+
function renderAppliedFixes(appliedFixes) {
|
|
3935
|
+
if (appliedFixes.length === 0)
|
|
3936
|
+
return [];
|
|
3937
|
+
const lines = [chalk.bold.hex(ORANGE)(' Applied fixes'), ''];
|
|
3938
|
+
for (const fix of appliedFixes) {
|
|
3939
|
+
lines.push(chalk.hex(APPLIED_FIX_COLORS[fix.verdict])(` ${appliedFixGlyph(fix)} ${formatAppliedFix(fix)}`));
|
|
3940
|
+
}
|
|
3941
|
+
lines.push('');
|
|
3942
|
+
return lines;
|
|
3943
|
+
}
|
|
3944
|
+
export function renderOptimize(findings, costRate, periodLabel, periodCost, sessionCount, callCount, healthScore, healthGrade, reworkedFiles, coachingNotes, appliedHeader, previouslyApplied, modelRecommendations, appliedFixes = [], provider) {
|
|
3945
|
+
const copy = optimizeRemediationCopy(provider);
|
|
3946
|
+
const lines = [];
|
|
3947
|
+
lines.push('');
|
|
3948
|
+
lines.push(` ${chalk.bold.hex(ORANGE)('CodeBurn config health')}${chalk.dim(' ' + periodLabel)}`);
|
|
3949
|
+
lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH)));
|
|
3950
|
+
const issueSuffix = findings.length > 0 ? `, ${findings.length} issue${findings.length > 1 ? 's' : ''}` : '';
|
|
3951
|
+
const measured = findings.filter(f => findingBasis(f) === 'measured').length;
|
|
3952
|
+
lines.push(' ' + [
|
|
3953
|
+
`${sessionCount} session${sessionCount === 1 ? '' : 's'}`,
|
|
3954
|
+
`${callCount.toLocaleString()} calls`,
|
|
3955
|
+
chalk.hex(GOLD)(formatCost(periodCost)),
|
|
3956
|
+
`Health: ${chalk.bold.hex(GRADE_COLORS[healthGrade])(healthGrade)}${chalk.dim(` (${healthScore}/100${issueSuffix})`)}`,
|
|
3957
|
+
].join(chalk.hex(DIM)(' ')));
|
|
3958
|
+
if (findings.length > 0) {
|
|
3959
|
+
lines.push(chalk.dim(` ${measured} measured · ${findings.length - measured} estimated`));
|
|
3960
|
+
}
|
|
3961
|
+
if (appliedHeader)
|
|
3962
|
+
lines.push(' ' + chalk.hex(GREEN)(appliedHeader));
|
|
3963
|
+
lines.push('');
|
|
3964
|
+
if (findings.length === 0) {
|
|
3965
|
+
lines.push(chalk.hex(GREEN)(' Nothing to fix. Your setup is lean.'));
|
|
3966
|
+
lines.push('');
|
|
3967
|
+
for (const line of optimizeEmptyScanLines(provider)) {
|
|
3968
|
+
lines.push(chalk.dim(` ${line}`));
|
|
3969
|
+
}
|
|
3970
|
+
lines.push('');
|
|
3971
|
+
lines.push(...renderAppliedFixes(appliedFixes));
|
|
3972
|
+
lines.push(...renderWorkflowSection(reworkedFiles, coachingNotes));
|
|
3973
|
+
return lines.join('\n');
|
|
3974
|
+
}
|
|
3975
|
+
const totalTokens = findings.reduce((s, f) => s + f.tokensSaved, 0);
|
|
3976
|
+
const totalCost = findings.reduce((s, f) => s + findingUSD(f, costRate), 0);
|
|
3977
|
+
const pctRaw = periodCost > 0 ? (totalCost / periodCost) * 100 : 0;
|
|
3978
|
+
const pct = pctRaw >= 1 ? pctRaw.toFixed(0) : pctRaw.toFixed(1);
|
|
3979
|
+
const totals = classTotals(findings, costRate);
|
|
3980
|
+
const costText = costRate > 0 ? ` (~${formatCost(totalCost)}, ~${pct}% of spend)` : '';
|
|
3981
|
+
// The headline is the whole board; name the apply-able slice separately so
|
|
3982
|
+
// it never reads as "what CodeBurn can fix for you".
|
|
3983
|
+
const applyable = costRate > 0 && totals.fix.count > 0 ? ` — apply-able: ~${formatCost(totals.fix.savingsUSD)}` : '';
|
|
3984
|
+
lines.push(chalk.hex(GREEN)(` Potential savings: ~${formatTokens(totalTokens)} tokens${costText}${applyable}`));
|
|
3985
|
+
lines.push('');
|
|
3986
|
+
// One block per class, in fix -> nudge -> keep order; numbering runs
|
|
3987
|
+
// continuously across the blocks so `--only` picks stay unambiguous.
|
|
3988
|
+
let n = 0;
|
|
3989
|
+
for (const cls of ['fix', 'nudge', 'keep']) {
|
|
3990
|
+
const group = findings.filter(f => findingClass(f) === cls);
|
|
3991
|
+
if (group.length === 0)
|
|
3992
|
+
continue;
|
|
3993
|
+
lines.push(chalk.bold.hex(ORANGE)(` ${classHeaderLine(cls, totals[cls], costRate)}`));
|
|
3994
|
+
lines.push('');
|
|
3995
|
+
for (const f of group) {
|
|
3996
|
+
const appliedOn = previouslyApplied?.[f.id];
|
|
3997
|
+
const shown = appliedOn ? { ...f, title: `${f.title} (previously applied ${appliedOn}, re-flagged)` } : f;
|
|
3998
|
+
lines.push(...renderFinding(++n, shown, costRate, copy));
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH)));
|
|
4002
|
+
lines.push('');
|
|
4003
|
+
lines.push(...renderAppliedFixes(appliedFixes));
|
|
4004
|
+
lines.push(...renderWorkflowSection(reworkedFiles, coachingNotes));
|
|
4005
|
+
if (modelRecommendations && modelRecommendations.length > 0) {
|
|
4006
|
+
lines.push(chalk.bold.hex(ORANGE)(' Model defaults recommendation'));
|
|
4007
|
+
lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH)));
|
|
4008
|
+
for (const rec of modelRecommendations) {
|
|
4009
|
+
lines.push(` ${rec.project}: ${chalk.bold(rec.currentModel)} -> ${chalk.bold.hex(GREEN)(rec.candidateModel)}`);
|
|
4010
|
+
lines.push(chalk.dim(` Current: ${(rec.currentOneShotRate * 100).toFixed(1)}% one-shot over ${rec.currentEditTurns} edits, ${formatCost(rec.currentCostPerEdit)}/edit`));
|
|
4011
|
+
lines.push(chalk.dim(` Candidate: ${(rec.candidateOneShotRate * 100).toFixed(1)}% one-shot over ${rec.candidateEditTurns} edits, ${formatCost(rec.candidateCostPerEdit)}/edit`));
|
|
4012
|
+
lines.push(` To apply: ${chalk.hex(CYAN)(`codeburn act apply-model ${rec.project}`)}`);
|
|
4013
|
+
lines.push('');
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
return lines.join('\n');
|
|
4017
|
+
}
|
|
4018
|
+
// File churn + coaching notes for the workflow-intelligence section. Both are
|
|
4019
|
+
// derived from the same parsed projects the detectors already ran on, so this
|
|
4020
|
+
// adds no extra file I/O.
|
|
4021
|
+
function buildWorkflowReport(projects) {
|
|
4022
|
+
const topReworkedFiles = aggregateFileChurn(projects);
|
|
4023
|
+
const corrections = scanUserCorrections(projects);
|
|
4024
|
+
const coachingNotes = buildCoachingNotes({
|
|
4025
|
+
worstOneShot: worstOneShotCategory(projects),
|
|
4026
|
+
corrections: corrections.corrections,
|
|
4027
|
+
correctionRate: corrections.correctionRate,
|
|
4028
|
+
topReworkedFile: topReworkedFiles[0] ?? null,
|
|
4029
|
+
medianTimeToFirstEditMs: medianTimeToFirstEditMs(projects),
|
|
4030
|
+
});
|
|
4031
|
+
return { topReworkedFiles, coachingNotes };
|
|
4032
|
+
}
|
|
4033
|
+
export async function runOptimize(projects, periodLabel, dateRange, opts = {}) {
|
|
4034
|
+
const format = opts.format ?? 'text';
|
|
4035
|
+
if (projects.length === 0 && format === 'text') {
|
|
4036
|
+
console.log(chalk.dim('\n No usage data found for this period.\n'));
|
|
4037
|
+
return;
|
|
4038
|
+
}
|
|
4039
|
+
if (format === 'text') {
|
|
4040
|
+
process.stderr.write(chalk.dim(' Analyzing your sessions...\n'));
|
|
4041
|
+
}
|
|
4042
|
+
const result = await scanAndDetect(projects, dateRange, opts.provider);
|
|
4043
|
+
const { findings, costRate, healthScore, healthGrade } = result;
|
|
4044
|
+
const sessionCount = optimizeSessionCount(projects);
|
|
4045
|
+
const periodCost = projects.reduce((s, p) => s + p.totalCostUSD, 0);
|
|
4046
|
+
const callCount = projects.reduce((s, p) => s + p.totalApiCalls, 0);
|
|
4047
|
+
if (format === 'json') {
|
|
4048
|
+
console.log(JSON.stringify(buildOptimizeJsonReport(projects, periodLabel, result, dateRange, opts.appliedFixes), null, 2));
|
|
4049
|
+
return;
|
|
4050
|
+
}
|
|
4051
|
+
const { topReworkedFiles, coachingNotes } = buildWorkflowReport(projects);
|
|
4052
|
+
const output = renderOptimize(findings, costRate, periodLabel, periodCost, sessionCount, callCount, healthScore, healthGrade, topReworkedFiles, coachingNotes, opts.appliedHeader, opts.previouslyApplied, result.modelRecommendations, opts.appliedFixes, opts.provider);
|
|
4053
|
+
console.log(output);
|
|
4054
|
+
}
|
|
4055
|
+
export function buildOptimizeJsonReport(projects, periodLabel, result, dateRange, appliedFixes = []) {
|
|
4056
|
+
const periodCostUSD = projects.reduce((s, p) => s + p.totalCostUSD, 0);
|
|
4057
|
+
const calls = projects.reduce((s, p) => s + p.totalApiCalls, 0);
|
|
4058
|
+
const potentialSavingsTokens = result.findings.reduce((s, f) => s + f.tokensSaved, 0);
|
|
4059
|
+
const potentialSavingsCostUSD = result.findings.reduce((s, f) => s + findingUSD(f, result.costRate), 0);
|
|
4060
|
+
const potentialSavingsPercent = periodCostUSD > 0
|
|
4061
|
+
? Math.round((potentialSavingsCostUSD / periodCostUSD) * 1000) / 10
|
|
4062
|
+
: null;
|
|
4063
|
+
return {
|
|
4064
|
+
period: {
|
|
4065
|
+
label: periodLabel,
|
|
4066
|
+
start: dateRange?.start.toISOString() ?? null,
|
|
4067
|
+
end: dateRange?.end.toISOString() ?? null,
|
|
4068
|
+
},
|
|
4069
|
+
summary: {
|
|
4070
|
+
healthScore: result.healthScore,
|
|
4071
|
+
healthGrade: result.healthGrade,
|
|
4072
|
+
findingCount: result.findings.length,
|
|
4073
|
+
periodCostUSD,
|
|
4074
|
+
sessions: optimizeSessionCount(projects),
|
|
4075
|
+
calls,
|
|
4076
|
+
potentialSavingsTokens,
|
|
4077
|
+
potentialSavingsCostUSD,
|
|
4078
|
+
potentialSavingsPercent,
|
|
4079
|
+
costRateUSD: result.costRate,
|
|
4080
|
+
measuredSavingsUSD: result.findings
|
|
4081
|
+
.filter(f => findingBasis(f) === 'measured')
|
|
4082
|
+
.reduce((s, f) => s + findingUSD(f, result.costRate), 0),
|
|
4083
|
+
byClass: classTotals(result.findings, result.costRate),
|
|
4084
|
+
},
|
|
4085
|
+
findings: result.findings.map(f => ({
|
|
4086
|
+
id: f.id,
|
|
4087
|
+
title: f.title,
|
|
4088
|
+
explanation: f.explanation,
|
|
4089
|
+
severity: f.impact,
|
|
4090
|
+
trend: f.trend ?? null,
|
|
4091
|
+
tokensSaved: f.tokensSaved,
|
|
4092
|
+
estimatedSavingsUSD: findingUSD(f, result.costRate),
|
|
4093
|
+
class: findingClass(f),
|
|
4094
|
+
basis: findingBasis(f),
|
|
4095
|
+
fix: f.fix,
|
|
4096
|
+
})),
|
|
4097
|
+
...buildWorkflowReport(projects),
|
|
4098
|
+
modelRecommendations: result.modelRecommendations,
|
|
4099
|
+
appliedFixes: appliedFixes.map(f => ({
|
|
4100
|
+
id: f.id,
|
|
4101
|
+
kind: f.kind,
|
|
4102
|
+
findingId: f.findingId,
|
|
4103
|
+
appliedAt: f.appliedAt,
|
|
4104
|
+
verdict: f.verdict,
|
|
4105
|
+
estimatedTokens: f.estimatedTokens,
|
|
4106
|
+
realizedTokens: f.realizedTokens,
|
|
4107
|
+
undoCommand: f.undoCommand,
|
|
4108
|
+
})),
|
|
4109
|
+
};
|
|
4110
|
+
}
|