evorule-governance 0.2.3

Governance layer primitives: audit chain, rule validation, time machine, I/O dispatching
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 EvoRule Project
// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
//! 审计器 - 基于 FactsLog 构建审计链
//!
//! # 功能
//! - 定期从 FactsLog 读取新事实
//! - 计算每个 Fact 的哈希,维护哈希链
//! - 生成审计报告(因果链、版本历史)
//! - 验证审计链完整性
//!
//! # 哈希链算法
//! - `last_hash` 初始为 `"genesis"`
//! - 每个事实的链哈希 = `blake3(prev_hash + fact_hash)`
//! - 该链哈希作为下一条目的 `prev_hash`,形成不可篡改的链式结构
//!
//! # 两套 WAL 合并
//! 自 0.2.0 起,哈希链已提升到 tier1 的 FactsLog/WAL 层。
//! - tier1 WAL 写入时自动计算并存储哈希链(`content_hash`/`prev_hash`/`chain_hash`)
//! - 审计器不再独立写 WAL(`append_wal` 已废弃)
//! - 审计器的 `last_hash` 应与 `FactsLog::last_hash()` 一致
//! - 恢复审计状态使用 [`Auditor::load_from_tier1_wal`](读取 tier1 WAL 并验证哈希链)

use crate::clock::LogicalClock;
use crate::hash;
use evorule_reactor::{Fact, FactId, FactsLog};
use std::collections::BTreeMap;

/// 审计条目
///
/// 对应一个被审计的 [`Fact`],记录其哈希、逻辑时间戳及哈希链前驱。
#[derive(Debug, Clone)]
pub struct AuditEntry {
    /// Fact ID
    pub fact_id: FactId,
    /// Fact 类型名
    pub fact_type: &'static str,
    /// 逻辑时钟值
    pub logical_time: u64,
    /// 内容哈希
    pub content_hash: String,
    /// 前一条目的哈希(形成哈希链)
    pub prev_hash: String,
    /// 因果父 Fact ID(如有)
    pub cause: Option<FactId>,
}

/// 审计链加载错误(两套 WAL 合并)
///
/// `load_from_tier1_wal` 的错误类型,涵盖哈希链验证的各种失败场景。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadError {
    /// 文件读取失败(I/O 错误或 WAL 格式错误)
    IoError(String),
    /// 哈希计算失败(Fact 序列化错误)
    HashError(String),
    /// Fact 内容被篡改(存储的 content_hash 与重算的不匹配)
    ContentHashMismatch {
        /// 记录索引
        index: usize,
        /// Fact ID
        fact_id: FactId,
        /// WAL 中存储的哈希
        stored: String,
        /// 重算得到的哈希
        recomputed: String,
    },
    /// 哈希链断裂(prev_hash 链接不正确)
    ChainBroken {
        /// 记录索引
        index: usize,
        /// Fact ID
        fact_id: FactId,
        /// WAL 中存储的 prev_hash
        stored_prev: String,
        /// 期望的 prev_hash(前一条的 chain_hash)
        expected_prev: String,
    },
    /// 链哈希被篡改(存储的 chain_hash 与重算的不匹配)
    ChainHashMismatch {
        /// 记录索引
        index: usize,
        /// Fact ID
        fact_id: FactId,
        /// WAL 中存储的 chain_hash
        stored: String,
        /// 重算得到的 chain_hash
        recomputed: String,
    },
}

impl core::fmt::Display for LoadError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            LoadError::IoError(msg) => write!(f, "WAL 读取失败: {msg}"),
            LoadError::HashError(msg) => write!(f, "哈希计算失败: {msg}"),
            LoadError::ContentHashMismatch {
                index,
                fact_id,
                stored,
                recomputed,
            } => write!(
                f,
                "Fact[{}] (id={}) 内容哈希不匹配: stored={stored}, recomputed={recomputed}",
                index, fact_id.0
            ),
            LoadError::ChainBroken {
                index,
                fact_id,
                stored_prev,
                expected_prev,
            } => write!(
                f,
                "Fact[{}] (id={}) 哈希链断裂: stored_prev={stored_prev}, expected_prev={expected_prev}",
                index, fact_id.0
            ),
            LoadError::ChainHashMismatch {
                index,
                fact_id,
                stored,
                recomputed,
            } => write!(
                f,
                "Fact[{}] (id={}) 链哈希不匹配: stored={stored}, recomputed={recomputed}",
                index, fact_id.0
            ),
        }
    }
}

impl std::error::Error for LoadError {}

/// 审计器
///
/// 周期性消费 [`FactsLog`] 中的新增事实,构建带哈希链的审计条目列表。
/// 维护 `BTreeMap<FactId, usize>` 实时索引,支持 O(log n) 的因果链查询。
///
/// # 持久化(WAL)
/// 可选地通过 [`Auditor::with_wal_path`] 启用 WAL 持久化。
/// 启用后,每个新增审计条目以 JSONL 格式追加写入磁盘,
/// 进程重启后可通过 [`Auditor::load_from_wal`] 恢复审计状态。
pub struct Auditor {
    /// FactsLog 引用
    facts_log: FactsLog,
    /// 逻辑时钟
    clock: LogicalClock,
    /// 已审计到的版本
    last_audited_version: u64,
    /// 审计条目列表
    entries: Vec<AuditEntry>,
    /// 上一条目的哈希
    last_hash: String,
    /// FactId -> entries 索引的实时索引(优化因果链查询)
    index: BTreeMap<FactId, usize>,
    /// WAL 持久化路径(可选)
    wal_path: Option<std::path::PathBuf>,
    /// 是否在 audit_new 后自动验证审计链完整性(P06)
    ///
    /// 启用后每次 audit_new 完成后自动调用 verify(),及时发现数据篡改。
    /// 性能开销为 O(n)(n 为审计条目数),建议在大条目数场景配合
    /// `auto_verify_threshold` 和 `auto_verify_interval` 使用。
    auto_verify: bool,
    /// 自动验证阈值(P06)
    ///
    /// 当审计条目数超过此阈值时,跳过自动验证以避免性能问题。
    /// 默认 1000。设为 0 表示不限制(始终验证)。
    auto_verify_threshold: usize,
    /// 自动验证间隔(P06)
    ///
    /// 每 N 次 audit_new 执行一次自动验证(仅在 auto_verify=true 时生效)。
    /// 默认 1(每次都验证)。设为 100 表示每 100 次验证一次。
    auto_verify_interval: usize,
    /// audit_new 调用计数(P06,用于间隔控制)
    audit_new_count: u64,
}

impl Auditor {
    /// 创建新审计器
    ///
    /// `last_hash` 初始为 `"genesis"`,`last_audited_version` 初始为 0。
    pub fn new(facts_log: FactsLog) -> Self {
        Self {
            facts_log,
            clock: LogicalClock::new(),
            last_audited_version: 0,
            entries: Vec::new(),
            last_hash: String::from("genesis"),
            index: BTreeMap::new(),
            wal_path: None,
            auto_verify: false,
            auto_verify_threshold: 1000,
            auto_verify_interval: 1,
            audit_new_count: 0,
        }
    }

    /// 创建带实时验证配置的审计器(P06)
    ///
    /// # 参数
    /// - `facts_log`:FactsLog 引用
    /// - `auto_verify`:是否在 audit_new 后自动验证
    /// - `auto_verify_threshold`:条目数超过此阈值时跳过验证(0 表示不限制)
    /// - `auto_verify_interval`:每 N 次 audit_new 验证一次(1 表示每次都验证)
    pub fn new_with_auto_verify(
        facts_log: FactsLog,
        auto_verify: bool,
        auto_verify_threshold: usize,
        auto_verify_interval: usize,
    ) -> Self {
        Self {
            facts_log,
            clock: LogicalClock::new(),
            last_audited_version: 0,
            entries: Vec::new(),
            last_hash: String::from("genesis"),
            index: BTreeMap::new(),
            wal_path: None,
            auto_verify,
            auto_verify_threshold,
            auto_verify_interval: if auto_verify_interval == 0 {
                1
            } else {
                auto_verify_interval
            },
            audit_new_count: 0,
        }
    }

    /// 设置实时验证配置(P06)
    ///
    /// 可在创建后修改自动验证配置。
    pub fn set_auto_verify(
        &mut self,
        auto_verify: bool,
        auto_verify_threshold: usize,
        auto_verify_interval: usize,
    ) {
        self.auto_verify = auto_verify;
        self.auto_verify_threshold = auto_verify_threshold;
        self.auto_verify_interval = if auto_verify_interval == 0 {
            1
        } else {
            auto_verify_interval
        };
    }

    /// 查询当前是否启用自动验证(P06)
    pub fn is_auto_verify_enabled(&self) -> bool {
        self.auto_verify
    }

    /// 设置 WAL 持久化路径(deprecated)
    ///
    /// # ⚠️ 已废弃(两套 WAL 合并)
    /// 自 0.2.0 起,哈希链已由 tier1 FactsLog/WAL 自动维护,
    /// 审计器不再需要独立写 WAL。此方法仅保留向后兼容,
    /// 设置的路径不会被使用(`append_wal` 已禁用)。
    ///
    /// # 迁移指南
    /// 审计状态持久化请使用 tier1 WAL(`FactsLog::with_wal`),
    /// 恢复审计状态请使用 [`Auditor::load_from_tier1_wal`]。
    #[deprecated(
        since = "0.2.0",
        note = "两套 WAL 合并:审计器不再独立写 WAL,请使用 tier1 FactsLog WAL"
    )]
    pub fn with_wal_path<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.wal_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// 将单条审计条目序列化为 JSONL 行(deprecated,仅供向后兼容)
    #[deprecated(since = "0.2.0", note = "两套 WAL 合并:审计器不再独立写 WAL")]
    #[allow(dead_code)]
    fn entry_to_json_line(entry: &AuditEntry) -> String {
        serde_json::json!({
            "fact_id": entry.fact_id.0,
            "fact_type": entry.fact_type,
            "logical_time": entry.logical_time,
            "content_hash": entry.content_hash,
            "prev_hash": entry.prev_hash,
            "cause": entry.cause.map(|c| c.0),
        })
        .to_string()
    }

    /// 追加单条审计条目到 WAL 文件(deprecated,已禁用)
    ///
    /// # ⚠️ 已废弃(两套 WAL 合并)
    /// 自 0.2.0 起,此函数不再执行任何写入操作。
    /// 哈希链由 tier1 FactsLog/WAL 自动维护。
    #[deprecated(
        since = "0.2.0",
        note = "两套 WAL 合并:审计器不再独立写 WAL,哈希链由 tier1 WAL 维护"
    )]
    #[allow(dead_code)]
    fn append_wal(&self, _entry: &AuditEntry) {
        // 两套 WAL 合并:不再写入 auditor WAL
        // 哈希链已由 tier1 FactsLog::append() 自动写入 tier1 WAL
    }

    /// 审计新增事实
    ///
    /// 从 FactsLog 读取 `last_audited_version` 之后的所有事实,
    /// 为每个事实创建 [`AuditEntry`],更新哈希链。
    ///
    /// # 去重策略
    /// 由于 `FactsLog::read_from` 按 `version_before` 过滤,而同一版本下可能
    /// 存在多条不改变版本号的事实(如 `Command`/`IoRequest`),直接以版本号
    /// 做去重会导致重复审计。故本实现以 `entries.len()` 作为已审计进度,
    /// 从 `FactsLog::history()` 中读取尚未审计的尾部事实,保证每条事实仅审计一次。
    ///
    /// # 返回值
    /// 本次新增的审计条目数量。
    // 审计遍历 + 哈希 + append 多步串联, 拆函数需共享 self 状态。详见 GATE_REFERENCE.md §六(豁免索引)
    #[allow(clippy::cognitive_complexity)]
    pub fn audit_new(&mut self) -> usize {
        // P06: 计数始终递增(按调用次数,而非新事实数),用于自动验证间隔控制
        self.audit_new_count += 1;

        let history = self.facts_log.history();
        let start = self.entries.len();
        if start >= history.len() {
            self.last_audited_version = self.facts_log.version();
            tracing::debug!(version = self.last_audited_version, "audit_new: 无新增事实");
            return 0;
        }

        let count = history.len() - start;
        for (idx_offset, fact) in history[start..].iter().enumerate() {
            let fact_id = fact.id();
            let fact_type = fact.type_name();
            let logical_time = self.clock.tick();
            let content_hash = match hash::fact_hash(fact) {
                Ok(h) => h,
                Err(e) => {
                    tracing::error!(
                        事实ID = ?fact_id,
                        事实类型 = %fact_type,
                        错误 = %e,
                        "审计器: 事实哈希计算失败,跳过损坏事实"
                    );
                    continue;
                }
            };
            let prev_hash = self.last_hash.clone();
            let cause = extract_cause(fact);

            // 计算新的链哈希:blake3(prev_hash + content_hash)
            let combined = format!("{}{}", prev_hash, content_hash);
            let new_hash = blake3::hash(combined.as_bytes()).to_hex().to_string();
            self.last_hash = new_hash;

            let entry_index = start + idx_offset;
            self.index.insert(fact_id, entry_index);

            self.entries.push(AuditEntry {
                fact_id,
                fact_type,
                logical_time,
                content_hash,
                prev_hash,
                cause,
            });

            // 两套 WAL 合并:不再写入 auditor WAL
            // 哈希链已由 tier1 FactsLog::append() 自动写入 tier1 WAL
        }

        self.last_audited_version = self.facts_log.version();
        tracing::debug!(
            audited = count,
            version = self.last_audited_version,
            "audit_new: 完成"
        );

        // P06: 实时审计验证
        if self.should_auto_verify() {
            if !self.verify() {
                tracing::error!(
                    entries = self.entries.len(),
                    audit_new_count = self.audit_new_count,
                    "audit_new: 实时审计验证失败,审计链可能存在数据篡改或损坏"
                );
            } else {
                tracing::debug!(entries = self.entries.len(), "audit_new: 实时审计验证通过");
            }
        }

        count
    }

    /// 判断本次是否应执行自动验证(P06)
    ///
    /// 综合考虑三个条件:
    /// 1. `auto_verify` 必须为 true
    /// 2. 条目数不超过 `auto_verify_threshold`(0 表示不限制)
    /// 3. `audit_new_count` 是 `auto_verify_interval` 的倍数
    fn should_auto_verify(&self) -> bool {
        if !self.auto_verify || self.entries.is_empty() {
            return false;
        }
        if self.auto_verify_threshold > 0 && self.entries.len() > self.auto_verify_threshold {
            tracing::debug!(
                entries = self.entries.len(),
                threshold = self.auto_verify_threshold,
                "实时审计验证: 条目数超过阈值,跳过验证"
            );
            return false;
        }
        if self.auto_verify_interval > 1
            && self.audit_new_count % (self.auto_verify_interval as u64) != 0
        {
            return false;
        }
        true
    }

    /// 验证审计链完整性
    ///
    /// 重新计算每个条目的链哈希,并校验其存储的 `prev_hash` 与上一条目
    /// 重算出的链哈希一致,确认链式结构未被篡改。
    ///
    /// # 返回值
    /// - `true`:所有条目的 `prev_hash` 链接自洽
    /// - `false`:发现断裂(某条目 `prev_hash` 与前驱重算哈希不匹配)
    pub fn verify(&self) -> bool {
        let mut prev_hash = String::from("genesis");
        for entry in &self.entries {
            if entry.prev_hash != prev_hash {
                tracing::warn!(
                    fact_id = entry.fact_id.0,
                    "verify: 哈希链断裂,prev_hash 不匹配"
                );
                return false;
            }
            // 重新计算当前条目的链哈希,作为下一跳的预期 prev_hash
            let combined = format!("{}{}", entry.prev_hash, entry.content_hash);
            let recomputed = blake3::hash(combined.as_bytes()).to_hex().to_string();
            prev_hash = recomputed;
        }
        tracing::debug!(entries = self.entries.len(), "verify: 审计链完整");
        true
    }

    /// 获取审计条目
    pub fn entries(&self) -> &[AuditEntry] {
        &self.entries
    }

    /// 获取当前审计链的末尾哈希
    ///
    /// 返回最后一条审计条目的链哈希,初始为 `"genesis"`。
    /// 可用于快速获取审计链状态,无需解析 `report()` 的 JSON。
    pub fn last_hash(&self) -> &str {
        &self.last_hash
    }

    /// 生成审计报告(JSON 格式)
    ///
    /// 包含审计器元信息(已审计版本、条目数、末尾哈希)与全部审计条目。
    pub fn report(&self) -> String {
        let entries_json: Vec<serde_json::Value> = self
            .entries
            .iter()
            .map(|e| {
                serde_json::json!({
                    "fact_id": e.fact_id.0,
                    "fact_type": e.fact_type,
                    "logical_time": e.logical_time,
                    "content_hash": e.content_hash,
                    "prev_hash": e.prev_hash,
                    "cause": e.cause.map(|c| c.0),
                })
            })
            .collect();

        let report = serde_json::json!({
            "last_audited_version": self.last_audited_version,
            "entry_count": self.entries.len(),
            "last_hash": self.last_hash,
            "entries": entries_json,
        });

        serde_json::to_string_pretty(&report).unwrap_or_else(|_| String::from("{}"))
    }

    /// 获取因果链(从指定 FactId 开始追溯 cause 链)
    ///
    /// 返回从该 FactId 起,沿 `cause` 字段向上追溯的审计条目列表,
    /// 顺序为:起始条目 → 其因果父 → … → 根因(`cause` 为 `None` 的条目)。
    /// 若中途找不到对应条目,则在断点处终止追溯。
    ///
    /// # 性能优化
    /// 使用实时维护的 `BTreeMap<FactId, usize>` 索引,查询复杂度为 O(log n)。
    pub fn causal_chain(&self, fact_id: FactId) -> Vec<AuditEntry> {
        let mut chain = Vec::new();
        let mut current = Some(fact_id);
        while let Some(cur_id) = current {
            match self.index.get(&cur_id) {
                Some(&i) => {
                    let entry = self.entries[i].clone();
                    current = entry.cause;
                    chain.push(entry);
                }
                None => {
                    tracing::warn!(fact_id = cur_id.0, "causal_chain: 追溯中断,未找到审计条目");
                    break;
                }
            }
        }
        chain
    }

    /// 从 WAL 文件加载审计状态(deprecated,读取旧 auditor WAL 格式)
    ///
    /// # ⚠️ 已废弃(两套 WAL 合并)
    /// 自 0.2.0 起,审计状态应从 tier1 WAL 恢复,请使用
    /// [`Auditor::load_from_tier1_wal`] 代替。
    ///
    /// 本方法仍可读取旧格式 auditor WAL 文件(`fact_id`/`fact_type`/
    /// `logical_time`/`content_hash`/`prev_hash`/`cause` JSONL),
    /// 但不验证哈希链完整性(旧格式无 `chain_hash` 字段)。
    ///
    /// # 注意
    /// 此方法不校验 FactsLog 中是否存在对应 Fact,仅恢复内存结构。
    /// 调用方应确保 WAL 文件来自可信来源。
    #[deprecated(
        since = "0.2.0",
        note = "两套 WAL 合并:请使用 load_from_tier1_wal 读取 tier1 WAL(带哈希验证)"
    )]
    pub fn load_from_wal(&mut self, path: &std::path::Path) -> std::io::Result<()> {
        use std::io::BufRead;

        if !path.exists() {
            return Ok(());
        }

        let file = std::fs::File::open(path)?;
        let reader = std::io::BufReader::new(file);

        for (idx, line) in reader.lines().enumerate() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }

            let parsed: serde_json::Value = match serde_json::from_str(&line) {
                Ok(v) => v,
                Err(_) => {
                    tracing::warn!(line = idx, "load_from_wal: 跳过无效 JSON 行");
                    continue;
                }
            };

            let fact_id_num = match parsed.get("fact_id").and_then(|v| v.as_u64()) {
                Some(n) => n,
                None => continue,
            };
            let fact_type = match parsed.get("fact_type").and_then(|v| v.as_str()) {
                Some(s) => s,
                None => continue,
            };
            let logical_time = parsed
                .get("logical_time")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            let content_hash = parsed
                .get("content_hash")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let prev_hash = parsed
                .get("prev_hash")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let cause = parsed.get("cause").and_then(|v| v.as_u64()).map(FactId);

            let fact_id = FactId(fact_id_num);
            let entry = AuditEntry {
                fact_id,
                // 安全:fact_type 是静态字符串名(来自 Fact::type_name),
                // 此处使用泄漏扩展生命周期。WAL 中的类型名都是已知的固定字符串,
                // 实际使用中应做类型映射表。这里做简化处理。
                fact_type: FACT_TYPE_STATIC_TABLE
                    .iter()
                    .copied()
                    .find(|t| *t == fact_type)
                    .unwrap_or("Unknown"),
                logical_time,
                content_hash: content_hash.clone(),
                prev_hash: prev_hash.clone(),
                cause,
            };

            self.index.insert(fact_id, self.entries.len());
            self.entries.push(entry);

            // 重算链哈希(验证并更新 last_hash)
            let combined = format!("{}{}", prev_hash, content_hash);
            self.last_hash = blake3::hash(combined.as_bytes()).to_hex().to_string();

            // 更新时钟到最大值
            if logical_time > self.clock.current() {
                // 逻辑时钟通过 tick 推进;从 WAL 恢复时直接设置到最大值+1
                // 这里我们用一个小技巧:多次 tick 直到达到目标
                while self.clock.current() < logical_time {
                    self.clock.tick();
                }
            }
        }

        self.wal_path = Some(path.to_path_buf());
        Ok(())
    }

    /// 从 tier1 WAL 加载审计状态并验证哈希链完整性(两套 WAL 合并)
    ///
    /// 读取 tier1 WAL 文件(统一格式,含 `content_hash`/`prev_hash`/`chain_hash`),
    /// 重建审计器的 `entries`、`index`、`last_hash` 和 `clock`,同时**验证**
    /// 哈希链完整性。
    ///
    /// # 验证内容
    /// 1. **content_hash 验证**:重算每个 Fact 的哈希,与 WAL 中存储的 `content_hash` 比对
    /// 2. **prev_hash 链接验证**:每条记录的 `prev_hash` 应等于前一条的 `chain_hash`
    /// 3. **chain_hash 验证**:重算 `blake3(prev_hash + content_hash)`,与存储的 `chain_hash` 比对
    ///
    /// # 向后兼容
    /// - **新格式**(有 `chain_hash` 字段):执行完整哈希链验证
    /// - **旧格式**(无 `chain_hash` 字段):仅重建状态,不验证哈希(发出警告)
    ///
    /// # 参数
    /// - `path`: tier1 WAL 文件路径
    ///
    /// # 返回值
    /// - `Ok(())`:加载并验证成功
    /// - `Err(LoadError)`:文件读取失败或哈希链验证失败
    ///
    /// # 错误类型
    /// - [`LoadError::IoError`]:文件读取失败
    /// - [`LoadError::ContentHashMismatch`]:Fact 内容被篡改(content_hash 不匹配)
    /// - [`LoadError::ChainBroken`]:哈希链断裂(prev_hash 链接不正确)
    /// - [`LoadError::ChainHashMismatch`]:链哈希不匹配(chain_hash 被篡改)
    pub fn load_from_tier1_wal(&mut self, path: &std::path::Path) -> Result<(), LoadError> {
        use evorule_reactor::read_wal_with_hash;

        let records = read_wal_with_hash(path).map_err(|e| LoadError::IoError(e.to_string()))?;

        // 清空当前状态
        self.entries.clear();
        self.index.clear();
        self.last_hash = String::from("genesis");
        self.last_audited_version = 0;
        self.audit_new_count = 0;

        let mut prev_hash = String::from("genesis");
        let mut has_hash_fields = false;
        let mut max_logical_time = 0u64;

        for (idx, record) in records.iter().enumerate() {
            let fact = &record.fact;
            let fact_id = fact.id();
            let fact_type = fact.type_name();

            // 检查是否有哈希字段(新格式)
            if record.chain_hash.is_some() {
                has_hash_fields = true;
            }

            // 验证 content_hash(新格式)
            if let Some(stored_content) = &record.content_hash {
                let recomputed = hash::fact_hash(fact)
                    .map_err(|e| LoadError::HashError(format!("fact[{}]: {}", idx, e)))?;
                if stored_content != &recomputed {
                    return Err(LoadError::ContentHashMismatch {
                        index: idx,
                        fact_id,
                        stored: stored_content.clone(),
                        recomputed,
                    });
                }
            }

            // 验证 prev_hash 链接(新格式)
            if let Some(stored_prev) = &record.prev_hash {
                if stored_prev != &prev_hash {
                    return Err(LoadError::ChainBroken {
                        index: idx,
                        fact_id,
                        stored_prev: stored_prev.clone(),
                        expected_prev: prev_hash.clone(),
                    });
                }
            }

            // 重算链哈希
            let content_hash = record
                .content_hash
                .clone()
                .unwrap_or_else(|| hash::fact_hash(fact).unwrap_or_else(|_| String::new()));
            let combined = format!("{}{}", prev_hash, content_hash);
            let recomputed_chain = blake3::hash(combined.as_bytes()).to_hex().to_string();

            // 验证 chain_hash(新格式)
            if let Some(stored_chain) = &record.chain_hash {
                if stored_chain != &recomputed_chain {
                    return Err(LoadError::ChainHashMismatch {
                        index: idx,
                        fact_id,
                        stored: stored_chain.clone(),
                        recomputed: recomputed_chain.clone(),
                    });
                }
            }

            prev_hash = recomputed_chain.clone();

            // 构建 AuditEntry
            let logical_time = idx as u64 + 1;
            let cause = extract_cause(fact);
            let entry = AuditEntry {
                fact_id,
                fact_type: FACT_TYPE_STATIC_TABLE
                    .iter()
                    .copied()
                    .find(|t| *t == fact_type)
                    .unwrap_or("Unknown"),
                logical_time,
                content_hash,
                prev_hash: if record.prev_hash.is_some() {
                    record.prev_hash.clone().unwrap_or_default()
                } else {
                    // 旧格式:使用重算的 prev_hash(初始为 genesis)
                    String::from("genesis")
                },
                cause,
            };

            self.index.insert(fact_id, idx);
            self.entries.push(entry);

            if logical_time > max_logical_time {
                max_logical_time = logical_time;
            }
        }

        // 恢复末尾哈希
        self.last_hash = if has_hash_fields {
            // 新格式:使用最后一条记录的 chain_hash
            records
                .last()
                .and_then(|r| r.chain_hash.clone())
                .unwrap_or(prev_hash)
        } else {
            // 旧格式:使用重算的链哈希
            prev_hash
        };

        // 同步逻辑时钟
        while self.clock.current() < max_logical_time {
            self.clock.tick();
        }

        // 更新已审计版本(从最后一条 Fact 推断)
        self.last_audited_version = records.len() as u64;

        if !has_hash_fields {
            tracing::warn!(
                path = %path.display(),
                "load_from_tier1_wal: 旧格式 WAL(无哈希字段),仅重建状态,未验证哈希链"
            );
        } else {
            tracing::info!(
                path = %path.display(),
                entries = self.entries.len(),
                last_hash = %self.last_hash,
                "load_from_tier1_wal: 加载并验证审计链成功"
            );
        }

        Ok(())
    }

    /// 导出审计链为 JSON 格式(P04)
    ///
    /// 返回包含所有审计条目的 JSON 字符串,可用于跨实例迁移或离线分析。
    ///
    /// # 导出格式
    /// ```json
    /// {
    ///   "version": "1.0",
    ///   "last_hash": "<末尾链哈希>",
    ///   "last_audited_version": <已审计版本>,
    ///   "entry_count": <条目数>,
    ///   "entries": [ { ...AuditEntry }, ... ]
    /// }
    /// ```
    ///
    /// # 安全说明
    /// 导出数据包含完整的哈希链信息,可作为审计证据。
    /// 调用方应妥善保护导出数据,防止被篡改。
    pub fn export(&self) -> String {
        let entries_json: Vec<serde_json::Value> = self
            .entries
            .iter()
            .map(|e| {
                serde_json::json!({
                    "fact_id": e.fact_id.0,
                    "fact_type": e.fact_type,
                    "logical_time": e.logical_time,
                    "content_hash": e.content_hash,
                    "prev_hash": e.prev_hash,
                    "cause": e.cause.map(|c| c.0),
                })
            })
            .collect();

        let export = serde_json::json!({
            "version": "1.0",
            "last_hash": self.last_hash,
            "last_audited_version": self.last_audited_version,
            "entry_count": self.entries.len(),
            "entries": entries_json,
        });

        serde_json::to_string_pretty(&export).unwrap_or_else(|_| String::from("{}"))
    }

    /// 从 JSON 导入审计链(P04)
    ///
    /// 覆盖当前审计状态,导入外部审计数据。
    ///
    /// # 参数
    /// `json_str`:由 `export()` 产生的 JSON 字符串
    ///
    /// # 返回
    /// - `Ok(())`:导入成功
    /// - `Err(String)`:JSON 解析或字段缺失错误
    ///
    /// # 安全注意事项
    /// 1. 导入操作会**完全覆盖**当前审计链,具有破坏性
    /// 2. 调用方应确保导入数据来自可信来源
    /// 3. 导入后会自动调用 `verify()` 校验哈希链完整性
    /// 4. `fact_type` 字段会被映射到 `FACT_TYPE_STATIC_TABLE` 中的已知类型,
    ///    未知类型会被替换为 `"Unknown"`(保留哈希链但丢失类型语义)
    pub fn import(&mut self, json_str: &str) -> Result<(), String> {
        let parsed: serde_json::Value =
            serde_json::from_str(json_str).map_err(|e| format!("JSON parse error: {}", e))?;

        let version = parsed
            .get("version")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "Missing 'version' field".to_string())?;

        if version != "1.0" {
            return Err(format!("Unsupported version: {} (expected 1.0)", version));
        }

        let entries_arr = parsed
            .get("entries")
            .and_then(|e| e.as_array())
            .ok_or_else(|| "Missing 'entries' array".to_string())?;

        // 清空当前状态
        self.entries.clear();
        self.index.clear();
        self.last_hash = String::from("genesis");
        self.last_audited_version = 0;
        self.audit_new_count = 0;

        for (idx, entry_val) in entries_arr.iter().enumerate() {
            let fact_id_num = entry_val
                .get("fact_id")
                .and_then(|v| v.as_u64())
                .ok_or_else(|| format!("Entry {} missing 'fact_id'", idx))?;
            let fact_type_str = entry_val
                .get("fact_type")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format!("Entry {} missing 'fact_type'", idx))?;
            let logical_time = entry_val
                .get("logical_time")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            let content_hash = entry_val
                .get("content_hash")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let prev_hash = entry_val
                .get("prev_hash")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let cause = entry_val.get("cause").and_then(|v| v.as_u64()).map(FactId);

            // 复用 FACT_TYPE_STATIC_TABLE 将字符串映射为 &'static str
            let fact_type: &'static str = FACT_TYPE_STATIC_TABLE
                .iter()
                .copied()
                .find(|t| *t == fact_type_str)
                .unwrap_or("Unknown");

            let entry = AuditEntry {
                fact_id: FactId(fact_id_num),
                fact_type,
                logical_time,
                content_hash,
                prev_hash,
                cause,
            };

            self.index.insert(entry.fact_id, idx);
            self.entries.push(entry);
        }

        // 恢复末尾哈希和已审计版本
        self.last_hash = parsed
            .get("last_hash")
            .and_then(|v| v.as_str())
            .unwrap_or("genesis")
            .to_string();
        self.last_audited_version = parsed
            .get("last_audited_version")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);

        // 同步逻辑时钟到导入数据中的最大 logical_time
        let max_logical_time = self
            .entries
            .iter()
            .map(|e| e.logical_time)
            .max()
            .unwrap_or(0);
        while self.clock.current() < max_logical_time {
            self.clock.tick();
        }

        tracing::info!(
            entries = self.entries.len(),
            last_audited_version = self.last_audited_version,
            "import: 审计链导入完成"
        );

        Ok(())
    }

    /// 导入后立即验证审计链完整性(P04 便捷方法)
    ///
    /// 等价于 `import()` 后调用 `verify()`,返回导入是否成功且审计链完整。
    pub fn import_and_verify(&mut self, json_str: &str) -> Result<bool, String> {
        self.import(json_str)?;
        let valid = self.verify();
        if !valid {
            tracing::warn!(
                entries = self.entries.len(),
                "import_and_verify: 导入后审计链验证失败,数据可能已损坏"
            );
        }
        Ok(valid)
    }

    /// 导出压缩的审计链(P05)
    ///
    /// 使用 gzip 压缩 [`export`](Self::export) 产生的 JSON 数据,
    /// 减少传输和存储大小。压缩率通常可达 5-10 倍(取决于条目数和哈希重复度)。
    ///
    /// # 返回
    /// - `Ok(Vec<u8>)`:gzip 压缩字节流
    /// - `Err(String)`:压缩失败(极少见,通常是内存不足)
    ///
    /// # 使用场景
    /// - 网络传输:减少带宽占用
    /// - 长期归档:减少存储成本
    /// - 跨实例迁移:批量传输
    pub fn export_compressed(&self) -> Result<Vec<u8>, String> {
        use flate2::write::GzEncoder;
        use flate2::Compression;
        use std::io::Write;

        let export_str = self.export();
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder
            .write_all(export_str.as_bytes())
            .map_err(|e| format!("Compression write error: {}", e))?;
        encoder
            .finish()
            .map_err(|e| format!("Compression finish error: {}", e))
    }

    /// 从压缩数据导入审计链(P05)
    ///
    /// 解压 gzip 数据后调用 [`import`](Self::import)。
    ///
    /// # 参数
    /// `compressed`:由 [`export_compressed`](Self::export_compressed) 产生的 gzip 字节流
    ///
    /// # 返回
    /// - `Ok(())`:解压并导入成功
    /// - `Err(String)`:解压失败或导入数据格式错误
    ///
    /// # 安全说明
    /// 与 [`import`](Self::import) 相同,调用方应确保数据来自可信来源。
    /// 此方法**不会**自动调用 `verify()`,如需验证请使用
    /// [`import_compressed_and_verify`](Self::import_compressed_and_verify)。
    pub fn import_compressed(&mut self, compressed: &[u8]) -> Result<(), String> {
        use flate2::read::GzDecoder;
        use std::io::Read;

        let mut decoder = GzDecoder::new(compressed);
        let mut decompressed = String::new();
        decoder
            .read_to_string(&mut decompressed)
            .map_err(|e| format!("Decompression error: {}", e))?;

        self.import(&decompressed)
    }

    /// 从压缩数据导入并立即验证(P05 便捷方法)
    ///
    /// 等价于 [`import_compressed`](Self::import_compressed) 后调用 [`verify`](Self::verify),
    /// 返回导入是否成功且审计链完整。
    pub fn import_compressed_and_verify(&mut self, compressed: &[u8]) -> Result<bool, String> {
        self.import_compressed(compressed)?;
        let valid = self.verify();
        if !valid {
            tracing::warn!(
                entries = self.entries.len(),
                "import_compressed_and_verify: 导入后审计链验证失败"
            );
        }
        Ok(valid)
    }
}

/// Fact 类型名静态表(用于 WAL 加载时获取 &'static str)
///
/// 包含所有已知的 Fact 变体类型名,加载 WAL 时从中查找匹配项,
/// 以获取 `&'static str` 引用。
const FACT_TYPE_STATIC_TABLE: &[&str] = &[
    "StateTransition",
    "Command",
    "PayloadUpdate",
    "IoRequest",
    "IoResponse",
    "ControlSignal",
    "Error",
    "Unknown",
];

/// 从 Fact 中提取因果父 Fact ID
///
/// - [`Fact::StateTransition`] / [`Fact::IoRequest`]:返回其 `cause` 字段
/// - [`Fact::IoResponse`]:返回其 `request_id`(语义上为因果前驱)
/// - 其他变体:返回 `None`
fn extract_cause(fact: &Fact) -> Option<FactId> {
    match fact {
        Fact::StateTransition { cause, .. } => Some(*cause),
        Fact::IoRequest { cause, .. } => Some(*cause),
        Fact::IoResponse { request_id, .. } => Some(*request_id),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
    use super::*;
    use evorule_reactor::{Fact, FactId, FactsLog, IoType};
    use evorule_tcb::JsonValue;

    fn make_facts_log() -> FactsLog {
        FactsLog::new()
    }

    #[test]
    fn test_auditor_basic_chain() {
        let log = make_facts_log();
        let f0 = Fact::PayloadUpdate {
            id: FactId(1),
            path: "k1".into(),
            value: JsonValue::string("v1"),
        };
        let id0 = f0.id();
        log.append(f0).unwrap();

        let f1 = Fact::StateTransition {
            id: FactId(2),
            cause: id0,
            new_payload: JsonValue::empty_object(),
            new_queue: vec![],
        };
        log.append(f1).unwrap();

        let mut auditor = Auditor::new(log);
        let n = auditor.audit_new();
        assert_eq!(n, 2);
        assert!(auditor.verify());
        assert_eq!(auditor.entries().len(), 2);
    }

    #[test]
    fn test_auditor_causal_chain() {
        let log = make_facts_log();

        let f0 = Fact::PayloadUpdate {
            id: FactId(1),
            path: "root".into(),
            value: JsonValue::from(0i64),
        };
        let id0 = f0.id();
        log.append(f0).unwrap();

        let f1 = Fact::StateTransition {
            id: FactId(2),
            cause: id0,
            new_payload: JsonValue::empty_object(),
            new_queue: vec![],
        };
        let id1 = f1.id();
        log.append(f1).unwrap();

        let f2 = Fact::IoRequest {
            id: FactId(3),
            cause: id1,
            io_type: IoType::http_get(),
            params: JsonValue::empty_object(),
        };
        let id2 = f2.id();
        log.append(f2).unwrap();

        let mut auditor = Auditor::new(log);
        auditor.audit_new();

        let chain = auditor.causal_chain(id2);
        assert_eq!(chain.len(), 3);
        assert_eq!(chain[0].fact_id, id2);
        assert_eq!(chain[1].fact_id, id1);
        assert_eq!(chain[2].fact_id, id0);
    }

    #[test]
    fn test_auditor_wal_persist_and_reload() {
        let tmp =
            std::env::temp_dir().join(format!("auditor_wal_test_{}.jsonl", std::process::id()));
        let _ = std::fs::remove_file(&tmp);

        // 第一轮:通过 tier1 WAL 写入(两套 WAL 合并后的统一路径)
        {
            let log = FactsLog::with_wal(&tmp).expect("create wal");
            let f0 = Fact::PayloadUpdate {
                id: FactId(1),
                path: "a".into(),
                value: JsonValue::from(1i64),
            };
            let f1 = Fact::PayloadUpdate {
                id: FactId(2),
                path: "b".into(),
                value: JsonValue::from(2i64),
            };
            log.append(f0).unwrap();
            log.append(f1).unwrap();

            let mut auditor = Auditor::new(log);
            let n = auditor.audit_new();
            assert_eq!(n, 2);
            assert!(auditor.verify());
        }

        // 第二轮:从 tier1 WAL 恢复(带哈希链验证)
        {
            let log = make_facts_log();
            let mut auditor = Auditor::new(log);
            auditor.load_from_tier1_wal(&tmp).expect("load tier1 wal");
            assert_eq!(auditor.entries().len(), 2);
            assert!(auditor.verify());
        }

        let _ = std::fs::remove_file(&tmp);
    }

    /// 验证 load_from_tier1_wal 能检测 Fact 内容篡改
    #[test]
    fn test_load_from_tier1_wal_detects_content_tamper() {
        let tmp =
            std::env::temp_dir().join(format!("auditor_tamper_test_{}.jsonl", std::process::id()));
        let _ = std::fs::remove_file(&tmp);

        // 写入正常 WAL
        {
            let log = FactsLog::with_wal(&tmp).expect("create wal");
            let f = Fact::PayloadUpdate {
                id: FactId(1),
                path: "a".into(),
                value: JsonValue::from(42i64),
            };
            log.append(f).unwrap();
        }

        // 篡改 WAL 文件中的 Fact 内容(修改 value 字段)
        {
            let content = std::fs::read_to_string(&tmp).expect("read wal");
            let tampered = content.replace("42", "999");
            std::fs::write(&tmp, tampered).expect("write tampered wal");
        }

        // 加载应失败(content_hash 不匹配)
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        let result = auditor.load_from_tier1_wal(&tmp);
        assert!(result.is_err(), "篡改 Fact 内容应被检测到");
        match result.unwrap_err() {
            LoadError::ContentHashMismatch { .. } => {}
            other => panic!("期望 ContentHashMismatch,得到: {other}"),
        }

        let _ = std::fs::remove_file(&tmp);
    }

    /// 验证 load_from_tier1_wal 能检测哈希链断裂
    #[test]
    fn test_load_from_tier1_wal_detects_chain_break() {
        let tmp =
            std::env::temp_dir().join(format!("auditor_chain_break_{}.jsonl", std::process::id()));
        let _ = std::fs::remove_file(&tmp);

        // 写入 2 条 Fact
        {
            let log = FactsLog::with_wal(&tmp).expect("create wal");
            let f0 = Fact::PayloadUpdate {
                id: FactId(1),
                path: "a".into(),
                value: JsonValue::from(1i64),
            };
            let f1 = Fact::PayloadUpdate {
                id: FactId(2),
                path: "b".into(),
                value: JsonValue::from(2i64),
            };
            log.append(f0).unwrap();
            log.append(f1).unwrap();
        }

        // 篡改第二条记录的 prev_hash(破坏链)
        {
            let content = std::fs::read_to_string(&tmp).expect("read wal");
            let lines: Vec<&str> = content.lines().collect();
            // 修改第二行的 prev_hash 字段
            let tampered_line2 = lines[1].replace("\"prev_hash\":\"", "\"prev_hash\":\"tampered");
            let tampered = format!("{}\n{}\n", lines[0], tampered_line2);
            std::fs::write(&tmp, tampered).expect("write tampered wal");
        }

        // 加载应失败(prev_hash 链接不匹配)
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        let result = auditor.load_from_tier1_wal(&tmp);
        assert!(result.is_err(), "哈希链断裂应被检测到");
        match result.unwrap_err() {
            LoadError::ChainBroken { .. } | LoadError::ChainHashMismatch { .. } => {}
            other => panic!("期望 ChainBroken 或 ChainHashMismatch,得到: {other}"),
        }

        let _ = std::fs::remove_file(&tmp);
    }

    #[test]
    #[allow(deprecated)]
    fn test_auditor_wal_nonexistent_file() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        let result = auditor.load_from_wal(std::path::Path::new("/nonexistent/path/wal.jsonl"));
        assert!(result.is_ok());
        assert_eq!(auditor.entries().len(), 0);
    }

    #[test]
    fn test_auditor_wal_incremental() {
        let tmp =
            std::env::temp_dir().join(format!("auditor_wal_incr_{}.jsonl", std::process::id()));
        let _ = std::fs::remove_file(&tmp);

        // 使用 tier1 WAL 持久化(两套 WAL 合并后的统一路径)
        let log = FactsLog::with_wal(&tmp).expect("create wal");
        let mut auditor = Auditor::new(log.clone());

        // 第一批
        let f1 = Fact::PayloadUpdate {
            id: FactId(1),
            path: "k1".into(),
            value: JsonValue::string("v1"),
        };
        log.append(f1).unwrap();
        assert_eq!(auditor.audit_new(), 1);

        // 第二批
        let f2 = Fact::PayloadUpdate {
            id: FactId(2),
            path: "k2".into(),
            value: JsonValue::string("v2"),
        };
        log.append(f2).unwrap();
        assert_eq!(auditor.audit_new(), 1);

        // 从 tier1 WAL 恢复应得到 2 条(带哈希链验证)
        let mut auditor2 = Auditor::new(make_facts_log());
        auditor2.load_from_tier1_wal(&tmp).expect("load tier1 wal");
        assert_eq!(auditor2.entries().len(), 2);
        assert!(auditor2.verify());

        let _ = std::fs::remove_file(&tmp);
    }

    #[test]
    fn test_auditor_empty() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        assert_eq!(auditor.audit_new(), 0);
        assert!(auditor.verify());
        assert_eq!(auditor.entries().len(), 0);
    }

    #[test]
    fn test_auditor_incremental_idempotent() {
        let log = make_facts_log();
        let f = Fact::PayloadUpdate {
            id: FactId(1),
            path: "x".into(),
            value: JsonValue::string("y"),
        };
        log.append(f).unwrap();

        let mut auditor = Auditor::new(log);
        assert_eq!(auditor.audit_new(), 1);
        // 再次调用 audit_new,无新事实,应返回 0
        assert_eq!(auditor.audit_new(), 0);
        assert_eq!(auditor.audit_new(), 0);
        assert_eq!(auditor.entries().len(), 1);
    }

    #[test]
    fn test_auditor_causal_chain_not_found() {
        let log = make_facts_log();
        let f = Fact::PayloadUpdate {
            id: FactId(1),
            path: "x".into(),
            value: JsonValue::string("y"),
        };
        log.append(f).unwrap();

        let mut auditor = Auditor::new(log);
        auditor.audit_new();

        // 不存在的 fact_id
        let chain = auditor.causal_chain(FactId(999));
        assert!(chain.is_empty());
    }

    #[test]
    fn test_auditor_causal_chain_root() {
        let log = make_facts_log();
        let f = Fact::PayloadUpdate {
            id: FactId(1),
            path: "x".into(),
            value: JsonValue::string("y"),
        };
        let id = f.id();
        log.append(f).unwrap();

        let mut auditor = Auditor::new(log);
        auditor.audit_new();

        // 根因(没有 cause)的因果链只有自己
        let chain = auditor.causal_chain(id);
        assert_eq!(chain.len(), 1);
        assert_eq!(chain[0].fact_id, id);
        assert!(chain[0].cause.is_none());
    }

    #[test]
    fn test_auditor_report_format() {
        let log = make_facts_log();
        let f = Fact::PayloadUpdate {
            id: FactId(1),
            path: "k".into(),
            value: JsonValue::string("v"),
        };
        log.append(f).unwrap();

        let mut auditor = Auditor::new(log);
        auditor.audit_new();

        let report = auditor.report();
        let parsed: serde_json::Value = serde_json::from_str(&report).unwrap();
        assert_eq!(parsed["entry_count"], 1);
        assert_eq!(parsed["entries"].as_array().unwrap().len(), 1);
        assert!(parsed["last_hash"].is_string());
        assert!(parsed["last_audited_version"].is_number());
    }

    #[test]
    fn test_auditor_verify_empty_chain() {
        let log = make_facts_log();
        let auditor = Auditor::new(log);
        assert!(auditor.verify());
    }

    #[test]
    fn test_auditor_io_response_causal_link() {
        let log = make_facts_log();
        let req = Fact::IoRequest {
            id: FactId(10),
            cause: FactId(1),
            io_type: IoType::http_get(),
            params: JsonValue::empty_object(),
        };
        let req_id = req.id();
        log.append(req).unwrap();

        let resp = Fact::IoResponse {
            id: FactId(11),
            request_id: req_id,
            result: JsonValue::string("ok"),
            error: None,
        };
        let resp_id = resp.id();
        log.append(resp).unwrap();

        let mut auditor = Auditor::new(log);
        auditor.audit_new();

        // IoResponse 的因果父是 request_id
        let chain = auditor.causal_chain(resp_id);
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].fact_id, resp_id);
        assert_eq!(chain[1].fact_id, req_id);
    }

    #[test]
    fn test_auditor_last_hash_genesis() {
        let log = make_facts_log();
        let auditor = Auditor::new(log);
        // 初始 last_hash 为 "genesis"
        // 通过 report 间接验证
        let report = auditor.report();
        let parsed: serde_json::Value = serde_json::from_str(&report).unwrap();
        assert_eq!(parsed["last_hash"], "genesis");
    }

    #[test]
    #[allow(deprecated)]
    fn test_auditor_wal_with_invalid_lines() {
        let tmp =
            std::env::temp_dir().join(format!("auditor_wal_bad_{}.jsonl", std::process::id()));
        let _ = std::fs::remove_file(&tmp);

        // 手动写入混合有效和无效行的 WAL
        use std::io::Write;
        let mut file = std::fs::File::create(&tmp).unwrap();
        writeln!(file, "not valid json").unwrap();
        writeln!(
            file,
            r#"{{"fact_id": 5, "fact_type": "PayloadUpdate", "logical_time": 3, "content_hash": "abc", "prev_hash": "genesis", "cause": null}}"#
        )
        .unwrap();
        writeln!(file).unwrap(); // 空行
        drop(file);

        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        auditor.load_from_wal(&tmp).expect("load wal");

        // 只有 1 条有效条目
        assert_eq!(auditor.entries().len(), 1);
        assert_eq!(auditor.entries()[0].fact_id, FactId(5));
        assert_eq!(auditor.entries()[0].fact_type, "PayloadUpdate");

        let _ = std::fs::remove_file(&tmp);
    }

    // === P06 实时审计验证测试 ===

    #[test]
    fn test_auto_verify_default_disabled() {
        let log = make_facts_log();
        let auditor = Auditor::new(log);
        assert!(
            !auditor.is_auto_verify_enabled(),
            "auto_verify 默认应为 false"
        );
    }

    #[test]
    fn test_auto_verify_enabled() {
        let log = make_facts_log();
        let auditor = Auditor::new_with_auto_verify(log, true, 1000, 1);
        assert!(auditor.is_auto_verify_enabled());
    }

    #[test]
    fn test_auto_verify_runs_after_audit_new() {
        let log = make_facts_log();
        log.append(Fact::Command {
            id: FactId(1),
            instruction: JsonValue::empty_object(),
        })
        .unwrap();
        log.append(Fact::StateTransition {
            id: FactId(2),
            cause: FactId(1),
            new_payload: JsonValue::empty_object(),
            new_queue: vec![],
        })
        .unwrap();

        // 启用自动验证
        let mut auditor = Auditor::new_with_auto_verify(log, true, 1000, 1);
        let n = auditor.audit_new();
        assert_eq!(n, 2);
        // 验证审计链应通过
        assert!(auditor.verify());
    }

    #[test]
    fn test_auto_verify_threshold_skips_verification() {
        let log = make_facts_log();

        // 添加 3 条事实
        for i in 0..3 {
            log.append(Fact::Command {
                id: FactId(i as u64 + 1),
                instruction: JsonValue::empty_object(),
            })
            .unwrap();
        }

        // 设置阈值为 2(条目数 3 > 2,应跳过验证)
        let mut auditor = Auditor::new_with_auto_verify(log, true, 2, 1);
        auditor.audit_new();
        // 条目数超过阈值,但审计链本身是正确的
        assert_eq!(auditor.entries().len(), 3);
        assert!(auditor.verify()); // 手动验证仍然通过
    }

    #[test]
    fn test_auto_verify_threshold_zero_means_no_limit() {
        let log = make_facts_log();

        for i in 0..100 {
            log.append(Fact::Command {
                id: FactId(i as u64 + 1),
                instruction: JsonValue::empty_object(),
            })
            .unwrap();
        }

        // 阈值 0 表示不限制
        let mut auditor = Auditor::new_with_auto_verify(log, true, 0, 1);
        auditor.audit_new();
        assert_eq!(auditor.entries().len(), 100);
        assert!(auditor.verify());
    }

    #[test]
    fn test_auto_verify_interval_skips_intermediate_calls() {
        let log = make_facts_log();

        // 第一次 audit_new 前添加事实
        log.append(Fact::Command {
            id: FactId(1),
            instruction: JsonValue::empty_object(),
        })
        .unwrap();

        // 间隔为 3,只在第 3、6、9... 次执行验证
        let mut auditor = Auditor::new_with_auto_verify(log, true, 0, 3);
        auditor.audit_new(); // count=1,不验证
        assert_eq!(auditor.audit_new_count, 1);

        // 再添加事实
        auditor
            .facts_log
            .append(Fact::Command {
                id: FactId(2),
                instruction: JsonValue::empty_object(),
            })
            .unwrap();
        auditor.audit_new(); // count=2,不验证
        assert_eq!(auditor.audit_new_count, 2);

        // 再添加事实
        auditor
            .facts_log
            .append(Fact::Command {
                id: FactId(3),
                instruction: JsonValue::empty_object(),
            })
            .unwrap();
        auditor.audit_new(); // count=3,验证
        assert_eq!(auditor.audit_new_count, 3);
        assert_eq!(auditor.entries().len(), 3);
    }

    #[test]
    fn test_set_auto_verify_after_creation() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        assert!(!auditor.is_auto_verify_enabled());

        auditor.set_auto_verify(true, 500, 10);
        assert!(auditor.is_auto_verify_enabled());
    }

    #[test]
    fn test_auto_verify_interval_zero_becomes_one() {
        let log = make_facts_log();
        // 间隔 0 会被自动修正为 1
        let auditor = Auditor::new_with_auto_verify(log, true, 0, 0);
        // 通过行为间接验证:添加一条事实后 audit_new 应执行验证(因为间隔=1)
        drop(auditor);
    }

    #[test]
    fn test_auto_verify_empty_entries_skips() {
        let log = make_facts_log();
        // 没有 fact 时 audit_new 应返回 0 且不验证
        let mut auditor = Auditor::new_with_auto_verify(log, true, 0, 1);
        let n = auditor.audit_new();
        assert_eq!(n, 0);
        assert_eq!(auditor.entries().len(), 0);
        // verify 在空条目时返回 true(无链可验证)
        assert!(auditor.verify());
    }

    #[test]
    fn test_auto_verify_detects_corruption() {
        let log = make_facts_log();
        log.append(Fact::Command {
            id: FactId(1),
            instruction: JsonValue::empty_object(),
        })
        .unwrap();
        log.append(Fact::Command {
            id: FactId(2),
            instruction: JsonValue::empty_object(),
        })
        .unwrap();

        let mut auditor = Auditor::new_with_auto_verify(log, true, 0, 1);
        auditor.audit_new();

        // 篡改第一条审计条目的 prev_hash
        auditor.entries[0].prev_hash = "tampered".to_string();

        // verify 应检测到篡改
        assert!(!auditor.verify());
    }

    // ===== P04: 导出/导入 测试 =====

    fn build_auditor_with_entries() -> Auditor {
        let log = make_facts_log();
        let f0 = Fact::PayloadUpdate {
            id: FactId(10),
            path: "k1".into(),
            value: JsonValue::string("v1"),
        };
        let id0 = f0.id();
        log.append(f0).unwrap();

        let f1 = Fact::StateTransition {
            id: FactId(11),
            cause: id0,
            new_payload: JsonValue::empty_object(),
            new_queue: vec![],
        };
        log.append(f1).unwrap();

        let mut auditor = Auditor::new(log);
        auditor.audit_new();
        auditor
    }

    #[test]
    fn test_export_format() {
        let auditor = build_auditor_with_entries();
        let json_str = auditor.export();

        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["version"], "1.0");
        assert!(parsed["last_hash"].is_string());
        assert_eq!(parsed["last_audited_version"], 2); // 断点 11: PayloadUpdate(v1) + StateTransition(v2)
        assert_eq!(parsed["entry_count"], 2);
        assert!(parsed["entries"].is_array());
        assert_eq!(parsed["entries"].as_array().unwrap().len(), 2);

        // 检查第一个条目字段
        let e0 = &parsed["entries"][0];
        assert_eq!(e0["fact_id"], 10);
        assert_eq!(e0["fact_type"], "PayloadUpdate");
        assert_eq!(e0["prev_hash"], "genesis");
        assert!(e0["cause"].is_null());
    }

    #[test]
    fn test_export_empty_auditor() {
        let log = make_facts_log();
        let auditor = Auditor::new(log);
        let json_str = auditor.export();

        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["version"], "1.0");
        assert_eq!(parsed["entry_count"], 0);
        assert_eq!(parsed["entries"], serde_json::Value::Array(vec![]));
        assert_eq!(parsed["last_hash"], "genesis");
    }

    #[test]
    fn test_import_export_roundtrip() {
        let auditor = build_auditor_with_entries();
        let export_str = auditor.export();
        let original_verify = auditor.verify();
        assert!(original_verify);

        // 导入到新 auditor
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        let result = imported.import(&export_str);
        assert!(result.is_ok());

        // 验证数据一致性
        assert_eq!(imported.entries().len(), 2);
        assert_eq!(imported.entries()[0].fact_id, FactId(10));
        assert_eq!(imported.entries()[1].fact_id, FactId(11));
        assert_eq!(
            imported.entries()[0].content_hash,
            auditor.entries()[0].content_hash
        );
        assert_eq!(imported.entries()[0].prev_hash, "genesis");
        assert_eq!(imported.last_hash, auditor.last_hash);
        assert_eq!(imported.last_audited_version, auditor.last_audited_version);

        // 导入后哈希链应保持完整
        assert!(imported.verify());
    }

    #[test]
    fn test_import_version_check() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        let bad_version = r#"{"version": "2.0", "entries": []}"#;
        let result = auditor.import(bad_version);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Unsupported version"));
    }

    #[test]
    fn test_import_missing_version() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        let no_version = r#"{"entries": []}"#;
        let result = auditor.import(no_version);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("version"));
    }

    #[test]
    fn test_import_missing_entries() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        let no_entries = r#"{"version": "1.0"}"#;
        let result = auditor.import(no_entries);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("entries"));
    }

    #[test]
    fn test_import_invalid_json() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        let result = auditor.import("not a valid json {{{");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("JSON parse error"));
    }

    #[test]
    fn test_import_unknown_fact_type_becomes_unknown() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        // 构造包含未知 fact_type 的导入数据
        let import_data = r#"{
            "version": "1.0",
            "last_hash": "anyhash",
            "last_audited_version": 1,
            "entries": [
                {
                    "fact_id": 99,
                    "fact_type": "SomeUnknownType",
                    "logical_time": 5,
                    "content_hash": "abc",
                    "prev_hash": "genesis",
                    "cause": null
                }
            ]
        }"#;

        let result = auditor.import(import_data);
        assert!(result.is_ok());
        assert_eq!(auditor.entries().len(), 1);
        assert_eq!(auditor.entries()[0].fact_type, "Unknown");
        assert_eq!(auditor.entries()[0].fact_id, FactId(99));
    }

    #[test]
    fn test_import_resets_state() {
        // 原审计器有 2 个条目
        let mut auditor = build_auditor_with_entries();
        assert_eq!(auditor.entries().len(), 2);

        // 导入空数据
        let empty_export = r#"{
            "version": "1.0",
            "last_hash": "genesis",
            "last_audited_version": 0,
            "entries": []
        }"#;
        let result = auditor.import(empty_export);
        assert!(result.is_ok());
        assert_eq!(auditor.entries().len(), 0);
        assert_eq!(auditor.last_hash, "genesis");
        assert_eq!(auditor.last_audited_version, 0);
    }

    #[test]
    fn test_import_and_verify_detects_corruption() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        // 构造 prev_hash 不连续的损坏数据
        let corrupted = r#"{
            "version": "1.0",
            "last_hash": "fakehash",
            "last_audited_version": 1,
            "entries": [
                {
                    "fact_id": 1,
                    "fact_type": "Command",
                    "logical_time": 1,
                    "content_hash": "hash1",
                    "prev_hash": "genesis",
                    "cause": null
                },
                {
                    "fact_id": 2,
                    "fact_type": "Command",
                    "logical_time": 2,
                    "content_hash": "hash2",
                    "prev_hash": "WRONG_PREV_HASH",
                    "cause": null
                }
            ]
        }"#;

        let result = auditor.import_and_verify(corrupted);
        assert!(result.is_ok());
        // 导入成功但验证应失败
        assert!(!result.unwrap());
    }

    #[test]
    fn test_import_preserves_causal_chain() {
        let auditor = build_auditor_with_entries();
        let export_str = auditor.export();

        // 验证原审计器的因果链
        let original_chain = auditor.causal_chain(FactId(11));
        assert_eq!(original_chain.len(), 2);

        // 导入到新审计器
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        imported.import(&export_str).unwrap();

        // 因果链应可正确追溯
        let chain = imported.causal_chain(FactId(11));
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].fact_id, FactId(11));
        assert_eq!(chain[1].fact_id, FactId(10));
    }

    #[test]
    fn test_import_resets_audit_new_count() {
        // 原审计器已多次调用 audit_new,计数 > 0
        let mut auditor = build_auditor_with_entries();
        auditor.audit_new(); // 再次调用,count = 2
        assert_eq!(auditor.audit_new_count, 2);

        // 导入应重置 audit_new_count
        let export_str = auditor.export();
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        imported.import(&export_str).unwrap();
        assert_eq!(imported.audit_new_count, 0);
    }

    // ===== P05: 压缩导出/导入 测试 =====

    #[test]
    fn test_export_compressed_returns_valid_gzip() {
        let auditor = build_auditor_with_entries();
        let compressed = auditor.export_compressed().unwrap();

        // gzip magic number: 0x1f 0x8b
        assert!(compressed.len() >= 2);
        assert_eq!(compressed[0], 0x1f);
        assert_eq!(compressed[1], 0x8b);
    }

    #[test]
    fn test_export_compressed_smaller_than_json() {
        // 构造较大的审计链(100 条目)
        let log = make_facts_log();
        for i in 0..100 {
            log.append(Fact::Command {
                id: FactId(i as u64 + 1),
                instruction: JsonValue::empty_object(),
            })
            .unwrap();
        }
        let mut auditor = Auditor::new(log);
        auditor.audit_new();

        let json_size = auditor.export().len();
        let compressed = auditor.export_compressed().unwrap();
        let compressed_size = compressed.len();

        // 压缩后应明显小于 JSON(通常 < 30%)
        // 由于 fact_type 等字段重复度高,压缩率应很好
        assert!(
            compressed_size < json_size,
            "compressed {} should be < json {}",
            compressed_size,
            json_size
        );
        // 压缩率至少应小于 50%
        let ratio = compressed_size as f64 / json_size as f64;
        assert!(ratio < 0.5, "compression ratio {} should be < 0.5", ratio);
    }

    #[test]
    fn test_import_compressed_roundtrip() {
        let auditor = build_auditor_with_entries();
        let compressed = auditor.export_compressed().unwrap();
        let original_verify = auditor.verify();
        assert!(original_verify);

        // 解压并导入到新 auditor
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        let result = imported.import_compressed(&compressed);
        assert!(result.is_ok());

        // 验证数据一致性
        assert_eq!(imported.entries().len(), 2);
        assert_eq!(imported.entries()[0].fact_id, FactId(10));
        assert_eq!(imported.entries()[1].fact_id, FactId(11));
        assert_eq!(imported.entries()[0].prev_hash, "genesis");
        assert_eq!(imported.last_hash, auditor.last_hash);

        // 导入后哈希链应保持完整
        assert!(imported.verify());
    }

    #[test]
    fn test_import_compressed_invalid_gzip() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        // 非 gzip 数据应返回错误
        let bad_data = b"this is not gzip data at all";
        let result = auditor.import_compressed(bad_data);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Decompression error"));
    }

    #[test]
    fn test_import_compressed_empty_data() {
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);

        // 空数据应返回错误
        let result = auditor.import_compressed(&[]);
        assert!(result.is_err());
    }

    #[test]
    fn test_import_compressed_and_verify_detects_corruption() {
        // 构造损坏的 JSON 数据(prev_hash 不连续)
        let corrupted_json = r#"{
            "version": "1.0",
            "last_hash": "fakehash",
            "last_audited_version": 1,
            "entries": [
                {
                    "fact_id": 1,
                    "fact_type": "Command",
                    "logical_time": 1,
                    "content_hash": "hash1",
                    "prev_hash": "genesis",
                    "cause": null
                },
                {
                    "fact_id": 2,
                    "fact_type": "Command",
                    "logical_time": 2,
                    "content_hash": "hash2",
                    "prev_hash": "WRONG",
                    "cause": null
                }
            ]
        }"#;

        // 先压缩损坏的 JSON
        use flate2::write::GzEncoder;
        use flate2::Compression;
        use std::io::Write;
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(corrupted_json.as_bytes()).unwrap();
        let corrupted_compressed = encoder.finish().unwrap();

        // 导入并验证应返回 Ok(false)
        let log = make_facts_log();
        let mut auditor = Auditor::new(log);
        let result = auditor.import_compressed_and_verify(&corrupted_compressed);
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[test]
    fn test_export_compressed_empty_auditor() {
        let log = make_facts_log();
        let auditor = Auditor::new(log);
        let compressed = auditor.export_compressed().unwrap();

        // 空审计器也能正常压缩(gzip 头 + 空 entries 数组)
        assert!(!compressed.is_empty());

        // 解压后应为有效 JSON
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        imported.import_compressed(&compressed).unwrap();
        assert_eq!(imported.entries().len(), 0);
        assert_eq!(imported.last_hash, "genesis");
    }

    #[test]
    fn test_compressed_preserves_causal_chain() {
        let auditor = build_auditor_with_entries();
        let compressed = auditor.export_compressed().unwrap();

        // 导入到新审计器
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        imported.import_compressed(&compressed).unwrap();

        // 因果链应可正确追溯
        let chain = imported.causal_chain(FactId(11));
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].fact_id, FactId(11));
        assert_eq!(chain[1].fact_id, FactId(10));
    }

    #[test]
    fn test_compressed_roundtrip_large_chain() {
        // 大批量数据的压缩/解压往返测试
        // 构造真实因果链:Fact1 → Fact2 → ... → Fact501(IoRequest 链)
        let log = make_facts_log();

        // 第 1 个:PayloadUpdate(根,无 cause)
        log.append(Fact::PayloadUpdate {
            id: FactId(1),
            path: "root".into(),
            value: JsonValue::from(0i64),
        })
        .unwrap();

        // 第 2..501:IoRequest 链,每个 cause 指向上一个
        for i in 1..500 {
            log.append(Fact::IoRequest {
                id: FactId(i as u64 + 1),
                cause: FactId(i as u64),
                io_type: evorule_reactor::IoType::http_get(),
                params: JsonValue::empty_object(),
            })
            .unwrap();
        }

        let mut auditor = Auditor::new(log);
        auditor.audit_new();
        assert_eq!(auditor.entries().len(), 500);

        // 压缩 → 解压 → 导入
        let compressed = auditor.export_compressed().unwrap();
        let log2 = make_facts_log();
        let mut imported = Auditor::new(log2);
        imported.import_compressed(&compressed).unwrap();

        // 验证数据完整
        assert_eq!(imported.entries().len(), 500);
        assert!(imported.verify());

        // 因果链应可从末尾追溯到根(长度 500)
        let chain = imported.causal_chain(FactId(500));
        assert_eq!(chain.len(), 500);
        assert_eq!(chain[0].fact_id, FactId(500)); // 末尾
        assert_eq!(chain[499].fact_id, FactId(1)); //    }
}