deadweight 0.4.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
//! End-to-end tests against a synthetic Claude Code config directory.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};

use serde_json::{Value, json};

static COUNTER: AtomicUsize = AtomicUsize::new(0);

struct Fixture {
    root: PathBuf,
}

impl Fixture {
    fn new(sessions: usize) -> Self {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let root = std::env::temp_dir().join(format!("deadweight-test-{}-{n}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        let claude = root.join("claude");
        let work = root.join("work");
        fs::create_dir_all(&work).unwrap();

        write(
            &claude.join("settings.json"),
            &json!({
                "theme": "dark",
                "enabledPlugins": { "bloat@mkt": true, "handy@mkt": true, "hooky@mkt": true }
            }),
        );

        let cache = claude.join("plugins").join("cache").join("mkt");
        let mut installed = serde_json::Map::new();
        for name in ["bloat", "handy", "hooky"] {
            let dir = cache.join(name);
            fs::create_dir_all(dir.join(".claude-plugin")).unwrap();
            write(
                &dir.join(".claude-plugin").join("plugin.json"),
                &json!({ "name": name }),
            );
            installed.insert(
                format!("{name}@mkt"),
                json!([{ "scope": "user", "installPath": dir }]),
            );
        }
        write(
            &cache.join("hooky").join("hooks").join("hooks.json"),
            &json!({ "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "hooky-start" } ] } ] } }),
        );
        write(
            &claude.join("plugins").join("installed_plugins.json"),
            &json!({ "version": 2, "plugins": installed }),
        );

        for skill in ["old-skill", "used-skill"] {
            let dir = claude.join("skills").join(skill);
            fs::create_dir_all(&dir).unwrap();
            fs::write(dir.join("SKILL.md"), format!("---\nname: {skill}\n---\n")).unwrap();
        }

        write(
            &claude.join(".claude.json"),
            &json!({ "mcpServers": { "idle-srv": { "command": "x", "env": { "TOKEN": "s3cr3t-value" } } } }),
        );

        let project = claude.join("projects").join("demo");
        fs::create_dir_all(&project).unwrap();
        let start = [
            attachment(json!({
                "type": "hook_success", "hookEvent": "SessionStart",
                "command": "hooky-start", "content": "x".repeat(720), "stdout": ""
            })),
            attachment(json!({
                "type": "deferred_tools_delta",
                "addedNames": ["CronCreate", "mcp__plugin_bloat_api__fetch", "mcp__plugin_bloat_api__push", "mcp__idle-srv__query", "mcp__claude_ai_Gmail__search_threads"],
                "failedMcpServers": [{ "name": "plugin:bloat:broken", "errorCode": "ENOTFOUND", "error": "getaddrinfo ENOTFOUND" }]
            })),
            attachment(json!({
                "type": "skill_listing", "isInitial": true, "skillCount": 5,
                "names": ["bloat:report", "handy:helper", "old-skill", "used-skill", "loop"],
                "content": format!(
                    "- bloat:report: {}\n- handy:helper: helps\n- old-skill: an old skill\n- used-skill\n- loop: built in",
                    "y".repeat(1800)
                )
            })),
            json!({ "type": "assistant", "message": { "role": "assistant", "content": [],
                "usage": { "input_tokens": 3, "cache_creation_input_tokens": 4000, "cache_read_input_tokens": 997 } } }),
        ];
        let usage = [
            tool_use("Skill", json!({ "skill": "handy:helper" })),
            tool_use("Skill", json!({ "skill": "used-skill" })),
        ];
        for i in 0..sessions {
            let mut lines: Vec<String> = start.iter().map(Value::to_string).collect();
            if i == 0 {
                lines.extend(usage.iter().map(Value::to_string));
            }
            fs::write(
                project.join(format!("session-{i}.jsonl")),
                lines.join("\n") + "\n",
            )
            .unwrap();
        }
        Fixture { root }
    }

    fn claude(&self) -> PathBuf {
        self.root.join("claude")
    }

    fn run(&self, args: &[&str]) -> (bool, String) {
        let out = Command::new(env!("CARGO_BIN_EXE_deadweight"))
            .args(args)
            .arg("--config-dir")
            .arg(self.claude())
            .current_dir(self.root.join("work"))
            .env("NO_COLOR", "1")
            .env_remove("CLAUDE_CONFIG_DIR")
            .output()
            .unwrap();
        let text = String::from_utf8_lossy(&out.stdout).to_string()
            + &String::from_utf8_lossy(&out.stderr);
        (out.status.success(), text)
    }

    fn json(&self, args: &[&str]) -> Value {
        let mut all = args.to_vec();
        all.push("--json");
        let (ok, text) = self.run(&all);
        assert!(ok, "deadweight failed: {text}");
        serde_json::from_str(&text).unwrap_or_else(|e| panic!("bad json ({e}): {text}"))
    }

    fn settings(&self) -> Value {
        serde_json::from_str(&fs::read_to_string(self.claude().join("settings.json")).unwrap())
            .unwrap()
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

fn write(path: &Path, v: &Value) {
    fs::create_dir_all(path.parent().unwrap()).unwrap();
    fs::write(path, serde_json::to_string_pretty(v).unwrap()).unwrap();
}

fn attachment(a: Value) -> Value {
    json!({ "type": "attachment", "timestamp": "2026-11-12T10:00:00.000Z", "attachment": a })
}

fn tool_use(name: &str, input: Value) -> Value {
    json!({ "type": "assistant", "message": { "role": "assistant",
        "content": [ { "type": "tool_use", "id": "t", "name": name, "input": input } ] } })
}

fn labels(v: &Value) -> Vec<String> {
    v.as_array()
        .unwrap()
        .iter()
        .map(|p| p["key"].as_str().or(p["name"].as_str()).unwrap().to_owned())
        .collect()
}

#[test]
fn audit_measures_and_attributes() {
    let f = Fixture::new(6);
    let v = f.json(&[]);
    let a = &v["analysis"];
    assert_eq!(a["measured_tokens"], 5000);
    assert_eq!(a["sessions"], 6);
    assert_eq!(a["failed_mcp"][0]["name"], "plugin:bloat:broken");
    assert_eq!(a["skills_without_description"], json!(["used-skill"]));
    assert_eq!(a["skill_budget"]["suggested"], 0.02);
    assert_eq!(a["skill_budget"]["configured"], false);

    let bloat = a["sources"]
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["label"] == "bloat")
        .expect("bloat source");
    assert_eq!(bloat["uses"], 0);
    assert_eq!(bloat["skills"], 1);
    assert_eq!(bloat["tools"], 2);
    // The 1800-character description belongs to bloat, not to the line before.
    assert!(bloat["tokens"].as_f64().unwrap() > 450.0);

    let plan = &v["plan"];
    assert_eq!(labels(&plan["plugins"]), vec!["bloat@mkt"]);
    assert_eq!(labels(&plan["hooked"]), vec!["hooky@mkt"]);
    assert_eq!(labels(&plan["skills"]), vec!["old-skill"]);
    assert_eq!(plan["connectors"]["names"], json!(["claude.ai Gmail"]));
}

#[test]
fn human_report_runs_and_never_prints_secrets() {
    let f = Fixture::new(6);
    let (ok, text) = f.run(&[]);
    assert!(ok, "{text}");
    assert!(text.contains("every request carries 5.0k tokens"), "{text}");
    assert!(text.contains("deadweight fix"), "{text}");
    assert!(!text.contains("s3cr3t-value"));
    let (_, json_text) = f.run(&["--json"]);
    assert!(!json_text.contains("s3cr3t-value"));
}

#[test]
fn fix_then_undo_round_trips() {
    let f = Fixture::new(6);
    let skill = f.claude().join("skills").join("old-skill");

    let v = f.json(&["fix", "--yes"]);
    assert_eq!(v["applied"], true);
    let s = f.settings();
    assert_eq!(s["enabledPlugins"]["bloat@mkt"], false);
    assert_eq!(s["enabledPlugins"]["handy@mkt"], true);
    assert_eq!(s["enabledPlugins"]["hooky@mkt"], true);
    assert_eq!(s["theme"], "dark");
    // Skills are hidden from the model, not moved.
    assert_eq!(
        s["skillOverrides"],
        json!({ "old-skill": "user-invocable-only" })
    );
    assert!(skill.join("SKILL.md").exists());
    assert_eq!(s["disableClaudeAiConnectors"], true);

    let v = f.json(&["undo", "--yes"]);
    assert_eq!(v["restored"], true);
    let s = f.settings();
    assert_eq!(s["enabledPlugins"]["bloat@mkt"], true);
    assert!(s.get("skillOverrides").is_none(), "{s}");
    assert!(s.get("disableClaudeAiConnectors").is_none(), "{s}");
    assert!(skill.join("SKILL.md").exists());

    let v = f.json(&["undo", "--yes"]);
    assert_eq!(v["restored"], false);
}

#[test]
fn fix_respects_keep_and_include_hooked() {
    let f = Fixture::new(6);
    let v = f.json(&["fix", "--dry-run", "--include-hooked", "--keep", "bloat"]);
    assert_eq!(labels(&v["plan"]["plugins"]), vec!["hooky@mkt"]);
    assert_eq!(f.settings()["enabledPlugins"]["bloat@mkt"], true);
}

#[test]
fn fix_refuses_with_too_little_history() {
    let f = Fixture::new(2);
    let (ok, text) = f.run(&["fix", "--yes"]);
    assert!(!ok);
    assert!(text.contains("too little history"), "{text}");
    assert_eq!(f.settings()["enabledPlugins"]["bloat@mkt"], true);
}

#[test]
fn missing_config_dir_is_a_clear_error() {
    let f = Fixture::new(1);
    let out = Command::new(env!("CARGO_BIN_EXE_deadweight"))
        .args(["--config-dir"])
        .arg(f.root.join("nope"))
        .output()
        .unwrap();
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("no Claude Code config found"));
}

/// A session started in `cwd` that makes `calls` calls to the idle-srv MCP server.
fn project_session(f: &Fixture, dir: &str, cwd: &str, calls: usize) {
    let mut lines =
        vec![json!({ "type": "user", "cwd": cwd, "message": { "role": "user", "content": "hi" } })];
    for _ in 0..calls {
        let mut t = tool_use("mcp__idle-srv__query", json!({}));
        t["cwd"] = json!(cwd);
        lines.push(t);
    }
    let text: Vec<String> = lines.iter().map(Value::to_string).collect();
    let project = f.claude().join("projects").join(dir);
    fs::create_dir_all(&project).unwrap();
    fs::write(project.join("s.jsonl"), text.join("\n") + "\n").unwrap();
}

#[test]
fn user_mcp_used_in_one_project_gets_a_scope_hint() {
    let f = Fixture::new(6);
    project_session(&f, "api", r"C:\code\api", 3);
    project_session(&f, "web", "/home/u/web", 0);

    let v = f.json(&[]);
    let hints = &v["analysis"]["scope_hints"];
    assert_eq!(hints.as_array().unwrap().len(), 1, "{hints}");
    assert_eq!(hints[0]["server"], "idle-srv");
    assert_eq!(hints[0]["used_in"], json!([["C:/code/api", 3]]));
    assert_eq!(hints[0]["projects_total"], 2);

    let (ok, text) = f.run(&[]);
    assert!(ok, "{text}");
    assert!(text.contains("USED IN ONE OR TWO"), "{text}");
    assert!(
        text.contains(r#"projects > "C:/code/api" > mcpServers"#),
        "{text}"
    );
    assert!(!text.contains("s3cr3t-value"));
}

#[test]
fn user_mcp_used_everywhere_gets_no_scope_hint() {
    let f = Fixture::new(6);
    project_session(&f, "api", "/home/u/api", 2);
    project_session(&f, "web", "/home/u/web", 1);
    let v = f.json(&[]);
    assert_eq!(v["analysis"]["scope_hints"], json!([]));
}

#[test]
fn park_skills_moves_them_and_undo_brings_them_back() {
    let f = Fixture::new(6);
    let skill = f.claude().join("skills").join("old-skill");
    f.json(&["fix", "--yes", "--park-skills", "--keep", "connectors"]);
    assert!(!skill.exists());
    assert!(f.settings().get("skillOverrides").is_none());
    assert!(f.settings().get("disableClaudeAiConnectors").is_none());
    f.json(&["undo", "--yes"]);
    assert!(skill.join("SKILL.md").exists());
}

#[test]
fn existing_overrides_are_kept_and_restored() {
    let f = Fixture::new(6);
    let mut s = f.settings();
    s["skillOverrides"] = json!({ "some-other": "off" });
    s["disableClaudeAiConnectors"] = json!(false);
    write(&f.claude().join("settings.json"), &s);

    f.json(&["fix", "--yes"]);
    let s = f.settings();
    assert_eq!(s["skillOverrides"]["some-other"], "off");
    assert_eq!(s["skillOverrides"]["old-skill"], "user-invocable-only");
    assert_eq!(s["disableClaudeAiConnectors"], true);

    f.json(&["undo", "--yes"]);
    let s = f.settings();
    assert_eq!(s["skillOverrides"], json!({ "some-other": "off" }));
    assert_eq!(s["disableClaudeAiConnectors"], false);
}

#[test]
fn undo_reads_version_1_manifests() {
    let f = Fixture::new(6);
    let dir = f
        .claude()
        .join("deadweight")
        .join("backups")
        .join("20261112-100000");
    let parked = dir.join("skills").join("old-skill");
    fs::create_dir_all(&parked).unwrap();
    let skill = f.claude().join("skills").join("old-skill");
    fs::rename(&skill, &parked).unwrap();
    write(
        &dir.join("manifest.json"),
        &json!({
            "version": 1, "created": "20261112-100000", "tool_version": "0.2.0",
            "plugins": [{ "key": "bloat@mkt", "previous": true }],
            "skills": [{ "name": "old-skill", "from": skill, "to": parked }],
            "restored": false
        }),
    );
    let mut s = f.settings();
    s["enabledPlugins"]["bloat@mkt"] = json!(false);
    write(&f.claude().join("settings.json"), &s);

    let v = f.json(&["undo", "--yes"]);
    assert_eq!(v["restored"], true);
    assert!(skill.join("SKILL.md").exists());
    assert_eq!(f.settings()["enabledPlugins"]["bloat@mkt"], true);
}

#[test]
fn card_shows_totals_and_no_names() {
    let f = Fixture::new(6);
    let (ok, text) = f.run(&["card"]);
    assert!(ok, "{text}");
    let png = fs::read(f.root.join("work").join("deadweight-card.png")).unwrap();
    assert_eq!(&png[1..4], b"PNG");

    let v = f.json(&["card", "--output", "card.svg"]);
    assert_eq!(v["card"]["measured"], 5000.0);
    let svg = fs::read_to_string(f.root.join("work").join("card.svg")).unwrap();
    assert!(svg.starts_with("<svg"));
    assert!(svg.contains("5.0k"));
    for name in [
        "bloat",
        "handy",
        "hooky",
        "old-skill",
        "used-skill",
        "idle-srv",
        "Gmail",
    ] {
        assert!(!svg.contains(name), "card leaks {name}");
    }
}