deadweight 0.2.0

Find the dead weight in your Claude Code setup: what every request carries before you type, and what you never use.
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
//! Human-readable terminal report.

use anstream::println;
use anstyle::{AnsiColor, Style};

use crate::analyze::{Analysis, Kind, Source};
use crate::fix::Plan;
use crate::util::{bar, fmt_tokens, plural, short_time};

const BOLD: Style = Style::new().bold();
const DIM: Style = Style::new().dimmed();
const RED: Style = AnsiColor::Red.on_default().bold();
const YELLOW: Style = AnsiColor::Yellow.on_default().bold();
const GREEN: Style = AnsiColor::Green.on_default().bold();
const CYAN: Style = AnsiColor::Cyan.on_default();

fn paint(style: Style, text: impl std::fmt::Display) -> String {
    format!("{style}{text}{style:#}")
}

pub fn print(a: &Analysis, plan: &Plan, show_all: bool) {
    println!();
    println!(
        "  {}  {}",
        paint(BOLD, "deadweight"),
        paint(DIM, "what your Claude Code setup costs on every request")
    );
    let when = a
        .session_started
        .as_deref()
        .map(short_time)
        .unwrap_or_else(|| "unknown time".into());
    println!(
        "  {}",
        paint(
            DIM,
            format!(
                "latest session {when} · {} {} in the last {} days",
                a.sessions,
                plural(a.sessions, "session", "sessions"),
                a.window_days
            )
        )
    );
    println!();

    headline(a);
    categories(a);
    sources(a, show_all);
    problems(a);
    footer(a, plan);
}

fn headline(a: &Analysis) {
    match a.measured_tokens {
        Some(m) => {
            println!(
                "  Before you type a word, every request carries {}",
                paint(RED, format!("{} tokens", fmt_tokens(m as f64)))
            );
            let mut note = "measured from your latest session".to_string();
            if let Some(med) = a.median_tokens {
                note.push_str(&format!(
                    "; median of recent sessions {}",
                    fmt_tokens(med as f64)
                ));
            }
            println!("  {}", paint(DIM, note));
        }
        None => println!(
            "  Your setup adds about {} tokens to every request",
            paint(RED, fmt_tokens(a.setup_tokens))
        ),
    }
    let builtin = match a.builtin_tools {
        Some(n) => format!("Claude Code itself (system prompt + {n} tools)"),
        None => "Claude Code itself".to_string(),
    };
    println!(
        "  {} from your setup · ~{} from {builtin}",
        paint(BOLD, format!("~{}", fmt_tokens(a.setup_tokens))),
        fmt_tokens(a.builtin_tokens)
    );
    println!();
}

fn categories(a: &Analysis) {
    println!("  {}", paint(BOLD, "WHAT YOUR SETUP ADDS"));
    let max = a.categories.first().map(|c| c.tokens).unwrap_or(0.0);
    for c in &a.categories {
        let label = format!("{} ({})", c.kind.label(), c.count);
        println!(
            "  {:<34} {:>7}  {}",
            label,
            format!("~{}", fmt_tokens(c.tokens)),
            paint(CYAN, bar(c.tokens, max, 24))
        );
    }
    println!();
}

fn sources(a: &Analysis, show_all: bool) {
    let list: Vec<_> = a
        .sources
        .iter()
        .filter(|s| !s.source.is_builtin() && s.tokens >= 1.0)
        .collect();
    let limit = if show_all { list.len() } else { 12 };
    println!("  {}", paint(BOLD, "BIGGEST SOURCES"));
    println!(
        "  {}",
        paint(
            DIM,
            format!(
                "{:<30} {:<13} {:>7}  {:>6}  {}",
                "name", "type", "tokens", "used", "contents"
            )
        )
    );
    for s in list.iter().take(limit) {
        let mut parts = Vec::new();
        if s.hook_tokens >= 1.0 {
            parts.push(format!("hooks {}", fmt_tokens(s.hook_tokens)));
        }
        if s.tools > 0 {
            parts.push(format!("{} {}", s.tools, plural(s.tools, "tool", "tools")));
        }
        if s.skills > 0 {
            parts.push(format!(
                "{} {}",
                s.skills,
                plural(s.skills, "skill", "skills")
            ));
        }
        if s.agents > 0 {
            parts.push(format!(
                "{} {}",
                s.agents,
                plural(s.agents, "agent", "agents")
            ));
        }
        let used = if matches!(s.source, Source::Memory(_)) || s.hook_tokens >= s.tokens {
            paint(DIM, format!("{:>6}", "n/a"))
        } else if s.uses == 0 {
            paint(RED, format!("{:>6}", "never"))
        } else {
            paint(GREEN, format!("{:>6}", format!("{}×", s.uses)))
        };
        println!(
            "  {:<30} {:<13} {:>7}  {}  {}",
            truncate(&s.label, 30),
            s.source.kind_label(),
            format!("~{}", fmt_tokens(s.tokens)),
            used,
            paint(DIM, parts.join(" · "))
        );
    }
    if list.len() > limit {
        println!(
            "  {}",
            paint(DIM, format!("… {} more (use --all)", list.len() - limit))
        );
    }
    println!();
}

fn problems(a: &Analysis) {
    let mut lines: Vec<String> = Vec::new();
    let bare = a.skills_without_description.len();
    if bare > 0 {
        lines.push(format!(
            "{} {} of {} skills are listed {}: the skill listing is full",
            paint(RED, "✗"),
            bare,
            a.skills_listed,
            paint(BOLD, "without a description"),
        ));
        lines.push(paint(
            DIM,
            format!(
                "    (~{} characters). Claude sees only their names, so it can't tell when to use them.",
                fmt_tokens(a.skill_listing_chars as f64)
            ),
        ));
        if !a.used_skills_without_description.is_empty() {
            lines.push(paint(
                DIM,
                format!(
                    "    Including {} you actually use: {}",
                    a.used_skills_without_description.len(),
                    preview(&a.used_skills_without_description, 5)
                ),
            ));
        }
    }
    if !a.failed_mcp.is_empty() {
        lines.push(format!(
            "{} {} MCP {} failed to connect at startup",
            paint(RED, "✗"),
            a.failed_mcp.len(),
            plural(a.failed_mcp.len(), "server", "servers")
        ));
        for f in &a.failed_mcp {
            lines.push(paint(DIM, format!("    {} ({})", f.name, f.code)));
        }
    }
    if !a.unauthenticated.is_empty() {
        let tools: usize = a.unauthenticated.iter().map(|u| u.tools).sum();
        lines.push(format!(
            "{} {} MCP {} never signed in, still listing {} auth-only tools",
            paint(YELLOW, "!"),
            a.unauthenticated.len(),
            plural(a.unauthenticated.len(), "server", "servers"),
            tools
        ));
        let names: Vec<String> = a.unauthenticated.iter().map(|u| u.server.clone()).collect();
        lines.push(paint(DIM, format!("    {}", preview(&names, 6))));
    }
    if !a.duplicates.is_empty() {
        lines.push(format!(
            "{} {} skill {} listed more than once",
            paint(YELLOW, "!"),
            a.duplicates.len(),
            plural(a.duplicates.len(), "name is", "names are")
        ));
        for d in a.duplicates.iter().take(6) {
            lines.push(paint(
                DIM,
                format!("    {}: {}", d.name, d.entries.join(", ")),
            ));
        }
    }
    if a.skills_listed > 0 {
        let unused_tokens: f64 = a
            .items
            .iter()
            .filter(|i| i.kind == Kind::Skill && i.uses == 0 && !i.source.is_builtin())
            .map(|i| i.tokens)
            .sum();
        lines.push(format!(
            "{} {} of {} listed skills were not used in {} days (~{} per request)",
            paint(YELLOW, "!"),
            a.skills_unused,
            a.skills_listed,
            a.window_days,
            fmt_tokens(unused_tokens)
        ));
    }
    for h in a.heavy_skills.iter().take(3) {
        lines.push(format!(
            "{} {} alone costs ~{} tokens per request (used {}× in {} days)",
            paint(YELLOW, "!"),
            paint(BOLD, &h.name),
            fmt_tokens(h.tokens),
            h.uses,
            a.window_days
        ));
    }
    if lines.is_empty() {
        return;
    }
    println!("  {}", paint(BOLD, "PROBLEMS"));
    for l in lines {
        println!("  {l}");
    }
    println!();
}

fn footer(a: &Analysis, plan: &Plan) {
    if a.sessions < 5 {
        println!(
            "  {}",
            paint(
                YELLOW,
                format!(
                    "Only {} {} of history: usage numbers are thin. Come back after a few more sessions.",
                    a.sessions,
                    plural(a.sessions, "session", "sessions")
                )
            )
        );
    }
    if !plan.is_empty() {
        let mut what = Vec::new();
        if !plan.plugins.is_empty() {
            what.push(format!(
                "disable {} unused {}",
                plan.plugins.len(),
                plural(plan.plugins.len(), "plugin", "plugins")
            ));
        }
        if !plan.skills.is_empty() {
            what.push(format!(
                "park {} unused {}",
                plan.skills.len(),
                plural(plan.skills.len(), "skill", "skills")
            ));
        }
        println!(
            "  Run {} to {} and save {} per request.",
            paint(BOLD, "deadweight fix"),
            what.join(" and "),
            paint(GREEN, format!("~{} tokens", fmt_tokens(plan.tokens)))
        );
    }
    if !plan.hooked.is_empty() {
        let t: f64 = plan.hooked.iter().map(|p| p.tokens).sum();
        let names: Vec<String> = plan.hooked.iter().map(|p| p.label.clone()).collect();
        println!(
            "  {}",
            paint(
                DIM,
                format!(
                    "{} more unused {} {} hooks ({}, ~{}); review, or add --include-hooked.",
                    names.len(),
                    plural(names.len(), "plugin", "plugins"),
                    plural(names.len(), "runs", "run"),
                    preview(&names, 4),
                    fmt_tokens(t)
                )
            )
        );
    }
    if !a.manual.is_empty() {
        println!();
        println!("  {}", paint(BOLD, "UNUSED, BUT YOURS TO REMOVE"));
        for m in a.manual.iter().take(6) {
            println!(
                "  {:<34} ~{:<6} {}",
                truncate(&m.what, 34),
                fmt_tokens(m.tokens),
                paint(CYAN, &m.how)
            );
        }
    }
    scope_hints(a);
    println!();
    let basis = if a.measured_tokens.is_some() {
        "The total is measured; the breakdown is estimated from text size."
    } else {
        "Figures are estimated from text size."
    };
    println!("  {}", paint(DIM, basis));
    println!();
}

fn scope_hints(a: &Analysis) {
    if a.scope_hints.is_empty() {
        return;
    }
    println!();
    println!(
        "  {}",
        paint(BOLD, "LOADED IN EVERY PROJECT, USED IN ONE OR TWO")
    );
    for h in a.scope_hints.iter().take(6) {
        let used: Vec<String> = h
            .used_in
            .iter()
            .map(|(p, n)| format!("{n}× in {p}"))
            .collect();
        println!(
            "  {:<34} ~{:<6} {}",
            truncate(&format!("mcp server {}", h.server), 34),
            fmt_tokens(h.tokens),
            paint(
                DIM,
                format!("{} (of {} projects)", used.join(", "), h.projects_total)
            )
        );
        let target = match h.used_in.as_slice() {
            [(p, _)] => format!("projects > \"{p}\" > mcpServers"),
            _ => "each of those projects' mcpServers".to_owned(),
        };
        println!(
            "    {}",
            paint(
                CYAN,
                format!(
                    "in .claude.json, move \"{}\" from the top-level mcpServers into {target}",
                    h.server
                )
            )
        );
    }
}

pub fn print_plan(plan: &Plan) {
    println!();
    if !plan.plugins.is_empty() {
        println!(
            "  {}",
            paint(
                BOLD,
                "Disable these plugins (settings.json → enabledPlugins: false)"
            )
        );
        for p in &plan.plugins {
            println!("    {:<56} ~{}", p.key, fmt_tokens(p.tokens));
        }
    }
    if !plan.skills.is_empty() {
        println!(
            "  {}",
            paint(BOLD, "Move these skills into the backup folder")
        );
        for s in &plan.skills {
            println!("    {:<56} ~{}", s.name, fmt_tokens(s.tokens));
        }
    }
    println!(
        "\n  Saves {} per request. Undo any time with {}.",
        paint(GREEN, format!("~{} tokens", fmt_tokens(plan.tokens))),
        paint(BOLD, "deadweight undo")
    );
}

pub fn success(msg: &str) {
    println!("  {} {msg}", paint(GREEN, "✓"));
}

pub fn note(msg: &str) {
    println!("  {}", paint(DIM, msg));
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_owned()
    } else {
        let mut t: String = s.chars().take(max - 1).collect();
        t.push('…');
        t
    }
}

fn preview(names: &[String], n: usize) -> String {
    let mut s = names.iter().take(n).cloned().collect::<Vec<_>>().join(", ");
    if names.len() > n {
        s.push_str(&format!(", +{} more", names.len() - n));
    }
    s
}