hirn-core 0.1.0

Core types for the hirn cognitive memory database
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::HirnError;
use crate::offline::OfflineSchedulerConfig;
use crate::resource::{
    DerivedArtifactIndexPolicy, ResourceIndexPolicy, ResourceQuotaPolicy, ResourceRetentionPolicy,
};
use crate::types::Namespace;

/// Helper macro: generates a `#[derive(Deserialize)] #[serde(default)]` mirror
/// struct with identical fields, a blanket `Default` delegation, and a
/// `TryFrom` that moves every field into `HirnConfig` then validates.
///
/// **Why?** Serde's `try_from` attribute is the only way to run validation on
/// every deserialization path (TOML, JSON, env-vars, …). This macro ensures
/// the field list is written **once** — adding a new config field is a
/// single-site change in the `hirn_config_fields!` invocation below.
macro_rules! hirn_config_fields {
    (
        $(
            $( #[doc = $doc:literal] )*
            pub $field:ident : $ty:ty,
        )*
    ) => {
        /// Database configuration with production-ready defaults.
        ///
        /// Deserialization automatically runs [`HirnConfig::validate`], so loading
        /// an invalid config from TOML/JSON is a hard error.
        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(try_from = "RawHirnConfig")]
        pub struct HirnConfig {
            $(
                $( #[doc = $doc] )*
                pub $field : $ty,
            )*
        }

        /// Private deserialization target — generated by `hirn_config_fields!`.
        /// Uses `#[serde(default)]` at the struct level so every missing field
        /// falls back to `HirnConfig::default()`.
        #[derive(Deserialize)]
        #[serde(default)]
        struct RawHirnConfig {
            $( $field : $ty, )*
        }

        impl Default for RawHirnConfig {
            fn default() -> Self {
                let d = HirnConfig::default();
                Self {
                    $( $field: d.$field, )*
                }
            }
        }

        impl TryFrom<RawHirnConfig> for HirnConfig {
            type Error = HirnError;
            fn try_from(raw: RawHirnConfig) -> Result<Self, Self::Error> {
                let config = Self {
                    $( $field: raw.$field, )*
                };
                config.validate()?;
                Ok(config)
            }
        }
    };
}

/// Controls how much raw text is retained after indexing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextRetention {
    /// Keep full content and summary (default).
    #[default]
    Full,
    /// Discard raw content after indexing; keep only the summary.
    SummaryOnly,
    /// Discard all text after indexing; keep only embeddings.
    None,
}

/// The distance metric used for vector comparisons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DistanceMetric {
    /// Cosine similarity (1 - cos(a,b)). Smaller = more similar.
    #[default]
    Cosine,
    /// Negative dot product (-a·b). Smaller = more similar.
    DotProduct,
    /// Squared Euclidean distance. Smaller = more similar.
    #[serde(rename = "l2")]
    L2,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct EmbedderRuntimeConfig {
    /// Optional outer batching wrapper size. `None` disables batching.
    pub batch_size: Option<usize>,
    /// Optional retry wrapper configuration.
    pub retry: Option<EmbedderRetryConfig>,
    /// Optional circuit-breaker wrapper configuration.
    pub circuit_breaker: Option<EmbedderCircuitBreakerRuntimeConfig>,
    /// Optional persistent cache wrapper configuration.
    pub persistent_cache: Option<EmbedderPersistentCacheRuntimeConfig>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbedderRetryConfig {
    /// Maximum retries after the initial attempt.
    pub max_retries: u32,
    /// Base exponential backoff in milliseconds.
    pub base_backoff_ms: u64,
    /// Maximum wall-clock retry budget in milliseconds.
    pub max_cumulative_timeout_ms: u64,
}

impl Default for EmbedderRetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            base_backoff_ms: 500,
            max_cumulative_timeout_ms: 10_000,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbedderCircuitBreakerRuntimeConfig {
    /// Consecutive failures required to open the breaker.
    pub failure_threshold: u32,
    /// Time to wait before allowing a recovery probe.
    pub recovery_timeout_ms: u64,
    /// Consecutive successes required to close after probing.
    pub success_threshold: u32,
}

impl Default for EmbedderCircuitBreakerRuntimeConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            recovery_timeout_ms: 30_000,
            success_threshold: 2,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbedderPersistentCacheRuntimeConfig {
    /// Maximum L1 in-memory entries to retain in the persistent cache wrapper.
    pub max_memory_entries: usize,
}

impl Default for EmbedderPersistentCacheRuntimeConfig {
    fn default() -> Self {
        Self {
            max_memory_entries: 10_000,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ConflictResolutionPolicy {
    /// Weight applied to revision recency when preferring a visible active claim.
    pub recency_weight: f32,
    /// Weight applied to source reliability when preferring a visible active claim.
    pub source_reliability_weight: f32,
    /// Weight applied to contradiction-edge support when preferring a visible active claim.
    pub supporting_evidence_weight: f32,
    /// Weight applied to explicit human/admin override revisions.
    pub human_override_weight: f32,
    /// When true, any explicit human/admin override outranks automatic arbitration.
    pub prefer_human_override: bool,
}

impl Default for ConflictResolutionPolicy {
    fn default() -> Self {
        Self {
            recency_weight: 0.20,
            source_reliability_weight: 0.35,
            supporting_evidence_weight: 0.30,
            human_override_weight: 0.15,
            prefer_human_override: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ConflictResolutionPolicyOverrides {
    /// Realm-scoped policy overrides keyed by realm name.
    pub by_realm: HashMap<String, ConflictResolutionPolicy>,
    /// Namespace-scoped policy overrides keyed by namespace identifier.
    pub by_namespace: HashMap<String, ConflictResolutionPolicy>,
}

const MAX_CONSOLIDATION_CAUSAL_WINDOW: usize = 10_000;

/// Controls whether and how hirn performs A-MEM–style backward memory evolution:
/// when a new memory arrives, top-k related historical memories are enriched with
/// a context note derived from the newcomer's perspective.
///
/// Async mode enqueues a `CognitiveJobKind::Evolve` offline job (non-blocking).
/// Synchronous mode performs evolution in the write critical path (expensive).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case", tag = "mode")]
pub enum EvolutionMode {
    /// Backward evolution disabled (default). No additional writes at ingest.
    #[default]
    None,
    /// Enqueue an offline `Evolve` job after each write (recommended for production).
    Async {
        /// Maximum number of historical neighbors to evolve per new memory. Default: 5.
        max_neighbors: usize,
    },
    /// Perform evolution synchronously in the write critical path.
    /// Use only when write latency is acceptable (e.g., background batch import).
    Synchronous {
        /// Maximum number of historical neighbors to evolve per new memory. Default: 3.
        max_neighbors: usize,
    },
}

hirn_config_fields! {
    /// Path to the database file.
    pub db_path: PathBuf,

    /// Maximum token budget for working memory.
    pub working_memory_token_limit: u32,

    /// Fraction of total token budget reserved for working memory (0.0–1.0).
    pub working_memory_reserve: f32,

    /// Recency decay constant λ (higher = faster decay).
    pub decay_lambda: f64,

    /// Importance threshold below which episodic records are archived.
    pub archive_threshold: f32,

    /// Importance threshold below which archived records are purged.
    pub purge_threshold: f32,

    /// Maximum number of episodic entries to retrieve in a single query.
    pub max_episodic_entries: u32,

    /// Hebbian learning rate η.
    pub hebbian_learning_rate: f64,

    /// Hebbian disuse decay rate `λ_decay`.
    pub hebbian_decay_rate: f64,

    /// Default total token budget for context assembly.
    pub token_budget: u32,

    /// Maximum preview artifacts packaged per record on RECALL JSON surfaces.
    pub recall_preview_package_max_previews: usize,

    /// Maximum characters retained from each packaged RECALL preview artifact.
    pub recall_preview_package_max_chars: usize,

    /// Maximum preview artifacts considered per record during preview-aware recall reranking.
    pub recall_preview_rerank_max_previews: usize,

    /// Maximum characters retained from each preview artifact during recall reranking.
    pub recall_preview_rerank_max_chars: usize,

    /// Maximum preview artifacts packaged per entry on THINK JSON surfaces.
    pub think_preview_package_max_previews: usize,

    /// Maximum characters retained from each packaged THINK preview artifact.
    pub think_preview_package_max_chars: usize,

    // ── HNSW vector index ────────────────────────────────────────────────
    /// HNSW M parameter (max bi-directional connections per layer). Default: 16.
    pub hnsw_m: usize,

    /// HNSW `ef_construction` (build-time search width). Default: 200.
    pub hnsw_ef_construction: usize,

    /// HNSW `ef_search` (query-time search width). Default: 50.
    pub hnsw_ef_search: usize,

    /// Expected embedding dimensionality. Default: 768.
    pub embedding_dimensions: crate::EmbeddingDimension,

    /// Allow the high-level HirnMemory facade to use pseudo embeddings when
    /// no real embedder is configured from the environment. Default: false.
    pub allow_pseudo_embedder_fallback: bool,

    /// Optional runtime wrapper composition for the active embedder.
    pub embedder_runtime: EmbedderRuntimeConfig,

    /// Distance metric for vector comparisons. Default: Cosine.
    pub metric: DistanceMetric,

    // ── Composite scoring weights (must sum to 1.0) ─────────────────────
    /// Weight for similarity in composite scoring (α).
    pub scoring_similarity_weight: f32,

    /// Weight for importance in composite scoring (β).
    pub scoring_importance_weight: f32,

    /// Weight for recency in composite scoring (γ).
    pub scoring_recency_weight: f32,

    /// Weight for activation in composite scoring (δ).
    pub scoring_activation_weight: f32,

    /// Weight for causal relevance in composite scoring (ε).
    pub scoring_causal_relevance_weight: f32,

    /// Weight for surprise in composite scoring (ζ).
    pub scoring_surprise_weight: f32,

    /// Weight for source reliability in composite scoring (η).
    pub scoring_source_reliability_weight: f32,

    // ── Graph / Activation ──────────────────────────────────────────────
    /// Spreading activation depth decay factor d (default 0.7).
    pub activation_decay_factor: f64,

    /// Maximum spreading activation traversal depth (default 3).
    pub activation_max_depth: usize,

    /// Convergence threshold ε — nodes below this excluded (default 0.01).
    pub activation_convergence_threshold: f64,

    /// Maximum propagation iterations (default 10).
    pub activation_max_iterations: usize,

    /// Lateral inhibition strength μ (default 0.1). 0.0 disables.
    pub inhibition_strength: f64,

    /// Hard safety cap on spreading activation frontier size per depth level (default 10,000).
    /// Prevents OOM/DoS from high-degree hub nodes (F-ENG-01).
    pub activation_max_frontier_size: usize,

    /// Similarity threshold for automatic `SimilarTo` edge creation (default 0.85).
    pub similarity_edge_threshold: f32,

    /// Max auto-created edges per record (default 10).
    pub max_auto_edges_per_record: usize,

    /// Minimum shared entities required for automatic `RelatedTo` edge creation (default 2).
    pub entity_overlap_threshold: usize,

    /// Depth threshold for delegating graph traversal to the cold (Lance) tier.
    /// When a causal chain or BFS traversal exceeds this depth, the engine
    /// switches from in-memory PropertyGraph DFS to batched Lance scans.
    /// Default: 5.
    pub graph_depth_delegation_threshold: usize,

    /// Epsilon (convergence threshold) for spreading-activation PageRank / BFS in
    /// `GraphActivationExec`. Iteration stops when the maximum score delta falls
    /// below this value. Default: 0.001.
    ///
    /// N-M13: previously hardcoded in `HirnExtensionPlanner`.
    pub graph_activation_epsilon: f32,

    /// Lateral inhibition µ weight for `GraphActivationExec` (SYNAPSE inhibition).
    /// Default: 0.5.
    ///
    /// N-M13: previously hardcoded in `HirnExtensionPlanner`.
    pub graph_activation_inhibition_mu: f32,

    /// Minimum causal confidence threshold for `CausalChainExec`.
    /// Edges with confidence below this value are excluded from causal chains.
    /// Default: 0.3.
    ///
    /// N-M13: previously hardcoded in `HirnExtensionPlanner`.
    pub causal_min_confidence: f32,

    /// Default context-budget token limit used by `QualityGateExec` when the
    /// HirnQL statement does not specify a LIMIT clause. Default: 4096.
    ///
    /// N-M13: previously hardcoded in `HirnExtensionPlanner`.
    pub default_token_budget: usize,

    // ── Consolidation scheduling ────────────────────────────────────────
    /// Periodic consolidation interval in seconds (0 = disabled). Default: 3600 (1 hour).
    pub consolidation_interval_secs: u64,

    /// Maximum number of episodes to consider in causal discovery during consolidation.
    /// 0 = use entire consolidation batch (no limit). Values above 10,000 are rejected
    /// as a safety guard against pathological discovery scans. Default: 100.
    pub consolidation_causal_window: usize,

    /// Reconsolidation labile window in seconds after recall (0 = disabled). Default: 3600 (1 hour).
    ///
    /// Neuroscience evidence places the labile window at hours-to-days, not minutes.
    /// At 5 minutes (the former default) memories stabilise faster than a single
    /// LLM agent session can span, preventing correction of recently-stored false
    /// beliefs. Set to 0 to disable reconsolidation (useful in low-latency settings).
    pub reconsolidation_window_secs: u64,

    // ── Compaction scheduling ───────────────────────────────────────────
    /// Periodic compaction interval in seconds (0 = manual only). Default: 3600 (1 hour).
    pub compaction_interval_secs: u64,

    /// Minimum Lance fragment count before compaction runs (0 = always compact). Default: 0.
    pub compaction_fragment_threshold: u32,

    // ── Admission Control ───────────────────────────────────────────────
    /// Enable admission control pipeline. Default: false.
    pub admission_enabled: bool,

    /// Surprise gate threshold (cosine distance). Default: 0.3.
    pub admission_surprise_threshold: f32,

    /// Duplicate detector similarity threshold. Default: 0.95.
    pub admission_duplicate_threshold: f32,

    /// Duplicate detector action: "reject" or "merge". Default: "reject".
    pub admission_duplicate_action: String,

    /// Per-agent token budget for the token budget gate. Default: `500_000`.
    pub admission_token_budget_limit: u64,

    /// Rate limiter: max writes per minute per agent. Default: 100.
    pub admission_rate_limit: u32,

    // ── RPE-Gated Admission ─────────────────────────────────────────────

    /// Enable RPE-gated fast/slow path routing. Default: false.
    /// When enabled, incoming memories are scored by reward prediction error.
    /// RPE < threshold → fast path (skip LLM analysis, prospective indexing, SVO).
    pub rpe_enabled: bool,

    /// RPE threshold for fast-path admission. Default: 0.3 (from D-MEM §4.2).
    /// Memories with RPE below this skip LLM analysis.
    pub rpe_fast_path_threshold: f32,

    /// Number of nearest neighbors to check for RPE similarity. Default: 5.
    pub rpe_similarity_search_limit: usize,

    // ── Prospective Indexing ────────────────────────────────────────────

    /// Enable prospective indexing (future query generation at write time). Default: false.
    pub prospective_indexing_enabled: bool,

    /// Number of future questions to generate per memory. Default: 5.
    pub prospective_indexing_num_questions: usize,

    /// Timeout in seconds for prospective indexing. Default: 5.
    pub prospective_indexing_timeout_secs: u64,

    /// Template strings for prospective question generation.
    /// Every non-empty template must contain the `{content}` placeholder for
    /// truncated memory content.
    /// Default: 5 heuristic templates (what/when/who/outcome/why).
    pub prospective_indexing_templates: Vec<String>,

    // ── SVO Extraction ──────────────────────────────────────────────────

    /// Enable SVO (Subject-Verb-Object) event extraction. Default: false.
    pub svo_extraction_enabled: bool,

    /// Minimum confidence for SVO events. Default: 0.5.
    pub svo_confidence_threshold: f32,

    /// LLM prompt template for SVO extraction. Must contain `{content}` placeholder.
    /// When set and an LLM provider is available, SVO extraction uses the LLM instead
    /// of regex fallback. Default: built-in prompt.
    pub svo_extraction_prompt: String,

    // ── Interference-Driven Consolidation ───────────────────────────────

    /// Cumulative interference threshold to trigger consolidation. Default: 0.3.
    /// When cumulative interference across recent writes exceeds this, consolidation fires.
    pub interference_consolidation_threshold: f32,

    /// Minimum seconds between interference-triggered consolidations. Default: 300 (5 min).
    pub interference_consolidation_cooldown_secs: u64,

    // ── Multivector / ColBERT ───────────────────────────────────────────

    /// Enable multivector (ColBERT-style) retrieval. Default: false.
    pub multivector_enabled: bool,

    /// Weight for blending multivector `MaxSim` score into composite scoring (0.0–1.0). Default: 0.0.
    pub multivector_weight: f32,

    // ── Predictive Prefetch ─────────────────────────────────────────────

    /// Enable predictive prefetch after recall. Default: false.
    pub prefetch_enabled: bool,

    /// BFS depth for graph neighbor discovery during prefetch. Default: 2.
    pub prefetch_activation_depth: usize,

    /// Minimum edge weight to traverse during prefetch. Default: 0.1.
    pub prefetch_min_edge_weight: f32,

    /// Maximum bytes to prefetch per recall (approximate). Default: 10 MB.
    pub prefetch_max_bytes: u64,

    /// Cooldown in seconds: skip re-prefetching recently prefetched nodes. Default: 300.
    pub prefetch_cooldown_secs: u64,

    // ── Cedar Policy Engine ─────────────────────────────────────────────

    /// Default realm for Cedar policy evaluation. Default: "default".
    pub default_realm: String,

    /// Default policy for grouped contradiction arbitration.
    pub conflict_resolution_policy: ConflictResolutionPolicy,

    /// Optional realm- and namespace-scoped overrides for contradiction arbitration.
    pub conflict_resolution_overrides: ConflictResolutionPolicyOverrides,

    // ── Query Diagnostics ────────────────────────────────────────────────

    /// Slow query threshold in milliseconds. Queries exceeding this duration
    /// are logged with full plan and context. Default: 100ms. 0 = disabled.
    pub slow_query_threshold_ms: u64,

    // ── Quality Gate ─────────────────────────────────────────────────────

    /// Quality gate threshold for auto-escalation. Default: 0.5.
    /// Queries scoring below this on the 4-dimension quality metric (coverage,
    /// confidence, coherence, sufficiency) will be re-run at a higher depth.
    pub quality_gate_threshold: f32,

    /// NLI contradiction probability threshold. Default: 0.7.
    /// Pairs with contradiction score above this are flagged as contradictions.
    pub nli_contradiction_threshold: f32,

    // ── Data Retention ──────────────────────────────────────────────────

    /// How much raw text to retain after indexing. Default: "full".
    pub text_retention: TextRetention,

    /// Operator-triggered retention rules for first-class resources.
    pub resource_retention_policy: ResourceRetentionPolicy,

    /// Operator-triggered quota rules for first-class resources.
    pub resource_quota_policy: ResourceQuotaPolicy,

    /// Additional modality-scoped secondary indices for the `resources` dataset.
    pub resource_index_policy: ResourceIndexPolicy,

    /// Additional artifact-kind-scoped secondary indices for the `derived_artifacts` dataset.
    pub derived_artifact_index_policy: DerivedArtifactIndexPolicy,

    // ── Offline Intelligence ─────────────────────────────────────────────

    /// Scheduler configuration for queued offline cognition jobs.
    pub offline_scheduler: OfflineSchedulerConfig,

    /// Minimum quality score required before dream hypotheses can be promoted.
    pub offline_dream_quality_threshold: f32,

    /// Minimum quality score required before reconcile proposals can be promoted.
    pub offline_reconcile_quality_threshold: f32,

    /// Minimum quality score required before planning agendas can be promoted.
    pub offline_plan_quality_threshold: f32,

    // ── Backward Memory Evolution (A-MEM) ────────────────────────────────

    /// Controls A-MEM–style backward evolution of historical memories.
    /// When a new memory arrives, top-k related existing memories are enriched
    /// with a context note derived from the newcomer's perspective.
    /// Default: `EvolutionMode::None` (disabled).
    pub evolution_mode: EvolutionMode,

    // ── FadeMem offline decay sweep ──────────────────────────────────────

    /// Interval in seconds between `CognitiveJobKind::Decay` sweeps (0 = disabled).
    ///
    /// When non-zero, the offline scheduler enqueues a `Decay` job at this
    /// interval. The job batch-scans all episodic and semantic memories that
    /// have not been accessed within `decay_sweep_window_secs` and applies
    /// the FadeMem adaptive decay formula to their `importance` column.
    ///
    /// Default: 0 (disabled). Recommended for long-running deployments: 3600 (1 hour).
    pub decay_interval_secs: u64,

    /// Look-back window for the decay sweep in seconds.
    ///
    /// Only memories with `last_accessed_ms < now - decay_sweep_window_secs`
    /// are touched by the decay job. Memories accessed more recently than this
    /// threshold are considered active and are skipped.
    ///
    /// Default: 86400 (24 hours). Tune alongside `memory_half_life_hours`.
    pub decay_sweep_window_secs: u64,

    // ── Execution Resource Limits ────────────────────────────────────────

    /// Memory limit in bytes for DataFusion execution (0 = unlimited). Default: 0.
    /// When set, DataFusion will spill to disk if this limit is exceeded.
    pub execution_memory_limit_bytes: u64,

    /// Maximum number of parallel threads for DataFusion execution (0 = auto-detect).
    /// Default: 0 (uses all available cores).
    pub execution_parallelism: usize,

    // ── Memory Decay & TTL ──────────────────────

    /// Base decay factor per half-life period. Default: 0.95.
    /// Formula: `importance *= decay_factor ^ (hours_since_last_access / half_life_hours)`.
    pub memory_decay_factor: f32,

    /// Half-life in hours for decay calculation. Default: 168 (one week).
    pub memory_half_life_hours: u64,

    /// Minimum importance threshold. Records decayed below this are archived. Default: 0.01.
    pub memory_min_importance: f32,

    // ── Tier Transition Policies ────────────────────────────────────────

    /// Working memory auto-promotion TTL in seconds (0 = disabled). Default: 0.
    pub tier_working_to_episodic_ttl_secs: u64,

    /// Consolidation threshold score for episodic → semantic promotion. Default: 0.7.
    pub tier_episodic_to_semantic_threshold: f32,

    /// Archive threshold for semantic memories. Default: 0.1.
    pub tier_semantic_archive_threshold: f32,

    /// Minimum EMA success rate to retain procedural memories. Default: 0.3.
    pub tier_procedural_min_success_rate: f32,

    // ── Audit Integrity ─────────────────────────────────────────────────

    /// Optional HMAC signing secret for tamper-evident event log integrity.
    ///
    /// When set, all events appended through the event log are signed with a
    /// blake3 keyed hash derived from this secret. Auditors can later verify
    /// entries to detect tampering.
    ///
    /// **Minimum length: 32 bytes (UTF-8).** Shorter secrets are rejected by
    /// `HirnConfig::validate()` with `InvalidConfig`.
    ///
    /// Provide a cryptographically random 32+ byte value; do not use
    /// human-memorable passwords. In production, inject via environment
    /// variable rather than committing to config files.
    pub event_hmac_secret: Option<String>,
}

/// Runtime-mutable tier transition policy.
///
/// Initialized from [`HirnConfig`] at startup.
/// Updated at runtime via `SET TIER_POLICY` HirnQL statements.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TierPolicy {
    /// Working memory auto-promotion TTL in seconds (0 = disabled).
    pub working_to_episodic_ttl_secs: u64,
    /// Consolidation threshold score for episodic → semantic promotion.
    pub episodic_to_semantic_threshold: f32,
    /// Archive threshold for semantic memories.
    pub semantic_archive_threshold: f32,
    /// Minimum EMA success rate to retain procedural memories.
    pub procedural_min_success_rate: f32,
}

impl TierPolicy {
    /// Create a `TierPolicy` from the corresponding fields in [`HirnConfig`].
    #[must_use]
    pub fn from_config(cfg: &HirnConfig) -> Self {
        Self {
            working_to_episodic_ttl_secs: cfg.tier_working_to_episodic_ttl_secs,
            episodic_to_semantic_threshold: cfg.tier_episodic_to_semantic_threshold,
            semantic_archive_threshold: cfg.tier_semantic_archive_threshold,
            procedural_min_success_rate: cfg.tier_procedural_min_success_rate,
        }
    }
}

impl Default for TierPolicy {
    fn default() -> Self {
        Self {
            working_to_episodic_ttl_secs: 0,
            episodic_to_semantic_threshold: 0.7,
            semantic_archive_threshold: 0.1,
            procedural_min_success_rate: 0.3,
        }
    }
}

impl Default for HirnConfig {
    fn default() -> Self {
        Self {
            db_path: PathBuf::from("brain"),
            working_memory_token_limit: 2048,
            working_memory_reserve: 0.2,
            decay_lambda: 0.01, // ~7-day half-life
            archive_threshold: 0.1,
            purge_threshold: 0.01,
            max_episodic_entries: 100,
            hebbian_learning_rate: 0.1,
            hebbian_decay_rate: 0.05,
            token_budget: 4096,
            recall_preview_package_max_previews: 1,
            recall_preview_package_max_chars: 160,
            recall_preview_rerank_max_previews: 2,
            recall_preview_rerank_max_chars: 240,
            think_preview_package_max_previews: 1,
            think_preview_package_max_chars: 160,
            hnsw_m: 16,
            hnsw_ef_construction: 200,
            hnsw_ef_search: 50,
            embedding_dimensions: crate::EmbeddingDimension::new_const(768),
            allow_pseudo_embedder_fallback: false,
            embedder_runtime: EmbedderRuntimeConfig::default(),
            metric: DistanceMetric::Cosine,
            scoring_similarity_weight: 0.30,
            scoring_importance_weight: 0.20,
            scoring_recency_weight: 0.20,
            scoring_activation_weight: 0.10,
            scoring_causal_relevance_weight: 0.05,
            scoring_surprise_weight: 0.10,
            scoring_source_reliability_weight: 0.05,
            activation_decay_factor: 0.7,
            activation_max_depth: 3,
            activation_convergence_threshold: 0.01,
            activation_max_iterations: 10,
            inhibition_strength: 0.1,
            activation_max_frontier_size: 10_000,
            similarity_edge_threshold: 0.85,
            max_auto_edges_per_record: 10,
            entity_overlap_threshold: 2,
            graph_depth_delegation_threshold: 5,
            graph_activation_epsilon: 0.001,
            graph_activation_inhibition_mu: 0.5,
            causal_min_confidence: 0.3,
            default_token_budget: 4096,
            consolidation_interval_secs: 3600,
            consolidation_causal_window: 100,
            reconsolidation_window_secs: 3600,
            compaction_interval_secs: 3600,
            compaction_fragment_threshold: 0,
            admission_enabled: false,
            admission_surprise_threshold: default_surprise_threshold(),
            admission_duplicate_threshold: default_duplicate_threshold(),
            admission_duplicate_action: default_duplicate_action(),
            admission_token_budget_limit: default_token_budget_limit(),
            admission_rate_limit: default_rate_limit(),
            rpe_enabled: false,
            rpe_fast_path_threshold: 0.3,
            rpe_similarity_search_limit: 5,
            prospective_indexing_enabled: false,
            prospective_indexing_num_questions: 5,
            prospective_indexing_timeout_secs: 5,
            prospective_indexing_templates: default_prospective_templates(),
            svo_extraction_enabled: false,
            svo_confidence_threshold: 0.5,
            svo_extraction_prompt: default_svo_extraction_prompt(),
            interference_consolidation_threshold: 0.3,
            interference_consolidation_cooldown_secs: 300,
            multivector_enabled: false,
            multivector_weight: 0.0,
            prefetch_enabled: false,
            prefetch_activation_depth: default_prefetch_activation_depth(),
            prefetch_min_edge_weight: default_prefetch_min_edge_weight(),
            prefetch_max_bytes: default_prefetch_max_bytes(),
            prefetch_cooldown_secs: default_prefetch_cooldown_secs(),
            default_realm: default_realm(),
            conflict_resolution_policy: ConflictResolutionPolicy::default(),
            conflict_resolution_overrides: ConflictResolutionPolicyOverrides::default(),
            slow_query_threshold_ms: default_slow_query_threshold_ms(),
            quality_gate_threshold: 0.5,
            nli_contradiction_threshold: 0.7,
            text_retention: TextRetention::default(),
            resource_retention_policy: ResourceRetentionPolicy::default(),
            resource_quota_policy: ResourceQuotaPolicy::default(),
            resource_index_policy: ResourceIndexPolicy::default(),
            derived_artifact_index_policy: DerivedArtifactIndexPolicy::default(),
            offline_scheduler: OfflineSchedulerConfig::default(),
            offline_dream_quality_threshold: 0.55,
            offline_reconcile_quality_threshold: 0.6,
            offline_plan_quality_threshold: 0.45,
            evolution_mode: EvolutionMode::None,
            decay_interval_secs: 0,
            decay_sweep_window_secs: 86_400,
            execution_memory_limit_bytes: 0,
            execution_parallelism: 0,
            memory_decay_factor: default_memory_decay_factor(),
            memory_half_life_hours: default_memory_half_life_hours(),
            memory_min_importance: default_memory_min_importance(),
            tier_working_to_episodic_ttl_secs: 0,
            tier_episodic_to_semantic_threshold: 0.7,
            tier_semantic_archive_threshold: 0.1,
            tier_procedural_min_success_rate: 0.3,
            event_hmac_secret: None,
        }
    }
}

impl HirnConfig {
    /// Create a new configuration builder pre-filled with defaults.
    #[must_use]
    pub fn builder() -> HirnConfigBuilder {
        HirnConfigBuilder(Self::default())
    }

    /// Validate the configuration. Returns an error describing the first
    /// invalid setting found.
    pub fn validate(&self) -> Result<(), HirnError> {
        fn invalid_config(field: &str, value: impl std::fmt::Display, reason: &str) -> HirnError {
            HirnError::InvalidConfig {
                field: field.to_string(),
                value: value.to_string(),
                reason: reason.to_string(),
            }
        }

        if self.archive_threshold <= self.purge_threshold {
            return Err(HirnError::InvalidInput(
                "archive_threshold must be strictly greater than purge_threshold".into(),
            ));
        }
        if self.decay_lambda <= 0.0 {
            return Err(HirnError::InvalidInput(
                "decay_lambda must be > 0.0 (zero means no recency scoring)".into(),
            ));
        }
        if self.hebbian_learning_rate < 0.0 {
            return Err(HirnError::InvalidInput(
                "hebbian_learning_rate must be non-negative".into(),
            ));
        }
        if self.hebbian_decay_rate < 0.0 {
            return Err(HirnError::InvalidInput(
                "hebbian_decay_rate must be non-negative".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.working_memory_reserve) {
            return Err(HirnError::InvalidInput(
                "working_memory_reserve must be in [0.0, 1.0]".into(),
            ));
        }
        if self.token_budget == 0 {
            return Err(HirnError::InvalidInput("token_budget must be > 0".into()));
        }
        // embedding_dimensions is validated by the EmbeddingDimension type itself.
        self.resource_retention_policy.validate()?;
        self.resource_quota_policy.validate()?;
        self.resource_index_policy.validate()?;
        self.derived_artifact_index_policy.validate()?;
        self.offline_scheduler.validate("offline_scheduler")?;
        if matches!(self.embedder_runtime.batch_size, Some(0)) {
            return Err(invalid_config(
                "embedder_runtime.batch_size",
                0,
                "must be >= 1 when batching is enabled",
            ));
        }
        if let Some(retry) = self.embedder_runtime.retry.as_ref() {
            if retry.base_backoff_ms == 0 {
                return Err(invalid_config(
                    "embedder_runtime.retry.base_backoff_ms",
                    retry.base_backoff_ms,
                    "must be > 0 when retry is enabled",
                ));
            }
            if retry.max_cumulative_timeout_ms == 0 {
                return Err(invalid_config(
                    "embedder_runtime.retry.max_cumulative_timeout_ms",
                    retry.max_cumulative_timeout_ms,
                    "must be > 0 when retry is enabled",
                ));
            }
        }
        if let Some(circuit_breaker) = self.embedder_runtime.circuit_breaker.as_ref() {
            if circuit_breaker.failure_threshold == 0 {
                return Err(invalid_config(
                    "embedder_runtime.circuit_breaker.failure_threshold",
                    circuit_breaker.failure_threshold,
                    "must be > 0 when circuit breaking is enabled",
                ));
            }
            if circuit_breaker.recovery_timeout_ms == 0 {
                return Err(invalid_config(
                    "embedder_runtime.circuit_breaker.recovery_timeout_ms",
                    circuit_breaker.recovery_timeout_ms,
                    "must be > 0 when circuit breaking is enabled",
                ));
            }
            if circuit_breaker.success_threshold == 0 {
                return Err(invalid_config(
                    "embedder_runtime.circuit_breaker.success_threshold",
                    circuit_breaker.success_threshold,
                    "must be > 0 when circuit breaking is enabled",
                ));
            }
        }
        if let Some(cache) = self.embedder_runtime.persistent_cache.as_ref() {
            if cache.max_memory_entries == 0 {
                return Err(invalid_config(
                    "embedder_runtime.persistent_cache.max_memory_entries",
                    cache.max_memory_entries,
                    "must be > 0 when persistent caching is enabled",
                ));
            }
        }
        let weight_sum = self.scoring_similarity_weight
            + self.scoring_importance_weight
            + self.scoring_recency_weight
            + self.scoring_activation_weight
            + self.scoring_causal_relevance_weight
            + self.scoring_surprise_weight
            + self.scoring_source_reliability_weight;
        if (weight_sum - 1.0).abs() > 1e-4 {
            return Err(HirnError::InvalidInput(format!(
                "scoring weights must sum to 1.0, got {weight_sum}"
            )));
        }
        // F-C1: Reject negative scoring weights.
        for (name, w) in [
            ("scoring_similarity_weight", self.scoring_similarity_weight),
            ("scoring_importance_weight", self.scoring_importance_weight),
            ("scoring_recency_weight", self.scoring_recency_weight),
            ("scoring_activation_weight", self.scoring_activation_weight),
            (
                "scoring_causal_relevance_weight",
                self.scoring_causal_relevance_weight,
            ),
            ("scoring_surprise_weight", self.scoring_surprise_weight),
            (
                "scoring_source_reliability_weight",
                self.scoring_source_reliability_weight,
            ),
        ] {
            if !(0.0..=1.0).contains(&w) {
                return Err(HirnError::InvalidInput(format!(
                    "{name} must be in [0.0, 1.0], got {w}"
                )));
            }
        }
        // Reject zero or invalid HNSW parameters.
        if self.hnsw_m < 2 {
            return Err(HirnError::InvalidInput("hnsw_m must be >= 2".into()));
        }
        if self.hnsw_ef_construction == 0 {
            return Err(HirnError::InvalidInput(
                "hnsw_ef_construction must be > 0".into(),
            ));
        }
        if self.hnsw_ef_search == 0 {
            return Err(HirnError::InvalidInput("hnsw_ef_search must be > 0".into()));
        }
        if self.consolidation_causal_window > MAX_CONSOLIDATION_CAUSAL_WINDOW {
            return Err(invalid_config(
                "consolidation_causal_window",
                self.consolidation_causal_window,
                "must be 0 or in 1..=10000",
            ));
        }

        // Memory decay validation.
        if !(0.0..=1.0).contains(&self.memory_decay_factor) {
            return Err(HirnError::InvalidInput(
                "memory_decay_factor must be in [0.0, 1.0]".into(),
            ));
        }
        if self.memory_half_life_hours == 0 {
            return Err(HirnError::InvalidInput(
                "memory_half_life_hours must be > 0".into(),
            ));
        }
        if self.memory_min_importance < 0.0 {
            return Err(HirnError::InvalidInput(
                "memory_min_importance must be >= 0.0".into(),
            ));
        }

        // Write-path threshold validation.
        if self.rpe_fast_path_threshold < 0.0 || self.rpe_fast_path_threshold > 2.0 {
            return Err(HirnError::InvalidInput(
                "rpe_fast_path_threshold must be in [0.0, 2.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.svo_confidence_threshold) {
            return Err(HirnError::InvalidInput(
                "svo_confidence_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if self.svo_extraction_enabled && !self.svo_extraction_prompt.contains("{content}") {
            return Err(HirnError::InvalidInput(
                "svo_extraction_prompt must contain {content} placeholder".into(),
            ));
        }
        for template in &self.prospective_indexing_templates {
            if !template.contains("{content}") {
                return Err(invalid_config(
                    "prospective_indexing_templates",
                    template,
                    "every template must contain the {content} placeholder",
                ));
            }
        }
        if self.interference_consolidation_threshold < 0.0 {
            return Err(HirnError::InvalidInput(
                "interference_consolidation_threshold must be >= 0.0".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.quality_gate_threshold) {
            return Err(HirnError::InvalidInput(
                "quality_gate_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.nli_contradiction_threshold) {
            return Err(HirnError::InvalidInput(
                "nli_contradiction_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.offline_dream_quality_threshold) {
            return Err(HirnError::InvalidInput(
                "offline_dream_quality_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.offline_reconcile_quality_threshold) {
            return Err(HirnError::InvalidInput(
                "offline_reconcile_quality_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.offline_plan_quality_threshold) {
            return Err(HirnError::InvalidInput(
                "offline_plan_quality_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        validate_conflict_resolution_policy(
            &self.conflict_resolution_policy,
            "conflict_resolution_policy",
        )?;
        for (realm, policy) in &self.conflict_resolution_overrides.by_realm {
            if realm.trim().is_empty() {
                return Err(invalid_config(
                    "conflict_resolution_overrides.by_realm",
                    realm,
                    "realm keys must be non-empty",
                ));
            }
            validate_conflict_resolution_policy(
                policy,
                &format!("conflict_resolution_overrides.by_realm.{realm}"),
            )?;
        }
        for (namespace, policy) in &self.conflict_resolution_overrides.by_namespace {
            Namespace::new(namespace).map_err(|_| {
                invalid_config(
                    "conflict_resolution_overrides.by_namespace",
                    namespace,
                    "namespace override keys must be valid namespace identifiers",
                )
            })?;
            validate_conflict_resolution_policy(
                policy,
                &format!("conflict_resolution_overrides.by_namespace.{namespace}"),
            )?;
        }

        // Tier policy validation.
        if !(0.0..=1.0).contains(&self.tier_episodic_to_semantic_threshold) {
            return Err(HirnError::InvalidInput(
                "tier_episodic_to_semantic_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.tier_semantic_archive_threshold) {
            return Err(HirnError::InvalidInput(
                "tier_semantic_archive_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.tier_procedural_min_success_rate) {
            return Err(HirnError::InvalidInput(
                "tier_procedural_min_success_rate must be in [0.0, 1.0]".into(),
            ));
        }

        // F-17: Cross-parameter consistency warnings.
        // These are not errors — just sub-optimal configurations.
        // Callers can check `config.warnings()` for advisory messages.

        // N-M07: Missing range validation for graph + scoring numeric params.
        if !(0.0..=1.0).contains(&self.activation_decay_factor) {
            return Err(HirnError::InvalidInput(
                "activation_decay_factor must be in (0.0, 1.0]".into(),
            ));
        }
        if self.activation_convergence_threshold <= 0.0 {
            return Err(HirnError::InvalidInput(
                "activation_convergence_threshold must be > 0.0".into(),
            ));
        }
        if self.inhibition_strength < 0.0 {
            return Err(HirnError::InvalidInput(
                "inhibition_strength must be >= 0.0".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.similarity_edge_threshold) {
            return Err(HirnError::InvalidInput(
                "similarity_edge_threshold must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.multivector_weight) {
            return Err(HirnError::InvalidInput(
                "multivector_weight must be in [0.0, 1.0]".into(),
            ));
        }
        if !(0.0..=1.0).contains(&self.causal_min_confidence) {
            return Err(HirnError::InvalidInput(
                "causal_min_confidence must be in [0.0, 1.0]".into(),
            ));
        }
        if self.default_token_budget == 0 {
            return Err(HirnError::InvalidInput(
                "default_token_budget must be > 0".into(),
            ));
        }

        // C-M05: HMAC secret minimum entropy enforcement.
        if let Some(ref secret) = self.event_hmac_secret {
            if secret.len() < 32 {
                return Err(HirnError::InvalidConfig {
                    field: "event_hmac_secret".to_string(),
                    value: format!("{} bytes", secret.len()),
                    reason: "must be at least 32 bytes for HMAC integrity; use a cryptographically random secret".to_string(),
                });
            }
        }

        // F-122: db_path writability check — fail early with an actionable message
        // rather than surfacing a cryptic storage error later during open().
        {
            let path = &self.db_path;
            if path.exists() {
                if !path.is_dir() {
                    return Err(invalid_config(
                        "db_path",
                        path.display(),
                        "path exists but is not a directory; provide a directory path",
                    ));
                }
            } else if let Some(parent) = path.parent() {
                if !parent.as_os_str().is_empty() && parent.exists() && !parent.is_dir() {
                    return Err(invalid_config(
                        "db_path",
                        path.display(),
                        "parent path exists but is not a directory; check db_path",
                    ));
                }
            }
        }

        Ok(())
    }

    /// Return the HMAC signing key bytes for event log integrity signing.
    ///
    /// Returns `None` if `event_hmac_secret` is not configured, meaning events
    /// will not be signed. When `Some`, the returned slice is guaranteed to be
    /// at least 32 bytes (enforced by `validate()`).
    #[must_use]
    pub fn event_hmac_key(&self) -> Option<&[u8]> {
        self.event_hmac_secret.as_deref().map(str::as_bytes)
    }

    /// Return advisory warnings about sub-optimal parameter combinations.
    /// Unlike `validate()`, these do not indicate invalid configurations.
    #[must_use]
    pub fn warnings(&self) -> Vec<String> {
        let mut warnings = Vec::new();
        if self.hnsw_ef_search < self.hnsw_m {
            warnings.push(format!(
                "hnsw_ef_search ({}) < hnsw_m ({}); search quality may be poor",
                self.hnsw_ef_search, self.hnsw_m
            ));
        }
        if self.hnsw_ef_construction < self.hnsw_ef_search {
            warnings.push(format!(
                "hnsw_ef_construction ({}) < hnsw_ef_search ({}); build quality lower than query quality",
                self.hnsw_ef_construction, self.hnsw_ef_search
            ));
        }
        warnings
    }
}

// ── Serde default value helpers for admission config ────────────────────

const fn default_surprise_threshold() -> f32 {
    0.3
}
const fn default_duplicate_threshold() -> f32 {
    0.95
}
fn default_duplicate_action() -> String {
    "reject".into()
}
const fn default_token_budget_limit() -> u64 {
    500_000
}
const fn default_rate_limit() -> u32 {
    100
}
const fn default_prefetch_activation_depth() -> usize {
    2
}
const fn default_prefetch_min_edge_weight() -> f32 {
    0.1
}
const fn default_prefetch_max_bytes() -> u64 {
    10_485_760
} // 10 MB
const fn default_prefetch_cooldown_secs() -> u64 {
    300
}
fn default_realm() -> String {
    "default".into()
}
const fn default_slow_query_threshold_ms() -> u64 {
    100
}
const fn default_memory_decay_factor() -> f32 {
    0.95
}
const fn default_memory_half_life_hours() -> u64 {
    168
}
const fn default_memory_min_importance() -> f32 {
    0.01
}

fn validate_conflict_resolution_policy(
    policy: &ConflictResolutionPolicy,
    field: &str,
) -> Result<(), HirnError> {
    let weights = [
        ("recency_weight", policy.recency_weight),
        (
            "source_reliability_weight",
            policy.source_reliability_weight,
        ),
        (
            "supporting_evidence_weight",
            policy.supporting_evidence_weight,
        ),
        ("human_override_weight", policy.human_override_weight),
    ];

    for (name, value) in weights {
        if !(0.0..=1.0).contains(&value) {
            return Err(HirnError::InvalidConfig {
                field: format!("{field}.{name}"),
                value: value.to_string(),
                reason: "must be in [0.0, 1.0]".to_string(),
            });
        }
    }

    let weight_sum = policy.recency_weight
        + policy.source_reliability_weight
        + policy.supporting_evidence_weight
        + policy.human_override_weight;
    if weight_sum <= 0.0 {
        return Err(HirnError::InvalidConfig {
            field: field.to_string(),
            value: weight_sum.to_string(),
            reason: "must assign a non-zero total weight".to_string(),
        });
    }

    Ok(())
}

fn default_prospective_templates() -> Vec<String> {
    vec![
        "What is known about {content}?".into(),
        "When did {content} happen?".into(),
        "Who was involved in {content}?".into(),
        "What was the outcome of {content}?".into(),
        "Why is {content} important?".into(),
    ]
}

fn default_svo_extraction_prompt() -> String {
    "Extract all Subject-Verb-Object events from the following text.\n\
     For each event, provide:\n\
     - subject: the actor or entity performing the action\n\
     - verb: the action or relation\n\
     - object: the target or entity affected\n\
     - time_start: when the event started (ISO 8601 or natural language, null if unknown)\n\
     - time_end: when the event ended (null if same as start or unknown)\n\
     - location: where the event occurred (null if unknown)\n\
     - confidence: your confidence in this extraction (0.0 to 1.0)\n\n\
     Return a JSON array of objects. Only include events with confidence >= 0.5.\n\n\
     Text: {content}"
        .into()
}

/// Builder for [`HirnConfig`].
pub struct HirnConfigBuilder(HirnConfig);

impl HirnConfigBuilder {
    #[must_use]
    pub fn db_path(mut self, path: impl AsRef<Path>) -> Self {
        self.0.db_path = path.as_ref().to_path_buf();
        self
    }

    #[must_use]
    pub const fn working_memory_token_limit(mut self, limit: u32) -> Self {
        self.0.working_memory_token_limit = limit;
        self
    }

    #[must_use]
    pub const fn working_memory_reserve(mut self, reserve: f32) -> Self {
        self.0.working_memory_reserve = reserve;
        self
    }

    #[must_use]
    pub const fn decay_lambda(mut self, lambda: f64) -> Self {
        self.0.decay_lambda = lambda;
        self
    }

    #[must_use]
    pub const fn archive_threshold(mut self, threshold: f32) -> Self {
        self.0.archive_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn purge_threshold(mut self, threshold: f32) -> Self {
        self.0.purge_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn max_episodic_entries(mut self, max: u32) -> Self {
        self.0.max_episodic_entries = max;
        self
    }

    #[must_use]
    pub const fn hebbian_learning_rate(mut self, rate: f64) -> Self {
        self.0.hebbian_learning_rate = rate;
        self
    }

    #[must_use]
    pub const fn hebbian_decay_rate(mut self, rate: f64) -> Self {
        self.0.hebbian_decay_rate = rate;
        self
    }

    #[must_use]
    pub const fn token_budget(mut self, budget: u32) -> Self {
        self.0.token_budget = budget;
        self
    }

    #[must_use]
    pub const fn recall_preview_package_max_previews(mut self, max: usize) -> Self {
        self.0.recall_preview_package_max_previews = max;
        self
    }

    #[must_use]
    pub const fn recall_preview_package_max_chars(mut self, max: usize) -> Self {
        self.0.recall_preview_package_max_chars = max;
        self
    }

    #[must_use]
    pub const fn recall_preview_rerank_max_previews(mut self, max: usize) -> Self {
        self.0.recall_preview_rerank_max_previews = max;
        self
    }

    #[must_use]
    pub const fn recall_preview_rerank_max_chars(mut self, max: usize) -> Self {
        self.0.recall_preview_rerank_max_chars = max;
        self
    }

    #[must_use]
    pub const fn think_preview_package_max_previews(mut self, max: usize) -> Self {
        self.0.think_preview_package_max_previews = max;
        self
    }

    #[must_use]
    pub const fn think_preview_package_max_chars(mut self, max: usize) -> Self {
        self.0.think_preview_package_max_chars = max;
        self
    }

    #[must_use]
    pub const fn hnsw_m(mut self, m: usize) -> Self {
        self.0.hnsw_m = m;
        self
    }

    #[must_use]
    pub const fn hnsw_ef_construction(mut self, ef: usize) -> Self {
        self.0.hnsw_ef_construction = ef;
        self
    }

    #[must_use]
    pub const fn hnsw_ef_search(mut self, ef: usize) -> Self {
        self.0.hnsw_ef_search = ef;
        self
    }

    #[must_use]
    pub const fn embedding_dimensions(mut self, dims: u32) -> Self {
        self.0.embedding_dimensions = crate::EmbeddingDimension::new_const(dims);
        self
    }

    #[must_use]
    pub const fn allow_pseudo_embedder_fallback(mut self, allow: bool) -> Self {
        self.0.allow_pseudo_embedder_fallback = allow;
        self
    }

    #[must_use]
    pub fn embedder_runtime(mut self, config: EmbedderRuntimeConfig) -> Self {
        self.0.embedder_runtime = config;
        self
    }

    #[must_use]
    pub fn conflict_resolution_policy(mut self, policy: ConflictResolutionPolicy) -> Self {
        self.0.conflict_resolution_policy = policy;
        self
    }

    #[must_use]
    pub fn conflict_resolution_realm_policy(
        mut self,
        realm: impl Into<String>,
        policy: ConflictResolutionPolicy,
    ) -> Self {
        self.0
            .conflict_resolution_overrides
            .by_realm
            .insert(realm.into(), policy);
        self
    }

    #[must_use]
    pub fn conflict_resolution_namespace_policy(
        mut self,
        namespace: impl Into<String>,
        policy: ConflictResolutionPolicy,
    ) -> Self {
        self.0
            .conflict_resolution_overrides
            .by_namespace
            .insert(namespace.into(), policy);
        self
    }

    #[must_use]
    pub const fn distance_metric(mut self, metric: DistanceMetric) -> Self {
        self.0.metric = metric;
        self
    }

    #[must_use]
    pub const fn scoring_weights(mut self, alpha: f32, beta: f32, gamma: f32, delta: f32) -> Self {
        self.0.scoring_similarity_weight = alpha;
        self.0.scoring_importance_weight = beta;
        self.0.scoring_recency_weight = gamma;
        self.0.scoring_activation_weight = delta;
        self
    }

    #[must_use]
    pub const fn scoring_causal_relevance_weight(mut self, weight: f32) -> Self {
        self.0.scoring_causal_relevance_weight = weight;
        self
    }

    #[must_use]
    pub const fn scoring_surprise_weight(mut self, weight: f32) -> Self {
        self.0.scoring_surprise_weight = weight;
        self
    }

    #[must_use]
    pub const fn scoring_source_reliability_weight(mut self, weight: f32) -> Self {
        self.0.scoring_source_reliability_weight = weight;
        self
    }

    #[must_use]
    pub const fn similarity_edge_threshold(mut self, threshold: f32) -> Self {
        self.0.similarity_edge_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn max_auto_edges_per_record(mut self, max: usize) -> Self {
        self.0.max_auto_edges_per_record = max;
        self
    }

    #[must_use]
    pub const fn entity_overlap_threshold(mut self, threshold: usize) -> Self {
        self.0.entity_overlap_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn consolidation_interval_secs(mut self, secs: u64) -> Self {
        self.0.consolidation_interval_secs = secs;
        self
    }

    #[must_use]
    pub const fn consolidation_causal_window(mut self, window: usize) -> Self {
        self.0.consolidation_causal_window = window;
        self
    }

    #[must_use]
    pub const fn reconsolidation_window_secs(mut self, secs: u64) -> Self {
        self.0.reconsolidation_window_secs = secs;
        self
    }

    #[must_use]
    pub const fn compaction_interval_secs(mut self, secs: u64) -> Self {
        self.0.compaction_interval_secs = secs;
        self
    }

    #[must_use]
    pub const fn compaction_fragment_threshold(mut self, threshold: u32) -> Self {
        self.0.compaction_fragment_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn multivector_enabled(mut self, enabled: bool) -> Self {
        self.0.multivector_enabled = enabled;
        self
    }

    /// Set the weight for multi-vector similarity scoring.
    #[must_use]
    pub const fn multivector_weight(mut self, weight: f32) -> Self {
        self.0.multivector_weight = weight;
        self
    }

    #[must_use]
    pub const fn prefetch_enabled(mut self, enabled: bool) -> Self {
        self.0.prefetch_enabled = enabled;
        self
    }

    #[must_use]
    pub const fn prefetch_activation_depth(mut self, depth: usize) -> Self {
        self.0.prefetch_activation_depth = depth;
        self
    }

    #[must_use]
    pub const fn prefetch_min_edge_weight(mut self, weight: f32) -> Self {
        self.0.prefetch_min_edge_weight = weight;
        self
    }

    #[must_use]
    pub const fn prefetch_max_bytes(mut self, bytes: u64) -> Self {
        self.0.prefetch_max_bytes = bytes;
        self
    }

    #[must_use]
    pub const fn prefetch_cooldown_secs(mut self, secs: u64) -> Self {
        self.0.prefetch_cooldown_secs = secs;
        self
    }

    /// Set the default realm name for the database instance.
    #[must_use]
    pub fn default_realm(mut self, realm: impl Into<String>) -> Self {
        self.0.default_realm = realm.into();
        self
    }

    #[must_use]
    pub const fn slow_query_threshold_ms(mut self, ms: u64) -> Self {
        self.0.slow_query_threshold_ms = ms;
        self
    }

    #[must_use]
    pub const fn quality_gate_threshold(mut self, threshold: f32) -> Self {
        self.0.quality_gate_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn offline_dream_quality_threshold(mut self, threshold: f32) -> Self {
        self.0.offline_dream_quality_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn offline_reconcile_quality_threshold(mut self, threshold: f32) -> Self {
        self.0.offline_reconcile_quality_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn offline_plan_quality_threshold(mut self, threshold: f32) -> Self {
        self.0.offline_plan_quality_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn nli_contradiction_threshold(mut self, threshold: f32) -> Self {
        self.0.nli_contradiction_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn text_retention(mut self, retention: TextRetention) -> Self {
        self.0.text_retention = retention;
        self
    }

    #[must_use]
    pub fn resource_retention_policy(mut self, policy: ResourceRetentionPolicy) -> Self {
        self.0.resource_retention_policy = policy;
        self
    }

    /// Set the operator-triggered resource quota policy.
    #[must_use]
    pub fn resource_quota_policy(mut self, policy: ResourceQuotaPolicy) -> Self {
        self.0.resource_quota_policy = policy;
        self
    }

    /// Set additional modality-scoped secondary indices for `resources`.
    #[must_use]
    pub fn resource_index_policy(mut self, policy: ResourceIndexPolicy) -> Self {
        self.0.resource_index_policy = policy;
        self
    }

    /// Set additional artifact-kind-scoped secondary indices for `derived_artifacts`.
    #[must_use]
    pub fn derived_artifact_index_policy(mut self, policy: DerivedArtifactIndexPolicy) -> Self {
        self.0.derived_artifact_index_policy = policy;
        self
    }

    /// Set the runtime policy for queued offline cognition jobs.
    #[must_use]
    pub fn offline_scheduler(mut self, config: OfflineSchedulerConfig) -> Self {
        self.0.offline_scheduler = config;
        self
    }

    /// Set the memory limit for DataFusion execution in bytes. 0 = unlimited.
    #[must_use]
    pub const fn execution_memory_limit_bytes(mut self, bytes: u64) -> Self {
        self.0.execution_memory_limit_bytes = bytes;
        self
    }

    /// Set the parallelism for DataFusion execution. 0 = auto-detect.
    #[must_use]
    pub const fn execution_parallelism(mut self, parallelism: usize) -> Self {
        self.0.execution_parallelism = parallelism;
        self
    }

    #[must_use]
    pub const fn memory_decay_factor(mut self, factor: f32) -> Self {
        self.0.memory_decay_factor = factor;
        self
    }

    #[must_use]
    pub const fn memory_half_life_hours(mut self, hours: u64) -> Self {
        self.0.memory_half_life_hours = hours;
        self
    }

    #[must_use]
    pub const fn memory_min_importance(mut self, threshold: f32) -> Self {
        self.0.memory_min_importance = threshold;
        self
    }

    #[must_use]
    pub const fn tier_working_to_episodic_ttl_secs(mut self, secs: u64) -> Self {
        self.0.tier_working_to_episodic_ttl_secs = secs;
        self
    }

    #[must_use]
    pub const fn tier_episodic_to_semantic_threshold(mut self, threshold: f32) -> Self {
        self.0.tier_episodic_to_semantic_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn tier_semantic_archive_threshold(mut self, threshold: f32) -> Self {
        self.0.tier_semantic_archive_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn tier_procedural_min_success_rate(mut self, rate: f32) -> Self {
        self.0.tier_procedural_min_success_rate = rate;
        self
    }

    #[must_use]
    pub const fn graph_depth_delegation_threshold(mut self, threshold: usize) -> Self {
        self.0.graph_depth_delegation_threshold = threshold;
        self
    }

    /// Build and validate the configuration.
    pub fn build(self) -> Result<HirnConfig, HirnError> {
        self.0.validate()?;
        Ok(self.0)
    }

    #[must_use]
    pub const fn rpe_enabled(mut self, enabled: bool) -> Self {
        self.0.rpe_enabled = enabled;
        self
    }

    #[must_use]
    pub const fn rpe_fast_path_threshold(mut self, threshold: f32) -> Self {
        self.0.rpe_fast_path_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn rpe_similarity_search_limit(mut self, limit: usize) -> Self {
        self.0.rpe_similarity_search_limit = limit;
        self
    }

    #[must_use]
    pub const fn prospective_indexing_enabled(mut self, enabled: bool) -> Self {
        self.0.prospective_indexing_enabled = enabled;
        self
    }

    #[must_use]
    pub const fn prospective_indexing_num_questions(mut self, num: usize) -> Self {
        self.0.prospective_indexing_num_questions = num;
        self
    }

    #[must_use]
    pub const fn prospective_indexing_timeout_secs(mut self, secs: u64) -> Self {
        self.0.prospective_indexing_timeout_secs = secs;
        self
    }

    #[must_use]
    pub fn prospective_indexing_templates(mut self, templates: Vec<String>) -> Self {
        self.0.prospective_indexing_templates = templates;
        self
    }

    #[must_use]
    pub const fn svo_extraction_enabled(mut self, enabled: bool) -> Self {
        self.0.svo_extraction_enabled = enabled;
        self
    }

    #[must_use]
    pub const fn svo_confidence_threshold(mut self, threshold: f32) -> Self {
        self.0.svo_confidence_threshold = threshold;
        self
    }

    #[must_use]
    pub fn svo_extraction_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.0.svo_extraction_prompt = prompt.into();
        self
    }

    #[must_use]
    pub const fn interference_consolidation_threshold(mut self, threshold: f32) -> Self {
        self.0.interference_consolidation_threshold = threshold;
        self
    }

    #[must_use]
    pub const fn interference_consolidation_cooldown_secs(mut self, secs: u64) -> Self {
        self.0.interference_consolidation_cooldown_secs = secs;
        self
    }

    /// Set the interval between FadeMem offline decay sweeps (0 = disabled).
    #[must_use]
    pub const fn decay_interval_secs(mut self, secs: u64) -> Self {
        self.0.decay_interval_secs = secs;
        self
    }

    /// Set the look-back window for the decay sweep.
    #[must_use]
    pub const fn decay_sweep_window_secs(mut self, secs: u64) -> Self {
        self.0.decay_sweep_window_secs = secs;
        self
    }
}

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

    #[test]
    fn default_is_valid() {
        let config = HirnConfig::default();
        config.validate().unwrap();
    }

    #[test]
    fn builder_custom_values() {
        let config = HirnConfig::builder()
            .db_path("/tmp/test")
            .token_budget(8192)
            .working_memory_token_limit(4096)
            .build()
            .unwrap();

        assert_eq!(config.db_path, PathBuf::from("/tmp/test"));
        assert_eq!(config.token_budget, 8192);
        assert_eq!(config.working_memory_token_limit, 4096);
    }

    #[test]
    fn purge_gt_archive_fails() {
        let result = HirnConfig::builder()
            .purge_threshold(0.5)
            .archive_threshold(0.1) // purge > archive → invalid
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn negative_decay_lambda_fails() {
        let result = HirnConfig::builder().decay_lambda(-1.0).build();
        assert!(result.is_err());
    }

    #[test]
    fn negative_hebbian_rate_fails() {
        let result = HirnConfig::builder().hebbian_learning_rate(-0.1).build();
        assert!(result.is_err());
    }

    #[test]
    fn toml_round_trip() {
        let config = HirnConfig::default();
        let toml_str = toml::to_string_pretty(&config).unwrap();
        let back: HirnConfig = toml::from_str(&toml_str).unwrap();
        assert_eq!(config.token_budget, back.token_budget);
        assert_eq!(config.db_path, back.db_path);
    }

    #[test]
    fn invalid_toml_rejected() {
        let config = HirnConfig::default();
        let mut toml_str = toml::to_string_pretty(&config).unwrap();
        // Set hnsw_m to 0 which should fail validation.
        toml_str = toml_str.replace("hnsw_m = 16", "hnsw_m = 0");
        let result: Result<HirnConfig, _> = toml::from_str(&toml_str);
        assert!(
            result.is_err(),
            "deserializing hnsw_m=0 should fail validation"
        );
    }

    #[test]
    fn prospective_templates_default() {
        let config = HirnConfig::default();
        assert_eq!(config.prospective_indexing_templates.len(), 5);
        assert!(config.prospective_indexing_templates[0].contains("{content}"));
    }

    #[test]
    fn prospective_templates_custom() {
        let config = HirnConfig::builder()
            .prospective_indexing_templates(vec![
                "Tell me about {content}".into(),
                "Summarize {content}".into(),
            ])
            .build()
            .unwrap();
        assert_eq!(config.prospective_indexing_templates.len(), 2);
        assert_eq!(
            config.prospective_indexing_templates[0],
            "Tell me about {content}"
        );
    }

    #[test]
    fn prospective_templates_missing_placeholder_rejected() {
        let err = HirnConfig::builder()
            .prospective_indexing_templates(vec!["Tell me about this memory".into()])
            .build()
            .unwrap_err();

        match err {
            HirnError::InvalidConfig { field, reason, .. } => {
                assert_eq!(field, "prospective_indexing_templates");
                assert!(reason.contains("{content}"));
            }
            other => panic!("expected InvalidConfig, got {other}"),
        }
    }

    #[test]
    fn prospective_templates_toml_round_trip() {
        let config = HirnConfig::default();
        let toml_str = toml::to_string_pretty(&config).unwrap();
        let back: HirnConfig = toml::from_str(&toml_str).unwrap();
        assert_eq!(
            config.prospective_indexing_templates,
            back.prospective_indexing_templates
        );
    }

    #[test]
    fn legacy_config_with_missing_new_fields_deserializes_with_defaults() {
        let legacy_toml = r#"
db_path = "./legacy-brain"
embedding_dimensions = 64
"#;

        let config: HirnConfig = toml::from_str(legacy_toml).unwrap();

        assert_eq!(config.db_path, std::path::PathBuf::from("./legacy-brain"));
        assert_eq!(config.embedding_dimensions, crate::EmbeddingDimension::new_const(64));
        assert!((config.rpe_fast_path_threshold - 0.3).abs() < f32::EPSILON);
        assert!((config.quality_gate_threshold - 0.5).abs() < f32::EPSILON);
        assert!((config.offline_dream_quality_threshold - 0.55).abs() < f32::EPSILON);
        assert!((config.offline_reconcile_quality_threshold - 0.6).abs() < f32::EPSILON);
        assert!((config.offline_plan_quality_threshold - 0.45).abs() < f32::EPSILON);
        assert!((config.interference_consolidation_threshold - 0.3).abs() < f32::EPSILON);
        assert_eq!(config.consolidation_causal_window, 100);
        assert!(!config.prospective_indexing_templates.is_empty());
    }

    #[test]
    fn invalid_svo_confidence_threshold_rejected() {
        let result = HirnConfig::builder().svo_confidence_threshold(1.5).build();
        assert!(result.is_err());
        let result = HirnConfig::builder().svo_confidence_threshold(-0.1).build();
        assert!(result.is_err());
    }

    #[test]
    fn invalid_rpe_threshold_rejected() {
        let result = HirnConfig::builder().rpe_fast_path_threshold(3.0).build();
        assert!(result.is_err());
        let result = HirnConfig::builder().rpe_fast_path_threshold(-0.1).build();
        assert!(result.is_err());
    }

    #[test]
    fn invalid_interference_threshold_rejected() {
        let result = HirnConfig::builder()
            .interference_consolidation_threshold(-1.0)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn invalid_offline_quality_threshold_rejected() {
        assert!(
            HirnConfig::builder()
                .offline_dream_quality_threshold(1.1)
                .build()
                .is_err()
        );
        assert!(
            HirnConfig::builder()
                .offline_reconcile_quality_threshold(-0.1)
                .build()
                .is_err()
        );
        assert!(
            HirnConfig::builder()
                .offline_plan_quality_threshold(1.5)
                .build()
                .is_err()
        );
    }

    #[test]
    fn invalid_causal_window_rejected() {
        let err = HirnConfig::builder()
            .consolidation_causal_window(MAX_CONSOLIDATION_CAUSAL_WINDOW + 1)
            .build()
            .unwrap_err();

        match err {
            HirnError::InvalidConfig { field, reason, .. } => {
                assert_eq!(field, "consolidation_causal_window");
                assert!(reason.contains("1..=10000"));
            }
            other => panic!("expected InvalidConfig, got {other}"),
        }
    }

    #[test]
    fn valid_write_path_guards_pass_cleanly() {
        let config = HirnConfig::builder()
            .prospective_indexing_templates(vec!["Tell me about {content}".into()])
            .consolidation_causal_window(MAX_CONSOLIDATION_CAUSAL_WINDOW)
            .build()
            .unwrap();

        assert_eq!(
            config.consolidation_causal_window,
            MAX_CONSOLIDATION_CAUSAL_WINDOW
        );
        assert_eq!(
            config.prospective_indexing_templates,
            vec!["Tell me about {content}".to_string()]
        );
    }

    #[test]
    fn invalid_conflict_resolution_weight_rejected() {
        let result = HirnConfig::builder()
            .conflict_resolution_policy(ConflictResolutionPolicy {
                recency_weight: 1.2,
                ..ConflictResolutionPolicy::default()
            })
            .build();

        assert!(result.is_err());
    }

    #[test]
    fn conflict_resolution_namespace_policy_round_trips() {
        let config = HirnConfig::builder()
            .conflict_resolution_namespace_policy(
                "team_ops",
                ConflictResolutionPolicy {
                    recency_weight: 0.8,
                    source_reliability_weight: 0.1,
                    supporting_evidence_weight: 0.1,
                    human_override_weight: 0.0,
                    prefer_human_override: true,
                },
            )
            .build()
            .unwrap();

        let toml_str = toml::to_string_pretty(&config).unwrap();
        let back: HirnConfig = toml::from_str(&toml_str).unwrap();

        assert_eq!(
            back.conflict_resolution_overrides
                .by_namespace
                .get("team_ops")
                .unwrap()
                .recency_weight,
            0.8
        );
    }

    #[test]
    fn invalid_embedder_runtime_guards_rejected() {
        let err = HirnConfig::builder()
            .embedder_runtime(EmbedderRuntimeConfig {
                batch_size: Some(0),
                retry: None,
                circuit_breaker: None,
                persistent_cache: None,
            })
            .build()
            .unwrap_err();

        match err {
            HirnError::InvalidConfig { field, .. } => {
                assert_eq!(field, "embedder_runtime.batch_size");
            }
            other => panic!("expected InvalidConfig, got {other}"),
        }

        let err = HirnConfig::builder()
            .embedder_runtime(EmbedderRuntimeConfig {
                batch_size: None,
                retry: Some(EmbedderRetryConfig {
                    max_retries: 1,
                    base_backoff_ms: 0,
                    max_cumulative_timeout_ms: 1,
                }),
                circuit_breaker: None,
                persistent_cache: None,
            })
            .build()
            .unwrap_err();

        match err {
            HirnError::InvalidConfig { field, .. } => {
                assert_eq!(field, "embedder_runtime.retry.base_backoff_ms");
            }
            other => panic!("expected InvalidConfig, got {other}"),
        }

        let err = HirnConfig::builder()
            .embedder_runtime(EmbedderRuntimeConfig {
                batch_size: None,
                retry: Some(EmbedderRetryConfig {
                    max_retries: 1,
                    base_backoff_ms: 1,
                    max_cumulative_timeout_ms: 0,
                }),
                circuit_breaker: None,
                persistent_cache: None,
            })
            .build()
            .unwrap_err();

        match err {
            HirnError::InvalidConfig { field, .. } => {
                assert_eq!(field, "embedder_runtime.retry.max_cumulative_timeout_ms");
            }
            other => panic!("expected InvalidConfig, got {other}"),
        }
    }
}