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
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
//! The base set — omh's opinion.
//!
//! Everything else in this codebase is a place to put this. A distribution is
//! not its machinery; it is what it chooses, and choosing is the part a
//! marketplace structurally cannot do.
//!
//! Entries earn their place by stating what they cost, what they buy, what was
//! considered instead, and how to remove them. **Cost is measured; benefit is
//! argued.** Those are different kinds of claim and are never presented as the
//! same one — a benchmark over a stochastic metric would have dressed the second
//! as the first, which is why there isn't one.
//!
//! The manifest is the single source of truth: `omh init` seeds from it and
//! `omh why` explains from it, so they cannot disagree.

use crate::hook::Field;
use crate::render::Server;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

/// The base set as data.
///
/// `omh init` seeds from this and `omh why` explains from it, so the two cannot
/// disagree about what is installed or why. Keeping the rationale in a shipped
/// file rather than in the binary also means the opinion is reviewable by the
/// people it is imposed on.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    /// The base set is versioned because it expires — a distribution's real
    /// work is re-choosing as the catalogue churns.
    pub version: String,
    #[serde(default, rename = "entry")]
    pub entries: Vec<Entry>,
    /// Candidates considered and turned down. Recorded so the same one is not
    /// re-litigated every time somebody rediscovers it.
    #[serde(default)]
    pub rejected: Vec<Rejected>,
    /// Where this was loaded from. Not part of the file — set by `load_dir`, so
    /// every answer can name the manifest that produced it.
    #[serde(skip)]
    pub path: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Entry {
    pub name: String,
    pub kind: Kind,
    /// What this entry is part of. A server, its hooks and its section of the
    /// rules are one thing, and this is the field that says so — `[omh]` takes
    /// feature names, so an entry belonging to nothing cannot be switched off.
    ///
    /// Required, like `because` and `since`: the grouping spent its life as a
    /// comment header, which is the one claim in the manifest no test could
    /// check.
    pub feature: String,
    pub since: String,
    /// Argued, not measured. The honest half.
    pub because: String,
    /// A default nobody can leave is a cage.
    pub remove: String,
    /// For `mcp` entries: what `init` seeds. Also the baseline that decides
    /// whether the user's copy counts as modified.
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub measured: Vec<Measured>,
    #[serde(default)]
    pub instead_of: Vec<Alternative>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Kind {
    Mcp,
    Hook,
    /// A section of the rules the agent is given. Ships as a base-set entry
    /// like everything else omh chooses — the prose an agent is handed costs
    /// context on every turn, and a cost nobody wrote down is one nobody can
    /// argue with.
    Rules,
}

impl Kind {
    /// Which catalogue capability an entry of this kind competes with for a
    /// name. `[use]` is keyed by capability and the manifest by kind, and this
    /// is the one place the two vocabularies meet.
    pub fn capability(&self) -> crate::adapter::Capability {
        match self {
            Self::Mcp => crate::adapter::Capability::Mcp,
            Self::Hook => crate::adapter::Capability::Hooks,
            Self::Rules => crate::adapter::Capability::Rules,
        }
    }
}

/// A cost, with the date it was taken and how.
///
/// Never rendered in the same shape as a computed value: one is a fact about
/// this machine right now, the other is a recording that can go stale, and
/// blurring them is how a document starts claiming more than it can support.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Measured {
    pub what: String,
    pub value: String,
    pub how: String,
    pub on: String,
}

/// `YYYY.MM` or `YYYY-MM-DD` → (year, month). One parser, so a date that the
/// staleness check cannot read is the same date the curation test rejects at
/// load — rather than one silently tolerating what the other would refuse.
pub fn parse_ym(s: &str) -> Option<(u32, u32)> {
    let mut parts = s.split(['.', '-']);
    let year: u32 = parts.next()?.parse().ok()?;
    let month: u32 = parts.next()?.parse().ok()?;
    (year >= 2000 && (1..=12).contains(&month)).then_some((year, month))
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Alternative {
    pub name: String,
    pub why: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rejected {
    pub name: String,
    pub considered: String,
    pub because: String,
}

impl Manifest {
    /// Load the newest manifest in `dir`, newest by **parsed version**.
    ///
    /// Not by filename sort. That was three silent wrong answers at once: any
    /// stray `.toml` sorting after the real one became the base set, `2027.2`
    /// beat `2027.10`, and nothing checked a file's declared `version` at all.
    /// One stray file made `omh init` seed `{}` and report success, and made
    /// `omh why` call omh's own entries the user's.
    ///
    /// Older manifests are kept rather than deleted, so `omh upgrade` can
    /// eventually diff two and say what entered, what left, and why.
    pub fn load_dir(dir: &Path) -> Result<Self> {
        let mut newest: Option<((u32, u32), PathBuf, Self)> = None;

        for entry in std::fs::read_dir(dir)
            .with_context(|| format!("reading {}", dir.display()))?
            .flatten()
        {
            let path = entry.path();
            if !path.extension().is_some_and(|x| x == "toml") {
                continue;
            }
            let raw = std::fs::read_to_string(&path)
                .with_context(|| format!("reading {}", path.display()))?;
            // A manifest an older omh seeded can be missing a field this one
            // requires, and every command loads the manifest — so the failure
            // is the whole tool, not one command. `init` refreshes bundled
            // files and keeps the old one, so saying that here is a way out
            // rather than the advice-that-does-nothing loop `read_layer`
            // documents.
            let manifest: Self = toml::from_str(&raw).with_context(|| {
                format!(
                    "parsing {} — if it was seeded by an older omh, `omh init` refreshes it",
                    path.display()
                )
            })?;

            // A file whose declared version is unreadable is not a candidate.
            // Accepting one on filename alone is what let `zz-notes.toml` win.
            let Some(version) = parse_ym(&manifest.version) else {
                continue;
            };
            if newest.as_ref().is_none_or(|(best, _, _)| version > *best) {
                newest = Some((version, path, manifest));
            }
        }

        let (_, path, mut manifest) = newest.with_context(|| {
            format!(
                "no usable base manifest in {} — run `omh init`",
                dir.display()
            )
        })?;

        // A manifest that parses but names nothing seeds an empty base set and
        // reports success, leaving every session running hooks that point at a
        // server which is not installed. Fail here rather than there.
        if manifest.entries.is_empty() {
            anyhow::bail!("{} declares no base-set entries", path.display());
        }
        manifest.path = Some(path);
        Ok(manifest)
    }

    /// Which manifest answered, and at what version.
    ///
    /// Four separate wrong answers reduced to `omh why` never saying this.
    pub fn source(&self) -> String {
        match &self.path {
            Some(p) => format!("{} · {}", p.display(), self.version),
            None => format!("(unsaved) · {}", self.version),
        }
    }

    /// The MCP servers `omh init` seeds, built from the manifest.
    ///
    /// There is no second definition in code to disagree with this one — that
    /// was the point of moving the base set into a file.
    pub fn servers(&self) -> BTreeMap<String, Server> {
        self.entries
            .iter()
            .filter(|e| e.kind == Kind::Mcp)
            .filter_map(|e| {
                Some((
                    e.name.clone(),
                    Server {
                        command: e.command.clone()?,
                        args: e.args.clone(),
                        env: BTreeMap::new(),
                    },
                ))
            })
            .collect()
    }

    /// One line per entry, for `omh init` to print. The full answer is
    /// `omh why <name>`.
    pub fn rationale(&self) -> Vec<(&str, &str)> {
        self.entries
            .iter()
            .filter(|e| e.kind == Kind::Mcp)
            .map(|e| (e.name.as_str(), e.because.as_str()))
            .collect()
    }

    pub fn entry(&self, name: &str) -> Option<&Entry> {
        self.entries.iter().find(|e| e.name == name)
    }

    /// Every name omh owns, by capability, each pointing at its feature.
    ///
    /// One derivation with two readers — `own`'s `reserved`, which stops a file
    /// standing in for a generated hook, and `[use]`, which refuses to let one
    /// be selected. The question both ask is "is this name omh's?", and two
    /// answers to it is how a feature gets taken apart by one of them while the
    /// other still thinks it is whole.
    pub fn owns(&self) -> crate::selection::Owned {
        let mut out = crate::selection::Owned::new();
        for entry in &self.entries {
            out.entry(entry.kind.capability())
                .or_default()
                .insert(entry.name.clone(), entry.feature.clone());
        }
        out
    }

    pub fn rejection(&self, name: &str) -> Option<&Rejected> {
        self.rejected.iter().find(|r| r.name == name)
    }
}

/// Where the graph server keeps its index inside the sandbox.
///
/// Mounted from a volume keyed by **repo**, not by harness, so the index
/// survives a container rebuild and a switch from Claude Code to opencode.
/// Const concatenation of a `&str` const is not available without a macro
/// crate, so this repeats the home rather than deriving it — and
/// `the_graph_cache_lives_under_the_agents_home` fails if the two drift.
pub const GRAPH_CACHE: &str = "/home/agent/.cache/codebase-memory-mcp";

pub const GRAPH_VERSION: &str = "0.9.0";

/// Port the graph UI is reachable on from the host.
pub const GRAPH_UI_PORT: u16 = 9749;

/// Port the server itself binds.
///
/// It binds **container loopback** and offers no bind-address flag, so a
/// published port forwards to nothing. Verified: `HTTP 200` inside the sandbox,
/// no response from the host. A bridge listening on all interfaces fixes it
/// without asking the tool to expose itself.
pub const GRAPH_UI_INTERNAL: u16 = 9748;

pub const GRAPH_BIN: &str = "codebase-memory-mcp";

// The MCP servers and their rationale are not here: they are
// `Manifest::servers()` and `Manifest::rationale()`, read from the base-set
// file. One file that `init` seeds from and `why` explains from cannot
// contradict itself; a hardcoded list beside it can.

/// The graph UI runs **once per repo**, not once per session.
///
/// Every session's graph lives in one volume, so a per-session server showed
/// every other session's graph anyway — N identical websites. Matching the
/// server's scope to its data's scope removes the duplication, survives
/// sessions starting and stopping, and lets the container mount *only* the
/// index: no worktree, no credentials, no profile.
pub fn ui_container(repo: &str) -> String {
    format!("omh-graph-{repo}")
}

/// A stable loopback port for the graph UI.
///
/// Derived, like the ssh port: a browser tab you left open must keep working
/// across a restart.
pub fn ui_port(container: &str) -> u16 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    container.hash(&mut h);
    "graph-ui".hash(&mut h);
    const LOW: u32 = 49152;
    (LOW + (h.finish() % (65535 - LOW) as u64) as u32) as u16
}

/// Install the **UI variant** from GitHub Releases, checksum-verified.
///
/// Not `npm install`: the published 0.9.0 installer hardcodes
/// `variant = platform === 'linux' ? '-portable' : ''` and never reads
/// `CBM_VARIANT`, so the documented `CBM_VARIANT=ui` yields the lean binary.
/// Verified in a container — it reports "built without the embedded UI".
pub fn graph_install() -> String {
    // `-portable` is upstream's own linux convention; TARGETARCH is what
    // buildkit sets, so the same Dockerfile works on arm64 and amd64.
    format!(
        "set -eu; \
         ARCH=${{TARGETARCH:-$(dpkg --print-architecture)}}; \
         A=codebase-memory-mcp-ui-linux-$ARCH-portable.tar.gz; \
         B=https://github.com/DeusData/codebase-memory-mcp/releases/download/v{GRAPH_VERSION}; \
         cd /tmp && curl -sSLO \"$B/$A\" && curl -sSLO \"$B/checksums.txt\" && \
         grep \" $A$\" checksums.txt | sha256sum -c - && \
         tar xzf \"$A\" && \
         install -m 0755 \"$(find /tmp -maxdepth 2 -name {GRAPH_BIN} -type f | head -1)\" \
           /usr/local/bin/{GRAPH_BIN} && \
         rm -rf /tmp/*"
    )
}

/// Serve the graph UI. Needs stdin held open: the MCP server shuts down when
/// stdio closes, and it takes the UI down with it.
pub fn ui_command(port: u16) -> String {
    format!(
        "sleep infinity | {GRAPH_BIN} --ui=true --port={GRAPH_UI_INTERNAL} & \
         socat TCP-LISTEN:{port},fork,reuseaddr TCP:127.0.0.1:{GRAPH_UI_INTERNAL}"
    )
}

/// Run the graph UI as a container of its own.
///
/// Its own container rather than a process inside a session: lifecycle becomes
/// `docker run` / `docker rm`, which is idempotent by construction. The
/// per-session version needed a `pgrep` guard, a detached exec, and a `pkill` —
/// and each of those was a bug before it worked.
pub fn ui_run_args(image: &str, container: &str, cache_volume: &str, port: u16) -> Vec<String> {
    vec![
        "run".into(),
        "-d".into(),
        "--name".into(),
        container.into(),
        "-p".into(),
        format!("127.0.0.1:{port}:{GRAPH_UI_PORT}"),
        // The index and nothing else. No worktree, no credentials, no profile.
        "-v".into(),
        format!("{cache_volume}:{GRAPH_CACHE}"),
        image.into(),
        "sh".into(),
        "-c".into(),
        ui_command(GRAPH_UI_PORT),
    ]
}

/// Drop a session's graph.
///
/// `omh s rm` removes the worktree; without this the index outlives the code it
/// describes, and every later `list_projects` offers graphs of branches that no
/// longer exist anywhere.
pub fn drop_graph_command(project: &str) -> Vec<String> {
    vec![
        "sh".into(),
        "-c".into(),
        format!("{GRAPH_BIN} cli delete_project --project '{project}' >/dev/null 2>&1 || true"),
    ]
}

/// One of omh's own hooks: the manifest entry it answers to, and the hook
/// itself in exactly the shape a `<repo>/.omh/hooks/` file holds.
///
/// Same shape deliberately. omh's are generated and yours are files, but a
/// harness receives one hooks configuration and cannot tell the tiers apart —
/// so if omh's could be written in a format yours cannot, the format would be
/// documentation rather than a contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hook {
    pub name: &'static str,
    pub hook: crate::hook::Hook,
}

/// The env var carrying the graph's project name into the sandbox.
///
/// Hooks run inside the container and must name the project they refresh. Baking
/// a path in would make the hook file session-specific; an env var keeps it one
/// shared, reviewable file.
pub const PROJECT_ENV: &str = "OMH_GRAPH_PROJECT";

/// A graph is per-session, because a session's worktree is not the checkout the
/// agent started from — it holds whatever the agent has since written.
pub fn project_name(repo: &str, session: &str) -> String {
    format!("{repo}-{session}")
}

/// The grep nudge, in the three literal pieces `$p` is spliced between.
///
/// Kept as data rather than one string so its cost can be **computed** instead
/// of typed into the manifest. The manifest declared `~40 B` for this for its
/// whole life; the real figure is over five times that, and nothing could
/// notice, because a hand-written number and the string it describes had no
/// relationship a test could check.
const GREP_NUDGE: [&str; 3] = [
    "This repo has a code graph: project ",
    ". For structural questions — where is X defined, what calls Y, what does \
     this module depend on — search_graph --project ",
    " answers in one call. Grep is right for literal text.",
];

/// What the nudge actually injects, for a given project name. This is the thing
/// the cost in the manifest is a claim about.
/// Test-only: the hook builds its jq expression from `GREP_NUDGE` directly,
/// since `$p` is interpolated by jq at run time rather than by Rust. This is
/// the same string in the form a test can measure.
#[cfg(test)]
pub fn grep_nudge(project: &str) -> String {
    format!(
        "{}{project}{}{project}{}",
        GREP_NUDGE[0], GREP_NUDGE[1], GREP_NUDGE[2]
    )
}

/// Hooks that make the graph actually get used. Without them the server is
/// installed and never called, which is how most of these end up.
///
/// Written in omh's own vocabulary — see `crate::hook`. None of them names a
/// harness event, a harness tool, or a harness's payload schema, which is what
/// they all did until the format landed: the interception is `when`, the text is
/// `inject`, and how either reaches a particular harness is adapter data.
pub fn hooks() -> Vec<Hook> {
    use crate::hook::{Action, Event, Hook as Canonical, Tool};

    // Every source extension worth not reading whole. A `case` arm rather than
    // a list omh iterates: it is evaluated by the shell inside the sandbox,
    // where omh is not running.
    const SOURCE: &str = "*.rs|*.ts|*.tsx|*.js|*.jsx|*.py|*.go|*.java|*.rb|*.php|*.c|*.h|*.cc|\
                          *.cpp|*.hpp|*.cs|*.swift|*.kt|*.scala";

    vec![
        Hook {
            name: "graph-refresh",
            // 0.14s incrementally. A graph describing the code as it was when
            // the session started is worse than none: it answers confidently
            // about code the agent has since rewritten.
            //
            // `|| true` stays the author's job, not the renderer's: a hook has
            // to degrade to a no-op rather than to an error, and a missing
            // `codebase-memory-mcp` must not fail somebody's turn.
            hook: Canonical {
                on: Event::TurnEnd,
                tools: vec![],
                when: None,
                action: Action::Run(format!(
                    "{GRAPH_BIN} cli index_repository --repo-path /work \
                     --name \"${PROJECT_ENV}\" --mode fast >/dev/null 2>&1 || true"
                )),
            },
        },
        Hook {
            name: "graph-orient",
            // The only graph tool that costs nothing per tool call: orientation
            // the agent is given once instead of discovering by reading files.
            //
            // SessionStart re-fires on resume and compact, so this is paid every
            // time context is rebuilt, not once. `overview` is 6,173 bytes; the
            // four aspects that actually orient are 2,138. The flag repeats — a
            // comma-separated list returns empty, verified against the binary.
            //
            // The one hook that needs `capture`: the text it injects is not
            // known until the graph has been asked, and `when` then keeps it
            // silent when the graph answered nothing.
            hook: Canonical {
                on: Event::SessionStart,
                tools: vec![],
                when: Some(format!("[ -n \"${}\" ]", crate::hook::CAPTURE_VAR)),
                action: Action::Inject {
                    capture: Some(format!(
                        "{GRAPH_BIN} cli get_architecture --project \"${PROJECT_ENV}\" \
                         --aspects layers --aspects packages --aspects boundaries \
                         --aspects entry_points 2>/dev/null | tail -1"
                    )),
                    text: format!(
                        "Code graph for project ${PROJECT_ENV} — modules, layers, boundaries \
                         and entry points. Query it with search_graph/trace_path/get_code_snippet \
                         rather than exploring by hand:\n${}",
                        crate::hook::CAPTURE_VAR
                    ),
                },
            },
        },
        Hook {
            name: "git-unavailable",
            // Silent unless the command is actually git, for the reason
            // `graph-read` is silent on small files: a nudge on every shell call
            // is noise the model tunes out, and the shell is most of what an
            // agent runs.
            //
            // git is matched anywhere a command can start, not just at the
            // front. `cd /work && git status` is the same mistake with a prefix,
            // and a **newline** is the separator that matters most — multi-line
            // shell is one of the most common shapes an agent emits, and an
            // earlier version of this pattern missed every one of them.
            // `[:blank:]` rather than `[:space:]` for the leading-whitespace
            // case, so the newline arm stays the thing doing that work.
            //
            // A predicate now rather than an early `exit 0`, which is the one
            // thing the translation changed: a `case` that matches nothing exits
            // 0, so the no-match arm has to say `false` out loud or every shell
            // call would be answered.
            //
            // Injects `GIT_ABSENT` so the sentence the agent meets here and the
            // one the `git-rules` section carries cannot drift.
            hook: Canonical {
                on: Event::BeforeTool,
                tools: vec![Tool::Shell],
                when: Some(format!(
                    "case \"${}\" in \
                     git\\ *|git) ;; \
                     *[\\;\\&\\|\\(]*git\\ *|*[[:blank:]]git\\ *) ;; \
                     *\"\n\"git\\ *) ;; \
                     *) false ;; esac",
                    Field::ToolCommand.var()
                )),
                // A refusal, not a notice. As an `inject` the call went ahead:
                // the agent read "git does not work here" and then ran
                // `git status` anyway, spending a tool call to reach an error
                // omh already knew was coming. git genuinely cannot work here —
                // the worktree's `.git` points at an admin directory omh does
                // not mount — so there is nothing for the call to discover.
                action: Action::Refuse {
                    text: GIT_ABSENT.to_string(),
                },
            },
        },
        Hook {
            name: "graph-first",
            // A nudge, not a wall: grep is right for a literal string, and a
            // hook that blocks correct work gets disabled.
            //
            // Built from GREP_NUDGE so the string the agent sees and the cost
            // the manifest claims cannot drift apart. It reads no payload field,
            // so the rendered command pays for no `jq` — search is frequent.
            hook: Canonical {
                on: Event::BeforeTool,
                tools: vec![Tool::Search],
                when: None,
                action: Action::Inject {
                    capture: None,
                    text: format!(
                        "{}${PROJECT_ENV}{}${PROJECT_ENV}{}",
                        GREP_NUDGE[0], GREP_NUDGE[1], GREP_NUDGE[2]
                    ),
                },
            },
        },
        Hook {
            name: "graph-read",
            // The largest avoidable cost in a session: reading a whole module to
            // see one function, when get_code_snippet answers in ~1,500 bytes.
            // No file size named on purpose — the figure that used to be here
            // was stale on the commit that wrote it.
            //
            // Read is also the most frequent tool there is, so this speaks only
            // when a symbol lookup would actually be cheaper — a source file big
            // enough to be worth not reading whole. Otherwise silent: a nudge on
            // every call becomes noise the model tunes out. The extension test
            // comes first so the common case costs a `case` and not a `wc`.
            hook: Canonical {
                on: Event::BeforeTool,
                tools: vec![Tool::Read],
                when: Some(format!(
                    "case \"${f}\" in {SOURCE}) ;; *) false ;; esac && \
                     [ -f \"${f}\" ] && [ \"$(wc -c < \"${f}\")\" -gt 8000 ]",
                    f = Field::ToolFile.var()
                )),
                action: Action::Inject {
                    capture: None,
                    text: format!(
                        "${f} is large. For one symbol rather than the whole file: \
                         get_code_snippet --project ${PROJECT_ENV} --qualified-name <name>, \
                         and search_graph finds the name.",
                        f = Field::ToolFile.var()
                    ),
                },
            },
        },
    ]
}

/// A section of the rules omh ships, in the shape a layer would store one.
///
/// The `name` is the manifest entry it answers to, exactly as a hook's is —
/// `the_manifest_and_the_code_describe_the_same_base_set` compares the two
/// name sets in both directions, so a section cannot ship unexplained and an
/// entry cannot explain a section nobody writes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Section {
    pub name: &'static str,
    pub body: String,
}

/// What the agent is told about git, in one place.
///
/// Both deliveries read from here — the `git-rules` section and the
/// `git-unavailable` hook — because two copies of a safety notice drift, and
/// the one that drifts is never the one you are reading.
///
/// Written as a claim about *this session*, not about git: an agent told "git
/// is broken" spends its turns trying to fix it, and the repair cannot work.
///
/// It also does no harm, which was checked rather than assumed — `git init`
/// against an unreachable gitdir refuses (git 2.55.0), naming the missing
/// directory, and leaves the pointer file exactly as it was. So this says the
/// attempt is futile, not that it is dangerous. The expensive failure here is
/// the agent promising a commit it cannot make.
pub const GIT_ABSENT: &str = "git does not work in this session, by design and not by fault. \
     The worktree's .git is a pointer at an admin directory on the host, which omh does not \
     mount — so every git command fails with `fatal: not a git repository`. Do not try to \
     repair it: `git init` refuses for the same reason, and re-cloning would only give you a \
     second repository nobody is reviewing. Nothing here is broken and nothing is lost. Your \
     work is already visible outside the sandbox, where the person you are working with \
     reviews it with `omh s diff`, commits it with `omh s commit`, and pushes it with \
     `omh s push`. Say that rather than offering to commit yourself.";

/// The rules omh ships, one section per base-set entry.
///
/// They live here rather than in the manifest for the reason hook commands do:
/// `memory-rules` interpolates `GUEST_LOCAL_NOTES` and `git-rules` reads
/// `GIT_ABSENT`, which the hook reads too. Flattened into TOML both couplings
/// become two strings that can drift, and the drift is silent — a safety notice
/// saying one thing in the rules and another in the hook.
///
/// They were prose `init` appended to `.omh/profile/AGENTS.md`, which meant they
/// reached the repos where somebody remembered and nowhere else, could not be
/// explained by `omh why`, and were invisible to the cost rollup.
pub fn sections() -> Vec<Section> {
    vec![
        Section {
            name: "graph-rules",
            body: "## Code graph\n\n\
                 This repo is indexed as a graph, refreshed after every turn. Prefer it over\n\
                 reading or grepping files when the question is structural:\n\n\
                 - `search_graph` — where is X defined, what is named like Y\n\
                 - `trace_path` — how does A reach B\n\
                 - `get_architecture` — what the modules are and how they depend on each other\n\
                 - `get_code_snippet` — read one symbol instead of a whole file\n\n\
                 Grep is still right for literal text: a string, a config value, a TODO.\n\n\
                 **Use the project named by `$OMH_GRAPH_PROJECT`.** Other sessions of this\n\
                 repo have their own graphs in the same store; querying one of those answers\n\
                 confidently about code that is not in this worktree.\n"
                .into(),
        },
        Section {
            name: "git-rules",
            // Orientation, where the hook is interception: a hook can only fire
            // once the agent has decided to run git, and by then it may already
            // have promised the user a commit. This is what stops the plan being
            // made.
            body: format!("## Git\n\n{GIT_ABSENT}\n"),
        },
        Section {
            name: "memory-rules",
            // "Which graph to ask" ships with memory rather than with the graph
            // because the decision it teaches is *when to reach for `recall`*,
            // and `recall` is what this feature introduces. With memory off the
            // agent should not be told to ask a tool it does not have; with the
            // graph off it loses a comparison, which is the cheaper of the two
            // wrong documents.
            body: format!(
                "## Which graph to ask\n\n\
                 There are two, and they do not overlap:\n\n\
                 - **the code graph** knows **what the code is** — where a symbol lives, how\n  \
                   one module reaches another. Re-derived from the code every turn, so it is\n  \
                   never out of date and never needs to be told anything.\n\
                 - **`recall`** knows **why** it is that way — what was tried and failed, what\n  \
                   turned out not to work, what surprised somebody. None of that is in the\n  \
                   code, so no amount of reading will recover it.\n\n\
                 A *where* or *what* question goes to the code graph. A *why*, *is this safe*,\n\
                 or *has this been tried* question goes to `recall`. When you are about to\n\
                 assume how something here behaves, ask `recall` first — that is exactly the\n\
                 assumption somebody already got wrong once.\n\n\
                 They compose: find the code with the code graph, then ask `recall` what is\n\
                 known about it before changing it.\n\n\
                 {}",
                note_taking()
            ),
        },
    ]
}

/// What the agent needs to write a note, and when to write one.
///
/// The **trigger** cannot move into a tool description: *record what surprised
/// you* is a rule an agent cannot look up, because it does not know it needs
/// it. That half stays here whatever the tool surface looks like.
///
/// The note **shape** is a different claim, and the one to re-argue. It was
/// written when nothing in the sandbox could call `remember`; that stopped
/// being true when the memory server shipped — `remember` and `recall` are
/// both offered inside the session, and `remember` enforces the schema at the
/// write. What is left is the case `memory::deliver` documents: a released omh
/// that finds no binary to deliver launches a session with no memory server,
/// and the agent writes the file by hand. The shape is insurance against that,
/// not a substitute for a tool that does not exist.
///
/// It is the largest single cost in the base set, so it is worth re-measuring
/// against how often delivery actually fails rather than carrying forward.
fn note_taking() -> String {
    format!(
        "## Memory\n\n\
         When something surprises you — you expected one thing and the repo did\n\
         another — record it. Not what you did; what you were wrong about.\n\n\
         Write a Markdown file into `{}/`, named after the\n\
         observation, in this shape:\n\n\
         ```markdown\n\
         ---\n\
         key: <the filename, without .md>\n\
         type: surprise\n\
         source: session $OMH_SESSION, <this harness>\n\
         recorded: <YYYY-MM-DD, the day it happened>\n\
         ---\n\n\
         # One line naming the surprise\n\n\
         ## Expected\n\n\
         ## Observed\n\n\
         ## Evidence\n\n\
         ## Answers\n\n\
         - <the question somebody would later ask to find this>\n\n\
         ## Related\n\n\
         - [[another-notes-key]]\n\
         ```\n\n\
         **Answers** is what makes the note findable later, and only you know it:\n\
         write the question you would have asked five minutes ago, in the words you\n\
         would have used. A note nobody can find is a note nobody wrote.\n\n\
         Store uncertainty rather than false precision, and date by when the thing\n\
         happened rather than when you mentioned it. If you have nothing to put\n\
         under **Expected**, there is nothing here worth recording.\n\n\
         Rename a note by rewriting its `key` and its filename together — never\n\
         one without the other.\n",
        crate::memory::GUEST_LOCAL_NOTES,
    )
}

/// What omh itself contributes to a session — generated from the manifest, and
/// nothing else.
///
/// Resolved by the caller and handed to `container::plan`, the rule
/// `memory_bin` and `base` already follow: `plan` stays pure given a temp
/// filesystem, and a probe inside it is a probe no test can reach.
///
/// It used to carry `disabled_servers` and `mcp_env` as well, on the argument
/// that both are decisions about the rendered document arriving from outside
/// `plan`. True, and not enough — they are decisions *this repo* made, which is
/// the opposite of what this type's name claims, and the moment a third one
/// arrived the type was two things wearing one word. They live in
/// [`crate::settings::RepoPolicy`] now, and the two travel side by side.
///
/// Empty is a legitimate value — every feature switched off. What keeps a
/// caller from shipping an empty one *by accident* is `container::Options`,
/// which has no `Default` and so cannot be built without naming this field.
///
/// `Default` here is for tests, which construct the empty case deliberately.
#[cfg_attr(test, derive(Default))]
#[derive(Debug, Clone)]
pub struct Own {
    pub hooks: Vec<Hook>,
    pub sections: Vec<Section>,
    /// Every hook name the manifest owns, whether or not its feature is on.
    ///
    /// A file in a layer answering to one of these is never read. With the
    /// feature on the generated hook wins anyway; with it off, nothing runs —
    /// and it was the second case that shipped broken: the four graph hooks
    /// kept firing from files `init` seeded, against a server that had been
    /// taken out of the document. Disabling that leaves the disabled thing
    /// running is worse than not offering it.
    pub reserved: BTreeSet<String>,
}

/// Everything the manifest generates, minus the features this repo turned off.
///
/// A feature is all-or-nothing on purpose. `codegraph` on with `graph-refresh`
/// off is a graph that quietly stops tracking the code, which is the one
/// combination that manufactures confident wrong answers — so it is
/// unrepresentable rather than warned about.
///
/// Two ways a feature is off, and they are different acts:
///
/// - **switched off here**, by `[omh]`. Nothing is uninstalled.
/// - **removed**, by taking its server out of your profile. `remove` promises
///   that `omh config mcp rm codegraph` takes the hooks and the rules section
///   with it, and that command only edits `mcp.json` — so the promise is kept
///   here or nowhere. Before generation the hooks were files and removing the
///   server left four of them behind; generating them unconditionally would
///   have rebuilt that defect with no file left to delete.
///
/// `installed` is the servers the resolved profile declares. A feature with no
/// server of its own — `git-notice` — is unaffected by it.
///
/// Fails rather than filters when the binary ships a hook or a section this
/// manifest does not describe. That is omh disagreeing with itself, not a
/// preference somebody expressed, and the two were the same silent `false`:
/// the entry was not generated *and* `reserved` blocked any layer file from
/// standing in, so it existed nowhere and nothing said so.
pub fn own(
    manifest: &Manifest,
    off: &BTreeSet<String>,
    installed: &BTreeSet<String>,
) -> Result<Own> {
    // A feature keeps its non-server parts only while a server it owns is
    // still there. `any` rather than `all`: a feature with two servers and one
    // removed is a judgement nothing here can make, and keeping it is the
    // conservative half.
    let gone: BTreeSet<&str> = manifest
        .entries
        .iter()
        .filter(|e| e.kind == Kind::Mcp)
        .fold(BTreeMap::<&str, bool>::new(), |mut acc, e| {
            let present = installed.contains(&e.name);
            *acc.entry(e.feature.as_str()).or_insert(false) |= present;
            acc
        })
        .into_iter()
        .filter(|(_, present)| !present)
        .map(|(feature, _)| feature)
        .collect();

    let on = |name: &str| -> Result<bool> {
        let entry = manifest.entry(name).with_context(|| {
            format!(
                "this omh ships `{name}` and {} describes no entry for it — the                  binary and the manifest disagree about the base set.                  `omh init` refreshes the bundled manifest.",
                manifest.source()
            )
        })?;
        Ok(!off.contains(&entry.feature) && !gone.contains(entry.feature.as_str()))
    };

    let mut own = Own {
        hooks: Vec::new(),
        sections: Vec::new(),
        // Every hook the manifest owns, on or off — which is why this is built
        // from the manifest rather than from `hooks()`. A file answering to one
        // of these is never read, and with the feature off there would be
        // nothing to override it with.
        reserved: manifest
            .entries
            .iter()
            .filter(|e| e.kind == Kind::Hook)
            .map(|e| e.name.clone())
            .collect(),
    };
    for hook in hooks() {
        if on(hook.name)? {
            own.hooks.push(hook);
        }
    }
    for section in sections() {
        if on(section.name)? {
            own.sections.push(section);
        }
    }
    Ok(own)
}

/// Index a repository into the shared graph.
///
/// Runs **inside the sandbox**, because the cache is a container volume: an
/// index built on the host would be written somewhere no session can read.
pub fn index_args(
    image: &str,
    cache_volume: &str,
    repo: &std::path::Path,
    name: &str,
) -> Vec<String> {
    vec![
        "run".into(),
        "--rm".into(),
        "-v".into(),
        // Read-only: indexing reads code, and an indexer that can write into
        // the checkout is a sandbox hole for no benefit.
        format!("{}:/work:ro", repo.display()),
        "-v".into(),
        format!("{cache_volume}:{GRAPH_CACHE}"),
        // The server derives its project name from the working directory, not
        // from --repo-path: run elsewhere and `--name r` becomes
        // `some-other-path-r`. Verified against the real binary.
        "-w".into(),
        "/work".into(),
        image.into(),
        GRAPH_BIN.into(),
        "cli".into(),
        "index_repository".into(),
        "--repo-path".into(),
        "/work".into(),
        // Sessions live at different paths and the server derives a project
        // name from the path; without this every session builds its own graph.
        "--name".into(),
        name.into(),
        "--mode".into(),
        "fast".into(),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;
    use std::path::Path;

    /// The manifest as shipped. Tested through the real file rather than a
    /// fixture: a manifest that parses in a test and not in the wild is the
    /// failure this whole module exists to prevent.
    const BUNDLED: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/base");

    /// `git log --reverse --date=short | head -1`. Nothing in this repo could
    /// have been measured before it existed.
    const FIRST_COMMIT: (u32, u32, u32) = (2026, 8, 5);

    fn shipped() -> Manifest {
        Manifest::load_dir(Path::new(BUNDLED)).expect("bundled base manifest")
    }

    /// `docs/design/distribution.md` says every base-set entry states what it
    /// costs, what it buys, what was considered instead, and how to remove it —
    /// and that anything unable to fill in all four is taste pretending to be
    /// curation.
    ///
    /// That was aspiration written in a document nothing enforced. Here it is a
    /// test, so a future entry cannot be added without its reasoning: the
    /// cheapest moment to demand a justification is before it ships, and the
    /// only moment anyone reliably does is when something turns red.
    #[test]
    fn every_base_set_entry_states_its_case() {
        let manifest = shipped();
        assert!(
            !manifest.entries.is_empty(),
            "a base set with no entries is not a distribution"
        );

        for e in &manifest.entries {
            assert!(!e.because.trim().is_empty(), "{}: no `because`", e.name);
            assert!(
                !e.remove.trim().is_empty(),
                "{}: no way to remove it",
                e.name
            );
            assert!(
                !e.instead_of.is_empty(),
                "{}: nothing recorded as considered-instead. An entry with no \
                 alternatives was not chosen, it was defaulted to.",
                e.name
            );
            assert!(
                !e.measured.is_empty(),
                "{}: no measured cost. Benefit is argued here, but cost is the \
                 half that must be measured — it is what creeps.",
                e.name
            );
            assert!(!e.since.trim().is_empty(), "{}: no `since`", e.name);

            for m in &e.measured {
                for (field, value) in [
                    ("what", &m.what),
                    ("value", &m.value),
                    ("how", &m.how),
                    ("on", &m.on),
                ] {
                    assert!(
                        !value.trim().is_empty(),
                        "{}: measured `{field}` is blank",
                        e.name
                    );
                }
                // A date the tool cannot read is a manifest defect, not a
                // measurement. Left unchecked it silently disables staleness
                // for that cost and prints itself to the user verbatim.
                parse_ym(&m.on).unwrap_or_else(|| panic!("{}: `{}` is not a date", e.name, m.on));

                // Day precision, not month. Every `on` in this manifest once
                // read 2026-08-04 — one day before this repository's first
                // commit, so no measurement of this repo could have been taken
                // then. A month-granular check passes that date happily, which
                // is how the first version of this very assertion failed to
                // catch the thing it was written for.
                let day: Vec<u32> = m.on.split('-').filter_map(|p| p.parse().ok()).collect();
                assert_eq!(day.len(), 3, "{}: `{}` needs YYYY-MM-DD", e.name, m.on);
                assert!(
                    (day[0], day[1], day[2]) >= FIRST_COMMIT,
                    "{}: measured {} predates this repository ({}-{:02}-{:02})",
                    e.name,
                    m.on,
                    FIRST_COMMIT.0,
                    FIRST_COMMIT.1,
                    FIRST_COMMIT.2
                );
            }
        }
    }

    /// An entry that names no feature is an entry nobody can switch off.
    ///
    /// `[omh]` is keyed on features, so this is load-bearing rather than
    /// documentary: the field is the only thing standing between a new entry
    /// and a default with no way out — which is the one thing the base set's
    /// own rule forbids.
    ///
    /// The grouping it records existed as a comment header in the manifest,
    /// the single claim in that file no test could check, while every other
    /// claim an entry makes is a field with a guard demanding it be filled.
    #[test]
    fn every_base_set_entry_names_its_feature() {
        for e in &shipped().entries {
            assert!(
                !e.feature.trim().is_empty(),
                "{}: names no feature. An entry belonging to nothing cannot be \
                 disabled, because `[omh]` takes feature names.",
                e.name
            );
        }
    }

    /// `remove` is printed by `omh why` as the way out, so an instruction that
    /// silently does nothing is worse than none at all.
    ///
    /// The five hooks each said `rm .omh/profile/hooks/<name>.json`, naming a
    /// file omh no longer writes. Removal is feature-level now: the graph hooks
    /// go with the server, and the git notice has nothing to uninstall.
    #[test]
    fn no_remove_instruction_names_a_path_omh_no_longer_writes() {
        for e in &shipped().entries {
            assert!(
                !e.remove.contains(".omh/profile/"),
                "{}: `remove` says `{}`, and that path is not written any more — \
                 the hooks are generated from this manifest",
                e.name,
                e.remove
            );
        }
    }

    /// A tool the agent does not know about is a tool it will not use — half
    /// of what makes the graph more than an installed package.
    ///
    /// Named tools, when *not* to use them, and which project is its own: the
    /// store holds every session's graph, and querying another session's
    /// answers confidently about code that is not in this worktree.
    #[test]
    fn the_graph_section_explains_the_tools_and_which_project_to_ask() {
        let body = section_body("graph-rules");
        assert!(body.contains("search_graph"), "must name the tools: {body}");
        assert!(
            body.to_lowercase().contains("grep"),
            "and when not to use them: {body}"
        );
        assert!(
            body.contains("OMH_GRAPH_PROJECT"),
            "and which project is its own: {body}"
        );
    }

    /// The agent meets `fatal: not a git repository` and has to explain it to
    /// itself. Left to guess it reaches for `git init`, which refuses for the
    /// same reason and changes nothing — so the notice says the repair is
    /// futile rather than leaving that to be discovered a turn later.
    ///
    /// Naming what to run instead is the load-bearing half: an agent that
    /// knows only that git is missing still promises a commit it cannot make.
    #[test]
    fn the_git_section_says_the_repair_is_futile_and_what_to_do_instead() {
        let body = section_body("git-rules");
        assert!(
            body.contains("git init"),
            "the move it would otherwise make has to be named: {body}"
        );
        assert!(
            body.contains("omh s commit") && body.contains("omh s push"),
            "and what the human runs instead: {body}"
        );
    }

    fn section_body(name: &str) -> String {
        sections()
            .into_iter()
            .find(|s| s.name == name)
            .unwrap_or_else(|| panic!("{name} is a section omh ships"))
            .body
    }

    /// A feature is not a group of hooks. It is a group of entries **across
    /// kinds** — a server, the hooks that make it used, the section telling the
    /// agent it is there — and that is why it is the unit removal and disabling
    /// work on. Half of `codegraph` is not a smaller version of it.
    ///
    /// Asserted on the one feature that has all three, and asserted because the
    /// grouping used to be a comment header: removing the server left four
    /// hooks nudging the agent toward something that was gone.
    #[test]
    fn a_feature_gathers_entries_across_kinds() {
        let manifest = shipped();
        let kinds: BTreeSet<Kind> = manifest
            .entries
            .iter()
            .filter(|e| e.feature == "codegraph")
            .map(|e| e.kind)
            .collect();
        assert_eq!(
            kinds,
            BTreeSet::from([Kind::Mcp, Kind::Hook, Kind::Rules]),
            "codegraph is a server, the hooks that make it used, and the section \
             that tells the agent it exists"
        );
    }

    /// The rules are the one cost paid on every single turn, so the number in
    /// the manifest has to be the number the agent is actually handed.
    ///
    /// The same guard as `the_grep_nudges_declared_cost_matches_the_string_it_ships`,
    /// and for the same reason: `~40 B` sat in this file describing a 243-byte
    /// string, through a review that read it twice, because a hand-written cost
    /// and the string it describes have no relationship a test can check.
    #[test]
    fn every_rules_section_costs_what_it_says() {
        let manifest = shipped();
        for section in sections() {
            let entry = manifest
                .entry(section.name)
                .unwrap_or_else(|| panic!("{} has no manifest entry", section.name));
            let claim = &entry.measured[0].value;
            let declared: usize = claim
                .trim_end_matches(" B")
                .replace(',', "")
                .trim()
                .parse()
                .unwrap_or_else(|_| panic!("{}: `{claim}` is not a byte count", section.name));
            assert_eq!(
                declared,
                section.body.len(),
                "{}: the manifest claims {declared} B and the section ships {} B. \
                 Re-measure rather than trimming the prose to fit.",
                section.name,
                section.body.len()
            );
        }
    }

    /// `omh config mcp rm codegraph` has to take the hooks and the rules
    /// section with it. Before generation the four hooks were files and
    /// removing the server left them behind, nudging the agent toward
    /// something that was gone; generation would have reintroduced exactly
    /// that, because what omh generates was decided by the manifest alone.
    ///
    /// The `remove` field promises this. A guard on the *string* — which is
    /// what shipped first — passes just as happily when the instruction does
    /// nothing, so this asserts the behaviour instead.
    #[test]
    fn removing_a_feature_server_stops_generating_the_rest_of_it() {
        let manifest = shipped();
        let installed = BTreeSet::from(["memory".to_string()]);
        let own = own(&manifest, &BTreeSet::new(), &installed).unwrap();

        assert!(
            !own.hooks.iter().any(|h| h.name.starts_with("graph-")),
            "no graph hook may outlive its server: {:?}",
            own.hooks.iter().map(|h| h.name).collect::<Vec<_>>()
        );
        assert!(
            !own.sections.iter().any(|s| s.name == "graph-rules"),
            "and neither may the section telling the agent to query it"
        );
        assert!(
            own.sections.iter().any(|s| s.name == "memory-rules"),
            "memory is still installed, so its section stays"
        );
        assert!(
            own.hooks.iter().any(|h| h.name == "git-unavailable"),
            "git-notice has no server to remove, so nothing about it changes"
        );
    }

    /// A name the code ships and the manifest does not describe is not a
    /// feature somebody switched off — it is omh disagreeing with itself, and
    /// the two states were the same `false`.
    ///
    /// What made it destructive rather than merely lossy: the hook was not
    /// generated *and* `reserved` blocked any layer file of that name from
    /// substituting, so it existed nowhere and nothing said so. Reachable by
    /// hand-editing `~/.omh/base`, which `omh why`'s own comment calls a
    /// directory anyone can drop a file into.
    #[test]
    fn a_shipped_hook_the_manifest_does_not_describe_is_an_error() {
        let dir = manifest_dir(&[("2026.08.toml", &format!("version = \"2026.08\"{ONE_ENTRY}"))]);
        let manifest = Manifest::load_dir(dir.path()).unwrap();

        let err = own(&manifest, &BTreeSet::new(), &BTreeSet::new())
            .expect_err("the binary ships hooks this manifest never mentions");
        let err = format!("{err:#}");
        assert!(err.contains("graph-refresh"), "must name it: {err}");
        assert!(err.contains("omh init"), "and the way out: {err}");
    }

    /// A hand-written cost and the thing it measures have no relationship a
    /// test can check — which is how `~40 B` sat in the manifest describing a
    /// 243-byte string, through a review that read it twice.
    ///
    /// Where a cost is computable it gets computed, and the manifest has to
    /// agree. This is the only measurement in the base set that can be checked
    /// in-process; the rest need a container, and are the reason `omh doctor`
    /// exists for adapter claims.
    #[test]
    fn the_grep_nudges_declared_cost_matches_the_string_it_ships() {
        // A representative session project name — `repo-sNN`, and it appears
        // twice in the nudge, so the length is not incidental.
        let project = project_name("ohmyharness", "s01");
        let actual = grep_nudge(&project).len();

        let entry = shipped()
            .entry("graph-first")
            .expect("graph-first in the manifest")
            .measured[0]
            .value
            .clone();
        let declared: usize = entry
            .trim_end_matches(" B")
            .replace(',', "")
            .trim()
            .parse()
            .unwrap_or_else(|_| panic!("graph-first cost `{entry}` is not a byte count"));

        assert_eq!(
            declared, actual,
            "the manifest claims {declared} B; the nudge it ships is {actual} B for project \
             `{project}`. Re-measure rather than adjusting the string to fit."
        );
    }

    // ── load_dir ────────────────────────────────────────────────────────────
    //
    // This had no tests, which is how it shipped three ways to silently choose
    // the wrong base set. All of them were found by running the binary in a
    // scratch HOME, none by reading it.

    fn manifest_dir(files: &[(&str, &str)]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for (name, body) in files {
            std::fs::write(dir.path().join(name), body).unwrap();
        }
        dir
    }

    const ONE_ENTRY: &str = r#"
[[entry]]
name = "codegraph"
kind = "mcp"
feature = "codegraph"
since = "2026.06"
because = "b"
remove = "r"
command = "c"
"#;

    /// The manifest in `~/.omh/base` is whatever the last `init` seeded, and a
    /// newer omh can require a field it does not have — `feature` did exactly
    /// that. Every command loads the manifest, so the upgrade turns the whole
    /// tool off until it is refreshed, and the way to refresh it is the one
    /// thing the error has to say.
    ///
    /// The closed loop this repo already paid for once: `chmod 000` on
    /// `mcp.json` made `omh why` advise `omh init`, which did nothing. Here
    /// `init` genuinely fixes it — bundled files are refreshed, with the old
    /// one kept — so the advice is worth giving and worth pinning.
    #[test]
    fn a_manifest_an_older_omh_wrote_says_how_to_refresh_it() {
        let dir = manifest_dir(&[(
            "2026.08.toml",
            "version = \"2026.08\"\n[[entry]]\nname = \"codegraph\"\nkind = \"mcp\"\n\
             since = \"2026.06\"\nbecause = \"b\"\nremove = \"r\"\ncommand = \"c\"\n",
        )]);
        let err = format!("{:#}", Manifest::load_dir(dir.path()).unwrap_err());
        assert!(err.contains("2026.08.toml"), "must name the file: {err}");
        assert!(err.contains("omh init"), "must say the way out: {err}");
    }

    /// A stray `.toml` sorting after the real manifest used to *become* the
    /// base set: `init` seeded `{}` and reported success, and `omh why` called
    /// omh's own entries the user's.
    #[test]
    fn a_stray_toml_cannot_become_the_base_set() {
        let dir = manifest_dir(&[
            ("2026.08.toml", &format!("version = \"2026.08\"{ONE_ENTRY}")),
            ("zz-notes.toml", "version = \"notes\"\n"),
        ]);
        let m = Manifest::load_dir(dir.path()).unwrap();
        assert_eq!(m.version, "2026.08");
        assert_eq!(m.servers().len(), 1, "the real manifest must win");
    }

    /// Filename sort made `2027.2` beat `2027.10`, silently serving an older
    /// base set. Zero-padding was load-bearing and unenforced.
    #[test]
    fn versions_are_compared_numerically_not_lexicographically() {
        let dir = manifest_dir(&[
            ("z.toml", &format!("version = \"2027.2\"{ONE_ENTRY}")),
            ("a.toml", &format!("version = \"2027.10\"{ONE_ENTRY}")),
        ]);
        assert_eq!(Manifest::load_dir(dir.path()).unwrap().version, "2027.10");
    }

    /// The failure `the_document_init_seeds_actually_contains_the_base_set`
    /// describes, arriving through the runtime path that test cannot see: a
    /// manifest that parses but names nothing seeds an empty base set while
    /// hooks still point at a server that is not installed.
    #[test]
    fn a_manifest_naming_nothing_is_an_error_not_an_empty_base_set() {
        let dir = manifest_dir(&[("2026.08.toml", "version = \"2026.08\"\n")]);
        let err = Manifest::load_dir(dir.path()).unwrap_err().to_string();
        assert!(err.contains("no base-set entries"), "got: {err}");
    }

    #[test]
    fn an_empty_directory_says_what_to_do() {
        let dir = manifest_dir(&[]);
        let err = Manifest::load_dir(dir.path()).unwrap_err().to_string();
        assert!(err.contains("omh init"), "got: {err}");
    }

    /// Every answer has to be able to name the manifest that produced it.
    #[test]
    fn a_loaded_manifest_knows_where_it_came_from() {
        let dir = manifest_dir(&[("2026.08.toml", &format!("version = \"2026.08\"{ONE_ENTRY}"))]);
        let source = Manifest::load_dir(dir.path()).unwrap().source();
        assert!(source.contains("2026.08.toml"), "got: {source}");
        assert!(source.contains("2026.08"), "got: {source}");
    }

    /// A rejection is a product artifact. Without one recorded, the same
    /// candidate gets re-litigated every time someone rediscovers it.
    #[test]
    fn rejections_say_why_they_were_rejected() {
        for r in &shipped().rejected {
            assert!(
                !r.because.trim().is_empty(),
                "{}: rejected with no reason",
                r.name
            );
        }
    }

    /// The manifest carries the *reasoning*; hook commands stay in code, because
    /// they are intricate shell that interpolates `GRAPH_BIN` and `PROJECT_ENV`
    /// and would lose that coupling flattened into TOML.
    ///
    /// Two sources describing one base set can drift, and the drift is silent in
    /// the worst direction: `omh why` confidently explaining an entry that is no
    /// longer installed, or an entry shipping with no explanation at all. So the
    /// name sets must match exactly, in both directions.
    #[test]
    fn the_manifest_and_the_code_describe_the_same_base_set() {
        let manifest = shipped();

        let declared: BTreeSet<&str> = manifest
            .entries
            .iter()
            .filter(|e| e.kind == Kind::Hook)
            .map(|e| e.name.as_str())
            .collect();
        let shipped_hooks: BTreeSet<&str> = hooks().iter().map(|h| h.name).collect();
        assert_eq!(
            declared, shipped_hooks,
            "hooks in the manifest vs hooks in the code"
        );

        // The rules sections have the same split for the same reason, and so
        // the same failure available: a section shipped with no entry reaches
        // every session unexplained and uncosted, and an entry with no section
        // is `omh why` describing prose nobody receives.
        let declared: BTreeSet<&str> = manifest
            .entries
            .iter()
            .filter(|e| e.kind == Kind::Rules)
            .map(|e| e.name.as_str())
            .collect();
        let shipped_sections: BTreeSet<&str> = sections().iter().map(|s| s.name).collect();
        assert_eq!(
            declared, shipped_sections,
            "rules sections in the manifest vs sections in the code"
        );

        // MCP servers are not checked here: since `Manifest::servers()` derives
        // from the manifest there is no second definition to disagree with, and
        // asserting it would only prove that a filter works. The hook half is
        // real because hook *commands* genuinely still live in code.
    }

    /// `Manifest::servers()` drops an entry whose `command` is missing, so an
    /// mcp entry without one is installed nowhere while still being listed in
    /// the base set and explained by `omh why` — present in every account of
    /// itself except the one that matters.
    #[test]
    fn an_mcp_entry_without_a_command_is_not_silently_dropped() {
        let manifest = shipped();
        let declared = manifest
            .entries
            .iter()
            .filter(|e| e.kind == Kind::Mcp)
            .count();
        assert_eq!(
            declared,
            manifest.servers().len(),
            "an mcp entry is missing its `command` and would seed nothing"
        );
    }

    /// Exactly the document `init` writes into the shared layer.
    ///
    /// A manifest that parses but yields an empty server map is silent on both
    /// sides: init reports success, and every new sandbox simply comes up
    /// without a graph. Nothing downstream notices, because "no MCP servers
    /// configured" is a legitimate state.
    #[test]
    fn the_document_init_seeds_actually_contains_the_base_set() {
        let manifest = shipped();
        let body =
            serde_json::to_string_pretty(&serde_json::json!({ "mcpServers": manifest.servers() }))
                .unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
        let servers = parsed["mcpServers"]
            .as_object()
            .expect("an mcpServers object");
        assert!(!servers.is_empty(), "init would seed an empty base set");
        assert_eq!(servers["codegraph"]["command"], GRAPH_BIN);
    }

    #[test]
    fn the_base_set_ships_a_code_graph() {
        let s = shipped().servers();
        assert!(
            s.contains_key("codegraph"),
            "got: {:?}",
            s.keys().collect::<Vec<_>>()
        );
        assert_eq!(s["codegraph"].command, GRAPH_BIN);
    }

    /// The manifest's arguments and the launcher's mounts have to name the
    /// same directories. A server that starts, finds nothing, and reports "0
    /// notes" is the failure this prevents — it looks exactly like an empty
    /// store, so nobody investigates.
    ///
    /// Asserted against the constants rather than against literals, so moving
    /// a mount without updating the manifest cannot stay green.
    #[test]
    fn the_memory_server_is_pointed_at_the_directories_omh_mounts() {
        let servers = shipped().servers();
        let memory = servers
            .get(crate::memory::tools::SERVER_KEY)
            .expect("the base set must declare the memory server");

        assert!(
            memory
                .args
                .iter()
                .any(|a| a == crate::memory::GUEST_LOCAL_NOTES),
            "the local store is mounted at {}, args say {:?}",
            crate::memory::GUEST_LOCAL_NOTES,
            memory.args
        );
        // The committed layer is tracked, so it arrives inside the worktree —
        // there is no mount for it, and its path is /work-relative.
        assert!(
            memory.args.iter().any(|a| a == "/work/.omh/notes"),
            "the team store lives in the checkout: {:?}",
            memory.args
        );
        // Nothing that pins a session: one manifest serves every session, and
        // the server reads $OMH_SESSION for provenance.
        assert!(
            !memory.args.iter().any(|a| a.contains("--session")),
            "a session baked into the base set would be wrong for every other one"
        );
    }

    /// A hand-typed byte count in this file has already been wrong by 5x — the
    /// grep nudge declared ~40 B and shipped 243. Anything computable in
    /// process is computed, and this is.
    #[test]
    fn the_memory_surfaces_declared_cost_matches_what_it_ships() {
        let mut server = crate::memory::tools::Server {
            team: std::path::PathBuf::from("/nonexistent-team"),
            local: std::path::PathBuf::from("/nonexistent-local"),
            templates: crate::memory::shipped_templates(),
            session: "s01".into(),
            client: None,
            today: || "2026-08-08".to_string(),
        };
        let listed = crate::mcp::Tools::list(&mut server);
        let actual: usize = listed
            .iter()
            .map(|t| {
                t.name.len()
                    + t.description.len()
                    + serde_json::to_string(&t.input_schema).unwrap().len()
            })
            .sum();

        let declared = shipped()
            .entries
            .iter()
            .find(|e| e.name == "memory")
            .expect("the memory entry")
            .measured
            .iter()
            .find(|m| m.what.contains("injected"))
            .expect("an injected-cost measurement")
            .value
            .trim_end_matches(" B")
            .parse::<usize>()
            .expect("a byte count");

        assert_eq!(
            actual, declared,
            "re-measure rather than adjusting the surface to fit"
        );
    }

    /// Base servers run in the sandbox. A command carrying a host path would
    /// work on the machine that wrote it and nowhere else.
    #[test]
    fn base_servers_reference_nothing_on_the_host() {
        for (name, server) in shipped().servers() {
            assert!(
                !server.command.contains('/'),
                "{name}: {} is a host path",
                server.command
            );
            for arg in &server.args {
                assert!(
                    !arg.starts_with("/Users") && !arg.starts_with("/home/")
                        || arg.starts_with("/home/agent"),
                    "{name}: {arg} is not a sandbox path"
                );
            }
        }
    }

    /// Every entry has to be able to answer "why is this here", and the answer
    /// has to be an actual sentence. `every_base_set_entry_states_its_case`
    /// checks a `because` exists; this checks it says something.
    #[test]
    fn every_entry_carries_its_argument() {
        let manifest = shipped();
        let reasons: BTreeMap<_, _> = manifest.rationale().into_iter().collect();
        for name in manifest.servers().keys() {
            let why = reasons
                .get(name.as_str())
                .unwrap_or_else(|| panic!("{name} has no rationale"));
            assert!(why.len() > 20, "{name}: `{why}` explains nothing");
        }
    }

    // ── indexing ────────────────────────────────────────────────────────────

    #[test]
    fn indexing_runs_inside_the_sandbox_with_the_cache_mounted() {
        let args = index_args(
            "omh/base:x",
            "omh-cache-repo",
            Path::new("/host/repo"),
            "repo",
        );
        let joined = args.join(" ");
        assert!(
            joined.contains("omh-cache-repo:"),
            "the cache volume must be mounted: {joined}"
        );
        assert!(
            joined.contains(GRAPH_CACHE),
            "at the path the server uses: {joined}"
        );
        assert!(
            joined.contains("/host/repo:"),
            "the code must be readable: {joined}"
        );
    }

    /// The repo is mounted read-only: indexing reads code, and an indexer that
    /// can write into the checkout is a sandbox hole for no benefit.
    #[test]
    fn indexing_cannot_write_to_the_checkout() {
        let joined = index_args("omh/base:x", "vol", Path::new("/host/repo"), "repo").join(" ");
        assert!(joined.contains("/host/repo:/work:ro"), "got: {joined}");
    }

    /// Sessions live at different paths, and the server derives a project name
    /// from the path. Without a stable name every session would build its own
    /// graph from scratch and share nothing.
    #[test]
    fn every_session_indexes_into_one_named_project() {
        let a = index_args("i", "v", Path::new("/host/repo"), "myrepo").join(" ");
        let b = index_args("i", "v", Path::new("/host/worktrees/s01"), "myrepo").join(" ");
        assert!(a.contains("--name myrepo") && b.contains("--name myrepo"));
    }

    #[test]
    fn indexing_names_the_repository_it_was_given() {
        let joined = index_args("i", "v", Path::new("/host/repo"), "r").join(" ");
        assert!(joined.contains("--repo-path /work"), "got: {joined}");
    }

    // ── keeping the graph current ───────────────────────────────────────────

    /// The server derives its project name from the **working directory**, not
    /// from `--repo-path`: run elsewhere, `--name probe` becomes
    /// `private-tmp-…-scratchpad-probe`. Verified against the real binary.
    #[test]
    fn indexing_runs_with_the_repo_as_its_working_directory() {
        let args = index_args("i", "v", Path::new("/host/repo"), "r");
        assert!(
            args.windows(2).any(|w| w[0] == "-w" && w[1] == "/work"),
            "the project name depends on cwd: {args:?}"
        );
    }

    #[test]
    fn a_sessions_graph_is_its_own() {
        assert_ne!(project_name("repo", "s01"), project_name("repo", "s02"));
        assert_ne!(project_name("alpha", "s01"), project_name("beta", "s01"));
    }

    #[test]
    fn a_sessions_graph_name_is_stable() {
        assert_eq!(project_name("repo", "s01"), project_name("repo", "s01"));
    }

    // ── hooks ───────────────────────────────────────────────────────────────

    fn hook(name: &str) -> Hook {
        hooks()
            .into_iter()
            .find(|h| h.name == name)
            .unwrap_or_else(|| panic!("no {name} hook"))
    }

    const ADAPTERS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/adapters");

    /// A hook as a harness actually receives it.
    ///
    /// Every assertion below is made here rather than against the authored
    /// hook, and that is the point: authored, `graph-read` says `before-tool`
    /// and `$OMH_TOOL_FILE`, which is a claim about nothing until an adapter
    /// has spelled both. Running these against the rendering is what makes the
    /// suite prove the translation as well as the hook — and the shipped
    /// adapter is the one whose maps have to be right.
    fn rendered(name: &str) -> crate::hook::Rendered {
        let adapter = crate::adapter::Adapter::find(Path::new(ADAPTERS), "claude").unwrap();
        let binding = adapter
            .supports(crate::adapter::Capability::Hooks)
            .expect("claude has hooks");
        match crate::hook::render(name, &hook(name).hook, binding, &adapter.tools).unwrap() {
            crate::hook::Outcome::Rendered(r) => r,
            crate::hook::Outcome::Dropped(d) => panic!("claude cannot express {d}"),
        }
    }

    /// Every shipped hook, rendered for the shipped adapter.
    fn all_rendered() -> Vec<(&'static str, crate::hook::Rendered)> {
        hooks()
            .into_iter()
            .map(|h| (h.name, rendered(h.name)))
            .collect()
    }

    /// A graph that describes the code as it was when the session started is
    /// worse than none: it answers confidently about code the agent has since
    /// rewritten. Re-indexing costs 0.14s.
    #[test]
    fn the_graph_refreshes_when_a_turn_ends() {
        let h = rendered("graph-refresh");
        assert_eq!(h.event, "Stop");
        assert!(h.command.contains("index_repository"), "got: {}", h.command);
        assert!(
            h.command.contains("/work"),
            "it indexes the session, not the checkout"
        );
    }

    /// The whole point. An MCP server the agent never reaches for is installed
    /// and inert.
    #[test]
    fn the_agent_is_pointed_at_the_graph_before_it_greps() {
        let h = rendered("graph-first");
        assert_eq!(h.event, "PreToolUse");
        assert!(h.matcher.contains("Grep"), "got: {}", h.matcher);
        assert!(
            h.command.contains("search_graph"),
            "the nudge must name the tool to use: {}",
            h.command
        );
    }

    /// A nudge, not a wall: grep is the right tool for a literal string, and a
    /// hook that blocks correct work gets disabled.
    #[test]
    fn the_nudge_never_blocks_the_tool() {
        let h = rendered("graph-first");
        for forbidden in ["exit 1", "deny", "block"] {
            assert!(
                !h.command.contains(forbidden),
                "must not block: {}",
                h.command
            );
        }
    }

    /// Hooks are one shared file across every session, so they name the project
    /// through the environment rather than baking a session into the text.
    ///
    /// Scoped to the hooks that reach the graph, which is where the guarantee
    /// comes from: the store holds every session's graph for this repo, so a
    /// query that does not name one answers about the wrong worktree. A hook
    /// that touches no store has no project to name, and asserting otherwise
    /// would only force a variable into text that does not use it.
    #[test]
    fn hooks_that_query_the_graph_name_their_project_through_the_environment() {
        let querying: Vec<_> = all_rendered()
            .into_iter()
            .filter(|(_, r)| r.command.contains(GRAPH_BIN))
            .collect();
        assert!(
            !querying.is_empty(),
            "the filter must still match something"
        );
        for (name, r) in querying {
            assert!(
                r.command.contains(PROJECT_ENV),
                "{name} must name its project: {}",
                r.command
            );
        }
    }

    /// The store holds every session's graph for this repo. A nudge that names
    /// the tool but not the project invites the agent to answer confidently
    /// about code that is not in this worktree — and it fires at the moment the
    /// agent is deciding, which is where naming it actually lands.
    #[test]
    fn the_nudge_names_the_project_to_query() {
        let h = rendered("graph-first");
        assert!(h.command.contains(PROJECT_ENV), "got: {}", h.command);
    }

    /// The rules file says this too, but a rules file decays as context grows —
    /// which is the reason this repo already gives for preferring delivery
    /// attached to the call. The hook fires at the moment the agent reaches for
    /// git, which is where the sentence actually lands.
    #[test]
    fn the_git_notice_fires_on_the_call_that_would_fail() {
        let h = rendered("git-unavailable");
        assert_eq!(h.event, "PreToolUse");
        assert_eq!(h.matcher, "Bash", "git arrives as a shell command");
        assert!(
            h.command.contains("git init"),
            "the repair it would otherwise reach for has to be named: {}",
            h.command
        );
    }

    /// P5's whole point: the translation, exercised by a second harness.
    ///
    /// Two of the five cross and three do not, and *which* is the result rather
    /// than a disappointment — `git-unavailable` crosses because `refuse` gave
    /// it a way to say it blocks, and the three nudges do not because opencode
    /// has no advisory channel before a tool runs. Named, not silent.
    #[test]
    fn omhs_hooks_translate_to_opencode_or_are_named() {
        let adapter = crate::adapter::Adapter::find(Path::new(ADAPTERS), "opencode").unwrap();
        let binding = adapter
            .supports(crate::adapter::Capability::Hooks)
            .expect("opencode has hooks now");

        // Through `render::document`, not `hook::render`: the rule that an
        // advisory nudge has no channel before a tool runs is the *plugin*
        // renderer's, because it is a fact about opencode's hook surface rather
        // than about any map. Asking the Claude-shaped renderer answered that
        // `graph-read` translates fine, which is how this test first passed
        // three names short.
        let own = crate::base::Own {
            hooks: hooks(),
            ..Default::default()
        };
        let doc = crate::render::document(
            crate::adapter::Capability::Hooks,
            binding,
            &[],
            &own,
            &Default::default(),
            &adapter.tools,
        )
        .unwrap();

        let named: Vec<&str> = doc.dropped.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(
            named,
            vec!["graph-first", "graph-orient", "graph-read"],
            "the advisory ones are dropped by name, never downgraded to a wall"
        );
        for landed in ["graph-refresh", "git-unavailable"] {
            assert!(
                doc.body.contains(landed),
                "a `run` and a `refuse` are what this harness can express: {}",
                doc.body
            );
        }
    }

    /// The git notice blocks the call rather than advising against it.
    ///
    /// It was an `inject` — a notice, with the call going ahead — so the agent
    /// read "git does not work here" and then ran `git status` anyway, spending
    /// a tool call to reach an error omh already knew was coming. git genuinely
    /// cannot work in this sandbox: there is no repository at `/work` that the
    /// agent may commit to, which is the whole point of the worktree model.
    ///
    /// It is the one hook in the base set that should block. The graph nudges
    /// must not — `graph-first` says so itself, "a nudge, not a wall" — and the
    /// format now carries the difference rather than leaving each renderer to
    /// guess it.
    #[test]
    fn the_git_notice_blocks_rather_than_advises() {
        let git = hooks()
            .into_iter()
            .find(|h| h.name == "git-unavailable")
            .expect("the base set ships it");
        assert!(
            matches!(git.hook.action, crate::hook::Action::Refuse { .. }),
            "got: {:?}",
            git.hook.action
        );

        // And the nudges still do not, or the change went too far.
        for name in ["graph-first", "graph-read", "graph-orient"] {
            let h = hooks().into_iter().find(|h| h.name == name).unwrap();
            assert!(
                matches!(h.hook.action, crate::hook::Action::Inject { .. }),
                "{name} is a nudge and has to stay one: {:?}",
                h.hook.action
            );
        }
    }

    /// omh's five are held to the format they impose on everybody else.
    ///
    /// `base::hooks()` builds `hook::Hook` by struct literal, so `parse` — the
    /// function whose doc says "no caller can hold an unchecked hook" — is
    /// never reached for the hooks that ship to every user.
    ///
    /// **What this covers narrowed when `Action` arrived**, and saying so is
    /// the point. Run-and-inject, neither, and a capture nothing reads are no
    /// longer things a struct literal can express, so no test is what stops
    /// them. What is left is the one check on a *value*: put a `$` in
    /// `GIT_ABSENT` or `GREP_NUDGE` — a price, a `$PATH` mention, a shell
    /// example — and the sandbox shell expands it to nothing, so the agent
    /// reads a sentence with a hole in it. Every assertion about the hook's
    /// text still passes, because the text is right; only the expansion is
    /// wrong. No type can take that one away.
    #[test]
    fn omhs_own_hooks_obey_the_format_they_impose() {
        for h in hooks() {
            // Serialised through `Hook`'s own wire shape rather than a `json!`
            // rebuilt by hand. A hand-built one is a second opinion about what
            // a hook file looks like, and it can be wrong in the same direction
            // as the code — this way the bytes are the ones omh would write.
            let json = serde_json::to_string(&h.hook).unwrap();
            let back = crate::hook::Hook::parse(&json, h.name)
                .unwrap_or_else(|e| panic!("{} is not a hook a user could write: {e:#}", h.name));
            assert_eq!(back, h.hook, "and it must survive the round trip");
        }
    }

    /// Every hook is a shell one-liner, and nothing else here would notice one
    /// that cannot parse.
    ///
    /// The `git-unavailable` hook embeds prose, and prose contains apostrophes:
    /// a `shell_quote` that lets one through produces `unexpected EOF while
    /// looking for matching '`, which is a hook that silently never runs. Every
    /// assertion over a hook's *command string* is satisfied by that hook —
    /// `contains("git init")` passes on a script `sh` refuses to parse. This is
    /// the cheapest guard that covers all of them, including the ones whose
    /// binaries are not installed here.
    #[test]
    fn every_hook_command_is_valid_shell() {
        for (name, r) in all_rendered() {
            let out = std::process::Command::new("sh")
                .args(["-n", "-c", &r.command])
                .output()
                .expect("sh must run");
            assert!(
                out.status.success(),
                "{name} is not parseable by sh: {}\n{}",
                String::from_utf8_lossy(&out.stderr),
                r.command
            );
        }
    }

    /// And that every one of them survives being *run*, which parsing does not
    /// prove: an unbound variable, a `case` that falls through to an error, or a
    /// missing binary all parse fine.
    ///
    /// The graph binary is stubbed rather than required — what is under test is
    /// omh's script, not the server. A hook whose tool is absent must still exit
    /// 0 and stay quiet, because a session where the graph is not installed is
    /// a session, not a failure.
    #[test]
    fn every_hook_runs_quietly_when_its_tool_says_nothing() {
        let stub = tempfile::tempdir().unwrap();
        for name in [GRAPH_BIN, "codebase-memory-mcp"] {
            let at = stub.path().join(name);
            std::fs::write(&at, "#!/bin/sh\nexit 0\n").unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&at, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
        }
        let path = format!(
            "{}:{}",
            stub.path().display(),
            std::env::var("PATH").unwrap_or_default()
        );

        for (name, r) in all_rendered() {
            let out = std::process::Command::new("sh")
                .arg("-c")
                .arg(&r.command)
                .env("PATH", &path)
                .env(PROJECT_ENV, "repo-s01")
                .stdin(std::process::Stdio::null())
                .output()
                .expect("sh must run");
            assert!(
                out.status.success(),
                "{name} exited {:?}: {}",
                out.status.code(),
                String::from_utf8_lossy(&out.stderr)
            );
            assert!(
                out.stderr.is_empty(),
                "{name} wrote to stderr, which the harness shows the user: {}",
                String::from_utf8_lossy(&out.stderr)
            );
        }
    }

    /// Run the hook the way the harness does.
    ///
    /// Asserting on the command *string* proves the sentence is embedded, never
    /// that a shell will emit it — and this one is a `case` over prose that has
    /// to survive `sh` quoting. Two separate defects lived through the string
    /// assertion above: the pattern matching nothing, and `shell_quote` letting
    /// the apostrophe in "worktree's" end the argument, which is a syntax error
    /// rather than a wrong answer.
    fn fire_hook(command: &str) -> String {
        use std::io::Write;
        let mut child = std::process::Command::new("sh")
            .arg("-c")
            .arg(&rendered("git-unavailable").command)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .expect("sh must run");
        let payload = serde_json::json!({ "tool_input": { "command": command } });
        child
            .stdin
            .take()
            .unwrap()
            .write_all(payload.to_string().as_bytes())
            .unwrap();
        let out = child.wait_with_output().unwrap();
        assert!(
            out.stderr.is_empty(),
            "the hook must not write to stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8(out.stdout).unwrap()
    }

    /// The prose survives shell quoting intact — and arrives as a *decision*,
    /// not a notice. The hook blocks the call now, so the reason travels under
    /// `permissionDecisionReason` rather than `additionalContext`.
    #[test]
    fn the_git_notice_reaches_the_agent_verbatim() {
        let fired = fire_hook("git status");
        let parsed: serde_json::Value =
            serde_json::from_str(&fired).unwrap_or_else(|e| panic!("not JSON: {fired} ({e})"));
        let out = &parsed["hookSpecificOutput"];
        // Claude Code discards a `hookSpecificOutput` that does not name its
        // event, so this key is what makes the decision arrive at all — and
        // deleting it from the template left the whole suite green.
        assert_eq!(
            out["hookEventName"].as_str(),
            Some("PreToolUse"),
            "a decision that does not name its moment is discarded: {fired}"
        );
        assert_eq!(
            out["permissionDecision"].as_str(),
            Some("deny"),
            "the call is blocked, not merely commented on: {fired}"
        );
        assert_eq!(
            out["permissionDecisionReason"].as_str().unwrap(),
            GIT_ABSENT,
            "the prose has to survive shell quoting intact"
        );
    }

    /// The shapes an agent actually emits. A newline-separated script is the
    /// most common of them and the easiest to miss, because a `case` separator
    /// class written by hand does not include one.
    #[test]
    fn the_git_notice_matches_git_wherever_a_command_can_start() {
        for command in [
            "git status",
            "cd /work && git status",
            "cd /work; git init",
            "cd /work\ngit status",
            "  git status",
            "echo hi | git apply",
        ] {
            assert!(
                !fire_hook(command).trim().is_empty(),
                "silent on {command:?}, which is a git call"
            );
        }
    }

    /// Bash is most of what an agent runs, so a nudge on every call is the
    /// noise `graph-read` exists to avoid. This is the `0 B` the manifest claims.
    #[test]
    fn the_git_notice_is_silent_on_everything_else() {
        for command in ["cargo test", "ls -la", "echo git", "rg digital"] {
            assert!(
                fire_hook(command).trim().is_empty(),
                "fired on {command:?}, which is not a git call"
            );
        }
    }

    // ── the graph UI ────────────────────────────────────────────────────────

    /// The npm package cannot deliver the UI build. Verified in a container:
    /// `CBM_VARIANT=ui npm install -g` still reports "built without the
    /// embedded UI", because the published installer ignores the variable.
    #[test]
    fn the_ui_build_comes_from_the_release_not_npm() {
        let cmd = graph_install();
        assert!(cmd.contains("-ui-"), "must fetch the UI variant: {cmd}");
        assert!(!cmd.contains("npm install"), "npm cannot deliver it: {cmd}");
    }

    /// A binary fetched over the network into an image every session runs is
    /// exactly where a supply-chain check earns its keep — and upstream
    /// publishes checksums.
    #[test]
    fn the_download_is_checksum_verified() {
        let cmd = graph_install();
        assert!(cmd.contains("checksums.txt"), "got: {cmd}");
        assert!(cmd.contains("sha256sum -c"), "got: {cmd}");
    }

    /// Apple Silicon builds arm64 images and Intel builds amd64; a hardcoded
    /// arch fails on one of them with a confusing exec error.
    #[test]
    fn the_download_follows_the_build_architecture() {
        let cmd = graph_install();
        assert!(
            cmd.contains("TARGETARCH") || cmd.contains("dpkg --print-architecture"),
            "arch must be derived: {cmd}"
        );
    }

    /// Verified in a container: backgrounded with stdin closed, the server logs
    /// `ui.serving` and then `server.shutdown` immediately — the UI dies with
    /// the stdio session.
    #[test]
    fn serving_the_ui_holds_stdin_open() {
        let cmd = ui_command(GRAPH_UI_PORT);
        assert!(
            cmd.contains("sleep infinity |"),
            "stdin must stay open: {cmd}"
        );
        assert!(cmd.contains("--ui=true"), "got: {cmd}");
    }

    /// The server binds container loopback and has no bind-address flag, so a
    /// published port forwards to nothing. Verified: HTTP 200 inside the
    /// sandbox, no response from the host.
    #[test]
    fn the_ui_is_bridged_onto_an_interface_the_host_can_reach() {
        let cmd = ui_command(GRAPH_UI_PORT);
        assert!(cmd.contains("socat"), "got: {cmd}");
        assert!(
            cmd.contains(&format!("TCP-LISTEN:{GRAPH_UI_PORT}")),
            "must listen where docker publishes: {cmd}"
        );
        assert!(
            cmd.contains(&format!("TCP:127.0.0.1:{GRAPH_UI_INTERNAL}")),
            "and forward to where the server binds: {cmd}"
        );
    }

    /// Regression: removing a session left its graph behind, so the cache grew
    /// with dead sessions and the agent could query code that no longer exists.
    #[test]
    fn removing_a_session_drops_its_graph() {
        let cmd = drop_graph_command("ohmyharness-s02").join(" ");
        assert!(cmd.contains("delete_project"), "got: {cmd}");
        assert!(cmd.contains("ohmyharness-s02"), "got: {cmd}");
    }

    /// Dropping a graph that was never built is not a failure — a session may
    /// have been removed before it ever launched.
    #[test]
    fn dropping_a_graph_that_is_not_there_is_forgiving() {
        let cmd = drop_graph_command("nope").join(" ");
        assert!(cmd.contains("|| true"), "got: {cmd}");
    }

    // ── the graph UI is a repo-scoped service ───────────────────────────────

    /// Every session's graph lives in one volume, so a per-session server
    /// served every other session's graph anyway — N identical websites.
    #[test]
    fn the_ui_is_named_for_the_repo_not_a_session() {
        let c = ui_container("ohmyharness");
        assert!(c.contains("ohmyharness"));
        assert!(!c.contains("s01"), "not session-scoped: {c}");
        assert_eq!(c, ui_container("ohmyharness"), "and stable");
    }

    /// It needs the index and nothing else. A UI container holding a writable
    /// worktree and live credentials would be exposure for no purpose.
    #[test]
    fn the_ui_container_mounts_only_the_index() {
        let args = ui_run_args("omh/base:x", "omh-graph-r", "omh-cache-r", 50000);
        let mounts: Vec<&String> = args
            .iter()
            .skip_while(|a| *a != "-v")
            .step_by(2)
            .skip(1)
            .take(1)
            .collect();
        assert_eq!(mounts.len(), 1, "exactly one mount: {args:?}");
        let joined = args.join(" ");
        assert!(joined.contains("omh-cache-r"), "the index: {joined}");
        assert!(!joined.contains("/work"), "no worktree: {joined}");
        assert!(!joined.contains(".claude"), "no credentials: {joined}");
    }

    #[test]
    fn the_ui_container_publishes_on_loopback_only() {
        let joined = ui_run_args("i", "c", "v", 50000).join(" ");
        assert!(joined.contains("127.0.0.1:50000:"), "got: {joined}");
        assert!(!joined.contains("0.0.0.0"), "got: {joined}");
    }

    /// Lifecycle is `docker run` / `docker rm`, which is idempotent by
    /// construction — the per-session version needed a pgrep guard, a detached
    /// exec and a pkill, and each was a bug before it worked.
    #[test]
    fn the_ui_runs_detached_under_its_own_name() {
        let args = ui_run_args("i", "omh-graph-r", "v", 1);
        assert!(args.contains(&"-d".to_string()), "got: {args:?}");
        assert!(args
            .windows(2)
            .any(|w| w[0] == "--name" && w[1] == "omh-graph-r"));
    }

    /// A hook talks to the model through `hookSpecificOutput`, never bare stdout
    /// — the first nudge shipped that way and may never have been seen.
    ///
    /// **Which** key depends on what the hook meant. An advisory nudge uses
    /// `additionalContext` and the call proceeds; a refusal uses
    /// `permissionDecision` and it does not. Asserting `additionalContext` for
    /// everything was right while every talking hook advised, and would now
    /// quietly demand that a refusal be downgraded to a notice.
    #[test]
    fn hooks_speak_through_the_documented_channel() {
        for (name, r) in all_rendered() {
            if r.event == "Stop" {
                continue; // refreshes the index, says nothing to the model
            }
            assert!(
                r.command.contains("hookSpecificOutput"),
                "{name}: {}",
                r.command
            );
            assert!(
                r.command
                    .contains(&format!(r#""hookEventName":"{}""#, r.event)),
                "{name}: a payload that does not name its moment is discarded: {}",
                r.command
            );
            let advises = r.command.contains("additionalContext");
            let refuses = r.command.contains("permissionDecision");
            assert!(
                advises ^ refuses,
                "{name} must advise or refuse, and say which: {}",
                r.command
            );
        }
    }

    /// Reading a whole module to see one function is the largest avoidable cost
    /// in a session: `get_code_snippet` answers the same question in ~1,500
    /// bytes. No file size named — the figure that used to be here was stale on
    /// the commit that wrote it, and it appeared in four places.
    #[test]
    fn reading_a_file_points_at_the_symbol_lookup() {
        let h = rendered("graph-read");
        assert_eq!(h.event, "PreToolUse");
        assert_eq!(h.matcher, "Read");
        assert!(h.command.contains("get_code_snippet"), "got: {}", h.command);
    }

    /// `Read` is the most frequent tool there is. A nudge on every call is
    /// recurring cost and becomes noise the model tunes out, so it speaks only
    /// when a symbol lookup would actually be cheaper.
    #[test]
    fn the_read_nudge_stays_silent_when_it_has_nothing_to_say() {
        let cmd = rendered("graph-read").command;
        assert!(cmd.contains("file_path"), "must inspect the target: {cmd}");
        assert!(cmd.contains("wc -c"), "and its size: {cmd}");
    }

    /// Orientation the agent gets once, instead of discovering it by reading
    /// files. The only graph tool that costs nothing per tool call.
    #[test]
    fn a_session_starts_with_the_module_map() {
        let h = rendered("graph-orient");
        assert_eq!(h.event, "SessionStart");
        assert!(h.command.contains("get_architecture"), "got: {}", h.command);
    }

    /// SessionStart re-fires on resume and compact, so this is not paid once —
    /// it is paid every time context is rebuilt. `overview` costs 6,173 bytes;
    /// the four aspects that actually orient cost 2,138.
    #[test]
    fn orientation_is_kept_small_because_it_repeats() {
        let cmd = rendered("graph-orient").command;
        assert!(
            !cmd.contains("overview"),
            "too broad for something that repeats: {cmd}"
        );
        for aspect in ["layers", "packages", "boundaries", "entry_points"] {
            assert!(cmd.contains(aspect), "missing {aspect}: {cmd}");
        }
    }

    /// A comma-separated list yields nothing; the flag repeats. Verified
    /// against the real binary.
    #[test]
    fn aspects_are_passed_as_repeated_flags() {
        let cmd = rendered("graph-orient").command;
        assert!(
            !cmd.contains("layers,packages"),
            "comma form returns empty: {cmd}"
        );
        assert_eq!(cmd.matches("--aspects").count(), 4, "got: {cmd}");
    }
}