omh 0.3.1

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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
//! `omh why` — who put this here, and on what grounds.
//!
//! An opinionated tool's characteristic failure is opacity: "without the hassle
//! of understanding" curdling into "unable to understand". `omh config` answers
//! *where* a value came from; this answers *why*, and for whose reasons.
//!
//! The distinction that matters is authorship. omh's own choices carry a
//! rationale, a measured cost, what was considered instead, and a way out. Your
//! choices carry provenance and **nothing else** — a tool that answers "because
//! it is in the base set" about something you added yourself is lying about its
//! own authorship, and being able to tell the two apart is the whole feature.
//!
//! Authorship is *derived*, never recorded. The base set is seeded into your
//! profile at `init` and then lives as ordinary config, so an omh entry and one
//! of yours are byte-identical in the same file. Comparing against the manifest
//! recovers the distinction without a marker that could go stale — and comparing
//! the value as well as the name yields the state people actually want to know
//! about: that they are running a modified default.

use crate::base::{Entry, Manifest, Rejected};
use crate::config::{Layer, Setting};
use std::collections::{BTreeMap, BTreeSet};

/// What omh knows, assembled from the manifest and the resolved profile.
pub struct Catalog<'a> {
    pub manifest: &'a Manifest,
    /// Name → exactly what omh ships, for deciding whether your copy is
    /// modified. Only MCP servers are compared: everything else omh ships is
    /// generated at launch, so there is no copy of yours for it to differ
    /// from — a file of that name is a leftover, and `Generated` says so.
    pub baselines: BTreeMap<String, String>,
    /// What is actually installed, with the layer it won in.
    pub installed: Vec<Setting>,
    /// Name → what `init` would have written for a detected stack: omh's
    /// writing, but not omh's opinion.
    ///
    /// Carries the command and layer, not just a label, because the name alone
    /// proves nothing — anyone can create `rust-test.json`.
    pub derived: BTreeMap<String, Derived>,
    /// Features this repo has switched off. Not a property of the entry —
    /// `omh why` answers about the base set and about *here*, and an answer
    /// that explains why something is installed while it is disabled three
    /// feet away is only half true.
    pub off: BTreeSet<String>,
}

/// What `init` writes for a detected stack, and where.
#[derive(Debug, Clone, PartialEq)]
pub struct Derived {
    /// e.g. "rust, detected from Cargo.toml"
    pub from: String,
    /// The command `init` would have written — `stack.test` or `stack.format`.
    pub command: String,
    /// Always the shared layer. `init` writes nowhere else, so a hook in
    /// `local` was not written by `init` whatever it is called.
    pub layer: Layer,
}

#[derive(Debug)]
pub enum Verdict<'a> {
    /// omh chose it and your copy matches what omh ships.
    Omh {
        entry: &'a Entry,
        yours: &'a Setting,
    },
    /// omh chose it, and the copy on disk is not what omh ships **now**.
    ///
    /// Deliberately not called "modified by you". omh cannot tell who changed
    /// it: `init` seeds the profile with `write_if_absent` and never revisits
    /// it, while the shipped baseline moves with every release. So the first
    /// omh upgrade that touches a hook command makes every existing profile
    /// differ — and the previous version of this verdict told all those users
    /// they had edited a file they never opened.
    ///
    /// Naming the difference is honest and useful. Naming a culprit is neither.
    Differs {
        entry: &'a Entry,
        ships: String,
        yours: &'a Setting,
    },
    /// omh chose it and it is not in your profile — removed, or `init` has not
    /// run. Not an error: leaving is supposed to be easy.
    Removed { entry: &'a Entry },
    /// omh generates it from the manifest at launch. It is not a file
    /// anywhere, which is the point — a hook you can edit is a hook omh can
    /// never ship a fix to.
    ///
    /// `stale` is a copy an older omh seeded, still on disk and no longer
    /// read. Carried rather than ignored: reporting it as what runs would be a
    /// confident wrong answer, and not mentioning it leaves somebody editing a
    /// file with no effect.
    Generated {
        entry: &'a Entry,
        stale: Option<&'a Setting>,
    },
    /// omh wrote it, from your repo rather than from its opinion. Nothing to
    /// argue about and nothing curated — `cargo fmt` is just what formats Rust.
    Derived { yours: &'a Setting, from: String },
    /// Yours. omh has no rationale for this and will not invent one.
    Yours { yours: &'a Setting },
    /// Considered and turned down. Recorded so the same candidate is not
    /// re-litigated every time somebody rediscovers it.
    Rejected { rejection: &'a Rejected },
    /// A feature with no entry of its own — `git-notice` names the pairing of
    /// a hook and a rules section, and nothing is called that.
    ///
    /// Answerable because feature names are user-facing: they are the whole
    /// `[omh]` key space, and the manifest prints `git-notice = false` as the
    /// way out of `git-unavailable`. A name omh tells you to type and then
    /// does not recognise is this command's own failure mode, pointing inward.
    Feature {
        name: String,
        gathers: Vec<&'a Entry>,
    },
    /// Nothing known. Lists what is, rather than guessing.
    Unknown { known: Vec<String> },
}

impl<'a> Catalog<'a> {
    pub fn why(&'a self, name: &str) -> Verdict<'a> {
        let entry = self.manifest.entry(name);
        let yours = self.installed.iter().find(|s| s.key == name);

        // Resolved before the file lookup, because for these the file is not
        // the answer even when there is one.
        if let Some(entry) = entry.filter(|e| e.kind != crate::base::Kind::Mcp) {
            return Verdict::Generated {
                entry,
                stale: yours,
            };
        }

        match (entry, yours) {
            (Some(entry), Some(yours)) => match self.baselines.get(name) {
                // A baseline that matches means untouched. A baseline omh does
                // not have means it cannot claim you changed anything, so the
                // quiet answer is the honest one.
                Some(ships) if ships != &yours.value => Verdict::Differs {
                    entry,
                    ships: ships.clone(),
                    yours,
                },
                _ => Verdict::Omh { entry, yours },
            },
            (Some(entry), None) => Verdict::Removed { entry },
            // A name match alone is not evidence omh wrote this. `init` writes
            // stack hooks only into the *shared* layer and only with the
            // command detection produced, so both are checkable — and a
            // hand-written `rust-test.json` in `local` was being reported as
            // "written by omh init", which is the same lie about authorship
            // this module exists to prevent, pointing the other way.
            (None, Some(yours)) => match self.derived.get(name) {
                Some(d) if d.layer == yours.layer && d.command == yours.value => Verdict::Derived {
                    yours,
                    from: d.from.clone(),
                },
                _ => Verdict::Yours { yours },
            },
            (None, None) => match self.manifest.rejection(name) {
                Some(rejection) => Verdict::Rejected { rejection },
                None => {
                    let gathers: Vec<&Entry> = self
                        .manifest
                        .entries
                        .iter()
                        .filter(|e| e.feature == name)
                        .collect();
                    if gathers.is_empty() {
                        Verdict::Unknown {
                            known: self.known(),
                        }
                    } else {
                        Verdict::Feature {
                            name: name.to_string(),
                            gathers,
                        }
                    }
                }
            },
        }
    }

    /// Everything answerable, for when a name matches nothing. Guessing what
    /// somebody meant would send them to the wrong explanation, which is worse
    /// than admitting ignorance.
    fn known(&self) -> Vec<String> {
        let mut names: Vec<String> = self
            .manifest
            .entries
            .iter()
            .map(|e| e.name.clone())
            // Features too: they are the `[omh]` key space and the manifest
            // instructs people to type them, so a list that omits them sends
            // somebody looking for a name omh itself printed.
            .chain(self.manifest.entries.iter().map(|e| e.feature.clone()))
            .chain(self.installed.iter().map(|s| s.key.clone()))
            .chain(self.manifest.rejected.iter().map(|r| r.name.clone()))
            .collect();
        names.sort();
        names.dedup();
        names
    }
}

/// Whether a measurement predates the base set it is shipped in.
///
/// Compared against the **manifest version**, not the entry's `since`. Against
/// `since` this could essentially never fire: a measurement is taken at or
/// after the entry was added, and `since` never moves, so no shipped number was
/// flaggable in 2027 or 2035. The proof it was inert is in this repo's history
/// — a byte count went wrong within a day of being written and staleness said
/// nothing, because it was structurally incapable of saying anything.
///
/// The manifest version moves every time the base set is re-cut, which is
/// exactly when measurements should be re-taken or re-affirmed.
fn is_stale(measured_on: &str, manifest_version: &str) -> bool {
    use crate::base::parse_ym as ym;
    match (ym(measured_on), ym(manifest_version)) {
        // Unparseable dates are not evidence of staleness. Saying nothing beats
        // labelling a good measurement stale because a format changed — and the
        // curation test rejects an unreadable date at load, so this arm is a
        // fallback rather than the guard.
        (Some(on), Some(version)) => on < version,
        _ => false,
    }
}

fn costs(entry: &Entry, version: &str, out: &mut String) {
    // Pad the value and its subject as one unit. Padding only the subject makes
    // the `measured` column wander, which reads as sloppiness in the exact place
    // the output is asking to be trusted.
    let claims: Vec<String> = entry
        .measured
        .iter()
        .map(|m| format!("{} {}", m.value, m.what))
        .collect();
    let width = claims.iter().map(|c| c.chars().count()).max().unwrap_or(0);

    let mut label = "costs";
    for (m, claim) in entry.measured.iter().zip(&claims) {
        let stale = if is_stale(&m.on, version) {
            "  (stale)"
        } else {
            ""
        };
        // The date rides on every cost line. A measurement without one reads as
        // a fact about right now, which is the fabricated authority this whole
        // command exists to avoid.
        out.push_str(&format!(
            "  {label:<11} {claim:<width$}   measured {}{stale}\n",
            m.on
        ));
        // How it was taken, always — not only when stale, as before. On a
        // command whose thesis is that cost is measured and benefit argued,
        // hiding the method on the happy path leaves the reader with a bare
        // number and no way to check it, which is the shape of the claim this
        // command was built to replace.
        out.push_str(&format!("  {:<11} {}\n", "", m.how));
        label = "";
    }
    // `how` now prints on every line, so a stale measurement needs only to say
    // that the base set has been re-cut since it was taken.
    if entry.measured.iter().any(|m| is_stale(&m.on, version)) {
        out.push_str(&format!(
            "              (stale: taken before base set {version} — re-measure or re-affirm)\n"
        ));
    }
}

/// What this entry is part of, and whether that is on here.
///
/// Both halves or neither: "part of codegraph" is only half an answer in a
/// repo where codegraph is switched off, and that is exactly the repo where
/// somebody is asking. A feature's own entry also lists what it brought,
/// because the question "what does removing this take with it" has no other
/// answer once the grouping stopped being a comment.
fn feature(catalog: &Catalog, entry: &Entry, out: &mut String) {
    let off = if catalog.off.contains(&entry.feature) {
        "   (off here)"
    } else {
        ""
    };
    out.push_str(&format!("  {:<11} {}{off}\n", "part of", entry.feature));

    let brings: Vec<&str> = catalog
        .manifest
        .entries
        .iter()
        .filter(|e| e.feature == entry.feature && e.name != entry.name)
        .map(|e| e.name.as_str())
        .collect();
    if entry.name == entry.feature && !brings.is_empty() {
        out.push_str(&format!("  {:<11} {}\n", "brings", brings.join(", ")));
    }
}

fn alternatives(entry: &Entry, out: &mut String) {
    let width = entry
        .instead_of
        .iter()
        .map(|a| a.name.chars().count())
        .max()
        .unwrap_or(0);
    let mut label = "instead of";
    for a in &entry.instead_of {
        out.push_str(&format!("  {label:<11} {:<width$}   {}\n", a.name, a.why));
        label = "";
    }
}

/// Every answer names the manifest that produced it.
///
/// Four separate wrong answers — a stray file becoming the base set, omh
/// disowning its own entries after an upgrade, an untouched hook read as an
/// edit, a permissions error read as "not installed" — were all invisible for
/// the same reason: nothing said which manifest, at which version, answered.
/// One line turns each of them from a confident wrong answer into a visible one.
pub fn render_with_source(
    catalog: &Catalog,
    verdict: &Verdict,
    version: &str,
    source: &str,
) -> String {
    let mut out = render(catalog, verdict, version);
    out.push_str(&format!("\n  answered from {source}\n"));
    out
}

pub fn render(catalog: &Catalog, verdict: &Verdict, version: &str) -> String {
    let mut out = String::new();
    match verdict {
        Verdict::Omh { entry, yours } => {
            out.push_str(&format!(
                "{} — omh's choice, in the base set since {}\n\n",
                entry.name, entry.since
            ));
            out.push_str(&format!("  {:<11} {}\n", "because", entry.because));
            feature(catalog, entry, &mut out);
            costs(entry, version, &mut out);
            alternatives(entry, &mut out);
            out.push_str(&format!("  {:<11} {}\n", "installed", yours.layer.whose()));
            out.push_str(&format!("  {:<11} {}\n", "remove", entry.remove));
        }
        Verdict::Differs {
            entry,
            ships,
            yours,
        } => {
            out.push_str(&format!(
                "{} — omh's choice, and your copy is not what omh ships now\n\n",
                entry.name
            ));
            out.push_str(&format!("  {:<11} {ships}\n", "omh ships"));
            out.push_str(&format!(
                "  {:<11} {}   in {}\n",
                "on disk",
                yours.value,
                yours.layer.whose()
            ));
            out.push_str(&format!("  {:<11} {}\n", "because", entry.because));
            feature(catalog, entry, &mut out);
            costs(entry, version, &mut out);
            out.push_str(&format!("  {:<11} {}\n", "remove", entry.remove));
            // Which of the two it is, omh does not know — so it says so rather
            // than picking the flattering guess or the accusing one.
            out.push_str(
                "\n  Either you changed it, or omh did in a later version:\n  \
                 `init` seeds your profile once and never rewrites it.\n",
            );
        }
        Verdict::Generated { entry, stale } => {
            out.push_str(&format!(
                "{} — omh's own, generated at launch since {}\n\n",
                entry.name, entry.since
            ));
            out.push_str(&format!("  {:<11} {}\n", "because", entry.because));
            feature(catalog, entry, &mut out);
            costs(entry, version, &mut out);
            alternatives(entry, &mut out);
            out.push_str(&format!("  {:<11} {}\n", "remove", entry.remove));
            // Line by line rather than one continued literal. The `\` escape
            // does strip the next line's leading whitespace, so the source
            // reads correctly and prints correctly — until `cargo fmt` joins
            // the literal onto one line and keeps that indentation as literal
            // spaces. Checked twice here, both times by reading the output of
            // a real `omh why` rather than the source.
            match stale {
                Some(stale) => {
                    out.push_str(&format!(
                        "\n  A file of this name is in {} and is no longer read.\n",
                        stale.layer.whose()
                    ));
                    out.push_str("  `init` seeded these before omh generated them, so editing\n");
                    out.push_str("  it changes nothing.\n");
                }
                None => {
                    out.push_str("\n  Not a file anywhere — omh writes it into the session and\n");
                    out.push_str("  nothing else. That is what lets a fix reach you with the\n");
                    out.push_str("  upgrade.\n");
                }
            }
        }
        Verdict::Removed { entry } => {
            out.push_str(&format!(
                "{} — omh's choice, not installed here\n\n",
                entry.name
            ));
            out.push_str(&format!("  {:<11} {}\n", "because", entry.because));
            feature(catalog, entry, &mut out);
            costs(entry, version, &mut out);
            alternatives(entry, &mut out);
            out.push_str(&format!("  {:<11} omh init\n", "restore"));
        }
        // omh wrote it, so disowning it would be as false as claiming your own
        // entry. But there is no argument to make for it either.
        Verdict::Derived { yours, from } => {
            out.push_str(&format!(
                "{} — written by omh init, from your repo\n\n",
                yours.key
            ));
            out.push_str(&format!("  {:<11} {from}\n", "derived from"));
            out.push_str(&format!("  {:<11} {}\n", "installed", yours.layer.whose()));
            out.push_str(
                "\n  Not a curated choice — it follows from what your repo is,\n  \
                 so there is nothing to argue about. Edit or delete it freely;\n  \
                 init will not write over your version.\n",
            );
        }
        // No rationale, and no claim of base-set membership. omh did not choose
        // this and must not lend it reasoning it does not have.
        Verdict::Yours { yours } => {
            out.push_str(&format!("{} — your choice, not omh's\n\n", yours.key));
            out.push_str(&format!("  {:<11} {}\n", "added in", yours.layer.whose()));
            let shadowed = if yours.shadows.is_empty() {
                "nothing".to_string()
            } else {
                yours
                    .shadows
                    .iter()
                    .map(|l| l.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            };
            out.push_str(&format!("  {:<11} {shadowed}\n", "overrides"));
            out.push_str("\n  omh has no rationale for this one — it is yours.\n");
        }
        Verdict::Rejected { rejection } => {
            out.push_str(&format!(
                "{} — considered {}, not in the base set\n\n",
                rejection.name, rejection.considered
            ));
            out.push_str(&format!("  {:<11} {}\n", "because", rejection.because));
        }
        Verdict::Feature { name, gathers } => {
            let off = if catalog.off.contains(name) {
                "  —  off in this repo"
            } else {
                ""
            };
            out.push_str(&format!("{name} — an omh feature{off}\n\n"));
            let width = gathers
                .iter()
                .map(|e| e.name.chars().count())
                .max()
                .unwrap_or(0);
            let mut label = "gathers";
            for entry in gathers {
                out.push_str(&format!(
                    "  {label:<11} {:<width$}   {}\n",
                    entry.name, entry.because
                ));
                label = "";
            }
            out.push_str(&format!("  {:<11} {}\n", "remove", gathers[0].remove));
            out.push_str("\n  A feature is all or nothing — `omh why <name>` explains\n");
            out.push_str("  each part, and there is no way to keep only some of them.\n");
        }
        Verdict::Unknown { known } => {
            out.push_str("omh has nothing recorded under that name.\n\n");
            out.push_str("  known:\n");
            for name in known {
                out.push_str(&format!("    {name}\n"));
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Layer;
    use std::path::Path;

    const BUNDLED: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/base");

    fn manifest() -> Manifest {
        Manifest::load_dir(Path::new(BUNDLED)).unwrap()
    }

    fn setting(key: &str, value: &str, layer: Layer) -> Setting {
        Setting {
            key: key.into(),
            value: value.into(),
            layer,
            shadows: Vec::new(),
        }
    }

    fn catalog<'a>(m: &'a Manifest, installed: Vec<Setting>) -> Catalog<'a> {
        let baselines = m
            .entries
            .iter()
            .filter_map(|e| e.command.clone().map(|c| (e.name.clone(), c)))
            .collect();
        Catalog {
            manifest: m,
            baselines,
            installed,
            derived: BTreeMap::new(),
            off: BTreeSet::new(),
        }
    }

    #[test]
    fn an_untouched_base_entry_is_omhs() {
        let m = manifest();
        let c = catalog(
            &m,
            vec![setting("codegraph", "codebase-memory-mcp", Layer::Shared)],
        );
        assert!(matches!(c.why("codegraph"), Verdict::Omh { .. }));
    }

    /// The state people actually want to know about after six months.
    #[test]
    fn a_changed_base_entry_reports_both_values() {
        let m = manifest();
        let c = catalog(&m, vec![setting("codegraph", "my-fork", Layer::Local)]);
        match c.why("codegraph") {
            Verdict::Differs { ships, yours, .. } => {
                assert_eq!(ships, "codebase-memory-mcp");
                assert_eq!(yours.value, "my-fork");
                assert_eq!(yours.layer, Layer::Local);
            }
            other => panic!("expected Differs, got {other:?}"),
        }
    }

    /// Removing something omh installed is supposed to be easy, so this is a
    /// normal answer rather than an error.
    #[test]
    fn a_removed_base_entry_is_still_explained() {
        let m = manifest();
        let c = catalog(&m, vec![]);
        assert!(matches!(c.why("codegraph"), Verdict::Removed { .. }));
    }

    /// `graph-first` is not a hook that happens to mention the graph; it is
    /// part of the graph, and removing the server takes it too.
    ///
    /// Unanswerable while the grouping was a comment header in the manifest,
    /// which is the whole reason `feature` became a field. Asserted on all
    /// three entry verdicts because a removed or edited entry is exactly when
    /// somebody is asking what it belonged to.
    #[test]
    fn every_entry_answer_names_the_feature_it_is_part_of() {
        let m = manifest();
        for c in [
            catalog(&m, vec![setting("graph-first", "nudge", Layer::Shared)]),
            catalog(&m, vec![]),
            catalog(&m, vec![setting("codegraph", "my-fork", Layer::Local)]),
            catalog(
                &m,
                vec![setting("codegraph", "codebase-memory-mcp", Layer::Shared)],
            ),
        ] {
            let name = if c.installed.iter().any(|s| s.key == "codegraph") {
                "codegraph"
            } else {
                "graph-first"
            };
            let verdict = c.why(name);
            // One line, not two `contains` — `remove` already names the
            // feature for these entries, so a split assertion passes on
            // output that never says what anything is part of.
            let out = render(&c, &verdict, "2026.08");
            assert!(
                out.lines()
                    .any(|l| l.trim().starts_with("part of") && l.trim().ends_with("codegraph")),
                "must say what it belongs to: {out}"
            );
        }
    }

    /// A hook or a rules section is generated from the manifest at launch and
    /// is not a file anywhere, so the file-shaped answers are all wrong about
    /// it: `Removed` says "not installed here" about something that is
    /// running, and `Omh` points at a layer nothing reads.
    ///
    /// The leftover case is the one that matters. Every repo initialised
    /// before generation still has five hook files sitting in its profile;
    /// they lose the merge, so reporting one as what omh ships would be a
    /// confident wrong answer about the thing this command exists to be right
    /// about.
    #[test]
    fn a_generated_entry_is_generated_not_missing_and_not_yours() {
        let m = manifest();

        for name in ["graph-refresh", "git-rules"] {
            assert!(
                matches!(catalog(&m, vec![]).why(name), Verdict::Generated { .. }),
                "{name} with no file"
            );
        }

        let leftover = setting("graph-refresh", "what an older omh wrote", Layer::Shared);
        let c = catalog(&m, vec![leftover]);
        let verdict = c.why("graph-refresh");
        assert!(
            matches!(verdict, Verdict::Generated { .. }),
            "a leftover file does not decide, so it cannot be the answer"
        );
        let out = render(&c, &verdict, "2026.08");
        assert!(
            out.contains("this repo") && out.contains("no longer read"),
            "the dead file is named rather than ignored: {out}"
        );
    }

    /// Off here is a fact about this repo, and the answer has to carry it —
    /// otherwise `omh why` explains why something is installed while it is
    /// switched off three feet away.
    #[test]
    fn a_verdict_says_whether_the_feature_is_on_here() {
        let m = manifest();
        let mut c = catalog(&m, vec![]);
        c.off = ["codegraph".to_string()].into();

        let out = render(&c, &c.why("graph-refresh"), "2026.08");
        assert!(out.contains("off here"), "got: {out}");
    }

    /// `git-notice` is a feature with no entry of its own, and the manifest
    /// prints `git-notice = false` as the way out of `git-unavailable`. Asked
    /// about it, omh answered "nothing recorded under that name" and listed
    /// names that did not include it.
    ///
    /// Feature names are user-facing vocabulary now — they are the whole
    /// `[omh]` key space, and `settings::validate` errors in terms of them —
    /// so the command built to explain omh's choices has to know them. An
    /// instruction printed as the way out and then not recognised is the shape
    /// CONTRIBUTING singles out: it worked, it said so, and it was wrong.
    #[test]
    fn a_feature_is_explained_even_when_no_entry_shares_its_name() {
        let m = manifest();
        let c = catalog(&m, vec![]);

        let out = render(&c, &c.why("git-notice"), "2026.08");
        assert!(
            out.contains("git-unavailable") && out.contains("git-rules"),
            "must list what the feature gathers: {out}"
        );

        match c.why("teleport") {
            Verdict::Unknown { known } => assert!(
                known.contains(&"git-notice".to_string()),
                "a name omh tells you to type has to be discoverable: {known:?}"
            ),
            other => panic!("expected Unknown, got {other:?}"),
        }
    }

    /// The other half of the grouping: what a feature brought with it. Nobody
    /// can answer "what does removing codegraph take" from a comment header.
    #[test]
    fn why_a_feature_lists_what_it_brings() {
        let m = manifest();
        let c = catalog(&m, vec![]);
        let out = render(&c, &c.why("codegraph"), "2026.08");
        for name in ["graph-orient", "graph-first", "graph-read", "graph-refresh"] {
            assert!(out.contains(name), "{name} is part of codegraph: {out}");
        }
    }

    /// The load-bearing case: omh must not claim authorship of your choices.
    #[test]
    fn your_own_entry_gets_no_rationale() {
        let m = manifest();
        let c = catalog(&m, vec![setting("linear", "npx", Layer::Local)]);
        match c.why("linear") {
            Verdict::Yours { yours } => assert_eq!(yours.layer, Layer::Local),
            other => panic!("expected Yours, got {other:?}"),
        }
    }

    /// A rejection is a product artifact, not a "not found".
    #[test]
    fn a_rejected_candidate_explains_its_rejection() {
        let m = manifest();
        let c = catalog(&m, vec![]);
        match c.why("gitnexus") {
            Verdict::Rejected { rejection } => {
                assert!(
                    rejection.because.contains("Noncommercial"),
                    "{}",
                    rejection.because
                );
            }
            other => panic!("expected Rejected, got {other:?}"),
        }
    }

    #[test]
    fn an_unknown_name_lists_what_is_known_instead_of_guessing() {
        let m = manifest();
        let c = catalog(&m, vec![setting("linear", "npx", Layer::Local)]);
        match c.why("lienar") {
            Verdict::Unknown { known } => {
                assert!(known.contains(&"codegraph".to_string()), "{known:?}");
                assert!(known.contains(&"linear".to_string()), "{known:?}");
                assert!(known.contains(&"gitnexus".to_string()), "{known:?}");
            }
            other => panic!("expected Unknown, got {other:?}"),
        }
    }

    /// Without a baseline omh cannot tell modified from untouched, and it must
    /// not assume the worse answer and accuse you of an edit you did not make.
    ///
    /// A manifest can reach this: `command` is optional, and `~/.omh/base` is
    /// a directory anyone can drop a file into.
    #[test]
    fn an_entry_with_no_baseline_is_not_reported_as_modified() {
        let m = manifest();
        let mut c = catalog(
            &m,
            vec![setting("codegraph", "anything at all", Layer::Shared)],
        );
        c.baselines.remove("codegraph");
        assert!(matches!(c.why("codegraph"), Verdict::Omh { .. }));
    }

    // ── rendering ────────────────────────────────────────────────────────────

    #[test]
    fn omhs_choice_reports_its_argument_and_its_cost() {
        let m = manifest();
        let c = catalog(
            &m,
            vec![setting("codegraph", "codebase-memory-mcp", Layer::Shared)],
        );
        let out = render(&c, &c.why("codegraph"), "2026.08");

        assert!(out.contains("omh's choice"), "{out}");
        assert!(
            out.contains("re-grepping"),
            "the argument is missing:\n{out}"
        );
        assert!(out.contains("0.46s"), "the cost is missing:\n{out}");
        assert!(
            out.contains("gitnexus"),
            "the alternatives are missing:\n{out}"
        );
        assert!(
            out.contains("omh config mcp rm codegraph"),
            "no way out:\n{out}"
        );
    }

    /// Cost is measured and benefit is argued: two different kinds of claim.
    /// A measurement printed without its date reads as a fact about right now,
    /// which is exactly the fabricated authority this command exists to avoid.
    #[test]
    fn every_measured_cost_carries_the_date_it_was_taken() {
        let m = manifest();
        for entry in &m.entries {
            let out = render(&catalog(&m, vec![]), &Verdict::Removed { entry }, "2026.08");
            for measured in &entry.measured {
                let line = out
                    .lines()
                    .find(|l| l.contains(&measured.value) && l.contains(&measured.what))
                    .unwrap_or_else(|| panic!("{}: no line for {}", entry.name, measured.what));
                assert!(
                    line.contains(&measured.on),
                    "{}: cost printed without its date: {line}",
                    entry.name
                );
            }
        }
    }

    /// A measurement taken before the entry's own version describes an older
    /// thing. Still worth showing — it is the only number there is — but not
    /// worth presenting as current.
    #[test]
    fn a_measurement_older_than_the_entry_is_marked_stale() {
        let m: Manifest = toml::from_str(
            r#"
version = "2026.08"
[[entry]]
name = "x"
kind = "mcp"
feature = "x"
since = "2026.08"
because = "b"
remove = "r"
command = "c"
[[entry.measured]]
what = "per turn"
value = "1s"
how = "h"
on = "2026-01-01"
[[entry.instead_of]]
name = "a"
why = "w"
"#,
        )
        .unwrap();
        // Measured in 2026-01, shipped in a base set cut in 2026.08: the number
        // predates the version it is being presented as evidence for.
        let c = catalog(&m, vec![]);
        let out = render(
            &c,
            &Verdict::Removed {
                entry: &m.entries[0],
            },
            "2026.08",
        );
        assert!(
            out.contains("stale"),
            "an outdated measurement must say so:\n{out}"
        );

        // The same measurement, in the base set it was actually taken for, is
        // not stale. Without this the check could be `=> true` and stay green —
        // which it was, and did.
        let fresh = render(
            &c,
            &Verdict::Removed {
                entry: &m.entries[0],
            },
            "2026.01",
        );
        assert!(
            !fresh.contains("stale"),
            "a current measurement must not be flagged:\n{fresh}"
        );
    }

    /// Staleness used to compare against the entry's own `since`, which never
    /// moves — so no shipped measurement could ever be flagged, in 2027 or in
    /// 2035. The proof it was inert is in this repo: a byte count went wrong
    /// within a day of being written and this said nothing.
    ///
    /// Against the manifest version it fires exactly when the base set is
    /// re-cut, which is when numbers should be re-taken or re-affirmed.
    #[test]
    fn staleness_is_measured_against_the_base_set_not_the_entrys_own_age() {
        let m = manifest();
        let entry = m.entry("codegraph").unwrap();

        let current = render(
            &catalog(&m, vec![]),
            &Verdict::Removed { entry },
            &m.version,
        );
        assert!(
            !current.contains("stale"),
            "shipped numbers are current:\n{current}"
        );

        // A later cut of the base set, with the same measurements carried over.
        let later = render(&catalog(&m, vec![]), &Verdict::Removed { entry }, "2027.01");

        // Assert the marker on the cost line itself, not merely the word
        // "stale" somewhere in the output. There are two call sites — the
        // per-measurement marker and the trailing summary — and a bare
        // `contains` is satisfied by either, so it cannot tell which one is
        // wired to the wrong comparison. Mutating one call site left this test
        // green until the assertion was tightened.
        let first = entry.measured.first().expect("codegraph has measurements");
        let cost_line = later
            .lines()
            .find(|l| l.contains(&first.value) && l.contains("measured"))
            .unwrap_or_else(|| panic!("no cost line in:\n{later}"));
        assert!(
            cost_line.contains("(stale)"),
            "re-cutting the base set must flag every carried-over number:\n{cost_line}"
        );
    }

    /// `how` is the entire evidence for a number. It used to print only when a
    /// measurement was stale — which, given the bug above, meant never. A bare
    /// figure with no method is the shape of claim this command replaced.
    #[test]
    fn the_method_is_shown_for_every_cost_not_only_stale_ones() {
        let m = manifest();
        let entry = m.entry("codegraph").unwrap();
        let out = render(
            &catalog(&m, vec![]),
            &Verdict::Removed { entry },
            &m.version,
        );

        for measured in &entry.measured {
            assert!(
                out.contains(&measured.how),
                "cost `{}` printed without how it was taken:\n{out}",
                measured.value
            );
        }
    }

    /// `init` generates `<stack>-test` and `<stack>-format` hooks from what it
    /// detected. Those are omh's writing but not omh's *opinion* — there is
    /// nothing curated to argue about, `cargo fmt` is simply what formats Rust.
    ///
    /// Calling them "your choice" is the same false claim of authorship as
    /// calling your own entry omh's, just pointing the other way, and it was the
    /// answer this command gave until running it revealed otherwise.
    fn rust_format() -> Derived {
        Derived {
            from: "rust, detected from Cargo.toml".into(),
            command: "cargo fmt".into(),
            layer: Layer::Shared,
        }
    }

    /// `init` writes stack hooks only into the shared layer, so one sitting in
    /// `local` was not written by `init` whatever it is called. Claiming
    /// otherwise is the same authorship lie this module exists to prevent,
    /// aimed the other way — reproduced with a hand-written `rust-test.json`.
    #[test]
    fn a_hook_in_a_layer_init_never_writes_to_is_yours() {
        let m = manifest();
        let mut c = catalog(&m, vec![setting("rust-format", "cargo fmt", Layer::Local)]);
        c.derived.insert("rust-format".into(), rust_format());
        assert!(
            matches!(c.why("rust-format"), Verdict::Yours { .. }),
            "init does not write to local, so this is not init's"
        );
    }

    /// Right name, right layer, different command: you rewrote it, and omh must
    /// not print "there is nothing to argue about" over your own work.
    #[test]
    fn a_rewritten_stack_hook_is_yours() {
        let m = manifest();
        let mut c = catalog(
            &m,
            vec![setting(
                "rust-format",
                "cargo +nightly fmt --all",
                Layer::Shared,
            )],
        );
        c.derived.insert("rust-format".into(), rust_format());
        assert!(matches!(c.why("rust-format"), Verdict::Yours { .. }));
    }

    #[test]
    fn a_hook_derived_from_your_stack_is_neither_omhs_opinion_nor_yours() {
        let m = manifest();
        let mut c = catalog(&m, vec![setting("rust-format", "cargo fmt", Layer::Shared)]);
        c.derived.insert("rust-format".into(), rust_format());

        match c.why("rust-format") {
            Verdict::Derived { from, .. } => assert!(from.contains("Cargo.toml"), "{from}"),
            other => panic!("expected Derived, got {other:?}"),
        }

        let out = render(&c, &c.why("rust-format"), "2026.08");
        assert!(!out.contains("base set"), "claims it is curated:\n{out}");
        assert!(
            !out.contains("your choice"),
            "disowns something omh wrote:\n{out}"
        );
        assert!(
            out.contains("Cargo.toml"),
            "does not say what it was derived from:\n{out}"
        );
    }

    /// The load-bearing negative. omh must not lend its reasoning to a choice
    /// it did not make — no rationale, and no claim of base-set membership.
    #[test]
    fn your_own_choice_never_borrows_omhs_authority() {
        let m = manifest();
        let c = catalog(&m, vec![setting("linear", "npx", Layer::Local)]);
        let out = render(&c, &c.why("linear"), "2026.08");

        assert!(out.contains("your choice"), "{out}");
        assert!(!out.contains("base set"), "claims omh installed it:\n{out}");
        assert!(!out.contains("because"), "invents a rationale:\n{out}");
        assert!(
            out.contains("local"),
            "provenance is the one thing it can say:\n{out}"
        );
    }

    /// Asserts the label→value **pairing**, not that both strings appear
    /// somewhere. The previous version passed with the two values swapped —
    /// output reading `omh ships my-fork` / `on disk codebase-memory-mcp` — which
    /// is the exact inversion this whole module exists to prevent.
    ///
    /// Pairing survives reformatting; column positions would not.
    #[test]
    fn a_differing_entry_pairs_each_value_with_its_own_label() {
        let m = manifest();
        let c = catalog(&m, vec![setting("codegraph", "my-fork", Layer::Local)]);
        let out = render(&c, &c.why("codegraph"), "2026.08");

        let line = |label: &str| {
            out.lines()
                .find(|l| l.trim_start().starts_with(label))
                .unwrap_or_else(|| panic!("no `{label}` line in:\n{out}"))
        };
        assert!(line("omh ships").contains("codebase-memory-mcp"), "{out}");
        assert!(!line("omh ships").contains("my-fork"), "{out}");
        assert!(line("on disk").contains("my-fork"), "{out}");
        assert!(!line("on disk").contains("codebase-memory-mcp"), "{out}");
    }

    /// omh cannot tell an edit from an upgrade — `init` seeds once and never
    /// revisits, while the shipped baseline moves every release. Claiming "you"
    /// accused every user of an edit they never made, the first time a hook
    /// command changed.
    #[test]
    fn a_difference_never_claims_who_caused_it() {
        let m = manifest();
        let c = catalog(&m, vec![setting("codegraph", "my-fork", Layer::Local)]);
        let out = render(&c, &c.why("codegraph"), "2026.08");
        assert!(
            !out.contains("modified by you") && !out.contains("you set"),
            "omh does not know who changed it:\n{out}"
        );
        assert!(out.contains("Either you changed it, or omh did"), "{out}");
    }

    /// The line that converts four silent wrong answers into visible ones. A
    /// stray manifest, a post-upgrade drift, an unreadable layer — each of them
    /// produces a confident answer, and the only way a reader can tell is by
    /// seeing which manifest was consulted.
    #[test]
    fn every_answer_names_the_manifest_that_produced_it() {
        let m = manifest();
        let c = catalog(
            &m,
            vec![setting("codegraph", "codebase-memory-mcp", Layer::Shared)],
        );
        let out = render_with_source(
            &c,
            &c.why("codegraph"),
            "2026.08",
            "/home/x/.omh/base/2026.08.toml · 2026.08",
        );
        assert!(out.contains("answered from"), "{out}");
        assert!(out.contains("2026.08.toml"), "{out}");
    }

    /// The whole `Rejected` arm could be emptied and the suite stayed green —
    /// and it carries the highest-consequence string the command emits. The
    /// gitnexus entry is a *licence* warning: a user who installs it at work is
    /// in violation of a dependency they never chose.
    #[test]
    fn a_rejection_prints_its_reasoning_and_when_it_was_considered() {
        let m = manifest();
        let c = catalog(&m, vec![]);
        let out = render(&c, &c.why("gitnexus"), &m.version);

        let r = m.rejection("gitnexus").unwrap();
        assert!(
            out.contains(&r.because),
            "the reasoning is the whole point:\n{out}"
        );
        assert!(
            out.contains(&r.considered),
            "when it was considered:\n{out}"
        );
        assert!(
            out.contains("Noncommercial"),
            "the licence problem must survive:\n{out}"
        );
    }

    /// "A default nobody can leave is a cage" is enforced for `Omh` and was not
    /// for `Removed` — its way back could be deleted green.
    #[test]
    fn a_removed_entry_says_how_to_get_it_back() {
        let m = manifest();
        let c = catalog(&m, vec![]);
        let out = render(&c, &c.why("codegraph"), &m.version);
        assert!(out.contains("not installed here"), "{out}");
        assert!(out.contains("omh init"), "no way back:\n{out}");
    }

    #[test]
    fn an_unknown_name_prints_the_alternatives_it_does_know() {
        let m = manifest();
        let c = catalog(&m, vec![]);
        let out = render(&c, &c.why("lienar"), "2026.08");
        assert!(out.contains("codegraph"), "{out}");
        assert!(!out.contains("omh's choice"), "guessed at a match:\n{out}");
    }
}