mushroomdb-cli 0.6.5

CLI binary for mushroomdb: start, shell, and server commands
Documentation
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
//! `mushroomdb` — thin dispatcher over [`cli`] lib functions.

use cli::{
    format_backup, format_demo, format_stats, format_suggest, install, maybe_run_demo_if_empty,
    parse_args, read_stats, run_algo, run_asof, run_backup, run_demo, run_export, run_migrate,
    run_query, run_schema_apply, run_snapshot, run_suggest, run_verify, usage, Command, ServeUi,
};
use core_api::{GraphError, SharedDb};
use std::collections::HashMap;
use std::io::{self, Read as _, Write};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

fn main() -> ExitCode {
    let raw: Vec<String> = std::env::args().skip(1).collect();
    match parse_args(&raw) {
        Ok(Command::Help) => {
            print!("{}", usage());
            ExitCode::SUCCESS
        }
        Ok(Command::Recall { db_dir, auto }) => {
            let mut raw = String::new();
            let _ = io::stdin().read_to_string(&mut raw);
            // `run_recall` returns a digest, never an error: it is silent on
            // every failure by contract. A *panic* is the one way it could
            // still reach the user, and it would do so before every prompt, so
            // it is caught here and the digest is simply empty.
            let digest = silently(|| cli::recall::run_recall(&resolve_db(db_dir, auto), &raw))
                .unwrap_or_default();
            // Not `print!`: that panics on EPIPE (exit 101) if the hook runner
            // closes the pipe. Every write error is swallowed instead.
            let mut stdout = io::stdout();
            let _ = stdout.write_all(digest.as_bytes());
            let _ = stdout.flush();
            ExitCode::SUCCESS // never block the prompt
        }
        Ok(Command::Brief { db_dir, auto }) => {
            // A SessionStart hook is the first thing a session sees. A store
            // that cannot be opened at all — missing, held by a writer, not a
            // store — has no brief to give, and greeting the user with that
            // error is worse than opening in silence: every failure here
            // prints nothing and exits 0. (A store that opens but is *empty*
            // does have something to say, and says it.)
            let brief = silently(|| cli::run_brief(&resolve_db(db_dir, auto)))
                .and_then(Result::ok)
                .unwrap_or_default();
            let mut stdout = io::stdout();
            let _ = stdout.write_all(brief.as_bytes());
            let _ = stdout.flush();
            ExitCode::SUCCESS
        }
        Ok(Command::Intercept { db_dir, auto }) => {
            // Claude Code reads exit 2 as "block this tool call, and give the
            // model what stderr said"; every other outcome — no opinion, a
            // store that will not open, a payload that will not parse, a panic
            // — is exit 0 and not one byte written, so a hook of ours can
            // never be why a search did not run.
            let mut raw = String::new();
            let _ = io::stdin().read_to_string(&mut raw);
            match silently(|| cli::intercept::run_intercept(&resolve_db(db_dir, auto), &raw))
                .flatten()
            {
                Some(message) => {
                    let mut stderr = io::stderr();
                    let _ = writeln!(stderr, "{message}");
                    let _ = stderr.flush();
                    ExitCode::from(2)
                }
                None => ExitCode::SUCCESS,
            }
        }
        Ok(Command::ImpactHook { db_dir, auto }) => {
            // Claude Code reads one `hookSpecificOutput` object on stdout as
            // context to add to the turn; exit 0 lets the edit proceed either
            // way. Nothing to say is nothing written, like every other hook
            // this binary provides.
            let mut raw = String::new();
            let _ = io::stdin().read_to_string(&mut raw);
            let text =
                silently(|| cli::impact_hook::run(&resolve_db(db_dir, auto), &raw)).flatten();
            print_hook_context("PreToolUse", text.as_deref());
            ExitCode::SUCCESS
        }
        Ok(Command::Enrich { db_dir, auto }) => {
            let mut raw = String::new();
            let _ = io::stdin().read_to_string(&mut raw);
            let text = silently(|| cli::enrich::run(&resolve_db(db_dir, auto), &raw)).flatten();
            print_hook_context("PostToolUse", text.as_deref());
            ExitCode::SUCCESS
        }
        Ok(Command::Map { db_dir, json }) => match cli::run_map(&db_dir, json) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Explore {
            db_dir,
            target,
            depth,
            full,
        }) => print_or_fail(cli::run_explore(&db_dir, &target, depth, full)),
        Ok(Command::Context {
            db_dir,
            target,
            full,
        }) => print_or_fail(cli::run_context(&db_dir, &target, full)),
        Ok(Command::Impact { db_dir, files }) => print_or_fail(cli::run_impact(&db_dir, &files)),
        Ok(Command::Owners { db_dir, path }) => print_or_fail(cli::run_owners(&db_dir, &path)),
        Ok(Command::Why { db_dir, a, b }) => print_or_fail(cli::run_why(&db_dir, &a, &b)),
        Ok(Command::Sync { db_dir, auto, json }) => {
            match cli::ingest_git::run_sync(&resolve_db(db_dir, auto)) {
                Ok(report) => {
                    if json {
                        print!("{}", cli::ingest_git::format_sync_json(&report));
                    } else {
                        print!("{}", cli::ingest_git::format_sync(&report));
                    }
                    ExitCode::SUCCESS
                }
                Err(e) => busy_aware(&e),
            }
        }
        Ok(Command::Touch {
            db_dir,
            auto,
            files,
        }) => {
            // Only read stdin when there is nothing on the command line: a hook
            // pipes a payload, a person does not, and blocking a person's
            // terminal on a read that will never end is the worse failure.
            let payload = if files.is_empty() {
                let mut raw = String::new();
                let _ = io::stdin().read_to_string(&mut raw);
                Some(raw)
            } else {
                None
            };
            if files.is_empty() || auto {
                silent_touch(db_dir, auto, &files, payload.as_deref());
                return ExitCode::SUCCESS;
            }
            match cli::ingest_git::run_touch(&resolve_db(db_dir, auto), &files, payload.as_deref())
            {
                Ok(report) => {
                    print!("{}", cli::ingest_git::format_touch(&report));
                    ExitCode::SUCCESS
                }
                Err(e) => busy_aware(&e),
            }
        }
        Ok(Command::Version) => {
            println!("{}", cli::version_string());
            ExitCode::SUCCESS
        }
        Ok(Command::IngestGit { db_dir, opts }) => {
            match cli::ingest_git::run_ingest_git(&db_dir, &opts) {
                Ok(report) => {
                    print!("{}", cli::ingest_git::format_ingest_git(&report));
                    ExitCode::SUCCESS
                }
                Err(e) => busy_aware(&e),
            }
        }
        Ok(Command::Serve {
            db_dir,
            addr,
            ui,
            demo_if_empty,
            token,
            role_tokens,
            snapshot_every,
            restore_from,
            tls_cert,
            tls_key,
        }) => {
            let token = token.filter(|s| !s.is_empty()).or_else(|| {
                std::env::var("MUSHROOMDB_TOKEN")
                    .ok()
                    .filter(|s| !s.is_empty())
            });
            if !addr.ip().is_loopback() && token.as_ref().map(|s| s.is_empty()).unwrap_or(true) {
                return fail(
                    "non-loopback --addr requires --token or MUSHROOMDB_TOKEN \
                     (see SECURITY.md)",
                );
            }
            // Merge --role-token flags with MUSHROOMDB_ROLE_TOKENS env var.
            // Format: "TOKEN1:ROLE1,TOKEN2:ROLE2". Flag entries win over env on
            // collision (flags are inserted last; HashMap retains last writer).
            let mut all_role_tokens: HashMap<String, String> = HashMap::new();
            if let Ok(env_val) = std::env::var("MUSHROOMDB_ROLE_TOKENS") {
                for pair in env_val.split(',') {
                    let pair = pair.trim();
                    if pair.is_empty() {
                        continue;
                    }
                    if let Some((tok, role)) = pair.split_once(':') {
                        if !tok.is_empty() && !role.is_empty() {
                            all_role_tokens.insert(tok.to_string(), role.to_string());
                        }
                    }
                }
            }
            for (tok, role) in role_tokens {
                all_role_tokens.insert(tok, role);
            }
            // Before the demo, so a restored store is never overwritten by it.
            if let Some(from) = restore_from {
                match cli::restore_if_empty(&db_dir, &from) {
                    Ok(cli::RestoreOutcome::Restored { from, files, bytes }) => println!(
                        "restored from {}: {} files, {} bytes",
                        from.display(),
                        files.len(),
                        bytes
                    ),
                    Ok(cli::RestoreOutcome::AlreadyPresent) => eprintln!(
                        "restore-from: {} already holds a store; not restoring",
                        db_dir.display()
                    ),
                    // A warning, not an error: a first boot with an empty
                    // backup volume must still start.
                    Ok(cli::RestoreOutcome::Empty) => {
                        eprintln!("restore-from: no backup found under {}", from.display())
                    }
                    Err(e) => return fail(&e.to_string()),
                }
            }
            if demo_if_empty {
                match maybe_run_demo_if_empty(&db_dir) {
                    Ok(Some(out)) => print!("{}", format_demo(&db_dir, &out)),
                    Ok(None) => {}
                    Err(e) => return fail(&e.to_string()),
                }
            }
            let ui = match ui {
                ServeUi::Filesystem(dir) => match cli::validate_ui_dir(&dir) {
                    Ok(dir) => ServeUi::Filesystem(dir),
                    Err(e) => return fail(&e),
                },
                other => other,
            };
            exit(run_serve(
                db_dir,
                addr,
                ui,
                token,
                all_role_tokens,
                snapshot_every,
                tls_cert,
                tls_key,
            ))
        }
        Ok(Command::Mcp {
            db_dir,
            auto,
            all_tools,
        }) => exit(run_mcp(resolve_db(db_dir, auto), all_tools)),
        Ok(Command::Stats { db_dir }) => match read_stats(&db_dir) {
            Ok(stats) => {
                print!("{}", format_stats(&stats));
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Demo { db_dir }) => match run_demo(&db_dir) {
            Ok(out) => {
                print!("{}", format_demo(&db_dir, &out));
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Suggest { db_dir }) => match run_suggest(&db_dir) {
            Ok(suggestions) => {
                print!("{}", format_suggest(&suggestions));
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::AsOf {
            db_dir,
            commit,
            query,
        }) => match run_asof(&db_dir, commit, query.as_deref()) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Algo {
            db_dir,
            subcmd,
            top,
            dir,
            edge_types,
            weight_prop,
            min_weight,
        }) => match run_algo(
            &db_dir,
            &subcmd,
            top,
            dir,
            edge_types,
            weight_prop,
            min_weight,
        ) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Query { db_dir, cypher }) => match run_query(&db_dir, &cypher) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Snapshot {
            db_dir,
            wal,
            retention,
        }) => match run_snapshot(&db_dir, wal, retention) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::SchemaApply {
            db_dir,
            schema_file,
        }) => match run_schema_apply(&db_dir, &schema_file) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Migrate { db_dir }) => match run_migrate(&db_dir) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Verify { db_dir }) => match run_verify(&db_dir) {
            Ok(msg) => {
                println!("{msg}");
                ExitCode::SUCCESS
            }
            Err(e) => {
                eprintln!("error: {}", e);
                ExitCode::from(1)
            }
        },
        Ok(Command::Backup { db_dir, dest }) => match run_backup(&db_dir, &dest) {
            Ok(report) => {
                print!("{}", format_backup(&dest, &report));
                if !report.verified {
                    eprintln!("warning: backup verification failed");
                    return ExitCode::from(1);
                }
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Export {
            db_dir,
            dest,
            format,
        }) => match run_export(&db_dir, &dest, &format) {
            Ok(out) => {
                print!("{out}");
                ExitCode::SUCCESS
            }
            Err(e) => fail(&e.to_string()),
        },
        Ok(Command::Install(opts)) => {
            let home = home_dir();
            let cwd = std::env::current_dir().unwrap_or_default();
            match install::run_install(&cwd, &home, &opts) {
                Ok(out) => {
                    print!("{out}");
                    ExitCode::SUCCESS
                }
                Err(e) => fail(&e.to_string()),
            }
        }
        Ok(Command::Uninstall(opts)) => {
            let home = home_dir();
            let cwd = std::env::current_dir().unwrap_or_default();
            match install::run_uninstall(&cwd, &home, &opts) {
                Ok(out) => {
                    print!("{out}");
                    ExitCode::SUCCESS
                }
                Err(e) => fail(&e.to_string()),
            }
        }
        Ok(Command::Disable(opts)) => {
            let home = home_dir();
            let cwd = std::env::current_dir().unwrap_or_default();
            match install::run_disable(&cwd, &home, &opts) {
                Ok(out) => {
                    print!("{out}");
                    ExitCode::SUCCESS
                }
                Err(e) => fail(&e.to_string()),
            }
        }
        Ok(Command::Enable(opts)) => {
            let home = home_dir();
            let cwd = std::env::current_dir().unwrap_or_default();
            match install::run_enable(&cwd, &home, &opts) {
                Ok(out) => {
                    print!("{out}");
                    ExitCode::SUCCESS
                }
                Err(e) => fail(&e.to_string()),
            }
        }
        Ok(Command::Doctor(opts)) => {
            let home = home_dir();
            let cwd = std::env::current_dir().unwrap_or_default();
            match cli::doctor::run_doctor(&cwd, &home, &opts) {
                Ok(report) => {
                    print!("{}", report.output);
                    if report.had_fail {
                        ExitCode::from(1)
                    } else {
                        ExitCode::SUCCESS
                    }
                }
                Err(e) => fail(&e.to_string()),
            }
        }
        Err(e) => {
            let _ = writeln!(io::stderr(), "{e}");
            eprint!("{}", usage());
            ExitCode::from(1)
        }
    }
}

fn exit(r: Result<(), String>) -> ExitCode {
    match r {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => fail(&e),
    }
}

/// Print a digest, or its error on stderr. The graph tools all answer the same
/// way: a string on success, one line on stderr and exit 1 otherwise.
fn print_or_fail(r: Result<String, cli::CliError>) -> ExitCode {
    match r {
        Ok(out) => {
            print!("{out}");
            ExitCode::SUCCESS
        }
        Err(e) => fail(&e.to_string()),
    }
}

fn fail(msg: &str) -> ExitCode {
    let _ = writeln!(io::stderr(), "{msg}");
    ExitCode::from(1)
}

/// Report a store-writing command's failure, distinguishing "busy" from the
/// rest. Exit 3 is "the store is busy, nothing was written" — a caller (a git
/// hook, a retry loop) can act on that without parsing the message.
fn busy_aware(e: &cli::CliError) -> ExitCode {
    let _ = writeln!(io::stderr(), "error: {e}");
    if e.0 == cli::ingest_git::BUSY_MESSAGE {
        ExitCode::from(3)
    } else {
        ExitCode::FAILURE
    }
}

/// Run `f`, returning `None` if it panicked and printing nothing either way.
///
/// The panic hook is replaced for the duration: an unwind would otherwise print
/// a message and a backtrace to stderr and exit 101, which for a hook body is
/// the noisiest possible outcome and the one a user can do least about. Both
/// hook bodies (`recall`, and `touch` in hook mode) go through this.
fn silently<T>(f: impl FnOnce() -> T) -> Option<T> {
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
    std::panic::set_hook(previous);
    outcome.ok()
}

/// Run `touch` as a hook body: say nothing, whatever happens, and let the
/// caller exit 0.
///
/// A `PostToolUse` hook fires on every edit the assistant makes, and everything
/// it writes to either stream lands in the user's session. Almost everything
/// this command can fail on is *routine* there rather than exceptional — a
/// payload for a file in some other project, a database that was never built
/// from a repository, a peer process holding the write lock — and none of it is
/// the user's problem to read about on every keystroke. So the outcome is
/// discarded, including the successful report: a line per edit is the loudest
/// noise of the lot.
///
/// Naming files on the command line opts out of all of it: see the `Touch` arm.
fn silent_touch(db_dir: Option<PathBuf>, auto: bool, files: &[PathBuf], payload: Option<&str>) {
    let _ = silently(|| {
        let db = resolve_db(db_dir, auto);
        cli::ingest_git::run_touch(&db, files, payload)
    });
}

/// Print one hook result object on stdout, or nothing at all for `None`.
///
/// The shape is Claude Code's documented `hookSpecificOutput`: an object
/// carrying the event's own name and `additionalContext`, the field both
/// `PreToolUse` and `PostToolUse` read as "add this to the turn". Nothing else
/// goes in it — no `permissionDecision`, no `decision` — because neither of
/// these hooks has an opinion about whether the tool call should happen.
///
/// Not `print!`: that panics on EPIPE (exit 101) if the hook runner closes the
/// pipe, and a hook body must never be why anything fails.
fn print_hook_context(event: &str, text: Option<&str>) {
    let Some(text) = text.filter(|t| !t.is_empty()) else {
        return;
    };
    let out = serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": event,
            "additionalContext": text,
        }
    });
    let mut stdout = io::stdout();
    let _ = stdout.write_all(out.to_string().as_bytes());
    let _ = stdout.flush();
}

/// The database a `<db-dir>`-or-`--auto` command should use.
fn resolve_db(db_dir: Option<PathBuf>, auto: bool) -> PathBuf {
    match db_dir {
        Some(dir) => dir,
        None => {
            debug_assert!(auto, "the parser rejects neither a dir nor --auto");
            cli::resolve_auto_db(
                std::env::var_os("CLAUDE_PROJECT_DIR").as_deref(),
                &std::env::current_dir().unwrap_or_default(),
                &home_dir(),
            )
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn run_serve(
    db_dir: PathBuf,
    addr: SocketAddr,
    ui: ServeUi,
    token: Option<String>,
    role_tokens: HashMap<String, String>,
    snapshot_every: Option<Duration>,
    tls_cert: Option<PathBuf>,
    tls_key: Option<PathBuf>,
) -> Result<(), String> {
    let rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
    rt.block_on(async {
        let db = SharedDb::open(&db_dir).map_err(|e| e.to_string())?;
        let (tx, rx) = tokio::sync::oneshot::channel();
        if let Some(period) = snapshot_every {
            let db_snap = db.clone();
            tokio::spawn(async move {
                let mut interval = tokio::time::interval(period);
                interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
                interval.tick().await; // skip immediate fire
                loop {
                    interval.tick().await;
                    let db_snap = db_snap.clone();
                    // A snapshot replaces wal.bin, so it needs the store's
                    // cross-process write lock. If another process holds it,
                    // skip this tick rather than wait: the next one is only a
                    // period away, and a snapshot is never urgent.
                    let taken =
                        tokio::task::spawn_blocking(move || cli::snapshot_shared(&db_snap)).await;
                    match taken {
                        Ok(Ok(())) => {}
                        Ok(Err(GraphError::Busy { .. })) => {
                            eprintln!(
                                "snapshot-every skipped: another process holds the write lock"
                            );
                        }
                        Ok(Err(e)) => eprintln!("snapshot-every failed: {e}"),
                        Err(e) => eprintln!("snapshot-every task panicked: {e}"),
                    }
                }
            });
        }
        let db_serve = db.clone();
        let mut serve = tokio::spawn(async move {
            // TLS path: both --tls-cert and --tls-key were supplied.
            if let (Some(cert), Some(key)) = (tls_cert, tls_key) {
                #[cfg(feature = "tls")]
                {
                    return server::serve_tls(db_serve, addr, tx, cert, key, token, role_tokens)
                        .await;
                }
                #[cfg(not(feature = "tls"))]
                {
                    let _ = (cert, key, db_serve, addr, tx, token, role_tokens);
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::Unsupported,
                        "this binary was built without TLS support; \
                         rebuild with --features tls or terminate TLS at a \
                         reverse proxy (see docs/site/deployment.md)",
                    ));
                }
            }
            match ui {
                ServeUi::Filesystem(dir) => {
                    server::serve_with_ui_and_role_tokens(
                        db_serve,
                        addr,
                        tx,
                        dir,
                        token,
                        role_tokens,
                    )
                    .await
                }
                ServeUi::None => {
                    server::serve_with_role_tokens(db_serve, addr, tx, token, role_tokens).await
                }
                ServeUi::Embedded => {
                    #[cfg(feature = "embed-ui")]
                    {
                        server::serve_with_embedded_ui(db_serve, addr, tx, token, role_tokens).await
                    }
                    #[cfg(not(feature = "embed-ui"))]
                    {
                        server::serve_with_role_tokens(db_serve, addr, tx, token, role_tokens).await
                    }
                }
            }
        });
        match rx.await {
            Ok(bound) => println!("listening on http://{bound}"),
            Err(_) => {
                return match serve.await {
                    Ok(Ok(())) => Err("server exited before readiness".into()),
                    Ok(Err(e)) => Err(e.to_string()),
                    Err(e) => Err(e.to_string()),
                };
            }
        }
        tokio::select! {
            result = &mut serve => match result {
                Ok(Ok(())) => Ok(()),
                Ok(Err(e)) => Err(e.to_string()),
                Err(e) => Err(e.to_string()),
            },
            _ = shutdown_signal() => {
                serve.abort();
                let _ = serve.await;
                // Same rule as the periodic snapshot: it needs the store's
                // write lock. Shutting down without one is fine — the WAL holds
                // every commit, and the next open replays it.
                match cli::snapshot_shared(&db) {
                    Ok(()) => {}
                    Err(GraphError::Busy { .. }) => {
                        eprintln!(
                            "shutdown snapshot skipped: another process holds the write lock"
                        );
                    }
                    Err(e) => return Err(e.to_string()),
                }
                Ok(())
            }
        }
    })
}

async fn shutdown_signal() {
    let ctrl_c = async {
        match tokio::signal::ctrl_c().await {
            Ok(()) => {}
            // Install failure is not SIGINT; park like SIGTERM handler Err.
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut sig) => {
                let _ = sig.recv().await;
            }
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        _ = ctrl_c => {}
        _ = terminate => {}
    }
}

fn run_mcp(db_dir: PathBuf, all_tools: bool) -> Result<(), String> {
    let db = SharedDb::open(&db_dir).map_err(|e| e.to_string())?;
    let stdin = io::stdin();
    let stdout = io::stdout();
    // The store's path, not just a handle: the `sync` tool re-runs this binary
    // against the directory, and cannot infer it from an open database.
    server::run_mcp_stdio_with(db, Some(db_dir), all_tools, stdin.lock(), stdout.lock())
        .map_err(|e| e.to_string())
}

fn home_dir() -> PathBuf {
    // Prefer HOME env var; fall back to /tmp for safety (never panic).
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/tmp"))
}