omh 0.2.0

Launch any coding harness, in a sandbox, with your setup already there.
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Settings with provenance.
//!
//! Three layers means the useful question is never "what is this set to" but
//! "which layer is it coming from, and what is it shadowing". So the resolver
//! reports origin alongside every value, the way `git config --show-origin`
//! does — otherwise a three-layer merge is undebuggable.

use crate::adapter::Render;
use crate::profile::Paths;
use crate::render::Server;
use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Layer {
    /// `~/.omh/profile` — yours, every project.
    Personal,
    /// `<repo>/.omh/profile` — committed, shared with the team.
    Shared,
    /// `<repo>/.omh/local` — gitignored, yours alone.
    Local,
}

/// A resolved setting: the winning value, where it came from, and what it beat.
#[derive(Debug, PartialEq)]
pub struct Setting {
    pub key: String,
    pub value: String,
    pub layer: Layer,
    /// Layers that also declared this key but lost. Always lower precedence.
    pub shadows: Vec<Layer>,
}

/// Where a write landed, and whether that location is under version control.
#[derive(Debug, PartialEq)]
pub struct Written {
    pub path: PathBuf,
    pub layer: Layer,
    pub committed: bool,
}

impl Layer {
    pub const ALL: [Layer; 3] = [Self::Personal, Self::Shared, Self::Local];

    /// `omh set` with no `--layer` writes here: a mistyped secret must not be
    /// committable by accident.
    pub const DEFAULT_WRITE: Layer = Self::Local;

    pub fn dir(&self, paths: &Paths) -> PathBuf {
        match self {
            Self::Personal => paths.root.join("profile"),
            Self::Shared => paths.repo.join(".omh/profile"),
            Self::Local => paths.repo.join(".omh/local"),
        }
    }

    /// Only the shared layer is under version control.
    pub fn is_committed(&self) -> bool {
        matches!(self, Self::Shared)
    }
}

impl std::str::FromStr for Layer {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self> {
        Layer::ALL
            .into_iter()
            .find(|l| l.to_string() == s)
            .with_context(|| format!("unknown layer `{s}` — expected personal, shared, or local"))
    }
}

impl std::fmt::Display for Layer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Personal => "personal",
            Self::Shared => "shared",
            Self::Local => "local",
        })
    }
}

/// Every `policy.toml` key across all layers, resolved with provenance.
pub fn policy(paths: &Paths) -> Result<Vec<Setting>> {
    let mut found = Vec::new();
    for layer in Layer::ALL {
        let path = layer.dir(paths).join("policy.toml");
        let Some(raw) = read_layer(&path)? else {
            continue;
        };
        let table: toml::Table =
            toml::from_str(&raw).with_context(|| format!("parsing {}", path.display()))?;
        for (key, value) in table {
            found.push((key, repr(&value), layer));
        }
    }
    Ok(resolve(found))
}

/// Read a layer's file, distinguishing "this layer declares nothing" from
/// "this layer could not be read".
///
/// `let Ok(..) else { continue }` conflated them, and the second case is
/// unrecoverable from the outside: `chmod 000` on `mcp.json` made `omh why`
/// answer "not installed here" about an installed server and advise `omh init`
/// — which does nothing, because `write_if_absent` sees the file exists. A
/// closed loop, exit 0, no error anywhere.
fn read_layer(path: &Path) -> Result<Option<String>> {
    match std::fs::read_to_string(path) {
        Ok(raw) => Ok(Some(raw)),
        // Absent is a normal, expected state: most layers declare most things
        // not at all.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

/// Every hook across all layers, resolved with provenance.
///
/// Same shape as [`servers`] deliberately: `omh why` treats an MCP server and a
/// hook as the same kind of thing — something installed, from some layer, that
/// omh either chose or you did. `render::merge_hooks` merges for *rendering*
/// and drops the layer, which is the one fact this needs.
pub fn hooks(paths: &Paths) -> Result<Vec<Setting>> {
    let mut found = Vec::new();
    for layer in Layer::ALL {
        let dir = layer.dir(paths).join("hooks");
        let entries = match std::fs::read_dir(&dir) {
            Ok(entries) => entries,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(e).with_context(|| format!("reading {}", dir.display())),
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.extension().is_some_and(|e| e == "json") {
                continue;
            }
            let raw = std::fs::read_to_string(&path)
                .with_context(|| format!("reading {}", path.display()))?;
            let doc: serde_json::Value = serde_json::from_str(&raw)
                .with_context(|| format!("parsing {}", path.display()))?;
            let name = path
                .file_stem()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string();
            // Not `unwrap_or("")`. An empty command compares unequal to every
            // baseline, so a hook file that is truncated, half-written, or
            // hand-edited with the wrong key was reported to the user as
            // "modified by you" — a false accusation, with a blank value as the
            // only tell, from the one command whose job is telling authorship
            // straight. `render.rs` treats the same file as a hard error, so
            // two subsystems told two stories about it.
            let command = doc
                .get("command")
                .and_then(|c| c.as_str())
                .with_context(|| {
                    format!(
                        "{} has no `command` string — it is not a usable hook",
                        path.display()
                    )
                })?;
            found.push((name, command.to_string(), layer));
        }
    }
    Ok(resolve(found))
}

/// Every MCP server across all layers, resolved with provenance.
pub fn servers(paths: &Paths) -> Result<Vec<Setting>> {
    let mut found = Vec::new();
    for layer in Layer::ALL {
        let path = layer.dir(paths).join("mcp.json");
        let Some(raw) = read_layer(&path)? else {
            continue;
        };
        let doc: serde_json::Value =
            serde_json::from_str(&raw).with_context(|| format!("parsing {}", path.display()))?;
        let Some(servers) = doc.get("mcpServers").and_then(|v| v.as_object()) else {
            continue;
        };
        for (name, spec) in servers {
            let command = spec.get("command").and_then(|c| c.as_str()).unwrap_or("");
            found.push((name.clone(), command.to_string(), layer));
        }
    }
    Ok(resolve(found))
}

pub fn set(paths: &Paths, key: &str, raw: &str, layer: Layer) -> Result<Written> {
    let path = layer.dir(paths).join("policy.toml");
    let mut table = read_table(&path)?;
    table.insert(key.to_string(), parse_value(raw));
    std::fs::create_dir_all(path.parent().unwrap())?;
    std::fs::write(&path, toml::to_string_pretty(&table)?)?;
    Ok(Written {
        path,
        layer,
        committed: layer.is_committed(),
    })
}

pub fn unset(paths: &Paths, key: &str, layer: Layer) -> Result<bool> {
    let path = layer.dir(paths).join("policy.toml");
    let mut table = read_table(&path)?;
    if table.remove(key).is_none() {
        return Ok(false);
    }
    std::fs::write(&path, toml::to_string_pretty(&table)?)?;
    Ok(true)
}

/// Last layer wins; every earlier declaration of the same key is recorded as
/// shadowed. Without that trail a three-layer merge cannot be debugged.
fn resolve(found: Vec<(String, String, Layer)>) -> Vec<Setting> {
    let mut by_key: BTreeMap<String, Vec<(String, Layer)>> = BTreeMap::new();
    for (key, value, layer) in found {
        by_key.entry(key).or_default().push((value, layer));
    }
    by_key
        .into_iter()
        .map(|(key, mut hits)| {
            let (value, layer) = hits.pop().expect("entry exists because it was inserted");
            Setting {
                key,
                value,
                layer,
                shadows: hits.into_iter().map(|(_, l)| l).collect(),
            }
        })
        .collect()
}

fn read_table(path: &Path) -> Result<toml::Table> {
    match std::fs::read_to_string(path) {
        Ok(raw) => toml::from_str(&raw).with_context(|| format!("parsing {}", path.display())),
        Err(_) => Ok(toml::Table::new()),
    }
}

/// Accept TOML literals (`["a", "b"]`, `true`, `30`) and fall back to a bare
/// string, so `omh set idle_timeout 30m` does not need quoting.
fn parse_value(raw: &str) -> toml::Value {
    toml::from_str::<toml::Table>(&format!("v = {raw}"))
        .ok()
        .and_then(|t| t.get("v").cloned())
        .unwrap_or_else(|| toml::Value::String(raw.to_string()))
}

fn repr(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

// ── MCP servers ─────────────────────────────────────────────────────────────

/// What an import did, or would do. Reported rather than assumed, because
/// import pulls config you did not type into a file you will commit.
#[derive(Debug, Default, PartialEq)]
pub struct Imported {
    pub added: Vec<String>,
    /// Present already with different settings. Skipped unless forced.
    pub conflicts: Vec<String>,
    /// Present already, byte-identical. Import is idempotent.
    pub unchanged: Vec<String>,
}

pub fn mcp_add(paths: &Paths, layer: Layer, name: &str, server: Server) -> Result<Written> {
    let path = mcp_path(paths, layer);
    let mut all = read_servers(&path)?;
    all.insert(name.to_string(), server);
    write_servers(&path, &all)?;
    Ok(Written {
        path,
        layer,
        committed: layer.is_committed(),
    })
}

pub fn mcp_remove(paths: &Paths, layer: Layer, name: &str) -> Result<bool> {
    let path = mcp_path(paths, layer);
    let mut all = read_servers(&path)?;
    if all.remove(name).is_none() {
        return Ok(false);
    }
    write_servers(&path, &all)?;
    Ok(true)
}

/// `dry_run` reports the same plan without writing.
pub fn mcp_import(
    paths: &Paths,
    layer: Layer,
    incoming: BTreeMap<String, Server>,
    force: bool,
    dry_run: bool,
) -> Result<Imported> {
    let path = mcp_path(paths, layer);
    let mut all = read_servers(&path)?;
    let mut report = Imported::default();

    for (name, server) in incoming {
        match all.get(&name) {
            // Identical: import stays idempotent and re-runnable.
            Some(existing) if *existing == server => report.unchanged.push(name),
            // Different: never clobber config the user wrote by hand.
            Some(_) if !force => report.conflicts.push(name),
            _ => {
                all.insert(name.clone(), server);
                report.added.push(name);
            }
        }
    }

    if !dry_run && !report.added.is_empty() {
        write_servers(&path, &all)?;
    }
    Ok(report)
}

fn mcp_path(paths: &Paths, layer: Layer) -> PathBuf {
    layer.dir(paths).join("mcp.json")
}

/// A layer's canonical file is itself `mcp-json`, so reading it is the same
/// parser import uses — one code path, one set of round-trip tests.
fn read_servers(path: &Path) -> Result<BTreeMap<String, Server>> {
    match std::fs::read_to_string(path) {
        Ok(raw) => crate::render::parse(Render::McpJson, &raw)
            .with_context(|| format!("reading {}", path.display())),
        Err(_) => Ok(BTreeMap::new()),
    }
}

fn write_servers(path: &Path, servers: &BTreeMap<String, Server>) -> Result<()> {
    std::fs::create_dir_all(path.parent().unwrap())?;
    let doc = serde_json::json!({ "mcpServers": servers });
    std::fs::write(path, serde_json::to_string_pretty(&doc)? + "\n")?;
    Ok(())
}

/// A policy value that is a list. `policy()` renders values for display, so an
/// array arrives as its TOML text and has to be parsed back.
pub fn policy_list(paths: &Paths, key: &str) -> Vec<String> {
    let Some(repr) = policy(paths)
        .ok()
        .and_then(|s| s.into_iter().find(|s| s.key == key))
    else {
        return Vec::new();
    };
    toml::from_str::<toml::Table>(&format!("v = {}", repr.value))
        .ok()
        .and_then(|t| t.get("v").and_then(|v| v.as_array()).cloned())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

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

    fn fixture() -> (tempfile::TempDir, Paths) {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        (dir, paths)
    }

    fn seed(paths: &Paths, layer: Layer, name: &str, body: &str) {
        let p = layer.dir(paths).join(name);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, body).unwrap();
    }

    // ── hooks ───────────────────────────────────────────────────────────────
    //
    // `hooks()` shipped with no tests at all while being the sole input to
    // `omh why`'s hook answers. Its body could be replaced with
    // `Ok(Vec::new())` and the whole suite stayed green — at which point every
    // installed hook reports as "not installed here".

    #[test]
    fn hooks_resolve_with_the_layer_they_came_from() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "hooks/graph-read.json",
            r#"{"command":"a"}"#,
        );
        seed(
            &paths,
            Layer::Local,
            "hooks/mine.json",
            r#"{"command":"b"}"#,
        );

        let found = hooks(&paths).unwrap();
        let by = |k: &str| {
            found
                .iter()
                .find(|s| s.key == k)
                .unwrap_or_else(|| panic!("{k}"))
        };
        assert_eq!(by("graph-read").value, "a");
        assert_eq!(by("graph-read").layer, Layer::Shared);
        assert_eq!(by("mine").layer, Layer::Local);
    }

    #[test]
    fn a_later_layer_wins_and_names_what_it_shadowed() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "hooks/x.json",
            r#"{"command":"shared"}"#,
        );
        seed(
            &paths,
            Layer::Local,
            "hooks/x.json",
            r#"{"command":"local"}"#,
        );

        let found = hooks(&paths).unwrap();
        let x = found.iter().find(|s| s.key == "x").unwrap();
        assert_eq!(x.value, "local");
        assert_eq!(x.shadows, vec![Layer::Shared]);
    }

    /// A hook file with no `command` used to become an empty string, which
    /// compares unequal to every baseline — so a truncated or hand-edited file
    /// was reported to the user as their own edit, with a blank value as the
    /// only tell. `render.rs` treats the same file as a hard error, so the two
    /// subsystems told two different stories about it.
    #[test]
    fn a_hook_without_a_command_is_an_error_not_an_empty_string() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "hooks/broken.json",
            r#"{"event":"Stop"}"#,
        );

        let err = hooks(&paths).unwrap_err().to_string();
        assert!(err.contains("broken.json"), "must name the file: {err}");
        assert!(err.contains("command"), "must say what is missing: {err}");
    }

    /// A layer that cannot be read is not a layer that declares nothing.
    ///
    /// Conflating them produced a closed loop: `chmod 000` on `mcp.json` made
    /// `omh why` report an installed server as "not installed here" and advise
    /// `omh init`, which does nothing because `write_if_absent` sees the file.
    /// Exit 0, no error, and no way out from the outside.
    #[cfg(unix)]
    #[test]
    fn an_unreadable_layer_is_an_error_not_an_absent_one() {
        use std::os::unix::fs::PermissionsExt;
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "mcp.json",
            r#"{"mcpServers":{"codegraph":{"command":"c"}}}"#,
        );
        let path = Layer::Shared.dir(&paths).join("mcp.json");
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();

        let result = servers(&paths);
        // Restore before asserting, so a failure does not leave a locked file.
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();

        let err = result
            .expect_err("an unreadable layer must not read as empty")
            .to_string();
        assert!(err.contains("mcp.json"), "must name the file: {err}");
    }

    /// The other half: absent really is normal, and must stay silent. Most
    /// layers declare most things not at all.
    #[test]
    fn an_absent_layer_is_not_an_error() {
        let (_d, paths) = fixture();
        assert!(servers(&paths).unwrap().is_empty());
        assert!(policy(&paths).unwrap().is_empty());
        assert!(hooks(&paths).unwrap().is_empty());
    }

    #[test]
    fn a_non_json_file_in_the_hooks_directory_is_ignored() {
        let (_d, paths) = fixture();
        seed(&paths, Layer::Shared, "hooks/notes.md", "not a hook");
        seed(
            &paths,
            Layer::Shared,
            "hooks/real.json",
            r#"{"command":"c"}"#,
        );

        let found = hooks(&paths).unwrap();
        assert_eq!(found.len(), 1, "got: {found:?}");
        assert_eq!(found[0].key, "real");
    }

    fn get<'a>(settings: &'a [Setting], key: &str) -> &'a Setting {
        settings
            .iter()
            .find(|s| s.key == key)
            .unwrap_or_else(|| panic!("no key {key}"))
    }

    // ── layers ──────────────────────────────────────────────────────────────

    #[test]
    fn only_the_shared_layer_is_committed() {
        assert!(Layer::Shared.is_committed());
        assert!(!Layer::Personal.is_committed());
        assert!(!Layer::Local.is_committed(), "local must be gitignored");
    }

    #[test]
    fn layers_map_to_their_directories() {
        let (_d, paths) = fixture();
        assert_eq!(Layer::Personal.dir(&paths), paths.root.join("profile"));
        assert_eq!(Layer::Shared.dir(&paths), paths.repo.join(".omh/profile"));
        assert_eq!(Layer::Local.dir(&paths), paths.repo.join(".omh/local"));
    }

    #[test]
    fn layers_round_trip_through_their_names() {
        for layer in Layer::ALL {
            assert_eq!(Layer::from_str(&layer.to_string()).unwrap(), layer);
        }
        assert!(Layer::from_str("nonsense").is_err());
    }

    // ── provenance ──────────────────────────────────────────────────────────

    #[test]
    fn policy_reports_the_winning_layer() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Personal,
            "policy.toml",
            "idle_timeout = \"30m\"",
        );
        let settings = policy(&paths).unwrap();
        assert_eq!(get(&settings, "idle_timeout").layer, Layer::Personal);
    }

    #[test]
    fn later_layers_win_and_the_loser_is_named() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Personal,
            "policy.toml",
            "idle_timeout = \"30m\"",
        );
        seed(
            &paths,
            Layer::Shared,
            "policy.toml",
            "idle_timeout = \"5m\"",
        );
        seed(&paths, Layer::Local, "policy.toml", "idle_timeout = \"2h\"");

        let s = policy(&paths).unwrap();
        let t = get(&s, "idle_timeout");
        assert_eq!(t.value, "2h", "local wins");
        assert_eq!(t.layer, Layer::Local);
        assert_eq!(
            t.shadows,
            vec![Layer::Personal, Layer::Shared],
            "a value that beat others must say so, or the merge is undebuggable"
        );
    }

    #[test]
    fn unshadowed_settings_report_no_losers() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "policy.toml",
            "carry_in = [\".env\"]",
        );
        assert!(get(&policy(&paths).unwrap(), "carry_in").shadows.is_empty());
    }

    #[test]
    fn missing_layers_are_not_an_error() {
        let (_d, paths) = fixture();
        assert!(policy(&paths).unwrap().is_empty());
        assert!(servers(&paths).unwrap().is_empty());
    }

    #[test]
    fn mcp_servers_resolve_with_provenance() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "mcp.json",
            r#"{"mcpServers":{"codegraph":{"command":"codebase-memory-mcp"}}}"#,
        );
        seed(
            &paths,
            Layer::Local,
            "mcp.json",
            r#"{"mcpServers":{"omh-memory":{"command":"omh-mcp"}}}"#,
        );

        let s = servers(&paths).unwrap();
        assert_eq!(s.len(), 2);
        assert_eq!(get(&s, "codegraph").layer, Layer::Shared);
        assert_eq!(get(&s, "omh-memory").layer, Layer::Local);
        assert_eq!(get(&s, "codegraph").value, "codebase-memory-mcp");
    }

    #[test]
    fn a_local_server_can_shadow_a_shared_one() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "mcp.json",
            r#"{"mcpServers":{"codegraph":{"command":"old"}}}"#,
        );
        seed(
            &paths,
            Layer::Local,
            "mcp.json",
            r#"{"mcpServers":{"codegraph":{"command":"new"}}}"#,
        );

        let s = servers(&paths).unwrap();
        assert_eq!(s.len(), 1);
        assert_eq!(get(&s, "codegraph").value, "new");
        assert_eq!(get(&s, "codegraph").shadows, vec![Layer::Shared]);
    }

    // ── writes ──────────────────────────────────────────────────────────────

    /// The safety property: an unqualified write can never reach version control.
    #[test]
    fn default_write_target_is_gitignored() {
        assert_eq!(Layer::DEFAULT_WRITE, Layer::Local);
        assert!(!Layer::DEFAULT_WRITE.is_committed());
    }

    #[test]
    fn set_creates_the_layer_file_when_absent() {
        let (_d, paths) = fixture();
        let w = set(&paths, "idle_timeout", "30m", Layer::DEFAULT_WRITE).unwrap();
        assert_eq!(w.path, Layer::Local.dir(&paths).join("policy.toml"));
        assert!(!w.committed);
        assert_eq!(get(&policy(&paths).unwrap(), "idle_timeout").value, "30m");
    }

    /// Writing to the committed layer must be flagged, because that is the one
    /// mistake git makes unrecoverable.
    #[test]
    fn writing_to_the_shared_layer_is_flagged_as_committed() {
        let (_d, paths) = fixture();
        let w = set(&paths, "carry_in", "[\".env\"]", Layer::Shared).unwrap();
        assert!(w.committed);
        assert_eq!(w.layer, Layer::Shared);
    }

    #[test]
    fn set_preserves_unrelated_keys() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Local,
            "policy.toml",
            "carry_in = [\".env\"]\nidle_timeout = \"5m\"",
        );
        set(&paths, "idle_timeout", "1h", Layer::Local).unwrap();

        let s = policy(&paths).unwrap();
        assert_eq!(get(&s, "idle_timeout").value, "1h");
        assert_eq!(
            get(&s, "carry_in").value,
            "[\".env\"]",
            "must not clobber siblings"
        );
    }

    #[test]
    fn set_accepts_arrays_as_well_as_scalars() {
        let (_d, paths) = fixture();
        set(&paths, "carry_in", "[\".env\", \"certs/\"]", Layer::Local).unwrap();
        assert_eq!(
            get(&policy(&paths).unwrap(), "carry_in").value,
            "[\".env\", \"certs/\"]"
        );
    }

    #[test]
    fn unset_touches_only_the_named_layer() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Personal,
            "policy.toml",
            "idle_timeout = \"30m\"",
        );
        seed(&paths, Layer::Local, "policy.toml", "idle_timeout = \"2h\"");

        assert!(unset(&paths, "idle_timeout", Layer::Local).unwrap());

        let resolved = policy(&paths).unwrap();
        let t = get(&resolved, "idle_timeout");
        assert_eq!(t.value, "30m", "the personal layer must resurface");
        assert_eq!(t.layer, Layer::Personal);
    }

    #[test]
    fn unset_reports_when_nothing_was_removed() {
        let (_d, paths) = fixture();
        assert!(!unset(&paths, "absent", Layer::Local).unwrap());
    }

    // ── mcp add / rm ────────────────────────────────────────────────────────

    fn server(command: &str) -> Server {
        Server {
            command: command.into(),
            args: vec![],
            env: BTreeMap::new(),
        }
    }

    fn names(paths: &Paths) -> Vec<String> {
        servers(paths).unwrap().into_iter().map(|s| s.key).collect()
    }

    #[test]
    fn mcp_add_creates_the_file_when_absent() {
        let (_d, paths) = fixture();
        let w = mcp_add(&paths, Layer::DEFAULT_WRITE, "g", server("c")).unwrap();
        assert_eq!(w.path, Layer::Local.dir(&paths).join("mcp.json"));
        assert_eq!(names(&paths), ["g"]);
    }

    /// MCP entries carry env, and env carries tokens. An unqualified add must
    /// land somewhere git will never see.
    #[test]
    fn mcp_add_defaults_to_the_gitignored_layer() {
        let (_d, paths) = fixture();
        let w = mcp_add(&paths, Layer::DEFAULT_WRITE, "g", server("c")).unwrap();
        assert!(!w.committed);
        assert_eq!(w.layer, Layer::Local);
    }

    #[test]
    fn mcp_add_to_the_shared_layer_is_flagged_as_committed() {
        let (_d, paths) = fixture();
        assert!(
            mcp_add(&paths, Layer::Shared, "g", server("c"))
                .unwrap()
                .committed
        );
    }

    #[test]
    fn mcp_add_preserves_existing_servers() {
        let (_d, paths) = fixture();
        mcp_add(&paths, Layer::Local, "first", server("a")).unwrap();
        mcp_add(&paths, Layer::Local, "second", server("b")).unwrap();
        assert_eq!(names(&paths), ["first", "second"]);
    }

    #[test]
    fn mcp_rm_touches_only_the_named_layer() {
        let (_d, paths) = fixture();
        mcp_add(&paths, Layer::Shared, "g", server("shared-cmd")).unwrap();
        mcp_add(&paths, Layer::Local, "g", server("local-cmd")).unwrap();

        assert!(mcp_remove(&paths, Layer::Local, "g").unwrap());

        let resolved = servers(&paths).unwrap();
        let g = get(&resolved, "g");
        assert_eq!(g.value, "shared-cmd", "the shared layer must resurface");
        assert_eq!(g.layer, Layer::Shared);
    }

    #[test]
    fn mcp_rm_reports_when_nothing_was_removed() {
        let (_d, paths) = fixture();
        assert!(!mcp_remove(&paths, Layer::Local, "absent").unwrap());
    }

    // ── import ──────────────────────────────────────────────────────────────

    fn incoming() -> BTreeMap<String, Server> {
        BTreeMap::from([
            ("a".to_string(), server("a-cmd")),
            ("b".to_string(), server("b-cmd")),
        ])
    }

    #[test]
    fn import_reports_what_it_would_add() {
        let (_d, paths) = fixture();
        let r = mcp_import(&paths, Layer::Local, incoming(), false, false).unwrap();
        assert_eq!(r.added, ["a", "b"]);
        assert!(r.conflicts.is_empty() && r.unchanged.is_empty());
        assert_eq!(names(&paths), ["a", "b"]);
    }

    #[test]
    fn dry_run_writes_nothing() {
        let (_d, paths) = fixture();
        let r = mcp_import(&paths, Layer::Local, incoming(), false, true).unwrap();
        assert_eq!(r.added, ["a", "b"], "the plan is still reported");
        assert!(names(&paths).is_empty(), "but nothing was written");
    }

    /// Re-importing the same config must be a no-op, not a duplicate or a churn
    /// of the file — otherwise `omh mcp import` is unsafe to re-run.
    #[test]
    fn importing_twice_changes_nothing() {
        let (_d, paths) = fixture();
        mcp_import(&paths, Layer::Local, incoming(), false, false).unwrap();
        let second = mcp_import(&paths, Layer::Local, incoming(), false, false).unwrap();
        assert_eq!(second.unchanged, ["a", "b"]);
        assert!(second.added.is_empty());
    }

    #[test]
    fn a_changed_server_is_a_conflict_not_a_silent_overwrite() {
        let (_d, paths) = fixture();
        mcp_add(&paths, Layer::Local, "a", server("mine")).unwrap();

        let r = mcp_import(&paths, Layer::Local, incoming(), false, false).unwrap();
        assert_eq!(r.conflicts, ["a"]);
        assert_eq!(r.added, ["b"], "unconflicted servers still import");
        assert_eq!(
            get(&servers(&paths).unwrap(), "a").value,
            "mine",
            "kept, not clobbered"
        );
    }

    #[test]
    fn force_resolves_a_conflict_by_overwriting() {
        let (_d, paths) = fixture();
        mcp_add(&paths, Layer::Local, "a", server("mine")).unwrap();

        let r = mcp_import(&paths, Layer::Local, incoming(), true, false).unwrap();
        assert_eq!(r.added, ["a", "b"]);
        assert!(r.conflicts.is_empty());
        assert_eq!(get(&servers(&paths).unwrap(), "a").value, "a-cmd");
    }

    #[test]
    fn importing_nothing_is_not_an_error() {
        let (_d, paths) = fixture();
        assert_eq!(
            mcp_import(&paths, Layer::Local, BTreeMap::new(), false, false).unwrap(),
            Imported::default()
        );
    }

    #[test]
    fn a_list_setting_comes_back_as_a_list() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Shared,
            "policy.toml",
            "carry_in = [\".env\", \"certs/\"]",
        );
        assert_eq!(policy_list(&paths, "carry_in"), vec![".env", "certs/"]);
    }

    #[test]
    fn an_absent_list_is_empty_not_an_error() {
        let (_d, paths) = fixture();
        assert!(policy_list(&paths, "carry_in").is_empty());
    }

    /// Layers merge as usual, so a project can narrow or widen what a personal
    /// default carries.
    #[test]
    fn a_later_layer_replaces_the_list() {
        let (_d, paths) = fixture();
        seed(
            &paths,
            Layer::Personal,
            "policy.toml",
            "carry_in = [\".env\"]",
        );
        seed(
            &paths,
            Layer::Local,
            "policy.toml",
            "carry_in = [\".env.local\"]",
        );
        assert_eq!(policy_list(&paths, "carry_in"), vec![".env.local"]);
    }
}