mnemo-engine 0.17.1

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! 12.3 step 3: `mnemo mcp install --client <name> <file>` (R-007.3).
//!
//! Adds this brain's MCP server to a client's config: always
//! `serve --mcp --shared`, never a secret, and in a project scope (a file
//! that's committed) no absolute path, `--embed-cmd` or key command.
//!
//! The clients, each checked against its vendor's documentation (fetched
//! 2026-11-14):
//! - **`claude-code`** (<https://code.claude.com/docs/en/mcp>):
//!   `claude mcp add-json <name> '<json>' --scope local|project|user`;
//!   project scope is `.mcp.json` at the project root (`mcpServers`), local
//!   and user are in `~/.claude.json`. `.mcp.json` expands `${VAR:-default}`
//!   in `args`, and Claude Code sets `CLAUDE_PROJECT_DIR` to the project root
//!   in the server's environment, so a project-relative path is
//!   `${CLAUDE_PROJECT_DIR:-.}/<path>`. Without `claude` on the PATH, only
//!   the project scope can be written (the file itself).
//! - **`cursor`** (<https://cursor.com/docs/context/mcp>): `.cursor/mcp.json`
//!   in the project, `~/.cursor/mcp.json` for the user (`mcpServers`, with
//!   `type`, `command`, `args`, `env`); `${workspaceFolder}` is the project
//!   root.
//! - **`claude-desktop`**
//!   (<https://modelcontextprotocol.io/docs/develop/connect-local-servers>):
//!   one per-user file, `~/Library/Application Support/Claude/` on macOS,
//!   `%APPDATA%\Claude\` on Windows, `~/.config/Claude/` on Linux,
//!   `claude_desktop_config.json` (`mcpServers`); paths must be absolute.
//!
//! Not in the table: VS Code (two formats, and its portable project file is
//! the same `.mcp.json` Claude Code reads, which expands a different
//! variable) and Codex (TOML, which would need a new dependency to edit).

use std::path::{Path, PathBuf};

use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
use serde_json::value::RawValue;
use serde_json::{json, Value};

/// A client `mcp install` knows.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Client {
    /// Claude Code.
    ClaudeCode,
    /// Cursor.
    Cursor,
    /// Claude Desktop.
    ClaudeDesktop,
}

/// Where the entry goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Scope {
    /// Committed with the project: no secret, no absolute path.
    Project,
    /// This project, for this user only (Claude Code).
    Local,
    /// Every project, for this user.
    User,
}

impl Scope {
    fn word(self) -> &'static str {
        match self {
            Scope::Project => "project",
            Scope::Local => "local",
            Scope::User => "user",
        }
    }
}

/// `mcp install`'s options.
pub struct Install {
    pub client: Client,
    pub file: String,
    /// 12.2: the path was left out, and `file` is the project brain. A
    /// project or local entry then names no path: the server finds the
    /// brain itself (`CLAUDE_PROJECT_DIR` for Claude Code, `-C
    /// ${workspaceFolder}` for Cursor).
    pub project: bool,
    pub scope: Option<Scope>,
    pub name: String,
    pub print: bool,
    pub yes: bool,
}

fn client_name(c: Client) -> &'static str {
    match c {
        Client::ClaudeCode => "claude-code",
        Client::Cursor => "cursor",
        Client::ClaudeDesktop => "claude-desktop",
    }
}

fn scopes(c: Client) -> &'static [Scope] {
    match c {
        Client::ClaudeCode => &[Scope::Project, Scope::Local, Scope::User],
        Client::Cursor => &[Scope::Project, Scope::User],
        Client::ClaudeDesktop => &[Scope::User],
    }
}

/// The git work tree `start` is in: the nearest directory up from it with a
/// `.git` (a directory, or a worktree's file).
pub(super) fn git_root(start: &Path) -> Option<PathBuf> {
    let mut d = Some(start);
    while let Some(dir) = d {
        if dir.join(".git").exists() {
            return Some(dir.to_path_buf());
        }
        d = dir.parent();
    }
    None
}

pub(super) fn home() -> Result<PathBuf, String> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .ok_or_else(|| "can't find the home directory (HOME isn't set)".to_string())
}

/// Claude Desktop's config file on this OS.
fn desktop_config() -> Result<PathBuf, String> {
    if cfg!(target_os = "macos") {
        Ok(home()?.join("Library/Application Support/Claude/claude_desktop_config.json"))
    } else if cfg!(windows) {
        let appdata = std::env::var_os("APPDATA")
            .map(PathBuf::from)
            .ok_or_else(|| "APPDATA isn't set".to_string())?;
        Ok(appdata.join("Claude").join("claude_desktop_config.json"))
    } else {
        Ok(home()?.join(".config/Claude/claude_desktop_config.json"))
    }
}

/// An executable named `name` on the PATH.
pub(super) fn on_path(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path).find_map(|d| {
        let p = d.join(name);
        let ok = std::fs::metadata(&p).is_ok_and(|m| m.is_file());
        #[cfg(windows)]
        let ok = ok || std::fs::metadata(p.with_extension("exe")).is_ok_and(|m| m.is_file());
        ok.then_some(p)
    })
}

/// What `run` decided: the entry, and where it goes.
struct Plan {
    scope: Scope,
    entry: Value,
    /// The config file to edit, or `None` when `claude mcp add-json` does it.
    file: Option<PathBuf>,
    /// The directory `claude` runs in (the project root), for its scopes.
    claude: Option<(PathBuf, PathBuf)>,
}

fn plan(o: &Install) -> Result<Plan, String> {
    let brain = std::fs::canonicalize(&o.file)
        .map_err(|e| format!("{}: {e} (mcp install needs an existing brain)", o.file))?;
    let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
    let cwd = std::fs::canonicalize(&cwd).unwrap_or(cwd);
    let root = git_root(&cwd);
    let allowed = scopes(o.client);
    let scope = match o.scope {
        Some(s) => s,
        // 12.2 step 5: the project brain is per user, so with the path left
        // out Claude Code defaults to its local scope, and Cursor (which has
        // none) to its project file, listed in `.git/info/exclude`.
        None if o.project && root.is_some() => match o.client {
            Client::ClaudeCode => Scope::Local,
            Client::Cursor => Scope::Project,
            Client::ClaudeDesktop => Scope::User,
        },
        None => match &root {
            // The project brain is under the git common dir, which for a
            // linked worktree is outside its root.
            Some(r) if (o.project || brain.starts_with(r)) && allowed.contains(&Scope::Project) => {
                Scope::Project
            }
            _ => Scope::User,
        },
    };
    if !allowed.contains(&scope) {
        let names: Vec<&str> = allowed.iter().map(|s| s.word()).collect();
        return Err(format!(
            "{} has no {} scope (it has: {}); nothing was written",
            client_name(o.client),
            scope.word(),
            names.join(", ")
        ));
    }
    // The command and the path. In a project scope (committed), `mnemo`
    // from the PATH and a path relative to the project root; otherwise
    // absolute, since a GUI client doesn't get the shell's PATH.
    //
    // 12.2: with the path left out, a project or local entry names no path
    // at all, and the server finds the project brain from where the client
    // starts it. A user scope (every project) keeps the absolute path.
    let (command, brain_arg) = if o.project && scope != Scope::User {
        if root.is_none() {
            return Err(format!(
                "the {} scope needs a git work tree, and {} isn't in one; use --scope user",
                scope.word(),
                cwd.display()
            ));
        }
        let command = if scope == Scope::Project {
            "mnemo".to_string()
        } else {
            std::env::current_exe()
                .and_then(std::fs::canonicalize)
                .map_err(|e| format!("can't find this mnemo's path: {e}"))?
                .to_string_lossy()
                .into_owned()
        };
        (command, None)
    } else if scope == Scope::Project {
        let Some(root) = &root else {
            return Err(format!(
                "the project scope needs a git work tree, and {} isn't in one; use --scope user",
                cwd.display()
            ));
        };
        let rel = brain.strip_prefix(root).map_err(|_| {
            format!(
                "{} is outside the project ({}), so a project-scoped config can't name it; \
                 use --scope user",
                brain.display(),
                root.display()
            )
        })?;
        let rel = rel
            .components()
            .map(|c| c.as_os_str().to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join("/");
        let arg = match o.client {
            Client::ClaudeCode => format!("${{CLAUDE_PROJECT_DIR:-.}}/{rel}"),
            Client::Cursor => format!("${{workspaceFolder}}/{rel}"),
            Client::ClaudeDesktop => unreachable!("no project scope"),
        };
        ("mnemo".to_string(), Some(arg))
    } else {
        let exe = std::env::current_exe()
            .and_then(std::fs::canonicalize)
            .map_err(|e| format!("can't find this mnemo's path: {e}"))?;
        (
            exe.to_string_lossy().into_owned(),
            Some(brain.to_string_lossy().into_owned()),
        )
    };
    let mut args: Vec<String> = Vec::new();
    if brain_arg.is_none() && o.client == Client::Cursor {
        // Cursor starts a server in no particular directory; its
        // `${workspaceFolder}` is the folder that holds `.cursor/mcp.json`.
        args.extend(["-C".to_string(), "${workspaceFolder}".to_string()]);
    }
    args.extend(["serve", "--mcp", "--shared"].map(String::from));
    args.extend(brain_arg);
    let mut entry = json!({
        "command": command,
        "args": args,
    });
    if o.client != Client::ClaudeDesktop {
        entry["type"] = json!("stdio");
    }
    check_rules(&entry, scope)?;
    let (file, claude) = match (o.client, scope) {
        (Client::ClaudeCode, s) => match on_path("claude") {
            Some(c) => (None, Some((c, root.clone().unwrap_or(cwd.clone())))),
            None if s == Scope::Project => (Some(root.clone().unwrap().join(".mcp.json")), None),
            None => {
                return Err(format!(
                    "Claude Code's {} scope lives in ~/.claude.json, which only the `claude` CLI \
                     writes, and `claude` isn't on the PATH; use --scope project, or install \
                     Claude Code",
                    s.word()
                ))
            }
        },
        (Client::Cursor, Scope::Project) => (
            Some(root.clone().unwrap().join(".cursor").join("mcp.json")),
            None,
        ),
        (Client::Cursor, _) => (Some(home()?.join(".cursor").join("mcp.json")), None),
        (Client::ClaudeDesktop, _) => (Some(desktop_config()?), None),
    };
    Ok(Plan {
        scope,
        entry,
        file,
        claude,
    })
}

/// The rules for everything `mcp install` writes (12.3 step 3): always
/// `--shared`, no secret, and in a project scope no absolute path,
/// `--embed-cmd` or key command.
fn check_rules(entry: &Value, scope: Scope) -> Result<(), String> {
    let args: Vec<&str> = entry["args"]
        .as_array()
        .map(|a| a.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    if !args.contains(&"--shared") {
        return Err("internal: an entry without --shared".into());
    }
    if entry.get("env").is_some() {
        return Err("internal: an entry with an environment".into());
    }
    if scope == Scope::Project {
        let cmd = entry["command"].as_str().unwrap_or("");
        let absolute = |s: &str| Path::new(s).is_absolute() || s.starts_with('~');
        if absolute(cmd) || args.iter().any(|a| absolute(a)) {
            return Err("internal: an absolute path in a project scope".into());
        }
        if args
            .iter()
            .any(|a| a.contains("embed-cmd") || a.contains("KEY_COMMAND"))
        {
            return Err("internal: an embedder or key command in a project scope".into());
        }
    }
    Ok(())
}

// --- An order-keeping JSON object --------------------------------------------

/// A JSON object's members in their order, each value as its original text.
pub(super) struct Ordered(pub(super) Vec<(String, Box<RawValue>)>);

impl<'de> Deserialize<'de> for Ordered {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> Visitor<'de> for V {
            type Value = Ordered;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a JSON object")
            }
            fn visit_map<A: MapAccess<'de>>(self, mut m: A) -> Result<Ordered, A::Error> {
                let mut v = Vec::new();
                while let Some((k, val)) = m.next_entry::<String, Box<RawValue>>()? {
                    v.push((k, val));
                }
                Ok(Ordered(v))
            }
        }
        d.deserialize_map(V)
    }
}

/// Write `members` as an object at `depth` (two spaces a level); each value's
/// own text is kept as it was.
pub(super) fn write_object(members: &[(String, String)], depth: usize) -> String {
    if members.is_empty() {
        return "{}".into();
    }
    let pad = "  ".repeat(depth + 1);
    let body: Vec<String> = members
        .iter()
        .map(|(k, v)| format!("{pad}{}: {v}", Value::String(k.clone())))
        .collect();
    format!("{{\n{}\n{}}}", body.join(",\n"), "  ".repeat(depth))
}

/// `entry` pretty-printed for `depth`.
pub(super) fn pretty_at(entry: &Value, depth: usize) -> String {
    let text = serde_json::to_string_pretty(entry).unwrap();
    let pad = "  ".repeat(depth);
    text.lines()
        .enumerate()
        .map(|(i, l)| {
            if i == 0 {
                l.to_string()
            } else {
                format!("{pad}{l}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The config's new text: `entry` under `mcpServers.<name>`, everything else
/// as it was. Returns it with the old entry, if there was one.
pub(super) fn merged(
    old: &str,
    name: &str,
    entry: &Value,
) -> Result<(String, Option<Value>), String> {
    let top: Ordered = if old.trim().is_empty() {
        Ordered(Vec::new())
    } else {
        serde_json::from_str(old)
            .map_err(|e| format!("can't parse it ({e}); nothing was written"))?
    };
    let mut members: Vec<(String, String)> = Vec::new();
    let mut found_servers = false;
    let mut previous = None;
    for (k, v) in top.0 {
        if k == "mcpServers" {
            found_servers = true;
            let servers: Ordered = serde_json::from_str(v.get()).map_err(|e| {
                format!("its mcpServers isn't an object ({e}); nothing was written")
            })?;
            let mut inner: Vec<(String, String)> = Vec::new();
            let mut replaced = false;
            for (sk, sv) in servers.0 {
                if sk == name {
                    previous = serde_json::from_str(sv.get()).ok();
                    inner.push((sk, pretty_at(entry, 2)));
                    replaced = true;
                } else {
                    inner.push((sk, sv.get().to_string()));
                }
            }
            if !replaced {
                inner.push((name.to_string(), pretty_at(entry, 2)));
            }
            members.push((k, write_object(&inner, 1)));
        } else {
            members.push((k, v.get().to_string()));
        }
    }
    if !found_servers {
        let inner = vec![(name.to_string(), pretty_at(entry, 2))];
        members.push(("mcpServers".into(), write_object(&inner, 1)));
    }
    let text = format!("{}\n", write_object(&members, 0));
    serde_json::from_str::<Value>(&text)
        .map_err(|e| format!("internal: the merge isn't JSON ({e})"))?;
    Ok((text, previous))
}

// --- Showing it ---------------------------------------------------------------

/// `v` with every value under an `env` or `headers` key masked, for display.
pub(super) fn masked(v: &Value) -> Value {
    match v {
        Value::Object(m) => Value::Object(
            m.iter()
                .map(|(k, val)| {
                    let val = if (k == "env" || k == "headers") && val.is_object() {
                        Value::Object(
                            val.as_object()
                                .unwrap()
                                .keys()
                                .map(|kk| (kk.clone(), json!("••••••")))
                                .collect(),
                        )
                    } else {
                        masked(val)
                    };
                    (k.clone(), val)
                })
                .collect(),
        ),
        Value::Array(a) => Value::Array(a.iter().map(masked).collect()),
        other => other.clone(),
    }
}

/// A line diff of `a` against `b` (`-` removed, `+` added, two spaces kept).
pub(super) fn diff(a: &str, b: &str) -> String {
    let (a, b): (Vec<&str>, Vec<&str>) = (a.lines().collect(), b.lines().collect());
    let (n, m) = (a.len(), b.len());
    let mut lcs = vec![vec![0usize; m + 1]; n + 1];
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            lcs[i][j] = if a[i] == b[j] {
                lcs[i + 1][j + 1] + 1
            } else {
                lcs[i + 1][j].max(lcs[i][j + 1])
            };
        }
    }
    let (mut i, mut j, mut out) = (0, 0, String::new());
    while i < n || j < m {
        if i < n && j < m && a[i] == b[j] {
            out.push_str(&format!("  {}\n", a[i]));
            i += 1;
            j += 1;
        } else if j < m && (i == n || lcs[i][j + 1] >= lcs[i + 1][j]) {
            out.push_str(&format!("+ {}\n", b[j]));
            j += 1;
        } else {
            out.push_str(&format!("- {}\n", a[i]));
            i += 1;
        }
    }
    out
}

/// For display, `v` masked further than [`masked`]: a value after a
/// `--passphrase` in `args`, and the user-info and query of a `url`. Used on
/// the entry being replaced, which an older config may have written by hand.
pub(super) fn masked_entry(v: &Value) -> Value {
    let mut v = masked(v);
    if let Some(args) = v.get_mut("args").and_then(Value::as_array_mut) {
        let mut after_flag = false;
        for a in args.iter_mut() {
            if after_flag {
                *a = json!("••••••");
            }
            after_flag = a.as_str() == Some("--passphrase");
        }
    }
    if let Some(url) = v.get_mut("url") {
        if let Some(u) = url.as_str() {
            let mut out = u.to_string();
            if let Some(q) = out.find('?') {
                out.truncate(q);
                out.push_str("?••••••");
            }
            if let Some(scheme) = out.find("://") {
                let rest = &out[scheme + 3..];
                if let Some(at) = rest.find('@').filter(|&at| !rest[..at].contains('/')) {
                    out = format!("{}••••••@{}", &out[..scheme + 3], &rest[at + 1..]);
                }
            }
            *url = json!(out);
        }
    }
    v
}

/// What `mcp install` shows (RB-010.2 Part B): only its own entry, as a diff
/// against the entry it replaces, and how many other servers the file keeps
/// unchanged. Nothing of another server, or of the rest of the file, is
/// printed.
pub(super) fn shown_change(
    old: &str,
    name: &str,
    previous: &Option<Value>,
    entry: &Value,
) -> String {
    let named = |v: &Value| {
        let mut m = serde_json::Map::new();
        m.insert(name.to_string(), v.clone());
        serde_json::to_string_pretty(&Value::Object(m)).unwrap()
    };
    let before = previous
        .as_ref()
        .map(|p| named(&masked_entry(p)))
        .unwrap_or_default();
    let mut out = diff(&before, &named(&masked_entry(entry)));
    // RB-011.2: what the replaced entry had that this one doesn't, by name
    // only (an `env` block's names, never its values).
    if let Some(prev) = previous.as_ref().and_then(Value::as_object) {
        let dropped: Vec<String> = prev
            .iter()
            .filter(|(k, _)| entry.get(k.as_str()).is_none())
            .filter(|(_, v)| !v.as_object().is_some_and(|m| m.is_empty()))
            .map(|(k, v)| match v.as_object() {
                Some(m) => format!(
                    "its `{k}` block: {}",
                    m.keys().cloned().collect::<Vec<_>>().join(", ")
                ),
                None => format!("its `{k}`"),
            })
            .collect();
        if !dropped.is_empty() {
            out.push_str(&format!(
                "(replaces the entry, dropping {})\n",
                dropped.join("; ")
            ));
        }
    }
    let others = serde_json::from_str::<Value>(old)
        .ok()
        .and_then(|v| v.get("mcpServers").and_then(Value::as_object).cloned())
        .map_or(0, |m| m.keys().filter(|k| k.as_str() != name).count());
    out.push_str(&format!(
        "({others} other server{} in the file left unchanged)\n",
        if others == 1 { "" } else { "s" }
    ));
    out
}

/// Ask `question` at the terminal; `true` for yes.
pub(super) fn confirm(question: &str) -> Result<bool, String> {
    use std::io::{BufRead, IsTerminal, Write};
    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
        return Err(
            "not at a terminal, so nothing was written; pass --yes to write without \
                    asking, or --print to see it"
                .into(),
        );
    }
    print!("{question} [y/N] ");
    std::io::stdout().flush().map_err(|e| e.to_string())?;
    let mut line = String::new();
    std::io::stdin()
        .lock()
        .read_line(&mut line)
        .map_err(|e| e.to_string())?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes"))
}

/// Write `text` to `path` atomically: a new temp file beside it, synced,
/// given the old file's mode, then renamed over it.
pub(super) fn write_atomically(path: &Path, text: &str) -> Result<(), String> {
    use std::io::Write;
    let dir = path.parent().ok_or("no parent directory")?;
    std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    let tmp = dir.join(format!(
        ".{}.mnemo-{}.tmp",
        path.file_name().unwrap().to_string_lossy(),
        std::process::id()
    ));
    let result = (|| -> std::io::Result<()> {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)?;
        f.write_all(text.as_bytes())?;
        f.sync_all()?;
        if let Ok(old) = std::fs::metadata(path) {
            std::fs::set_permissions(&tmp, old.permissions())?;
        }
        std::fs::rename(&tmp, path)
    })();
    result.map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        format!("writing {}: {e}", path.display())
    })
}

/// What the server will need for this brain's secret, said once.
pub(super) fn secret_note(brain: &str) -> Option<String> {
    use mnemo_engine::keys::{self, SecretKind};
    let info = keys::file_info(brain).ok()?;
    match info.kind {
        SecretKind::Passphrase => Some(
            "this brain uses a passphrase: the server will need MNEMO_PASSPHRASE in its \
             environment, or the passphrase in the keychain (nothing secret is written to the \
             config)"
                .into(),
        ),
        SecretKind::Key => {
            let stored = keys::default_store()
                .and_then(|s| s.get(&info.salt).ok().flatten())
                .is_some();
            (!stored).then(|| {
                "this brain's key isn't in this machine's keychain: run `mnemo unlock` first, or \
                 give the server MNEMO_KEY or MNEMO_KEY_FILE"
                    .into()
            })
        }
    }
}

/// Offer to move a `MNEMO_PASSPHRASE` the old entry carried into the
/// keychain, at a terminal. `--yes` never moves one. Returns whether the
/// entry can now be written without it.
fn move_passphrase(previous: &Option<Value>, brain: &str, yes: bool) -> Result<(), String> {
    use mnemo_engine::keys::{self, StoredSecret};
    let Some(pp) = previous
        .as_ref()
        .and_then(|p| p.pointer("/env/MNEMO_PASSPHRASE"))
        .and_then(Value::as_str)
    else {
        return Ok(());
    };
    let pp = zeroize::Zeroizing::new(pp.to_string());
    if yes {
        return Err(
            "the entry being replaced holds MNEMO_PASSPHRASE, and --yes never moves it: \
                    run this at a terminal to move it into the keychain, or remove it from the \
                    config first; nothing was written"
                .into(),
        );
    }
    if !confirm("The entry being replaced holds MNEMO_PASSPHRASE. Move it into the keychain?")? {
        return Err("left as it is; nothing was written (the new entry carries no secret)".into());
    }
    let store =
        keys::default_store().ok_or("no keychain is available here; nothing was written")?;
    store.check_available().map_err(|e| e.to_string())?;
    // It must open the brain before it's kept.
    mnemo_engine::Mnemo::open_read_only(brain, &pp)
        .map_err(|e| format!("that passphrase doesn't open {brain} ({e}); nothing was written"))?;
    let info = keys::file_info(brain).map_err(|e| e.to_string())?;
    keys::store_and_check(&*store, &info.salt, &StoredSecret::Passphrase(pp), brain)
        .map_err(|e| e.to_string())?;
    println!("moved MNEMO_PASSPHRASE into {}", store.describe());
    Ok(())
}

/// Run `mcp install`.
pub fn run(o: Install) -> Result<(), String> {
    let p = plan(&o)?;
    let client = client_name(o.client);
    if let Some((claude, dir)) = &p.claude {
        let json = serde_json::to_string(&p.entry).unwrap();
        println!(
            "{client} ({} scope): claude mcp add-json {} '{json}' --scope {}",
            p.scope.word(),
            o.name,
            p.scope.word()
        );
        if o.print {
            return Ok(());
        }
        if !o.yes && !confirm("Run it?")? {
            return Err("nothing was written".into());
        }
        let out = std::process::Command::new(claude)
            .args(["mcp", "add-json", &o.name, &json, "--scope", p.scope.word()])
            .current_dir(dir)
            .output()
            .map_err(|e| format!("running claude: {e}"))?;
        if !out.status.success() {
            return Err(format!(
                "claude mcp add-json failed: {} (if a server named {} is already there, remove \
                 it with `claude mcp remove {} --scope {}`, then run this again)",
                String::from_utf8_lossy(&out.stderr).trim(),
                o.name,
                o.name,
                p.scope.word()
            ));
        }
    } else {
        let path = p.file.clone().unwrap();
        let old = match std::fs::read_to_string(&path) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
            Err(e) => return Err(format!("{}: {e}", path.display())),
        };
        let (new, previous) =
            merged(&old, &o.name, &p.entry).map_err(|e| format!("{}: {e}", path.display()))?;
        println!("{client} ({} scope): {}", p.scope.word(), path.display());
        print!("{}", shown_change(&old, &o.name, &previous, &p.entry));
        if o.print {
            return Ok(());
        }
        move_passphrase(&previous, &o.file, o.yes)?;
        if previous.is_some()
            && !o.yes
            && !confirm(&format!("Replace the server named {}?", o.name))?
        {
            return Err("nothing was written".into());
        }
        if previous.is_none() && !o.yes && !confirm("Write it?")? {
            return Err("nothing was written".into());
        }
        write_atomically(&path, &new)?;
        println!("wrote {}", path.display());
        // 12.2 step 5: a Cursor project file written for the project brain
        // is this user's, so git is told to leave it out.
        if o.project && p.scope == Scope::Project && o.client == Client::Cursor {
            exclude_file(&path);
        }
    }
    if let Some(note) = secret_note(&o.file) {
        eprintln!("note: {note}");
    }
    // RB-010.4 item 4: the server's first start would otherwise fetch the
    // model before it answers the client.
    #[cfg(feature = "embed-candle")]
    if !mnemo_engine::builtin::is_installed() {
        eprintln!(
            "note: the built-in embedder's model ({}) isn't in the cache yet: run `mnemo \
             embedder install` now, or the server's first start fetches it before it answers \
             the client",
            mnemo_engine::builtin::human_size(mnemo_engine::builtin::download_size())
        );
    }
    Ok(())
}

/// List a file in `.git/info/exclude`'s marked block, unless git tracks it.
pub(super) fn exclude_file(path: &Path) {
    use super::project;
    let Some(dir) = path.parent() else { return };
    let (Ok(root), Ok(common)) = (project::toplevel(dir), project::common_dir(dir)) else {
        return;
    };
    let file = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    if project::tracked(&root, &file) {
        eprintln!(
            "note: git tracks {}, so it can't be left out of commits",
            file.display()
        );
        return;
    }
    let Some(line) = project::exclude_line(&root, &file) else {
        return;
    };
    let ex = project::exclude_path(&common);
    let old = std::fs::read_to_string(&ex).unwrap_or_default();
    let new = project::with_excluded(&old, &[line]);
    if new != old {
        if let Err(e) = write_atomically(&ex, &new) {
            eprintln!("note: {e}");
        }
    }
}

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

    #[test]
    fn a_merge_keeps_other_servers_and_their_text() {
        let old = "{\n  \"theme\": \"dark\",\n  \"mcpServers\": {\n    \"other\": {\"command\": \"x\",   \"args\": []}\n  }\n}\n";
        let entry = json!({"command": "mnemo", "args": ["serve", "--mcp", "--shared", "b"]});
        let (new, prev) = merged(old, "mnemo", &entry).unwrap();
        assert!(prev.is_none());
        assert!(
            new.contains("{\"command\": \"x\",   \"args\": []}"),
            "{new}"
        );
        assert!(new.find("theme").unwrap() < new.find("mcpServers").unwrap());
        let v: Value = serde_json::from_str(&new).unwrap();
        assert_eq!(v["mcpServers"]["mnemo"]["args"][2], "--shared");
    }

    #[test]
    fn env_and_headers_are_masked_for_display() {
        let v = json!({"mcpServers": {"a": {"env": {"MNEMO_PASSPHRASE": "hunter2"}, "headers": {"Authorization": "Bearer t"}}}});
        let s = serde_json::to_string(&masked(&v)).unwrap();
        assert!(!s.contains("hunter2") && !s.contains("Bearer"), "{s}");
        assert!(s.contains("MNEMO_PASSPHRASE"));
    }
}