omh 0.2.0

Launch any coding harness, in a sandbox, with your setup already there.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
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
//! 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::render::Server;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::BTreeMap;
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,
    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, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Kind {
    Mcp,
    Hook,
}

/// 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()))?;
            let manifest: Self =
                toml::from_str(&raw).with_context(|| format!("parsing {}", 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)
    }

    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"),
    ]
}

/// Canonical hook, in the shape a profile layer stores.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hook {
    pub name: &'static str,
    pub event: &'static str,
    pub matcher: &'static str,
    pub command: String,
}

/// 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]
    )
}

/// Wrap a string for `sh`, so prose with punctuation cannot end the argument
/// it is inside. Single quotes, and the only character that matters inside them
/// is the single quote itself.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// 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.
pub fn hooks() -> Vec<Hook> {
    // Nudges speak through `hookSpecificOutput.additionalContext` — the
    // documented channel a hook uses to reach the model. Bare stdout on exit 0
    // is not, and the first version of the grep nudge may never have been seen.
    let nudge = |body: &str| {
        format!(
            "jq -nc --arg p \"${PROJECT_ENV}\" '{{\"hookSpecificOutput\":{{\
             \"hookEventName\":\"PreToolUse\",\"additionalContext\":{body}}}}}'"
        )
    };

    vec![
        Hook {
            name: "graph-refresh",
            event: "Stop",
            matcher: "",
            // 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.
            command: format!(
                "{GRAPH_BIN} cli index_repository --repo-path /work \
                 --name \"${PROJECT_ENV}\" --mode fast >/dev/null 2>&1 || true"
            ),
        },
        Hook {
            name: "graph-orient",
            event: "SessionStart",
            matcher: "",
            // 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.
            command: format!(
                "a=$({GRAPH_BIN} cli get_architecture --project \"${PROJECT_ENV}\" \
                 --aspects layers --aspects packages --aspects boundaries \
                 --aspects entry_points 2>/dev/null | tail -1); \
                 [ -n \"$a\" ] || exit 0; \
                 jq -nc --arg a \"$a\" --arg p \"${PROJECT_ENV}\" \
                 '{{\"hookSpecificOutput\":{{\"hookEventName\":\"SessionStart\",\
                 \"additionalContext\":(\"Code graph for project \" + $p + \
                 \" — modules, layers, boundaries and entry points. Query it with \
                 search_graph/trace_path/get_code_snippet rather than exploring by \
                 hand:\\n\" + $a)}}}}'"
            ),
        },
        Hook {
            name: "git-unavailable",
            event: "PreToolUse",
            matcher: "Bash",
            // Silent unless the command is actually git, for the reason
            // `graph-read` is silent on small files: a nudge on every Bash call
            // is noise the model tunes out, and Bash 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
            // Bash 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.
            //
            // Built from `detect::GIT_ABSENT` so the sentence the agent sees
            // here and the one `init` writes into the rules cannot drift.
            command: format!(
                "c=$(jq -r '.tool_input.command // empty'); \
                 case \"$c\" in \
                 git\\ *|git) ;; \
                 *[\\;\\&\\|\\(]*git\\ *|*[[:blank:]]git\\ *) ;; \
                 *) case \"$c\" in *\"\
                 \"git\\ *) ;; *) exit 0 ;; esac ;; esac; \
                 jq -nc --arg m {} '{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\
                 \"additionalContext\":$m}}}}'",
                shell_quote(crate::detect::GIT_ABSENT)
            ),
        },
        Hook {
            name: "graph-first",
            event: "PreToolUse",
            matcher: "Grep|Glob",
            // 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.
            command: nudge(&format!(
                r#"("{}" + $p + "{}" + $p + "{}")"#,
                GREP_NUDGE[0], GREP_NUDGE[1], GREP_NUDGE[2]
            )),
        },
        Hook {
            name: "graph-read",
            event: "PreToolUse",
            matcher: "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.
            command: format!(
                "f=$(jq -r '.tool_input.file_path // empty'); \
                 case \"$f\" in \
                 *.rs|*.ts|*.tsx|*.js|*.jsx|*.py|*.go|*.java|*.rb|*.php|*.c|*.h|*.cc|\
                 *.cpp|*.hpp|*.cs|*.swift|*.kt|*.scala) ;; *) exit 0 ;; esac; \
                 [ -f \"$f\" ] || exit 0; \
                 [ \"$(wc -c < \"$f\")\" -gt 8000 ] || exit 0; \
                 jq -nc --arg p \"${PROJECT_ENV}\" --arg f \"$f\" \
                 '{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\
                 \"additionalContext\":($f + \" is large. For one symbol rather than the \
                 whole file: get_code_snippet --project \" + $p + \" --qualified-name \
                 <name>, and search_graph finds the name.\")}}}}'"
            ),
        },
    ]
}

/// 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
                );
            }
        }
    }

    /// 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"
since = "2026.06"
because = "b"
remove = "r"
command = "c"
"#;

    /// 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"
        );

        // 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"))
    }

    /// 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 = hook("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 = hook("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 = hook("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<_> = hooks()
            .into_iter()
            .filter(|h| h.command.contains(GRAPH_BIN))
            .collect();
        assert!(
            !querying.is_empty(),
            "the filter must still match something"
        );
        for h in querying {
            assert!(
                h.command.contains(PROJECT_ENV),
                "{} must name its project: {}",
                h.name,
                h.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 = hook("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 = hook("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
        );
    }

    /// 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 h in hooks() {
            let out = std::process::Command::new("sh")
                .args(["-n", "-c", &h.command])
                .output()
                .expect("sh must run");
            assert!(
                out.status.success(),
                "{} is not parseable by sh: {}\n{}",
                h.name,
                String::from_utf8_lossy(&out.stderr),
                h.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 h in hooks() {
            let out = std::process::Command::new("sh")
                .arg("-c")
                .arg(&h.command)
                .env("PATH", &path)
                .env(PROJECT_ENV, "repo-s01")
                .stdin(std::process::Stdio::null())
                .output()
                .expect("sh must run");
            assert!(
                out.status.success(),
                "{} exited {:?}: {}",
                h.name,
                out.status.code(),
                String::from_utf8_lossy(&out.stderr)
            );
            assert!(
                out.stderr.is_empty(),
                "{} wrote to stderr, which the harness shows the user: {}",
                h.name,
                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(&hook("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()
    }

    #[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})"));
        assert_eq!(
            parsed["hookSpecificOutput"]["additionalContext"]
                .as_str()
                .unwrap(),
            crate::detect::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.additionalContext`,
    /// injected as a system reminder. Bare stdout on exit 0 is not that
    /// mechanism — the first nudge shipped that way and may never have been seen.
    #[test]
    fn nudges_speak_through_additional_context() {
        for h in hooks() {
            if h.event == "Stop" {
                continue; // refreshes the index, says nothing to the model
            }
            assert!(
                h.command.contains("additionalContext"),
                "{}: {}",
                h.name,
                h.command
            );
            assert!(
                h.command.contains("hookSpecificOutput"),
                "{}: {}",
                h.name,
                h.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 = hook("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 = hook("graph-read").command.clone();
        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 = hook("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 = hook("graph-orient").command.clone();
        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 = hook("graph-orient").command.clone();
        assert!(
            !cmd.contains("layers,packages"),
            "comma form returns empty: {cmd}"
        );
        assert_eq!(cmd.matches("--aspects").count(), 4, "got: {cmd}");
    }
}