lysosome 0.5.1

Find and safely reclaim the disk your dev tools and coding agents leave behind
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
//! `lysosome mcp`: a Model Context Protocol server on stdin/stdout.
//!
//! Newline-delimited JSON-RPC 2.0. Every tool call is turned into the
//! arguments of the matching command and runs the same code as
//! `lysosome <command> --json`, so results follow the versioned JSON
//! contract in `schema/`. `clean` is a dry run unless the call confirms
//! exact item ids; `--permanent` and `--interactive` are not reachable.
//! Only protocol goes to stdout.

use std::ffi::OsString;
use std::io::{BufRead, Write};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::Path;
use std::process::ExitCode;
use std::sync::atomic::Ordering;
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, Instant};

use clap::{Args, Parser};
use serde_json::{json, Map, Value};

use crate::{caches, clean, errors, scan, worktrees, Cli, Command};

/// Newest first; an unknown client version gets the newest.
const PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];

const INSTRUCTIONS: &str = "\
lysosome finds disk that dev tools and coding agents leave behind (dormant git \
worktrees, git-ignored build output of idle projects, package caches, AI models, \
Docker, Xcode) and labels every item by safety tier. scan, worktrees and caches \
are read-only. clean is a dry run unless you pass confirm: true together with the \
exact item ids (from a scan or a clean dry run) in only, or with the plan token a \
clean dry run returns (plan_token) in plan, which cleans exactly that dry run's items. \
For a quick overview pass summary: true to scan or worktrees (totals plus the top items). \
A confirmed clean that takes longer than about 90 seconds keeps running in the background \
and returns {\"status\": \"running\", \"job\": ...}: call clean_status with that job until \
it returns the result. Files go to the Trash, \
which frees no disk until it is emptied: a clean result's summary.trashed_bytes \
says how much is still there, so tell the user to empty the Trash (`lysosome clean \
--empty-own-trash --yes` in a terminal deletes only what lysosome put there). Every item is re-checked right before acting, and REVIEW items are never cleaned. \
Pass roots to keep scans fast; without roots the whole home folder is walked.";

#[derive(Debug, Clone, Args)]
pub struct McpArgs {}

pub fn serve() -> ExitCode {
    // Cleanups through MCP are attributed in the action log unless the
    // client already says who it is. Set before any thread exists.
    // The action log drops actors outside [a-z0-9._-]{1,32}; use ours then.
    let valid = |a: &str| {
        (1..=32).contains(&a.len())
            && a.bytes()
                .all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'.' | b'_' | b'-'))
    };
    if !std::env::var("LYSOSOME_ACTOR").is_ok_and(|a| valid(&a)) {
        std::env::set_var("LYSOSOME_ACTOR", "mcp");
    }
    let mut stdin = std::io::stdin().lock();
    let mut stdout = std::io::stdout().lock();
    let mut buf = Vec::new();
    loop {
        buf.clear();
        match stdin.read_until(b'\n', &mut buf) {
            Ok(0) => break,
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => {
                eprintln!("lysosome mcp: could not read stdin: {e}");
                return ExitCode::FAILURE;
            }
        }
        // Invalid UTF-8 becomes a parse error reply, not a silent exit.
        let line = String::from_utf8_lossy(&buf);
        if line.trim().is_empty() {
            continue;
        }
        if let Some(reply) = handle_line(&line) {
            let mut text = reply.to_string();
            text.push('\n');
            if stdout
                .write_all(text.as_bytes())
                .and_then(|_| stdout.flush())
                .is_err()
            {
                break;
            }
        }
    }
    ExitCode::SUCCESS
}

/// One line in, at most one line out (notifications get no reply).
fn handle_line(line: &str) -> Option<Value> {
    match serde_json::from_str::<Value>(line) {
        Ok(Value::Array(batch)) if batch.is_empty() => Some(error_reply(
            Value::Null,
            -32600,
            "invalid request: empty batch",
        )),
        Ok(Value::Array(batch)) => {
            let replies: Vec<Value> = batch.iter().filter_map(handle).collect();
            (!replies.is_empty()).then_some(Value::Array(replies))
        }
        Ok(msg) => handle(&msg),
        Err(e) => Some(error_reply(
            Value::Null,
            -32700,
            &format!("parse error: {e}"),
        )),
    }
}

fn handle(msg: &Value) -> Option<Value> {
    if !msg.is_object() {
        return Some(error_reply(
            Value::Null,
            -32600,
            "invalid request: not an object",
        ));
    }
    let id = msg.get("id").cloned();
    // JSON-RPC ids are strings or numbers; a null id can't be answered usefully.
    if id
        .as_ref()
        .is_some_and(|i| !(i.is_string() || i.is_number()))
    {
        return Some(error_reply(
            Value::Null,
            -32600,
            "invalid request: id must be a string or number",
        ));
    }
    let Some(method) = msg.get("method").and_then(Value::as_str) else {
        // A response (we never send requests, so ignore it), or junk with an id.
        if msg.get("result").is_some() || msg.get("error").is_some() {
            return None;
        }
        return id.map(|id| error_reply(id, -32600, "invalid request: no method"));
    };
    // Notifications (initialized, cancelled...) need no answer.
    let id = id?;
    let params = msg.get("params").cloned().unwrap_or(Value::Null);
    let result = match method {
        "initialize" => Ok(initialize(&params)),
        "ping" => Ok(json!({})),
        "tools/list" => Ok(json!({ "tools": tools() })),
        "tools/call" => call(&params),
        _ => Err((-32601, format!("method not found: {method}"))),
    };
    Some(match result {
        Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
        Err((code, message)) => error_reply(id, code, &message),
    })
}

fn error_reply(id: Value, code: i64, message: &str) -> Value {
    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
}

fn initialize(params: &Value) -> Value {
    let asked = params.get("protocolVersion").and_then(Value::as_str);
    let version = PROTOCOL_VERSIONS
        .iter()
        .find(|v| Some(**v) == asked)
        .unwrap_or(&PROTOCOL_VERSIONS[0]);
    json!({
        "protocolVersion": version,
        "capabilities": { "tools": { "listChanged": false } },
        "serverInfo": {
            "name": lysosome_core::TOOL_NAME,
            "title": "lysosome",
            "version": env!("CARGO_PKG_VERSION"),
        },
        "instructions": INSTRUCTIONS,
    })
}

// ------------------------------------------------------------------ tools

fn roots_schema() -> Value {
    json!({
        "type": "array",
        "items": { "type": "string" },
        "description": "Folders to scan (absolute paths or ~/...). Default: the whole home folder, which is slow."
    })
}

fn project_props() -> Map<String, Value> {
    let mut m = Map::new();
    m.insert("roots".into(), roots_schema());
    m.insert(
        "days".into(),
        json!({ "type": "integer", "minimum": 0, "description": "Idle days before a project or worktree counts as dormant (default 30)." }),
    );
    m.insert(
        "depth".into(),
        json!({ "type": "integer", "minimum": 0, "description": "Maximum folder depth to search for repositories." }),
    );
    m.insert(
        "no_gh".into(),
        json!({ "type": "boolean", "description": "Don't ask GitHub (via gh) whether REVIEW worktrees were squash-merged." }),
    );
    m.insert(
        "offline".into(),
        json!({ "type": "boolean", "description": "Never use the network." }),
    );
    m
}

fn object(props: Map<String, Value>) -> Value {
    json!({ "type": "object", "properties": props, "additionalProperties": false })
}

/// `open_world`: may ask GitHub through `gh` (off with no_gh / offline).
fn read_only(title: &str, open_world: bool) -> Value {
    json!({ "title": title, "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": open_world })
}

fn tools() -> Value {
    let mut scan = project_props();
    scan.insert(
        "all".into(),
        json!({ "type": "boolean", "description": "Also list ACTIVE items." }),
    );
    scan.insert(
        "summary".into(),
        json!({ "type": "boolean", "description": "Return only totals by status, category and kind plus the top biggest items, not every finding. Much smaller; use it first on big folders." }),
    );
    scan.insert(
        "top".into(),
        json!({ "type": "integer", "minimum": 0, "description": "With summary: how many of the biggest items to list (default 30)." }),
    );
    let wt = scan.clone();
    scan.insert(
        "no_system".into(),
        json!({ "type": "boolean", "description": "Skip machine-wide caches, AI models, Docker, Xcode, Android and editor data." }),
    );

    let mut caches = Map::new();
    caches.insert(
        "categories".into(),
        json!({
            "type": "array",
            "items": { "enum": ["ai_models", "containers", "xcode", "package_caches", "android", "editors", "app_caches"] },
            "description": "Only these categories. Default: all."
        }),
    );

    let mut clean = project_props();
    for (k, d) in [
        ("worktrees", "Clean dormant git worktrees."),
        (
            "artifacts",
            "Clean git-ignored build/dependency folders of idle projects.",
        ),
        (
            "caches",
            "Clean package caches, AI models, Docker, Xcode, Android and editor data.",
        ),
        (
            "strip_artifacts",
            "Keep the worktrees; remove only the git-ignored artifact folders inside them (dormant ones, and active ones idle a day with no agent session running in them).",
        ),
    ] {
        clean.insert(
            k.into(),
            json!({ "type": "boolean", "description": format!("{d} With none of worktrees/artifacts/caches, all three.") }),
        );
    }
    clean.insert(
        "tier".into(),
        json!({ "enum": ["regenerable", "regenerable_expensive"], "description": "Highest tier to clean (default regenerable: cheap to rebuild). regenerable_expensive adds dependencies, AI models and images. review is never cleaned." }),
    );
    clean.insert(
        "older_than".into(),
        json!({ "type": "string", "description": "Only items idle at least this long: 90d, 12w, 6mo, 1y." }),
    );
    clean.insert(
        "only".into(),
        json!({ "type": "array", "items": { "type": "string" }, "description": "Item ids (<kind>:<path>) or, for a dry run, globs. Required with confirm, and then only exact ids." }),
    );
    clean.insert(
        "plan".into(),
        json!({ "type": "string", "description": "A dry run's plan_token. With confirm: clean exactly that dry run's items (the dry run's options are reused; pass no other arguments). Tokens expire after an hour and work once." }),
    );
    clean.insert(
        "confirm".into(),
        json!({ "type": "boolean", "description": "Actually clean the items in only (or in plan). Without it nothing is changed and the plan is returned, with a plan_token. Ask the user first; with only, repeat the dry run's other arguments." }),
    );
    let mut status = Map::new();
    status.insert(
        "job".into(),
        json!({ "type": "string", "description": "The job a confirmed clean returned while still running." }),
    );

    json!([
        {
            "name": "scan",
            "description": "Find reclaimable disk: idle project artifacts, dormant git worktrees, package caches, AI models, Docker and Xcode data. Read-only. Returns the versioned lysosome report (schema/lysosome.schema.json); findings carry id, size_bytes, tier and status.",
            "inputSchema": object(scan),
            "annotations": read_only("Scan for reclaimable disk", true),
        },
        {
            "name": "worktrees",
            "description": "Find dormant git worktrees and the disk they hold, with REMOVABLE / REVIEW / ORPHAN / ACTIVE status. Read-only. Same report format as scan.",
            "inputSchema": object(wt),
            "annotations": read_only("Find dormant git worktrees", true),
        },
        {
            "name": "caches",
            "description": "Find machine-wide package caches, AI models, Docker, Xcode, Android and editor data. Read-only. Same report format as scan.",
            "inputSchema": object(caches),
            "annotations": read_only("Find caches and models", false),
        },
        {
            "name": "clean",
            "description": "Clean up safely. Without confirm it is a dry run that returns the plan (schema/clean.schema.json) and a plan_token, and changes nothing. With confirm: true and plan: <plan_token>, it cleans exactly the dry run's items; with confirm: true and exact item ids in only, just those items (then pass the same roots, days, depth, tier and scope as the dry run, because the items are found again). Each is re-checked first, files go to the Trash, dirty, unpushed or REVIEW items are never touched. Show the plan to the user and get their OK before confirming. A long clean returns {status: running, job} and continues in the background; poll clean_status.",
            "inputSchema": object(clean),
            "annotations": {
                "title": "Clean up reclaimable disk",
                "readOnlyHint": false,
                "destructiveHint": true,
                "idempotentHint": false,
                "openWorldHint": true
            },
        },
        {
            "name": "clean_status",
            "description": "Wait (up to about 90 seconds) for a confirmed clean that is still running in the background, then return its result (the same document a finished clean returns) or its progress ({status: running, done, total, freed_bytes}) if it is still going. Call again until it returns the result.",
            "inputSchema": object(status),
            "annotations": read_only("Check a running clean", false),
        }
    ])
}

/// A tool result (`isError` for failures the model should see).
fn tool_result(text: String, is_error: bool) -> Value {
    json!({ "content": [{ "type": "text", "text": text }], "isError": is_error })
}

fn tool_error(code: &'static str, message: String, hint: &str) -> Value {
    let err = errors::CliError {
        code,
        message,
        hint: Some(hint.to_string()),
    };
    tool_result(errors::json(&err), true)
}

fn call(params: &Value) -> Result<Value, (i64, String)> {
    let name = params
        .get("name")
        .and_then(Value::as_str)
        .ok_or((-32602, "tools/call needs a name".to_string()))?;
    let empty = Map::new();
    let args = match params.get("arguments") {
        None | Some(Value::Null) => &empty,
        Some(Value::Object(m)) => m,
        Some(_) => return Err((-32602, "arguments must be an object".into())),
    };
    if name == "clean_status" {
        if let Some(k) = args.keys().find(|k| k.as_str() != "job") {
            return Ok(tool_error(
                "usage",
                format!("clean_status has no argument `{k}`"),
                "see the tool's inputSchema in tools/list",
            ));
        }
        let job = args.get("job").and_then(Value::as_str);
        return Ok(wait_job(job, true));
    }
    let argv = match name {
        "scan" | "worktrees" | "caches" | "clean" => match build_argv(name, args) {
            Ok(v) => v,
            Err(message) => {
                return Ok(tool_error(
                    "usage",
                    message,
                    "see the tool's inputSchema in tools/list",
                ))
            }
        },
        _ => return Err((-32602, format!("unknown tool: {name}"))),
    };
    if name == "clean" && flag(args, "confirm").unwrap_or(false) {
        return Ok(start_clean(argv));
    }
    Ok(run_argv(argv, None))
}

// ------------------------------------------------------------------ jobs
//
// A confirmed clean can take minutes (git worktree remove, cache commands),
// longer than MCP clients wait for a tool call. It runs on its own thread;
// the call waits up to `wait()` for it and otherwise returns the job's
// progress. `clean_status` waits again. One clean at a time.

struct Job {
    id: String,
    progress: Arc<clean::JobProgress>,
    rx: mpsc::Receiver<Value>,
    /// The finished result, when it arrived but wasn't returned yet.
    result: Option<Value>,
    started: Instant,
}

static JOB: Mutex<Option<Job>> = Mutex::new(None);

/// How long one call waits for a running clean (`LYSOSOME_MCP_WAIT_SECS`,
/// default 90 s: under the usual 120 s client timeout).
fn wait() -> Duration {
    Duration::from_secs(
        std::env::var("LYSOSOME_MCP_WAIT_SECS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(90),
    )
}

fn job_slot() -> std::sync::MutexGuard<'static, Option<Job>> {
    JOB.lock().unwrap_or_else(|e| e.into_inner())
}

fn start_clean(argv: Vec<OsString>) -> Value {
    {
        let mut slot = job_slot();
        if let Some(j) = slot.as_mut() {
            if j.result.is_none() {
                if let Ok(v) = j.rx.try_recv() {
                    j.result = Some(v);
                }
            }
            let what = if j.result.is_some() {
                "has finished, but its result wasn't collected yet"
            } else {
                "is still running"
            };
            return tool_error(
                "busy",
                format!("clean job {} {what}; one clean runs at a time", j.id),
                &format!("call clean_status with {{\"job\": \"{}\"}} first", j.id),
            );
        }
        let progress = Arc::new(clean::JobProgress::default());
        let (tx, rx) = mpsc::channel();
        let p = Arc::clone(&progress);
        let started = Instant::now();
        let id = format!(
            "clean-{:x}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_millis())
        );
        std::thread::spawn(move || {
            let _ = tx.send(run_argv(argv, Some(p)));
        });
        *slot = Some(Job {
            id: id.clone(),
            progress,
            rx,
            result: None,
            started,
        });
    }
    wait_job(None, false)
}

/// Wait for the running clean (`id`, if given, must be it).
fn wait_job(id: Option<&str>, poll: bool) -> Value {
    let Some(mut job) = job_slot().take() else {
        return tool_error(
            "no_job",
            "no clean is running".into(),
            "a confirmed clean that finished returned its result already; see the action log for past cleans",
        );
    };
    if let Some(id) = id {
        if id != job.id {
            let msg = format!("no clean job {id}; the running one is {}", job.id);
            *job_slot() = Some(job);
            return tool_error("unknown_job", msg, "pass the job the clean returned");
        }
    }
    if let Some(v) = job.result.take() {
        return v;
    }
    // clean_status always waits a little, so polling makes progress.
    let limit = if poll {
        wait().max(Duration::from_secs(1))
    } else {
        wait()
    };
    match job.rx.recv_timeout(limit) {
        Ok(v) => v,
        Err(mpsc::RecvTimeoutError::Timeout) => {
            let p = &job.progress;
            let status = json!({
                "status": "running",
                "job": job.id,
                "done": p.done.load(Ordering::SeqCst),
                "total": p.total.load(Ordering::SeqCst),
                "freed_bytes": p.freed_bytes.load(Ordering::SeqCst),
                "trashed_bytes": p.trashed_bytes.load(Ordering::SeqCst),
                "current": p.current.lock().map(|c| c.clone()).unwrap_or_default(),
                "elapsed_secs": job.started.elapsed().as_secs(),
                "next": format!("call clean_status with {{\"job\": \"{}\"}} to wait for the result", job.id),
            });
            *job_slot() = Some(job);
            tool_result(status.to_string(), false)
        }
        Err(mpsc::RecvTimeoutError::Disconnected) => tool_error(
            "internal",
            "the clean job ended without a result".into(),
            "check the action log for what was done, and please report it",
        ),
    }
}

/// Parse like the command line, then run the command's own code. `job`:
/// live counters for a background clean.
fn run_argv(argv: Vec<OsString>, job: Option<Arc<clean::JobProgress>>) -> Value {
    let mut cli = match Cli::try_parse_from(argv) {
        Ok(c) => c,
        Err(e) => {
            let text = e.render().to_string();
            let first = text.lines().next().unwrap_or("invalid arguments");
            return tool_error(
                "usage",
                first.trim_start_matches("error: ").to_string(),
                "see the tool's inputSchema in tools/list",
            );
        }
    };
    if let (Some(Command::Clean(a)), Some(j)) = (&mut cli.command, job) {
        a.job = Some(j);
    }
    let ran = catch_unwind(AssertUnwindSafe(|| match &cli.command {
        Some(Command::Scan(a)) => scan::run(a, &cli.global).map(|t| (t, false)),
        Some(Command::Worktrees(a)) => worktrees::run(a, &cli.global).map(|t| (t, false)),
        Some(Command::Caches(a)) => caches::run(a, &cli.global).map(|t| (t, false)),
        Some(Command::Clean(a)) => clean::run(a, &cli.global).map(|o| (o.text, o.failed)),
        _ => unreachable!("build_argv only builds the four tools"),
    }));
    match ran {
        Ok(Ok((text, failed))) => tool_result(text, failed),
        Ok(Err(e)) => tool_result(errors::json(&errors::describe(&e)), true),
        Err(_) => tool_error(
            "internal",
            "lysosome hit an internal error running this tool".into(),
            "run the same command in a terminal with --json to see it, and please report it",
        ),
    }
}

fn build_argv(tool: &str, args: &Map<String, Value>) -> Result<Vec<OsString>, String> {
    // The advertised inputSchema is the allow-list.
    let tools = tools();
    let props = tools
        .as_array()
        .and_then(|ts| ts.iter().find(|t| t["name"] == tool))
        .and_then(|t| t["inputSchema"]["properties"].as_object())
        .ok_or(format!("unknown tool `{tool}`"))?;
    if let Some(k) = args.keys().find(|k| !props.contains_key(k.as_str())) {
        return Err(format!("{tool} has no argument `{k}`"));
    }
    let mut v: Vec<String> = vec![
        lysosome_core::TOOL_NAME.into(),
        "--progress".into(),
        "off".into(),
        "--no-color".into(),
        tool.into(),
        "--json".into(),
    ];
    for key in ["days", "depth", "top"] {
        if let Some(x) = args.get(key) {
            let n = x
                .as_u64()
                .ok_or(format!("`{key}` must be a non-negative integer"))?;
            v.push(format!("--{key}={n}"));
        }
    }
    for key in [
        "no_gh",
        "offline",
        "all",
        "no_system",
        "worktrees",
        "artifacts",
        "caches",
        "strip_artifacts",
        "summary",
    ] {
        if flag(args, key)? {
            v.push(format!("--{}", key.replace('_', "-")));
        }
    }
    if let Some(t) = args.get("tier") {
        let t = t.as_str().ok_or("`tier` must be a string")?;
        v.push(format!("--tier={t}"));
    }
    if let Some(a) = args.get("older_than") {
        let a = a.as_str().ok_or("`older_than` must be a string")?;
        v.push(format!("--older-than={a}"));
    }
    for c in strings(args, "categories")? {
        v.push(format!("--category={c}"));
    }
    let only = strings(args, "only")?;
    let plan = match args.get("plan") {
        None | Some(Value::Null) => None,
        Some(Value::String(t)) if crate::plans::valid_token(t) => Some(t.clone()),
        Some(_) => return Err("`plan` must be the plan_token of a clean dry run".into()),
    };
    if let Some(t) = &plan {
        if !only.is_empty() {
            return Err("pass either `plan` or `only`, not both".into());
        }
        if flag(args, "confirm")? {
            v.push("--yes".into());
        }
        v.push(format!("--plan={t}"));
    } else if flag(args, "confirm")? {
        if only.is_empty() {
            return Err("confirm needs the exact ids of the items to clean in `only`; run clean without confirm first to get the plan".into());
        }
        if let Some(bad) = only.iter().find(|o| !is_exact_id(o)) {
            return Err(format!(
                "`{bad}` is not an item id; with confirm, `only` takes exact ids like \"node_modules:/path/to/project/node_modules\", no globs"
            ));
        }
        // --only also matches kinds, names and globs; with --only-exact the
        // plan keeps just the items whose id is listed.
        v.push("--yes".into());
        v.push("--only-exact".into());
    } else if tool == "clean" {
        v.push("--plan-token".into());
    }
    for o in &only {
        v.push(format!("--only={o}"));
    }
    let mut v: Vec<OsString> = v.into_iter().map(OsString::from).collect();
    let roots = strings(args, "roots")?;
    // The server's working directory is the client's business, so a
    // relative root would scan an arbitrary folder. `~` is expanded later,
    // as on the command line.
    if let Some(r) = roots
        .iter()
        .find(|r| !(Path::new(r).is_absolute() || *r == "~" || r.starts_with("~/")))
    {
        return Err(format!(
            "root `{r}` must be an absolute path or start with ~/"
        ));
    }
    if !roots.is_empty() {
        v.push("--".into());
        v.extend(roots.iter().map(OsString::from));
    }
    Ok(v)
}

fn flag(args: &Map<String, Value>, key: &str) -> Result<bool, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(false),
        Some(Value::Bool(b)) => Ok(*b),
        Some(_) => Err(format!("`{key}` must be true or false")),
    }
}

fn strings(args: &Map<String, Value>, key: &str) -> Result<Vec<String>, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(Vec::new()),
        Some(Value::Array(a)) => a
            .iter()
            .map(|x| {
                x.as_str()
                    .filter(|s| !s.is_empty())
                    .map(str::to_string)
                    .ok_or(format!("`{key}` must be a list of non-empty strings"))
            })
            .collect(),
        Some(_) => Err(format!("`{key}` must be a list of strings")),
    }
}

/// Shaped like an item id, `<kind>:<path>`, to catch a bare kind or name
/// passed by mistake. Matching itself is exact (`--only-exact`), so `*` and
/// `?` in a real path are fine.
fn is_exact_id(s: &str) -> bool {
    s.split_once(':')
        .is_some_and(|(kind, path)| !kind.is_empty() && !path.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn argv(tool: &str, args: Value) -> Result<Vec<String>, String> {
        build_argv(tool, args.as_object().unwrap())
            .map(|v| v.into_iter().map(|s| s.into_string().unwrap()).collect())
    }

    #[test]
    fn invalid_messages_get_an_error_and_responses_none() {
        let code = |line: &str| handle_line(line).map(|r| r["error"]["code"].clone());
        assert_eq!(code("[]"), Some(json!(-32600)));
        assert_eq!(code("{not json"), Some(json!(-32700)));
        assert_eq!(
            code(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#),
            Some(json!(-32600))
        );
        let batch = handle_line("[1]").unwrap();
        assert_eq!(batch[0]["error"]["code"], -32600);
        assert_eq!(handle_line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#), None);
        assert_eq!(
            handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#),
            None
        );
    }

    #[test]
    fn exact_ids_only() {
        assert!(is_exact_id("node_modules:/a/b/node_modules"));
        assert!(!is_exact_id("node_modules"));
        assert!(!is_exact_id("npm*"));
        assert!(is_exact_id("node_modules:/code/what?/node_modules"));
        assert!(is_exact_id("docker-image:docker://image/abc"));
        assert!(is_exact_id("node_modules:/code/foo[1]/node_modules"));
        assert!(!is_exact_id(":/a"));
    }

    #[test]
    fn clean_is_a_dry_run_unless_confirmed_with_ids() {
        let a = argv("clean", json!({ "only": ["npm*"] })).unwrap();
        assert!(!a.contains(&"--yes".to_string()));
        assert!(argv("clean", json!({ "confirm": true })).is_err());
        assert!(argv("clean", json!({ "confirm": true, "only": ["npm*"] })).is_err());
        let a = argv(
            "clean",
            json!({ "confirm": true, "only": ["target:/x/target"] }),
        )
        .unwrap();
        assert!(a.contains(&"--yes".to_string()));
        assert!(a.contains(&"--only=target:/x/target".to_string()));
        assert!(a.contains(&"--only-exact".to_string()));
    }

    #[test]
    fn unknown_and_dangerous_arguments_are_refused() {
        assert!(argv("clean", json!({ "permanent": true })).is_err());
        assert!(argv("clean", json!({ "interactive": true })).is_err());
        assert!(argv("scan", json!({ "confirm": true })).is_err());
        assert!(argv("scan", json!({ "days": -1 })).is_err());
    }

    #[test]
    fn roots_are_absolute_and_follow_a_double_dash() {
        let a = argv("scan", json!({ "roots": ["/--yes", "~/code"] })).unwrap();
        let dd = a.iter().position(|s| s == "--").unwrap();
        assert_eq!(a[dd + 1..], ["/--yes", "~/code"]);
        assert!(argv("scan", json!({ "roots": ["code"] })).is_err());
        assert!(argv("scan", json!({ "roots": ["--yes"] })).is_err());
    }
}