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
//! Protocol v2 dispatch — typed semantic commands with audit trail.
//!
//! This module is the ONLY entry point for commands received on the daemon
//! socket. The wire layer (`socket_handle_connection`) accepts only v2
//! `protocol::Request` messages — v1 raw-string commands are not accepted
//! from the wire.
//!
//! ## Command routing
//!
//! - **Knowledge-side mutations** (8 commands): native handlers in
//!   `mcp::handlers`. Mutation + file-link updates + audit committed
//!   atomically in one `transact_knowledge` call.
//! - **Session-side mutations** (4 commands): native handlers here.
//!   Mutation + audit committed atomically in one `transact_sessions_raw`.
//! - **Side-effecting reads** (MemGet, MemBootstrap): native handlers in
//!   `mcp::handlers`. Consultation receipts + audit committed atomically
//!   in sessions tree. Cross-tree access_count bumps are deferred best-effort.
//! - **Compound** (FileEditHook): per-tree atomic batches with substep audit.
//! - **MemQuery**: native pure-read handler via `dispatch_mem_query`
//!   (γ-C1.5). Centralizes mode dispatch so v1 (rmcp tool wrapper) and
//!   v2 (typed Command::MemQuery) produce byte-identical responses.
//! - **Pure reads** (8 commands): v1 bridge for read-only dispatch. No
//!   mutations, no audit, no side effects. The v1 bridge CANNOT reach
//!   `put` or `delete` — no `Command` variant maps to those strings.
//!
//! ## Audit routing
//!
//! - Knowledge-side: `audit:knowledge:<nanos>` in the knowledge tree
//!   (Immediate durability, co-located with mutation).
//! - Session-side + side-effecting reads: `audit:session:<nanos>` in the
//!   sessions tree (Eventual durability, co-located with mutation).
//!
//! ## Transaction model
//!
//! SurrealKV supports multi-key atomic transactions within a single tree.
//! The real constraint is mati's two-tree architecture: no single
//! transaction can span both the knowledge and sessions trees.
//!
//! - Same-tree commands: mutation + audit in one transaction.
//! - Cross-tree commands (FileEditHook, SessionHarvest): per-tree atomic
//!   batches with explicit substep audit.
//! - Best-effort secondary effects (graph edges, access_count bumps):
//!   outside the main transaction, failures logged but not propagated.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use uuid::Uuid;

use crate::graph::Graph;
use crate::mcp::metadata::PeerContext;
use crate::mcp::metrics;
use crate::mcp::protocol::{self, AuditEntry, Command, ErrorCode, Request, Response};
use crate::store::session as sess;

// ── Request context ─────────────────────────────────────────────────────────

/// Ambient context for a single v2 request. Constructed once in
/// `socket_handle_connection`, consumed by `dispatch_v2`.
///
/// Not Clone by design — each request gets exactly one context.
pub(crate) struct RequestContext {
    /// Peer identity from Unix socket credentials.
    pub peer: PeerContext,
    /// Daemon session UUID (from DaemonMetadata, established at startup).
    pub daemon_session: Uuid,
    /// Repository root path (for commands needing filesystem access).
    pub repo_root: PathBuf,
}

// ── V2 dispatch entry point ─────────────────────────────────────────────────

/// Dispatch a v2 protocol request. Returns a v2 `Response`.
///
/// Flow:
/// 1. Validate protocol version (fail-closed before any side effect)
/// 2. Classify command as knowledge-side, session-side, or pure-read
/// 3. Dispatch to appropriate handler path
/// 4. Write audit entry transactionally where possible
pub(crate) async fn dispatch_v2(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: Request,
) -> Response {
    // Capture command kind before dispatch so it survives any `req` move into
    // a handler. The metrics layer is a process-global no-op when not
    // initialized (tests, etc), so this is safe regardless of daemon state.
    let command_kind = req.cmd.kind();
    let start = Instant::now();

    // Funnel every return path through a single block expression so the
    // metric recorder below captures version-mismatch and session-mismatch
    // rejections the same way it captures successful dispatches.
    let resp: Response = 'dispatch: {
        // 1. Version check — enforced before any dispatch or side effect.
        if req.v != protocol::PROTOCOL_VERSION {
            let resp = Response::err(
                req.id,
                ErrorCode::VersionMismatch,
                format!(
                    "protocol version mismatch: client={} server={}",
                    req.v,
                    protocol::PROTOCOL_VERSION
                ),
            );
            // Audit version mismatch for mutating commands (best-effort since
            // the version itself is wrong — we don't know which tree to target).
            if req.cmd.is_mutation() {
                best_effort_audit(graph, ctx, &req, false, Some(ErrorCode::VersionMismatch)).await;
            }
            break 'dispatch resp;
        }

        // 1b. Session fence — reject requests from stale clients whose cached
        // daemon metadata predates a daemon restart. The client should re-read
        // DaemonMetadata and retry once. Nil session on the request is tolerated
        // only when the daemon itself has a nil session (test / legacy fallback).
        if req.session != ctx.daemon_session {
            let resp = Response::err(
                req.id,
                ErrorCode::SessionMismatch,
                format!(
                    "session mismatch: request={} daemon={}; re-read daemon metadata and retry",
                    req.session, ctx.daemon_session
                ),
            );
            if req.cmd.is_mutation() {
                best_effort_audit(graph, ctx, &req, false, Some(ErrorCode::SessionMismatch)).await;
            }
            break 'dispatch resp;
        }

        // 2. Dispatch based on command classification.
        //
        // All mutations and side-effecting reads have native handlers.
        // Only pure reads (8 commands) use the v1 bridge, which cannot
        // reach any mutation path.
        if is_side_effecting_read(&req.cmd) {
            // MemGet / MemBootstrap: native handler with sessions-tree
            // transactional audit + deferred cross-tree best-effort writes.
            dispatch_side_effecting_read(graph, ctx, &req).await
        } else if matches!(&req.cmd, Command::MemQuery(_)) {
            // γ-C1.5: mem_query is a pure read (no audit, no side effects)
            // but still has rich business logic — route natively to the
            // canonical `handle_mem_query` so v1 and v2 dispatch can never
            // drift. Pre-γ, this fell through to the v1 bridge which
            // serialized back to a string and re-entered `MatiServer::mem_query`.
            dispatch_mem_query(graph, &req).await
        } else if is_session_side(&req.cmd) {
            // Session-side mutations: native handler with audit in sessions tree.
            dispatch_session_side(graph, ctx, &req).await
        } else if is_knowledge_mutation(&req.cmd) {
            // Knowledge-side mutations: native handler with atomic mutation+audit
            // in one transact_knowledge commit.
            dispatch_knowledge_mutation(graph, ctx, &req).await
        } else if is_compound(&req.cmd) {
            // FileEditHook: compound (consultation hit in sessions + reparse in knowledge).
            // Each substep has its own audit in its respective tree.
            dispatch_file_edit_hook(graph, ctx, &req).await
        } else if is_config_command(&req.cmd) {
            // Runtime config get/set — talks to enforcement helpers that use
            // raw bytes outside the transact_knowledge audit path. ConfigSet
            // already emits an EnforcementConfigChanged event via the helper,
            // which is the human-facing audit signal for config changes.
            dispatch_config(graph, &req).await
        } else {
            // Pure reads only — no mutations, no side effects, no audit.
            dispatch_via_v1(graph, ctx, &req).await
        }
    };

    // Saturating cast: per-request latencies above u32::MAX µs (~71 minutes)
    // are pegged rather than wrapping to a tiny value.
    let elapsed_us = start.elapsed().as_micros().min(u128::from(u32::MAX)) as u32;
    let is_error = matches!(resp, Response::Err { .. });
    metrics::record(command_kind, elapsed_us, is_error);

    resp
}

/// Returns true for side-effecting read commands (Category B).
/// These have native handlers with sessions-tree transactional audit.
fn is_side_effecting_read(cmd: &Command) -> bool {
    matches!(cmd, Command::MemGet(_) | Command::MemBootstrap(_))
}

/// Returns true for commands whose mutations target the sessions tree.
fn is_session_side(cmd: &Command) -> bool {
    matches!(
        cmd,
        Command::SessionLog(_)
            | Command::ConsultationHit(_)
            | Command::SessionFlush
            | Command::SessionHarvest
            | Command::SessionClearConsults
    )
}

/// Returns true for mutation commands whose primary writes target the
/// knowledge tree. These use native handlers with atomic mutation+audit.
fn is_knowledge_mutation(cmd: &Command) -> bool {
    matches!(
        cmd,
        Command::GotchaUpsert(_)
            | Command::GotchaConfirm(_)
            | Command::GotchaTombstone(_)
            | Command::FileEnrich(_)
            | Command::FileReparse(_)
            | Command::DocCapture(_)
            | Command::DecisionUpsert(_)
            | Command::DevNoteUpsert(_)
            | Command::RecordImport(_)
    )
}

/// FileEditHook is a compound: ConsultationHit (session) + FileReparse (knowledge).
/// Handled by dispatching to both paths — not a single-tree transaction.
fn is_compound(cmd: &Command) -> bool {
    matches!(cmd, Command::FileEditHook(_))
}

/// Returns true for runtime configuration commands. These touch raw key/value
/// pairs (`enforcement:mode`, `enforcement:retention_days`) and are routed
/// through a dedicated dispatcher rather than the v1 bridge or the typical
/// knowledge-mutation transactional audit path.
fn is_config_command(cmd: &Command) -> bool {
    matches!(
        cmd,
        Command::ConfigGet(_) | Command::ConfigSet(_) | Command::SandboxAudit(_)
    )
}

/// Dispatch ConfigGet / ConfigSet against the daemon's store.
///
/// ConfigGet is a pure read with no audit entry. ConfigSet calls the
/// enforcement helpers, which already write an `EnforcementConfigChanged`
/// event whenever the value actually changes — that event is the durable
/// audit trail for config mutations.
async fn dispatch_config(graph: &Arc<tokio::sync::RwLock<Graph>>, req: &Request) -> Response {
    use crate::store::enforcement::{
        get_enforcement_mode, get_retention_days, set_enforcement_mode, set_retention_days,
        EnforcementMode,
    };

    let request_id = req.id;
    let g = graph.read().await;
    let store = g.store();

    match &req.cmd {
        Command::ConfigGet(input) => {
            let value = match input.key.as_str() {
                "audit.write_durability" => {
                    let mode = get_enforcement_mode(store).await;
                    match mode {
                        EnforcementMode::Advisory => "best_effort".to_string(),
                        EnforcementMode::Strict => "strict".to_string(),
                    }
                }
                "enforcement.retention" => get_retention_days(store).await.to_string(),
                other => {
                    return Response::err(
                        request_id,
                        ErrorCode::ValidationFailed,
                        format!(
                            "unknown config key: {other}; valid keys: audit.write_durability, enforcement.retention"
                        ),
                    );
                }
            };
            Response::ok(request_id, serde_json::Value::String(value))
        }
        Command::ConfigSet(input) => match input.key.as_str() {
            "audit.write_durability" => {
                let mode = match input.value.as_str() {
                    "best_effort" => EnforcementMode::Advisory,
                    "strict" => EnforcementMode::Strict,
                    other => {
                        return Response::err(
                            request_id,
                            ErrorCode::ValidationFailed,
                            format!(
                                "invalid audit.write_durability: {other}; valid values: best_effort, strict"
                            ),
                        );
                    }
                };
                match set_enforcement_mode(store, mode).await {
                    Ok(old) => {
                        let old_label = match old {
                            EnforcementMode::Advisory => "best_effort",
                            EnforcementMode::Strict => "strict",
                        };
                        Response::ok(request_id, serde_json::json!({ "old": old_label }))
                    }
                    Err(e) => Response::err(request_id, ErrorCode::StoreError, e.to_string()),
                }
            }
            "enforcement.retention" => {
                let days: u64 = match input.value.parse() {
                    Ok(d) if d > 0 => d,
                    Ok(_) => {
                        return Response::err(
                            request_id,
                            ErrorCode::ValidationFailed,
                            "retention must be at least 1 day".to_string(),
                        );
                    }
                    Err(_) => {
                        return Response::err(
                            request_id,
                            ErrorCode::ValidationFailed,
                            format!(
                                "invalid retention value: {} (expected integer days)",
                                input.value
                            ),
                        );
                    }
                };
                match set_retention_days(store, days).await {
                    Ok(()) => Response::ok(request_id, serde_json::Value::Null),
                    Err(e) => Response::err(request_id, ErrorCode::StoreError, e.to_string()),
                }
            }
            other => Response::err(
                request_id,
                ErrorCode::ValidationFailed,
                format!(
                    "unknown config key: {other}; valid keys: audit.write_durability, enforcement.retention"
                ),
            ),
        },
        Command::SandboxAudit(input) => {
            // Best-effort: record the L3 sandbox-floor change as an
            // EnforcementConfigChanged event in the hash-chained log (socket-mode
            // counterpart of the CLI's direct-mode recording).
            let _ = crate::store::enforcement::record_event(
                store,
                crate::store::enforcement::EnforcementEventType::EnforcementConfigChanged {
                    setting: input.setting.clone(),
                    old_value: String::new(),
                    new_value: input.new_value.clone(),
                },
                crate::store::enforcement::SubjectKind::Config,
                input.setting.clone(),
                "cli".to_string(),
                None,
                input.reason.clone(),
                None,
            )
            .await;
            Response::ok(request_id, serde_json::Value::Null)
        }
        _ => unreachable!("is_config_command guard"),
    }
}

// ── Side-effecting read handlers ────────────────────────────────────────────

/// Pure-read native dispatch for `Command::MemQuery`. Calls
/// `handle_mem_query` directly — no audit, no consultation receipt, no
/// deferred writes. γ-C1.5 contract: v1-string and v2-typed paths produce
/// byte-identical responses for the same MemQueryInput.
async fn dispatch_mem_query(graph: &Arc<tokio::sync::RwLock<Graph>>, req: &Request) -> Response {
    use super::handlers;
    let request_id = req.id;
    let input = match &req.cmd {
        Command::MemQuery(i) => i,
        _ => unreachable!("dispatch_mem_query guard"),
    };
    let g = graph.read().await;
    match handlers::handle_mem_query(g.store(), &g, input).await {
        Ok(data) => Response::ok(request_id, data),
        Err((code, msg)) => Response::err(request_id, code, msg),
    }
}

async fn dispatch_side_effecting_read(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: &Request,
) -> Response {
    use super::handlers;
    let request_id = req.id;

    match &req.cmd {
        Command::MemGet(input) => {
            let g = graph.read().await;
            match handlers::handle_mem_get(g.store(), graph, ctx, request_id, input).await {
                Ok(data) => Response::ok(request_id, data),
                Err((code, msg)) => {
                    // Handler error paths skip audit — write rejection audit
                    // to sessions tree before returning.
                    let entry = build_audit_entry(
                        ctx,
                        request_id,
                        "mem_get",
                        &input.key,
                        false,
                        Some(code.clone()),
                    );
                    write_session_audit(g.store(), &entry).await;
                    Response::err(request_id, code, msg)
                }
            }
        }
        Command::MemBootstrap(input) => {
            let g = graph.read().await;
            match handlers::handle_mem_bootstrap(g.store(), &g, graph, ctx, request_id, input).await
            {
                Ok(injection) => Response::ok(request_id, serde_json::Value::String(injection)),
                Err((code, msg)) => {
                    // Handler already wrote rejection audit to sessions tree.
                    Response::err(request_id, code, msg)
                }
            }
        }
        _ => unreachable!("is_side_effecting_read guard"),
    }
}

// ── Knowledge-side native handlers ──────────────────────────────────────────
//
// These handlers use typed DTOs, validate input, and commit mutation+audit
// atomically in a single transact_knowledge call.

async fn dispatch_knowledge_mutation(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: &Request,
) -> Response {
    use super::handlers;

    let g = graph.read().await;
    let store = g.store();
    let request_id = req.id;

    let result = match &req.cmd {
        Command::GotchaUpsert(input) => {
            handlers::handle_gotcha_upsert(store, ctx, request_id, input).await
        }
        Command::GotchaConfirm(input) => {
            handlers::handle_gotcha_confirm(store, ctx, request_id, input).await
        }
        Command::GotchaTombstone(input) => {
            handlers::handle_gotcha_tombstone(store, ctx, request_id, input).await
        }
        Command::FileEnrich(input) => {
            handlers::handle_file_enrich(store, ctx, request_id, input).await
        }
        Command::FileReparse(input) => {
            handlers::handle_file_reparse(store, ctx, request_id, input, &ctx.repo_root).await
        }
        Command::DocCapture(input) => {
            handlers::handle_doc_capture(store, ctx, request_id, input, &ctx.repo_root).await
        }
        Command::DecisionUpsert(input) => {
            handlers::handle_decision_upsert(store, ctx, request_id, input).await
        }
        Command::DevNoteUpsert(input) => {
            handlers::handle_dev_note_upsert(store, ctx, request_id, input).await
        }
        Command::RecordImport(input) => {
            handlers::handle_record_import(store, ctx, request_id, input).await
        }
        _ => {
            unreachable!("is_knowledge_mutation guard ensures only knowledge mutations reach here")
        }
    };

    match result {
        Ok(data) => Response::ok(request_id, data),
        Err((code, message)) => {
            // Write rejected-mutation audit (still atomic — rejection means
            // no mutation record, so audit is a standalone knowledge write).
            if let Some((audit_key, audit_bytes)) = handlers::make_audit(
                ctx,
                request_id,
                req.cmd.kind(),
                req.cmd.target_key(),
                false,
                Some(code.clone()),
            ) {
                let _ = store.put_raw(&audit_key, &audit_bytes).await;
            }
            Response::err(request_id, code, message)
        }
    }
}

// ── FileEditHook — compound command ─────────────────────────────────────────
//
// Substep 1: ConsultationHit (sessions tree) — best-effort.
// Substep 2: FileReparse (knowledge tree) — native handler with audit.
// Each substep writes its own audit in its respective tree.

async fn dispatch_file_edit_hook(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: &Request,
) -> Response {
    let input = match &req.cmd {
        Command::FileEditHook(i) => i,
        _ => unreachable!(),
    };
    let request_id = req.id;

    // Substep 1: consultation hit (sessions tree, best-effort).
    //
    // Same staged transactional model as ConsultationHit: daily agg +
    // consultation receipt + audit committed atomically in one
    // sessions-tree transaction. Cross-tree access_count bump is a
    // separate best-effort write. The whole substep is non-blocking —
    // staging or transaction failures are logged, never propagated.
    {
        let g = graph.read().await;
        let store = g.store();
        let file_key = format!("file:{}", input.path);

        // Stage session-tree writes.
        let agg_key = sess::today_key("analytics:hit_");
        let staged_agg = sess::upsert_daily_agg_staged(store, &agg_key, &file_key).await;
        let staged_receipt = sess::consultation_receipt_staged(&file_key, None);
        let audit_entry = build_audit_entry(
            ctx,
            request_id,
            "file_edit_hook:consultation",
            &file_key,
            true,
            None,
        );
        let audit_key = audit_nanos_key("audit:session:");
        let audit_bytes = serialize_audit(&audit_entry);

        // Atomic commit: agg + receipt + audit (all sessions tree).
        let mut writes: Vec<(&str, &[u8])> = Vec::new();
        if let Ok(ref agg) = staged_agg {
            writes.push((&agg.0, &agg.1));
        }
        if let Ok(ref receipt) = staged_receipt {
            writes.push((&receipt.0, &receipt.1));
        }
        if let Some(ref ab) = audit_bytes {
            writes.push((&audit_key, ab));
        }

        if let Err(e) = store.transact_sessions_raw(&writes).await {
            tracing::warn!(
                request_id = %request_id,
                "file_edit_hook: consultation substep sessions transaction failed: {e}"
            );
        }

        // Cross-tree best-effort: access_count bump on knowledge record.
        if let Ok(Some(mut record)) = store.get(&file_key).await {
            record.access_count += 1;
            record.last_accessed = now_secs();
            let _ = store.put(&file_key, &record).await;
        }
    }

    // Substep 2: reparse (knowledge tree, native handler with audit).
    {
        let g = graph.read().await;
        let store = g.store();
        let reparse_input = protocol::FileReparseInput {
            path: input.path.clone(),
        };
        match super::handlers::handle_file_reparse(
            store,
            ctx,
            request_id,
            &reparse_input,
            &ctx.repo_root,
        )
        .await
        {
            Ok(_) => {}
            Err((_code, msg)) => {
                tracing::warn!("file_edit_hook: reparse substep failed: {msg}");
                // Non-fatal — post-edit hook must not block the agent.
            }
        }
    }

    Response::ok(request_id, serde_json::Value::Null)
}

// ── Session-side native handlers ────────────────────────────────────────────
//
// These handlers write mutation + audit atomically in the sessions tree
// using `transact_sessions_raw`.

async fn dispatch_session_side(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: &Request,
) -> Response {
    let g = graph.read().await;
    let store = g.store();
    let request_id = req.id;
    let command_kind = req.cmd.kind().to_string();
    let target_key = req.cmd.target_key().to_string();

    match &req.cmd {
        Command::SessionLog(input) => {
            let agg_prefix = match input.event {
                protocol::SessionEvent::Miss => "analytics:miss_",
                protocol::SessionEvent::ComplianceMiss => "compliance:miss_",
                protocol::SessionEvent::ComplianceHit => "compliance:allow_after_receipt_",
                protocol::SessionEvent::CodexShellMiss => "compliance:codex_shell_miss_",
                protocol::SessionEvent::Bootstrap => "analytics:bootstrap_",
                protocol::SessionEvent::PromptNudge => "analytics:codex_prompt_nudge_",
                // Edit-gate events share the read aggregates (coarse counts); the
                // edit-vs-read distinction lives in the hash-chained event's
                // decision_reason_code, not the daily aggregate.
                protocol::SessionEvent::EditConsulted => "compliance:allow_after_receipt_",
                protocol::SessionEvent::EditBlocked => "compliance:miss_",
                // Floor-mandate deny shares the miss aggregate; the distinction lives in the
                // event's decision_reason_code (floor_consult_required).
                protocol::SessionEvent::FloorConsultMiss => "compliance:miss_",
            };
            let agg_key = sess::today_key(agg_prefix);

            // Stage agg record + audit for one atomic commit.
            let staged_agg = match sess::upsert_daily_agg_staged(store, &agg_key, &input.key).await
            {
                Ok(s) => s,
                Err(e) => {
                    let entry = build_audit_entry(
                        ctx,
                        request_id,
                        &command_kind,
                        &target_key,
                        false,
                        Some(ErrorCode::StoreError),
                    );
                    write_session_audit(store, &entry).await;
                    return Response::err(request_id, ErrorCode::StoreError, e.to_string());
                }
            };
            let audit_entry =
                build_audit_entry(ctx, request_id, &command_kind, &target_key, true, None);
            // Audit is required — fail closed if serialization fails.
            let audit_bytes = match serialize_audit(&audit_entry) {
                Some(b) => b,
                None => {
                    return Response::err(
                        request_id,
                        ErrorCode::Internal,
                        "audit serialization failed".to_string(),
                    );
                }
            };
            let audit_key = audit_nanos_key("audit:session:");

            // One atomic transaction: agg mutation + audit.
            let writes: Vec<(&str, &[u8])> =
                vec![(&staged_agg.0, &staged_agg.1), (&audit_key, &audit_bytes)];
            if let Err(e) = store.transact_sessions_raw(&writes).await {
                // Transaction failed — accepted audit inside was lost.
                let entry = build_audit_entry(
                    ctx,
                    request_id,
                    &command_kind,
                    &target_key,
                    false,
                    Some(ErrorCode::StoreError),
                );
                write_session_audit(store, &entry).await;
                return Response::err(request_id, ErrorCode::StoreError, e.to_string());
            }

            // Best-effort enforcement event recording (post-transaction).
            match input.event {
                protocol::SessionEvent::ComplianceMiss => {
                    let _ = crate::store::enforcement::record_event_with_session(
                        store,
                        crate::store::enforcement::EnforcementEventType::Deny,
                        crate::store::enforcement::SubjectKind::File,
                        input.key.clone(),
                        "claude".to_string(),
                        None,
                        "gotcha_above_threshold".to_string(),
                        None,
                        input.session_id.clone(),
                    )
                    .await;
                }
                protocol::SessionEvent::ComplianceHit => {
                    let _ = crate::store::enforcement::record_event_with_session(
                        store,
                        crate::store::enforcement::EnforcementEventType::AllowAfterReceipt,
                        crate::store::enforcement::SubjectKind::File,
                        input.key.clone(),
                        "claude".to_string(),
                        None,
                        "receipt_valid".to_string(),
                        None,
                        input.session_id.clone(),
                    )
                    .await;
                }
                // Codex's post-bash hook runs AFTER a shell command finished;
                // by the time we observe "no consultation receipt", the
                // bypass already happened. Record it as `BypassDetected`
                // (label "bypass") rather than `Deny` — nothing was actually
                // denied. Without this arm the event landed only in the
                // daily `compliance:codex_shell_miss_<date>` aggregate and
                // was invisible to `mati history --enforcement`
                // (smoke finding step 128).
                protocol::SessionEvent::CodexShellMiss => {
                    let _ = crate::store::enforcement::record_event(
                        store,
                        crate::store::enforcement::EnforcementEventType::BypassDetected,
                        crate::store::enforcement::SubjectKind::File,
                        input.key.clone(),
                        "codex".to_string(),
                        None,
                        "codex_shell_pre_consult_miss".to_string(),
                        None,
                    )
                    .await;
                }
                // Plane 2: edit-time audit evidence. Same frozen event TYPES as
                // reads (AllowAfterReceipt / Deny) — only the decision_reason_code
                // differs, so the trail attributes the edit gate without touching
                // the frozen hash contract.
                protocol::SessionEvent::EditConsulted => {
                    let _ = crate::store::enforcement::record_event_with_session(
                        store,
                        crate::store::enforcement::EnforcementEventType::AllowAfterReceipt,
                        crate::store::enforcement::SubjectKind::File,
                        input.key.clone(),
                        "claude".to_string(),
                        None,
                        "edit_after_receipt".to_string(),
                        None,
                        input.session_id.clone(),
                    )
                    .await;
                }
                protocol::SessionEvent::EditBlocked => {
                    let _ = crate::store::enforcement::record_event_with_session(
                        store,
                        crate::store::enforcement::EnforcementEventType::Deny,
                        crate::store::enforcement::SubjectKind::File,
                        input.key.clone(),
                        "claude".to_string(),
                        None,
                        "edit_blocked_unconsulted".to_string(),
                        None,
                        input.session_id.clone(),
                    )
                    .await;
                }
                // Enterprise floor mandate deny — distinct reason code so the audit/report can
                // separate an org consultation mandate from a local gotcha.
                protocol::SessionEvent::FloorConsultMiss => {
                    let _ = crate::store::enforcement::record_event_with_session(
                        store,
                        crate::store::enforcement::EnforcementEventType::Deny,
                        crate::store::enforcement::SubjectKind::File,
                        input.key.clone(),
                        "claude".to_string(),
                        None,
                        "floor_consult_required".to_string(),
                        None,
                        input.session_id.clone(),
                    )
                    .await;
                }
                _ => {}
            }

            Response::ok(request_id, serde_json::Value::Null)
        }

        Command::ConsultationHit(input) => {
            // Stage all sessions-tree writes: daily agg + consultation receipt + audit.
            let agg_key = sess::today_key("analytics:hit_");
            let staged_agg = match sess::upsert_daily_agg_staged(store, &agg_key, &input.key).await
            {
                Ok(s) => s,
                Err(e) => {
                    let entry = build_audit_entry(
                        ctx,
                        request_id,
                        &command_kind,
                        &target_key,
                        false,
                        Some(ErrorCode::StoreError),
                    );
                    write_session_audit(store, &entry).await;
                    return Response::err(request_id, ErrorCode::StoreError, e.to_string());
                }
            };
            let staged_receipt =
                match sess::consultation_receipt_staged(&input.key, input.actor.as_deref()) {
                    Ok(s) => s,
                    Err(e) => {
                        let entry = build_audit_entry(
                            ctx,
                            request_id,
                            &command_kind,
                            &target_key,
                            false,
                            Some(ErrorCode::StoreError),
                        );
                        write_session_audit(store, &entry).await;
                        return Response::err(request_id, ErrorCode::StoreError, e.to_string());
                    }
                };
            let audit_entry =
                build_audit_entry(ctx, request_id, &command_kind, &target_key, true, None);
            // Audit is required — fail closed if serialization fails.
            let audit_bytes = match serialize_audit(&audit_entry) {
                Some(b) => b,
                None => {
                    return Response::err(
                        request_id,
                        ErrorCode::Internal,
                        "audit serialization failed".to_string(),
                    );
                }
            };
            let audit_key = audit_nanos_key("audit:session:");

            // One atomic transaction: agg + receipt + audit (all sessions tree).
            let writes: Vec<(&str, &[u8])> = vec![
                (&staged_agg.0, &staged_agg.1),
                (&staged_receipt.0, &staged_receipt.1),
                (&audit_key, &audit_bytes),
            ];
            if let Err(e) = store.transact_sessions_raw(&writes).await {
                // Transaction failed — accepted audit inside was lost.
                let entry = build_audit_entry(
                    ctx,
                    request_id,
                    &command_kind,
                    &target_key,
                    false,
                    Some(ErrorCode::StoreError),
                );
                write_session_audit(store, &entry).await;
                return Response::err(request_id, ErrorCode::StoreError, e.to_string());
            }

            // Cross-tree substep: access_count bump on target record (knowledge tree).
            // Best-effort — does not block the response.
            if let Ok(Some(mut target_record)) = store.get(&input.key).await {
                target_record.access_count += 1;
                target_record.last_accessed = now_secs();
                let _ = store.put(&input.key, &target_record).await;
            }

            // Best-effort enforcement event: ReceiptMinted — session-attributed.
            let _ = crate::store::enforcement::record_event_with_session(
                store,
                crate::store::enforcement::EnforcementEventType::ReceiptMinted,
                crate::store::enforcement::SubjectKind::File,
                input.key.clone(),
                "claude".to_string(),
                None,
                "consultation_requested".to_string(),
                None,
                input.session_id.clone().or_else(|| input.agent_id.clone()),
            )
            .await;

            Response::ok(request_id, serde_json::Value::Null)
        }

        Command::SessionFlush => {
            // Stage session:current record + audit for one atomic commit.
            let staged_flush = match sess::session_flush_staged(store).await {
                Ok(Some(s)) => s,
                Ok(None) => {
                    // No consulted keys — nothing to flush. Still audit.
                    let audit_entry =
                        build_audit_entry(ctx, request_id, &command_kind, &target_key, true, None);
                    write_session_audit(store, &audit_entry).await;
                    return Response::ok(request_id, serde_json::Value::Null);
                }
                Err(e) => {
                    let entry = build_audit_entry(
                        ctx,
                        request_id,
                        &command_kind,
                        &target_key,
                        false,
                        Some(ErrorCode::StoreError),
                    );
                    write_session_audit(store, &entry).await;
                    return Response::err(request_id, ErrorCode::StoreError, e.to_string());
                }
            };
            let audit_entry =
                build_audit_entry(ctx, request_id, &command_kind, &target_key, true, None);
            // Audit is required — fail closed if serialization fails.
            let audit_bytes = match serialize_audit(&audit_entry) {
                Some(b) => b,
                None => {
                    return Response::err(
                        request_id,
                        ErrorCode::Internal,
                        "audit serialization failed".to_string(),
                    );
                }
            };
            let audit_key = audit_nanos_key("audit:session:");

            let writes: Vec<(&str, &[u8])> = vec![
                (&staged_flush.0, &staged_flush.1),
                (&audit_key, &audit_bytes),
            ];
            if let Err(e) = store.transact_sessions_raw(&writes).await {
                let entry = build_audit_entry(
                    ctx,
                    request_id,
                    &command_kind,
                    &target_key,
                    false,
                    Some(ErrorCode::StoreError),
                );
                write_session_audit(store, &entry).await;
                return Response::err(request_id, ErrorCode::StoreError, e.to_string());
            }
            Response::ok(request_id, serde_json::Value::Null)
        }

        Command::SessionHarvest => {
            // SessionHarvest is inherently cross-tree (promotes gotchas in
            // knowledge, archives sessions). Delegate to existing logic which
            // commits its own per-step transactions, then write session-side audit.
            let result = sess::session_harvest_no_staleness(store).await;
            let (accepted, error_code) = match &result {
                Ok(()) => (true, None),
                Err(_) => (false, Some(ErrorCode::StoreError)),
            };
            // Audit is session-side, written after harvest completes.
            // Harvest itself is multi-step with internal commits — cannot be
            // made atomic end-to-end (cross-tree). Audit records the outcome.
            let entry = build_audit_entry(
                ctx,
                request_id,
                &command_kind,
                &target_key,
                accepted,
                error_code,
            );
            write_session_audit(store, &entry).await;

            match result {
                Ok(()) => Response::ok(request_id, serde_json::Value::Null),
                Err(e) => Response::err(request_id, ErrorCode::StoreError, e.to_string()),
            }
        }

        Command::SessionClearConsults => {
            // Silent scan+delete — no audit entry by design. Compaction wipes the
            // agent's memory, so clearing receipts is a maintenance action, not a
            // semantic mutation worth auditing. Fail-open on error (log, not crash).
            match sess::session_clear_consults(store).await {
                Ok(()) => Response::ok(request_id, serde_json::Value::Null),
                Err(e) => {
                    tracing::warn!(error = %e, "session_clear_consults failed; post-compaction re-block window not restored");
                    Response::err(request_id, ErrorCode::StoreError, e.to_string())
                }
            }
        }

        _ => unreachable!("is_session_side guard ensures only session commands reach here"),
    }
}

// ── V1 bridge (internal adapter) ────────────────────────────────────────────
//
// Converts v2 Command variants into v1 SocketRequest format and delegates to
// the existing socket_dispatch. This is an INTERNAL adapter — not reachable
// from the wire. The raw `put` and `delete` arms in socket_dispatch are
// unreachable because no Command variant maps to "put" or "delete".

async fn dispatch_via_v1(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: &Request,
) -> Response {
    use super::server::{socket_dispatch, SocketRequest};

    let (cmd, args) = command_to_v1(&req.cmd);

    // Safety guard: the v1 bridge must NEVER produce "put" or "delete".
    // Primary guard is unreachable!() in command_to_v1; this is defense-in-depth.
    if cmd == "put" || cmd == "delete" {
        return Response::err(
            req.id,
            ErrorCode::Internal,
            format!("v1 bridge produced forbidden mutation command: {cmd}"),
        );
    }

    let v1_req = SocketRequest {
        cmd,
        version: Some(1),
        args,
    };

    let v1_resp = socket_dispatch(graph, &ctx.repo_root, &v1_req).await;

    // Convert v1 SocketResponse to v2 Response.
    if v1_resp.ok {
        Response::ok(req.id, v1_resp.data.unwrap_or(serde_json::Value::Null))
    } else {
        let message = v1_resp.error.unwrap_or_else(|| "unknown error".to_string());
        let code = classify_v1_error(&message);
        Response::err(req.id, code, message)
    }
}

/// Map v1 error message strings to v2 structured error codes.
fn classify_v1_error(message: &str) -> ErrorCode {
    if message.contains("not found") {
        ErrorCode::NotFound
    } else if message.contains("already exists") {
        ErrorCode::Conflict
    } else if message.contains("tombstoned") || message.contains("cannot confirm") {
        ErrorCode::InvalidStateTransition
    } else if message.contains("store") {
        ErrorCode::StoreError
    } else {
        ErrorCode::Internal
    }
}

/// Map a v2 Command variant to v1 (cmd string, args JSON).
///
/// This function NEVER returns "put" or "delete" — those raw mutation
/// commands have no corresponding Command variant.
fn command_to_v1(cmd: &Command) -> (String, serde_json::Value) {
    use serde_json::json;

    match cmd {
        // A. Pure reads
        Command::Ping => ("ping".into(), json!({})),
        Command::Metrics => ("metrics".into(), json!({})),
        Command::Get(i) => ("get".into(), json!({ "key": i.key })),
        Command::HookEvaluate(i) => (
            "hook_evaluate".into(),
            json!({ "file_key": i.file_key, "include_recent": i.include_recent, "actor": i.actor }),
        ),
        Command::ScanPrefix(i) => ("scan_prefix".into(), json!({ "prefix": i.prefix })),
        Command::History(i) => ("history".into(), json!({ "key": i.key, "limit": i.limit })),
        Command::HistorySince(i) => (
            "history_since".into(),
            json!({ "key": i.key, "since_ts": i.since_ts, "limit": i.limit }),
        ),
        Command::SessionCheckConsulted(i) => {
            ("session_check_consulted".into(), json!({ "key": i.key }))
        }
        Command::SessionCheckConsultedRecent(i) => (
            "session_check_consulted_recent".into(),
            json!({ "key": i.key, "ttl_secs": i.ttl_secs }),
        ),
        // MemQuery is now handled natively via `dispatch_mem_query`
        // (γ-C1.5). It must not reach this bridge.
        Command::MemQuery(_) => {
            unreachable!("MemQuery is handled natively, not via v1 bridge")
        }
        Command::ScanEnforcementEvents(i) => (
            "scan_enforcement_events".into(),
            json!({ "since_seq": i.since_seq, "until_seq": i.until_seq }),
        ),

        // B. Reads with side effects — handled natively, not via v1 bridge.
        Command::MemGet(_) | Command::MemBootstrap(_) => {
            unreachable!("side-effecting reads are handled natively, not via v1 bridge")
        }

        // Knowledge-side mutations are handled by native handlers — not via v1 bridge.
        Command::GotchaUpsert(_)
        | Command::GotchaConfirm(_)
        | Command::GotchaTombstone(_)
        | Command::FileEnrich(_)
        | Command::FileReparse(_)
        | Command::FileEditHook(_)
        | Command::DocCapture(_)
        | Command::DecisionUpsert(_)
        | Command::DevNoteUpsert(_)
        | Command::RecordImport(_) => {
            unreachable!("knowledge-side mutations are handled natively, not via v1 bridge")
        }

        // Session-side commands are handled natively — should not reach here.
        Command::SessionLog(_)
        | Command::ConsultationHit(_)
        | Command::SessionFlush
        | Command::SessionHarvest
        | Command::SessionClearConsults => {
            unreachable!("session-side commands are handled natively, not via v1 bridge")
        }

        // Config commands are handled natively — should not reach here.
        Command::ConfigGet(_) | Command::ConfigSet(_) | Command::SandboxAudit(_) => {
            unreachable!("config commands are handled natively, not via v1 bridge")
        }
    }
}

// ── Audit helpers ───────────────────────────────────────────────────────────

fn build_audit_entry(
    ctx: &RequestContext,
    request_id: Uuid,
    command_kind: &str,
    target_key: &str,
    accepted: bool,
    error_code: Option<ErrorCode>,
) -> AuditEntry {
    AuditEntry {
        ts: now_secs(),
        peer_uid: ctx.peer.uid,
        peer_pid: ctx.peer.pid,
        daemon_session: ctx.daemon_session,
        request_id,
        command_kind: command_kind.to_string(),
        target_key: target_key.to_string(),
        accepted,
        error_code,
    }
}

fn serialize_audit(entry: &AuditEntry) -> Option<Vec<u8>> {
    match rmp_serde::to_vec_named(entry) {
        Ok(b) => Some(b),
        Err(e) => {
            tracing::warn!("audit: serialize failed: {e}");
            None
        }
    }
}

fn audit_nanos_key(prefix: &str) -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("{prefix}{nanos}")
}

/// Write audit to sessions tree. Used for session-side mutations.
/// Best-effort — never blocks the response.
async fn write_session_audit(store: &crate::store::Store, entry: &AuditEntry) {
    let Some(bytes) = serialize_audit(entry) else {
        return;
    };
    let key = audit_nanos_key("audit:session:");
    if let Err(e) = store.put_raw(&key, &bytes).await {
        tracing::warn!("audit: session write failed for {key}: {e}");
    }
}

/// Best-effort audit for protocol-level errors (version mismatch) where
/// the correct tree is ambiguous. Writes to sessions tree.
async fn best_effort_audit(
    graph: &Arc<tokio::sync::RwLock<Graph>>,
    ctx: &RequestContext,
    req: &Request,
    accepted: bool,
    error_code: Option<ErrorCode>,
) {
    let entry = build_audit_entry(
        ctx,
        req.id,
        req.cmd.kind(),
        req.cmd.target_key(),
        accepted,
        error_code,
    );
    let g = graph.read().await;
    write_session_audit(g.store(), &entry).await;
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::Graph;
    use crate::mcp::metadata::PeerContext;
    use crate::mcp::protocol::*;
    use crate::store::Store;

    /// Explicit test PeerContext — makes it obvious that auth is bypassed
    /// for handler isolation testing.
    fn test_peer() -> PeerContext {
        PeerContext {
            uid: 501,
            pid: Some(99999),
        }
    }

    /// Stable session UUID shared by test_ctx and make_request so the
    /// session fence passes. Tests that need a mismatch construct their
    /// own Request/RequestContext.
    fn test_session() -> Uuid {
        // Deterministic but non-nil so it exercises the real comparison path.
        Uuid::from_bytes([0xAA; 16])
    }

    fn test_ctx(repo_root: &std::path::Path) -> RequestContext {
        RequestContext {
            peer: test_peer(),
            daemon_session: test_session(),
            repo_root: repo_root.to_path_buf(),
        }
    }

    fn make_request(cmd: Command) -> Request {
        Request {
            v: PROTOCOL_VERSION,
            id: Uuid::new_v4(),
            session: test_session(),
            agent: None,
            cmd,
        }
    }

    #[tokio::test]
    async fn v2_ping_dispatches() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::Ping);
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Ok { data, .. } => {
                assert_eq!(data, serde_json::json!("pong"));
            }
            Response::Err { message, .. } => panic!("expected Ok, got Err: {message}"),
        }
    }

    #[tokio::test]
    async fn v2_version_mismatch_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = Request {
            v: 99,
            id: Uuid::new_v4(),
            session: Uuid::new_v4(),
            agent: None,
            cmd: Command::Ping,
        };
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Err { code, .. } => {
                assert_eq!(code, ErrorCode::VersionMismatch);
            }
            Response::Ok { .. } => panic!("expected VersionMismatch error"),
        }
    }

    #[tokio::test]
    async fn v2_get_returns_null_for_missing_key() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::Get(GetInput {
            key: "file:nonexistent".into(),
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Ok { data, .. } => {
                assert!(data.is_null(), "missing key should return null");
            }
            Response::Err { message, .. } => panic!("expected Ok(null), got Err: {message}"),
        }
    }

    #[tokio::test]
    async fn v2_session_log_writes_audit_to_sessions_tree() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::SessionLog(SessionLogInput {
            event: SessionEvent::Miss,
            key: "file:test".into(),
            session_id: None,
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;
        assert!(matches!(resp, Response::Ok { .. }));

        // Audit should be in sessions tree (audit:session:* prefix).
        let g = graph.read().await;
        let session_audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            !session_audit_keys.is_empty(),
            "session-side mutation should produce audit:session:* entry"
        );
        // And NOT in knowledge tree.
        let knowledge_audit_keys = g.store().scan_keys("audit:knowledge:").await.unwrap();
        assert!(
            knowledge_audit_keys.is_empty(),
            "session-side mutation should not produce audit:knowledge:* entry"
        );
    }

    #[tokio::test]
    async fn v2_session_clear_consults_deletes_receipts_silently() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        // Mint two consult receipts through the real v2 path.
        for key in ["file:a.rs", "file:b.rs"] {
            let req = make_request(Command::ConsultationHit(ConsultationHitInput {
                key: key.into(),
                actor: None,
                session_id: None,
                agent_id: None,
            }));
            assert!(matches!(
                dispatch_v2(&graph, &ctx, req).await,
                Response::Ok { .. }
            ));
        }

        // Two receipts exist; capture the audit count so we can prove the clear adds none.
        let audit_before = {
            let g = graph.read().await;
            assert_eq!(
                g.store()
                    .scan_keys("session:consulted:")
                    .await
                    .unwrap()
                    .len(),
                2,
                "two receipts should exist before clear"
            );
            g.store().scan_keys("audit:session:").await.unwrap().len()
        };

        // Clear through the v2 dispatch path.
        let req = make_request(Command::SessionClearConsults);
        assert!(matches!(
            dispatch_v2(&graph, &ctx, req).await,
            Response::Ok { .. }
        ));

        let g = graph.read().await;
        assert!(
            g.store()
                .scan_keys("session:consulted:")
                .await
                .unwrap()
                .is_empty(),
            "all receipts should be gone after clear"
        );
        assert_eq!(
            g.store().scan_keys("audit:session:").await.unwrap().len(),
            audit_before,
            "clear must be silent — it must not write an audit:session:* entry"
        );
    }

    #[tokio::test]
    async fn v2_pure_read_does_not_write_audit() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::Ping);
        let _ = dispatch_v2(&graph, &ctx, req).await;

        let g = graph.read().await;
        let session_keys = g.store().scan_keys("audit:session:").await.unwrap();
        let knowledge_keys = g.store().scan_keys("audit:knowledge:").await.unwrap();
        assert!(session_keys.is_empty() && knowledge_keys.is_empty());
    }

    #[tokio::test]
    async fn v2_audit_entry_contains_peer_identity() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));

        let peer = PeerContext {
            uid: 12345,
            pid: Some(67890),
        };
        let daemon_session = test_session();
        let ctx = RequestContext {
            peer,
            daemon_session,
            repo_root: dir.path().to_path_buf(),
        };

        let req = make_request(Command::ConsultationHit(ConsultationHitInput {
            key: "file:test".into(),
            actor: None,
            session_id: None,
            agent_id: None,
        }));
        let request_id = req.id;
        let _ = dispatch_v2(&graph, &ctx, req).await;

        // Read back the audit entry from sessions tree.
        let g = graph.read().await;
        let audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert_eq!(audit_keys.len(), 1);

        let txn = g
            .store()
            .sessions_tree()
            .begin_with_mode(surrealkv::Mode::ReadOnly)
            .unwrap();
        let raw = txn.get(audit_keys[0].as_bytes()).unwrap().unwrap();
        let entry: AuditEntry = rmp_serde::from_slice(&raw).unwrap();

        assert_eq!(entry.peer_uid, 12345);
        assert_eq!(entry.peer_pid, Some(67890));
        assert_eq!(entry.daemon_session, daemon_session);
        assert_eq!(entry.request_id, request_id);
        assert_eq!(entry.command_kind, "consultation_hit");
        assert_eq!(entry.target_key, "file:test");
        assert!(entry.accepted);
        assert!(entry.error_code.is_none());
    }

    #[tokio::test]
    async fn v1_bridge_only_handles_pure_reads() {
        // The v1 bridge handles ONLY pure reads that have no native dispatch
        // arm. Mutations, side-effecting reads, AND `Command::MemQuery`
        // (γ-C1.5) are all handled natively. Verify the remaining v1 bridge
        // commands never produce "put" or "delete".
        //
        // Pre-γ-C1.5 this list contained 9 entries; MemQuery was the 9th.
        // It now lives in `dispatch_mem_query` — see the byte-identical
        // parity tests in `handlers::tests::mem_query_*`.
        let pure_read_commands: Vec<Command> = vec![
            Command::Ping,
            Command::Get(GetInput { key: "k".into() }),
            Command::HookEvaluate(HookEvaluateInput {
                file_key: "file:k".into(),
                include_recent: false,
                actor: None,
            }),
            Command::ScanPrefix(ScanPrefixInput { prefix: "p".into() }),
            Command::History(HistoryInput {
                key: "k".into(),
                limit: 10,
            }),
            Command::HistorySince(HistorySinceInput {
                key: "k".into(),
                since_ts: 0,
                limit: 10,
            }),
            Command::SessionCheckConsulted(SessionCheckConsultedInput { key: "k".into() }),
            Command::SessionCheckConsultedRecent(SessionCheckConsultedRecentInput {
                key: "k".into(),
                ttl_secs: 900,
            }),
        ];

        assert_eq!(
            pure_read_commands.len(),
            8,
            "must cover all 8 pure read commands still routed via v1 bridge \
             (was 9 before γ-C1.5 moved MemQuery to a native arm)"
        );
        for cmd in pure_read_commands {
            assert!(!cmd.is_mutation(), "{} must not be a mutation", cmd.kind());
            assert!(
                !is_side_effecting_read(&cmd),
                "{} must not be a side-effecting read",
                cmd.kind()
            );
            let (v1_cmd, _) = command_to_v1(&cmd);
            assert_ne!(
                v1_cmd,
                "put",
                "v1 bridge must never produce 'put': got it for {}",
                cmd.kind()
            );
            assert_ne!(
                v1_cmd,
                "delete",
                "v1 bridge must never produce 'delete': got it for {}",
                cmd.kind()
            );
        }
    }

    #[test]
    fn command_to_v1_hook_evaluate_carries_actor() {
        // Regression: the v2->v1 bridge dropped `actor`, so the daemon ran an
        // actor-blind consult lookup (subagents rode the global receipt).
        // Live-E2E caught it; this locks it in.
        let cmd = Command::HookEvaluate(HookEvaluateInput {
            file_key: "file:x".into(),
            include_recent: false,
            actor: Some("agentZ".into()),
        });
        let (kind, args) = command_to_v1(&cmd);
        assert_eq!(kind, "hook_evaluate");
        assert_eq!(args.get("actor").and_then(|v| v.as_str()), Some("agentZ"));
    }

    #[test]
    fn no_mutation_or_side_effecting_read_reaches_v1_bridge() {
        // All 8 knowledge-side mutations + 4 session-side mutations + 1 compound
        // + 2 side-effecting reads are handled natively. Only pure reads go
        // through the v1 bridge.
        let all_mutations: Vec<Command> = vec![
            Command::GotchaUpsert(GotchaDraftInput {
                key: "gotcha:t".into(),
                rule: "r".into(),
                reason: "r".into(),
                severity: Severity::Normal,
                affected_files: vec![],
                ref_url: None,
                tags: vec![],
                priority: Priority::Normal,
                source: None,
            }),
            Command::GotchaConfirm(GotchaConfirmInput {
                key: "gotcha:t".into(),
            }),
            Command::GotchaTombstone(GotchaTombstoneInput {
                key: "gotcha:t".into(),
            }),
            Command::FileEnrich(FileEnrichInput {
                path: "p".into(),
                purpose: "p".into(),
                entry_points: vec![],
                decision_keys: vec![],
                todos: vec![],
                tags: vec![],
                priority: Priority::Normal,
            }),
            Command::FileReparse(FileReparseInput { path: "p".into() }),
            Command::FileEditHook(FileEditHookInput { path: "p".into() }),
            Command::DocCapture(DocCaptureInput { path: "p".into() }),
            Command::DecisionUpsert(DecisionUpsertInput {
                slug: "s".into(),
                value: "v".into(),
                summary: "s".into(),
                rationale: "r".into(),
                tags: vec![],
                priority: Priority::Normal,
            }),
            Command::DevNoteUpsert(DevNoteUpsertInput {
                key: None,
                text: "t".into(),
                tags: vec![],
                priority: Priority::Normal,
            }),
            Command::SessionLog(SessionLogInput {
                event: SessionEvent::Miss,
                key: "k".into(),
                session_id: None,
            }),
            Command::ConsultationHit(ConsultationHitInput {
                key: "k".into(),
                actor: None,
                session_id: None,
                agent_id: None,
            }),
            Command::SessionFlush,
            Command::SessionHarvest,
            Command::SessionClearConsults,
            // Side-effecting reads.
            Command::MemGet(MemGetInput { key: "k".into() }),
            Command::MemBootstrap(MemBootstrapInput {
                context_files: vec![],
            }),
        ];
        for cmd in &all_mutations {
            assert!(
                is_knowledge_mutation(cmd)
                    || is_session_side(cmd)
                    || is_compound(cmd)
                    || is_side_effecting_read(cmd),
                "{} must be handled natively, not via v1 bridge",
                cmd.kind()
            );
        }
    }

    #[tokio::test]
    async fn knowledge_side_mutation_audit_goes_to_knowledge_tree() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        // GotchaConfirm is knowledge-side. It will fail (no record), but
        // should still produce a knowledge-tree audit entry.
        let req = make_request(Command::GotchaConfirm(GotchaConfirmInput {
            key: "gotcha:nonexistent".into(),
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;
        assert!(matches!(resp, Response::Err { .. }));

        let g = graph.read().await;
        let knowledge_audit = g.store().scan_keys("audit:knowledge:").await.unwrap();
        assert!(
            !knowledge_audit.is_empty(),
            "knowledge-side mutation should produce audit:knowledge:* entry"
        );
        let session_audit = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            session_audit.is_empty(),
            "knowledge-side mutation should NOT produce audit:session:* entry"
        );
    }

    // ── Native MemGet / MemBootstrap tests ──────────────────────────────

    #[tokio::test]
    async fn native_mem_get_empty_key_returns_error_with_rejection_audit() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::MemGet(MemGetInput { key: "".into() }));
        let resp = dispatch_v2(&graph, &ctx, req).await;

        // Must return Response::Err, not Response::Ok with error payload.
        match resp {
            Response::Err { code, .. } => {
                assert_eq!(code, ErrorCode::ValidationFailed);
            }
            Response::Ok { data, .. } => {
                panic!("empty key must return Response::Err, got Ok with: {data}")
            }
        }

        // Rejection audit must exist in sessions tree with accepted=false.
        let g = graph.read().await;
        let audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            !audit_keys.is_empty(),
            "empty-key rejection must produce session audit"
        );
        let txn = g
            .store()
            .sessions_tree()
            .begin_with_mode(surrealkv::Mode::ReadOnly)
            .unwrap();
        let raw = txn.get(audit_keys[0].as_bytes()).unwrap().unwrap();
        let entry: AuditEntry = rmp_serde::from_slice(&raw).unwrap();
        assert!(!entry.accepted, "rejection audit must have accepted=false");
        assert_eq!(entry.error_code, Some(ErrorCode::ValidationFailed));
    }

    #[tokio::test]
    async fn native_mem_get_returns_null_for_missing_key() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::MemGet(MemGetInput {
            key: "file:nonexistent".into(),
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Ok { data, .. } => assert!(data.is_null()),
            Response::Err { message, .. } => panic!("expected Ok(null): {message}"),
        }
    }

    #[tokio::test]
    async fn native_mem_get_writes_session_audit_and_consultation_receipt() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::MemGet(MemGetInput {
            key: "file:src/main.rs".into(),
        }));
        let _ = dispatch_v2(&graph, &ctx, req).await;

        let g = graph.read().await;
        // Audit should be in sessions tree.
        let audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            !audit_keys.is_empty(),
            "MemGet should produce session-side audit"
        );

        // Consultation receipt should exist.
        let consulted = g
            .store()
            .get("session:consulted:file:src/main.rs")
            .await
            .unwrap();
        assert!(
            consulted.is_some(),
            "MemGet should write consultation receipt"
        );

        // No knowledge-side audit.
        let k_audit = g.store().scan_keys("audit:knowledge:").await.unwrap();
        assert!(
            k_audit.is_empty(),
            "MemGet should NOT produce knowledge-side audit"
        );
    }

    #[tokio::test]
    async fn native_mem_bootstrap_writes_session_audit() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::MemBootstrap(MemBootstrapInput {
            context_files: vec![],
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;

        // Should return an injection string.
        match resp {
            Response::Ok { data, .. } => {
                assert!(data.is_string(), "MemBootstrap should return a string");
            }
            Response::Err { message, .. } => panic!("expected Ok: {message}"),
        }

        let g = graph.read().await;
        let audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            !audit_keys.is_empty(),
            "MemBootstrap should produce session-side audit"
        );
    }

    #[tokio::test]
    async fn version_mismatch_cannot_reach_side_effecting_read() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        // Version 99 + MemGet: version check must reject before any side effect.
        let req = Request {
            v: 99,
            id: Uuid::new_v4(),
            session: Uuid::new_v4(),
            agent: None,
            cmd: Command::MemGet(MemGetInput {
                key: "file:test".into(),
            }),
        };
        let resp = dispatch_v2(&graph, &ctx, req).await;
        assert!(matches!(
            resp,
            Response::Err {
                code: ErrorCode::VersionMismatch,
                ..
            }
        ));

        // No consultation receipt should exist.
        let g = graph.read().await;
        let consulted = g.store().get("session:consulted:file:test").await.unwrap();
        assert!(
            consulted.is_none(),
            "version mismatch must not write consultation receipt"
        );
    }

    #[tokio::test]
    async fn session_log_mutation_and_audit_are_both_in_sessions_tree() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::SessionLog(SessionLogInput {
            event: SessionEvent::ComplianceMiss,
            key: "file:src/auth.rs".into(),
            session_id: None,
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;
        assert!(matches!(resp, Response::Ok { .. }));

        let g = graph.read().await;
        // Both the compliance agg and audit should be in sessions tree.
        let compliance_keys = g.store().scan_keys("compliance:miss_").await.unwrap();
        assert!(
            !compliance_keys.is_empty(),
            "SessionLog should write compliance agg"
        );
        let audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            !audit_keys.is_empty(),
            "SessionLog should write session-side audit"
        );
        // Nothing in knowledge tree.
        let k_audit = g.store().scan_keys("audit:knowledge:").await.unwrap();
        assert!(k_audit.is_empty());
    }

    /// Regression: SessionLog with CodexShellMiss must produce a
    /// `BypassDetected` enforcement event in the hash-chained log, not just
    /// a daily aggregate. Smoke finding #128 — pre-fix, the event was
    /// invisible to `mati history --enforcement`.
    #[tokio::test]
    async fn session_log_codex_shell_miss_records_bypass_enforcement_event() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::SessionLog(SessionLogInput {
            event: SessionEvent::CodexShellMiss,
            key: "file:src/cli/repair.rs".into(),
            session_id: None,
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;
        assert!(matches!(resp, Response::Ok { .. }));

        let g = graph.read().await;

        // Daily aggregate (unchanged from pre-fix behavior).
        let agg = g
            .store()
            .scan_keys("compliance:codex_shell_miss_")
            .await
            .unwrap();
        assert!(
            !agg.is_empty(),
            "codex_shell_miss daily agg must be written"
        );

        // NEW: enforcement event in the hash-chained log so `mati history`
        // surfaces it. Pre-fix the scan returned empty.
        let events = crate::store::enforcement::scan_events_since(g.store(), 0)
            .await
            .expect("scan enforcement events");
        assert!(
            !events.is_empty(),
            "CodexShellMiss must record a hash-chained enforcement event \
             (label='bypass') — regression for smoke finding #128"
        );

        let evt = &events[0];
        assert_eq!(
            evt.agent_type, "codex",
            "codex-post-bash event must attribute agent=codex, got: {evt:?}"
        );
        assert_eq!(
            evt.subject_key, "file:src/cli/repair.rs",
            "subject_key must match input.key"
        );
        assert!(
            matches!(
                evt.event_type,
                crate::store::enforcement::EnforcementEventType::BypassDetected
            ),
            "event_type must be BypassDetected, got: {:?}",
            evt.event_type
        );

        // Sanity: the CLI label that `mati history --enforcement` would show
        // for this event is "bypass" (per src/store/enforcement.rs:1000).
        assert_eq!(
            crate::store::enforcement::event_type_label(&evt.event_type),
            "bypass"
        );
    }

    #[tokio::test]
    async fn v2_session_mismatch_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        // Construct a request with a different session UUID.
        let req = Request {
            v: PROTOCOL_VERSION,
            id: Uuid::new_v4(),
            session: Uuid::new_v4(), // does NOT match test_session()
            agent: None,
            cmd: Command::Ping,
        };
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Err { code, message, .. } => {
                assert_eq!(code, ErrorCode::SessionMismatch);
                assert!(
                    message.contains("re-read daemon metadata"),
                    "error should guide the client to retry: {message}"
                );
            }
            Response::Ok { .. } => panic!("expected SessionMismatch error"),
        }
    }

    #[tokio::test]
    async fn v2_matching_session_passes_fence() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        // make_request uses test_session() which matches ctx.daemon_session.
        let req = make_request(Command::Ping);
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Ok { data, .. } => {
                assert_eq!(data, serde_json::json!("pong"));
            }
            Response::Err { message, .. } => panic!("expected Ok, got Err: {message}"),
        }
    }

    #[tokio::test]
    async fn file_edit_hook_consultation_substep_writes_receipt_and_audit_atomically() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        // Create a dummy file so reparse doesn't need real filesystem.
        let test_path = dir.path().join("test.rs");
        std::fs::write(&test_path, "fn main() {}").unwrap();

        let req = make_request(Command::FileEditHook(FileEditHookInput {
            path: "test.rs".into(),
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;
        assert!(matches!(resp, Response::Ok { .. }));

        let g = graph.read().await;

        // Session-side audit must exist (from consultation substep).
        let audit_keys = g.store().scan_keys("audit:session:").await.unwrap();
        assert!(
            !audit_keys.is_empty(),
            "FileEditHook consultation substep must produce session-side audit"
        );

        // Consultation receipt must exist (staged + committed atomically with audit).
        let consulted = g
            .store()
            .get("session:consulted:file:test.rs")
            .await
            .unwrap();
        assert!(
            consulted.is_some(),
            "FileEditHook consultation substep must write consultation receipt"
        );

        // Daily hit agg must exist (staged + committed atomically with audit).
        let hit_keys = g.store().scan_keys("analytics:hit_").await.unwrap();
        assert!(
            !hit_keys.is_empty(),
            "FileEditHook consultation substep must write daily hit agg"
        );

        // Verify the audit entry is for the consultation substep.
        let txn = g
            .store()
            .sessions_tree()
            .begin_with_mode(surrealkv::Mode::ReadOnly)
            .unwrap();
        let raw = txn.get(audit_keys[0].as_bytes()).unwrap().unwrap();
        let entry: AuditEntry = rmp_serde::from_slice(&raw).unwrap();
        assert_eq!(entry.command_kind, "file_edit_hook:consultation");
        assert!(entry.accepted);
    }

    /// ConfigGet routes through the dedicated native dispatcher and returns
    /// the default value (`advisory`) when nothing has been written yet.
    #[tokio::test]
    async fn config_get_returns_default_enforcement_mode() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::ConfigGet(ConfigGetInput {
            key: "audit.write_durability".into(),
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;

        match resp {
            Response::Ok { data, .. } => assert_eq!(data, serde_json::json!("best_effort")),
            Response::Err { message, .. } => panic!("expected Ok, got Err: {message}"),
        }
    }

    /// ConfigSet writes the value via the daemon path; the next ConfigGet
    /// reflects the new value end-to-end through dispatch_v2.
    #[tokio::test]
    async fn config_set_then_get_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let set_req = make_request(Command::ConfigSet(ConfigSetInput {
            key: "audit.write_durability".into(),
            value: "strict".into(),
        }));
        let set_resp = dispatch_v2(&graph, &ctx, set_req).await;
        match set_resp {
            Response::Ok { data, .. } => {
                assert_eq!(data, serde_json::json!({ "old": "best_effort" }));
            }
            Response::Err { message, .. } => panic!("expected Ok, got Err: {message}"),
        }

        let get_req = make_request(Command::ConfigGet(ConfigGetInput {
            key: "audit.write_durability".into(),
        }));
        let get_resp = dispatch_v2(&graph, &ctx, get_req).await;
        match get_resp {
            Response::Ok { data, .. } => assert_eq!(data, serde_json::json!("strict")),
            Response::Err { message, .. } => panic!("expected Ok, got Err: {message}"),
        }
    }

    /// Invalid enforcement mode value is rejected with ValidationFailed —
    /// the daemon never persists garbage values.
    #[tokio::test]
    async fn config_set_rejects_invalid_enforcement_mode() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let req = make_request(Command::ConfigSet(ConfigSetInput {
            key: "audit.write_durability".into(),
            value: "paranoid".into(),
        }));
        let resp = dispatch_v2(&graph, &ctx, req).await;
        match resp {
            Response::Err { code, .. } => assert_eq!(code, ErrorCode::ValidationFailed),
            Response::Ok { .. } => panic!("expected Err, got Ok"),
        }
    }

    /// Unknown config key surfaces ValidationFailed on both get and set.
    #[tokio::test]
    async fn config_unknown_key_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph = Arc::new(tokio::sync::RwLock::new(graph));
        let ctx = test_ctx(dir.path());

        let get_req = make_request(Command::ConfigGet(ConfigGetInput {
            key: "nope.nope".into(),
        }));
        match dispatch_v2(&graph, &ctx, get_req).await {
            Response::Err { code, .. } => assert_eq!(code, ErrorCode::ValidationFailed),
            Response::Ok { .. } => panic!("expected ValidationFailed for unknown get key"),
        }

        let set_req = make_request(Command::ConfigSet(ConfigSetInput {
            key: "nope.nope".into(),
            value: "x".into(),
        }));
        match dispatch_v2(&graph, &ctx, set_req).await {
            Response::Err { code, .. } => assert_eq!(code, ErrorCode::ValidationFailed),
            Response::Ok { .. } => panic!("expected ValidationFailed for unknown set key"),
        }
    }
}