forked from getagentseal/codeburn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimize.ts
More file actions
1948 lines (1715 loc) · 75.3 KB
/
Copy pathoptimize.ts
File metadata and controls
1948 lines (1715 loc) · 75.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import chalk from 'chalk'
import { readdir, stat } from 'fs/promises'
import { existsSync, statSync } from 'fs'
import { basename, join } from 'path'
import { homedir } from 'os'
import { readSessionLines, readSessionFileSync } from './fs-utils.js'
import { discoverAllSessions } from './providers/index.js'
import type { DateRange, ProjectSummary } from './types.js'
import { formatCost } from './currency.js'
import { formatTokens } from './format.js'
// ============================================================================
// Display constants
// ============================================================================
const ORANGE = '#FF8C42'
const DIM = '#666666'
const GOLD = '#FFD700'
const CYAN = '#5BF5E0'
const GREEN = '#5BF5A0'
const RED = '#F55B5B'
// ============================================================================
// Token estimation constants
// ============================================================================
const AVG_TOKENS_PER_READ = 600
const TOKENS_PER_MCP_TOOL = 400
const TOOLS_PER_MCP_SERVER = 5
const TOKENS_PER_AGENT_DEF = 80
const TOKENS_PER_SKILL_DEF = 80
const TOKENS_PER_COMMAND_DEF = 60
const CLAUDEMD_TOKENS_PER_LINE = 13
const BASH_TOKENS_PER_CHAR = 0.25
// ============================================================================
// Detector thresholds
// ============================================================================
const CLAUDEMD_HEALTHY_LINES = 200
const CLAUDEMD_HIGH_THRESHOLD_LINES = 400
const MIN_JUNK_READS_TO_FLAG = 3
const JUNK_READS_HIGH_THRESHOLD = 20
const JUNK_READS_MEDIUM_THRESHOLD = 5
const MIN_DUPLICATE_READS_TO_FLAG = 5
const DUPLICATE_READS_HIGH_THRESHOLD = 30
const DUPLICATE_READS_MEDIUM_THRESHOLD = 10
const MIN_EDITS_FOR_RATIO = 10
const HEALTHY_READ_EDIT_RATIO = 4
const LOW_RATIO_HIGH_THRESHOLD = 2
const LOW_RATIO_MEDIUM_THRESHOLD = 3
const MIN_API_CALLS_FOR_CACHE = 10
const CACHE_EXCESS_HIGH_THRESHOLD = 15000
const UNUSED_MCP_HIGH_THRESHOLD = 3
// MCP tool coverage detector thresholds. A server only earns a finding when
// every condition holds: the inventory is large enough to matter, real-world
// usage is poor, and we observed it in enough sessions to trust the signal.
const MCP_COVERAGE_MIN_TOOLS = 10
const MCP_COVERAGE_MIN_SESSIONS = 2
const MCP_COVERAGE_LOW_THRESHOLD = 0.20
const MCP_COVERAGE_HIGH_IMPACT_TOKENS = 200_000
// Anthropic prices cache writes at 125% of base input and cache reads at
// roughly 10% of base input. We use these to keep overhead estimates honest:
// most MCP schema bytes live in the cached prefix and only get charged at
// the discount rate after the first turn of a session.
const CACHE_WRITE_MULTIPLIER = 1.25
const CACHE_READ_DISCOUNT = 0.10
const GHOST_AGENTS_HIGH_THRESHOLD = 5
const GHOST_AGENTS_MEDIUM_THRESHOLD = 2
const GHOST_SKILLS_HIGH_THRESHOLD = 10
const GHOST_SKILLS_MEDIUM_THRESHOLD = 5
const GHOST_COMMANDS_MEDIUM_THRESHOLD = 10
const MCP_NEW_CONFIG_GRACE_MS = 24 * 60 * 60 * 1000
const BASH_DEFAULT_LIMIT = 30000
const BASH_RECOMMENDED_LIMIT = 15000
const MIN_SESSIONS_FOR_OUTLIER = 3
const SESSION_OUTLIER_MULTIPLIER = 2
const MIN_SESSION_OUTLIER_COST_USD = 1
const SESSION_OUTLIER_PREVIEW = 5
const CONTEXT_BLOAT_MIN_INPUT_TOKENS = 75_000
const CONTEXT_BLOAT_MIN_RATIO = 25
const CONTEXT_BLOAT_TARGET_RATIO = 15
const CONTEXT_BLOAT_PREVIEW = 5
const CONTEXT_BLOAT_LOW_INPUT_TOKENS = 200_000
const CONTEXT_BLOAT_HIGH_INPUT_TOKENS = 500_000
const CONTEXT_BLOAT_LOW_MAX_CANDIDATES = 2
const CONTEXT_BLOAT_HIGH_MIN_CANDIDATES = 10
const CONTEXT_BLOAT_GROWTH_RATIO = 2
const CONTEXT_BLOAT_GROWTH_MAX_GAP_MS = 7 * 24 * 60 * 60 * 1000
const CONTEXT_BLOAT_RATIO_DISPLAY_CAP = 1000
const WORTH_IT_MIN_COST_USD = 2
const WORTH_IT_NO_EDIT_MIN_COST_USD = 3
const WORTH_IT_MIN_RETRIES = 3
const WORTH_IT_RETRY_WITH_EDIT_MIN_RETRIES = 2
const WORTH_IT_PREVIEW = 5
const WORTH_IT_LOW_MAX_CANDIDATES = 2
const WORTH_IT_LOW_MAX_TOTAL_COST_USD = 10
const WORTH_IT_HIGH_MIN_CANDIDATES = 10
const WORTH_IT_HIGH_TOTAL_COST_USD = 50
// ============================================================================
// Scoring constants
// ============================================================================
const HEALTH_WEIGHT_HIGH = 15
const HEALTH_WEIGHT_MEDIUM = 7
const HEALTH_WEIGHT_LOW = 3
const HEALTH_MAX_PENALTY = 80
const GRADE_A_MIN = 90
const GRADE_B_MIN = 75
const GRADE_C_MIN = 55
const GRADE_D_MIN = 30
// Rebalanced so a high-impact finding with zero observed tokens (e.g.
// detectGhostAgents firing on five files but tokensSaved=400) cannot
// outrank a medium-impact finding with many millions of tokens.
// Old: 0.7/0.3 → high+0 = 0.70, medium+1B = 0.65 (high+0 won).
// New: 0.5/0.5 → high+0 = 0.50, medium+1B = 0.75 (medium+1B wins).
// Token normalize lifted to 5M so the rank scales over a realistic range.
const URGENCY_IMPACT_WEIGHT = 0.5
const URGENCY_TOKEN_WEIGHT = 0.5
const URGENCY_TOKEN_NORMALIZE = 5_000_000
// ============================================================================
// File system constants
// ============================================================================
const MAX_IMPORT_DEPTH = 5
const IMPORT_PATTERN = /^@(\.\.?\/[^\s]+|\/[^\s]+)/gm
const COMMAND_PATTERN = /<command-name>([^<]+)<\/command-name>|(?:^|\s)\/([a-zA-Z][\w-]*)/gm
const JUNK_DIRS = [
'node_modules', '.git', 'dist', 'build', '__pycache__', '.next',
'.nuxt', '.output', 'coverage', '.cache', '.tsbuildinfo',
'.venv', 'venv', '.svn', '.hg',
]
const JUNK_PATTERN = new RegExp(`/(?:${JUNK_DIRS.join('|')})/`)
const SHELL_PROFILES = ['.zshrc', '.bashrc', '.bash_profile', '.profile']
const TOP_ITEMS_PREVIEW = 3
const GHOST_NAMES_PREVIEW = 5
const GHOST_CLEANUP_COMMANDS_LIMIT = 10
// ============================================================================
// Types
// ============================================================================
export type Impact = 'high' | 'medium' | 'low'
export type HealthGrade = 'A' | 'B' | 'C' | 'D' | 'F'
/// Where a paste-style suggestion belongs. Without this, users couldn't tell
/// whether a prompt should go into CLAUDE.md (permanent rule), be pasted at
/// the start of a future session (one-time constraint), be asked of Claude
/// in the current chat (one-time prompt), or be added to a shell config file.
/// Issue #277 — users were dropping one-time session openers into CLAUDE.md
/// permanently because the destination wasn't clearly stated.
export type PasteDestination =
| 'claude-md' // permanent project rule, append to CLAUDE.md
| 'session-opener' // one-time paste at the start of a NEW session
| 'prompt' // one-time ask in the current Claude conversation
| 'shell-config' // append to ~/.zshrc / ~/.bashrc
export type WasteAction =
| { type: 'paste'; label: string; text: string; destination?: PasteDestination }
| { type: 'command'; label: string; text: string }
| { type: 'file-content'; label: string; path: string; content: string }
export type Trend = 'active' | 'improving'
export type WasteFinding = {
title: string
explanation: string
impact: Impact
tokensSaved: number
fix: WasteAction
trend?: Trend
}
export type OptimizeResult = {
findings: WasteFinding[]
costRate: number
healthScore: number
healthGrade: HealthGrade
}
export type ToolCall = {
name: string
input: Record<string, unknown>
sessionId: string
project: string
recent?: boolean
}
export type ApiCallMeta = {
cacheCreationTokens: number
version: string
recent?: boolean
}
type ScanData = {
toolCalls: ToolCall[]
projectCwds: Set<string>
apiCalls: ApiCallMeta[]
userMessages: string[]
}
// ============================================================================
// JSONL scanner
// ============================================================================
const FILE_READ_CONCURRENCY = 16
const RESULT_CACHE_TTL_MS = 60_000
const RECENT_WINDOW_HOURS = 48
const RECENT_WINDOW_MS = RECENT_WINDOW_HOURS * 60 * 60 * 1000
const DEFAULT_TREND_PERIOD_DAYS = 30
const DEFAULT_TREND_PERIOD_MS = DEFAULT_TREND_PERIOD_DAYS * 24 * 60 * 60 * 1000
const IMPROVING_THRESHOLD = 0.5
async function collectJsonlFiles(dirPath: string): Promise<string[]> {
const files = await readdir(dirPath).catch(() => [])
const result = files.filter(f => f.endsWith('.jsonl')).map(f => join(dirPath, f))
for (const entry of files) {
if (entry.endsWith('.jsonl')) continue
const subPath = join(dirPath, entry, 'subagents')
const subFiles = await readdir(subPath).catch(() => [])
for (const sf of subFiles) {
if (sf.endsWith('.jsonl')) result.push(join(subPath, sf))
}
}
return result
}
async function isFileStaleForRange(filePath: string, range: DateRange | undefined): Promise<boolean> {
if (!range) return false
try {
const s = await stat(filePath)
return s.mtimeMs < range.start.getTime()
} catch { return false }
}
async function runWithConcurrency<T>(
items: T[],
limit: number,
worker: (item: T) => Promise<void>,
): Promise<void> {
let idx = 0
async function next(): Promise<void> {
while (idx < items.length) {
const current = idx++
await worker(items[current])
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => next()))
}
type ScanFileResult = {
calls: ToolCall[]
cwds: string[]
apiCalls: ApiCallMeta[]
userMessages: string[]
}
function inRange(timestamp: string | undefined, range: DateRange | undefined): boolean {
if (!range) return true
if (!timestamp) return false
const ts = new Date(timestamp)
return ts >= range.start && ts <= range.end
}
function isRecent(timestamp: string | undefined, cutoff: number): boolean {
if (!timestamp) return false
return new Date(timestamp).getTime() >= cutoff
}
export async function scanJsonlFile(
filePath: string,
project: string,
dateRange: DateRange | undefined,
recentCutoffMs = Date.now() - RECENT_WINDOW_MS,
): Promise<ScanFileResult> {
const calls: ToolCall[] = []
const cwds: string[] = []
const apiCalls: ApiCallMeta[] = []
const userMessages: string[] = []
const sessionId = basename(filePath, '.jsonl')
let lastVersion = ''
for await (const line of readSessionLines(filePath)) {
if (!line.trim()) continue
let entry: Record<string, unknown>
try { entry = JSON.parse(line) } catch { continue }
if (entry.version && typeof entry.version === 'string') lastVersion = entry.version
const ts = typeof entry.timestamp === 'string' ? entry.timestamp : undefined
const withinRange = inRange(ts, dateRange)
const recent = isRecent(ts, recentCutoffMs)
if (entry.cwd && typeof entry.cwd === 'string' && withinRange) cwds.push(entry.cwd)
if (entry.type === 'user') {
if (!withinRange) continue
const msg = entry.message as Record<string, unknown> | undefined
const msgContent = msg?.content
if (typeof msgContent === 'string') {
userMessages.push(msgContent)
} else if (Array.isArray(msgContent)) {
for (const block of msgContent) {
if (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
userMessages.push(block.text)
}
}
}
continue
}
if (entry.type !== 'assistant') continue
if (!withinRange) continue
const msg = entry.message as Record<string, unknown> | undefined
const usage = msg?.usage as Record<string, unknown> | undefined
if (usage) {
const cacheCreate = (usage.cache_creation_input_tokens as number) ?? 0
if (cacheCreate > 0) apiCalls.push({ cacheCreationTokens: cacheCreate, version: lastVersion, recent })
}
const blocks = msg?.content
if (!Array.isArray(blocks)) continue
for (const block of blocks) {
if (block.type !== 'tool_use') continue
calls.push({
name: block.name as string,
input: (block.input as Record<string, unknown>) ?? {},
sessionId,
project,
recent,
})
}
}
return { calls, cwds, apiCalls, userMessages }
}
async function scanSessions(dateRange?: DateRange): Promise<ScanData> {
const sources = await discoverAllSessions('claude')
const allCalls: ToolCall[] = []
const allCwds = new Set<string>()
const allApiCalls: ApiCallMeta[] = []
const allUserMessages: string[] = []
const tasks: Array<{ file: string; project: string }> = []
for (const source of sources) {
const files = await collectJsonlFiles(source.path)
for (const file of files) {
if (await isFileStaleForRange(file, dateRange)) continue
tasks.push({ file, project: source.project })
}
}
await runWithConcurrency(tasks, FILE_READ_CONCURRENCY, async ({ file, project }) => {
const { calls, cwds, apiCalls, userMessages } = await scanJsonlFile(file, project, dateRange)
allCalls.push(...calls)
for (const cwd of cwds) allCwds.add(cwd)
allApiCalls.push(...apiCalls)
allUserMessages.push(...userMessages)
})
return { toolCalls: allCalls, projectCwds: allCwds, apiCalls: allApiCalls, userMessages: allUserMessages }
}
// ============================================================================
// Shared helpers
// ============================================================================
function readJsonFile(path: string): Record<string, unknown> | null {
const raw = readSessionFileSync(path)
if (raw === null) return null
try { return JSON.parse(raw) } catch { return null }
}
function shortHomePath(absPath: string): string {
const home = homedir()
return absPath.startsWith(home) ? '~' + absPath.slice(home.length) : absPath
}
function isReadTool(name: string): boolean {
return name === 'Read' || name === 'FileReadTool'
}
type McpConfigEntry = { normalized: string; original: string; mtime: number }
export function loadMcpConfigs(projectCwds: Iterable<string>): Map<string, McpConfigEntry> {
const servers = new Map<string, McpConfigEntry>()
const configPaths = [
join(homedir(), '.claude', 'settings.json'),
join(homedir(), '.claude', 'settings.local.json'),
]
for (const cwd of projectCwds) {
configPaths.push(join(cwd, '.mcp.json'))
configPaths.push(join(cwd, '.claude', 'settings.json'))
configPaths.push(join(cwd, '.claude', 'settings.local.json'))
}
for (const p of configPaths) {
if (!existsSync(p)) continue
const config = readJsonFile(p)
if (!config) continue
let mtime = 0
try { mtime = statSync(p).mtimeMs } catch {}
const serversObj = (config.mcpServers ?? {}) as Record<string, unknown>
for (const name of Object.keys(serversObj)) {
const normalized = name.replace(/:/g, '_')
const existing = servers.get(normalized)
if (!existing || existing.mtime < mtime) {
servers.set(normalized, { normalized, original: name, mtime })
}
}
}
return servers
}
// ============================================================================
// Detectors
// ============================================================================
export function detectJunkReads(calls: ToolCall[], dateRange?: DateRange): WasteFinding | null {
const dirCounts = new Map<string, number>()
let totalJunkReads = 0
let recentJunkReads = 0
for (const call of calls) {
if (!isReadTool(call.name)) continue
const filePath = call.input.file_path as string | undefined
if (!filePath || !JUNK_PATTERN.test(filePath)) continue
totalJunkReads++
if (call.recent) recentJunkReads++
for (const dir of JUNK_DIRS) {
if (filePath.includes(`/${dir}/`)) {
dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + 1)
break
}
}
}
if (totalJunkReads < MIN_JUNK_READS_TO_FLAG) return null
const hasRecentActivity = calls.some(c => c.recent)
const trend = sessionTrend(recentJunkReads, totalJunkReads, dateRange, hasRecentActivity)
if (trend === 'resolved') return null
const sorted = [...dirCounts.entries()].sort((a, b) => b[1] - a[1])
const dirList = sorted.slice(0, TOP_ITEMS_PREVIEW).map(([d, n]) => `${d}/ (${n}x)`).join(', ')
const tokensSaved = totalJunkReads * AVG_TOKENS_PER_READ
const detected = sorted.map(([d]) => d)
const commonDefaults = ['node_modules', '.git', 'dist', '__pycache__']
const extras = commonDefaults.filter(d => !dirCounts.has(d)).slice(0, Math.max(0, 6 - detected.length))
const dirsToAvoid = [...detected, ...extras].join(', ')
return {
title: 'Claude is reading build/dependency folders',
explanation: `Claude read into ${dirList} (${totalJunkReads} reads). These are generated or dependency directories, not your code. Tell Claude in CLAUDE.md to avoid them.`,
impact: totalJunkReads > JUNK_READS_HIGH_THRESHOLD ? 'high' : totalJunkReads > JUNK_READS_MEDIUM_THRESHOLD ? 'medium' : 'low',
tokensSaved,
fix: {
type: 'paste',
destination: 'claude-md',
label: 'Append to your project CLAUDE.md:',
text: `Do not read or search files under these directories unless I explicitly ask: ${dirsToAvoid}.`,
},
trend,
}
}
export function detectDuplicateReads(calls: ToolCall[], dateRange?: DateRange): WasteFinding | null {
const sessionFiles = new Map<string, Map<string, { count: number; recent: number }>>()
for (const call of calls) {
if (!isReadTool(call.name)) continue
const filePath = call.input.file_path as string | undefined
if (!filePath || JUNK_PATTERN.test(filePath)) continue
const key = `${call.project}:${call.sessionId}`
if (!sessionFiles.has(key)) sessionFiles.set(key, new Map())
const fm = sessionFiles.get(key)!
const entry = fm.get(filePath) ?? { count: 0, recent: 0 }
entry.count++
if (call.recent) entry.recent++
fm.set(filePath, entry)
}
let totalDuplicates = 0
let recentDuplicates = 0
const fileDupes = new Map<string, number>()
for (const fm of sessionFiles.values()) {
for (const [file, entry] of fm) {
if (entry.count <= 1) continue
const extra = entry.count - 1
totalDuplicates += extra
if (entry.recent > 1) recentDuplicates += entry.recent - 1
const name = basename(file)
fileDupes.set(name, (fileDupes.get(name) ?? 0) + extra)
}
}
if (totalDuplicates < MIN_DUPLICATE_READS_TO_FLAG) return null
const hasRecentActivity = calls.some(c => c.recent)
const trend = sessionTrend(recentDuplicates, totalDuplicates, dateRange, hasRecentActivity)
if (trend === 'resolved') return null
const worst = [...fileDupes.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, TOP_ITEMS_PREVIEW)
.map(([name, n]) => `${name} (${n + 1}x)`)
.join(', ')
const tokensSaved = totalDuplicates * AVG_TOKENS_PER_READ
return {
title: 'Claude is re-reading the same files',
explanation: `${totalDuplicates} redundant re-reads across sessions. Top repeats: ${worst}. Each re-read loads the same content into context again.`,
impact: totalDuplicates > DUPLICATE_READS_HIGH_THRESHOLD ? 'high' : totalDuplicates > DUPLICATE_READS_MEDIUM_THRESHOLD ? 'medium' : 'low',
tokensSaved,
fix: {
type: 'paste',
destination: 'prompt',
label: 'Point Claude at exact locations in your prompt, for example:',
text: 'In <file> lines <start>-<end>, look at the <function> function.',
},
trend,
}
}
/**
* Per-server breakdown of MCP tool inventory vs invocations, computed from the
* `mcpInventory` field captured by the Claude parser.
*
* Each session that loaded a server contributes its observed tool list to
* the union for that server. Invocations come from the existing
* `mcpBreakdown` per-call counts plus the parser's `call.tools` stream.
*/
export type McpServerCoverage = {
server: string
toolsAvailable: number
toolsInvoked: number
unusedTools: string[]
invocations: number
loadedSessions: number
coverageRatio: number
}
type McpSchemaCostEstimate = {
cacheWriteTokens: number
cacheReadTokens: number
effectiveInputTokens: number
}
/**
* Aggregate MCP inventory and invocations across the projects in scope.
*
* Returns one entry per `mcp__<server>__*` namespace observed in any
* session's `mcpInventory`. Counts of invocations come from
* `session.mcpBreakdown` (per-server call totals already maintained by the
* parser).
*/
export function aggregateMcpCoverage(projects: ProjectSummary[]): McpServerCoverage[] {
type ServerAcc = {
inventory: Set<string>
invokedTools: Set<string>
invocations: number
loadedSessions: number
}
const servers = new Map<string, ServerAcc>()
function getOrInit(server: string): ServerAcc {
let acc = servers.get(server)
if (!acc) {
acc = { inventory: new Set(), invokedTools: new Set(), invocations: 0, loadedSessions: 0 }
servers.set(server, acc)
}
return acc
}
for (const project of projects) {
for (const session of project.sessions) {
// Only sessions with an observed inventory count toward `loadedSessions`.
// Pure invocation-only sessions (server seen via `call.mcpTools` or
// `session.mcpBreakdown` without any matching `deferred_tools_delta`)
// could otherwise satisfy the `MCP_COVERAGE_MIN_SESSIONS` threshold
// without giving us evidence that the schema was actually loaded.
const inventoriedServers = new Set<string>()
const sessionInvoked = new Map<string, Set<string>>()
// Inventory: union of tools observed available in this session.
for (const fqn of session.mcpInventory ?? []) {
const parts = fqn.split('__')
if (parts.length < 3 || parts[0] !== 'mcp') continue
const server = parts[1]
if (!server) continue
const tool = parts.slice(2).join('__')
if (!tool) continue
const acc = getOrInit(server)
acc.inventory.add(fqn)
inventoriedServers.add(server)
}
// Invoked tools: walk turns to collect per-tool invocations. We can't
// get this from session.mcpBreakdown alone because that's keyed by
// server, not tool.
for (const turn of session.turns) {
for (const call of turn.assistantCalls) {
for (const fqn of call.mcpTools) {
const parts = fqn.split('__')
if (parts.length < 3 || parts[0] !== 'mcp') continue
const server = parts[1]
if (!server) continue
let invoked = sessionInvoked.get(server)
if (!invoked) {
invoked = new Set()
sessionInvoked.set(server, invoked)
}
invoked.add(fqn)
}
}
}
// Invocation totals: trust mcpBreakdown which was already aggregated
// turn-by-turn, including any invocations the inventory pass missed.
for (const [server, data] of Object.entries(session.mcpBreakdown)) {
const acc = getOrInit(server)
acc.invocations += data.calls
}
for (const [server, invoked] of sessionInvoked) {
const acc = getOrInit(server)
for (const fqn of invoked) acc.invokedTools.add(fqn)
}
for (const server of inventoriedServers) {
getOrInit(server).loadedSessions += 1
}
}
}
const result: McpServerCoverage[] = []
for (const [server, acc] of servers) {
if (acc.inventory.size === 0) continue
// Coverage is only meaningful against tools we actually observed in the
// inventory: invocations of tools never inventoried (older config, typo,
// etc.) would otherwise inflate the numerator and could even drive
// `unusedCount` negative.
const invokedInInventory = new Set<string>()
for (const fqn of acc.invokedTools) {
if (acc.inventory.has(fqn)) invokedInInventory.add(fqn)
}
const unusedTools = Array.from(acc.inventory).filter(t => !invokedInInventory.has(t)).sort()
const toolsInvoked = acc.inventory.size - unusedTools.length
result.push({
server,
toolsAvailable: acc.inventory.size,
toolsInvoked,
unusedTools,
invocations: acc.invocations,
loadedSessions: acc.loadedSessions,
coverageRatio: acc.inventory.size === 0 ? 0 : toolsInvoked / acc.inventory.size,
})
}
result.sort((a, b) => b.toolsAvailable - a.toolsAvailable)
return result
}
/**
* Cache-aware token cost estimate for the unused-tool overhead of one or
* more servers, summed across all sessions that loaded any of them.
*
* Returns three buckets:
* - `cacheWriteTokens`: schema bytes paid at full input price (each
* cache-creation event in a session that loaded one of the servers).
* - `cacheReadTokens`: schema bytes carried at the cache-read discount on
* subsequent turns (ongoing overhead).
* - `effectiveInputTokens`: equivalent fresh-input tokens, weighted by
* cache pricing. Used to estimate dollar cost downstream by multiplying
* by the project's input rate.
*
* We cap each call's contribution at the observed cache-creation /
* cache-read totals for that call: it is not meaningful to claim more MCP
* overhead than the call's own cache bucket could possibly contain. The
* cap is applied once across the combined unused-schema budget for all
* flagged servers, not per server, so two flagged servers cannot both
* independently claim the same call's cache bucket.
*
* Anthropic caches expire after roughly 5 minutes of inactivity, so a long
* session can rebuild the cache multiple times. Every call that reports
* `cacheCreationInputTokens > 0` is treated as another rebuild, not just
* the very first one.
*
* "Loaded" is defined exclusively by observed inventory: a session that
* invoked a server without ever emitting a `deferred_tools_delta` for it
* does not count, matching the invariant `aggregateMcpCoverage` uses for
* `loadedSessions`.
*/
export function estimateMcpSchemaCost(
unusedToolCount: number,
projects: ProjectSummary[],
server: string,
): McpSchemaCostEstimate
export function estimateMcpSchemaCost(
unusedToolCountsByServer: Record<string, number>,
projects: ProjectSummary[],
servers: string[],
): McpSchemaCostEstimate
export function estimateMcpSchemaCost(
unusedToolCounts: Record<string, number> | number,
projects: ProjectSummary[],
serverOrServers: string | string[],
): McpSchemaCostEstimate {
let servers: string[]
let counts: Record<string, number>
if (typeof unusedToolCounts === 'number') {
if (typeof serverOrServers !== 'string') {
throw new TypeError('single-server MCP cost estimates require a string server name')
}
servers = [serverOrServers]
counts = { [serverOrServers]: unusedToolCounts }
} else {
if (!Array.isArray(serverOrServers)) {
throw new TypeError('multi-server MCP cost estimates require a string[] server list')
}
servers = serverOrServers
counts = unusedToolCounts
}
const totalUnusedSchemaTokens = servers.reduce(
(s, srv) => s + (counts[srv] ?? 0) * TOKENS_PER_MCP_TOOL,
0,
)
if (totalUnusedSchemaTokens === 0) {
return { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0 }
}
const serverSet = new Set(servers)
let cacheWriteTokens = 0
let cacheReadTokens = 0
for (const project of projects) {
for (const session of project.sessions) {
// A session counts only if its observed inventory included at least
// one of the flagged servers — same invariant `aggregateMcpCoverage`
// uses for `loadedSessions`.
let loaded = false
for (const fqn of session.mcpInventory ?? []) {
const seg = fqn.split('__')[1]
if (seg && serverSet.has(seg)) { loaded = true; break }
}
if (!loaded) continue
for (const turn of session.turns) {
for (const call of turn.assistantCalls) {
// Both buckets can be non-zero on the same call (cache rebuild
// alongside a partial read), so account for them independently.
// The cap is applied to the combined unused-schema budget so
// multiple flagged servers cannot all claim the same call.
if (call.usage.cacheCreationInputTokens > 0) {
cacheWriteTokens += Math.min(totalUnusedSchemaTokens, call.usage.cacheCreationInputTokens)
}
if (call.usage.cacheReadInputTokens > 0) {
cacheReadTokens += Math.min(totalUnusedSchemaTokens, call.usage.cacheReadInputTokens)
}
}
}
}
}
const effectiveInputTokens = cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT
return { cacheWriteTokens, cacheReadTokens, effectiveInputTokens }
}
/**
* Find MCP servers whose tool inventory is largely unused. Replaces the
* older server-only `detectUnusedMcp` (which only flagged servers with
* literal zero invocations).
*
* A server is flagged when, taken together:
* - it exposed more than `MCP_COVERAGE_MIN_TOOLS` tools,
* - we saw it loaded in at least `MCP_COVERAGE_MIN_SESSIONS` sessions,
* - the coverage ratio is below `MCP_COVERAGE_LOW_THRESHOLD`.
*
* Token-savings estimates use the cache-aware accounting from
* `estimateMcpSchemaCost` so we don't mistake cached-prefix carry-over for
* fresh-input billing.
*/
export function detectMcpToolCoverage(
projects: ProjectSummary[],
coverage = aggregateMcpCoverage(projects),
): WasteFinding | null {
if (coverage.length === 0) return null
const flagged = coverage.filter(c =>
c.toolsAvailable > MCP_COVERAGE_MIN_TOOLS
&& c.loadedSessions >= MCP_COVERAGE_MIN_SESSIONS
&& c.coverageRatio < MCP_COVERAGE_LOW_THRESHOLD,
)
if (flagged.length === 0) return null
flagged.sort((a, b) => (b.toolsAvailable - b.toolsInvoked) - (a.toolsAvailable - a.toolsInvoked))
const lines: string[] = []
const removeCommands: string[] = []
const unusedCountsByServer: Record<string, number> = {}
const flaggedServers: string[] = []
for (const c of flagged) {
unusedCountsByServer[c.server] = c.toolsAvailable - c.toolsInvoked
flaggedServers.push(c.server)
const pct = Math.round(c.coverageRatio * 100)
lines.push(
`${c.server}: ${c.toolsInvoked}/${c.toolsAvailable} tools used (${pct}% coverage) across ${c.loadedSessions} session${c.loadedSessions === 1 ? '' : 's'}`,
)
removeCommands.push(`claude mcp remove '${c.server}'`)
}
// Single combined cost pass: caps each call's contribution at the
// total unused-schema budget across all flagged servers, so two
// flagged servers cannot independently claim the same call's cache
// bucket and overstate `tokensSaved`.
const cost = estimateMcpSchemaCost(unusedCountsByServer, projects, flaggedServers)
const tokensSaved = Math.round(cost.effectiveInputTokens)
const impact: Impact = tokensSaved >= MCP_COVERAGE_HIGH_IMPACT_TOKENS
? 'high'
: flagged.length >= UNUSED_MCP_HIGH_THRESHOLD
? 'high'
: 'medium'
return {
title: `${flagged.length} MCP server${flagged.length === 1 ? '' : 's'} with low tool coverage`,
explanation:
`Schema for unused tools is loaded into the system prompt every session and ` +
`carried in the cached prefix on every turn. ` +
`${lines.join('; ')}.`,
impact,
tokensSaved,
fix: {
type: 'command',
label: flagged.length === 1
? 'Remove the underused server, or trim its tools in your MCP config:'
: 'Remove underused servers, or trim their tools in your MCP config:',
text: removeCommands.join('\n'),
},
}
}
export function detectUnusedMcp(
calls: ToolCall[],
projects: ProjectSummary[],
projectCwds: Set<string>,
mcpCoverage = aggregateMcpCoverage(projects),
): WasteFinding | null {
const configured = loadMcpConfigs(projectCwds)
if (configured.size === 0) return null
const calledServers = new Set<string>()
for (const call of calls) {
if (!call.name.startsWith('mcp__')) continue
const seg = call.name.split('__')[1]
if (seg) calledServers.add(seg)
}
for (const p of projects) {
for (const s of p.sessions) {
for (const server of Object.keys(s.mcpBreakdown)) calledServers.add(server)
}
}
// Servers that the new coverage detector will flag fall under its
// jurisdiction (per-tool granularity, cache-aware costing) and we
// suppress them here to avoid double-flagging. Importantly, we suppress
// only the servers that actually clear the coverage detector's
// thresholds — a small, inventoried-but-uninvoked server that the
// coverage detector skips would otherwise become a blind spot.
const coverageReportedServers = new Set(
mcpCoverage
.filter(c =>
c.toolsAvailable > MCP_COVERAGE_MIN_TOOLS
&& c.loadedSessions >= MCP_COVERAGE_MIN_SESSIONS
&& c.coverageRatio < MCP_COVERAGE_LOW_THRESHOLD,
)
.map(c => c.server),
)
const now = Date.now()
const unused: string[] = []
for (const entry of configured.values()) {
if (calledServers.has(entry.normalized)) continue
if (coverageReportedServers.has(entry.normalized)) continue
if (entry.mtime > 0 && now - entry.mtime < MCP_NEW_CONFIG_GRACE_MS) continue
unused.push(entry.original)
}
if (unused.length === 0) return null
const totalSessions = projects.reduce((s, p) => s + p.sessions.length, 0)
const schemaTokensPerSession = unused.length * TOOLS_PER_MCP_SERVER * TOKENS_PER_MCP_TOOL
const tokensSaved = schemaTokensPerSession * Math.max(totalSessions, 1)
return {
title: `${unused.length} MCP server${unused.length > 1 ? 's' : ''} configured but never used`,
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.`,
impact: unused.length >= UNUSED_MCP_HIGH_THRESHOLD ? 'high' : 'medium',
tokensSaved,
fix: {
type: 'command',
label: `Remove unused server${unused.length > 1 ? 's' : ''}:`,
text: unused.map(s => `claude mcp remove ${s}`).join('\n'),
},
}
}
function expandImports(filePath: string, seen: Set<string>, depth: number): { totalLines: number; importedFiles: number } {
if (depth > MAX_IMPORT_DEPTH || seen.has(filePath)) return { totalLines: 0, importedFiles: 0 }
seen.add(filePath)
const content = readSessionFileSync(filePath)
if (content === null) return { totalLines: 0, importedFiles: 0 }
let totalLines = content.split('\n').length
let importedFiles = 0
const dir = join(filePath, '..')
IMPORT_PATTERN.lastIndex = 0
for (const match of content.matchAll(IMPORT_PATTERN)) {
const rawPath = match[1]
if (!rawPath) continue
const resolved = rawPath.startsWith('/') ? rawPath : join(dir, rawPath)
if (!existsSync(resolved)) continue
const nested = expandImports(resolved, seen, depth + 1)
totalLines += nested.totalLines
importedFiles += 1 + nested.importedFiles
}
return { totalLines, importedFiles }
}
export function detectBloatedClaudeMd(projectCwds: Set<string>): WasteFinding | null {
const bloated: { path: string; expandedLines: number; imports: number }[] = []
for (const cwd of projectCwds) {
for (const name of ['CLAUDE.md', '.claude/CLAUDE.md']) {
const fullPath = join(cwd, name)
if (!existsSync(fullPath)) continue
const { totalLines, importedFiles } = expandImports(fullPath, new Set(), 0)
if (totalLines > CLAUDEMD_HEALTHY_LINES) {
bloated.push({ path: `${shortHomePath(cwd)}/${name}`, expandedLines: totalLines, imports: importedFiles })
}
}
}
if (bloated.length === 0) return null
const sorted = bloated.sort((a, b) => b.expandedLines - a.expandedLines)
const worst = sorted[0]
const totalExtraLines = sorted.reduce((s, b) => s + (b.expandedLines - CLAUDEMD_HEALTHY_LINES), 0)
const tokensSaved = totalExtraLines * CLAUDEMD_TOKENS_PER_LINE
const list = sorted.slice(0, TOP_ITEMS_PREVIEW).map(b => {
const importNote = b.imports > 0 ? ` with ${b.imports} @-import${b.imports > 1 ? 's' : ''}` : ''
return `${b.path} (${b.expandedLines} lines${importNote})`
}).join(', ')
return {
title: `Your CLAUDE.md is too long`,
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.`,
impact: worst.expandedLines > CLAUDEMD_HIGH_THRESHOLD_LINES ? 'high' : 'medium',
tokensSaved,
fix: {
type: 'paste',
destination: 'prompt',
label: 'Ask Claude in the current session to trim it:',
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.`,
},
}
}
const READ_TOOL_NAMES = new Set(['Read', 'Grep', 'Glob', 'FileReadTool', 'GrepTool', 'GlobTool'])
const EDIT_TOOL_NAMES = new Set(['Edit', 'Write', 'FileEditTool', 'FileWriteTool', 'NotebookEdit'])
export function detectLowReadEditRatio(calls: ToolCall[]): WasteFinding | null {
let reads = 0
let edits = 0
let recentEdits = 0
let recentReads = 0
for (const call of calls) {
if (READ_TOOL_NAMES.has(call.name)) {
reads++
if (call.recent) recentReads++
} else if (EDIT_TOOL_NAMES.has(call.name)) {
edits++
if (call.recent) recentEdits++
}
}