supercode-cli 0.5.89

Volter Harness — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
//! User configuration, credentials, and model aliases for the CLI.
//!
//! Precedence (highest first): CLI flags > environment > project-local
//! `.supercode.toml` (walking up from cwd) > user `config.toml` > built-in
//! defaults. Config home is `$SUPERCODE_HOME`, else `$XDG_CONFIG_HOME/supercode`,
//! else `~/.config/supercode` (predictable, like `gh`/`codex` — not buried in
//! macOS "Application Support").
//!
//! This TOML layer is independent of the SDK's JSON `ConfigProfile`/
//! `Config::from_profile_file` mechanism, which the CLI does not use.

use std::collections::BTreeMap;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use supercode_harness::configfile::{
    merge_permissions_capability, CapabilityConfig, CoreSection, HarnessConfig,
};
use supercode_harness::{ApprovalPolicy, SandboxPolicy};

/// The built-in default model and endpoint.
pub const DEFAULT_MODEL: &str = "anthropic/claude-opus-4-8";
pub const DEFAULT_BASE_URL: &str = "https://openrouter.ai/api/v1";

/// File-backed configuration (a layer below CLI flags). Every field is optional
/// so layers merge cleanly.
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct FileConfig {
    pub model: Option<String>,
    pub base_url: Option<String>,
    pub effort: Option<String>,
    pub sandbox: Option<String>,
    pub approval: Option<String>,
    pub temperature: Option<f32>,
    pub max_tokens: Option<u32>,
    pub project_context: Option<bool>,
    pub system_prompt: Option<String>,
    /// P4 (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4", §3.1
    /// `core.append_system_prompt`, D2 row 1): an additive suffix composed
    /// onto whatever `system_prompt` resolves to (file value, then
    /// `--system-prompt`/`--system-prompt-file`, then this, then
    /// `--append-system-prompt`) — distinct from REPLACING it via
    /// `system_prompt` above. `[project-forbidden]`, same trust boundary as
    /// `system_prompt` (§3.3: prompt injection).
    pub append_system_prompt: Option<String>,
    /// P4 (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4", §1.8/§3.1
    /// `core.api_key_cmd`, D6 row): a credential-helper command (pi§6
    /// `!command` form), consulted by `build_config` only when no key was
    /// found via `--api-key`/the standard provider env vars/
    /// `credentials.toml` (`resolve_api_key`'s existing chain). UNLIKE
    /// `reduce`/`schema_tier`, this is NOT safe from a project config — see
    /// `sanitized_for_project`: same credential-redirection trust boundary
    /// as `base_url`/`api_key_env`. Never file-plaintext of the key itself
    /// — this is a COMMAND string, resolved lazily by `Agent::new`.
    pub api_key_cmd: Option<String>,
    /// Master switch for reduced mode (SPEC.md C1/D5): sidecar recording,
    /// default reduction policy, and B6 tool deferral, default-on together.
    /// Unlike `base_url`/`system_prompt`/`sandbox`/`approval`, this is safe
    /// to allow from a *project* `.supercode.toml` too (D5) — it only ever
    /// saves tokens, never spends money or weakens a security posture.
    pub reduce: Option<bool>,
    /// Global tool-schema tier (TR-8/T5): `full` | `medium` | `minimal`. Like
    /// `reduce`, safe from a project config too — it only ever shrinks what's
    /// advertised, never weakens a security posture or redirects a request.
    pub schema_tier: Option<String>,
    /// UX-26 (B7-warn): enable/disable the cache-cold warning. Like `reduce`/
    /// `schema_tier`, safe from a project config too — it only ever
    /// suppresses a stderr notice, never weakens a security posture or
    /// redirects a request.
    pub cache_warnings: Option<bool>,
    /// UX-28: config-driven lifecycle hooks (`[hooks]` — `pre_tool`/
    /// `post_tool`/`session_start`/`session_end` external commands). UNLIKE
    /// `reduce`/`schema_tier`/`cache_warnings`, this is NOT safe from a
    /// project config — see `sanitized_for_project`, which strips it exactly
    /// like `base_url`/`system_prompt`/`sandbox`/`approval`: opening an
    /// untrusted repo must never silently register a command to run.
    #[serde(default)]
    pub hooks: crate::hooks::HooksFileConfig,
    /// UX-22: master switch for turn-finish notifications (desktop +
    /// terminal bell). UNLIKE `cache_warnings`/`reduce`, this is NOT safe
    /// from a project config — see `sanitized_for_project`: turning this on
    /// silently from an opened repo, combined with `notify_email`, would be
    /// a real (if narrow) exfiltration channel.
    pub notify: Option<bool>,
    /// UX-22: minimum turn duration (seconds) before a notification fires.
    /// Benign (only affects timing, never enables/redirects anything), so
    /// unlike `notify`/`notify_email` this IS safe from a project config.
    pub notify_threshold_secs: Option<u64>,
    /// UX-22: optional email channel (stretch per the backlog item) — SMTP
    /// settings for mirroring the desktop notification to an email
    /// address. Like `notify`, stripped from a project config (see
    /// `sanitized_for_project`). The account password is never a config
    /// field — see `SUPERCODE_NOTIFY_EMAIL_PASSWORD` in `notify.rs`.
    pub notify_email: Option<NotifyEmailConfig>,
    /// Composable-harness `[core]` table (§3.1) — P4d (design §5.2 P1's
    /// "port the CLI's `FileConfig` loader onto it; `userconfig.rs` becomes
    /// a thin adapter"): reuses the SDK's [`CoreSection`] shape directly so
    /// the same `[core]` TOML table parses identically here and in
    /// `supercode_harness::configfile::HarnessConfig`. This is the NEW, spec-shaped
    /// way to set every `core.*` key from §3.1 that has no legacy flat
    /// top-level field above (`api_key_env`, `max_iterations`,
    /// `max_total_output_tokens`, `max_tool_output_bytes`, `additional_dirs`,
    /// `extra_headers`, `extra_body`, `core.retry.*`, `core.tools.*`,
    /// `core.skills.*`, `[core.prompts]`, `core.compaction.*`,
    /// `core.session.*`, `core.steering.*`, `core.output.*`,
    /// `core.model_switch.allow_switch`, `doom_loop_threshold`,
    /// `env_context`, `nested_instructions`, `instruction_imports`,
    /// `project_root_markers`, `project_doc_max_bytes`, …). Fields this
    /// struct ALREADY carries as a flat legacy top-level key (`model`,
    /// `base_url`, `effort`, `temperature`, `max_tokens`, `system_prompt`,
    /// `append_system_prompt`, `project_context`, `api_key_cmd`,
    /// `schema_tier` via `core.tools.schema_tier`) may ALSO be set here —
    /// `build_config` (main.rs) falls back to the `[core]` value only when
    /// the legacy flat field is unset, so an existing config keeps meaning
    /// exactly what it always meant (no behavior change), while a config
    /// written purely in the new `[core]` shape works too.
    ///
    /// P4e closed most of the remaining runtime gap: `parallel_tool_calls`
    /// (`Agent::run_tools_concurrently`), `context_injections`
    /// (`Agent::with_parts`' assembly site), `core.tools.bash.timeout_secs`
    /// (`ToolContext::bash_timeout_secs` → `BashTool::execute`),
    /// `core.compaction.enabled` (`Agent::maybe_compact`'s master gate),
    /// `core.session.dir` (`session_store()`, via `SESSION_DIR_OVERRIDE`),
    /// `core.session.retention_days` (`sessions prune`,
    /// `SessionStore::prune_expired`), `core.session.export_format`
    /// (`sessions export`, `human_export::render_messages`), and
    /// `core.session.git_metadata` (`Agent::git_metadata`/
    /// `save_git_metadata`) all now reach real behavior. A follow-up
    /// independent Fable-5 review of P4e found the closeout wasn't
    /// actually complete — `core.session.persist`/`.name`, the
    /// `core.session.dir` split-brain (`sessions list`/`export`/`fork`/
    /// `delete`/`prune` resolved the store BEFORE `core.session.dir`,
    /// while `run`/`chat` resolved it first), `sessions fork` dropping the
    /// sidecar family, and `core.session.auto_title` (P4b, same dead-key
    /// class) were all fixed in that follow-up pass: `persist` gates
    /// `persist_session`/`persist_full_view` (main.rs), `name` is honored
    /// by `mint_session_name`/`new_session_name`, `sessions_cmd` now
    /// resolves config before opening the store, `SessionStore::fork`
    /// copies the whole `<name>.*` sidecar family (validating `--at` never
    /// cuts off a dangling tool_call), and `auto_title` installs a real
    /// production `SessionTitler` (`CliSessionTitler`, main.rs) after the
    /// first exchange. That same pass also closed a security gap: the
    /// project layer could previously set the WHOLE `[core.session]`
    /// operational block (`dir`/`name`/`persist`/`retention_days`/
    /// `export_format`/`git_metadata`) — now stripped by
    /// `sanitize_for_project` (fail-closed, `auto_title` is the one
    /// exception left project-legal). Still genuinely P4-future:
    /// `core.tools.enabled`/`core.skills.dirs`/`core.compaction.summarize`
    /// (module/skills/span-summary subsystems out of P4e's scope),
    /// `core.output.format` (the declarative `EventSink`/JSONL bridge), and
    /// `core.hot_reload` (annotated aspirational in §3.1 — a config-watch
    /// subsystem, not built; see `CoreSection::hot_reload`'s doc comment).
    #[serde(default)]
    pub core: CoreSection,
    /// Composable-harness (`docs/composable-harness/COMPOSABLE-HARNESS-
    /// DESIGN.md` §3.1) `extends`: a built-in preset name, or (user/global
    /// layer only) a file path. FORWARD-COMPATIBLE FOR P1 (design §5.2):
    /// parsed and sanitization-checked, but NOT resolved — full preset
    /// resolution (§3.5) is P2. A project file may only name a built-in
    /// preset, never a path (`sanitized_for_project`, §3.3: "a repo-supplied
    /// preset file is config injection through the back door").
    #[serde(default)]
    pub extends: Option<String>,
    /// Composable-harness `[capabilities.*]` modules (§3.1), reusing the
    /// SDK's [`CapabilityConfig`] shape so the same TOML table parses
    /// identically here and in `supercode_harness::configfile::HarnessConfig`.
    /// FORWARD-COMPATIBLE FOR P1: parsed, sanitized per the §3.3 forbidden
    /// table, and carried through `overlay`, but NOT yet consumed — module
    /// runtime wiring is P3 (full `FileConfig`→`HarnessConfig` adapter is a
    /// P1-followup; see `sanitized_for_project`'s doc comment).
    #[serde(default)]
    pub capabilities: BTreeMap<String, CapabilityConfig>,
    /// Composable-harness `[experimental]` feature flags (§3.1 obligation
    /// 8), e.g. `module_registry = true` (P3, §5.3 risk 2's mandatory gate).
    /// Same forward-compatible treatment as `extends`/`capabilities`: parsed
    /// and carried through `overlay_project`, consumed by `build_config`'s
    /// P3 resolver hand-off (`main.rs`). LOW-1 (P3 review): UNLIKE
    /// `capabilities`, this is NOT narrowed key-by-key from a project
    /// config — see `sanitized_for_project`, which strips the table WHOLE.
    /// `module_registry` happens to be narrowing-only today, but §3.3's
    /// monotonic-tightening principle wants a project file categorically
    /// unable to toggle experimental/mode-switching flags, since a future
    /// flag added here isn't guaranteed to stay narrowing-only. User/global
    /// layer only, same trust boundary as `hooks`/`notify`.
    #[serde(default)]
    pub experimental: BTreeMap<String, serde_json::Value>,
    /// BP-9 (D6 row "Named profiles", cx§6 `-p/--profile`): switchable
    /// named config bundles. `[profiles.<name>]` carries any subset of the
    /// keys this same struct accepts; `supercode --profile <name>` overlays
    /// that bundle as its own layer between the user layer and the project
    /// layer (cx's `user → profile → project` order).
    ///
    /// User/global layer ONLY — `sanitized_for_project` drops the table
    /// whole. A repo defining selectable bundles is config injection with an
    /// extra step: the bundle's contents would bypass the per-key project
    /// sanitization the moment a user selected it by name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub profiles: BTreeMap<String, Box<FileConfig>>,
    /// BP-9 (D6 row "Credential helpers / keyring"): where the stored API
    /// key lives. User/global layer only (`sanitized_for_project` drops it):
    /// pointing someone's credential reads/writes at a different store is
    /// the same trust class as `base_url`.
    #[serde(default)]
    pub credentials: CredentialsConfig,
}

/// BP-9: `[credentials]` — which store `supercode login` writes to and
/// `resolve_api_key` reads from.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct CredentialsConfig {
    /// `"file"` (default — `credentials.toml`, 0600) or `"keyring"` (the
    /// OS keychain/secret service). An unrecognized value falls back to
    /// the file store with a warning rather than failing a login.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store: Option<String>,
}

/// BP-9: where credentials are stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialStore {
    /// `credentials.toml` under the config home, 0600. The default.
    File,
    /// The OS keyring, through the platform's own tool (macOS `security`,
    /// Linux `secret-tool`).
    Keyring,
}

/// The keyring service/account this tool stores its key under.
pub const KEYRING_SERVICE: &str = "supercode";
/// The keyring account name for the provider API key.
pub const KEYRING_ACCOUNT: &str = "api_key";

impl CredentialStore {
    /// Parse a `[credentials] store` value; unknown spellings fall back to
    /// the file store (a typo must never lock someone out of their key).
    pub fn parse(value: Option<&str>) -> CredentialStore {
        match value.map(str::trim) {
            Some("keyring") => CredentialStore::Keyring,
            _ => CredentialStore::File,
        }
    }

    /// Display label for `doctor` / `login`.
    pub fn label(self) -> &'static str {
        match self {
            CredentialStore::File => "credentials.toml",
            CredentialStore::Keyring => "OS keyring",
        }
    }
}

/// SMTP settings for [`FileConfig::notify_email`]. See `notify.rs` for the
/// (deliberately minimal, no-TLS) SMTP client this feeds.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NotifyEmailConfig {
    pub smtp_host: String,
    #[serde(default = "default_smtp_port")]
    pub smtp_port: u16,
    pub from: String,
    pub to: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
}

fn default_smtp_port() -> u16 {
    25
}

/// Capability names a project file is allowed to flip `enabled = true` on by
/// default (COMPOSABLE-HARNESS-DESIGN.md §3.3's Project-ALLOWED list,
/// S9 default disposition): "it only ever saves tokens, never spends money
/// or weakens a security posture" — same rationale as the legacy `reduce`
/// field below. Every other module's `enabled = true` is forbidden by
/// default; DISABLING a module (narrowing) is always fine and never checked
/// here.
const PROJECT_ALLOWED_CAPABILITY_ENABLE: &[&str] = &["reduction"];

/// Capability tables a project file may never set AT ALL, regardless of
/// `enabled` — each is a §3.3 "Why" row about arbitrary command execution or
/// a listener, so even inert-looking settings under the table are refused:
/// `hooks` (arbitrary command execution), `plugins` (config-borne code
/// execution, D-10), `server` (a listener), `integrations` (cloud/IDE/CI
/// surfaces, same class as `server`/`plugins`). P5-12: `trust` joined this
/// list alongside its own dependents — a project self-declaring
/// `[capabilities.trust] default = "always"` would grant itself the exact
/// gate D-10 exists to keep out of its own hands (mirrors
/// `crate::configfile::PROJECT_FORBIDDEN_CAPABILITY_TABLES`'s identical
/// addition, both resolvers in lockstep).
const PROJECT_FORBIDDEN_CAPABILITY_TABLES: &[&str] =
    &["hooks", "plugins", "server", "integrations", "trust"];

/// Sandbox policy strings that represent the LOOSEST confinement (§3.3:
/// "sandbox toward `danger_full_access`" is forbidden; anything else is a
/// tightening move and is legal from a project file). Parses `v` with
/// `crate::parse_sandbox` — the EXACT function `build_config` uses to turn a
/// `sandbox` string into the enforced [`SandboxPolicy`] — rather than a
/// separate, potentially-incomplete string match. This is the F1 fix: the
/// old hardcoded `matches!(v, "danger_full_access" | "danger-full-access")`
/// missed the `"full"` alias `parse_sandbox` itself accepts, so a project
/// file setting `sandbox = "full"` sailed through sanitization untouched and
/// resolved to full filesystem access. Reusing the real parser means no
/// alias can ever slip past unrecognized again, by construction.
fn is_loosening_sandbox(v: &str) -> bool {
    crate::parse_sandbox(v) == Some(SandboxPolicy::DangerFullAccess)
}

/// Approval policy strings that represent the LOOSEST posture (§3.3:
/// "approval toward `never`" is forbidden; `on_request`/`untrusted` tighten
/// and are legal from a project file). Same rationale as
/// [`is_loosening_sandbox`]: parses with `crate::parse_approval`, the same
/// function `build_config` uses, instead of a separate string match.
fn is_loosening_approval(v: &str) -> bool {
    crate::parse_approval(v) == Some(ApprovalPolicy::Never)
}

/// Strictness rank for a [`SandboxPolicy`] — LOWER is stricter (more
/// confining). §3.3's explicit order: `ReadOnly` (strictest) >
/// `WorkspaceWrite` > `DangerFullAccess` (loosest).
fn sandbox_rank(p: SandboxPolicy) -> u8 {
    match p {
        SandboxPolicy::ReadOnly => 0,
        SandboxPolicy::WorkspaceWrite => 1,
        SandboxPolicy::DangerFullAccess => 2,
    }
}

/// Strictness rank for an [`ApprovalPolicy`] — LOWER is stricter (prompts
/// more). §3.3's explicit order: `Untrusted` (strictest, prompts most) >
/// `OnRequest` > `ModelRequested` > `Never` (loosest). `ModelRequested`
/// (P5-1, design §3.2 S8) is not reachable through this crate's own
/// `parse_approval` yet (out of this unit's scope — the CLI's TOML config
/// surface doesn't parse it), but the rank exists so this stays exhaustive
/// against `supercode-harness`'s `ApprovalPolicy` and matches
/// `configfile::approval_rank`'s SDK-side ordering (that copy's doc comment
/// has the full rationale).
fn approval_rank(p: ApprovalPolicy) -> u8 {
    match p {
        ApprovalPolicy::Untrusted => 0,
        ApprovalPolicy::OnRequest => 1,
        ApprovalPolicy::ModelRequested => 2,
        ApprovalPolicy::Never => 3,
    }
}

/// F2/F3 fix: the real §3.3 monotonic clamp for `sandbox`, applied at
/// overlay time on PARSED policies (not raw strings). The merged value is
/// the STRICTER of the user layer (`user`) and the project layer
/// (`project`) — a project file may tighten-or-match the user's posture,
/// never widen it. When `user` is unset, its "effective" value for
/// comparison purposes is the built-in default (`WorkspaceWrite`, exactly
/// what `build_config` falls back to) — this is what makes case 1 (F1) work
/// even with no user config at all: a project's `"full"` is compared
/// against `WorkspaceWrite` and loses. Uses `crate::parse_sandbox` — same
/// alias set as the CLI consumer, so a project value that doesn't parse (an
/// unrecognized spelling) is never trusted to be safe and is dropped too
/// (this is also what fixes the `read_only`-doesn't-parse-hyphen-only case,
/// since `parse_sandbox` itself now normalizes underscores).
fn clamp_sandbox(
    user: Option<&str>,
    project: Option<&str>,
    clamped: &mut Vec<String>,
) -> Option<String> {
    let Some(proj_raw) = project else {
        // The project didn't set this key at all — nothing to clamp; the
        // user's own (never-sanitized) value passes through untouched.
        return user.map(str::to_string);
    };
    let user_effective = user
        .and_then(crate::parse_sandbox)
        .unwrap_or(SandboxPolicy::WorkspaceWrite);
    match crate::parse_sandbox(proj_raw) {
        Some(p) if sandbox_rank(p) <= sandbox_rank(user_effective) => Some(proj_raw.to_string()),
        _ => {
            clamped.push("sandbox".to_string());
            user.map(str::to_string)
        }
    }
}

/// F2/F3 fix: the same monotonic clamp as [`clamp_sandbox`], for `approval`.
/// The assumed built-in floor when `user` is unset is `OnRequest` — never
/// `Never` — because `Never` (the loosest approval) is an absolute
/// §3.3-forbidden value from a project file regardless of context (matching
/// `is_loosening_approval`'s unconditional strip); using `OnRequest` as the
/// floor means a project can't sneak `never` through just because the user
/// happened to leave `approval` unset.
fn clamp_approval(
    user: Option<&str>,
    project: Option<&str>,
    clamped: &mut Vec<String>,
) -> Option<String> {
    let Some(proj_raw) = project else {
        return user.map(str::to_string);
    };
    let user_effective = user
        .and_then(crate::parse_approval)
        .unwrap_or(ApprovalPolicy::OnRequest);
    match crate::parse_approval(proj_raw) {
        Some(p) if approval_rank(p) <= approval_rank(user_effective) => Some(proj_raw.to_string()),
        _ => {
            clamped.push("approval".to_string());
            user.map(str::to_string)
        }
    }
}

/// `extends` values a project file may not use: a file path (§3.3 — "a
/// repo-supplied preset file is config injection through the back door").
/// Built-in preset NAMES (`"pi-core"`, `"cc-parity"`, ...) remain legal.
fn is_preset_path(v: &str) -> bool {
    v.contains('/') || v.contains('\\') || v.to_ascii_lowercase().ends_with(".toml")
}

/// Strip/narrow a project-local `capabilities` table to the §3.3 monotonic-
/// tightening rule, recording what it touched into `dropped`.
fn sanitize_capabilities(
    capabilities: BTreeMap<String, CapabilityConfig>,
    dropped: &mut Vec<String>,
) -> BTreeMap<String, CapabilityConfig> {
    let mut out = BTreeMap::new();
    for (name, mut cap) in capabilities {
        if PROJECT_FORBIDDEN_CAPABILITY_TABLES.contains(&name.as_str()) {
            dropped.push(format!("capabilities.{name}"));
            continue;
        }
        if name == "mcp" {
            // `servers`/`serve` are named explicitly in §3.3 as the
            // injection surface (inline server defs, standalone listener),
            // so they're always stripped here regardless of what happens
            // to `enabled` below via the general default-disposition check
            // (mcp isn't on the S9 Project-ALLOWED list either).
            if cap.settings.remove("servers").is_some() {
                dropped.push("capabilities.mcp.servers".to_string());
            }
            if cap
                .settings
                .get("serve")
                .and_then(serde_json::Value::as_bool)
                == Some(true)
            {
                cap.settings.remove("serve");
                dropped.push("capabilities.mcp.serve".to_string());
            }
        }
        if name == "notify" && cap.settings.remove("email").is_some() {
            dropped.push("capabilities.notify.email".to_string());
        }
        if name == "lsp" {
            // P5-11: `capabilities.lsp.servers.*` is config-borne code
            // execution (`command`/`args`) — same D-10 injection class as
            // `mcp.servers` above, stripped the same way regardless of
            // `enabled` (mirrors `crate::configfile::sanitize_for_project`'s
            // identical strip, kept in lockstep so the SDK's `HarnessConfig`
            // resolver and this CLI's `FileConfig` resolver never diverge on
            // what a hostile project config can smuggle in).
            if cap.settings.remove("servers").is_some() {
                dropped.push("capabilities.lsp.servers".to_string());
            }
        }
        if name == "formatters" {
            // P5-11: every key besides the two recognized scalars
            // (`diff_back`/`timeout_secs`) is a formatter DEFINITION
            // (`command`/`args`) — same D-10 class as `lsp.servers` just
            // above; formatter defs are SIBLINGS of `enabled` (not nested
            // under one sub-key like `lsp.servers`), so each one is checked
            // individually. `diff_back = false` is the C10-unsafe direction
            // (silences the model-visible annotation) and is stripped too —
            // same "never let a project assert the unsafe value" posture as
            // `sandbox.enabled = false` elsewhere in this function. Mirrors
            // `crate::configfile::sanitize_for_project`'s identical strip.
            let formatter_keys: Vec<String> = cap
                .settings
                .keys()
                .filter(|k| !matches!(k.as_str(), "diff_back" | "timeout_secs"))
                .cloned()
                .collect();
            for key in formatter_keys {
                cap.settings.remove(&key);
                dropped.push(format!("capabilities.formatters.{key}"));
            }
            if cap
                .settings
                .get("diff_back")
                .and_then(serde_json::Value::as_bool)
                == Some(false)
            {
                cap.settings.remove("diff_back");
                dropped.push("capabilities.formatters.diff_back".to_string());
            }
        }
        if name == "permissions" {
            // F4 fix: §3.3 names `capabilities.permissions.*` in a
            // LOOSENING direction as forbidden exactly like the top-level
            // `sandbox`/`approval` fields (tightening remains legal) — but
            // unlike those, this table's settings were never handled here
            // at all, so a project's `approval = "never"`, a loosening
            // `sandbox`, `auto_approved_tools` additions, and `rules.allow`
            // additions all rode through the generic settings catch-all and
            // out the other side of `overlay` untouched. Inert in P1 (no
            // runtime consumes `capabilities.permissions` yet), but this is
            // the exact boundary P3 builds its enforcement on, so it must
            // be airtight now.
            match cap.settings.get("sandbox") {
                Some(serde_json::Value::String(sb)) if is_loosening_sandbox(sb) => {
                    cap.settings.remove("sandbox");
                    dropped.push("capabilities.permissions.sandbox".to_string());
                }
                Some(serde_json::Value::Object(_)) => {
                    // Security-review finding 1 (of the 630bdb0 F1-F4 review):
                    // the design's own §3.1 schema states `sandbox = "<tier>"`
                    // (bare form, handled above) ≡
                    // `[capabilities.permissions.sandbox] tier = "<tier>"`
                    // (table form) — same key, two spellings. The bare-string
                    // branch above only ever saw `Value::String`, so a
                    // project file spelling the loosening as a table sailed
                    // through untouched: `[capabilities.permissions.sandbox]
                    // tier = "danger_full_access"` never hit
                    // `is_loosening_sandbox` at all.
                    if let Some(tbl) = cap
                        .settings
                        .get_mut("sandbox")
                        .and_then(|v| v.as_object_mut())
                    {
                        if let Some(tier) = tbl.get("tier").and_then(|v| v.as_str()) {
                            if is_loosening_sandbox(tier) {
                                tbl.remove("tier");
                                dropped.push("capabilities.permissions.sandbox.tier".to_string());
                            }
                        }
                        // P5-10: `enabled` (OS-level enforcement engaged)
                        // only ever legitimately TIGHTENS by turning
                        // enforcement ON — an explicit project `enabled =
                        // false` is the one loosening direction (it can
                        // defeat a TRUSTED layer's `enabled = true`) and is
                        // unconditionally dropped, matching
                        // `configfile::sanitize_for_project`'s identical
                        // fix (same rationale there — no base comparison
                        // needed, "never let a project assert false" holds
                        // regardless of the trusted layer's own value).
                        // `enabled = true` passes through untouched.
                        if matches!(tbl.get("enabled"), Some(serde_json::Value::Bool(false))) {
                            tbl.remove("enabled");
                            dropped.push("capabilities.permissions.sandbox.enabled".to_string());
                        }
                        // P5-10: `escalation`/`env_policy` graduate from an
                        // unconditional strip to the SAME two-stage
                        // treatment `tier`/`approval` get — catch the
                        // single absolute-loosest value here, leave
                        // anything else for `overlay_project`'s call into
                        // `configfile::clamp_project_permissions` (the
                        // proper rank-vs-trusted-layer comparison — see
                        // that function's doc comment for why this now has
                        // a safe order to clamp against, unlike
                        // `network.allow_domains`/`.deny_domains` below).
                        if let Some(esc) = tbl.get("escalation").and_then(|v| v.as_str()) {
                            if supercode_harness::sandbox::SandboxEscalation::parse(esc)
                                == Some(supercode_harness::sandbox::SandboxEscalation::Allow)
                            {
                                tbl.remove("escalation");
                                dropped.push(
                                    "capabilities.permissions.sandbox.escalation".to_string(),
                                );
                            }
                        }
                        if let Some(ep) = tbl.get("env_policy").and_then(|v| v.as_str()) {
                            if supercode_harness::sandbox::SandboxEnvPolicy::parse(ep)
                                == Some(supercode_harness::sandbox::SandboxEnvPolicy::Inherit)
                            {
                                tbl.remove("env_policy");
                                dropped.push(
                                    "capabilities.permissions.sandbox.env_policy".to_string(),
                                );
                            }
                        }
                        // `network.allow_domains`/`.deny_domains` have no
                        // established strictness order to safely clamp
                        // against yet (same "no safe-to-trust ordering"
                        // rationale as `auto_approved_tools`/`rules.allow`
                        // below) — stripped outright. `network.enabled`
                        // gets the never-assert-false treatment, same as
                        // the table's own `enabled` above.
                        if let Some(net) = tbl.get_mut("network").and_then(|v| v.as_object_mut()) {
                            for k in ["allow_domains", "deny_domains"] {
                                if net.remove(k).is_some() {
                                    dropped.push(format!(
                                        "capabilities.permissions.sandbox.network.{k}"
                                    ));
                                }
                            }
                            if matches!(net.get("enabled"), Some(serde_json::Value::Bool(false))) {
                                net.remove("enabled");
                                dropped.push(
                                    "capabilities.permissions.sandbox.network.enabled".to_string(),
                                );
                            }
                        }
                    }
                }
                _ => {}
            }
            // `approval` is bare-string-only in the current §3.1 schema dump
            // (no `[capabilities.permissions.approval]`/`.approvals` TABLE is
            // defined there — `permissions.approvals` in the design's module
            // table (§2, row 10) names the interactive-UI/caching subsystem,
            // not a config table shape) — nothing to generalize here
            // symmetrically with `sandbox` above; if a table form is ever
            // added to the schema, mirror the `sandbox` handling above.
            if let Some(ap) = cap.settings.get("approval").and_then(|v| v.as_str()) {
                if is_loosening_approval(ap) {
                    cap.settings.remove("approval");
                    dropped.push("capabilities.permissions.approval".to_string());
                }
            }
            // `auto_approved_tools` has no user-layer counterpart to clamp
            // against at this (inert, pre-consumption) stage, so — like
            // `hooks`/`notify_email` above — it is always stripped from a
            // project file outright rather than trusted to only ever
            // shrink the allowlist.
            if cap.settings.remove("auto_approved_tools").is_some() {
                dropped.push("capabilities.permissions.auto_approved_tools".to_string());
            }
            // `rules.deny` additions only tighten (more explicit denials),
            // so the SANITIZER leaves the raw value alone here; the HIGH fix
            // (Fable-5 P4a review, Attack B) is enforced downstream at MERGE
            // time instead (`overlay_project` → `merge_permissions_capability`
            // unions this survivor into the trusted layer's own `deny`
            // rather than letting it replace it — a project value that
            // "only tightens" on its own can still WIDEN if it's allowed to
            // replace a stricter trusted list). `rules.allow` additions
            // widen (grant exceptions) and are always stripped here, same
            // rationale as `auto_approved_tools` above.
            if let Some(rules) = cap
                .settings
                .get_mut("rules")
                .and_then(|v| v.as_object_mut())
            {
                if rules.remove("allow").is_some() {
                    dropped.push("capabilities.permissions.rules.allow".to_string());
                }
            }
        }
        if matches!(
            name.as_str(),
            "tools_web" | "tools_background" | "telemetry" | "session_share"
        ) && cap.enabled == Some(true)
        {
            cap.enabled = None;
            dropped.push(format!("capabilities.{name}.enabled"));
        }
        // Default disposition (S9): opting IN to any module not on the
        // allowlist is forbidden by default, even ones with no dedicated
        // rule above — disabling (narrowing) is always left alone.
        if cap.enabled == Some(true) && !PROJECT_ALLOWED_CAPABILITY_ENABLE.contains(&name.as_str())
        {
            cap.enabled = None;
            dropped.push(format!("capabilities.{name}.enabled"));
        }
        out.insert(name, cap);
    }
    out
}

impl FileConfig {
    /// [`Self::sanitized_for_project`] with the layer NAMED, so a diagnostic
    /// says which of the two untrusted files it is about.
    fn sanitized_for_layer(self, layer: &str) -> FileConfig {
        let mut dropped = Vec::new();
        if self.base_url.is_some() {
            dropped.push("base_url".to_string());
        }
        if self.system_prompt.is_some() {
            dropped.push("system_prompt".to_string());
        }
        if self.append_system_prompt.is_some() {
            // P4: same prompt-injection trust boundary as `system_prompt`
            // above — a project file must not be able to append arbitrary
            // instructions to the system prompt any more than it can
            // replace it outright.
            dropped.push("append_system_prompt".to_string());
        }
        if self.api_key_cmd.is_some() {
            // P4: same credential-redirection trust boundary as `base_url`
            // above — a project file must not be able to make `supercode`
            // run an arbitrary command and send its output as the API key.
            dropped.push("api_key_cmd".to_string());
        }
        // §3.3: sandbox/approval generalize from a blanket strip to
        // monotonic tightening — only the LOOSEST value is forbidden.
        let sandbox = match self.sandbox {
            Some(sb) if is_loosening_sandbox(&sb) => {
                dropped.push("sandbox".to_string());
                None
            }
            other => other,
        };
        let approval = match self.approval {
            Some(ap) if is_loosening_approval(&ap) => {
                dropped.push("approval".to_string());
                None
            }
            other => other,
        };
        if self.hooks != crate::hooks::HooksFileConfig::default() {
            // UX-28: a project-local `.supercode.toml` must never be able to
            // register an external-command hook — that would mean merely
            // `cd`-ing into an untrusted repo and running `supercode` could
            // execute an attacker-chosen command with zero user action
            // beyond starting the CLI. Hooks are opt-in from YOUR OWN config
            // only (`~/.config/supercode/config.toml` or `SUPERCODE_HOOK_*`
            // env), same trust boundary as `base_url`/`system_prompt`/
            // `sandbox`/`approval` above.
            dropped.push("hooks".to_string());
        }
        if self.notify.is_some() {
            dropped.push("notify".to_string());
        }
        if self.notify_email.is_some() {
            dropped.push("notify_email".to_string());
        }
        let extends = match self.extends {
            Some(e) if is_preset_path(&e) => {
                dropped.push("extends (path)".to_string());
                None
            }
            other => other,
        };
        let capabilities = sanitize_capabilities(self.capabilities, &mut dropped);
        // P4d (design §5.2 P1's "port the CLI's `FileConfig` loader onto
        // it"): delegate `[core]` sanitization to the SDK resolver's own
        // `sanitize_for_project` — the same tested/reviewed boundary
        // `resolve()` enforces — by round-tripping `self.core` through a
        // scratch `HarnessConfig` with everything else left at its inert
        // default (so only `core`-scoped drops come back out; `capabilities`/
        // `extends`/`experimental` keep the handling already above/below,
        // unchanged, to avoid two logic paths disagreeing on the same key).
        let core_probe = HarnessConfig {
            schema: None,
            schema_version: 1,
            extends: None,
            core: self.core,
            capabilities: BTreeMap::new(),
            experimental: serde_json::Map::new(),
        };
        let (core_sanitized, core_dropped) =
            supercode_harness::configfile::sanitize_for_project(&core_probe);
        dropped.extend(core_dropped);
        let core = core_sanitized.core;
        // LOW-1 (independent Fable-5 review of P3): `[experimental]` was
        // NOT in this §3.3 forbidden-key set, so a project-layer config
        // could flip an experimental/mode-switching flag (and, combined
        // with `extends`, select a built-in preset that turns on
        // `module_registry`). `module_registry` itself only ever narrows
        // (§5.3 risk 2's mandatory gate), but the monotonic-tightening
        // principle wants project configs categorically unable to toggle
        // ANYTHING under `[experimental]` — a future flag added here may
        // not be narrowing-only. Strip the whole table, same fail-closed
        // treatment as `hooks`/`notify`/`base_url`: experimental gates are
        // user/global-layer only.
        if !self.experimental.is_empty() {
            dropped.push("experimental".to_string());
        }
        // BP-9: a repo must not define selectable config bundles (their
        // contents would bypass this per-key sanitization the moment a user
        // named one), nor redirect where credentials are read/written.
        if !self.profiles.is_empty() {
            dropped.push("profiles".to_string());
        }
        if self.credentials != CredentialsConfig::default() {
            dropped.push("credentials".to_string());
        }
        if !dropped.is_empty() {
            // `load` runs more than once per invocation, so this dedups —
            // but BP-9 keyed it on the LAYER and the dropped set rather
            // than a process-wide `Once`. With two untrusted layers
            // (`.supercode.toml` and `.supercode.local.toml`) a single
            // `Once` reported whichever file was sanitized first and
            // silently swallowed the second one's drops.
            warn_config_once(
                format!("project-drop:{layer}:{}", dropped.join(",")),
                format!(
                    "\x1b[33mwarning: ignoring untrusted field(s) [{}] from {layer} \
                     — set these in your user config or via flags\x1b[0m",
                    dropped.join(", ")
                ),
            );
        }
        FileConfig {
            base_url: None,
            system_prompt: None,
            append_system_prompt: None,
            api_key_cmd: None,
            sandbox,
            approval,
            hooks: crate::hooks::HooksFileConfig::default(),
            notify: None,
            notify_email: None,
            extends,
            capabilities,
            core,
            experimental: BTreeMap::new(),
            profiles: BTreeMap::new(),
            credentials: CredentialsConfig::default(),
            ..self
        }
    }

    /// BP-9 (D6 row "Named profiles"): overlay a TRUSTED bundle (a
    /// `[profiles.<name>]` table, or a `--settings`/`-c` layer) onto this
    /// config — `over` wins wherever it sets a value.
    ///
    /// Deliberately NOT [`Self::overlay_project`]: that one clamps
    /// `sandbox`/`approval` to the stricter of the two because its `over`
    /// side is an untrusted repo. These layers came from the user's own
    /// config file or their own command line, so a profile that selects a
    /// LOOSER posture is doing what its author asked. Nested `profiles`
    /// tables on `over` are ignored (a profile does not select a profile).
    fn overlay_trusted(self, over: FileConfig) -> FileConfig {
        let base = self;
        let mut capabilities = base.capabilities;
        for (name, cap) in over.capabilities {
            capabilities.insert(name, cap);
        }
        let core_merged = supercode_harness::configfile::HarnessConfig {
            core: base.core,
            ..Default::default()
        }
        .overlay(&supercode_harness::configfile::HarnessConfig {
            core: over.core,
            ..Default::default()
        })
        .core;
        FileConfig {
            model: over.model.or(base.model),
            base_url: over.base_url.or(base.base_url),
            effort: over.effort.or(base.effort),
            sandbox: over.sandbox.or(base.sandbox),
            approval: over.approval.or(base.approval),
            temperature: over.temperature.or(base.temperature),
            max_tokens: over.max_tokens.or(base.max_tokens),
            project_context: over.project_context.or(base.project_context),
            system_prompt: over.system_prompt.or(base.system_prompt),
            append_system_prompt: over.append_system_prompt.or(base.append_system_prompt),
            api_key_cmd: over.api_key_cmd.or(base.api_key_cmd),
            reduce: over.reduce.or(base.reduce),
            schema_tier: over.schema_tier.or(base.schema_tier),
            cache_warnings: over.cache_warnings.or(base.cache_warnings),
            hooks: crate::hooks::HooksFileConfig {
                pre_tool: over.hooks.pre_tool.or(base.hooks.pre_tool),
                post_tool: over.hooks.post_tool.or(base.hooks.post_tool),
                session_start: over.hooks.session_start.or(base.hooks.session_start),
                session_end: over.hooks.session_end.or(base.hooks.session_end),
                stop: over.hooks.stop.or(base.hooks.stop),
                user_prompt_submit: over
                    .hooks
                    .user_prompt_submit
                    .or(base.hooks.user_prompt_submit),
                notification: over.hooks.notification.or(base.hooks.notification),
                subagent_start: over.hooks.subagent_start.or(base.hooks.subagent_start),
                subagent_stop: over.hooks.subagent_stop.or(base.hooks.subagent_stop),
                pre_compact: over.hooks.pre_compact.or(base.hooks.pre_compact),
                post_compact: over.hooks.post_compact.or(base.hooks.post_compact),
                timeout_ms: over.hooks.timeout_ms.or(base.hooks.timeout_ms),
            },
            notify: over.notify.or(base.notify),
            notify_threshold_secs: over.notify_threshold_secs.or(base.notify_threshold_secs),
            notify_email: over.notify_email.or(base.notify_email),
            extends: over.extends.or(base.extends),
            capabilities,
            core: core_merged,
            experimental: {
                let mut e = base.experimental;
                e.extend(over.experimental);
                e
            },
            profiles: base.profiles,
            credentials: CredentialsConfig {
                store: over.credentials.store.or(base.credentials.store),
            },
        }
    }

    /// Overlay a project layer onto this (trusted) layer — `project` wins
    /// wherever it sets a value.
    ///
    /// **INVARIANT (security-review finding 2 of the 630bdb0 F1-F4 review —
    /// hardened here): `self` MUST be the TRUSTED layer (user/base config)
    /// and `project` MUST be the UNTRUSTED, already-`sanitized_for_project`
    /// layer.** This is a caller invariant the type system can't enforce by
    /// itself (both sides are the same `FileConfig` type), so the method and
    /// parameter names spell the roles out explicitly rather than the
    /// generic `overlay(self, other)` this used to be: `sandbox`/`approval`
    /// are NOT a plain "other wins" merge like every other field — per the
    /// F2/F3 fix, `clamp_sandbox`/`clamp_approval` always resolve to the
    /// STRICTER of the two, computed on parsed policies, never the
    /// project's raw string outright. Reversing the two arguments at some
    /// future call site would silently invert that into a WIDENING path (a
    /// hostile project's raw sandbox/approval value would be treated as the
    /// trusted floor a real user config gets clamped against) — the old
    /// `self`/`other` naming gave no hint that direction mattered at all.
    /// No behavior change: this is the same clamp/merge logic as before,
    /// renamed for clarity at the one real call site (`load`, below).
    fn overlay_project(self, project: FileConfig) -> FileConfig {
        let trusted = self;
        let mut clamped = Vec::new();
        let sandbox = clamp_sandbox(
            trusted.sandbox.as_deref(),
            project.sandbox.as_deref(),
            &mut clamped,
        );
        let approval = clamp_approval(
            trusted.approval.as_deref(),
            project.approval.as_deref(),
            &mut clamped,
        );
        if !clamped.is_empty() {
            use std::sync::Once;
            static WARNED: Once = Once::new();
            WARNED.call_once(|| {
                eprintln!(
                    "\x1b[33mwarning: a project .supercode.toml attempted to WIDEN [{}] beyond \
                     your own config — clamped to the stricter value (§3.3 monotonic tightening)\x1b[0m",
                    clamped.join(", ")
                );
            });
        }

        let mut capabilities = trusted.capabilities;
        for (name, cap) in project.capabilities {
            if name == "permissions" {
                // HIGH fix (independent Fable-5 review of P4a — Attack A/B,
                // §3.3 monotonic tightening): P4a made `permissions` the
                // first `[capabilities.*]` table that's actually
                // load-bearing (`rules.deny` backs the hard approval floor
                // `Config::needs_approval` enforces even under
                // `ApprovalPolicy::Never`), so it can no longer use the
                // coarse per-key "table replace" every other (still inert)
                // capability below still uses. A per-capability `insert`
                // here let a hostile project's `[capabilities.permissions]`
                // table — even one `sanitized_for_project` strips down to
                // EMPTY — wholesale REPLACE the trusted layer's populated
                // table (Attack A), and even a surviving, individually
                // harmless project `rules.deny` would otherwise REPLACE
                // rather than add to the trusted layer's list (Attack B).
                // `merge_permissions_capability` (shared with the core
                // resolver's `resolve_top`, so both routes agree) deep-merges
                // instead of replacing and unions `rules.deny` instead of
                // letting it shrink.
                let trusted_permissions = capabilities.get("permissions").cloned();
                if let Some(merged) =
                    merge_permissions_capability(trusted_permissions.as_ref(), Some(&cap))
                {
                    // P5-10 (§2 module 12): `escalation`/`env_policy` now
                    // carry a safe strictness ORDER (see
                    // `configfile::clamp_project_permissions`'s doc
                    // comment), so — mirroring the top-level `sandbox`/
                    // `approval` `clamp_sandbox`/`clamp_approval` calls
                    // above — the project's table-form values are clamped
                    // to no looser than the TRUSTED layer's own, not just
                    // merged wholesale. Uses the same throwaway-
                    // `HarnessConfig`-wrapping-just-`capabilities` trick
                    // `sanitized_for_project`'s own doc comment already
                    // documents for `[core]`, so this reuses the SDK
                    // resolver's tested clamp rather than a second,
                    // potentially-drifting copy.
                    let base_hc = supercode_harness::configfile::HarnessConfig {
                        capabilities: trusted_permissions
                            .clone()
                            .map(|c| BTreeMap::from([("permissions".to_string(), c)]))
                            .unwrap_or_default(),
                        ..Default::default()
                    };
                    let project_hc = supercode_harness::configfile::HarnessConfig {
                        capabilities: BTreeMap::from([("permissions".to_string(), cap.clone())]),
                        ..Default::default()
                    };
                    let mut merged_hc = supercode_harness::configfile::HarnessConfig {
                        capabilities: BTreeMap::from([("permissions".to_string(), merged)]),
                        ..Default::default()
                    };
                    let more_clamped = supercode_harness::configfile::clamp_project_permissions(
                        &base_hc,
                        &project_hc,
                        &mut merged_hc,
                    );
                    if !more_clamped.is_empty() {
                        use std::sync::Once;
                        static WARNED2: Once = Once::new();
                        WARNED2.call_once(|| {
                            eprintln!(
                                "\x1b[33mwarning: a project .supercode.toml attempted to WIDEN \
                                 [{}] beyond your own config — clamped to the stricter value \
                                 (§3.3 monotonic tightening)\x1b[0m",
                                more_clamped.join(", ")
                            );
                        });
                    }
                    if let Some(final_permissions) = merged_hc.capabilities.remove("permissions") {
                        capabilities.insert(name, final_permissions);
                    }
                }
                continue;
            }
            if name == "reduction" {
                let trusted_reduction = capabilities.get("reduction").cloned();
                if let Some(merged) = supercode_harness::configfile::merge_reduction_capability(
                    trusted_reduction.as_ref(),
                    Some(&cap),
                ) {
                    capabilities.insert(name, merged);
                }
                continue;
            }
            // Per-capability table replace (§3.3 "tables merge key-wise")
            // for every other capability; deeper field-level merging within
            // one capability's settings is a P1-followup once the settings
            // are actually consumed (P3+) for those tables — nothing reads
            // them yet for anything besides `permissions` (now load-bearing,
            // handled above), so a coarser per-key overlay is observably
            // identical today.
            capabilities.insert(name, cap);
        }
        // P4d (design §5.2 P1's "port the CLI's `FileConfig` loader onto
        // it"): merge `[core]` with the exact §3.3 overlay semantics
        // (scalars replace, tables merge key-wise, arrays replace) by
        // delegating to `HarnessConfig::overlay` — the same merge the SDK
        // resolver's preset-chain/layer folding uses — rather than
        // hand-rolling a third copy of `merge_opt!`'s per-field logic here.
        // `project.core` has already been through the `core_probe`
        // sanitization above (via `sanitized_for_project`), so this is a
        // trusted-base <- sanitized-project merge, matching every other
        // field in this function.
        let core = HarnessConfig {
            core: trusted.core,
            ..Default::default()
        }
        .overlay(&HarnessConfig {
            core: project.core,
            ..Default::default()
        })
        .core;
        FileConfig {
            model: project.model.or(trusted.model),
            base_url: project.base_url.or(trusted.base_url),
            effort: project.effort.or(trusted.effort),
            sandbox,
            approval,
            temperature: project.temperature.or(trusted.temperature),
            max_tokens: project.max_tokens.or(trusted.max_tokens),
            project_context: project.project_context.or(trusted.project_context),
            system_prompt: project.system_prompt.or(trusted.system_prompt),
            // P4: `project.append_system_prompt` is always `None` here too
            // (stripped in `sanitized_for_project`), same fallback pattern.
            append_system_prompt: project
                .append_system_prompt
                .or(trusted.append_system_prompt),
            // P4: `project.api_key_cmd` is always `None` by the time it
            // reaches here (stripped in `sanitized_for_project`) — this
            // correctly falls back to the trusted (user/global) layer's own
            // value, same pattern as `hooks` below.
            api_key_cmd: project.api_key_cmd.or(trusted.api_key_cmd),
            reduce: project.reduce.or(trusted.reduce),
            schema_tier: project.schema_tier.or(trusted.schema_tier),
            cache_warnings: project.cache_warnings.or(trusted.cache_warnings),
            // UX-28: per-field overlay, not "other wins outright" — a
            // project config's `hooks` is always `default()` by the time it
            // reaches here (stripped above), so this correctly falls back
            // to the USER config's hooks field-by-field rather than a
            // project's (always-empty) table wiping them out.
            hooks: crate::hooks::HooksFileConfig {
                pre_tool: project.hooks.pre_tool.or(trusted.hooks.pre_tool),
                post_tool: project.hooks.post_tool.or(trusted.hooks.post_tool),
                session_start: project.hooks.session_start.or(trusted.hooks.session_start),
                session_end: project.hooks.session_end.or(trusted.hooks.session_end),
                stop: project.hooks.stop.or(trusted.hooks.stop),
                // P5-7: the expanded CC/CX-common events fall back to the
                // USER layer field-by-field exactly like the five above —
                // `project.hooks` is ALWAYS `default()` (all-`None`) by the
                // time it reaches here (`sanitized_for_project` strips the
                // whole `[hooks]` table the moment any field, old or new, is
                // set), so a project can never register ANY of these either.
                user_prompt_submit: project
                    .hooks
                    .user_prompt_submit
                    .or(trusted.hooks.user_prompt_submit),
                notification: project.hooks.notification.or(trusted.hooks.notification),
                subagent_start: project
                    .hooks
                    .subagent_start
                    .or(trusted.hooks.subagent_start),
                subagent_stop: project.hooks.subagent_stop.or(trusted.hooks.subagent_stop),
                pre_compact: project.hooks.pre_compact.or(trusted.hooks.pre_compact),
                post_compact: project.hooks.post_compact.or(trusted.hooks.post_compact),
                timeout_ms: project.hooks.timeout_ms.or(trusted.hooks.timeout_ms),
            },
            notify: project.notify.or(trusted.notify),
            notify_threshold_secs: project
                .notify_threshold_secs
                .or(trusted.notify_threshold_secs),
            notify_email: project.notify_email.or(trusted.notify_email),
            extends: project.extends.or(trusted.extends),
            capabilities,
            core,
            experimental: {
                // Key-wise merge (§3.3 "tables merge key-wise"), same
                // pattern as `capabilities` above — a project layer setting
                // one experimental flag must not blow away others the user
                // config already set.
                let mut e = trusted.experimental;
                e.extend(project.experimental);
                e
            },
            // BP-9: both are project-forbidden (stripped above), so these
            // always fall back to the trusted layer's own — same pattern as
            // `hooks`.
            profiles: trusted.profiles,
            credentials: CredentialsConfig {
                store: project.credentials.store.or(trusted.credentials.store),
            },
        }
    }
}

/// Config home directory (created lazily by writers).
pub fn config_home() -> PathBuf {
    if let Ok(h) = std::env::var("SUPERCODE_HOME") {
        if !h.is_empty() {
            return PathBuf::from(h);
        }
    }
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
        if !xdg.is_empty() {
            return PathBuf::from(xdg).join("supercode");
        }
    }
    let home = supercode_interchange::user_home()
        .map(|home| home.to_string_lossy().into_owned())
        .ok_or(std::env::VarError::NotPresent)
        .unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join(".config").join("supercode")
}

pub fn config_file() -> PathBuf {
    config_home().join("config.toml")
}

pub fn credentials_file() -> PathBuf {
    config_home().join("credentials.toml")
}

#[derive(Default, Deserialize, Serialize)]
struct Credentials {
    api_key: Option<String>,
}

/// Load + merge user config and the nearest project-local `.supercode.toml`.
pub fn load(cwd: &std::path::Path) -> FileConfig {
    load_with_trusted_extends(cwd).0
}

/// Load the merged config and retain the trusted user layer's `extends`
/// separately. Project configs may name built-in presets, but resolving that
/// name as the trusted top layer would let a repository reintroduce modules
/// (`server`, `plugins`, `trust`, hooks) that project sanitization removed.
/// Runtime preset resolution therefore uses this provenance-preserving value
/// while still overlaying the project's individually-sanitized capabilities.
pub fn load_with_trusted_extends(cwd: &std::path::Path) -> (FileConfig, Option<String>) {
    load_layered(cwd, &LoadOptions::default()).unwrap_or_else(|e| {
        // `LoadOptions::default()` names no profile and no per-run layer, so
        // the only failure modes this call can hit don't exist. Keep the
        // legacy signature total rather than making every caller handle an
        // impossible error.
        warn_config_once(format!("layered-load:{e}"), format!("warning: {e}"));
        (FileConfig::default(), None)
    })
}

/// BP-9: the launch-time layers `load_layered` applies on top of the file
/// layers, in precedence order (see `configfile::ConfigLayers` for the
/// canonical precedence line).
#[derive(Debug, Clone, Default)]
pub struct LoadOptions {
    /// `--profile <name>`: a `[profiles.<name>]` bundle from the USER
    /// config, applied between the user layer and the project layer.
    pub profile: Option<String>,
    /// `--settings <json|path>` documents, applied above the file layers.
    pub settings: Vec<String>,
    /// `-c/--config key=value` assignments, applied last.
    pub overrides: Vec<String>,
}

/// BP-9: the full CLI layer stack —
/// `user → profile → project → project-local → --settings → -c`.
///
/// The two file layers below the user config are UNTRUSTED and each goes
/// through `sanitized_for_project` + `overlay_project`'s clamp individually;
/// the profile and the two per-run layers are TRUSTED (the user's own config
/// file, the user's own command line) and use `overlay_trusted`.
pub fn load_layered(
    cwd: &std::path::Path,
    opts: &LoadOptions,
) -> Result<(FileConfig, Option<String>), String> {
    let user = read_file_config(&config_file());
    let trusted_extends = user.extends.clone();

    // The marker-bounded discovery walk uses the USER layer's markers: they
    // are the only ones known before a project file has been found, and
    // `core.project_root_markers` is exactly the knob that answers "where
    // does this project stop?".
    let markers = user
        .core
        .project_root_markers
        .clone()
        .unwrap_or_else(|| vec![".git".to_string()]);

    let mut merged = user;
    if let Some(name) = opts.profile.as_deref() {
        let bundle = merged
            .profiles
            .get(name)
            .map(|b| (**b).clone())
            .ok_or_else(|| {
                let known: Vec<&str> = merged.profiles.keys().map(String::as_str).collect();
                if known.is_empty() {
                    format!(
                        "no profile `{name}`: this config defines no [profiles.*] table \
                         (add one to {})",
                        config_file().display()
                    )
                } else {
                    format!("no profile `{name}` (known profiles: {})", known.join(", "))
                }
            })?;
        merged = merged.overlay_trusted(bundle);
    }

    for name in [PROJECT_CONFIG_FILE, PROJECT_LOCAL_CONFIG_FILE] {
        let Some(path) = find_upward(cwd, name, &markers) else {
            continue;
        };
        merged = merged.overlay_project(read_file_config(&path).sanitized_for_layer(name));
    }

    Ok((apply_run_layers(merged, opts)?, trusted_extends))
}

/// BP-9: the two TRUSTED per-run layers (`--settings`, then
/// `-c/--config key=value`) on top of whatever the file layers resolved to.
/// Separate from [`load_layered`] because `--bare` drops the FILE layers but
/// keeps this command line's own (see `Cli::bare`'s doc comment).
pub fn apply_run_layers(base: FileConfig, opts: &LoadOptions) -> Result<FileConfig, String> {
    let mut merged = base;
    for spec in &opts.settings {
        merged = merged.overlay_trusted(read_settings_layer(spec)?);
    }
    if !opts.overrides.is_empty() {
        let text = supercode_harness::configfile::overrides_to_toml(&opts.overrides)
            .map_err(|e| e.to_string())?;
        let layer: FileConfig = toml::from_str(&text).map_err(|e| {
            format!("invalid inline config override: {e} (assembled from `{text}`)")
        })?;
        merged = merged.overlay_trusted(layer);
    }
    Ok(merged)
}

/// BP-9: one `--settings` document as a [`FileConfig`] layer — inline JSON
/// (`{…}`), or a path to a `.json`/`.toml` file.
fn read_settings_layer(spec: &str) -> Result<FileConfig, String> {
    let trimmed = spec.trim();
    if trimmed.starts_with('{') {
        return serde_json::from_str(trimmed).map_err(|e| format!("invalid --settings JSON: {e}"));
    }
    let path = std::path::Path::new(trimmed);
    let text = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read --settings {}: {e}", path.display()))?;
    if path.extension().is_some_and(|e| e == "toml") {
        toml::from_str(&text).map_err(|e| format!("invalid --settings {}: {e}", path.display()))
    } else {
        serde_json::from_str(&text)
            .map_err(|e| format!("invalid --settings {}: {e}", path.display()))
    }
}

/// Read a user/project [`FileConfig`] without silently turning an existing,
/// malformed or unreadable file into defaults. Startup remains tolerant so a
/// typo cannot brick every command, but the fallback is explicit on stderr
/// and names the exact file/error. Never prints file contents (which may carry
/// endpoint/header configuration).
fn read_file_config(path: &std::path::Path) -> FileConfig {
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return FileConfig::default(),
        Err(e) => {
            warn_config_once(
                format!(
                    "read:{}:{:?}:{}",
                    path.display(),
                    e.kind(),
                    supercode_harness::reduce::content_hash(e.to_string().as_bytes())
                ),
                format!(
                    "warning: failed to read config `{}` ({e}) — ignoring this file",
                    path.display()
                ),
            );
            return FileConfig::default();
        }
    };
    match toml::from_str::<FileConfig>(&text) {
        Ok(config) => config,
        Err(e) => {
            let (key, location) = parse_config_diagnostic_identity(path, &e);
            warn_config_once(
                key,
                format!(
                    "warning: failed to parse config `{}` (TOML syntax/schema error{location}) \
                     — ignoring this file",
                    path.display(),
                ),
            );
            FileConfig::default()
        }
    }
}

fn parse_config_diagnostic_identity(
    path: &std::path::Path,
    error: &toml::de::Error,
) -> (String, String) {
    // `Display` may contain a source excerpt. Hash it only for the hidden
    // dedup identity so changed errors at the same byte offset still surface,
    // but never print it (or config contents).
    let fingerprint = supercode_harness::reduce::content_hash(error.to_string().as_bytes());
    let location = error
        .span()
        .map(|span| format!(" near byte {}", span.start))
        .unwrap_or_default();
    (
        format!("parse:{}:{location}:{fingerprint}", path.display()),
        location,
    )
}

/// Several startup subsystems resolve config independently. Emit one copy of
/// an identical file diagnostic per process rather than flooding a real CLI
/// invocation, while allowing a different path/error identity to surface.
fn warn_config_once(key: String, message: String) {
    static SEEN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
        std::sync::OnceLock::new();
    let seen = SEEN.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()));
    let mut seen = seen.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
    if seen.insert(key) {
        eprintln!("{message}");
    }
}

/// The checked-in project config filename.
pub const PROJECT_CONFIG_FILE: &str = ".supercode.toml";

/// BP-9: the per-user project layer, gitignored by convention. Sits ABOVE
/// `.supercode.toml` in precedence and gets the identical §3.3 sanitization
/// — a convention is not a trust boundary (see
/// `configfile::ConfigLayers`'s doc comment).
pub const PROJECT_LOCAL_CONFIG_FILE: &str = ".supercode.local.toml";

/// BP-9 (D6 row "Project-root detection markers"): walk up from `cwd`
/// looking for `name`, STOPPING at the project root the configured markers
/// define. A config file above the project root belongs to a different
/// project (or to `$HOME`, where the user config already lives), so
/// climbing past the root is how an unrelated repo's settings leak in.
///
/// The root itself is inclusive — a `.supercode.toml` beside `.git` is the
/// project's config. With no marker anywhere above `cwd` the walk runs to
/// the filesystem root, which is the pre-BP-9 behavior.
fn find_upward(cwd: &std::path::Path, name: &str, markers: &[String]) -> Option<PathBuf> {
    let root = supercode_harness::project_root_for(cwd, markers);
    let mut dir = Some(cwd);
    while let Some(d) = dir {
        let candidate = d.join(name);
        if candidate.is_file() {
            return Some(candidate);
        }
        if root.as_deref() == Some(d) {
            return None;
        }
        dir = d.parent();
    }
    None
}

fn read_toml<T: for<'de> Deserialize<'de>>(path: &std::path::Path) -> Option<T> {
    let text = std::fs::read_to_string(path).ok()?;
    toml::from_str(&text).ok()
}

/// Which provider env vars may supply the key for `base_url`. A third-party
/// key (OpenAI/Anthropic) must never be auto-sent to the OpenRouter gateway, so
/// for an OpenRouter endpoint only its own key is eligible. Custom / vendor
/// endpoints keep the flexible fallback.
fn eligible_env_vars(base_url: &str) -> &'static [&'static str] {
    if base_url.to_ascii_lowercase().contains("openrouter") {
        &["OPENROUTER_API_KEY"]
    } else {
        &["OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"]
    }
}

/// BP-9: the configured credential store. Read from the USER config file
/// directly rather than threaded through every caller: `[credentials]` is
/// user/global-layer only (`sanitized_for_project` drops it), so the merged
/// config can never disagree with the user file about it, and the callers
/// that need a key (`login`, `doctor`, `build_config`) do not all have a
/// merged `FileConfig` in hand.
pub fn credential_store() -> CredentialStore {
    CredentialStore::parse(
        read_file_config(&config_file())
            .credentials
            .store
            .as_deref(),
    )
}

/// Read the API key out of the OS keyring through the platform's own tool.
/// `None` on any failure (tool missing, no entry, locked keychain) — every
/// caller treats that as "no stored key", which is the same posture as a
/// missing `credentials.toml`.
pub fn keyring_get() -> Option<String> {
    let out = keyring_read_command()?.output().ok()?;
    if !out.status.success() {
        return None;
    }
    let key = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!key.is_empty()).then_some(key)
}

/// Store the API key in the OS keyring. Returns a human-readable error when
/// the platform has no supported tool, so `login` can say so instead of
/// silently writing nowhere.
pub fn keyring_set(key: &str) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        let out = std::process::Command::new("security")
            .args([
                "add-generic-password",
                "-U",
                "-s",
                KEYRING_SERVICE,
                "-a",
                KEYRING_ACCOUNT,
                "-w",
                key,
            ])
            .output()
            .map_err(|e| format!("`security` is not available ({e})"))?;
        if !out.status.success() {
            return Err(format!(
                "`security add-generic-password` failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            ));
        }
        return Ok(());
    }
    #[cfg(target_os = "linux")]
    {
        use std::io::Write;
        let mut child = std::process::Command::new("secret-tool")
            .args([
                "store",
                "--label=supercode",
                "service",
                KEYRING_SERVICE,
                "account",
                KEYRING_ACCOUNT,
            ])
            .stdin(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| {
                format!("`secret-tool` is not available ({e}); install libsecret-tools")
            })?;
        child
            .stdin
            .as_mut()
            .ok_or_else(|| "cannot write to secret-tool".to_string())?
            .write_all(key.as_bytes())
            .map_err(|e| format!("cannot write to secret-tool: {e}"))?;
        let status = child
            .wait()
            .map_err(|e| format!("secret-tool did not finish: {e}"))?;
        if !status.success() {
            return Err("`secret-tool store` failed".to_string());
        }
        return Ok(());
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        let _ = key;
        Err(
            "no OS keyring integration on this platform; use the default \
             `[credentials] store = \"file\"`"
                .to_string(),
        )
    }
}

/// The platform's keyring READ command, or `None` where there is none.
fn keyring_read_command() -> Option<std::process::Command> {
    #[cfg(target_os = "macos")]
    {
        let mut cmd = std::process::Command::new("security");
        cmd.args([
            "find-generic-password",
            "-w",
            "-s",
            KEYRING_SERVICE,
            "-a",
            KEYRING_ACCOUNT,
        ]);
        Some(cmd)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = std::process::Command::new("secret-tool");
        cmd.args([
            "lookup",
            "service",
            KEYRING_SERVICE,
            "account",
            KEYRING_ACCOUNT,
        ]);
        Some(cmd)
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        None
    }
}

/// The stored key from whichever store is configured.
fn stored_api_key() -> Option<String> {
    match credential_store() {
        CredentialStore::File => {
            read_toml::<Credentials>(&credentials_file()).and_then(|c| c.api_key)
        }
        CredentialStore::Keyring => keyring_get(),
    }
}

/// Resolve the API key from (in order) an explicit flag, the standard provider
/// env vars eligible for `base_url`, then the configured credential store
/// (`credentials.toml` by default, the OS keyring under
/// `[credentials] store = "keyring"`).
pub fn resolve_api_key(flag: Option<&str>, base_url: &str) -> Option<String> {
    if let Some(k) = flag {
        if !k.is_empty() {
            return Some(k.to_string());
        }
    }
    for var in eligible_env_vars(base_url) {
        if let Ok(v) = std::env::var(var) {
            if !v.is_empty() {
                return Some(v);
            }
        }
    }
    stored_api_key()
}

/// Where the resolved key came from (for `doctor`).
pub fn api_key_source(flag: Option<&str>, base_url: &str) -> Option<&'static str> {
    if flag.map(|k| !k.is_empty()).unwrap_or(false) {
        return Some("--api-key flag");
    }
    for var in eligible_env_vars(base_url) {
        if std::env::var(var).map(|v| !v.is_empty()).unwrap_or(false) {
            return Some(match *var {
                "OPENROUTER_API_KEY" => "OPENROUTER_API_KEY env",
                "OPENAI_API_KEY" => "OPENAI_API_KEY env",
                _ => "ANTHROPIC_API_KEY env",
            });
        }
    }
    if stored_api_key().is_some() {
        return Some(credential_store().label());
    }
    None
}

/// Forget the configured local credential. Provider-side revocation is separate.
pub fn clear_api_key() -> std::io::Result<()> {
    if credential_store() == CredentialStore::File {
        return match std::fs::remove_file(credentials_file()) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            result => result,
        };
    }
    #[cfg(target_os = "macos")]
    let status = std::process::Command::new("security")
        .args([
            "delete-generic-password",
            "-s",
            KEYRING_SERVICE,
            "-a",
            KEYRING_ACCOUNT,
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()?;
    #[cfg(target_os = "linux")]
    let status = std::process::Command::new("secret-tool")
        .args([
            "clear",
            "service",
            KEYRING_SERVICE,
            "account",
            KEYRING_ACCOUNT,
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()?;
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    {
        if status.success() || (cfg!(target_os = "macos") && status.code() == Some(44)) {
            return Ok(());
        }
        Err(std::io::Error::other(
            "could not remove the configured keyring credential",
        ))
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "keyring storage is unavailable on this platform",
    ))
}

/// Persist the config file (creates the config home).
pub fn save_config(cfg: &FileConfig) -> std::io::Result<()> {
    std::fs::create_dir_all(config_home())?;
    let text = toml::to_string_pretty(cfg).expect("serialize config");
    std::fs::write(config_file(), text)
}

/// Persist the API key to the configured store: `credentials.toml` with
/// 0600 perms by default, the OS keyring under
/// `[credentials] store = "keyring"`.
pub fn save_api_key(key: &str) -> std::io::Result<()> {
    if credential_store() == CredentialStore::Keyring {
        return keyring_set(key).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e));
    }
    std::fs::create_dir_all(config_home())?;
    let creds = Credentials {
        api_key: Some(key.to_string()),
    };
    let path = credentials_file();
    std::fs::write(
        &path,
        toml::to_string_pretty(&creds).expect("serialize creds"),
    )?;
    set_owner_only(&path)?;
    Ok(())
}

#[cfg(unix)]
fn set_owner_only(path: &std::path::Path) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
}

#[cfg(not(unix))]
fn set_owner_only(_path: &std::path::Path) -> std::io::Result<()> {
    Ok(())
}

// ---- MCP server registry ---------------------------------------------------

/// A configured external MCP server — stdio (the original, still-default
/// shape) or, P5-2 (COMPOSABLE-HARNESS-DESIGN.md §2 module 15 D7 row 2),
/// remote HTTP/SSE. `command` is now OPTIONAL (was a required `String`)
/// SOLELY so a remote-transport entry can omit it — every existing
/// stdio-only `mcp.json`/`[capabilities.mcp.servers.*]` entry that already
/// sets `command` continues to parse/re-save byte-identically (a `Some`
/// value serializes as the bare string it always did, via
/// `skip_serializing_if`); [`Self::transport`]'s default (`"stdio"`, absent
/// key) is what makes an old file's ABSENCE of `transport` still mean
/// exactly what it always meant.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct McpServerDef {
    /// `"stdio"` (default) | `"http"` | `"sse"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transport: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    /// Extra environment variables for the spawned server process, set ON
    /// TOP OF (never replacing) supercode's own inherited environment —
    /// matching Claude Code / Codex's `env` field semantics, and how
    /// `tokio::process::Command` behaves by default (it inherits the parent
    /// environment unless `.env_clear()` is called, so `.envs(...)` only
    /// adds/overrides the named vars). `None` when absent, and
    /// `skip_serializing_if` keeps it that way on re-save, so an existing
    /// `mcp.json` written before `env` support existed loads and re-saves
    /// byte-for-byte identical — no spurious `"env": {}` key appears.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<std::collections::BTreeMap<String, String>>,
    /// The remote endpoint URL — required (and only meaningful) for
    /// `transport = "http"|"sse"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Extra request headers for the remote transports (e.g. a static API
    /// key some servers accept as a header instead of OAuth). SECURITY:
    /// like [`Self::oauth`], this whole server DEFINITION (this struct) is
    /// project-forbidden — see `configfile::sanitize_for_project`'s
    /// `capabilities.mcp.servers` strip — so a header value set here is
    /// only ever user/global-layer-controlled, never project-supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<std::collections::BTreeMap<String, String>>,
    /// OAuth endpoint configuration for the remote transports (P5-2 §2
    /// module 15 D7 row 2's OAuth deliverable) — the ENDPOINTS only, never
    /// a token: see `crate::mcp_oauth_store`'s doc comment for why the
    /// actual access/refresh tokens live in a SEPARATE trust-grade file
    /// (`mcp_oauth.json`, 0600, `config_home()`-only), not here, and never
    /// reachable through `.supercode.toml` at all.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oauth: Option<McpOAuthServerConfig>,
}

/// The endpoints/identity an MCP server's OAuth device-code flow needs —
/// see [`McpServerDef::oauth`]'s doc comment for why this carries no token.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct McpOAuthServerConfig {
    pub device_authorization_endpoint: String,
    pub token_endpoint: String,
    pub client_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
}

/// The `mcp.json` registry — shape matches Claude Code / Codex `--mcp-config`
/// files (`{ "mcpServers": { "<name>": { "command", "args" } } }`), so the same
/// files work here.
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct McpServers {
    #[serde(rename = "mcpServers", default)]
    pub servers: std::collections::BTreeMap<String, McpServerDef>,
}

pub fn mcp_file() -> PathBuf {
    config_home().join("mcp.json")
}

/// Read an MCP registry from a specific JSON file.
pub fn read_mcp_file(path: &std::path::Path) -> std::io::Result<McpServers> {
    let text = std::fs::read_to_string(path)?;
    serde_json::from_str(&text).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}

/// Load the user's stored MCP registry (empty if none).
pub fn load_mcp() -> McpServers {
    read_mcp_file(&mcp_file()).unwrap_or_default()
}

/// Persist the MCP registry.
pub fn save_mcp(reg: &McpServers) -> std::io::Result<()> {
    std::fs::create_dir_all(config_home())?;
    std::fs::write(
        mcp_file(),
        serde_json::to_string_pretty(reg).expect("serialize mcp"),
    )
}

// ---- MCP OAuth token storage (P5-2, trust-grade) ---------------------------
//
// COMPOSABLE-HARNESS-DESIGN.md §2.1 "model.oauth → trust-grade token
// storage" — the same security posture applies here: an MCP server's OAuth
// access/refresh token is a CREDENTIAL, the exact trust class as
// `Config::api_key` (§3.2 S13, "never a plaintext file key... never a
// project-readable location"). Mirrors `credentials_file`/`save_api_key`'s
// existing precedent EXACTLY:
// - lives at `config_home()` — user/global directory ONLY, never inside a
//   project (there is no per-project variant of this path at all, so a
//   project can't even name it, let alone redirect it);
// - written with 0600 (`set_owner_only`) so no other local user can read it;
// - reachable through NO `.supercode.toml` key whatsoever — unlike
//   `capabilities.mcp.servers` (stripped from the project layer by
//   `configfile::sanitize_for_project`), a token isn't even a config FIELD
//   whose value could be set; the only way tokens enter this file is
//   `save_mcp_oauth_tokens`, called from the CLI's own OAuth flow
//   (`supercode_harness::mcp_oauth::run_device_flow`/`refresh_token`).

/// Path to the MCP OAuth token store.
pub fn mcp_oauth_file() -> PathBuf {
    config_home().join("mcp_oauth.json")
}

#[derive(Default, Deserialize, Serialize)]
struct McpOAuthStore {
    #[serde(default)]
    servers: std::collections::BTreeMap<String, supercode_harness::mcp_oauth::McpOAuthTokens>,
}

/// Load the stored OAuth tokens for `server`, if any were saved.
pub fn load_mcp_oauth_tokens(server: &str) -> Option<supercode_harness::mcp_oauth::McpOAuthTokens> {
    let store: McpOAuthStore = read_toml_or_json(&mcp_oauth_file())?;
    store.servers.get(server).cloned()
}

/// Persist `tokens` for `server`, creating/updating `mcp_oauth.json` with
/// 0600 permissions (same helper `save_api_key` uses).
pub fn save_mcp_oauth_tokens(
    server: &str,
    tokens: &supercode_harness::mcp_oauth::McpOAuthTokens,
) -> std::io::Result<()> {
    std::fs::create_dir_all(config_home())?;
    let mut store: McpOAuthStore = read_toml_or_json(&mcp_oauth_file()).unwrap_or_default();
    store.servers.insert(server.to_string(), tokens.clone());
    let path = mcp_oauth_file();
    std::fs::write(
        &path,
        serde_json::to_string_pretty(&store).expect("serialize mcp oauth store"),
    )?;
    set_owner_only(&path)?;
    Ok(())
}

/// Remove any stored OAuth tokens for `server` (e.g. `mcp logout`).
pub fn remove_mcp_oauth_tokens(server: &str) -> std::io::Result<()> {
    let Some(mut store): Option<McpOAuthStore> = read_toml_or_json(&mcp_oauth_file()) else {
        return Ok(());
    };
    if store.servers.remove(server).is_some() {
        let path = mcp_oauth_file();
        std::fs::write(
            &path,
            serde_json::to_string_pretty(&store).expect("serialize mcp oauth store"),
        )?;
        set_owner_only(&path)?;
    }
    Ok(())
}

/// Small helper: this store is JSON (matches `mcp.json`'s own format, and
/// `McpOAuthTokens` isn't `toml`-friendly for `Option`-heavy shapes the way
/// `read_toml` elsewhere in this file assumes) — a thin, explicitly-named
/// wrapper rather than overloading `read_toml`'s name for a different
/// format.
fn read_toml_or_json<T: serde::de::DeserializeOwned>(path: &std::path::Path) -> Option<T> {
    let text = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&text).ok()
}

/// Expand a friendly model alias to its full slug. Unknown values pass through
/// unchanged, so any real slug still works.
///
/// P4 (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4": "aliases + fallback chains
/// (userconfig.rs:386-411) promoted into core"): delegates to
/// [`supercode_harness::model_catalog::resolve_alias`], the single source of truth
/// now — this is a thin re-export kept for the CLI's many existing call
/// sites (zero call-site churn, zero behavior change: same eleven aliases,
/// byte-identical resolution).
pub fn resolve_model_alias(model: &str) -> String {
    supercode_harness::model_catalog::resolve_alias(model)
}

/// The known aliases, for `doctor` / help display. Delegates to
/// [`supercode_harness::model_catalog::DEFAULT_ALIASES`] — see [`resolve_model_alias`].
pub fn alias_table() -> &'static [(&'static str, &'static str)] {
    supercode_harness::model_catalog::DEFAULT_ALIASES
}