mati 0.1.2

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
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
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
//! CLI adapter for `mati hook-decide <variant>`.
//!
//! Owns daemon readiness, stdin parsing, and platform-specific output.
//! Delegates the pure enforcement decision to `hooks::decide::evaluate()`.

use anyhow::Result;
use clap::{Args, ValueEnum};
use globset::{Glob, GlobSet, GlobSetBuilder};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::cli::daemon::{daemon_result, mati_root_for, DaemonResult};
use mati_core::hooks::decide::{self, Decision, EnforcementInput, HookEvent};

// ── Public types ────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum HookVariant {
    ClaudePreRead,
    /// Claude PreToolUse(Edit|Write|NotebookEdit): gate file *edits*. Uses
    /// `consulted_recent` (a recent-consultation TTL, matching the Codex
    /// `apply_patch` edit gate) — NOT the read gate's persistent `consulted` — so
    /// an edit must be preceded by a *recent* mem_get: read-then-edit flows within
    /// the TTL, and blind or stale-consult edits deny. Non-deny outcomes DEFER to
    /// the normal permission flow instead of emitting `allow` — edits are
    /// permission-required, so force-allow would suppress the user's edit prompt.
    ClaudePreEdit,
    ClaudePreBash,
    CodexPreBash,
    CodexPostBash,
    /// Codex PreToolUse(apply_patch): gate file *edits*. Multi-file flow
    /// (`run_apply_patch`) — parses the patch envelope and denies if any
    /// touched file has an unconsulted confirmed gotcha.
    CodexPreApplyPatch,
    /// Claude PostToolUse(mcp__mati__mem_get): record actor-scoped consult receipt.
    /// Payload carries session_id, agent_id (subagent), and tool_input.key.
    ///
    /// clap's default kebab derive would yield `claude-post-mem-get`; pin the CLI
    /// value to `claude-post-memget` so it matches the installed hook script
    /// (`post-memget.sh` → `mati hook-decide claude-post-memget`).
    #[value(name = "claude-post-memget")]
    ClaudePostMemGet,
}

#[derive(Args, Debug)]
pub struct HookDecideArgs {
    /// Which hook variant to execute.
    #[arg(value_enum)]
    pub variant: HookVariant,
}

// ── Entry point ─────────────────────────────────────────────────────────────

/// Outer end-to-end deadline for the hook process.
///
/// Claude Code SIGKILLs the hook subprocess at 3000ms wall-clock. SIGKILL
/// bypasses every internal `log_fail_open` call, leaving operators blind to
/// wedged-daemon spikes — the exact failure mode `fail_open.log` exists to
/// surface. This ceiling fires ~500ms before SIGKILL so we get one clean
/// fail-open log entry + an allow stdout before Claude reaps us.
const HOOK_DEADLINE_MS: u64 = 2500;

pub async fn run(args: HookDecideArgs) -> Result<()> {
    let variant = args.variant;
    match tokio::time::timeout(Duration::from_millis(HOOK_DEADLINE_MS), run_inner(args)).await {
        Ok(inner_result) => inner_result,
        Err(_elapsed) => {
            // Internal deadline exceeded. We don't know which path stalled
            // (path may not even have been extracted yet), so log with the
            // sentinel "<unknown>" — still better than no entry at all.
            log_fail_open("<unknown>", "hook process exceeded internal deadline");
            emit_allow(variant);
            Ok(())
        }
    }
}

async fn run_inner(args: HookDecideArgs) -> Result<()> {
    // 1. Read stdin (tool input JSON from hook protocol). MUST be async: the
    // outer HOOK_DEADLINE_MS timeout can only fire at an await point, so a
    // blocking std::io read (e.g. a caller that never closes the pipe) would
    // ride straight past the internal deadline to Claude Code's 3000ms
    // SIGKILL — skipping the fail-open log entry the deadline exists to write.
    let mut input_str = String::new();
    tokio::io::AsyncReadExt::read_to_string(&mut tokio::io::stdin(), &mut input_str).await?;
    let input: serde_json::Value =
        serde_json::from_str(&input_str).unwrap_or(serde_json::Value::Null);

    // apply_patch is multi-file: it parses the patch envelope and evaluates
    // every touched path, so it has its own flow rather than the single-path
    // pipeline below.
    if args.variant == HookVariant::CodexPreApplyPatch {
        return run_apply_patch(&input).await;
    }

    // claude-post-memget: records an actor-scoped consult receipt using
    // tool_input.key directly — NOT a file path, so skip extract_path entirely.
    if args.variant == HookVariant::ClaudePostMemGet {
        return run_post_memget(&input).await;
    }

    // 1b. Parse agent_id: present only in subagent hook payloads.
    // Gate actor = agent_id if present, else None (NO session_id fallback).
    // - Subagent: actor = Some(agent_id) → reads actor-scoped receipt.
    // - Main thread: actor = None → reads global receipt (unchanged path).
    let agent_id = input
        .get("agent_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty());

    // 2. Extract file path (variant-specific).
    let raw_path = match extract_path(&input, args.variant) {
        Some(p) => p,
        None => {
            emit_allow(args.variant);
            return Ok(());
        }
    };

    // 3. Resolve repo root via git2 (no subprocess).
    let cwd = std::env::current_dir()?;
    let repo_root = discover_repo_root(&cwd);
    let repo_root_str = repo_root.as_ref().and_then(|p| p.to_str());
    // Platform limitation: bare relative paths in shell commands (e.g. `cat foo.rs`)
    // resolve against the hook process cwd, which is the repo root when set by
    // Claude Code / Codex. If the platform changes cwd semantics, relative paths
    // may need a tool_input.workdir field to resolve correctly.
    //
    // `rel_path` is the LEXICAL key — the primary gate. When it finds no
    // gotcha, the canonical-key fallback below (WI-20) re-evaluates the
    // symlink's real target so the gate still fires.
    let rel_path = decide::normalize_path(&raw_path, repo_root_str);

    // 4. Resolve mati root (for daemon socket). Use repo_root for consistent slug.
    let root_for_slug = repo_root.as_deref().unwrap_or(&cwd);
    let mati_root = match mati_root_for(root_for_slug) {
        Ok(r) => r,
        Err(_) => {
            log_fail_open(&rel_path, "cannot determine mati root");
            emit_allow(args.variant);
            return Ok(());
        }
    };

    // 5. Ensure daemon is reachable (auto-start if needed).
    if !ensure_daemon(&mati_root).await {
        log_fail_open(&rel_path, "daemon not running after auto-start");
        emit_allow(args.variant);
        return Ok(());
    }

    // 6. codex-post-bash: separate flow — no evaluate(), just compliance logging.
    if args.variant == HookVariant::CodexPostBash {
        return run_post_bash(&mati_root, &rel_path).await;
    }

    // 7. Single hook_evaluate round-trip.
    let file_key = format!("file:{rel_path}");
    // ClaudePreEdit and CodexPreBash both want the recent-TTL consultation, not
    // the persistent `consulted` flag: an edit / shell-read must be freshly
    // preceded by a mem_get (matches the Codex apply_patch edit gate).
    let include_recent = matches!(
        args.variant,
        HookVariant::CodexPreBash | HookVariant::ClaudePreEdit
    );

    // Enterprise consult-mandate globs (env-supplied; see `apply_consult_mandate`), compiled
    // once and applied at every evaluation site below — primary, canonical (symlink), and
    // multi-file extras — for parity with gotcha enforcement.
    let consult_globs = consult_globset();

    let eval_data = match daemon_result(
        &mati_root,
        "hook_evaluate",
        serde_json::json!({
            "file_key": &file_key,
            "include_recent": include_recent,
            "actor": agent_id,
        }),
    )
    .await
    {
        // `daemon_data` rejects `{"ok": false}` envelopes — a daemon-side
        // error must take the fail-open-and-record path below, not evaluate
        // a Null bundle as "no record" (which would log a false Miss).
        DaemonResult::Ok(resp) => match daemon_data(&resp) {
            Some(d) => d,
            None => {
                log_fail_open(&rel_path, "hook_evaluate returned error");
                emit_allow(args.variant);
                return Ok(());
            }
        },
        _ => {
            log_fail_open(&rel_path, "hook_evaluate failed");
            emit_allow(args.variant);
            return Ok(());
        }
    };

    // 8–11. Process eval response through the adapter pipeline.
    let mut adapter = process_eval_response(args.variant, &rel_path, &eval_data);
    // Consult mandate on the PRIMARY (lexical) file — before the escalation blocks so a
    // mandated deny short-circuits the canonical/extra round-trips too.
    apply_consult_mandate(
        &mut adapter,
        args.variant,
        &rel_path,
        consulted_flag(&eval_data, include_recent),
        consult_globs.as_ref(),
    );

    // Fail-open telemetry for store/gotcha errors on the LEXICAL evaluation.
    // This describes the lexical lookup that just ran; the canonical fallback
    // below has its own per-lookup error handling (a failed canonical
    // hook_evaluate simply leaves the lexical decision intact).
    let lexical_fail_open = match check_eval_data(args.variant, &rel_path, &eval_data) {
        EvalDataCheck::FailOpen(reason) => Some(reason),
        EvalDataCheck::Ok(_) => None,
    };

    // WI-20: canonical-key fallback (symlink-bypass close).
    //
    // The lexical key (`file:<rel_path>`) is the primary gate and is evaluated
    // first, above — never weakened. ONLY when the lexical gate did NOT deny do
    // we resolve the symlink: a symlink to a gotcha'd file has a different
    // lexical key, so the lexical gate misses it. We canonicalize the accessed
    // path (resolving symlinks), strip the canonicalized repo_root, and evaluate
    // that target's key too. If the real target carries an unconsulted confirmed
    // gotcha, the gate fires on it. Fully defensive: any failure (no repo root,
    // canonicalize error, target outside the repo, identical key) leaves the
    // lexical-only decision untouched. Perf: one extra realpath + one daemon
    // round-trip, and only on the non-deny path, so the common case is zero-cost.
    if !matches!(adapter.decision, Decision::Deny { .. }) {
        if let Some(canon_rel) =
            canonical_rel_path(&raw_path, &cwd, repo_root.as_deref(), &rel_path)
        {
            let canon_key = format!("file:{canon_rel}");
            if let Some(canon_eval) = match daemon_result(
                &mati_root,
                "hook_evaluate",
                serde_json::json!({
                    "file_key": &canon_key,
                    "include_recent": include_recent,
                    "actor": agent_id,
                }),
            )
            .await
            {
                DaemonResult::Ok(resp) => {
                    let d = daemon_data(&resp);
                    if d.is_none() {
                        // Escalate-only path: the lexical decision stands, but
                        // record the gap — the real target went ungated.
                        log_fail_open(&canon_rel, "hook_evaluate returned error (canonical)");
                    }
                    d
                }
                _ => None,
            } {
                let mut canon_adapter =
                    process_eval_response(args.variant, &canon_rel, &canon_eval);
                // Mandate the symlink's real target too (parity with the gotcha WI-20 close).
                apply_consult_mandate(
                    &mut canon_adapter,
                    args.variant,
                    &canon_rel,
                    consulted_flag(&canon_eval, include_recent),
                    consult_globs.as_ref(),
                );
                // Only ESCALATE: adopt the canonical result solely when it denies.
                // A non-deny canonical outcome never downgrades the lexical
                // decision (e.g. a lexical Advisory must survive). The canonical
                // adapter is self-contained — its deny reason and audit events
                // already key on `canon_rel` (the real target) — so swapping the
                // adapter alone re-points output + events at the resolved file.
                if matches!(canon_adapter.decision, Decision::Deny { .. }) {
                    adapter = canon_adapter;
                }
            }
        }
    }

    // Multi-file bash reads (`cat a.rs b.rs`, `grep pat f1 f2`): the single-path
    // flow above fully evaluated the PRIMARY file; gate the REMAINING files too
    // so a gotcha on a non-primary file still denies. Escalate-only, mirroring
    // the canonical fallback (a non-deny extra file never downgrades the
    // decision) and a no-op when the command names a single file — the common
    // case — so it adds zero daemon round-trips there. Capped like apply_patch.
    if !matches!(adapter.decision, Decision::Deny { .. })
        && matches!(
            args.variant,
            HookVariant::ClaudePreBash | HookVariant::CodexPreBash
        )
    {
        if let Some(cmd) = input
            .pointer("/tool_input/command")
            .and_then(|v| v.as_str())
        {
            if let Some(class) = decide::classify_command(cmd) {
                for extra_raw in decide::extract_file_paths(cmd, class)
                    .into_iter()
                    .take(decide::MAX_APPLY_PATCH_FILES)
                {
                    let extra_rel = decide::normalize_path(&extra_raw, repo_root_str);
                    if extra_rel == rel_path {
                        continue; // primary already evaluated above
                    }
                    let extra_key = format!("file:{extra_rel}");
                    match daemon_result(
                        &mati_root,
                        "hook_evaluate",
                        serde_json::json!({
                            "file_key": &extra_key,
                            "include_recent": include_recent,
                            "actor": agent_id,
                        }),
                    )
                    .await
                    {
                        DaemonResult::Ok(resp) => {
                            let Some(extra_eval) = daemon_data(&resp) else {
                                log_fail_open(
                                    &extra_rel,
                                    "hook_evaluate returned error (extra file)",
                                );
                                continue;
                            };
                            let mut extra_adapter =
                                process_eval_response(args.variant, &extra_rel, &extra_eval);
                            // Mandate non-primary bash args too (parity with gotcha extra-file gating).
                            apply_consult_mandate(
                                &mut extra_adapter,
                                args.variant,
                                &extra_rel,
                                consulted_flag(&extra_eval, include_recent),
                                consult_globs.as_ref(),
                            );
                            if matches!(extra_adapter.decision, Decision::Deny { .. }) {
                                adapter = extra_adapter;
                                break;
                            }
                        }
                        // Per-file fail-open, but RECORDED (gap-aware doctrine —
                        // matches the apply_patch loop): the extra file simply
                        // isn't gated this round, and the log says so.
                        _ => log_fail_open(&extra_rel, "hook_evaluate failed (extra file)"),
                    }
                }
            }
        }
    }

    // Platform-specific output FIRST, audit events second: the outer deadline
    // can cancel this future between the two. A decision that was delivered
    // but not recorded is an honest gap (fail-open doctrine); an event
    // recorded for a decision that was never delivered would be a phantom
    // entry in the hash-chained audit log. Missing beats false.
    if !adapter.stdout.is_empty() {
        println!("{}", adapter.stdout);
    }
    if !adapter.stderr.is_empty() {
        eprintln!("{}", adapter.stderr);
    }

    // Fire audit events (sequential daemon round-trips, bounded by the outer
    // deadline). session_id (Claude Code provides it at the top level of the
    // hook input) and agent_id (present in subagent payloads) attribute these
    // events to the agent session / actor — per-actor audit.
    let session_id = input.get("session_id").and_then(|v| v.as_str());
    fire_events(&mati_root, &adapter.events, session_id, agent_id).await;

    // Emit the lexical fail-open telemetry captured before the fallback.
    if let Some(reason) = lexical_fail_open {
        log_fail_open(&rel_path, &reason);
    }

    if adapter.exit_code != 0 {
        let _ = std::io::Write::flush(&mut std::io::stderr());
        std::process::exit(adapter.exit_code);
    }

    Ok(())
}

// ── Path extraction ─────────────────────────────────────────────────────────

fn extract_path(input: &serde_json::Value, variant: HookVariant) -> Option<String> {
    match variant {
        HookVariant::ClaudePreRead | HookVariant::ClaudePreEdit => {
            // Structured path from Claude Code. Read/Edit/Write use `file_path`;
            // NotebookEdit uses `notebook_path`. We check both (plus a legacy
            // `path` fallback) so the edit gate covers every edit-class tool in
            // the matcher regardless of which field the tool populates — rather
            // than assuming one field for a tool whose schema we haven't pinned.
            input
                .pointer("/tool_input/file_path")
                .or_else(|| input.pointer("/tool_input/notebook_path"))
                .or_else(|| input.pointer("/tool_input/path"))
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
        }
        HookVariant::ClaudePreBash | HookVariant::CodexPreBash | HookVariant::CodexPostBash => {
            // Raw command string — classify then extract.
            let cmd = input
                .pointer("/tool_input/command")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())?;
            let class = decide::classify_command(cmd)?;
            decide::extract_file_path(cmd, class)
        }
        // apply_patch is multi-file and handled by `run_apply_patch` before the
        // single-path pipeline; never reaches here.
        HookVariant::CodexPreApplyPatch => None,
        // post-memget is handled by `run_post_memget` before extract_path is called;
        // it uses tool_input.key directly, not a file path.
        HookVariant::ClaudePostMemGet => None,
    }
}

// ── Repo root ───────────────────────────────────────────────────────────────

/// Discover the git repo root via git2. Returns `None` for bare repos or
/// when not inside a git repository. No subprocess spawned.
///
/// Note: `repo.workdir()` may return a path with a trailing separator
/// (e.g. `/path/to/repo/`). We strip it so that `derive_slug()` produces
/// the same hash as `std::env::current_dir()` (which omits it). Without
/// this, repos without a remote URL get different slugs from `hook-decide`
/// vs `mati init`/`mati daemon`, causing daemon socket discovery to fail.
fn discover_repo_root(cwd: &Path) -> Option<PathBuf> {
    git2::Repository::discover(cwd).ok().and_then(|repo| {
        // Strip the trailing separator that git2's workdir() sometimes adds.
        // `to_str` (NOT `to_string_lossy`): a non-UTF-8 root would be
        // silently rewritten with U+FFFD — a valid-looking but WRONG path,
        // producing a wrong slug and wrong store keys (a permanent, silent
        // gate miss). Returning None instead falls back to cwd-based
        // resolution, which is at least honest about not knowing the root.
        let root = repo.workdir()?.to_str()?.trim_end_matches('/');
        Some(PathBuf::from(root))
    })
}

/// WI-20: compute the CANONICAL repo-relative key for the symlink-bypass
/// fallback, or `None` if the canonical resolution can't be trusted.
///
/// Returns `Some(canonical_rel)` ONLY when, after resolving symlinks on the
/// accessed path, both hold:
///
///   - the canonical target lands UNDER the canonical repo root, AND
///   - the canonical key DIFFERS from the lexical key (`lexical_rel`).
///
/// Otherwise returns `None`, leaving the lexical-only decision intact. This is
/// the additive half of the gate: it never weakens the lexical lookup — the
/// caller only consults it when the lexical gate did not already deny.
///
/// Defensive by construction: a missing repo root, a `canonicalize` failure, a
/// target resolving outside the repo, or a no-op (same key) all yield `None`.
/// Reuses [`super::sandbox::canonicalize_lenient`] so symlink resolution matches
/// the L3 sandbox floor exactly (canonicalize; on a non-existent leaf,
/// canonicalize the parent and re-append the leaf).
fn canonical_rel_path(
    raw_path: &str,
    cwd: &Path,
    repo_root: Option<&Path>,
    lexical_rel: &str,
) -> Option<String> {
    // No repo root → we can't strip a prefix to form a repo-relative key.
    let repo_root = repo_root?;

    // Resolve the repo root itself through symlinks so the `starts_with`
    // containment check below is sound (e.g. macOS `/var` → `/private/var`).
    let canon_root = super::sandbox::canonicalize_lenient(repo_root)?;

    // Build the ABSOLUTE accessed path. A relative shell arg (`cat foo.rs`)
    // resolves against the hook process cwd (the repo root under Claude/Codex).
    let raw = Path::new(raw_path);
    let abs_access = if raw.is_absolute() {
        raw.to_path_buf()
    } else {
        cwd.join(raw)
    };

    // Resolve symlinks on the accessed path (this is the whole point: a symlink
    // to a gotcha'd file canonicalizes to the real target).
    let canon_access = super::sandbox::canonicalize_lenient(&abs_access)?;

    // Containment: the canonical target must be inside the repo. Out-of-repo
    // targets can't match a store key and must never deny — fall back to lexical.
    let stripped = canon_access.strip_prefix(&canon_root).ok()?;
    let stripped_str = stripped.to_str()?;

    // Normalize to the same lexical key shape used at registration / lookup.
    let canon_rel = decide::normalize_path(stripped_str, None);

    // Zero-cost no-op: if the canonical key equals the lexical one (no symlink
    // involved), skip the redundant second daemon round-trip.
    if canon_rel == lexical_rel {
        return None;
    }
    Some(canon_rel)
}

// ── Daemon readiness ────────────────────────────────────────────────────────

/// Ensure the daemon is reachable. Auto-starts if needed.
///
/// Pass-33: this is now a thin delegate to
/// [`mati_core::mcp::daemon_lifecycle::ensure_daemon`]. The library-side
/// implementation is the canonical one — sharing it lets MCP socket-backed
/// callers (`proxy_daemon_result` / `proxy_daemon_v2`) auto-spawn with the
/// exact same recovery semantics as the hook path. See the lib module
/// docs for the full Phase 1–4 strategy.
async fn ensure_daemon(mati_root: &Path) -> bool {
    mati_core::mcp::daemon_lifecycle::ensure_daemon(mati_root).await
}

// ── codex-post-bash flow ────────────────────────────────────────────────────

/// Compliance logging only — no `evaluate()`, no gotcha fetching.
async fn run_post_bash(mati_root: &Path, rel_path: &str) -> Result<()> {
    let file_key = format!("file:{rel_path}");

    // Reuse existing session_check_consulted_recent command.
    let consulted = match daemon_result(
        mati_root,
        "session_check_consulted_recent",
        serde_json::json!({
            "key": &file_key,
            "ttl_secs": mati_core::store::session::CONSULTED_RECENT_TTL_SECS,
        }),
    )
    .await
    {
        DaemonResult::Ok(resp) => match daemon_data(&resp) {
            Some(d) => d.as_bool().unwrap_or(false),
            // Daemon-side error: the consultation state is UNKNOWN. Recording
            // a CodexShellMiss here would be a false "bypass detected" audit
            // event (the daemon is reachable, so it WOULD be recorded).
            None => return Ok(()),
        },
        _ => false,
    };

    // Fire the appropriate compliance event via typed v2 command.
    let event = if consulted {
        mati_core::mcp::protocol::SessionEvent::ComplianceHit
    } else {
        mati_core::mcp::protocol::SessionEvent::CodexShellMiss
    };
    let cmd =
        mati_core::mcp::protocol::Command::SessionLog(mati_core::mcp::protocol::SessionLogInput {
            event,
            key: file_key.clone(),
            session_id: None,
        });
    let _ = super::daemon::daemon_v2(mati_root, cmd).await;

    // Post-hook: no output, always exit 0.
    Ok(())
}

// ── claude-post-memget flow ─────────────────────────────────────────────────

/// Record an actor-scoped consult receipt after a successful mem_get.
///
/// Fail-open at every step: if the key, session_id, or daemon is missing, exit 0.
/// No stdout output (PostToolUse hooks are fire-and-forget).
async fn run_post_memget(input: &serde_json::Value) -> Result<()> {
    // A failed mem_get delivered no context — minting a receipt for it would
    // wrongly downgrade a future deny (a receipt is proof the record was
    // READ). MCP tool errors surface as `tool_response.isError: true`; an
    // absent field means success, so this guard is a no-op on the happy path.
    if input
        .pointer("/tool_response/isError")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        return Ok(());
    }

    let key = match input
        .pointer("/tool_input/key")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
    {
        Some(k) => k,
        None => return Ok(()),
    };

    let agent_id = input
        .get("agent_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty());
    let session_id = input
        .get("session_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty());
    let actor = agent_id.or(session_id);

    let cwd = std::env::current_dir()?;
    // Resolve the daemon slug the way the gate does (repo root, not cwd) so the
    // actor-scoped receipt lands in the same store the gate will read.
    let repo_root = discover_repo_root(&cwd);
    let root_for_slug = repo_root.as_deref().unwrap_or(&cwd);
    let mati_root = match mati_root_for(root_for_slug) {
        Ok(r) => r,
        Err(_) => return Ok(()),
    };
    if !ensure_daemon(&mati_root).await {
        return Ok(());
    }

    let cmd = mati_core::mcp::protocol::Command::ConsultationHit(
        mati_core::mcp::protocol::ConsultationHitInput {
            key: key.to_string(),
            actor: actor.map(str::to_string),
            session_id: session_id.map(str::to_string),
            agent_id: agent_id.map(str::to_string),
        },
    );
    let _ = super::daemon::daemon_v2(&mati_root, cmd).await;
    Ok(())
}

// ── codex-pre-apply-patch flow ──────────────────────────────────────────────

/// Multi-file edit enforcement for Codex `apply_patch`.
///
/// Parses the patch envelope into target paths, evaluates each against the
/// gotcha store, and denies (exit 2 + stderr) if ANY touched file has a
/// confirmed gotcha the agent has not consulted. Fails OPEN at every step
/// (no command, no paths, unreachable daemon, per-file eval error, file count
/// over the cap) — wrongly blocking all edits is worse than missing a gotcha.
async fn run_apply_patch(input: &serde_json::Value) -> Result<()> {
    let variant = HookVariant::CodexPreApplyPatch;

    // 1. Patch text from tool_input.command.
    let Some(cmd) = input
        .pointer("/tool_input/command")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
    else {
        emit_allow(variant);
        return Ok(());
    };

    // 2. Parse target paths from the envelope.
    let mut raw_paths = decide::extract_apply_patch_files(cmd);
    if raw_paths.is_empty() {
        emit_allow(variant);
        return Ok(());
    }
    if raw_paths.len() > decide::MAX_APPLY_PATCH_FILES {
        log_fail_open(
            "<apply_patch>",
            &format!(
                "patch touches {} files; gating only the first {}",
                raw_paths.len(),
                decide::MAX_APPLY_PATCH_FILES
            ),
        );
        raw_paths.truncate(decide::MAX_APPLY_PATCH_FILES);
    }

    // 3. Repo root + mati root + daemon (shared shape with the single-path flow).
    let cwd = std::env::current_dir()?;
    let repo_root = discover_repo_root(&cwd);
    let repo_root_str = repo_root.as_ref().and_then(|p| p.to_str());
    let root_for_slug = repo_root.as_deref().unwrap_or(&cwd);
    let mati_root = match mati_root_for(root_for_slug) {
        Ok(r) => r,
        Err(_) => {
            log_fail_open("<apply_patch>", "cannot determine mati root");
            emit_allow(variant);
            return Ok(());
        }
    };
    if !ensure_daemon(&mati_root).await {
        log_fail_open("<apply_patch>", "daemon not running after auto-start");
        emit_allow(variant);
        return Ok(());
    }

    // 4. Evaluate each touched path; collect the ones that must be consulted.
    // agent_id is present in subagent hook payloads; None on the Codex path.
    let agent_id = input
        .get("agent_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty());
    // Enterprise consult-mandate globs — parity with the single-path flow.
    let consult_globs = consult_globset();
    let mut denied: Vec<String> = Vec::new();
    let mut events: Vec<HookEvent> = Vec::new();
    for raw in &raw_paths {
        let rel_path = decide::normalize_path(raw, repo_root_str);
        let file_key = format!("file:{rel_path}");
        let eval_data = match daemon_result(
            &mati_root,
            "hook_evaluate",
            serde_json::json!({ "file_key": &file_key, "include_recent": true, "actor": agent_id }),
        )
        .await
        {
            DaemonResult::Ok(resp) => match daemon_data(&resp) {
                Some(d) => d,
                None => {
                    // Per-file fail-open on a daemon-side error — recorded,
                    // not evaluated as a false "no record".
                    log_fail_open(&rel_path, "hook_evaluate returned error");
                    continue;
                }
            },
            _ => {
                // Per-file fail-open: don't block the whole edit on one bad lookup.
                log_fail_open(&rel_path, "hook_evaluate failed");
                continue;
            }
        };

        let mut adapter = process_eval_response(variant, &rel_path, &eval_data);
        // Consult mandate on the patch target — parity with the read/edit
        // gates (this path uses include_recent semantics, hence `true`).
        apply_consult_mandate(
            &mut adapter,
            variant,
            &rel_path,
            consulted_flag(&eval_data, true),
            consult_globs.as_ref(),
        );
        // WI-20 parity: a patch targeting an in-repo symlink would otherwise
        // evaluate only the lexical key and write through to the real target
        // ungated. Escalate-only, like the read/edit path: a non-deny
        // canonical result never downgrades the lexical decision, and
        // `canonical_rel_path` returns None (zero cost) for non-symlinks.
        if !matches!(adapter.decision, Decision::Deny { .. }) {
            if let Some(canon_rel) = canonical_rel_path(raw, &cwd, repo_root.as_deref(), &rel_path)
            {
                let canon_key = format!("file:{canon_rel}");
                if let Some(canon_eval) = match daemon_result(
                    &mati_root,
                    "hook_evaluate",
                    serde_json::json!({ "file_key": &canon_key, "include_recent": true, "actor": agent_id }),
                )
                .await
                {
                    DaemonResult::Ok(resp) => {
                        let d = daemon_data(&resp);
                        if d.is_none() {
                            log_fail_open(
                                &canon_rel,
                                "hook_evaluate returned error (canonical)",
                            );
                        }
                        d
                    }
                    _ => None,
                } {
                    let mut canon_adapter =
                        process_eval_response(variant, &canon_rel, &canon_eval);
                    apply_consult_mandate(
                        &mut canon_adapter,
                        variant,
                        &canon_rel,
                        consulted_flag(&canon_eval, true),
                        consult_globs.as_ref(),
                    );
                    if matches!(canon_adapter.decision, Decision::Deny { .. }) {
                        adapter = canon_adapter;
                    }
                }
            }
        }
        // The Deny carries its own file_key — the lexical key, the canonical
        // (real-target) key, or the mandate key, whichever actually denied.
        if let Decision::Deny {
            file_key: denied_key,
            ..
        } = &adapter.decision
        {
            denied.push(denied_key.clone());
            events.extend(adapter.events);
        }
    }

    // 5. Deny if any file needs consultation; otherwise allow. Output FIRST,
    // audit events second (missing beats false — see run_inner).
    if denied.is_empty() {
        emit_allow(variant);
        return Ok(());
    }
    let msg = if denied.len() == 1 {
        format!("mati: call mem_get(\"{}\") before editing", denied[0])
    } else {
        format!(
            "mati: consult these files before editing — call mem_get for each: {}",
            denied.join(", ")
        )
    };
    eprintln!("{msg}");
    let _ = std::io::Write::flush(&mut std::io::stderr());

    // 6. Fire compliance events for the blocked files (fire-and-forget).
    // Codex apply_patch: no Claude session_id in the input; agent_id is
    // present only in subagent payloads.
    fire_events(&mati_root, &events, None, agent_id).await;
    std::process::exit(2);
}

// ── Fail-open telemetry ─────────────────────────────────────────────────────

fn log_fail_open(rel_path: &str, reason: &str) {
    eprintln!("[mati] WARNING: enforcement bypassed for {rel_path}{reason}");
    if let Some(home) = dirs::home_dir() {
        let log_dir = home.join(".mati");
        let _ = std::fs::create_dir_all(&log_dir);
        let log_path = log_dir.join("fail_open.log");
        log_fail_open_at(&log_path, rel_path, reason);
    }
}

/// Append one entry to `fail_open.log`. Format MUST match the parser in
/// `cli::stats::parse_iso_timestamp` — the round-trip is covered by
/// `fail_open_log_round_trip_writer_reader` in `cli::stats`'s test module.
pub(super) fn log_fail_open_at(log_path: &Path, rel_path: &str, reason: &str) {
    let now = iso_utc_now();
    let entry = format!("{now} FAIL_OPEN hook=hook-decide file={rel_path} reason={reason}\n");
    let _ = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_path)
        .and_then(|mut f| std::io::Write::write_all(&mut f, entry.as_bytes()));
}

/// UTC timestamp in ISO 8601 format `YYYY-MM-DDTHH:MM:SSZ`.
///
/// Format is the canonical on-disk shape for `fail_open.log` and any other
/// human/parser-readable log written from the hook path. `parse_iso_timestamp`
/// in `cli::stats` is the matching reader; changing one without the other
/// silently breaks the 7-day fail-open window in `mati stats` / `mati doctor`.
fn iso_utc_now() -> String {
    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}

// ── Platform-aware event mapping ────────────────────────────────────────────

/// Filter and translate events based on platform semantics.
///
/// Codex pre-bash:
///   - Deny → CodexShellBlocked (not generic BlockedUnconsultedRead)
///   - Advisory/Liability are silent → suppress Hit (no receipt)
///   - AlreadyConsulted → suppress ComplianceHit (codex-post-bash records it)
///   - NoRecord → Miss (keep)
///
/// Claude pre-read/pre-bash: keep all events as-is.
fn platform_events(
    variant: HookVariant,
    decision: &Decision,
    events: Vec<HookEvent>,
) -> Vec<HookEvent> {
    match variant {
        HookVariant::CodexPreBash | HookVariant::CodexPreApplyPatch => events
            .into_iter()
            .filter_map(|e| match e {
                HookEvent::Miss { .. } => Some(e),
                HookEvent::BlockedUnconsultedRead { key } => {
                    Some(HookEvent::CodexShellBlocked { key })
                }
                HookEvent::Hit { .. } => {
                    // Suppress Hit for outcomes where Codex receives no context.
                    // Minting a consultation receipt without delivering context
                    // would incorrectly downgrade future deny decisions.
                    // `evaluate()` emits Hit only for Advisory and Liability;
                    // AlreadyConsulted emits ComplianceHit (handled below).
                    match decision {
                        Decision::Advisory { .. } | Decision::Liability { .. } => None,
                        _ => Some(e),
                    }
                }
                HookEvent::ComplianceHit { .. } => {
                    // codex-post-bash owns ComplianceHit/AllowAfterReceipt
                    // for shell commands — suppress from pre-bash to avoid
                    // double-recording the enforcement event.
                    None
                }
                _ => Some(e),
            })
            .collect(),
        HookVariant::CodexPostBash | HookVariant::ClaudePostMemGet => {
            // Post-bash and post-memget use their own flows — should not reach here.
            events
        }
        HookVariant::ClaudePreEdit => events
            .into_iter()
            // Plane 2: translate to edit-attributed events and KEEP them, so the
            // audit trail records both that a stale/blind edit was blocked
            // (EditBlocked → Deny) and that a consulted edit proceeded
            // (EditConsulted → AllowAfterReceipt), each with an edit-specific
            // reason code. Drop the rest — the read gate owns Hit/Miss here.
            .filter_map(|e| match e {
                HookEvent::BlockedUnconsultedRead { key } => Some(HookEvent::EditBlocked { key }),
                // Keep the floor-mandate deny (its own reason code), don't fold into EditBlocked.
                HookEvent::FloorConsultBlocked { key } => {
                    Some(HookEvent::FloorConsultBlocked { key })
                }
                HookEvent::ComplianceHit { key } => Some(HookEvent::EditConsulted { key }),
                _ => None,
            })
            .collect(),
        HookVariant::ClaudePreRead | HookVariant::ClaudePreBash => {
            // Claude delivers context for all non-silent outcomes.
            events
        }
    }
}

// ── Event firing ────────────────────────────────────────────────────────────

async fn fire_events(
    mati_root: &Path,
    events: &[HookEvent],
    session_id: Option<&str>,
    agent_id: Option<&str>,
) {
    use mati_core::mcp::protocol as p;
    // Per-actor audit attribution (schema_version 2): tag each SessionLog with the
    // agent session that triggered it, when the platform provides one.
    let sid = || session_id.map(str::to_string);
    for event in events {
        let cmd = match event {
            // Receipt scope must match the evaluation scope: the gate was
            // queried with `actor = agent_id`, so the receipt minted here is
            // scoped the same way. A subagent's Advisory hit must NOT mint a
            // global receipt — receipts are strictly key-scoped in the store
            // (no actor↔global fallback), and a global receipt would satisfy
            // the main thread's gate for context only the subagent received.
            HookEvent::Hit { key } => p::Command::ConsultationHit(p::ConsultationHitInput {
                key: key.clone(),
                actor: agent_id.map(str::to_string),
                session_id: sid(),
                agent_id: agent_id.map(str::to_string),
            }),
            HookEvent::Miss { key } => p::Command::SessionLog(p::SessionLogInput {
                event: p::SessionEvent::Miss,
                key: key.clone(),
                session_id: sid(),
            }),
            HookEvent::BlockedUnconsultedRead { key } => {
                p::Command::SessionLog(p::SessionLogInput {
                    event: p::SessionEvent::ComplianceMiss,
                    key: key.clone(),
                    session_id: sid(),
                })
            }
            HookEvent::CodexShellBlocked { key } => p::Command::SessionLog(p::SessionLogInput {
                event: p::SessionEvent::CodexShellMiss,
                key: key.clone(),
                session_id: sid(),
            }),
            HookEvent::ComplianceHit { key } => p::Command::SessionLog(p::SessionLogInput {
                event: p::SessionEvent::ComplianceHit,
                key: key.clone(),
                session_id: sid(),
            }),
            HookEvent::EditConsulted { key } => p::Command::SessionLog(p::SessionLogInput {
                event: p::SessionEvent::EditConsulted,
                key: key.clone(),
                session_id: sid(),
            }),
            HookEvent::EditBlocked { key } => p::Command::SessionLog(p::SessionLogInput {
                event: p::SessionEvent::EditBlocked,
                key: key.clone(),
                session_id: sid(),
            }),
            HookEvent::FloorConsultBlocked { key } => p::Command::SessionLog(p::SessionLogInput {
                event: p::SessionEvent::FloorConsultMiss,
                key: key.clone(),
                session_id: sid(),
            }),
        };
        // Fire-and-forget — drop silently on failure (P9).
        let _ = super::daemon::daemon_v2(mati_root, cmd).await;
    }
}

// ── Platform output ─────────────────────────────────────────────────────────

/// The force-allow JSON, emitted ONLY for the Claude read gate.
///
/// INVARIANT (do not widen): `permissionDecision:"allow"` bypasses Claude
/// Code's permission system entirely. Read/Glob/Grep are no-permission tools,
/// so the read gate's allow is a harmless no-op. Bash and Edit/Write are
/// permission-REQUIRED tools — force-allowing them would silently suppress the
/// user's permission prompt for every command/edit mati doesn't deny (i.e.
/// installing mati would auto-approve arbitrary shell commands). Every variant
/// other than `ClaudePreRead` must DEFER: empty stdout, exit 0. Covered by
/// `only_pre_read_force_allows` in the test module.
fn allow_output(variant: HookVariant) -> Option<&'static str> {
    match variant {
        HookVariant::ClaudePreRead => Some(
            r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}"#,
        ),
        HookVariant::ClaudePreBash
        | HookVariant::CodexPreBash
        | HookVariant::CodexPostBash
        | HookVariant::CodexPreApplyPatch
        | HookVariant::ClaudePreEdit
        | HookVariant::ClaudePostMemGet => None,
    }
}

fn emit_allow(variant: HookVariant) {
    if let Some(json) = allow_output(variant) {
        println!("{json}");
    }
}

// emit_decision, emit_claude_decision, and emit_codex_pre_bash_decision
// have been replaced by format_decision() + format_claude_output() in the
// testable adapter core above. The run() function now uses process_eval_response().

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Unwrap a daemon response envelope, treating `{"ok": false}` as a failure.
///
/// `send_v2_raw` maps a daemon-side ERROR (backpressure, session mismatch,
/// handler failure) to `DaemonResult::Ok({"ok": false, ...})` — the transport
/// succeeded, the command didn't. Reading `data` without checking `ok` would
/// hand the gate a `Null` bundle that evaluates as NoRecord: the access is
/// allowed (correct, fail-open) but the audit trail records a false Miss
/// ("no knowledge about this file") instead of a gap, and `fail_open.log`
/// stays silent. Returns `None` on `ok: false` so callers take their
/// fail-open-and-record path instead.
fn daemon_data(resp: &serde_json::Value) -> Option<serde_json::Value> {
    if resp.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
        Some(resp.get("data").cloned().unwrap_or(serde_json::Value::Null))
    } else {
        None
    }
}

fn extract_gotcha_map(eval_data: &serde_json::Value) -> HashMap<String, serde_json::Value> {
    eval_data
        .get("gotcha_records")
        .and_then(|v| v.as_object())
        .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
        .unwrap_or_default()
}

/// Escape a string for inclusion inside a JSON string value.
///
/// Delegates to serde_json so ALL control characters (U+0000–U+001F) are
/// escaped, not just `\n`/`\r`/`\t` — an unescaped control char anywhere in a
/// deny reason would make the whole hook output unparseable, and an
/// unparseable deny is a lost deny.
fn escape_json_string(s: &str) -> String {
    let mut quoted =
        serde_json::to_string(s).expect("serializing a &str to a JSON string cannot fail");
    // Strip the surrounding quotes serde adds.
    quoted.pop();
    quoted.remove(0);
    quoted
}

// ── Testable adapter core ───────────────────────────────────────────────────

/// Result of processing a hook_evaluate response through the full adapter
/// pipeline: eval_data → EnforcementInput → evaluate → platform_events →
/// format output. Captures everything a test needs to verify without I/O.
#[derive(Debug)]
struct AdapterResult {
    /// Platform-specific stdout (JSON for Claude, empty for Codex allow).
    stdout: String,
    /// Platform-specific stderr (only Codex deny).
    stderr: String,
    /// Exit code (2 for Codex deny, 0 otherwise).
    exit_code: i32,
    /// Events to fire (already platform-filtered).
    events: Vec<HookEvent>,
    /// The semantic decision (used by tests via Debug).
    #[allow(dead_code)]
    decision: Decision,
}

// ── Floor consult mandate (enterprise governance overlay) ────────────────────

/// Compile the enterprise floor's signed consult-required globs, supplied out-of-band via
/// `MATI_CONSULT_GLOBS` (a JSON array of glob strings, e.g. `["phi/**","src/payments/**"]`).
///
/// A NEUTRAL primitive: OSS enforces per-actor consultation on whatever globs it is handed;
/// verifying the signed floor that produced them is the caller's job (mati-cloud). Returns
/// `None` (no mandate) when unset, empty, or unparseable — fail-open, matching the hook posture.
fn consult_globset() -> Option<GlobSet> {
    consult_globset_from(&std::env::var("MATI_CONSULT_GLOBS").ok()?)
}

/// The actor's consultation status from a `hook_evaluate` bundle: the recent-TTL flag for
/// edit/shell gates, the persistent flag otherwise (mirrors `check_eval_data`).
fn consulted_flag(eval_data: &serde_json::Value, include_recent: bool) -> bool {
    let field = if include_recent {
        "consulted_recent"
    } else {
        "consulted"
    };
    eval_data
        .get(field)
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
}

/// Pure compile step for [`consult_globset`], split out for testing without env.
fn consult_globset_from(raw: &str) -> Option<GlobSet> {
    let globs: Vec<String> = serde_json::from_str(raw).ok()?;
    if globs.is_empty() {
        return None;
    }
    let mut builder = GlobSetBuilder::new();
    for g in &globs {
        match Glob::new(g) {
            Ok(glob) => {
                builder.add(glob);
            }
            // Fail-open, but RECORDED: a typo'd org glob silently
            // un-enforcing a path class would be an unrecorded blind spot.
            Err(e) => log_fail_open(
                g,
                &format!("invalid consult-mandate glob, not enforced: {e}"),
            ),
        }
    }
    builder.build().ok().filter(|s| !s.is_empty())
}

/// Escalate the decision to a Deny when the accessed file matches a signed consult-required
/// glob and this actor has not consulted it — a governance mandate to consult even absent a
/// local gotcha. Never downgrades an existing Deny (deny > consult); no-op when there is no
/// mandate or the actor already consulted (consultation satisfies it, like a gotcha'd file).
/// The per-actor receipt is minted by the agent's own `mem_get` on the file.
fn apply_consult_mandate(
    adapter: &mut AdapterResult,
    variant: HookVariant,
    rel_path: &str,
    consulted: bool,
    globs: Option<&GlobSet>,
) {
    let Some(globs) = globs else {
        return;
    };
    if consulted || matches!(adapter.decision, Decision::Deny { .. }) || !globs.is_match(rel_path) {
        return;
    }
    let file_key = format!("file:{rel_path}");
    let decision = Decision::Deny {
        file_key: file_key.clone(),
        reason: format!(
            "[mati] Org policy requires consulting {rel_path} before access — \
             call mem_get(\"{file_key}\") first."
        ),
    };
    let events = platform_events(
        variant,
        &decision,
        vec![HookEvent::FloorConsultBlocked { key: file_key }],
    );
    let (stdout, stderr, exit_code) = format_decision(variant, &decision, rel_path);
    *adapter = AdapterResult {
        stdout,
        stderr,
        exit_code,
        events,
        decision,
    };
}

/// Special adapter outcome when the eval_data contains errors.
enum EvalDataCheck {
    /// Proceed with enforcement evaluation.
    Ok(EnforcementInput),
    /// Fail-open due to store/gotcha error.
    FailOpen(String),
}

/// Check eval_data for store/gotcha errors and build EnforcementInput.
fn check_eval_data(
    variant: HookVariant,
    rel_path: &str,
    eval_data: &serde_json::Value,
) -> EvalDataCheck {
    let include_recent = matches!(
        variant,
        HookVariant::CodexPreBash
            | HookVariant::CodexPostBash
            | HookVariant::CodexPreApplyPatch
            | HookVariant::ClaudePreEdit
            | HookVariant::ClaudePostMemGet
    );
    let already_consulted = if include_recent {
        eval_data
            .get("consulted_recent")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    } else {
        eval_data
            .get("consulted")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    };

    let input = EnforcementInput {
        rel_path: rel_path.to_string(),
        file_record: eval_data
            .get("file_record")
            .cloned()
            .filter(|v| !v.is_null()),
        gotcha_records: extract_gotcha_map(eval_data),
        already_consulted,
    };

    let store_error = eval_data
        .get("store_error")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if store_error && input.file_record.is_none() {
        return EvalDataCheck::FailOpen("store error during hook_evaluate".into());
    }

    let gotcha_error = eval_data
        .get("gotcha_error")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if gotcha_error {
        return EvalDataCheck::FailOpen("gotcha fetch error during hook_evaluate".into());
    }

    EvalDataCheck::Ok(input)
}

/// Process a hook_evaluate response through the full adapter pipeline.
/// No I/O — returns a result struct for testing.
fn process_eval_response(
    variant: HookVariant,
    rel_path: &str,
    eval_data: &serde_json::Value,
) -> AdapterResult {
    let enforcement_input = match check_eval_data(variant, rel_path, eval_data) {
        EvalDataCheck::Ok(input) => input,
        EvalDataCheck::FailOpen(_reason) => {
            // Same rule as `allow_output`: only the read gate force-allows;
            // every other variant defers on fail-open (empty stdout).
            let stdout = allow_output(variant)
                .map(str::to_string)
                .unwrap_or_default();
            return AdapterResult {
                stdout,
                stderr: String::new(),
                exit_code: 0,
                events: vec![],
                decision: Decision::Allow,
            };
        }
    };

    let result = decide::evaluate(&enforcement_input);
    let events = platform_events(variant, &result.decision, result.events);

    let (stdout, stderr, exit_code) = format_decision(variant, &result.decision, rel_path);

    AdapterResult {
        stdout,
        stderr,
        exit_code,
        events,
        decision: result.decision,
    }
}

/// Format the decision as platform output strings + exit code.
/// Does NOT call process::exit — returns the values for the caller to act on.
fn format_decision(
    variant: HookVariant,
    decision: &Decision,
    _rel_path: &str,
) -> (String, String, i32) {
    match variant {
        HookVariant::ClaudePreRead => {
            let stdout = format_claude_output(decision);
            (stdout, String::new(), 0)
        }
        HookVariant::ClaudePreBash => {
            // Bash is a permission-REQUIRED tool: a deny is a deny, but every
            // non-deny outcome must DEFER to the normal permission flow —
            // never `permissionDecision:"allow"`, which would suppress the
            // user's prompt for the command (see `allow_output`). Context for
            // advisory/consulted outcomes is injected via `additionalContext`
            // WITHOUT a permissionDecision, which Claude Code treats as
            // "inject context, permission flow proceeds normally".
            let stdout = match decision {
                Decision::Deny { reason, .. } => format_deny(reason),
                Decision::AlreadyConsulted { context } => {
                    format_context_only(&format!("[mati] Record already consulted. {context}"))
                }
                Decision::Advisory { context } | Decision::Liability { context, .. } => {
                    format_context_only(&format!("[mati] {context}"))
                }
                _ => String::new(),
            };
            (stdout, String::new(), 0)
        }
        HookVariant::ClaudePreEdit => match decision {
            // Use the decision's own reason (like the read gate) so the message reflects the
            // actual cause — a local gotcha OR an org consultation mandate — instead of always
            // claiming "Confirmed gotcha".
            Decision::Deny { reason, .. } => (format_deny(reason), String::new(), 0),
            // Non-deny: DEFER to the normal permission flow (empty stdout, exit 0).
            // Deliberately NOT permissionDecision:"allow" — see pre_edit.rs.
            _ => (String::new(), String::new(), 0),
        },
        HookVariant::CodexPreBash | HookVariant::CodexPreApplyPatch => match decision {
            Decision::Deny { file_key, .. } => {
                let stderr = format!("mati: call mem_get(\"{file_key}\") first");
                (String::new(), stderr, 2)
            }
            _ => (String::new(), String::new(), 0),
        },
        HookVariant::CodexPostBash | HookVariant::ClaudePostMemGet => {
            (String::new(), String::new(), 0)
        }
    }
}

/// PreToolUse deny JSON — shared by the read, bash, and edit gates.
fn format_deny(reason: &str) -> String {
    let escaped = escape_json_string(reason);
    format!(
        r#"{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"{escaped}"}}}}"#
    )
}

/// PreToolUse output that injects context WITHOUT a permissionDecision: the
/// permission flow proceeds normally. Used by permission-required tool gates
/// (Bash) for non-deny outcomes, where a force-allow would suppress the
/// user's prompt.
fn format_context_only(msg: &str) -> String {
    let escaped = escape_json_string(msg);
    format!(
        r#"{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","additionalContext":"{escaped}"}}}}"#
    )
}

fn format_claude_output(decision: &Decision) -> String {
    match decision {
        Decision::Deny { reason, .. } => format_deny(reason),
        Decision::AlreadyConsulted { context } => {
            let escaped =
                escape_json_string(&format!("[mati] Record already consulted. {context}"));
            format!(
                r#"{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"{escaped}"}}}}"#
            )
        }
        Decision::Advisory { context } => {
            let escaped = escape_json_string(&format!("[mati] {context}"));
            format!(
                r#"{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"{escaped}"}}}}"#
            )
        }
        Decision::Liability { context, .. } => {
            let escaped = escape_json_string(&format!("[mati] {context}"));
            format!(
                r#"{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"{escaped}"}}}}"#
            )
        }
        _ => {
            r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}"#
                .to_string()
        }
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    // ── extract_path ────────────────────────────────────────────────────

    #[test]
    fn extract_path_claude_pre_read_file_path() {
        let input = json!({"tool_input": {"file_path": "/home/user/project/src/main.rs"}});
        assert_eq!(
            extract_path(&input, HookVariant::ClaudePreRead),
            Some("/home/user/project/src/main.rs".into())
        );
    }

    #[test]
    fn extract_path_claude_pre_read_path_fallback() {
        let input = json!({"tool_input": {"path": "src/main.rs"}});
        assert_eq!(
            extract_path(&input, HookVariant::ClaudePreRead),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn extract_path_claude_pre_read_empty() {
        let input = json!({"tool_input": {"file_path": ""}});
        assert_eq!(extract_path(&input, HookVariant::ClaudePreRead), None);
    }

    #[test]
    fn extract_path_codex_pre_bash_cat() {
        let input = json!({"tool_input": {"command": "cat src/main.rs"}});
        assert_eq!(
            extract_path(&input, HookVariant::CodexPreBash),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn extract_path_codex_pre_bash_non_file_command() {
        let input = json!({"tool_input": {"command": "ls -la"}});
        assert_eq!(extract_path(&input, HookVariant::CodexPreBash), None);
    }

    #[test]
    fn extract_path_codex_pre_bash_empty_command() {
        let input = json!({"tool_input": {"command": ""}});
        assert_eq!(extract_path(&input, HookVariant::CodexPreBash), None);
    }

    #[test]
    fn extract_path_codex_fixture_tool_input_command() {
        // The supported Codex input fixture — proves no regression.
        let input = json!({"tool_input": {"command": "cat src/main.rs"}});
        assert_eq!(
            extract_path(&input, HookVariant::CodexPreBash),
            Some("src/main.rs".into())
        );
    }

    // ── platform_events ─────────────────────────────────────────────────

    #[test]
    fn codex_deny_translates_to_shell_blocked() {
        let events = vec![HookEvent::BlockedUnconsultedRead {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::Deny {
            file_key: "file:src/main.rs".into(),
            reason: "test".into(),
        };
        let result = platform_events(HookVariant::CodexPreBash, &decision, events);
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result[0],
            HookEvent::CodexShellBlocked { key } if key == "file:src/main.rs"
        ));
    }

    #[test]
    fn codex_advisory_suppresses_hit() {
        let events = vec![HookEvent::Hit {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::Advisory {
            context: "test".into(),
        };
        let result = platform_events(HookVariant::CodexPreBash, &decision, events);
        assert!(
            result.is_empty(),
            "Codex should not mint receipts for silent outcomes"
        );
    }

    #[test]
    fn codex_liability_suppresses_hit() {
        let events = vec![HookEvent::Hit {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::Liability {
            staleness: 0.85,
            context: "test".into(),
        };
        let result = platform_events(HookVariant::CodexPreBash, &decision, events);
        assert!(result.is_empty());
    }

    #[test]
    fn codex_already_consulted_suppresses_hit() {
        // Codex AlreadyConsulted emits ComplianceHit (post-Bug 1). Codex
        // pre-bash still suppresses it so codex-post-bash owns it.
        let events = vec![HookEvent::ComplianceHit {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::AlreadyConsulted {
            context: "test".into(),
        };
        let result = platform_events(HookVariant::CodexPreBash, &decision, events);
        assert!(result.is_empty());
    }

    #[test]
    fn codex_no_record_keeps_miss() {
        let events = vec![HookEvent::Miss {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::NoRecord;
        let result = platform_events(HookVariant::CodexPreBash, &decision, events);
        assert_eq!(result.len(), 1);
        assert!(matches!(&result[0], HookEvent::Miss { .. }));
    }

    #[test]
    fn claude_keeps_all_events() {
        let events = vec![HookEvent::Hit {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::Advisory {
            context: "test".into(),
        };
        let result = platform_events(HookVariant::ClaudePreRead, &decision, events);
        assert_eq!(
            result.len(),
            1,
            "Claude should keep Hit for advisory outcomes"
        );
    }

    #[test]
    fn claude_deny_keeps_blocked_event() {
        let events = vec![HookEvent::BlockedUnconsultedRead {
            key: "file:src/main.rs".into(),
        }];
        let decision = Decision::Deny {
            file_key: "file:src/main.rs".into(),
            reason: "test".into(),
        };
        let result = platform_events(HookVariant::ClaudePreBash, &decision, events);
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result[0],
            HookEvent::BlockedUnconsultedRead { .. }
        ));
    }

    // ── End-to-end adapter tests ────────────────────────────────────────
    //
    // These test the full adapter pipeline: mock hook_evaluate response →
    // EnforcementInput → evaluate → platform_events → format output.
    // Exercises the same code path as run() without daemon I/O.

    fn deny_eligible_eval_data() -> serde_json::Value {
        json!({
            "file_key": "file:src/main.rs",
            "file_record": {
                "value": "Entry point",
                "confidence": { "value": 0.7 },
                "quality": { "value": 0.5 },
                "staleness": { "value": 0.1, "tier": "fresh" },
                "payload": { "gotcha_keys": ["gotcha:test-rule"] }
            },
            "gotcha_records": {
                "gotcha:test-rule": {
                    "value": "Never call unwrap in this file",
                    "confidence": { "value": 0.8 },
                    "quality": { "value": 0.6 },
                    "payload": { "confirmed": true }
                }
            },
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        })
    }

    #[test]
    fn e2e_codex_deny_exit2_stderr_and_shell_blocked_event() {
        let data = deny_eligible_eval_data();
        let result = process_eval_response(HookVariant::CodexPreBash, "src/main.rs", &data);

        assert_eq!(result.exit_code, 2, "Codex deny must exit 2");
        assert!(
            result.stderr.contains("mem_get"),
            "stderr must instruct agent to call mem_get, got: {}",
            result.stderr
        );
        assert!(result.stdout.is_empty(), "Codex deny should have no stdout");
        assert_eq!(result.events.len(), 1);
        assert!(
            matches!(&result.events[0], HookEvent::CodexShellBlocked { key } if key == "file:src/main.rs"),
            "Codex deny must emit CodexShellBlocked, got: {:?}",
            result.events
        );
        assert!(matches!(result.decision, Decision::Deny { .. }));
    }

    #[test]
    fn e2e_codex_apply_patch_deny_exit2_when_unconsulted() {
        // apply_patch reads the recent-TTL receipt (consulted_recent). With no
        // receipt, a confirmed gotcha on a touched file must deny the edit.
        let data = deny_eligible_eval_data();
        let result = process_eval_response(HookVariant::CodexPreApplyPatch, "src/main.rs", &data);

        assert_eq!(result.exit_code, 2, "apply_patch deny must exit 2");
        assert!(matches!(result.decision, Decision::Deny { .. }));
        assert_eq!(result.events.len(), 1);
        assert!(
            matches!(&result.events[0], HookEvent::CodexShellBlocked { key } if key == "file:src/main.rs"),
            "apply_patch deny must emit CodexShellBlocked, got: {:?}",
            result.events
        );
    }

    #[test]
    fn e2e_codex_apply_patch_allows_after_consult() {
        // Once the file has a recent consultation receipt, the edit is allowed.
        let mut data = deny_eligible_eval_data();
        data["consulted_recent"] = json!(true);
        let result = process_eval_response(HookVariant::CodexPreApplyPatch, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "consulted edit must be allowed");
        assert!(!matches!(result.decision, Decision::Deny { .. }));
    }

    #[test]
    fn e2e_claude_deny_json_output_and_blocked_event() {
        let data = deny_eligible_eval_data();
        let result = process_eval_response(HookVariant::ClaudePreBash, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "Claude always exits 0");
        let json: serde_json::Value =
            serde_json::from_str(&result.stdout).expect("stdout must be valid JSON");
        assert_eq!(
            json.pointer("/hookSpecificOutput/permissionDecision")
                .and_then(|v| v.as_str()),
            Some("deny")
        );
        assert!(
            json.pointer("/hookSpecificOutput/permissionDecisionReason")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .contains("mem_get"),
            "deny reason must mention mem_get"
        );
        assert_eq!(result.events.len(), 1);
        assert!(matches!(
            &result.events[0],
            HookEvent::BlockedUnconsultedRead { .. }
        ));
    }

    #[test]
    fn e2e_codex_advisory_silent_no_hit() {
        let data = json!({
            "file_key": "file:src/lib.rs",
            "file_record": {
                "value": "Library root",
                "confidence": { "value": 0.45 },
                "quality": { "value": 0.5 },
                "staleness": { "value": 0.1, "tier": "fresh" },
                "payload": { "gotcha_keys": [] }
            },
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::CodexPreBash, "src/lib.rs", &data);

        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.is_empty(), "Codex advisory must be silent");
        assert!(result.stderr.is_empty());
        // Advisory emits Hit in the core, but Codex suppresses it.
        assert!(
            result.events.is_empty(),
            "Codex must NOT mint consultation receipt for advisory, got: {:?}",
            result.events
        );
        assert!(matches!(result.decision, Decision::Advisory { .. }));
    }

    #[test]
    fn e2e_claude_advisory_injects_context() {
        let data = json!({
            "file_key": "file:src/lib.rs",
            "file_record": {
                "value": "Library root",
                "confidence": { "value": 0.45 },
                "quality": { "value": 0.5 },
                "staleness": { "value": 0.1, "tier": "fresh" },
                "payload": { "gotcha_keys": [] }
            },
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::ClaudePreRead, "src/lib.rs", &data);

        assert_eq!(result.exit_code, 0);
        let json: serde_json::Value =
            serde_json::from_str(&result.stdout).expect("stdout must be valid JSON");
        assert_eq!(
            json.pointer("/hookSpecificOutput/permissionDecision")
                .and_then(|v| v.as_str()),
            Some("allow")
        );
        assert!(
            json.pointer("/hookSpecificOutput/additionalContext")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .contains("[mati]"),
            "Claude advisory must inject context"
        );
        // Claude DOES fire Hit for advisory.
        assert_eq!(result.events.len(), 1);
        assert!(matches!(&result.events[0], HookEvent::Hit { .. }));
    }

    #[test]
    fn e2e_codex_consulted_allows_silently() {
        let mut data = deny_eligible_eval_data();
        data["consulted_recent"] = json!(true);
        let result = process_eval_response(HookVariant::CodexPreBash, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "consulted file must not be blocked");
        assert!(result.stdout.is_empty());
        assert!(result.stderr.is_empty());
        // AlreadyConsulted is silent for Codex pre-bash — ComplianceHit is
        // suppressed so codex-post-bash is the sole emitter of AllowAfterReceipt
        // for shell commands.
        assert!(result.events.is_empty());
    }

    #[test]
    fn e2e_claude_consulted_records_allow_after_receipt() {
        // Bug 1 regression guard: when Claude pre-read allows a consulted
        // read, the adapter must emit ComplianceHit so the daemon records
        // an AllowAfterReceipt enforcement event.
        let mut data = deny_eligible_eval_data();
        data["consulted"] = json!(true);
        let result = process_eval_response(HookVariant::ClaudePreRead, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "Claude always exits 0");
        let json: serde_json::Value =
            serde_json::from_str(&result.stdout).expect("stdout must be valid JSON");
        assert_eq!(
            json.pointer("/hookSpecificOutput/permissionDecision")
                .and_then(|v| v.as_str()),
            Some("allow")
        );
        assert!(matches!(result.decision, Decision::AlreadyConsulted { .. }));
        assert_eq!(result.events.len(), 1);
        assert!(
            matches!(&result.events[0], HookEvent::ComplianceHit { key } if key == "file:src/main.rs"),
            "AlreadyConsulted must emit ComplianceHit so AllowAfterReceipt is recorded, got: {:?}",
            result.events
        );
    }

    #[test]
    fn e2e_store_error_fails_open() {
        let data = json!({
            "file_key": "file:src/main.rs",
            "file_record": null,
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": true,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::CodexPreBash, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "store error must fail open");
        assert_eq!(result.decision, Decision::Allow);
    }

    #[test]
    fn e2e_gotcha_error_fails_open() {
        let data = json!({
            "file_key": "file:src/main.rs",
            "file_record": {
                "value": "test",
                "confidence": { "value": 0.7 },
                "quality": { "value": 0.5 },
                "staleness": { "value": 0.1, "tier": "fresh" },
                "payload": { "gotcha_keys": ["gotcha:broken"] }
            },
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": true
        });
        let result = process_eval_response(HookVariant::ClaudePreBash, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "gotcha error must fail open");
        assert!(
            result.stdout.is_empty(),
            "Bash fail-open must DEFER (empty stdout), never force-allow — \
             Bash is permission-required; got: {}",
            result.stdout
        );
        assert_eq!(result.decision, Decision::Allow);
    }

    // ── Outer deadline wrapper ──────────────────────────────────────────
    //
    // Mirrors the production wrapper in `run()`: when the inner future
    // exceeds the deadline, the wrapper must produce an allow output and
    // log a fail-open entry. We can't drive the real `run()` from a unit
    // test (it reads stdin and may spawn daemons), so we test the deadline
    // shape directly using the same `tokio::time::timeout` + `emit_allow`
    // path the production code takes.

    async fn run_with_deadline<F>(deadline_ms: u64, variant: HookVariant, inner: F) -> Result<()>
    where
        F: std::future::Future<Output = Result<()>>,
    {
        match tokio::time::timeout(Duration::from_millis(deadline_ms), inner).await {
            Ok(inner_result) => inner_result,
            Err(_elapsed) => {
                // Match the production wrapper exactly. We don't write to
                // the real fail_open.log here — production code does, and
                // testing that side effect would require touching the home
                // dir. The load-bearing assertion is "completes within
                // budget + emits allow", not "wrote to disk".
                emit_allow(variant);
                Ok(())
            }
        }
    }

    #[tokio::test]
    async fn outer_deadline_emits_allow_on_timeout() {
        use std::time::Instant;

        // Use a small real deadline + a long inner sleep. We assert the
        // wrapper returns close to `deadline_ms`, not after `inner_sleep_ms`.
        // This proves `timeout` actually fires before the inner future
        // completes. The deadline is small so the test stays fast — the
        // production constant (HOOK_DEADLINE_MS = 2500) is verified
        // separately by the wrapper's structure, not by waiting 2.5s here.
        let deadline_ms = 100u64;
        let inner_sleep_ms = 5_000u64;

        let start = Instant::now();
        let result = run_with_deadline(deadline_ms, HookVariant::ClaudePreRead, async move {
            tokio::time::sleep(Duration::from_millis(inner_sleep_ms)).await;
            Ok(())
        })
        .await;
        let elapsed = start.elapsed();

        // The wrapper must absorb the timeout into Ok(()).
        assert!(
            result.is_ok(),
            "deadline wrapper must never propagate Err on timeout, got: {result:?}"
        );

        // The wrapper must complete close to the deadline, not after the
        // inner sleep. Generous upper bound to tolerate CI scheduler noise,
        // but well below `inner_sleep_ms` so timeout-vs-completion is
        // unambiguous.
        assert!(
            elapsed < Duration::from_millis(deadline_ms + 400),
            "wrapper took {elapsed:?} — should fire near deadline ({deadline_ms}ms), not wait for inner sleep ({inner_sleep_ms}ms)"
        );
        assert!(
            elapsed >= Duration::from_millis(deadline_ms),
            "wrapper took {elapsed:?} — must wait at least the deadline ({deadline_ms}ms) before timing out"
        );

        // The production wrapper calls `emit_allow(variant)` on timeout.
        // We can't capture process stdout from a unit test, so we verify
        // the contract by re-checking the exact JSON shape `emit_allow`
        // produces for the Claude variants — a regression there would also
        // break this test's expectations.
        let allow_json =
            r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}"#;
        let parsed: serde_json::Value =
            serde_json::from_str(allow_json).expect("allow JSON shape must parse");
        assert_eq!(
            parsed
                .pointer("/hookSpecificOutput/permissionDecision")
                .and_then(|v| v.as_str()),
            Some("allow"),
            "deadline path must produce permissionDecision=allow"
        );
    }

    #[test]
    fn daemon_data_rejects_error_envelope() {
        // The client wraps daemon-side errors (backpressure, session
        // mismatch, handler failure) as DaemonResult::Ok({"ok": false}).
        // The gate must treat those as eval failures — evaluating the
        // missing `data` as Null would record a false Miss.
        let ok = json!({"ok": true, "v": 2, "data": {"consulted": true}});
        assert_eq!(
            daemon_data(&ok),
            Some(json!({"consulted": true})),
            "ok envelope must yield its data"
        );
        let err = json!({"ok": false, "v": 2, "error": "backpressure", "code": "backpressure"});
        assert!(
            daemon_data(&err).is_none(),
            "error envelope must not evaluate as data"
        );
        assert!(daemon_data(&json!({"v": 2})).is_none());
    }

    // ── Coverage-widening guard ─────────────────────────────────────────
    //
    // `permissionDecision:"allow"` bypasses Claude Code's permission system.
    // Only the read gate (Read/Glob/Grep — no-permission tools) may ever emit
    // it. If this test fails, a change has reintroduced the Bash/edit
    // permission-prompt bypass.

    #[test]
    fn only_pre_read_force_allows() {
        use HookVariant::*;
        for variant in [
            ClaudePreRead,
            ClaudePreEdit,
            ClaudePreBash,
            CodexPreBash,
            CodexPostBash,
            CodexPreApplyPatch,
            ClaudePostMemGet,
        ] {
            // 1. The fail-open / no-path allow output.
            match variant {
                ClaudePreRead => assert!(
                    allow_output(variant).is_some(),
                    "read gate keeps its no-op allow"
                ),
                _ => assert!(
                    allow_output(variant).is_none(),
                    "{variant:?} must DEFER on allow — force-allow would bypass \
                     the user's permission prompt"
                ),
            }
            // 2. Every non-deny decision outcome.
            let non_deny_decisions = [
                Decision::Allow,
                Decision::NoRecord,
                Decision::Tombstone,
                Decision::AlreadyConsulted {
                    context: "ctx".into(),
                },
                Decision::Advisory {
                    context: "ctx".into(),
                },
                Decision::Liability {
                    staleness: 0.9,
                    context: "ctx".into(),
                },
            ];
            for decision in &non_deny_decisions {
                let (stdout, _, _) = format_decision(variant, decision, "src/x.rs");
                if variant != ClaudePreRead {
                    assert!(
                        !stdout.contains(r#""permissionDecision":"allow""#),
                        "{variant:?} emitted a force-allow for {decision:?}: {stdout}"
                    );
                }
            }
        }
    }

    #[test]
    fn e2e_claude_pre_bash_defers_no_record() {
        // A bash command touching a file with no record must DEFER — empty
        // stdout, so the user's Bash permission prompt is preserved.
        let data = json!({
            "file_key": "file:src/new.rs",
            "file_record": null,
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::ClaudePreBash, "src/new.rs", &data);

        assert_eq!(result.exit_code, 0);
        assert!(
            result.stdout.is_empty(),
            "no-record bash read must defer, got: {}",
            result.stdout
        );
        assert!(matches!(result.decision, Decision::NoRecord));
    }

    #[test]
    fn e2e_claude_pre_bash_advisory_injects_context_without_permission_decision() {
        // Advisory on the bash path: context is injected via additionalContext
        // ONLY — no permissionDecision field at all, so the permission flow
        // proceeds normally.
        let data = json!({
            "file_key": "file:src/lib.rs",
            "file_record": {
                "value": "Library root",
                "confidence": { "value": 0.45 },
                "quality": { "value": 0.5 },
                "staleness": { "value": 0.1, "tier": "fresh" },
                "payload": { "gotcha_keys": [] }
            },
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::ClaudePreBash, "src/lib.rs", &data);

        assert_eq!(result.exit_code, 0);
        let json: serde_json::Value =
            serde_json::from_str(&result.stdout).expect("stdout must be valid JSON");
        assert!(
            json.pointer("/hookSpecificOutput/permissionDecision")
                .is_none(),
            "bash advisory must NOT carry a permissionDecision, got: {}",
            result.stdout
        );
        assert!(
            json.pointer("/hookSpecificOutput/additionalContext")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .contains("[mati]"),
            "bash advisory must inject context, got: {}",
            result.stdout
        );
        assert!(matches!(result.decision, Decision::Advisory { .. }));
    }

    #[test]
    fn e2e_claude_pre_bash_deny_still_denies() {
        // The defer change must not weaken the deny: a confirmed unconsulted
        // gotcha on the bash path still emits permissionDecision:"deny".
        let data = deny_eligible_eval_data();
        let result = process_eval_response(HookVariant::ClaudePreBash, "src/main.rs", &data);

        let json: serde_json::Value =
            serde_json::from_str(&result.stdout).expect("stdout must be valid JSON");
        assert_eq!(
            json.pointer("/hookSpecificOutput/permissionDecision")
                .and_then(|v| v.as_str()),
            Some("deny")
        );
    }

    #[test]
    fn escape_json_string_escapes_control_chars() {
        // All of U+0000–U+001F must be escaped, not just \n \r \t — an
        // unescaped control char makes the deny JSON unparseable (lost deny).
        let hostile = "a\u{08}b\u{0C}c\u{1B}d\"e\\f\ng";
        let escaped = escape_json_string(hostile);
        let wrapped = format!("{{\"v\":\"{escaped}\"}}");
        let parsed: serde_json::Value =
            serde_json::from_str(&wrapped).expect("escaped output must be valid inside JSON");
        assert_eq!(parsed.pointer("/v").and_then(|v| v.as_str()), Some(hostile));
    }

    #[test]
    fn e2e_no_record_allows() {
        let data = json!({
            "file_key": "file:src/new.rs",
            "file_record": null,
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::ClaudePreRead, "src/new.rs", &data);

        assert_eq!(result.exit_code, 0);
        assert!(matches!(result.decision, Decision::NoRecord));
        assert_eq!(result.events.len(), 1);
        assert!(matches!(&result.events[0], HookEvent::Miss { .. }));
    }

    // ── ClaudePreEdit (WI-01, L1 edit-gate) ─────────────────────────────

    #[test]
    fn extract_path_claude_pre_edit_file_path() {
        // Edit/Write both pass the target at tool_input.file_path, same as Read.
        let input = json!({"tool_input": {"file_path": "/repo/src/pay.rs"}});
        assert_eq!(
            extract_path(&input, HookVariant::ClaudePreEdit),
            Some("/repo/src/pay.rs".into())
        );
    }

    #[test]
    fn extract_path_claude_pre_edit_notebook_path() {
        // NotebookEdit carries the target at tool_input.notebook_path, not
        // file_path — the edit gate must still extract it so notebooks are gated.
        let input = json!({"tool_input": {"notebook_path": "/repo/nb/analysis.ipynb"}});
        assert_eq!(
            extract_path(&input, HookVariant::ClaudePreEdit),
            Some("/repo/nb/analysis.ipynb".into())
        );
    }

    #[test]
    fn extract_path_codex_pre_bash_egrep_and_fgrep() {
        // egrep/fgrep satisfy Claude's read-before-edit; mati now detects them so
        // they can't be used to satisfy the read requirement unconsulted.
        let egrep = json!({"tool_input": {"command": "egrep TODO src/main.rs"}});
        assert_eq!(
            extract_path(&egrep, HookVariant::CodexPreBash),
            Some("src/main.rs".into())
        );
        let fgrep = json!({"tool_input": {"command": "fgrep needle src/main.rs"}});
        assert_eq!(
            extract_path(&fgrep, HookVariant::CodexPreBash),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn e2e_claude_pre_edit_denies_blind_edit() {
        // Blind edit (no consultation receipt) to a confirmed-gotcha file must be
        // denied with an edit-flavored Claude PreToolUse deny JSON.
        let data = deny_eligible_eval_data();
        let result = process_eval_response(HookVariant::ClaudePreEdit, "src/main.rs", &data);

        assert_eq!(
            result.exit_code, 0,
            "Claude always exits 0; deny is in the JSON"
        );
        let json: serde_json::Value =
            serde_json::from_str(&result.stdout).expect("deny stdout must be valid JSON");
        assert_eq!(
            json.pointer("/hookSpecificOutput/permissionDecision")
                .and_then(|v| v.as_str()),
            Some("deny")
        );
        // The message now comes from the decision's own reason (like the read gate), so it
        // instructs the agent to consult; the edit-vs-read distinction lives in the event below
        // (EditBlocked → `edit_blocked_unconsulted`), not the message wording.
        assert!(
            json.pointer("/hookSpecificOutput/permissionDecisionReason")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .contains("mem_get"),
            "deny reason must instruct the agent to consult, got: {}",
            result.stdout
        );
        // Plane 2: records an edit-attributed Deny enforcement event.
        assert_eq!(result.events.len(), 1);
        assert!(matches!(&result.events[0], HookEvent::EditBlocked { .. }));
        assert!(matches!(result.decision, Decision::Deny { .. }));
    }

    #[test]
    fn e2e_claude_pre_edit_defers_after_consult() {
        // With a RECENT consultation receipt (consulted_recent, matching the
        // Codex apply_patch edit gate), the edit DEFERS to the normal permission
        // flow (empty stdout, exit 0) — deliberately NOT a forced allow.
        let mut data = deny_eligible_eval_data();
        data["consulted_recent"] = json!(true);
        let result = process_eval_response(HookVariant::ClaudePreEdit, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0);
        assert!(
            result.stdout.is_empty(),
            "consulted edit must DEFER (empty stdout), not force-allow, got: {}",
            result.stdout
        );
        assert!(result.stderr.is_empty());
        assert!(matches!(result.decision, Decision::AlreadyConsulted { .. }));
        // Plane 2: a consulted edit records an EditConsulted event (→
        // AllowAfterReceipt, reason `edit_after_receipt`) — the audit evidence
        // that this edit was preceded by a recent consult.
        assert_eq!(result.events.len(), 1);
        assert!(matches!(&result.events[0], HookEvent::EditConsulted { .. }));
    }

    #[test]
    fn e2e_claude_pre_edit_defers_no_record() {
        // No record / no gotcha → defer (never force-allow, never block) so the
        // user's normal edit-permission flow applies.
        let data = json!({
            "file_key": "file:src/new.rs",
            "file_record": null,
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": false,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::ClaudePreEdit, "src/new.rs", &data);

        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.is_empty(), "no-record edit must defer");
        assert!(matches!(result.decision, Decision::NoRecord));
        // No block event for a non-gotcha file.
        assert!(result.events.is_empty());
    }

    #[test]
    fn e2e_claude_pre_edit_store_error_defers() {
        // Fail-open: a store error must defer (empty stdout), never block the edit.
        let data = json!({
            "file_key": "file:src/main.rs",
            "file_record": null,
            "gotcha_records": {},
            "consulted": false,
            "consulted_recent": false,
            "store_error": true,
            "gotcha_error": false
        });
        let result = process_eval_response(HookVariant::ClaudePreEdit, "src/main.rs", &data);

        assert_eq!(result.exit_code, 0, "store error must fail open (defer)");
        assert!(result.stdout.is_empty());
        assert_eq!(result.decision, Decision::Allow);
    }

    // ── canonical_rel_path (WI-20 symlink-bypass fallback) ──────────────────
    //
    // These exercise the canonical-key resolver directly against a real
    // filesystem (tempdir + real symlinks). The full deny-through-symlink
    // enforcement is proven end-to-end in `tests/hook_decide_integration.rs`.

    // Unix-only: these create real symlinks via `std::os::unix::fs::symlink`.
    // The CI test matrix is Unix-only (ubuntu + macos); gating at the function
    // level keeps them honest if a Windows runner is ever added, matching the
    // integration test's `#[cfg(unix)]`.
    #[cfg(unix)]
    #[test]
    fn canonical_rel_resolves_symlink_to_real_target_key() {
        // A symlink to a real in-repo file must canonicalize to the REAL
        // target's repo-relative key — this is the bypass-closing resolution.
        let repo = tempfile::TempDir::new().expect("tempdir");
        let root = repo.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/real.rs"), "fn x() {}\n").unwrap();
        // link.rs (at repo root) → src/real.rs
        std::os::unix::fs::symlink(root.join("src/real.rs"), root.join("link.rs")).unwrap();

        // Accessed via the symlink. Lexical key would be "link.rs"; canonical
        // must resolve to "src/real.rs".
        let got = canonical_rel_path(
            root.join("link.rs").to_str().unwrap(),
            root,
            Some(root),
            "link.rs",
        );
        assert_eq!(got.as_deref(), Some("src/real.rs"));
    }

    #[cfg(unix)]
    #[test]
    fn canonical_rel_relative_access_resolves_against_cwd() {
        // A bare relative shell arg (`cat link.rs`) resolves against cwd (the
        // repo root) before canonicalization.
        let repo = tempfile::TempDir::new().expect("tempdir");
        let root = repo.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/real.rs"), "fn x() {}\n").unwrap();
        std::os::unix::fs::symlink(root.join("src/real.rs"), root.join("link.rs")).unwrap();

        let got = canonical_rel_path("link.rs", root, Some(root), "link.rs");
        assert_eq!(got.as_deref(), Some("src/real.rs"));
    }

    #[test]
    fn canonical_rel_non_symlink_is_noop() {
        // A plain (non-symlink) in-repo file canonicalizes back to its own
        // lexical key — the helper returns None so we skip the redundant
        // second daemon round-trip (zero-cost common path).
        let repo = tempfile::TempDir::new().expect("tempdir");
        let root = repo.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/real.rs"), "fn x() {}\n").unwrap();

        let got = canonical_rel_path(
            root.join("src/real.rs").to_str().unwrap(),
            root,
            Some(root),
            "src/real.rs",
        );
        assert_eq!(got, None, "non-symlink access must not trigger a fallback");
    }

    #[cfg(unix)]
    #[test]
    fn canonical_rel_outside_repo_is_none() {
        // A symlink pointing OUTSIDE the repo must NOT yield a key — it can't
        // match a store record and must never deny. Falls back to lexical-only.
        let repo = tempfile::TempDir::new().expect("tempdir");
        let outside = tempfile::TempDir::new().expect("tempdir");
        let root = repo.path();
        std::fs::write(outside.path().join("secret.rs"), "fn x() {}\n").unwrap();
        std::os::unix::fs::symlink(outside.path().join("secret.rs"), root.join("escape.rs"))
            .unwrap();

        let got = canonical_rel_path(
            root.join("escape.rs").to_str().unwrap(),
            root,
            Some(root),
            "escape.rs",
        );
        assert_eq!(got, None, "out-of-repo symlink target must yield no key");
    }

    #[test]
    fn canonical_rel_no_repo_root_is_none() {
        // Without a repo root we can't form a repo-relative key — fall back to
        // lexical-only (never crash).
        let got = canonical_rel_path("/some/abs/path.rs", Path::new("/tmp"), None, "path.rs");
        assert_eq!(got, None);
    }

    #[test]
    fn canonical_rel_nonexistent_leaf_under_real_dir() {
        // canonicalize_lenient tolerates a missing leaf: a not-yet-created file
        // under a real (possibly symlinked) directory still yields its key.
        let repo = tempfile::TempDir::new().expect("tempdir");
        let root = repo.path();
        std::fs::create_dir_all(root.join("src")).unwrap();

        // No symlink, leaf does not exist → canonicalizes to its own lexical
        // key → no-op (None).
        let got = canonical_rel_path(
            root.join("src/ghost.rs").to_str().unwrap(),
            root,
            Some(root),
            "src/ghost.rs",
        );
        assert_eq!(got, None);
    }

    // ── Floor consult mandate overlay ────────────────────────────────────────

    fn allow_adapter() -> AdapterResult {
        AdapterResult {
            stdout: "allow".to_string(),
            stderr: String::new(),
            exit_code: 0,
            events: vec![],
            decision: Decision::Allow,
        }
    }

    fn phi_globs() -> GlobSet {
        consult_globset_from(r#"["phi/**"]"#).unwrap()
    }

    #[test]
    fn consult_globset_from_parses_and_rejects() {
        assert!(consult_globset_from(r#"["phi/**","src/pay/**"]"#).is_some());
        assert!(consult_globset_from("[]").is_none());
        assert!(consult_globset_from("not json").is_none());
    }

    #[test]
    fn mandate_denies_unconsulted_match() {
        let g = phi_globs();
        let mut a = allow_adapter();
        apply_consult_mandate(
            &mut a,
            HookVariant::ClaudePreRead,
            "phi/records.rs",
            false,
            Some(&g),
        );
        assert!(matches!(a.decision, Decision::Deny { .. }));
        assert!(
            a.stdout.contains("deny"),
            "pre-read deny output must be emitted"
        );
        assert!(
            matches!(
                a.events.first(),
                Some(HookEvent::FloorConsultBlocked { .. })
            ),
            "floor mandate deny must emit its own event (distinct audit reason code)"
        );
    }

    #[test]
    fn mandate_pre_edit_deny_uses_org_policy_message() {
        let g = phi_globs();
        let mut a = allow_adapter();
        apply_consult_mandate(
            &mut a,
            HookVariant::ClaudePreEdit,
            "phi/records.rs",
            false,
            Some(&g),
        );
        assert!(matches!(a.decision, Decision::Deny { .. }));
        assert!(
            a.stdout.contains("deny") && a.stdout.contains("Org policy"),
            "pre-edit mandate deny must show the org-policy reason, not 'Confirmed gotcha'; got {}",
            a.stdout
        );
    }

    #[test]
    fn mandate_allows_when_consulted() {
        let g = phi_globs();
        let mut a = allow_adapter();
        apply_consult_mandate(
            &mut a,
            HookVariant::ClaudePreRead,
            "phi/records.rs",
            true,
            Some(&g),
        );
        assert!(
            matches!(a.decision, Decision::Allow),
            "consultation satisfies the mandate"
        );
    }

    #[test]
    fn mandate_noop_on_nonmatch_or_no_globs() {
        let g = phi_globs();
        let mut a = allow_adapter();
        apply_consult_mandate(
            &mut a,
            HookVariant::ClaudePreRead,
            "src/main.rs",
            false,
            Some(&g),
        );
        assert!(
            matches!(a.decision, Decision::Allow),
            "non-matching path is untouched"
        );

        let mut b = allow_adapter();
        apply_consult_mandate(
            &mut b,
            HookVariant::ClaudePreRead,
            "phi/records.rs",
            false,
            None,
        );
        assert!(
            matches!(b.decision, Decision::Allow),
            "no mandate -> no change"
        );
    }

    #[test]
    fn mandate_applies_to_apply_patch_variant() {
        // Parity: the enterprise consult mandate gates Codex apply_patch edits
        // exactly like reads/edits — deny with exit 2 + mem_get instruction.
        let g = phi_globs();
        let mut a = allow_adapter();
        apply_consult_mandate(
            &mut a,
            HookVariant::CodexPreApplyPatch,
            "phi/records.rs",
            false,
            Some(&g),
        );
        assert!(matches!(a.decision, Decision::Deny { .. }));
        assert_eq!(a.exit_code, 2, "apply_patch mandate deny must exit 2");
        assert!(
            a.stderr.contains("mem_get"),
            "apply_patch mandate deny must instruct consultation, got: {}",
            a.stderr
        );
    }

    #[test]
    fn mandate_preserves_existing_deny() {
        let g = phi_globs();
        let mut a = AdapterResult {
            stdout: "x".to_string(),
            stderr: String::new(),
            exit_code: 0,
            events: vec![],
            decision: Decision::Deny {
                file_key: "file:phi/x.rs".to_string(),
                reason: "gotcha-deny".to_string(),
            },
        };
        apply_consult_mandate(
            &mut a,
            HookVariant::ClaudePreRead,
            "phi/x.rs",
            false,
            Some(&g),
        );
        match &a.decision {
            Decision::Deny { reason, .. } => {
                assert_eq!(reason, "gotcha-deny", "deny > consult; not overwritten")
            }
            _ => panic!("expected the pre-existing Deny to survive"),
        }
    }
}