ai-memory 0.7.0

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! Substrate-level agent-action rules engine (issue #691).
//!
//! The K9 governance pipeline in [`crate::governance`] gates only the
//! six substrate-INTERNAL ops ([`crate::governance::Op`]). It has no
//! insertion point for agent-EXTERNAL actions like Bash command
//! execution, filesystem writes outside the substrate, network
//! requests, or process spawns. Issue #691 RCA: every operator hard
//! rule that has ever been violated in the v0.7.0 campaign (5-6
//! occurrences of `/tmp` writes, low-disk `cargo` runs) lived OUTSIDE
//! the K9 surface.
//!
//! This module adds a second engine — [`check_agent_action`] — that
//! evaluates a declarative table of rules at every external-action
//! entry point. Rules are typed data in the `governance_rules` table
//! (migration `0024_v07_governance_rules.sql`); the engine here is
//! the read path that compiles a rule's `matcher` JSON into an
//! [`AgentAction`] match decision and returns a [`Decision`].
//!
//! # Enforcement language (honest)
//!
//! - **Substrate-INTERNAL ops** ([`memory_store`], [`memory_link`],
//!   etc.): the K9 pipeline is **substrate-authoritative** —
//!   mechanically applied at the write path. The agent cannot
//!   bypass.
//! - **Agent-EXTERNAL ops** (Bash / FilesystemWrite outside the
//!   substrate / NetworkRequest / ProcessSpawn): this engine is
//!   **substrate-rule-bound, harness-mediated**. The rule lives in
//!   the substrate's `governance_rules` table; the harness (Claude
//!   Code PreToolUse hook of type `mcp_tool`) consults the substrate
//!   via [`crate::mcp::tools::check_agent_action`] and honors the
//!   decision. That is mechanical at the **harness hook boundary**
//!   (operator-configured), not at the **agent attention** boundary
//!   (probabilistic).
//!
//! # Wired-state (v0.7.0 7th-form closeout — issue #760)
//!
//! This module is now **wired at the harness boundary** across four
//! daemon-side wire-points enumerated in issue #691:
//!
//! | Wire-point                          | AgentAction variant   | File:line                                   |
//! |-------------------------------------|-----------------------|---------------------------------------------|
//! | Skill manifest emission             | `FilesystemWrite`     | `src/mcp/tools/skill_export.rs:162,209`     |
//! | Federation peer POST                | `NetworkRequest`      | `src/federation/sync.rs:66`                 |
//! | Hooks subprocess spawn              | `ProcessSpawn`        | `src/hooks/executor.rs:399,783`             |
//! | LLM (Ollama / OpenAI) HTTP          | `NetworkRequest`      | `src/llm.rs:421`                            |
//!
//! Every wire-point calls [`crate::governance::wire_check::check`]
//! BEFORE the external action proceeds. The daemon `bootstrap_serve`
//! installs ONE [`crate::governance::wire_check::GOVERNANCE_PRE_ACTION`]
//! closure that consults [`check_agent_action_no_audit`] against the
//! operator-signed `governance_rules` table. CLI one-shot binaries
//! never install the hook so direct operator ops stay unimpeded.
//!
//! The substrate-INTERNAL `Custom("memory_write")` gate runs through
//! the parallel [`crate::storage::GOVERNANCE_PRE_WRITE`] hook.
//!
//! Seed rules R001-R004 land at `enabled = 0` per migration
//! `0024_v07_governance_rules.sql`. The operator activates them via
//! `ai-memory governance install-defaults` (or per-rule via
//! `ai-memory rules enable <id> --sign` after running `rules keygen`).
//! Until activation the wire is mechanically inert — the audit-honest
//! property is that the wire EXISTS and is consulted on every external
//! action, not that any specific rule fires by default.

use std::path::PathBuf;
use std::sync::Arc;

use anyhow::{Context, Result};
use rusqlite::{Connection, OptionalExtension};
use serde::{Deserialize, Serialize};

use crate::governance::rule_cache::RuleCache;
use crate::governance::rules_store::Rule;
use crate::signed_events::{append_signed_event, payload_hash};

/// Canonical bash-matcher field (#767 SEC-12) — shared with the CLI
/// `rules add` validation path (#1558 batch 6).
pub(crate) const MATCHER_COMMAND_SUBSTRING: &str = "command_substring";
/// Legacy matcher-field alias accepted through the rename cycle.
pub(crate) const MATCHER_COMMAND_REGEX: &str = "command_regex";

/// Wire-name for the `governance.check` event_type recorded in the
/// `signed_events` audit chain every time [`check_agent_action`]
/// runs. Audit-side dashboards filter on this string.
pub const GOVERNANCE_CHECK_EVENT_TYPE: &str = "governance.check";

/// #1558 batch 5 wave 3 — canonical [`AgentAction::kind`] wire tags.
/// One spelling per action kind; the `kind()` match arms below, the
/// CLI `rules test` payload parser, and the MCP
/// `memory_check_agent_action` argument parser all reference these
/// consts so the `governance_rules.kind` lookup vocabulary cannot
/// drift across surfaces.
pub mod action_kinds {
    /// [`AgentAction::Bash`] wire tag.
    pub const BASH: &str = "bash";
    /// [`AgentAction::FilesystemWrite`] wire tag.
    pub const FILESYSTEM_WRITE: &str = "filesystem_write";
    /// [`AgentAction::NetworkRequest`] wire tag.
    pub const NETWORK_REQUEST: &str = "network_request";
    /// [`AgentAction::ProcessSpawn`] wire tag.
    pub const PROCESS_SPAWN: &str = "process_spawn";
    /// [`AgentAction::Custom`] wire tag.
    pub const CUSTOM: &str = "custom";
}

// ---------------------------------------------------------------------------
// AgentAction — the agent-external action vocabulary
// ---------------------------------------------------------------------------

/// One agent-external action proposed for evaluation. The harness's
/// PreToolUse hook constructs one of these from the tool input and
/// hands it to [`check_agent_action`] via MCP; the CLI's `rules
/// check` verb does the same locally.
///
/// The variant names are the canonical `kind` strings in the
/// `governance_rules.kind` column (lower_snake). Adding a new variant
/// is wire-compatible — existing rules with unknown kinds are
/// ignored by the engine, not failed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AgentAction {
    /// A shell command the harness is about to execute. `cwd` is the
    /// resolved working directory when the harness knows it
    /// (Bash-tool calls always carry one; one-shot dispatches may
    /// not).
    Bash {
        command: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cwd: Option<PathBuf>,
    },
    /// A filesystem write outside the substrate (a file create /
    /// edit / append). `byte_estimate` lets a future quota rule
    /// refuse a write that would tip a disk into ENOSPC; today it
    /// is informational.
    FilesystemWrite {
        path: PathBuf,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        byte_estimate: Option<u64>,
    },
    /// An outbound network request the harness is about to issue.
    /// `scheme` is the wire scheme (`https`, `http`, etc.) for
    /// future scheme-restrictive rules; the K9 pipeline never
    /// inspects this path.
    NetworkRequest {
        host: String,
        #[serde(default)]
        scheme: String,
    },
    /// A child-process spawn — `cargo build`, `npm install`,
    /// `colima delete`, etc. `binary` is the resolved program name
    /// (not the full path); `args` are the literal argv tail.
    ProcessSpawn {
        binary: String,
        #[serde(default)]
        args: Vec<String>,
    },
    /// Extension point for actions outside the four canonical kinds.
    /// `payload` is whatever shape the caller proposes; matcher
    /// rules of kind `custom` consult its `custom_kind` field plus
    /// their own JSON `matches` map. The inner field is named
    /// `custom_kind` rather than `kind` to avoid colliding with the
    /// outer `#[serde(tag = "kind")]` discriminator.
    Custom {
        custom_kind: String,
        payload: serde_json::Value,
    },
}

impl AgentAction {
    /// Canonical lower-snake tag used to look up rules in the
    /// `governance_rules.kind` column. Stable wire format.
    #[must_use]
    pub fn kind(&self) -> &str {
        match self {
            AgentAction::Bash { .. } => action_kinds::BASH,
            AgentAction::FilesystemWrite { .. } => action_kinds::FILESYSTEM_WRITE,
            AgentAction::NetworkRequest { .. } => action_kinds::NETWORK_REQUEST,
            AgentAction::ProcessSpawn { .. } => action_kinds::PROCESS_SPAWN,
            AgentAction::Custom { .. } => action_kinds::CUSTOM,
        }
    }

    /// JSON shape suitable for `signed_events.payload_hash` input.
    /// Stable across versions: the field order is `kind` first then
    /// remaining variant fields. Used both for audit and for the
    /// canonical representation a future signature would commit to.
    ///
    /// # Errors
    ///
    /// Returns an error only if `serde_json` cannot serialize the
    /// variant — in practice never happens with the shapes here.
    pub fn canonical_bytes(&self) -> Result<Vec<u8>> {
        let val = serde_json::to_value(self)
            .context("agent_action canonical_bytes: serialize AgentAction")?;
        serde_json::to_vec(&val).context("agent_action canonical_bytes: re-serialize Value to vec")
    }
}

// ---------------------------------------------------------------------------
// Decision — the engine output
// ---------------------------------------------------------------------------

/// Outcome of [`check_agent_action`]. Mirrors the [`crate::governance::Decision`]
/// vocabulary but narrower: this engine has no `Modify` (rules can't
/// rewrite an external action) and no `Ask` (the harness path is
/// synchronous — operator-approval queueing is the K10 surface, not
/// this one).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "decision", rename_all = "snake_case")]
pub enum Decision {
    /// Action proceeds. No matching `refuse` rule. There may be
    /// `warn` / `log` rules that emitted to the audit chain but the
    /// caller is cleared to proceed.
    Allow,
    /// Action refused. `rule_id` names the rule whose matcher fired;
    /// `reason` is its operator-authored explanation.
    Refuse { rule_id: String, reason: String },
    /// Action proceeds with a logged warning. `rule_id` + `reason`
    /// are present for the audit row but the harness should not
    /// block.
    Warn { rule_id: String, reason: String },
}

impl Decision {
    /// `true` if the decision blocks the action.
    #[must_use]
    pub fn is_refusal(&self) -> bool {
        matches!(self, Decision::Refuse { .. })
    }

    /// `true` if the decision permits the action (Allow or Warn).
    #[must_use]
    pub fn is_allowed(&self) -> bool {
        !self.is_refusal()
    }
}

// ---------------------------------------------------------------------------
// Severity — the column type in `governance_rules`
// ---------------------------------------------------------------------------

/// Per-rule severity. Drives whether a matched rule blocks the
/// action (`Refuse`), emits a logged warning (`Warn`), or is silent
/// (`Log`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    Refuse,
    Warn,
    Log,
}

impl Severity {
    /// Wire string for the `governance_rules.severity` column.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Refuse => "refuse",
            Severity::Warn => "warn",
            Severity::Log => "log",
        }
    }

    /// Parse from the wire string. Returns `None` on unknown values;
    /// the caller is expected to surface a clear loader error.
    #[must_use]
    pub fn from_str(s: &str) -> Option<Severity> {
        match s {
            "refuse" => Some(Severity::Refuse),
            "warn" => Some(Severity::Warn),
            "log" => Some(Severity::Log),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Matchers — per-kind JSON evaluators
// ---------------------------------------------------------------------------

/// Evaluate whether `rule`'s `matcher` JSON applies to `action`.
///
/// Per-kind matcher shapes:
///
/// | AgentAction          | Matcher JSON shape                                                      |
/// |----------------------|-------------------------------------------------------------------------|
/// | `Bash`               | `{"command_substring":"..."}` — literal substring match on `command`    |
/// | `FilesystemWrite`    | `{"glob":"/tmp/**"}` — tiny glob over `path`                            |
/// | `NetworkRequest`     | `{"host":"*.evil.example.com"}` — glob host match (plain host = exact)   |
/// | `ProcessSpawn`       | `{"binary":"cargo","disk_free_min_gib":20,"args_contain":"..."}` — binary + disk + optional argv substring |
/// | `Custom`             | `{"kind":"<kind>","namespace_glob":"secure/**","tier":"long","title_contains":"..."}` — kind + optional payload predicates (ANDed) |
///
/// # Bash field naming (SEC-12 / COR-10, Cluster D, issue #767)
///
/// The substring-match field is `command_substring`. The legacy name
/// `command_regex` is accepted as a SILENT alias for one ship cycle
/// so existing operator configs continue to load — the engine never
/// treated the value as a regex (always a literal substring). New
/// configs MUST use `command_substring`. The CLI loader emits a
/// deprecation warning when it sees the legacy name. See
/// [`validate_command_substring`] for the regex-metacharacter
/// rejection that the CLI add path enforces.
///
/// Returns `false` on a kind/matcher mismatch (e.g. a `bash` rule
/// against a `FilesystemWrite` action) — the caller pre-filters on
/// `kind` so this should not happen, but the engine is defensive.
#[must_use]
pub fn matcher_applies(rule: &Rule, action: &AgentAction) -> bool {
    if rule.kind != action.kind() {
        return false;
    }
    let Ok(matcher) = serde_json::from_str::<serde_json::Value>(&rule.matcher) else {
        // Malformed matcher JSON — treat as non-matching rather than
        // panic. The operator-facing `ai-memory rules add` validates
        // the JSON at write time so this is a defense-in-depth
        // fallback.
        return false;
    };

    match action {
        AgentAction::Bash { command, .. } => match_bash(&matcher, command),
        AgentAction::FilesystemWrite { path, .. } => match_filesystem_write(&matcher, path),
        AgentAction::NetworkRequest { host, .. } => match_network_request(&matcher, host),
        AgentAction::ProcessSpawn { binary, args } => match_process_spawn(&matcher, binary, args),
        AgentAction::Custom {
            custom_kind,
            payload,
        } => match_custom(&matcher, custom_kind, payload),
    }
}

/// SEC-12 (Cluster D, issue #767) — operator-facing validator for
/// the `command_substring` matcher value. Rejects any regex
/// metacharacter the field name (`command_regex` pre-rename) used to
/// suggest the engine supported — `. * + ? [ ] ( ) ^ $ |`. The
/// engine has always treated the value as a literal substring; the
/// validator catches an operator who pastes a real regex expecting
/// it to work and would otherwise silently produce a never-matching
/// rule (e.g. `rm\s+-rf` is never a substring of `rm -rf /`).
///
/// Backslash is permitted (Windows paths, escape sequences in
/// operator-authored shell snippets) but a backslash followed by a
/// regex metacharacter is still flagged — the operator likely meant
/// "literal `.`" expecting the engine to honour the escape, which it
/// does not.
///
/// # Errors
///
/// Returns `Err(String)` describing the offending character (and
/// position) for the operator-facing CLI message. The caller surfaces
/// the error verbatim to stderr + exits non-zero.
pub fn validate_command_substring(value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err("command_substring must not be empty".to_string());
    }
    // Regex metacharacters the legacy `command_regex` name suggested
    // the engine honoured. The engine has always done substring; the
    // validator catches the operator misuse.
    const FORBIDDEN: &[char] = &['.', '*', '+', '?', '[', ']', '(', ')', '^', '$', '|', '\\'];
    if let Some(pos) = value.find(|c: char| FORBIDDEN.contains(&c)) {
        let offending = value.as_bytes()[pos] as char;
        return Err(format!(
            "command_substring rejects regex metacharacter {offending:?} at byte {pos}: \
             the matcher is a LITERAL substring match (despite the legacy `command_regex` \
             field name). Quote the literal text you want to match, e.g. `\"rm -rf\"` \
             rather than `\"rm\\s+-rf\"`. If you need true regex semantics, file an issue \
             — the engine will gain a typed `command_regex` discriminator in a future ship."
        ));
    }
    Ok(())
}

fn match_bash(matcher: &serde_json::Value, command: &str) -> bool {
    // SEC-12 (Cluster D, issue #767) — accept the new canonical
    // `command_substring` AND the legacy alias `command_regex` so
    // existing operator configs continue to load through the ship
    // cycle that renames the field. New configs MUST use
    // `command_substring`; the CLI add path warns when it sees the
    // legacy name.
    let needle = matcher
        .get(MATCHER_COMMAND_SUBSTRING)
        .or_else(|| matcher.get(MATCHER_COMMAND_REGEX))
        .and_then(|v| v.as_str());
    let Some(needle) = needle else {
        return false;
    };
    // The matcher value is a LITERAL substring (never a regex —
    // despite the legacy field name). The CLI add path validates
    // operator-supplied values with [`validate_command_substring`].
    command.contains(needle)
}

fn match_filesystem_write(matcher: &serde_json::Value, path: &std::path::Path) -> bool {
    let Some(glob) = matcher.get("glob").and_then(|v| v.as_str()) else {
        return false;
    };
    let path_str = path.to_string_lossy();
    crate::governance::glob_matches(glob, &path_str)
}

fn match_network_request(matcher: &serde_json::Value, host: &str) -> bool {
    let Some(target_host) = matcher.get("host").and_then(|v| v.as_str()) else {
        return false;
    };
    // Glob match on host (same engine as the filesystem `glob` matcher).
    // A plain host with no `*` matches exactly — so pre-existing exact-host
    // rules are unchanged — while `*.example.com`-style patterns now fire
    // as the operator intended. Pre-fix this was a literal `==`, so a glob
    // host pattern silently never matched: a DENY rule written as
    // `{"host":"*.evil.example.com"}` would fail-OPEN, letting every
    // subdomain through the gate. Hostnames contain no `/`, so the
    // single-`*` (segment-bounded) and `**` (cross-segment) forms behave
    // identically here.
    crate::governance::glob_matches(target_host, host)
}

fn match_process_spawn(matcher: &serde_json::Value, binary: &str, args: &[String]) -> bool {
    let Some(target_binary) = matcher.get("binary").and_then(|v| v.as_str()) else {
        return false;
    };
    if target_binary != binary {
        return false;
    }
    // SEC-13 (Cluster D, issue #767) — optional `args_contain`
    // matcher. When present, the rule fires ONLY if the joined argv
    // tail (space-separated, lossy String) contains the substring.
    // Same literal-substring contract as the bash matcher — full
    // regex is intentionally out of scope.
    if let Some(needle) = matcher.get("args_contain").and_then(|v| v.as_str()) {
        let joined = args.join(" ");
        if !joined.contains(needle) {
            return false;
        }
    }
    // Optional `disk_free_min_gib`: refuse spawn when free disk on
    // the working volume drops below the threshold. The engine
    // probes `/` (root volume) via `statvfs`-equivalent and converts
    // to GiB. If the probe fails, we treat the rule as NOT matching
    // (avoid spurious refusals on systems where the probe is
    // unsupported); the caller can layer a stricter "refuse on
    // probe failure" policy later.
    if let Some(threshold) = matcher
        .get("disk_free_min_gib")
        .and_then(serde_json::Value::as_u64)
    {
        let free_gib = match disk_free_gib_at_root() {
            Some(g) => g,
            None => return false,
        };
        return free_gib < threshold;
    }
    true
}

fn match_custom(matcher: &serde_json::Value, kind: &str, payload: &serde_json::Value) -> bool {
    let Some(target_kind) = matcher.get("kind").and_then(|v| v.as_str()) else {
        return false;
    };
    if target_kind != kind {
        return false;
    }
    // #1457 (SEC, MED-HIGH) — optional payload predicates. Before this
    // change a `custom` rule could only key off the opaque `kind`
    // string, so an operator could not write a governance rule that
    // refuses, e.g., long-tier writes into a protected namespace even
    // though the substrate pre-write hook already publishes
    // `namespace`/`tier`/`memory_kind`/`title` in the Custom payload
    // (see `bootstrap_serve`'s GOVERNANCE_PRE_WRITE closure). Each
    // predicate below is ANDed with the others; an absent predicate is
    // simply not constraining. All predicates must match for the rule
    // to fire. A predicate that references a field missing from the
    // payload makes the rule NOT match (fail-safe: the rule can only
    // *refuse* a write it can positively identify).

    // `namespace_glob`: glob over the payload `namespace` string,
    // reusing the same engine as the FilesystemWrite `glob` matcher.
    if let Some(ns_glob) = matcher.get("namespace_glob").and_then(|v| v.as_str()) {
        let Some(ns) = payload.get("namespace").and_then(|v| v.as_str()) else {
            return false;
        };
        if !crate::governance::glob_matches(ns_glob, ns) {
            return false;
        }
    }

    // `tier`: exact match on the payload `tier` string (e.g. "long").
    if let Some(target_tier) = matcher.get("tier").and_then(|v| v.as_str()) {
        let Some(tier) = payload.get("tier").and_then(|v| v.as_str()) else {
            return false;
        };
        if target_tier != tier {
            return false;
        }
    }

    // `title_contains`: literal substring over the payload `title`,
    // same contract as the bash/process-spawn substring matchers (no
    // regex by design).
    if let Some(needle) = matcher.get("title_contains").and_then(|v| v.as_str()) {
        let Some(title) = payload.get("title").and_then(|v| v.as_str()) else {
            return false;
        };
        if !title.contains(needle) {
            return false;
        }
    }

    true
}

/// Probe free disk space at `/` in GiB. Returns `None` when the
/// platform does not expose the `statvfs` API or the call fails.
/// Used by [`match_process_spawn`] to evaluate the
/// `disk_free_min_gib` threshold on R004 (cargo refused on low-disk
/// system).
#[must_use]
fn disk_free_gib_at_root() -> Option<u64> {
    disk_free_gib_at_path(std::path::Path::new("/"))
}

/// Probe free disk space at `path` in GiB. Pulled out as a function
/// so tests can exercise the conversion logic against a known path
/// without depending on the root filesystem layout.
#[cfg(unix)]
fn disk_free_gib_at_path(path: &std::path::Path) -> Option<u64> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    let c_path = CString::new(path.as_os_str().as_bytes()).ok()?;
    // SAFETY: `statvfs` reads through the C-string pointer and
    // writes to the libc::statvfs struct passed by mutable reference.
    // The struct is zeroed first; the pointer outlives the call.
    let mut buf: libc::statvfs = unsafe { std::mem::zeroed() };
    // SAFETY: `c_path.as_ptr()` is a valid NUL-terminated C string
    // for the duration of the call; `&mut buf` is a valid mutable
    // reference. The call writes to `buf` and returns 0 on success.
    let rc = unsafe { libc::statvfs(c_path.as_ptr(), &raw mut buf) };
    if rc != 0 {
        return None;
    }
    // Free blocks for unprivileged users × fragment size = free bytes.
    let free_bytes = u64::from(buf.f_bavail).saturating_mul(u64::from(buf.f_frsize));
    Some(free_bytes / (1024 * 1024 * 1024))
}

/// Windows / wasm / other-target stub. The seed rule R004 is a
/// no-op on these targets (the `cargo` refusal is a unix-host
/// concern; CI on Windows has its own disk discipline).
#[cfg(not(unix))]
fn disk_free_gib_at_path(_path: &std::path::Path) -> Option<u64> {
    None
}

// ---------------------------------------------------------------------------
// RuleEngine — unified rule-load + decision-routing core (issue #850)
// ---------------------------------------------------------------------------

/// Refactor Wave-2 Tier-A2 (issue #850) — unified rule engine consumed
/// by every governance entry point.
///
/// Before this refactor each of the three callsites that consult
/// `governance_rules` (the substrate `GOVERNANCE_PRE_WRITE` hook, the
/// `wire_check` agent-external hook, and the audited `check_agent_action`
/// MCP / CLI surface) duplicated the rule-load + first-refusal-wins
/// loop in its own function (`check_agent_action`,
/// `check_agent_action_no_audit`, `check_agent_action_deferred`).
/// Adding a new severity variant or matcher field meant touching three
/// near-identical loops. The `RuleEngine` collapses the load + routing
/// logic into one place; the three legacy free functions remain as
/// thin wrappers so the public API is wire-stable.
///
/// `rules` holds the snapshot of enabled rules of the *target kind*
/// (the engine is constructed per-action, not per-table — kind-scoped
/// loading matches the existing `list_enabled_by_kind` shape and
/// preserves the signature-verification side effects in
/// [`crate::governance::rules_store::list_enabled_by_kind`]).
///
/// The combinator is **first-refusal-wins** with `warn` falling
/// through and `log` being silent — identical semantics to the
/// pre-refactor inline loops.
pub struct RuleEngine {
    /// `Arc<Vec<Rule>>` so the per-instance [`RuleCache`] (#991) can
    /// share a snapshot across many `load_for_action_cached` calls
    /// without cloning the row data. Cache miss / un-cached path
    /// wraps a fresh `Vec` in `Arc::new`; cache hits clone the
    /// `Arc` (refcount bump, no row data copy).
    rules: Arc<Vec<Rule>>,
}

impl RuleEngine {
    /// Construct an engine scoped to a single `AgentAction`'s kind
    /// without consulting any cache. Equivalent to
    /// `load_for_action_cached(conn, None, action)`.
    ///
    /// Reads the enabled rule rows of matching `kind` from
    /// `governance_rules` via
    /// [`crate::governance::rules_store::list_enabled_by_kind`]; the
    /// signature-verification gate (L1-6 bypass-impossibility
    /// invariant) runs inside that helper and is preserved verbatim.
    ///
    /// # Errors
    ///
    /// Propagates any SQLite error from `list_enabled_by_kind`.
    pub fn load_for_action(conn: &Connection, action: &AgentAction) -> Result<Self> {
        Self::load_for_action_cached(conn, None, action)
    }

    /// Cached variant of [`Self::load_for_action`] (#991).
    ///
    /// When `cache` is `Some`, consults the per-instance [`RuleCache`]
    /// — cache hit returns the cached `Arc<Vec<Rule>>` without
    /// re-running the SQL + Ed25519-verify path; cache miss loads via
    /// [`crate::governance::rules_store::list_enabled_by_kind`] and
    /// inserts. When `cache` is `None`, behaves exactly like
    /// [`Self::load_for_action`] (no cache consultation, fresh load).
    ///
    /// # Errors
    ///
    /// Propagates any SQLite error from `list_enabled_by_kind`.
    pub fn load_for_action_cached(
        conn: &Connection,
        cache: Option<&RuleCache>,
        action: &AgentAction,
    ) -> Result<Self> {
        let kind = action.kind();
        let rules = if let Some(c) = cache {
            c.get_or_load(conn, kind).with_context(|| {
                format!("RuleEngine::load_for_action_cached: get_or_load({kind})")
            })?
        } else {
            let v = crate::governance::rules_store::list_enabled_by_kind(conn, kind).with_context(
                || format!("RuleEngine::load_for_action: list_enabled_by_kind({kind})"),
            )?;
            Arc::new(v)
        };
        Ok(Self { rules })
    }

    /// Construct an engine directly from a pre-loaded rules slice.
    /// Useful for tests that want to skip the SQLite round-trip or
    /// for future callsites that already hold a cached rule list.
    #[must_use]
    pub fn from_rules(rules: Vec<Rule>) -> Self {
        Self {
            rules: Arc::new(rules),
        }
    }

    /// Evaluate `action` against the loaded rules. Returns the
    /// first-refusal-wins [`Decision`].
    ///
    /// `agent_id` is unused by the matcher today but threaded through
    /// so future agent-scoped matchers (operator allow-lists, agent
    /// quotas) can consult it without an API break.
    #[must_use]
    pub fn evaluate(&self, _agent_id: &str, action: &AgentAction) -> Decision {
        let mut first_warn: Option<(String, String)> = None;
        for rule in self.rules.iter() {
            if !matcher_applies(rule, action) {
                continue;
            }
            let severity = Severity::from_str(&rule.severity).unwrap_or(Severity::Log);
            match severity {
                Severity::Refuse => {
                    return Decision::Refuse {
                        rule_id: rule.id.clone(),
                        reason: rule.reason.clone(),
                    };
                }
                Severity::Warn => {
                    if first_warn.is_none() {
                        first_warn = Some((rule.id.clone(), rule.reason.clone()));
                    }
                }
                Severity::Log => {
                    // Log-only: silent in the engine. Audited entry
                    // points still emit the final decision's signed
                    // event below; per-log emission would amplify.
                }
            }
        }
        match first_warn {
            Some((rule_id, reason)) => Decision::Warn { rule_id, reason },
            None => Decision::Allow,
        }
    }

    /// Borrow the loaded rule slice. Used by [`count_matching_rules`]
    /// and by tests that want to assert load-side behaviour without
    /// running the matcher.
    #[must_use]
    pub fn rules(&self) -> &[Rule] {
        &self.rules
    }
}

// ---------------------------------------------------------------------------
// check_agent_action — the public entry point
// ---------------------------------------------------------------------------

/// Evaluate `action` against every enabled rule of matching kind in
/// the `governance_rules` table and return a [`Decision`].
///
/// Thin wrapper over [`RuleEngine::load_for_action`] +
/// [`RuleEngine::evaluate`]; the audit-emit side effect is the only
/// reason this entry point exists distinct from the `_no_audit`
/// variant.
///
/// The combinator is **first-refusal wins**: as soon as a `refuse`
/// rule matches, the engine returns `Refuse` and stops scanning
/// (subsequent matches are not evaluated). If no `refuse` rule
/// matches, the engine returns the first `warn` match (or `Allow`
/// if none).
///
/// Every call — refusal AND allow — emits one row to the
/// `signed_events` audit table with `event_type =
/// "governance.check"` and `payload_hash` over the canonical
/// representation of (action, decision). This is the load-bearing
/// audit chain for the v1.0 procurement review.
///
/// # Errors
///
/// Returns an error if the SQLite query fails or the audit emit
/// fails. A serde encoding error on `canonical_bytes` is propagated.
///
/// # Examples
///
/// ```ignore
/// # use ai_memory::governance::agent_action::{AgentAction, Decision, check_agent_action};
/// # use rusqlite::Connection;
/// let conn: Connection = todo!();
/// let action = AgentAction::FilesystemWrite {
///     path: "/tmp/foo".into(),
///     byte_estimate: None,
/// };
/// let decision = check_agent_action(&conn, "agent:test", &action)?;
/// match decision {
///     Decision::Refuse { rule_id, reason } => {
///         eprintln!("refused by {rule_id}: {reason}");
///     }
///     _ => { /* proceed */ }
/// }
/// # Ok::<_, anyhow::Error>(())
/// ```
pub fn check_agent_action(
    conn: &Connection,
    agent_id: &str,
    action: &AgentAction,
) -> Result<Decision> {
    check_agent_action_cached(conn, None, agent_id, action)
}

/// Cached variant of [`check_agent_action`] (#991).
///
/// `cache: Some(...)` consults the per-instance [`RuleCache`] (cache
/// hit returns the cached `Arc<Vec<Rule>>` without re-running the SQL
/// + Ed25519-verify path). `cache: None` behaves exactly like
/// [`check_agent_action`] (no cache consultation).
///
/// # Errors
///
/// Returns an error if the SQLite query fails or the audit emit fails.
pub fn check_agent_action_cached(
    conn: &Connection,
    cache: Option<&RuleCache>,
    agent_id: &str,
    action: &AgentAction,
) -> Result<Decision> {
    let engine = RuleEngine::load_for_action_cached(conn, cache, action).with_context(|| {
        format!(
            "check_agent_action_cached: load engine for {}",
            action.kind()
        )
    })?;
    let decision = engine.evaluate(agent_id, action);
    emit_check_event(conn, agent_id, action, &decision)?;
    emit_forensic_decision(agent_id, action, &decision);
    Ok(decision)
}

/// v0.7.0 #697 — translate a `(action, decision)` into the forensic
/// log shape and emit. No-op when the forensic sink is uninitialised.
fn emit_forensic_decision(agent_id: &str, action: &AgentAction, decision: &Decision) {
    let (decision_str, rule_id) = match decision {
        Decision::Allow => ("allow", String::new()),
        Decision::Refuse { rule_id, .. } => ("refuse", rule_id.clone()),
        Decision::Warn { rule_id, .. } => ("warn", rule_id.clone()),
    };
    // payload is `{action, decision_detail}` — keeps the forensic row
    // self-describing without depending on cross-table joins for a
    // SIEM walking the chain.
    let payload = serde_json::json!({
        "action": action,
        "decision_detail": decision,
    });
    crate::governance::audit::record_decision(
        agent_id,
        decision_str,
        action.kind(),
        &rule_id,
        payload,
    );
}

/// Append a `governance.check` row to `signed_events`. Helper so
/// every exit point in [`check_agent_action`] is symmetric (audit
/// chain is otherwise lossy on the Refuse short-circuit path).
fn emit_check_event(
    conn: &Connection,
    agent_id: &str,
    action: &AgentAction,
    decision: &Decision,
) -> Result<()> {
    // Canonical representation: serialize {action, decision} as a
    // stable JSON object and hash it. A future format-agility
    // change recomputes the hash over a different canonical
    // encoding without touching the call sites.
    let canonical = serde_json::json!({
        "action": action,
        "decision": decision,
    });
    let bytes =
        serde_json::to_vec(&canonical).context("emit_check_event: serialize canonical payload")?;
    let hash = payload_hash(&bytes);
    // v0.7.0 #1035 — sign the payload_hash with the daemon's
    // process-wide audit key when one is installed. When `init` ran
    // with `signing_key: None` (no key on disk), the helper returns
    // `None` and we fall through to the legacy unsigned posture.
    let (signature, attest_level) = match crate::governance::audit::try_sign_audit_payload(&hash) {
        Some((sig, level)) => (Some(sig), level.to_string()),
        None => (
            None,
            crate::models::AttestLevel::Unsigned.as_str().to_string(),
        ),
    };
    let event = crate::signed_events::SignedEvent {
        id: uuid::Uuid::new_v4().to_string(),
        agent_id: agent_id.to_string(),
        event_type: GOVERNANCE_CHECK_EVENT_TYPE.to_string(),
        payload_hash: hash,
        signature,
        attest_level,
        timestamp: chrono::Utc::now().to_rfc3339(),
        ..crate::signed_events::SignedEvent::default()
    };
    append_signed_event(conn, &event).context("emit_check_event: append_signed_event")?;
    Ok(())
}

/// v0.7.0 L1-6 Deliverable E — read-only variant of [`check_agent_action`]
/// suitable for the substrate pre-write hook path.
///
/// Identical to [`check_agent_action`] except it does NOT emit a
/// `governance.check` row to `signed_events`. Two reasons the
/// pre-write hook can't use the full audit path:
///
///   1. Re-entrancy. The hook fires INSIDE `storage::insert` —
///      i.e. while the caller already holds the substrate's
///      `Connection`. Calling `append_signed_event` on a sibling
///      connection would race the write lock under WAL; calling it
///      on the same connection would corrupt the in-flight INSERT's
///      statement state.
///   2. Symmetry. The substrate-INTERNAL gate path is already
///      audited at every callsite (handlers/http.rs and mcp/tools/store.rs
///      both emit an `AuditAction::Store` row on success / a typed
///      MemoryError on failure). A second emit here would amplify.
///
/// First-refusal-wins combinator: same as the audited path. Returns
/// `Decision::Refuse { rule_id, reason }` for the first `refuse`
/// match, `Decision::Warn { rule_id, reason }` for the first `warn`
/// match when no refusal fires, otherwise `Decision::Allow`.
///
/// # Errors
///
/// Returns an error if the SQLite query for enabled rules fails.
pub fn check_agent_action_no_audit(conn: &Connection, action: &AgentAction) -> Result<Decision> {
    check_agent_action_no_audit_cached(conn, None, action)
}

/// Cached variant of [`check_agent_action_no_audit`] (#991).
///
/// `cache: Some(...)` consults the per-instance [`RuleCache`]; `cache:
/// None` behaves exactly like [`check_agent_action_no_audit`].
///
/// # Errors
///
/// Returns an error if the rules-table SELECT fails.
pub fn check_agent_action_no_audit_cached(
    conn: &Connection,
    cache: Option<&RuleCache>,
    action: &AgentAction,
) -> Result<Decision> {
    let engine = RuleEngine::load_for_action_cached(conn, cache, action).with_context(|| {
        format!(
            "check_agent_action_no_audit_cached: load engine for {}",
            action.kind()
        )
    })?;
    let decision = engine.evaluate("", action);
    emit_forensic_decision("", action, &decision);
    Ok(decision)
}

/// v0.7.0 Policy-Engine Item 3 — deferred-audit variant of
/// [`check_agent_action_no_audit`] used by the substrate
/// `GOVERNANCE_PRE_WRITE` hook (issue #691 follow-up).
///
/// Identical matching semantics to [`check_agent_action_no_audit`]:
/// reads from the connection passed in (single-use, hot-path
/// no-allocation on the Allow leg). On a refusal it ALSO submits a
/// [`crate::governance::deferred_audit::DeferredAuditEvent`] to the
/// supplied queue so the background drainer can chain-log the
/// refusal to `signed_events` AFTER the in-flight write
/// transaction has released its lock.
///
/// # Why this exists
///
/// The `GOVERNANCE_PRE_WRITE` storage hook fires INSIDE
/// `storage::insert`, while the substrate's writer connection is
/// held under `Arc<Mutex<Connection>>`. Calling
/// `append_signed_event` on that same connection would re-enter the
/// in-flight INSERT and deadlock. The `_no_audit` variant solved
/// the deadlock but at the cost of dropping the chain-log property
/// for storage refusals. This variant fixes that by deferring the
/// audit write to a background tokio task with its OWN
/// `Connection` (SQLite WAL allows parallel writers).
///
/// On Allow / Warn paths the queue is NOT touched — the
/// load-bearing audit emit only happens on `Refuse`.
///
/// # Errors
///
/// Returns an error if the rules-table SELECT fails. The deferred
/// audit submit is fire-and-forget (it never errors out to the
/// caller; a closed receiver bumps a metric counter and emits a
/// tracing::warn).
pub fn check_agent_action_deferred(
    conn: &Connection,
    agent_id: &str,
    action: &AgentAction,
    queue: &crate::governance::deferred_audit::DeferredAuditQueue,
) -> Result<Decision> {
    check_agent_action_deferred_cached(conn, None, agent_id, action, queue)
}

/// Cached variant of [`check_agent_action_deferred`] (#991).
///
/// `cache: Some(...)` consults the per-instance [`RuleCache`]; `cache:
/// None` behaves exactly like [`check_agent_action_deferred`]. This is
/// the hot-path entry point used by the substrate
/// `GOVERNANCE_PRE_WRITE` storage hook — passing a cache here is the
/// load-bearing win that recovers the original #983 0.5-3ms-per-write
/// gain without the cross-connection poisoning that triggered the
/// #990 revert.
///
/// # Errors
///
/// Returns an error if the rules-table SELECT fails.
pub fn check_agent_action_deferred_cached(
    conn: &Connection,
    cache: Option<&RuleCache>,
    agent_id: &str,
    action: &AgentAction,
    queue: &crate::governance::deferred_audit::DeferredAuditQueue,
) -> Result<Decision> {
    let decision = check_agent_action_no_audit_cached(conn, cache, action)?;
    if decision.is_refusal() {
        queue.submit_refusal(agent_id, action, &decision);
    }
    Ok(decision)
}

/// Convenience for tests + the future K10 wiring: count how many
/// rules match the given action without running side effects.
/// Skips the audit emit (read-only).
///
/// # Errors
///
/// Returns an error if the SQLite query fails.
pub fn count_matching_rules(conn: &Connection, action: &AgentAction) -> Result<usize> {
    let engine = RuleEngine::load_for_action(conn, action)
        .with_context(|| format!("count_matching_rules: load engine for {}", action.kind()))?;
    Ok(engine
        .rules()
        .iter()
        .filter(|r| matcher_applies(r, action))
        .count())
}

/// Read-side helper: return the most-recent `governance.check`
/// audit row for `agent_id` (or any agent when `agent_id` is None).
/// Used by the MCP `rule_list` tool to surface "last check" info
/// in the operator UI.
///
/// # Errors
///
/// Returns an error if the SQLite query fails.
pub fn most_recent_check(conn: &Connection, agent_id: Option<&str>) -> Result<Option<String>> {
    let row: Option<String> = if let Some(aid) = agent_id {
        conn.query_row(
            "SELECT timestamp FROM signed_events \
             WHERE event_type = ?1 AND agent_id = ?2 \
             ORDER BY timestamp DESC LIMIT 1",
            rusqlite::params![GOVERNANCE_CHECK_EVENT_TYPE, aid],
            |r| r.get::<_, String>(0),
        )
        .optional()?
    } else {
        conn.query_row(
            "SELECT timestamp FROM signed_events \
             WHERE event_type = ?1 \
             ORDER BY timestamp DESC LIMIT 1",
            rusqlite::params![GOVERNANCE_CHECK_EVENT_TYPE],
            |r| r.get::<_, String>(0),
        )
        .optional()?
    };
    Ok(row)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::governance::rules_store;

    /// Build a fresh in-memory connection with the governance_rules
    /// table and the signed_events table — the engine's only two
    /// dependencies. Avoids pulling in the full migration ladder
    /// (which would also drag in fts5 / hnsw / etc.).
    fn fresh_conn() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE governance_rules (
                 id TEXT PRIMARY KEY,
                 kind TEXT NOT NULL,
                 matcher TEXT NOT NULL,
                 severity TEXT NOT NULL,
                 reason TEXT NOT NULL,
                 namespace TEXT NOT NULL DEFAULT '_global',
                 created_by TEXT NOT NULL,
                 created_at INTEGER NOT NULL,
                 enabled INTEGER NOT NULL DEFAULT 1,
                 signature BLOB,
                 attest_level TEXT NOT NULL DEFAULT 'unsigned'
             );
             CREATE TABLE signed_events (
                 id TEXT PRIMARY KEY,
                 agent_id TEXT NOT NULL,
                 event_type TEXT NOT NULL,
                 payload_hash BLOB NOT NULL,
                 signature BLOB,
                 attest_level TEXT NOT NULL DEFAULT 'unsigned',
                 timestamp TEXT NOT NULL,
                 -- v34 (V-4 closeout, #698) — cross-row chain columns.
                 prev_hash BLOB,
                 sequence INTEGER
             );",
        )
        .unwrap();
        conn
    }

    /// Issue #819 — short alias for the test-only thread-local guard
    /// that forces [`rules_store::resolve_operator_pubkey`] to return
    /// `None`. Tests that insert unsigned rules and expect
    /// `check_agent_action` to honor them must hold this guard for
    /// their full body, otherwise on dev hosts with a real
    /// `operator.key.pub` staged at the platform config path the
    /// L1-6 signature gate will skip the unsigned fixtures and the
    /// assertions will fail (test failures don't reproduce on
    /// clean-HOME CI; the guard makes the local dev loop match CI).
    #[must_use = "the guard must be held for the scope of the test"]
    fn no_operator_pubkey() -> rules_store::ForceNoOperatorPubkeyGuard {
        rules_store::force_no_operator_pubkey_for_test()
    }

    /// Issue #899 — guard against cross-test forensic-sink bleed.
    ///
    /// Every test that calls [`check_agent_action`] (or
    /// [`check_agent_action_no_audit`]) indirectly fires
    /// [`crate::governance::audit::record_decision`] via
    /// [`emit_forensic_decision`]. If a sibling test in
    /// `governance::audit::tests` has just initialised the
    /// process-wide forensic sink at its tempdir, this thread's
    /// `record_decision` would land a row in that sibling's
    /// tempdir — bleeding the sibling's row count.
    ///
    /// Tests that exercise `check_agent_action*` MUST hold this
    /// lock for the duration of the call. The lock is the same
    /// `OnceLock<Mutex<()>>` `audit::tests` uses, so the two
    /// modules now serialise their access to the shared sink.
    /// Acquire pattern mirrors `no_operator_pubkey`:
    ///
    /// ```ignore
    /// let _forensic = forensic_lock();
    /// let _no_pubkey = no_operator_pubkey();
    /// let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
    /// ```
    #[must_use = "the guard must be held for the scope of the test"]
    fn forensic_lock() -> std::sync::MutexGuard<'static, ()> {
        crate::governance::audit::forensic_sink_test_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner())
    }

    fn add_rule(
        conn: &Connection,
        id: &str,
        kind: &str,
        matcher: &str,
        severity: &str,
        enabled: bool,
    ) {
        rules_store::insert(
            conn,
            &Rule {
                id: id.to_string(),
                kind: kind.to_string(),
                matcher: matcher.to_string(),
                severity: severity.to_string(),
                reason: format!("{id}: test"),
                namespace: "_global".to_string(),
                created_by: "test".to_string(),
                created_at: 0,
                enabled,
                signature: None,
                attest_level: crate::models::AttestLevel::Unsigned.as_str().to_string(),
            },
        )
        .unwrap();
    }

    #[test]
    fn agent_action_kind_strings_are_stable() {
        assert_eq!(
            AgentAction::Bash {
                command: "ls".into(),
                cwd: None
            }
            .kind(),
            "bash"
        );
        assert_eq!(
            AgentAction::FilesystemWrite {
                path: "/x".into(),
                byte_estimate: None
            }
            .kind(),
            "filesystem_write"
        );
        assert_eq!(
            AgentAction::NetworkRequest {
                host: "h".into(),
                scheme: "https".into()
            }
            .kind(),
            "network_request"
        );
        assert_eq!(
            AgentAction::ProcessSpawn {
                binary: "b".into(),
                args: vec![]
            }
            .kind(),
            "process_spawn"
        );
        assert_eq!(
            AgentAction::Custom {
                custom_kind: "k".into(),
                payload: serde_json::json!({})
            }
            .kind(),
            "custom"
        );
    }

    #[test]
    fn severity_roundtrip() {
        for s in &[Severity::Refuse, Severity::Warn, Severity::Log] {
            assert_eq!(Severity::from_str(s.as_str()), Some(*s));
        }
        assert_eq!(Severity::from_str("nope"), None);
    }

    #[test]
    fn allow_when_no_rule_matches() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        let action = AgentAction::Bash {
            command: "ls -la".into(),
            cwd: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert_eq!(decision, Decision::Allow);
        assert!(decision.is_allowed());
    }

    #[test]
    fn refuse_filesystem_write_glob_match() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R001",
            "filesystem_write",
            r#"{"glob":"/tmp/**"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::FilesystemWrite {
            path: "/tmp/foo.txt".into(),
            byte_estimate: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert!(decision.is_refusal());
        match decision {
            Decision::Refuse { rule_id, .. } => assert_eq!(rule_id, "R001"),
            _ => panic!("expected refuse"),
        }
    }

    #[test]
    fn allow_filesystem_write_outside_glob() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R001",
            "filesystem_write",
            r#"{"glob":"/tmp/**"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::FilesystemWrite {
            path: "/Users/foo/safe.txt".into(),
            byte_estimate: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert_eq!(decision, Decision::Allow);
    }

    #[test]
    fn disabled_rule_does_not_match() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R001",
            "filesystem_write",
            r#"{"glob":"/tmp/**"}"#,
            "refuse",
            false, // disabled
        );
        let action = AgentAction::FilesystemWrite {
            path: "/tmp/foo".into(),
            byte_estimate: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert_eq!(decision, Decision::Allow);
    }

    #[test]
    fn warn_rule_returns_warn_not_refuse() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "W001",
            "bash",
            r#"{"command_regex":"rm -rf"}"#,
            "warn",
            true,
        );
        let action = AgentAction::Bash {
            command: "rm -rf /opt/scratch".into(),
            cwd: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        match decision {
            Decision::Warn { rule_id, .. } => assert_eq!(rule_id, "W001"),
            _ => panic!("expected warn"),
        }
    }

    #[test]
    fn refuse_wins_over_warn_when_both_match() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "W001",
            "bash",
            r#"{"command_regex":"rm"}"#,
            "warn",
            true,
        );
        add_rule(
            &conn,
            "R900",
            "bash",
            r#"{"command_regex":"rm -rf /"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::Bash {
            command: "rm -rf /".into(),
            cwd: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert!(decision.is_refusal());
    }

    #[test]
    fn process_spawn_binary_match() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-cargo",
            "process_spawn",
            r#"{"binary":"cargo"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::ProcessSpawn {
            binary: "cargo".into(),
            args: vec!["build".into()],
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert!(decision.is_refusal());
    }

    #[test]
    fn process_spawn_binary_mismatch_allows() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-cargo",
            "process_spawn",
            r#"{"binary":"cargo"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::ProcessSpawn {
            binary: "npm".into(),
            args: vec!["install".into()],
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert_eq!(decision, Decision::Allow);
    }

    #[test]
    fn network_request_exact_host_match() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-evil",
            "network_request",
            r#"{"host":"evil.example.com"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::NetworkRequest {
            host: "evil.example.com".into(),
            scheme: "https".into(),
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert!(decision.is_refusal());

        let allow_action = AgentAction::NetworkRequest {
            host: "good.example.com".into(),
            scheme: "https".into(),
        };
        let allow_decision = check_agent_action(&conn, "agent:t", &allow_action).unwrap();
        assert_eq!(allow_decision, Decision::Allow);
    }

    // SR — network host matcher glob support. Pre-fix the matcher did a
    // literal `==`, so a DENY rule written with a `*.example.com` wildcard
    // silently never matched (fail-OPEN): every subdomain sailed past the
    // gate. The fix routes the host through `glob_matches`, so the wildcard
    // DENY rule now fires on every subdomain while an exact host outside the
    // pattern is still allowed.
    #[test]
    fn network_request_glob_host_match_closes_fail_open() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-evil-glob",
            "network_request",
            r#"{"host":"*.evil.example.com"}"#,
            "refuse",
            true,
        );

        // A subdomain under the wildcard must be refused (pre-fix: allowed).
        for sub in ["api.evil.example.com", "c2.evil.example.com"] {
            let action = AgentAction::NetworkRequest {
                host: sub.into(),
                scheme: "https".into(),
            };
            let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
            assert!(
                decision.is_refusal(),
                "wildcard DENY rule must refuse subdomain {sub}"
            );
        }

        // A host outside the wildcard is still allowed.
        let allow_action = AgentAction::NetworkRequest {
            host: "good.example.org".into(),
            scheme: "https".into(),
        };
        assert_eq!(
            check_agent_action(&conn, "agent:t", &allow_action).unwrap(),
            Decision::Allow
        );
    }

    #[test]
    fn custom_action_matches_on_kind() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-custom",
            "custom",
            r#"{"kind":"approve_deploy"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::Custom {
            custom_kind: "approve_deploy".into(),
            payload: serde_json::json!({"env": "prod"}),
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert!(decision.is_refusal());
    }

    // ---- #1457 (SEC, MED-HIGH): custom payload predicates ------------------

    /// A `namespace_glob` predicate refuses a matching memory_write and
    /// leaves non-matching namespaces alone.
    #[test]
    fn custom_namespace_glob_predicate_scopes_refusal() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-ns",
            "custom",
            r#"{"kind":"memory_write","namespace_glob":"secure/**"}"#,
            "refuse",
            true,
        );
        let inside = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"namespace": "secure/keys", "tier": "long"}),
        };
        assert!(
            check_agent_action(&conn, "agent:t", &inside)
                .unwrap()
                .is_refusal()
        );
        let outside = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"namespace": "public/notes", "tier": "long"}),
        };
        assert_eq!(
            check_agent_action(&conn, "agent:t", &outside).unwrap(),
            Decision::Allow
        );
    }

    /// `tier` and `title_contains` predicates AND together: the rule
    /// fires only when BOTH match.
    #[test]
    fn custom_tier_and_title_predicates_and_together() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-tt",
            "custom",
            r#"{"kind":"memory_write","tier":"long","title_contains":"SECRET"}"#,
            "refuse",
            true,
        );
        let both = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"tier": "long", "title": "the SECRET plan"}),
        };
        assert!(
            check_agent_action(&conn, "agent:t", &both)
                .unwrap()
                .is_refusal()
        );
        // Right title, wrong tier ⇒ no match.
        let wrong_tier = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"tier": "mid", "title": "the SECRET plan"}),
        };
        assert_eq!(
            check_agent_action(&conn, "agent:t", &wrong_tier).unwrap(),
            Decision::Allow
        );
        // Right tier, title lacks needle ⇒ no match.
        let wrong_title = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"tier": "long", "title": "harmless note"}),
        };
        assert_eq!(
            check_agent_action(&conn, "agent:t", &wrong_title).unwrap(),
            Decision::Allow
        );
    }

    /// A predicate referencing a payload field that is absent makes the
    /// rule NOT match (fail-safe — a refusal must positively identify
    /// its target).
    #[test]
    fn custom_predicate_missing_payload_field_does_not_match() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-miss",
            "custom",
            r#"{"kind":"memory_write","namespace_glob":"secure/**"}"#,
            "refuse",
            true,
        );
        let no_ns = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"tier": "long"}),
        };
        assert_eq!(
            check_agent_action(&conn, "agent:t", &no_ns).unwrap(),
            Decision::Allow
        );
    }

    /// Backwards-compat: a kind-only `custom` rule still fires
    /// regardless of payload contents.
    #[test]
    fn custom_kind_only_rule_ignores_payload() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-kindonly",
            "custom",
            r#"{"kind":"memory_write"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"namespace": "anything", "tier": "short"}),
        };
        assert!(
            check_agent_action(&conn, "agent:t", &action)
                .unwrap()
                .is_refusal()
        );
    }

    #[test]
    fn check_emits_signed_event() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        let action = AgentAction::Bash {
            command: "ls".into(),
            cwd: None,
        };
        let _ = check_agent_action(&conn, "agent:test", &action).unwrap();
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM signed_events WHERE event_type = ?1 AND agent_id = ?2",
                rusqlite::params![GOVERNANCE_CHECK_EVENT_TYPE, "agent:test"],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn deferred_check_allow_signs_nothing_on_request_thread() {
        // Grounds the EXPLAIN-audit slate "Fix #5" premise (move
        // audit-chain Ed25519 per-row signing off the request thread):
        // the `memory_store` write path's governance gate
        // (`storage::GOVERNANCE_PRE_WRITE` -> this fn) performs ZERO
        // synchronous signing on an ALLOW verdict. Contrast
        // `check_emits_signed_event`, which proves the SYNCHRONOUS
        // `check_agent_action` signs + appends a `signed_events` row on
        // EVERY check (Allow included) — that path is reached only by the
        // CLI `rules check` one-shot and the explicit
        // `memory_check_agent_action` tool, never by a memory write.
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        let (queue, _rx) = crate::governance::deferred_audit::DeferredAuditQueue::new();
        let action = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"namespace": "anything", "tier": "short"}),
        };
        let decision =
            check_agent_action_deferred_cached(&conn, None, "agent:hotpath", &action, &queue)
                .unwrap();
        assert_eq!(decision, Decision::Allow);
        // No rule matched -> ALLOW -> NOT a refusal -> nothing enqueued
        // to the off-thread drainer either.
        assert!(!decision.is_refusal());
        // The load-bearing assertion: the request thread wrote ZERO
        // signed_events rows. A regression that re-routed the write-path
        // gate through the synchronous `emit_check_event` (per-row
        // Ed25519 sign + chain INSERT) would make this count == 1.
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM signed_events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            count, 0,
            "write-path governance gate must not synchronously sign on ALLOW; \
             per-row Ed25519 signing belongs off the request thread"
        );
    }

    #[test]
    fn refuse_short_circuit_still_emits_event() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R001",
            "filesystem_write",
            r#"{"glob":"/tmp/**"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::FilesystemWrite {
            path: "/tmp/x".into(),
            byte_estimate: None,
        };
        let _ = check_agent_action(&conn, "agent:t", &action).unwrap();
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM signed_events WHERE event_type = ?1",
                rusqlite::params![GOVERNANCE_CHECK_EVENT_TYPE],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn count_matching_rules_skips_audit() {
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R1",
            "bash",
            r#"{"command_regex":"foo"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::Bash {
            command: "foo bar".into(),
            cwd: None,
        };
        assert_eq!(count_matching_rules(&conn, &action).unwrap(), 1);
        // No audit row written by count.
        let audit_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM signed_events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(audit_count, 0);
    }

    #[test]
    fn malformed_matcher_does_not_panic() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        add_rule(&conn, "R-bad", "bash", "not json", "refuse", true);
        let action = AgentAction::Bash {
            command: "anything".into(),
            cwd: None,
        };
        let decision = check_agent_action(&conn, "agent:t", &action).unwrap();
        assert_eq!(decision, Decision::Allow);
    }

    #[test]
    fn matcher_applies_kind_mismatch_returns_false() {
        let rule = Rule {
            id: "R".to_string(),
            kind: "bash".to_string(),
            matcher: r#"{"command_regex":"x"}"#.to_string(),
            severity: "refuse".to_string(),
            reason: "r".to_string(),
            namespace: "_global".to_string(),
            created_by: "test".to_string(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: crate::models::AttestLevel::Unsigned.as_str().to_string(),
        };
        let action = AgentAction::FilesystemWrite {
            path: "/x".into(),
            byte_estimate: None,
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn canonical_bytes_includes_kind() {
        let a = AgentAction::Bash {
            command: "ls".into(),
            cwd: None,
        };
        let bytes = a.canonical_bytes().unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.contains("\"kind\""), "got {s}");
        assert!(s.contains("\"bash\""), "got {s}");
    }

    #[test]
    fn most_recent_check_empty_returns_none() {
        let conn = fresh_conn();
        assert_eq!(most_recent_check(&conn, None).unwrap(), None);
        assert_eq!(most_recent_check(&conn, Some("agent:x")).unwrap(), None);
    }

    #[test]
    fn most_recent_check_returns_latest() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        let action = AgentAction::Bash {
            command: "x".into(),
            cwd: None,
        };
        check_agent_action(&conn, "agent:a", &action).unwrap();
        assert!(most_recent_check(&conn, Some("agent:a")).unwrap().is_some());
        assert!(most_recent_check(&conn, Some("agent:b")).unwrap().is_none());
        assert!(most_recent_check(&conn, None).unwrap().is_some());
    }

    // -----------------------------------------------------------------
    // L1-6 Deliverable E — check_agent_action_no_audit coverage
    // (substrate pre-write hook consults this variant; identical
    // matching semantics, zero side effects on `signed_events`)
    // -----------------------------------------------------------------

    #[test]
    fn no_audit_allow_when_no_rule_matches() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        let action = AgentAction::Bash {
            command: "ls".into(),
            cwd: None,
        };
        let decision = check_agent_action_no_audit(&conn, &action).unwrap();
        assert_eq!(decision, Decision::Allow);
        let audit_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM signed_events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(audit_count, 0, "no_audit variant must not write audit rows");
    }

    #[test]
    fn no_audit_refuses_with_same_shape_as_audited_path() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-test",
            "custom",
            r#"{"kind":"memory_write"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({"namespace": "secrets/api"}),
        };
        let decision = check_agent_action_no_audit(&conn, &action).unwrap();
        match decision {
            Decision::Refuse { rule_id, reason } => {
                assert_eq!(rule_id, "R-test");
                assert!(reason.contains("R-test"), "reason: {reason}");
            }
            other => panic!("expected Refuse, got {other:?}"),
        }
        let audit_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM signed_events", [], |r| r.get(0))
            .unwrap();
        assert_eq!(audit_count, 0, "refusal in no_audit variant must not write");
    }

    #[test]
    fn no_audit_disabled_rule_yields_allow() {
        let _forensic = forensic_lock();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-disabled",
            "custom",
            r#"{"kind":"memory_write"}"#,
            "refuse",
            false,
        );
        let action = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({}),
        };
        let decision = check_agent_action_no_audit(&conn, &action).unwrap();
        assert_eq!(decision, Decision::Allow);
    }

    #[test]
    fn no_audit_warn_returned_when_no_refuse_matches() {
        let _forensic = forensic_lock();
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "W-test",
            "custom",
            r#"{"kind":"memory_write"}"#,
            "warn",
            true,
        );
        let action = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({}),
        };
        let decision = check_agent_action_no_audit(&conn, &action).unwrap();
        match decision {
            Decision::Warn { rule_id, .. } => assert_eq!(rule_id, "W-test"),
            other => panic!("expected Warn, got {other:?}"),
        }
    }

    #[test]
    fn decision_serializes_as_tagged_enum() {
        let d = Decision::Refuse {
            rule_id: "R1".to_string(),
            reason: "no".to_string(),
        };
        let v = serde_json::to_value(&d).unwrap();
        assert_eq!(v["decision"], "refuse");
        assert_eq!(v["rule_id"], "R1");
        let allow = Decision::Allow;
        let av = serde_json::to_value(&allow).unwrap();
        assert_eq!(av["decision"], "allow");
    }

    #[test]
    fn matcher_applies_returns_false_on_kind_mismatch() {
        let rule = Rule {
            id: "R".into(),
            kind: "bash".into(),
            matcher: r#"{"command_regex":"rm"}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let action = AgentAction::FilesystemWrite {
            path: "/x".into(),
            byte_estimate: None,
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn matcher_applies_returns_false_on_malformed_matcher_json() {
        let rule = Rule {
            id: "R".into(),
            kind: "bash".into(),
            matcher: "{not valid json".into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let action = AgentAction::Bash {
            command: "ls".into(),
            cwd: None,
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn matcher_applies_bash_with_missing_field_returns_false() {
        let rule = Rule {
            id: "R".into(),
            kind: "bash".into(),
            matcher: r#"{"other_field":"x"}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let action = AgentAction::Bash {
            command: "ls".into(),
            cwd: None,
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn matcher_applies_network_request_exact_host() {
        let rule = Rule {
            id: "R".into(),
            kind: "network_request".into(),
            matcher: r#"{"host":"evil.example.com"}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let evil = AgentAction::NetworkRequest {
            host: "evil.example.com".into(),
            scheme: "https".into(),
        };
        let good = AgentAction::NetworkRequest {
            host: "good.example.com".into(),
            scheme: "https".into(),
        };
        assert!(matcher_applies(&rule, &evil));
        assert!(!matcher_applies(&rule, &good));
    }

    #[test]
    fn matcher_applies_process_spawn_with_binary_only() {
        let rule = Rule {
            id: "R".into(),
            kind: "process_spawn".into(),
            matcher: r#"{"binary":"cargo"}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let cargo = AgentAction::ProcessSpawn {
            binary: "cargo".into(),
            args: vec!["build".into()],
        };
        let other = AgentAction::ProcessSpawn {
            binary: "ls".into(),
            args: vec![],
        };
        assert!(matcher_applies(&rule, &cargo));
        assert!(!matcher_applies(&rule, &other));
    }

    #[test]
    fn matcher_applies_process_spawn_with_missing_binary_field() {
        let rule = Rule {
            id: "R".into(),
            kind: "process_spawn".into(),
            matcher: r#"{}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let action = AgentAction::ProcessSpawn {
            binary: "cargo".into(),
            args: vec![],
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn matcher_applies_filesystem_write_missing_glob_field() {
        let rule = Rule {
            id: "R".into(),
            kind: "filesystem_write".into(),
            matcher: r#"{"other":"x"}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let action = AgentAction::FilesystemWrite {
            path: "/x".into(),
            byte_estimate: None,
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn matcher_applies_custom_missing_kind_field() {
        let rule = Rule {
            id: "R".into(),
            kind: "custom".into(),
            matcher: r#"{}"#.into(),
            severity: "refuse".into(),
            reason: "r".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let action = AgentAction::Custom {
            custom_kind: "memory_write".into(),
            payload: serde_json::json!({}),
        };
        assert!(!matcher_applies(&rule, &action));
    }

    #[test]
    fn count_matching_rules_returns_count() {
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R1",
            "bash",
            r#"{"command_regex":"rm"}"#,
            "refuse",
            true,
        );
        add_rule(
            &conn,
            "R2",
            "bash",
            r#"{"command_regex":"rm"}"#,
            "warn",
            true,
        );
        add_rule(
            &conn,
            "R3",
            "bash",
            r#"{"command_regex":"ls"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::Bash {
            command: "rm -rf".into(),
            cwd: None,
        };
        let count = count_matching_rules(&conn, &action).unwrap();
        assert_eq!(count, 2, "two rules match 'rm', one matches 'ls'");
    }

    #[test]
    fn count_matching_rules_zero_when_no_rules() {
        let conn = fresh_conn();
        let action = AgentAction::Bash {
            command: "ls".into(),
            cwd: None,
        };
        let count = count_matching_rules(&conn, &action).unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn decision_matches_for_each_variant() {
        let w = Decision::Warn {
            rule_id: "W".into(),
            reason: "warn".into(),
        };
        assert!(matches!(w, Decision::Warn { .. }));
        let allow = Decision::Allow;
        assert!(matches!(allow, Decision::Allow));
        assert!(allow.is_allowed());
        let refuse = Decision::Refuse {
            rule_id: "R".into(),
            reason: "no".into(),
        };
        assert!(refuse.is_refusal());
    }

    #[test]
    fn severity_as_str_round_trip() {
        for s in [Severity::Refuse, Severity::Warn, Severity::Log] {
            let back = Severity::from_str(s.as_str()).unwrap();
            assert_eq!(s, back);
        }
    }

    #[test]
    fn agent_action_serialize_round_trip_for_each_variant() {
        let actions = [
            AgentAction::Bash {
                command: "ls".into(),
                cwd: None,
            },
            AgentAction::FilesystemWrite {
                path: "/tmp/x".into(),
                byte_estimate: Some(1024),
            },
            AgentAction::NetworkRequest {
                host: "h.example.com".into(),
                scheme: "https".into(),
            },
            AgentAction::ProcessSpawn {
                binary: "cargo".into(),
                args: vec!["build".into()],
            },
            AgentAction::Custom {
                custom_kind: "memory_write".into(),
                payload: serde_json::json!({"ns": "a"}),
            },
        ];
        for a in &actions {
            let json = serde_json::to_value(a).unwrap();
            assert!(json.is_object(), "action should serialize as object");
            // Has discriminator field.
            assert!(
                json["type"].is_string() || json["kind"].is_string() || json.get("type").is_some()
            );
        }
    }

    // -----------------------------------------------------------------
    // Refactor Wave-2 Tier-A2 (issue #850) — RuleEngine unit coverage.
    // The three entry-point wrappers (check_agent_action,
    // check_agent_action_no_audit, check_agent_action_deferred) all
    // route through RuleEngine now; the tests above already exercise
    // them at the wrapper boundary. The cases below pin the engine's
    // direct semantics so a future regression in the wrapper layer
    // shows up at the engine level too.
    // -----------------------------------------------------------------

    #[test]
    fn rule_engine_from_rules_evaluate_allow_when_no_match() {
        let engine = RuleEngine::from_rules(vec![]);
        let decision = engine.evaluate(
            "agent:t",
            &AgentAction::Bash {
                command: "ls".into(),
                cwd: None,
            },
        );
        assert_eq!(decision, Decision::Allow);
        assert!(engine.rules().is_empty());
    }

    #[test]
    fn rule_engine_first_refusal_wins_over_warn() {
        let warn_rule = Rule {
            id: "W1".into(),
            kind: "bash".into(),
            matcher: r#"{"command_substring":"rm"}"#.into(),
            severity: "warn".into(),
            reason: "warn-rm".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let refuse_rule = Rule {
            id: "R1".into(),
            kind: "bash".into(),
            matcher: r#"{"command_substring":"rm -rf"}"#.into(),
            severity: "refuse".into(),
            reason: "refuse-rm-rf".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        // Order rules so warn comes first — first-refusal-wins must
        // still return refuse regardless of slice order.
        let engine = RuleEngine::from_rules(vec![warn_rule, refuse_rule]);
        let decision = engine.evaluate(
            "agent:t",
            &AgentAction::Bash {
                command: "rm -rf /tmp/x".into(),
                cwd: None,
            },
        );
        match decision {
            Decision::Refuse { rule_id, .. } => assert_eq!(rule_id, "R1"),
            other => panic!("expected Refuse, got {other:?}"),
        }
    }

    #[test]
    fn rule_engine_warn_when_only_warn_matches() {
        let rule = Rule {
            id: "W1".into(),
            kind: "bash".into(),
            matcher: r#"{"command_substring":"rm"}"#.into(),
            severity: "warn".into(),
            reason: "warn-rm".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let engine = RuleEngine::from_rules(vec![rule]);
        let decision = engine.evaluate(
            "agent:t",
            &AgentAction::Bash {
                command: "rm /tmp/x".into(),
                cwd: None,
            },
        );
        match decision {
            Decision::Warn { rule_id, reason } => {
                assert_eq!(rule_id, "W1");
                assert_eq!(reason, "warn-rm");
            }
            other => panic!("expected Warn, got {other:?}"),
        }
    }

    #[test]
    fn rule_engine_log_severity_is_silent() {
        let rule = Rule {
            id: "L1".into(),
            kind: "bash".into(),
            matcher: r#"{"command_substring":"ls"}"#.into(),
            severity: "log".into(),
            reason: "log-ls".into(),
            namespace: "_global".into(),
            created_by: "test".into(),
            created_at: 0,
            enabled: true,
            signature: None,
            attest_level: "unsigned".into(),
        };
        let engine = RuleEngine::from_rules(vec![rule]);
        let decision = engine.evaluate(
            "agent:t",
            &AgentAction::Bash {
                command: "ls -la".into(),
                cwd: None,
            },
        );
        // Log-only rules do not produce Warn or Refuse — engine
        // collapses to Allow.
        assert_eq!(decision, Decision::Allow);
    }

    #[test]
    fn rule_engine_load_for_action_round_trips_through_sqlite() {
        let _no_pubkey = no_operator_pubkey();
        let conn = fresh_conn();
        add_rule(
            &conn,
            "R-engine",
            "filesystem_write",
            r#"{"glob":"/tmp/**"}"#,
            "refuse",
            true,
        );
        let action = AgentAction::FilesystemWrite {
            path: "/tmp/engine.txt".into(),
            byte_estimate: None,
        };
        let engine = RuleEngine::load_for_action(&conn, &action).unwrap();
        // Engine carries exactly the kind-scoped rule we inserted.
        assert_eq!(engine.rules().len(), 1);
        assert_eq!(engine.rules()[0].id, "R-engine");
        let decision = engine.evaluate("agent:t", &action);
        match decision {
            Decision::Refuse { rule_id, .. } => assert_eq!(rule_id, "R-engine"),
            other => panic!("expected Refuse, got {other:?}"),
        }
    }
}