truth-mirror 0.15.0

Truthfulness gate and adversarial reviewer harness for AI coding agents.
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
//! truth-mirror configuration: adversarial pairs, reasoning effort, gates,
//! ground-truth, trajectory, and enforcement.
use std::{
    collections::BTreeMap,
    fs::{self, OpenOptions},
    io::{self, Write},
    path::{Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
};

use serde::{Deserialize, Serialize};
use thiserror::Error;

pub const DEFAULT_STATE_DIR: &str = ".truth";
pub const LEGACY_STATE_DIR: &str = ".truth-mirror";
pub const MAX_PETITION_BATCH_SIZE: usize = 32;

/// Environment variable that can force-disable (or leave enabled) truth-mirror.
pub const TRUTH_MIRROR_ENABLED_ENV: &str = "TRUTH_MIRROR_ENABLED";

static CONFIG_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Checked-in annotated config asset used for both system and project defaults.
pub const DEFAULT_CONFIG_ASSET: &str = include_str!("../assets/config.toml");

/// Hard safety ceiling for concurrent provider processes.
pub const MAX_CONCURRENT_REVIEW_RUNS: usize = 4;
pub const DEFAULT_MEMORY_SKILL_BLOCKED_PATTERNS: &[&str] = &[
    "BEGIN SYSTEM PROMPT",
    "ignore previous instructions",
    "api_key",
    "secret_key",
    "secret:",
    "secret=",
    "token:",
    "token=",
    "password:",
    "password=",
    "credential:",
    "credential=",
    "private_key",
    "aws_secret_access_key",
];

/// Reasoning effort (`C`). Highest is `Xhigh`.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
#[value(rename_all = "lowercase")]
pub enum Effort {
    Minimal,
    Low,
    Medium,
    High,
    #[default]
    Xhigh,
}

impl Effort {
    pub fn as_str(self) -> &'static str {
        match self {
            Effort::Minimal => "minimal",
            Effort::Low => "low",
            Effort::Medium => "medium",
            Effort::High => "high",
            Effort::Xhigh => "xhigh",
        }
    }

    /// The highest supported effort — the default reviewer aggressiveness.
    pub fn highest() -> Self {
        Effort::Xhigh
    }

    /// Value accepted by Claude's `--effort`. Verified: claude takes
    /// `low|medium|high|xhigh|max` and has no `minimal`, so `Minimal` clamps to
    /// `low`. (Codex and Pi both accept `minimal`.)
    pub fn claude_value(self) -> &'static str {
        match self {
            Effort::Minimal => "low",
            other => other.as_str(),
        }
    }
}

/// A concrete reviewer/arbiter selection: harness + model + reasoning effort.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct HarnessSelection {
    pub harness: String,
    pub model: String,
    #[serde(default)]
    pub effort: Effort,
}

impl HarnessSelection {
    pub fn new(harness: impl Into<String>, model: impl Into<String>, effort: Effort) -> Self {
        Self {
            harness: harness.into(),
            model: model.into(),
            effort,
        }
    }
}

/// The opposed reviewer (and optional second-pass arbiter) for one writer harness.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct AdversarialPair {
    pub reviewer: HarnessSelection,
    #[serde(default)]
    pub arbiter: Option<HarnessSelection>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TruthMirrorConfig {
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    #[serde(default = "default_announce_when_disabled")]
    pub announce_when_disabled: bool,
    #[serde(default = "default_ledger_dir")]
    pub ledger_dir: String,
    #[serde(default)]
    pub allow_same_model: bool,
    /// Writer harness assumed when none is provided on the CLI or commit trailer.
    #[serde(default = "default_writer")]
    pub default_writer: String,
    /// Adversarial pairs keyed by writer harness (lowercase). Empty in the parsed
    /// form when `[pairs]` is absent; `normalize` fills defaults / folds legacy.
    #[serde(default)]
    pub pairs: BTreeMap<String, AdversarialPair>,
    #[serde(default)]
    pub strict: StrictConfig,
    #[serde(default)]
    pub gates: GatesConfig,
    #[serde(default)]
    pub ground_truth: GroundTruthConfig,
    #[serde(default)]
    pub history: HistoryConfig,
    #[serde(default)]
    pub enforcement: EnforcementConfig,
    #[serde(default)]
    pub skills: SkillsConfig,
    #[serde(default)]
    pub memory_skill: MemorySkillConfig,
    /// Reviewer subprocess settings (per-review wall-clock timeout).
    #[serde(default)]
    pub reviewer: ReviewerPolicyConfig,
    /// Legacy `[review]` block, folded into `pairs` on load for back-compat.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub review: Option<LegacyReview>,
}

impl Default for TruthMirrorConfig {
    fn default() -> Self {
        Self {
            enabled: default_enabled(),
            announce_when_disabled: default_announce_when_disabled(),
            ledger_dir: default_ledger_dir(),
            allow_same_model: false,
            default_writer: default_writer(),
            pairs: default_pairs(),
            strict: StrictConfig::default(),
            gates: GatesConfig::default(),
            ground_truth: GroundTruthConfig::default(),
            history: HistoryConfig::default(),
            enforcement: EnforcementConfig::default(),
            skills: SkillsConfig::default(),
            memory_skill: MemorySkillConfig::default(),
            reviewer: ReviewerPolicyConfig::default(),
            review: None,
        }
    }
}
/// Resolve the system configuration directory from `$XDG_CONFIG_HOME` or `$HOME`.
pub fn system_config_dir() -> Result<PathBuf, ConfigError> {
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
        return Ok(PathBuf::from(xdg).join("truth-mirror"));
    }
    if let Some(home) = std::env::var_os("HOME").filter(|v| !v.is_empty()) {
        return Ok(PathBuf::from(home).join(".config/truth-mirror"));
    }
    Err(ConfigError::NoSystemConfigDir)
}

/// Full path to the system `config.toml`.
pub fn system_config_path() -> Result<PathBuf, ConfigError> {
    Ok(system_config_dir()?.join("config.toml"))
}

/// Write `contents` to `path` atomically by hard-linking a synced temporary file.
/// The link is the create-exclusive primitive: an existing destination is preserved.
pub(crate) fn write_config_atomically(path: &Path, contents: &str) -> Result<(), ConfigError> {
    let dir = path
        .parent()
        .ok_or_else(|| ConfigError::CreateSystemConfig {
            path: path.to_path_buf(),
            source: io::Error::new(io::ErrorKind::InvalidInput, "no parent directory"),
        })?;
    fs::create_dir_all(dir).map_err(|source| ConfigError::CreateSystemConfig {
        path: path.to_path_buf(),
        source,
    })?;
    let serial = CONFIG_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let temp_path = dir.join(format!(
        ".truth-mirror-config-{}-{serial}.tmp",
        std::process::id()
    ));
    let mut temp = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temp_path)
        .map_err(|source| ConfigError::CreateSystemConfig {
            path: path.to_path_buf(),
            source,
        })?;
    if let Err(source) = temp
        .write_all(contents.as_bytes())
        .and_then(|()| temp.sync_all())
    {
        let _ = fs::remove_file(&temp_path);
        return Err(ConfigError::CreateSystemConfig {
            path: path.to_path_buf(),
            source,
        });
    }
    let linked = fs::hard_link(&temp_path, path);
    let _ = fs::remove_file(&temp_path);
    match linked {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => Ok(()),
        Err(source) => Err(ConfigError::CreateSystemConfig {
            path: path.to_path_buf(),
            source,
        }),
    }
}

/// Create the system config from the checked-in asset when absent, preserving any
/// existing file byte-for-byte. Returns the path to the system config.
pub fn ensure_system_config() -> Result<PathBuf, ConfigError> {
    let path = system_config_path()?;
    if !path.exists() {
        write_config_atomically(&path, DEFAULT_CONFIG_ASSET)?;
    }
    Ok(path)
}
/// Create the project-local config from the checked-in asset when absent,
/// preserving any existing file byte-for-byte. Returns the path to the project
/// config.
pub fn ensure_project_config(state_dir: &Path) -> Result<PathBuf, ConfigError> {
    let path = TruthMirrorConfig::default_path(state_dir);
    if !path.exists() {
        write_config_atomically(&path, DEFAULT_CONFIG_ASSET)?;
    }
    Ok(path)
}

/// Deep-merge two TOML values. Tables merge recursively; scalars and arrays are
/// replaced by the overlay value.
fn merge_toml(base: &mut toml::Value, overlay: toml::Value) {
    match (base, overlay) {
        (toml::Value::Table(base_table), toml::Value::Table(overlay_table)) => {
            for (key, overlay_value) in overlay_table {
                let base_value = base_table
                    .entry(key)
                    .or_insert(toml::Value::Table(toml::map::Map::new()));
                merge_toml(base_value, overlay_value);
            }
        }
        (base, overlay) => *base = overlay,
    }
}

fn read_toml_value(path: &Path) -> Result<Option<toml::Value>, ConfigError> {
    match fs::read_to_string(path) {
        Ok(contents) => {
            let table = contents
                .parse::<toml::Table>()
                .map_err(|source| ConfigError::Parse {
                    path: path.to_path_buf(),
                    source,
                })?;
            Ok(Some(toml::Value::Table(table)))
        }
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(source) => Err(ConfigError::Read {
            path: path.to_path_buf(),
            source,
        }),
    }
}

fn parse_env_enabled() -> Result<Option<bool>, ConfigError> {
    match std::env::var_os(TRUTH_MIRROR_ENABLED_ENV) {
        None => Ok(None),
        Some(raw) => {
            let s = raw.to_string_lossy().trim().to_ascii_lowercase();
            match s.as_str() {
                "true" | "1" => Ok(Some(true)),
                "false" | "0" => Ok(Some(false)),
                _ => Err(ConfigError::InvalidEnabledEnv {
                    value: raw.to_string_lossy().into_owned(),
                }),
            }
        }
    }
}

impl TruthMirrorConfig {
    /// Effective runtime loader: built-in defaults < system config < project or
    /// explicit config < `TRUTH_MIRROR_ENABLED` env var. The optional system
    /// layer is read-only and best-effort; installation materializes it.
    /// Monotonic `enabled`: any system/project/env false disables; true never
    /// re-enables a lower false layer.
    pub fn load_for_cli(
        explicit_path: Option<&Path>,
        state_dir: &Path,
    ) -> Result<Self, ConfigError> {
        let project_path = if let Some(path) = explicit_path {
            PathBuf::from(path)
        } else {
            // Resolve the project config path WITHOUT creating it. Loading config
            // happens for every command, including `install-hooks --dry-run` and
            // commands that fail a precondition, and both must leave no `.truth`
            // behind. Project-local materialization is owned by the install path
            // (hooks::ensure_state_gitignore -> ensure_default_config).
            Self::default_path(state_dir)
        };
        Self::load_effective(project_path)
    }

    fn load_effective(project_path: PathBuf) -> Result<Self, ConfigError> {
        // The checked-in asset is the authoritative default surface; parse it once
        // and use it as the merge base so every non-legacy key is present.
        let mut base: toml::Value = toml::Value::Table(
            DEFAULT_CONFIG_ASSET
                .parse::<toml::Table>()
                .expect("checked-in assets/config.toml must be valid TOML"),
        );

        // Track `enabled` across layers with AND semantics: any explicit false
        // from any layer disables inference; true cannot re-enable after false.
        let mut enabled = true;

        if let Ok(system_path) = system_config_path()
            && system_path.is_file()
        {
            match read_toml_value(&system_path) {
                Ok(Some(system)) => {
                    if system.get("enabled").and_then(toml::Value::as_bool) == Some(false) {
                        enabled = false;
                    }
                    merge_toml(&mut base, system);
                }
                Ok(None) | Err(ConfigError::Read { .. }) => {}
                Err(error) => return Err(error),
            }
        }

        if let Some(project) = read_toml_value(&project_path)? {
            if project.get("enabled").and_then(toml::Value::as_bool) == Some(false) {
                enabled = false;
            }
            merge_toml(&mut base, project);
        }

        let env_enabled = parse_env_enabled()?;
        let final_enabled = enabled && env_enabled.unwrap_or(true);
        if let Some(table) = base.as_table_mut() {
            table.insert("enabled".to_owned(), toml::Value::Boolean(final_enabled));
        }

        let mut config: Self = base.try_into().map_err(|source| ConfigError::Parse {
            path: project_path.clone(),
            source,
        })?;
        config.normalize();
        config.validate()?;
        Ok(config)
    }
    pub fn load_or_default(path: impl Into<PathBuf>) -> Result<Self, ConfigError> {
        let path = path.into();
        match fs::read_to_string(&path) {
            Ok(contents) => Self::from_toml_str(&path, &contents),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
            Err(source) => Err(ConfigError::Read { path, source }),
        }
    }

    pub fn from_toml_str(path: &Path, contents: &str) -> Result<Self, ConfigError> {
        let mut config: Self = toml::from_str(contents).map_err(|source| ConfigError::Parse {
            path: path.to_path_buf(),
            source,
        })?;
        config.normalize();
        config.validate()?;
        Ok(config)
    }

    /// Resolve the effective `pairs`: explicit `[pairs]` win; a legacy `[review]`
    /// block folds in as an OVERRIDE for its writer (on top of defaults so other
    /// writers still resolve); with neither, all writers get default pairs.
    fn normalize(&mut self) {
        // Lowercase explicit pair keys FIRST so every comparison below is
        // case-insensitive (matching `pair_for`). Otherwise a `[pairs.CODEX]` could
        // be clobbered by a legacy `[review]` folded under `codex`.
        let lowered: BTreeMap<String, AdversarialPair> = std::mem::take(&mut self.pairs)
            .into_iter()
            .map(|(key, value)| (key.trim().to_ascii_lowercase(), value))
            .collect();
        self.pairs = lowered;

        let had_explicit_pairs = !self.pairs.is_empty();
        let review = self.review.take();

        if !had_explicit_pairs && review.is_some() {
            // Legacy-only config: seed defaults so non-legacy writers still resolve.
            self.pairs = default_pairs();
        }

        if let Some(review) = review {
            let writer = review.watched.harness.trim().to_ascii_lowercase();
            let pair = AdversarialPair {
                reviewer: HarnessSelection::new(
                    review.reviewer.harness,
                    review.reviewer.model,
                    Effort::highest(),
                ),
                arbiter: None,
            };
            if had_explicit_pairs {
                // Explicit `[pairs]` win: legacy only fills a writer they omit.
                self.pairs.entry(writer).or_insert(pair);
            } else {
                // Legacy-only config: override the seeded default for this writer.
                self.pairs.insert(writer, pair);
            }
        }

        if self.pairs.is_empty() {
            self.pairs = default_pairs();
        }
        if self.history.transcript_path.as_deref() == Some("") {
            self.history.transcript_path = None;
        }
    }

    fn validate(&self) -> Result<(), ConfigError> {
        for (writer, pair) in &self.pairs {
            if let Some(arbiter) = &pair.arbiter
                && normalized_model(&arbiter.model) == normalized_model(&pair.reviewer.model)
            {
                return Err(ConfigError::ArbiterNotDistinct {
                    writer: writer.clone(),
                });
            }
        }
        if !self.memory_skill.scan.entropy_threshold.is_finite()
            || self.memory_skill.scan.entropy_threshold <= 0.0
        {
            return Err(ConfigError::InvalidMemorySkillEntropyThreshold {
                value: self.memory_skill.scan.entropy_threshold,
            });
        }
        if !self.memory_skill.signals.similarity_threshold.is_finite()
            || !(0.0..=1.0).contains(&self.memory_skill.signals.similarity_threshold)
        {
            return Err(ConfigError::InvalidMemorySkillSimilarityThreshold {
                value: self.memory_skill.signals.similarity_threshold,
            });
        }
        if !(1..=MAX_PETITION_BATCH_SIZE).contains(&self.reviewer.max_petition_batch_size) {
            return Err(ConfigError::InvalidPetitionBatchSize {
                value: self.reviewer.max_petition_batch_size,
            });
        }
        if !(1..=MAX_CONCURRENT_REVIEW_RUNS).contains(&self.reviewer.max_concurrent_runs) {
            return Err(ConfigError::InvalidConcurrentReviewRuns {
                value: self.reviewer.max_concurrent_runs,
            });
        }

        if self.memory_skill.max_skill_bytes == 0 {
            return Err(ConfigError::InvalidMemorySkillMaxSkillBytes);
        }
        if self.memory_skill.scan.secret_detector_timeout_seconds == 0 {
            return Err(ConfigError::InvalidMemorySkillSecretDetectorTimeout);
        }
        Ok(())
    }

    /// The adversarial pair for a writer harness (case-insensitive).
    pub fn pair_for(&self, writer_harness: &str) -> Option<&AdversarialPair> {
        self.pairs.get(&writer_harness.trim().to_ascii_lowercase())
    }

    pub fn default_path(state_dir: &Path) -> PathBuf {
        state_dir.join("config.toml")
    }
    #[cfg(test)]
    fn from_test_sources(
        system: Option<&str>,
        project: &str,
        env_enabled: Option<bool>,
    ) -> Result<Self, ConfigError> {
        let mut base: toml::Value = toml::Value::Table(
            DEFAULT_CONFIG_ASSET
                .parse::<toml::Table>()
                .expect("checked-in asset must be valid TOML"),
        );
        let mut enabled = true;
        if let Some(system) = system {
            let value: toml::Value =
                toml::from_str(system).map_err(|source| ConfigError::Parse {
                    path: PathBuf::from("system.toml"),
                    source,
                })?;
            if value.get("enabled").and_then(toml::Value::as_bool) == Some(false) {
                enabled = false;
            }
            merge_toml(&mut base, value);
        }
        let project_value: toml::Value =
            toml::from_str(project).map_err(|source| ConfigError::Parse {
                path: PathBuf::from("project.toml"),
                source,
            })?;
        if project_value.get("enabled").and_then(toml::Value::as_bool) == Some(false) {
            enabled = false;
        }
        merge_toml(&mut base, project_value);

        let final_enabled = enabled && env_enabled.unwrap_or(true);
        if let Some(table) = base.as_table_mut() {
            table.insert("enabled".to_owned(), toml::Value::Boolean(final_enabled));
        }

        let mut config: Self = base.try_into().map_err(|source| ConfigError::Parse {
            path: PathBuf::from("project.toml"),
            source,
        })?;
        config.normalize();
        config.validate()?;
        Ok(config)
    }
}

/// Default per-review wall-clock timeout: 20 minutes. Two days of field use
/// showed wedged reviewer subprocesses running 1–7 hours with the queue frozen
/// behind them; a healthy adversarial review takes minutes, so 20 minutes is
/// comfortably past legitimate work and short enough to unstick the queue.
pub const DEFAULT_REVIEWER_TIMEOUT_SECS: u64 = 20 * 60;

/// Reviewer queue policies, subprocess settings, and concurrent scheduling.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct ReviewerPolicyConfig {
    /// Opt-in compatibility boundary: false retains one reviewer invocation per petition.
    pub batch_petitions: bool,
    pub max_petition_batch_size: usize,
    /// Per-review wall-clock timeout in seconds. A reviewer subprocess that
    /// outlives this is killed and the run recorded as failed with a timeout
    /// reason, so one wedged reviewer never freezes the queue. `0` disables
    /// the timeout.
    pub timeout_secs: u64,
    /// Maximum number of independent reviewer processes in one drain wave.
    /// `1` preserves the historical serial scheduler.
    pub max_concurrent_runs: usize,
}

impl Default for ReviewerPolicyConfig {
    fn default() -> Self {
        Self {
            batch_petitions: false,
            max_petition_batch_size: MAX_PETITION_BATCH_SIZE,
            timeout_secs: DEFAULT_REVIEWER_TIMEOUT_SECS,
            max_concurrent_runs: 1,
        }
    }
}

impl ReviewerPolicyConfig {
    /// The configured timeout as a duration, or `None` when disabled (`0`).
    pub fn timeout(&self) -> Option<std::time::Duration> {
        (self.timeout_secs > 0).then(|| std::time::Duration::from_secs(self.timeout_secs))
    }
}

/// Legacy single watched/reviewer pair (pre-adversarial-pairs config).
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct LegacyReview {
    pub watched: LegacyModel,
    pub reviewer: LegacyModel,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct LegacyModel {
    pub harness: String,
    pub model: String,
}

/// Strict goal-loop thresholds. `N == 0` disables that stop condition.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct StrictConfig {
    pub stop_after_lies: u32,
    pub stop_after_fuckups: u32,
    pub max_passes: u32,
}

impl Default for StrictConfig {
    fn default() -> Self {
        Self {
            stop_after_lies: 1,
            stop_after_fuckups: 3,
            max_passes: 3,
        }
    }
}

impl StrictConfig {
    pub fn goal_policy(
        &self,
        lies_override: Option<u32>,
        fuckups_override: Option<u32>,
    ) -> crate::reviewer::StrictGoalPolicy {
        crate::reviewer::StrictGoalPolicy {
            stop_after_lies: lies_override.unwrap_or(self.stop_after_lies),
            stop_after_fuckups: fuckups_override.unwrap_or(self.stop_after_fuckups),
        }
    }
}

/// Deterministic-gate configuration: banned diff sentinels, evidence patterns,
/// and diff paths excluded from marker scanning.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GatesConfig {
    pub fake_markers: Vec<String>,
    pub evidence_patterns: Vec<String>,
    pub marker_ignore_paths: Vec<String>,
}

impl Default for GatesConfig {
    fn default() -> Self {
        Self {
            fake_markers: strs(crate::claim::DEFAULT_FAKE_MARKERS),
            evidence_patterns: strs(crate::claim::DEFAULT_EVIDENCE_PATTERNS),
            marker_ignore_paths: strs(crate::claim::DEFAULT_MARKER_IGNORE_PATHS),
        }
    }
}

impl GatesConfig {
    /// The resolved gate policy: config values plus built-in defaults for any
    /// list left empty, so an empty config never silently disables a gate.
    pub fn to_policy(&self) -> crate::claim::GatePolicy {
        crate::claim::GatePolicy {
            fake_markers: union_defaults(&self.fake_markers, crate::claim::DEFAULT_FAKE_MARKERS),
            evidence_patterns: union_defaults(
                &self.evidence_patterns,
                crate::claim::DEFAULT_EVIDENCE_PATTERNS,
            ),
            marker_ignore_paths: union_defaults(
                &self.marker_ignore_paths,
                crate::claim::DEFAULT_MARKER_IGNORE_PATHS,
            ),
        }
    }
}

fn strs(values: &[&str]) -> Vec<String> {
    values.iter().map(|value| (*value).to_owned()).collect()
}

/// Built-in defaults ALWAYS apply; configured values are additive. A repo can add
/// its own banned tokens or evidence patterns but cannot silently disable the
/// deterministic anti-lie defaults by setting a shorter list.
fn union_defaults(values: &[String], defaults: &[&str]) -> Vec<String> {
    let mut out: Vec<String> = strs(defaults);
    for value in values {
        if !out.iter().any(|existing| existing == value) {
            out.push(value.clone());
        }
    }
    out
}

/// Ground-truth constraint loading.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GroundTruthConfig {
    pub enabled: bool,
    pub file_names: Vec<String>,
    pub include_openspec_specs: bool,
    pub max_bytes: usize,
}

impl Default for GroundTruthConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            file_names: ["TRUTH.md", "AGENTS.md", "CLAUDE.md", ".truth/TRUTH.md"]
                .iter()
                .map(|name| (*name).to_owned())
                .collect(),
            include_openspec_specs: true,
            max_bytes: 20_000,
        }
    }
}

/// Conversation-trajectory window.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct HistoryConfig {
    pub window_user: usize,
    pub window_agent: usize,
    pub max_bytes: usize,
    /// Optional repo-relative JSONL transcript (`{role,text}` per line). When
    /// unset or missing, recent commits are used as the trajectory proxy.
    pub transcript_path: Option<String>,
}

impl Default for HistoryConfig {
    fn default() -> Self {
        Self {
            window_user: 3,
            window_agent: 10,
            max_bytes: 12_000,
            transcript_path: None,
        }
    }
}

/// Enforcement escalation thresholds. `0` disables a condition.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct EnforcementConfig {
    pub block_tools_after_unresolved: u32,
    pub block_tools_after_secs: u64,
}

impl EnforcementConfig {
    pub fn is_enabled(&self) -> bool {
        self.block_tools_after_unresolved > 0 || self.block_tools_after_secs > 0
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct SkillsConfig {
    pub enabled: bool,
}

impl Default for SkillsConfig {
    fn default() -> Self {
        Self { enabled: true }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MemorySkillMode {
    Off,
    Suggest,
    #[default]
    Stage,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MemorySkillCandidateKind {
    HowToSkill,
    AntiPatternSkill,
    RemediationSkill,
}

impl MemorySkillCandidateKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::HowToSkill => "how_to_skill",
            Self::AntiPatternSkill => "anti_pattern_skill",
            Self::RemediationSkill => "remediation_skill",
        }
    }
}

impl std::fmt::Display for MemorySkillCandidateKind {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct MemorySkillConfig {
    pub enabled: bool,
    pub mode: MemorySkillMode,
    pub candidate_dir: String,
    pub approved_dir: String,
    pub approved_slug_prefix: String,
    pub toolbox_delivery_registry: String,
    pub allow_global_writes: bool,
    pub require_claim_evidence: bool,
    pub max_candidates_per_commit: usize,
    pub max_skill_bytes: usize,
    pub pre_push_blocks_pending: bool,
    /// Historical config key: when true, `memory_skill::scan_text` rejects the
    /// whole candidate on secret matches; it does not redact matched text in
    /// place. Scanning is fully disabled only when this is false and
    /// `memory_skill.scan.secret_detection = "off"`.
    pub redact_secrets: bool,
    pub signals: MemorySkillSignalsConfig,
    pub review: MemorySkillReviewConfig,
    pub scan: MemorySkillScanConfig,
}

impl Default for MemorySkillConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            mode: MemorySkillMode::Stage,
            candidate_dir: format!("{DEFAULT_STATE_DIR}/skills/candidates"),
            approved_dir: ".agents/skills".to_owned(),
            approved_slug_prefix: "generated-".to_owned(),
            toolbox_delivery_registry: String::new(),
            allow_global_writes: false,
            require_claim_evidence: true,
            max_candidates_per_commit: 1,
            max_skill_bytes: 12_000,
            pre_push_blocks_pending: false,
            redact_secrets: true,
            signals: MemorySkillSignalsConfig::default(),
            review: MemorySkillReviewConfig::default(),
            scan: MemorySkillScanConfig::default(),
        }
    }
}

impl MemorySkillConfig {
    pub fn effective_enabled(&self, skills: &SkillsConfig) -> bool {
        skills.enabled && self.enabled && self.mode != MemorySkillMode::Off
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct MemorySkillSignalsConfig {
    pub similarity_threshold: f64,
    pub min_occurrences: usize,
    pub require_reusable_procedure: bool,
    pub capture_passes_as_how_to: bool,
    pub capture_rejections_as_remediation: bool,
    pub capture_rejections_as_antipattern: bool,
    pub rejection_precedence: Vec<MemorySkillCandidateKind>,
}

impl Default for MemorySkillSignalsConfig {
    fn default() -> Self {
        Self {
            similarity_threshold: 0.55,
            min_occurrences: 2,
            require_reusable_procedure: true,
            capture_passes_as_how_to: true,
            capture_rejections_as_remediation: true,
            capture_rejections_as_antipattern: true,
            rejection_precedence: vec![
                MemorySkillCandidateKind::AntiPatternSkill,
                MemorySkillCandidateKind::RemediationSkill,
            ],
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct MemorySkillReviewConfig {
    pub require_adversarial_review: bool,
    pub require_reviewed_ledger_entry: bool,
    pub require_pass_for_how_to: bool,
    pub require_structured_findings_checked: bool,
    pub reject_without_ledger_entry: bool,
}

impl Default for MemorySkillReviewConfig {
    fn default() -> Self {
        Self {
            require_adversarial_review: true,
            require_reviewed_ledger_entry: true,
            require_pass_for_how_to: true,
            require_structured_findings_checked: true,
            reject_without_ledger_entry: true,
        }
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct MemorySkillScanConfig {
    pub secret_detection: SecretDetectionMode,
    /// Optional scanner command. A non-zero exit is treated as a detected
    /// finding; best-effort mode only downgrades operational failures.
    pub secret_detector: String,
    pub allow_secret_detector_command: bool,
    pub secret_detector_timeout_seconds: u64,
    pub entropy_threshold: f64,
    pub blocked_patterns: Vec<String>,
    pub blocked_patterns_case_insensitive: bool,
}

impl Default for MemorySkillScanConfig {
    fn default() -> Self {
        Self {
            secret_detection: SecretDetectionMode::Required,
            secret_detector: String::new(),
            allow_secret_detector_command: false,
            secret_detector_timeout_seconds: 10,
            entropy_threshold: 4.5,
            blocked_patterns: Vec::new(),
            blocked_patterns_case_insensitive: true,
        }
    }
}

impl MemorySkillScanConfig {
    pub fn effective_blocked_patterns(&self) -> Vec<String> {
        let mut patterns = Vec::new();
        for pattern in DEFAULT_MEMORY_SKILL_BLOCKED_PATTERNS {
            push_unique_pattern(
                &mut patterns,
                pattern,
                self.blocked_patterns_case_insensitive,
            );
        }
        for pattern in &self.blocked_patterns {
            push_unique_pattern(
                &mut patterns,
                pattern,
                self.blocked_patterns_case_insensitive,
            );
        }
        patterns
    }
}

fn push_unique_pattern(patterns: &mut Vec<String>, pattern: &str, case_insensitive: bool) {
    let pattern = pattern.trim();
    if pattern.is_empty()
        || patterns.iter().any(|existing| {
            if case_insensitive {
                existing.eq_ignore_ascii_case(pattern)
            } else {
                existing == pattern
            }
        })
    {
        return;
    }
    patterns.push(pattern.to_owned());
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SecretDetectionMode {
    #[default]
    Required,
    BestEffort,
    Off,
}

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("failed to read config {path}: {source}")]
    Read {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error("failed to parse config {path}: {source}")]
    Parse {
        path: PathBuf,
        #[source]
        source: toml::de::Error,
    },
    #[error("failed to create system config {path}: {source}")]
    CreateSystemConfig {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error("TRUTH_MIRROR_ENABLED must be 'true', 'false', '1', or '0', got '{value}'")]
    InvalidEnabledEnv { value: String },
    #[error("could not resolve system config directory; set XDG_CONFIG_HOME or HOME")]
    NoSystemConfigDir,
    #[error("pair for writer {writer:?} has an arbiter model equal to the reviewer model")]
    ArbiterNotDistinct { writer: String },
    #[error("memory_skill.scan.entropy_threshold must be finite and greater than 0.0, got {value}")]
    InvalidMemorySkillEntropyThreshold { value: f64 },
    #[error(
        "memory_skill.signals.similarity_threshold must be finite and between 0.0 and 1.0, got {value}"
    )]
    InvalidMemorySkillSimilarityThreshold { value: f64 },
    #[error(
        "reviewer.max_petition_batch_size must be between 1 and {MAX_PETITION_BATCH_SIZE}, got {value}"
    )]
    InvalidPetitionBatchSize { value: usize },
    #[error(
        "reviewer.max_concurrent_runs must be between 1 and {MAX_CONCURRENT_REVIEW_RUNS}, got {value}"
    )]
    InvalidConcurrentReviewRuns { value: usize },
    #[error("memory_skill.max_skill_bytes must be greater than 0")]
    InvalidMemorySkillMaxSkillBytes,
    #[error("memory_skill.scan.secret_detector_timeout_seconds must be greater than 0")]
    InvalidMemorySkillSecretDetectorTimeout,
}

fn default_enabled() -> bool {
    true
}

fn default_announce_when_disabled() -> bool {
    true
}

fn default_ledger_dir() -> String {
    DEFAULT_STATE_DIR.to_owned()
}

fn default_writer() -> String {
    "codex".to_owned()
}

/// Sensible opposed pairs so a repo with no `[pairs]` still reviews adversarially.
fn default_pairs() -> BTreeMap<String, AdversarialPair> {
    let mut pairs = BTreeMap::new();
    pairs.insert(
        "codex".to_owned(),
        AdversarialPair {
            reviewer: HarnessSelection::new("claude", "claude-opus-4-8", Effort::highest()),
            arbiter: Some(HarnessSelection::new(
                "pi",
                "openai-codex/gpt-5.5",
                Effort::highest(),
            )),
        },
    );
    pairs.insert(
        "claude".to_owned(),
        AdversarialPair {
            reviewer: HarnessSelection::new("codex", "gpt-5.5", Effort::highest()),
            // Arbiter must be a third distinct model. The reviewer is codex/gpt-5.5;
            // using pi/openai-codex/gpt-5.5 as arbiter would be the SAME underlying
            // model after provider-prefix stripping, violating the distinct-model rule.
            // Gemini (gemini-2.5-pro) is a genuinely different family and provider,
            // and InvocationPlan::for_harness supports ReviewerHarness::Gemini.
            arbiter: Some(HarnessSelection::new(
                "gemini",
                "gemini-2.5-pro",
                Effort::highest(),
            )),
        },
    );
    pairs.insert(
        "pi".to_owned(),
        AdversarialPair {
            reviewer: HarnessSelection::new("codex", "gpt-5.5", Effort::highest()),
            arbiter: Some(HarnessSelection::new(
                "claude",
                "claude-opus-4-8",
                Effort::highest(),
            )),
        },
    );
    // Grok is a watched agent surface, not a reviewer harness. Oppose with Claude
    // review + Codex arbiter so model/provider families stay distinct by default.
    pairs.insert(
        "grok".to_owned(),
        AdversarialPair {
            reviewer: HarnessSelection::new("claude", "claude-opus-4-8", Effort::highest()),
            arbiter: Some(HarnessSelection::new("codex", "gpt-5.5", Effort::highest())),
        },
    );
    pairs
}

/// Normalise a model identifier for opposition comparisons.
///
/// Strips the provider prefix (everything up to and including the last `/`)
/// so `openai-codex/gpt-5.5` compares equal to `gpt-5.5`. Keeps config
/// validation consistent with the runtime check in `reviewer::normalized_model`.
/// The prefix is only stripped when it leaves a non-empty suffix.
pub(crate) fn normalized_model(model: &str) -> String {
    let model = model.trim();
    let short = model
        .rsplit_once('/')
        .and_then(|(_, suffix)| {
            let s = suffix.trim();
            if s.is_empty() { None } else { Some(s) }
        })
        .unwrap_or(model);
    short.to_ascii_lowercase()
}

#[cfg(test)]
fn parse_env_enabled_for_test(value: &str) -> Result<Option<bool>, ConfigError> {
    if value.is_empty() {
        return Ok(None);
    }
    match value.trim().to_ascii_lowercase().as_str() {
        "true" | "1" => Ok(Some(true)),
        "false" | "0" => Ok(Some(false)),
        _ => Err(ConfigError::InvalidEnabledEnv {
            value: value.to_owned(),
        }),
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn default_config_has_four_opposed_pairs() {
        let config = TruthMirrorConfig::default();

        assert_eq!(config.pairs.len(), 4);
        assert_eq!(config.ledger_dir, ".truth");
        assert!(config.skills.enabled);
        assert!(config.memory_skill.enabled);
        assert!(config.memory_skill.effective_enabled(&config.skills));
        assert_eq!(config.memory_skill.mode, super::MemorySkillMode::Stage);
        assert_eq!(config.memory_skill.signals.similarity_threshold, 0.55);
        let codex = config.pair_for("codex").unwrap();
        assert_eq!(codex.reviewer.harness, "claude");
        assert_eq!(codex.reviewer.model, "claude-opus-4-8");
        assert_eq!(codex.reviewer.effort, Effort::Xhigh);
        let grok = config.pair_for("grok").unwrap();
        assert_eq!(grok.reviewer.harness, "claude");
        assert_eq!(grok.reviewer.model, "claude-opus-4-8");
    }

    #[test]
    fn reviewer_batching_defaults_to_legacy_serial_petitions() {
        let config = TruthMirrorConfig::default();

        assert!(!config.reviewer.batch_petitions);
        assert_eq!(
            config.reviewer.max_petition_batch_size,
            super::MAX_PETITION_BATCH_SIZE
        );
        assert_eq!(config.reviewer.max_concurrent_runs, 1);
    }

    #[test]
    fn reviewer_batching_policy_parses_when_explicitly_enabled() {
        let contents = r#"
[reviewer]
batch_petitions = true
max_petition_batch_size = 7
max_concurrent_runs = 2
"#;

        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        assert!(config.reviewer.batch_petitions);
        assert_eq!(config.reviewer.max_petition_batch_size, 7);
        assert_eq!(config.reviewer.max_concurrent_runs, 2);
    }

    #[test]
    fn reviewer_concurrency_rejects_zero_and_values_above_the_bound() {
        for value in [0, super::MAX_CONCURRENT_REVIEW_RUNS + 1] {
            let contents = format!("[reviewer]\nmax_concurrent_runs = {value}\n");

            let error =
                TruthMirrorConfig::from_toml_str(Path::new("config.toml"), &contents).unwrap_err();

            assert!(matches!(
                error,
                super::ConfigError::InvalidConcurrentReviewRuns { value: invalid }
                    if invalid == value
            ));
        }
    }

    #[test]
    fn reviewer_batch_size_rejects_zero_and_values_above_the_bound() {
        for value in [0, super::MAX_PETITION_BATCH_SIZE + 1] {
            let contents =
                format!("[reviewer]\nbatch_petitions = true\nmax_petition_batch_size = {value}\n");

            let error =
                TruthMirrorConfig::from_toml_str(Path::new("config.toml"), &contents).unwrap_err();

            assert!(matches!(
                error,
                super::ConfigError::InvalidPetitionBatchSize { value: invalid }
                    if invalid == value
            ));
        }
    }

    #[test]
    fn reviewer_timeout_defaults_to_twenty_minutes() {
        let config = TruthMirrorConfig::default();

        assert_eq!(
            config.reviewer.timeout_secs,
            super::DEFAULT_REVIEWER_TIMEOUT_SECS
        );
        assert_eq!(
            config.reviewer.timeout(),
            Some(std::time::Duration::from_secs(20 * 60))
        );
    }

    #[test]
    fn reviewer_timeout_parses_and_zero_disables() {
        // A wedged reviewer froze the ONYXIO queue for hours (0.9.2 field
        // report): the timeout is configurable, and 0 opts out explicitly.
        let contents = "[reviewer]\ntimeout_secs = 90\n";
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();
        assert_eq!(
            config.reviewer.timeout(),
            Some(std::time::Duration::from_secs(90))
        );

        let disabled = "[reviewer]\ntimeout_secs = 0\n";
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), disabled).unwrap();
        assert_eq!(config.reviewer.timeout(), None);
    }

    #[test]
    fn effort_serializes_lowercase() {
        assert_eq!(Effort::Xhigh.as_str(), "xhigh");
        assert_eq!(Effort::highest(), Effort::Xhigh);
    }

    #[test]
    fn pairs_config_parses_and_resolves_by_writer() {
        // Arbiter must be distinct from reviewer after provider-prefix stripping:
        // gemini/gemini-2.5-pro normalizes to "gemini-2.5-pro", which != "gpt-5.5".
        let contents = r#"
default_writer = "claude"

[pairs.claude]
reviewer = { harness = "codex", model = "gpt-5.5", effort = "xhigh" }
arbiter  = { harness = "gemini", model = "gemini-2.5-pro", effort = "high" }

[pairs.codex]
reviewer = { harness = "claude", model = "claude-opus-4-8" }
"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        let claude_pair = config.pair_for("claude").unwrap();
        assert_eq!(claude_pair.reviewer.harness, "codex");
        assert_eq!(claude_pair.reviewer.effort, Effort::Xhigh);
        assert_eq!(claude_pair.arbiter.as_ref().unwrap().effort, Effort::High);

        // Omitted effort defaults to highest.
        let codex_pair = config.pair_for("codex").unwrap();
        assert_eq!(codex_pair.reviewer.effort, Effort::Xhigh);
    }

    #[test]
    fn arbiter_same_as_reviewer_after_prefix_strip_is_rejected() {
        // openai-codex/gpt-5.5 normalizes to gpt-5.5, same as the reviewer model.
        // This was the bug in the original claude default pair (B1/B2 remediation).
        let contents = r#"
[pairs.claude]
reviewer = { harness = "codex", model = "gpt-5.5" }
arbiter  = { harness = "pi", model = "openai-codex/gpt-5.5" }
"#;
        let result = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("arbiter"),
            "expected arbiter error, got: {err}"
        );
    }

    #[test]
    fn default_claude_pair_arbiter_is_distinct_from_reviewer() {
        // B1 fix: the claude default pair used to have arbiter=pi/openai-codex/gpt-5.5
        // and reviewer=codex/gpt-5.5. After provider-prefix stripping both normalize
        // to "gpt-5.5", which is the same model. The fix changed the arbiter to
        // gemini/gemini-2.5-pro. This test ensures the default config loads without
        // ArbiterNotDistinct and has a genuinely distinct arbiter.
        let config = TruthMirrorConfig::default();
        let pair = config.pair_for("claude").expect("claude pair must exist");
        let arbiter = pair.arbiter.as_ref().expect("claude arbiter must be set");
        assert_eq!(
            arbiter.harness, "gemini",
            "claude arbiter harness must be gemini"
        );
        assert_ne!(
            super::normalized_model(&arbiter.model),
            super::normalized_model(&pair.reviewer.model),
            "claude arbiter must be distinct from reviewer after normalization"
        );
    }

    #[test]
    fn normalized_strips_provider_prefix_for_comparison() {
        // B2: openai-codex/gpt-5.5 and gpt-5.5 should normalize to the same token.
        assert_eq!(
            super::normalized_model("openai-codex/gpt-5.5"),
            super::normalized_model("gpt-5.5")
        );
        // Prefix-only values (bare "/") keep their identity to avoid false collisions.
        assert_ne!(super::normalized_model("/"), super::normalized_model(""));
    }

    #[test]
    fn legacy_review_block_overrides_default_pair() {
        // Reviewer distinct from the built-in codex default (claude/opus-4-8) so
        // the test proves the legacy block actually overrides the default rather
        // than coincidentally matching it.
        let contents = r#"
ledger_dir = ".truth-mirror"

[review.watched]
harness = "codex"
model = "gpt-5.5"

[review.reviewer]
harness = "gemini"
model = "gemini-3-pro"
"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        let pair = config.pair_for("codex").unwrap();
        assert_eq!(pair.reviewer.harness, "gemini");
        assert_eq!(pair.reviewer.model, "gemini-3-pro");
        // Other writers still resolve from defaults.
        assert!(config.pair_for("claude").is_some());
        assert!(config.pair_for("pi").is_some());
        assert!(config.pair_for("grok").is_some());
    }

    #[test]
    fn explicit_pairs_win_over_legacy_review() {
        // A mixed migration config must not let legacy [review] clobber a modern
        // explicit [pairs.<writer>] entry.
        let contents = r#"
[pairs.codex]
reviewer = { harness = "claude", model = "explicit-model" }

[review.watched]
harness = "codex"
model = "gpt-5.5"

[review.reviewer]
harness = "gemini"
model = "legacy-model"
"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        let pair = config.pair_for("codex").unwrap();
        assert_eq!(pair.reviewer.harness, "claude");
        assert_eq!(pair.reviewer.model, "explicit-model");
    }

    #[test]
    fn explicit_pairs_win_case_insensitively_over_legacy() {
        // `[pairs.CODEX]` (uppercase) must not be clobbered by a legacy [review]
        // folded under lowercase `codex`.
        let contents = r#"
[pairs.CODEX]
reviewer = { harness = "claude", model = "explicit-model" }

[review.watched]
harness = "codex"
model = "gpt-5.5"

[review.reviewer]
harness = "gemini"
model = "legacy-model"
"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        let pair = config.pair_for("codex").unwrap();
        assert_eq!(pair.reviewer.model, "explicit-model");
        // No duplicate CODEX/codex entries.
        assert_eq!(config.pairs.len(), 1);
    }

    #[test]
    fn arbiter_equal_to_reviewer_model_is_rejected() {
        let contents = r#"
[pairs.codex]
reviewer = { harness = "claude", model = "same-model" }
arbiter  = { harness = "pi", model = "same-model" }
"#;
        let error =
            TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap_err();

        assert!(matches!(
            error,
            super::ConfigError::ArbiterNotDistinct { .. }
        ));
    }

    #[test]
    fn missing_config_loads_default() {
        let config = TruthMirrorConfig::load_or_default("missing-config.toml").unwrap();

        assert_eq!(config.pairs.len(), 4);
        assert!(config.ground_truth.enabled);
        assert_eq!(config.history.window_user, 3);
        assert!(!config.enforcement.is_enabled());
    }

    #[test]
    fn gates_config_parses_and_builds_policy() {
        let contents = r#"
[pairs.codex]
reviewer = { harness = "claude", model = "claude-opus-4-8" }

[gates]
fake_markers = ["pretend-pass"]
evidence_patterns = ["jira:"]
marker_ignore_paths = [".md", "vendor/"]
"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        // Config values are ADDITIVE: built-in defaults always apply, plus the
        // repo's custom entries. A repo can add but not silently disable defaults.
        // The default marker literal is built at runtime so it never appears as an
        // added line in this file (truth-mirror's own gate would flag it).
        let default_marker = ["mock", "as", "real"].join("-");
        let policy = config.gates.to_policy();
        assert!(policy.fake_markers.iter().any(|m| m == "pretend-pass"));
        assert!(policy.fake_markers.contains(&default_marker));
        assert!(policy.evidence_patterns.iter().any(|p| p == "jira:"));
        assert!(policy.evidence_patterns.iter().any(|p| p == "tests:"));
        assert!(policy.marker_ignore_paths.iter().any(|p| p == "vendor/"));
        assert!(policy.marker_ignore_paths.iter().any(|p| p == "openspec/"));
    }

    #[test]
    fn memory_skill_effective_enabled_requires_parent_self_and_active_mode() {
        let skills_enabled = super::SkillsConfig { enabled: true };
        let skills_disabled = super::SkillsConfig { enabled: false };
        let mut memory = super::MemorySkillConfig {
            enabled: true,
            mode: super::MemorySkillMode::Stage,
            ..super::MemorySkillConfig::default()
        };

        assert!(memory.effective_enabled(&skills_enabled));
        assert!(!memory.effective_enabled(&skills_disabled));

        memory.enabled = false;
        assert!(!memory.effective_enabled(&skills_enabled));

        memory.enabled = true;
        memory.mode = super::MemorySkillMode::Off;
        assert!(!memory.effective_enabled(&skills_enabled));
    }

    #[test]
    fn missing_config_file_enables_memory_skill() {
        let temp = tempfile::tempdir().unwrap();
        let config = TruthMirrorConfig::load_or_default(temp.path().join("missing.toml")).unwrap();

        assert!(config.skills.enabled);
        assert!(config.memory_skill.enabled);
        assert!(config.memory_skill.effective_enabled(&config.skills));
    }

    #[test]
    fn empty_config_enables_memory_skill() {
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), "").unwrap();

        assert!(config.skills.enabled);
        assert!(config.memory_skill.enabled);
        assert!(config.memory_skill.effective_enabled(&config.skills));
    }

    #[test]
    fn config_without_skill_sections_enables_memory_skill() {
        let contents = r#"
[history]
window_user = 5

"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        assert!(config.skills.enabled);
        assert!(config.memory_skill.enabled);
        assert!(config.memory_skill.effective_enabled(&config.skills));
    }

    #[test]
    fn memory_skill_rejection_precedence_is_legacy_compatible() {
        let contents = r#"
[memory_skill.signals]
rejection_precedence = ["how_to_skill"]
"#;

        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        assert_eq!(
            config.memory_skill.signals.rejection_precedence,
            vec![super::MemorySkillCandidateKind::HowToSkill]
        );
    }

    #[test]
    fn memory_skill_entropy_threshold_must_be_finite() {
        let contents = r#"
[memory_skill.scan]
entropy_threshold = inf
"#;

        let error =
            TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap_err();

        assert!(matches!(
            error,
            super::ConfigError::InvalidMemorySkillEntropyThreshold { .. }
        ));
    }
    #[test]
    fn runtime_enable_defaults_to_true_and_parses_top_level_false() {
        assert!(TruthMirrorConfig::default().enabled);
        let config =
            TruthMirrorConfig::from_toml_str(Path::new("config.toml"), "enabled = false\n")
                .unwrap();
        assert!(!config.enabled);
    }

    #[test]
    fn announce_when_disabled_defaults_true_and_uses_last_layer() {
        assert!(TruthMirrorConfig::default().announce_when_disabled);

        let system_disabled = super::TruthMirrorConfig::from_test_sources(
            Some("announce_when_disabled = false\n"),
            "",
            None,
        )
        .unwrap();
        assert!(!system_disabled.announce_when_disabled);

        let project_override = super::TruthMirrorConfig::from_test_sources(
            Some("announce_when_disabled = false\n"),
            "announce_when_disabled = true\n",
            None,
        )
        .unwrap();
        assert!(project_override.announce_when_disabled);
    }

    #[test]
    fn memory_skill_entropy_threshold_must_be_positive() {
        let contents = r#"
[memory_skill.scan]
entropy_threshold = 0.0
"#;

        let error =
            TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap_err();

        assert!(matches!(
            error,
            super::ConfigError::InvalidMemorySkillEntropyThreshold { .. }
        ));
    }

    #[test]
    fn memory_skill_max_skill_bytes_must_be_positive() {
        let contents = r#"
[memory_skill]
max_skill_bytes = 0
"#;

        let error =
            TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap_err();

        assert!(matches!(
            error,
            super::ConfigError::InvalidMemorySkillMaxSkillBytes
        ));
    }

    #[test]
    fn memory_skill_secret_detector_timeout_must_be_positive() {
        let contents = r#"
[memory_skill.scan]
secret_detector_timeout_seconds = 0
"#;

        let error =
            TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap_err();

        assert!(matches!(
            error,
            super::ConfigError::InvalidMemorySkillSecretDetectorTimeout
        ));
    }

    #[test]
    fn memory_skill_similarity_threshold_must_be_finite_and_bounded() {
        for value in ["-0.1", "1.1", "nan", "inf"] {
            let contents = format!("[memory_skill.signals]\nsimilarity_threshold = {value}\n");
            let error =
                TruthMirrorConfig::from_toml_str(Path::new("config.toml"), &contents).unwrap_err();
            assert!(matches!(
                error,
                super::ConfigError::InvalidMemorySkillSimilarityThreshold { .. }
            ));
        }
    }

    #[test]
    fn empty_gate_lists_fall_back_to_defaults() {
        // An explicitly empty list must not silently disable a gate.
        let policy = super::GatesConfig {
            fake_markers: Vec::new(),
            evidence_patterns: Vec::new(),
            marker_ignore_paths: Vec::new(),
        }
        .to_policy();

        assert!(!policy.fake_markers.is_empty());
        assert!(!policy.evidence_patterns.is_empty());
        assert!(!policy.marker_ignore_paths.is_empty());
    }

    #[test]
    fn memory_skill_blocked_patterns_trim_and_dedupe() {
        let config = super::MemorySkillScanConfig {
            blocked_patterns: vec![
                " API_KEY ".to_owned(),
                " custom ".to_owned(),
                " ".to_owned(),
                "custom".to_owned(),
            ],
            ..super::MemorySkillScanConfig::default()
        };

        let patterns = config.effective_blocked_patterns();

        assert_eq!(
            patterns
                .iter()
                .filter(|pattern| pattern.eq_ignore_ascii_case("api_key"))
                .count(),
            1
        );
        assert_eq!(
            patterns
                .iter()
                .filter(|pattern| *pattern == "custom")
                .count(),
            1
        );
        assert!(patterns.iter().all(|pattern| pattern.trim() == pattern));
    }

    #[test]
    fn pair_keys_are_lowercased() {
        let contents = r#"
[pairs.CODEX]
reviewer = { harness = "claude", model = "claude-opus-4-8" }
"#;
        let config = TruthMirrorConfig::from_toml_str(Path::new("config.toml"), contents).unwrap();

        assert!(config.pair_for("codex").is_some());
        assert!(config.pair_for("CoDeX").is_some());
    }

    #[test]
    fn checked_in_config_asset_parses_to_defaults() {
        let parsed = TruthMirrorConfig::from_toml_str(
            Path::new("assets/config.toml"),
            super::DEFAULT_CONFIG_ASSET,
        )
        .expect("checked-in asset must be valid and pass validation");
        let expected = TruthMirrorConfig::default();
        assert_eq!(parsed, expected);
    }
    #[test]
    fn system_false_project_true_is_disabled() {
        let config = super::TruthMirrorConfig::from_test_sources(
            Some("enabled = false\n"),
            "enabled = true\n",
            None,
        )
        .unwrap();
        assert!(!config.enabled);
    }

    #[test]
    fn project_false_env_true_is_disabled() {
        let config =
            super::TruthMirrorConfig::from_test_sources(None, "enabled = false\n", Some(true))
                .unwrap();
        assert!(!config.enabled);
    }

    #[test]
    fn env_false_overrides_project_true() {
        let config =
            super::TruthMirrorConfig::from_test_sources(None, "enabled = true\n", Some(false))
                .unwrap();
        assert!(!config.enabled);
    }

    #[test]
    fn default_asset_is_enabled() {
        let config = super::TruthMirrorConfig::from_test_sources(None, "", None).unwrap();
        assert!(config.enabled);
    }

    #[test]
    fn ensure_project_config_creates_and_preserves_existing_bytes() {
        let temp = tempfile::tempdir().unwrap();
        let state_dir = temp.path().join(".truth");
        super::ensure_project_config(&state_dir).unwrap();
        let path = state_dir.join("config.toml");
        assert!(path.is_file());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            super::DEFAULT_CONFIG_ASSET
        );
        std::fs::write(&path, "custom").unwrap();
        super::ensure_project_config(&state_dir).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "custom");
    }

    #[test]
    fn invalid_env_value_is_a_hard_error() {
        let result = super::parse_env_enabled_for_test("maybe");
        assert!(matches!(
            result,
            Err(super::ConfigError::InvalidEnabledEnv { .. })
        ));
    }

    #[test]
    fn valid_env_values_are_accepted() {
        assert_eq!(
            super::parse_env_enabled_for_test("true").unwrap(),
            Some(true)
        );
        assert_eq!(
            super::parse_env_enabled_for_test("false").unwrap(),
            Some(false)
        );
        assert_eq!(super::parse_env_enabled_for_test("1").unwrap(), Some(true));
        assert_eq!(super::parse_env_enabled_for_test("0").unwrap(), Some(false));
        assert_eq!(super::parse_env_enabled_for_test("").unwrap(), None);
    }
}