croft-software 0.2.132

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

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

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

use crate::app::{PanelAlignment, QuickInputPosition, SideBarPosition};
use crate::theme::Theme;

/// The layout chrome chosen in the "Customize Layout" popup (croft's analog of
/// VS Code's title-bar layout controls). Every field carries its own
/// `#[serde(default)]` so a config written before this block existed still
/// parses straight into these defaults. The primary side bar (⌘B) and panel
/// (⌃J) visibility stay ephemeral per launch and so are NOT stored here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct LayoutPrefs {
    #[serde(default = "default_true")]
    pub activity_bar: bool,
    #[serde(default = "default_true")]
    pub status_bar: bool,
    /// The editor minimap. On unless switched off, also for an older config
    /// that has no such key.
    #[serde(default = "default_true")]
    pub minimap: bool,
    #[serde(default)]
    pub side_bar_position: SideBarPosition,
    #[serde(default)]
    pub secondary_side_bar: bool,
    #[serde(default)]
    pub panel_alignment: PanelAlignment,
    #[serde(default)]
    pub quick_input_position: QuickInputPosition,
    /// View: Toggle Centered Layout (#1585): the editor keeps
    /// `centered_layout_width` columns in the middle of the window.
    #[serde(default)]
    pub centered_layout: bool,
    /// Zen Mode centres the editor, as VS Code's `zenMode.centerLayout`
    /// (#1585). On by default.
    #[serde(default = "default_true")]
    pub zen_center_layout: bool,
    /// How wide the centred editor is, in columns (#1585).
    #[serde(default = "default_centered_layout_width")]
    pub centered_layout_width: u16,
}

fn default_centered_layout_width() -> u16 {
    120
}

impl Default for LayoutPrefs {
    fn default() -> Self {
        Self {
            activity_bar: true,
            status_bar: true,
            minimap: true,
            side_bar_position: SideBarPosition::default(),
            secondary_side_bar: false,
            panel_alignment: PanelAlignment::default(),
            quick_input_position: QuickInputPosition::default(),
            centered_layout: false,
            zen_center_layout: true,
            centered_layout_width: default_centered_layout_width(),
        }
    }
}

/// When a paste of more than one line into a terminal asks first (#1274),
/// VS Code's `terminal.integrated.enableMultiLinePasteWarning`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MultilinePasteWarning {
    /// Only when the program in the pane has not turned on bracketed paste,
    /// so each line would run the moment it lands.
    #[default]
    Auto,
    /// Before every multi-line paste.
    Always,
    /// Never.
    Never,
}

/// Which of the Explorer's stacked sub-views are shown, toggled from the
/// "Views and More Actions" (⋯) menu on the EXPLORER header. Mirrors VS Code's
/// defaults: Open Editors hidden, every other view shown. Each field carries
/// its own `#[serde(default)]` so a config written before this block existed
/// still parses straight into these defaults.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExplorerViewsPrefs {
    #[serde(default)]
    pub open_editors: bool,
    #[serde(default = "default_true")]
    pub folders: bool,
    #[serde(default = "default_true")]
    pub outline: bool,
    #[serde(default = "default_true")]
    pub timeline: bool,
    /// The DEPENDENCIES view. `alias` keeps configs written under the old
    /// Rust-only `rust_dependencies` key parsing into this generalized field.
    #[serde(default = "default_true", alias = "rust_dependencies")]
    pub dependencies: bool,
    /// The AGENT LANE view (#345): only drawn while a coding agent has
    /// changed files, so on by default costs nothing until one has.
    #[serde(default = "default_true")]
    pub agent_lane: bool,
}

fn default_true() -> bool {
    true
}

impl Default for ExplorerViewsPrefs {
    fn default() -> Self {
        Self {
            open_editors: false,
            folders: true,
            outline: true,
            timeline: true,
            dependencies: true,
            agent_lane: true,
        }
    }
}

/// One per-host pane accent rule (iTerm2's automatic profile switching,
/// scoped to what a TUI can dress): panes whose shell-reported hostname
/// (OSC 7) matches `pattern` (glob, e.g. "prod-*") wear `accent` (hex
/// `#rrggbb`, danger red when absent) on their border and name pill, plus
/// a translucent `badge` watermark.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct HostAccentRule {
    pub pattern: String,
    #[serde(default)]
    pub accent: Option<String>,
    #[serde(default)]
    pub badge: Option<String>,
}

/// One notification sink (#358): where an event goes and which events.
///
/// `kind` is `ntfy` (`topic`, optional `server`), `webhook` (`url`,
/// optional `headers`), `termux` (runs `termux-notification`), or
/// `command` (`argv`, with the notification in `CROFT_*` environment
/// variables). `events` names the kinds it takes — `command_finished`,
/// `tests_failed`, `osc9`, `agent_waiting` — or is empty for all of them;
/// `min_duration_secs` is the threshold for a finished command (default
/// 10). Webhook headers may carry a secret: keep them in
/// `config.local.json`, the machine-local layer that is never synced.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct NotificationSink {
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub topic: Option<String>,
    #[serde(default)]
    pub server: Option<String>,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    #[serde(default)]
    pub argv: Vec<String>,
    #[serde(default)]
    pub events: Vec<String>,
    #[serde(default)]
    pub min_duration_secs: Option<u64>,
}

/// `#rrggbb` → bytes; anything else is treated as unset.
pub fn parse_hex(s: &str) -> Option<(u8, u8, u8)> {
    let hex = s.strip_prefix('#')?;
    if hex.len() != 6 {
        return None;
    }
    let n = u32::from_str_radix(hex, 16).ok()?;
    Some(((n >> 16) as u8, (n >> 8) as u8, n as u8))
}

/// The settings one language may override (#1440). Each is unset unless a
/// `languages.<id>` block names it, and an unset one falls back to the
/// global setting of the same name. Any other key in a block is ignored.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct LanguagePrefs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format_on_save: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format_on_type: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub render_whitespace: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disable_inlay_hints: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disable_auto_close_pairs: Option<bool>,
}

/// The [`LanguagePrefs`] keys: the settings a language block may set.
pub const LANGUAGE_KEYS: &[&str] = &[
    "format_on_save",
    "format_on_type",
    "render_whitespace",
    "disable_inlay_hints",
    "disable_auto_close_pairs",
];

/// The on-disk preferences document. New fields must default so an older
/// config still parses; `#[serde(default)]` covers that.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Prefs {
    /// Active color theme, stored by its stable [`Theme::id`].
    #[serde(default)]
    pub theme: String,
    /// On-screen keyboard split layout (two thumb clusters on foldables),
    /// toggled by the OSK's `split` key.
    #[serde(default)]
    pub osk_split: bool,
    /// When true, the startup "switch to iTerm2/Ghostty" nudge shown in
    /// terminals that can't render croft's inline images is silenced (the
    /// user dismissed it with "don't show again").
    #[serde(default)]
    pub suppress_terminal_warning: bool,
    /// Visibility of the Explorer's stacked sub-views (⋯ menu toggles).
    #[serde(default)]
    pub explorer_views: ExplorerViewsPrefs,
    /// Collapse the sidebar when focus moves to the editor or a terminal
    /// (#260). Off by default: hiding chrome on focus surprises people who
    /// did not ask for it, so this is opt-in.
    #[serde(default)]
    pub sidebar_auto_hide: bool,
    /// Which files the PROBLEMS panel lists (#256): `whole_project` (default,
    /// every file a server or build tool reported) or `open_files`.
    /// Unrecognised values read as `whole_project`, so a typo shows more
    /// rather than silently hiding diagnostics.
    #[serde(default)]
    pub problems_scope: String,
    /// Whether the whole-project check may run without being asked (#256):
    /// `auto` (under a file-count cap), `on`, or `off`. Unrecognised values
    /// read as `auto`, so a typo cannot start a compile on a huge root.
    #[serde(default)]
    pub problems_project_scope: String,
    /// What a gcc/clang-shaped build message counts its column in:
    /// `display` (screen cells, a tab running to the next multiple of 8;
    /// gcc 11 and newer), `byte` (clang, older gcc) or `char`. Unrecognised
    /// or empty reads as `display`. It decides where "Go to Problem" and a
    /// click in PROBLEMS put the caret on a line with a tab or a non-ASCII
    /// character.
    #[serde(default)]
    pub build_column_unit: String,
    /// Default whitespace handling for new diff views: `off` (every byte
    /// counts), `leading` (ignore indentation changes), or `all` (ignore every
    /// whitespace-only difference). Unrecognised values read as `off`, so a
    /// typo degrades to the safe, byte-exact view rather than hiding changes.
    /// Per-view toggling never writes back here.
    #[serde(default)]
    pub diff_ignore_whitespace: String,
    /// Extension ids the user has disabled in the Extensions panel. Absent or
    /// empty means every bundled and installed extension is enabled (the
    /// default), so disabling is opt-in and an older config still parses.
    #[serde(default)]
    pub disabled_extensions: BTreeSet<String>,
    /// The first-launch tour was finished or skipped (#377): the welcome
    /// panel stops offering it.
    #[serde(default)]
    pub tour_done: bool,
    /// MCP sidecar extension ids the user has consented to spawn (the first-run
    /// consent gate). croft never launches a sidecar process until its extension
    /// id is in this set.
    #[serde(default)]
    pub mcp_consented: BTreeSet<String>,
    /// Trust-on-first-use tool fingerprints, keyed by command id. Recorded the
    /// first time a command's tool is called; a later mismatch (a silent tool
    /// rug-pull) makes croft refuse the call. See
    /// [`crate::mcp::client::tool_fingerprint`].
    #[serde(default)]
    pub mcp_tool_fingerprints: BTreeMap<String, String>,
    /// Layout chrome chosen in the "Customize Layout" popup.
    #[serde(default)]
    pub layout: LayoutPrefs,
    /// When true, saving a file first asks the language server to format it
    /// (VS Code's `editor.formatOnSave`). Off by default, matching VS Code, so
    /// an older config parses straight to disabled.
    #[serde(default)]
    pub format_on_save: bool,
    /// The formatter a project names for every file, VS Code's
    /// `editor.defaultFormatter` (#1499), as an extension id such as
    /// `biomejs.biome`. Format on save skips a file whose named formatter
    /// croft does not run, rather than formatting it with something else.
    #[serde(default)]
    pub default_formatter: Option<String>,
    /// `editor.defaultFormatter` for one language, keyed by its VS Code
    /// language id (`"[typescript]": { "editor.defaultFormatter": … }`,
    /// #1499). Wins over `default_formatter` for that language.
    #[serde(default)]
    pub language_formatters: BTreeMap<String, String>,
    /// When true, every save ends the file with a newline (VS Code's
    /// `files.insertFinalNewline`, #1657). Off by default, matching VS Code;
    /// a `.editorconfig` `insert_final_newline` wins for its file.
    #[serde(default)]
    pub insert_final_newline: bool,
    /// When true, every save strips trailing spaces and tabs from the lines
    /// no caret is on (VS Code's `files.trimTrailingWhitespace`, #1657). Off
    /// by default; a `.editorconfig` `trim_trailing_whitespace` wins.
    #[serde(default)]
    pub trim_trailing_whitespace: bool,
    /// When true, every save drops the empty lines after the last line of
    /// text (VS Code's `files.trimFinalNewlines`, #1657). Off by default.
    #[serde(default)]
    pub trim_final_newlines: bool,
    /// When true, typing one of the language server's on-type trigger
    /// characters (`}`, `;`, newline, per its capability) runs
    /// `textDocument/onTypeFormatting` on the just-typed spot (VS Code's
    /// `editor.formatOnType`). Off by default, matching VS Code.
    #[serde(default)]
    pub format_on_type: bool,
    /// When true, a dirty buffer writes itself to disk about a second after
    /// the last edit (VS Code's `files.autoSave: afterDelay`). Off by
    /// default, matching VS Code.
    #[serde(default)]
    pub auto_save: bool,
    /// When true, a dirty buffer writes itself the moment it loses focus
    /// (VS Code's `files.autoSave: onFocusChange`): the editor pane losing
    /// focus, or the active tab changing. Independent of `auto_save`, so
    /// both can be on. Off by default, matching VS Code.
    #[serde(default)]
    pub auto_save_on_focus_change: bool,
    /// Opt-out for the GitLens-style current-line inline blame annotation,
    /// which is on by default. Stored as the disable flag (like
    /// `suppress_terminal_warning`) so the derived `Default` and an older
    /// config both mean "blame shown".
    #[serde(default)]
    pub disable_inline_blame: bool,
    /// Auto-closing pairs (#121) are ON by default; this stores the opt-out
    /// (a default-false field keeps old configs valid, like inline blame).
    #[serde(default)]
    pub disable_auto_close_pairs: bool,
    /// A multi-line paste is re-indented under the caret line (#1218); this
    /// stores the opt-out for people who want the clipboard verbatim.
    #[serde(default)]
    pub disable_paste_reindent: bool,
    /// Completion opens as a word is typed in code (#929), as VS Code's
    /// `editor.quickSuggestions` does; this stores the opt-out, leaving it
    /// to Ctrl+Space and the server's trigger characters.
    #[serde(default)]
    pub disable_quick_suggestions: bool,
    /// Opt-out for debugger inline values (#135), on by default like VS
    /// Code's `debug.inlineValues: "auto"`. Stored as the disable flag so
    /// the derived `Default` and an older config both mean "values shown".
    #[serde(default)]
    pub disable_inline_values: bool,
    /// Opt-out for saving unsaved editors before a debug or run launch
    /// (#1400), a task or a Testing run (#1639), on by default like VS
    /// Code's `debug.saveBeforeStart` (`allEditorsInActiveGroup`); `"none"`
    /// there maps to true here.
    #[serde(default)]
    pub disable_save_before_debug: bool,
    /// Start in Vim mode (#1286). Toggle Vim Mode saves it, so the mode a
    /// user left croft in is the one the next launch starts in. Applies
    /// only while the `vim` extension is enabled.
    #[serde(default)]
    pub vim_mode: bool,
    /// Whitespace rendering mode (#133): "selection" (VS Code's default,
    /// also what the empty string an older config deserializes to means),
    /// "all", or "none". Parsed by `WhitespaceMode::from_pref`.
    #[serde(default)]
    pub render_whitespace: String,
    /// Vertical rulers (#1524), VS Code's `editor.rulers`: a dim line down
    /// the editor at each of these columns marks a line-length limit, such
    /// as 80 or 100. Empty draws none.
    #[serde(default)]
    pub rulers: Vec<u16>,
    /// Word-based completion (#1566), VS Code's
    /// `editor.wordBasedSuggestions`: which open documents' words Ctrl+Space
    /// offers when no language server has suggestions. "off",
    /// "currentDocument", "matchingDocuments" (the default, also what the
    /// empty string means: the open documents in the same language) or
    /// "allDocuments". Parsed by `WordSuggestions::from_pref`.
    #[serde(default)]
    pub word_based_suggestions: String,
    /// Opt-out for bracket-pair colorization (#131), on by default like VS
    /// Code's `editor.bracketPairColorization.enabled` (default since 1.67).
    /// Stored as the disable flag so the derived `Default` and an older
    /// config both mean "brackets coloured".
    #[serde(default)]
    pub disable_bracket_colors: bool,
    /// Opt-out for indentation guides (#129), which are on by default like
    /// VS Code's `editor.guides.indentation`. Stored as the disable flag so
    /// the derived `Default` and an older config both mean "guides shown".
    #[serde(default)]
    pub disable_indent_guides: bool,
    /// Home on a wrapped line (#1569): with this on, pressing Home on the
    /// start of a continuation row goes to the start of the row above, one
    /// visual row per press, before the line's own stops. Off (the default)
    /// is VS Code's `cursorHome`: from a row's start straight to the line's
    /// first non-blank character and column 0.
    #[serde(default)]
    pub home_walks_wrapped_rows: bool,
    /// Gutter line numbers (#1576, VS Code's `editor.lineNumbers`): "on"
    /// (also what the empty string an older config deserializes to means),
    /// "relative", "interval" or "off". Parsed by `LineNumbers::from_pref`.
    #[serde(default)]
    pub line_numbers: String,
    /// Opt-out for LSP inlay hints (inline type / parameter annotations),
    /// which are on by default like VS Code's `editor.inlayHints.enabled`.
    /// Stored as the disable flag so the derived `Default` and an older
    /// config both mean "hints shown".
    #[serde(default)]
    pub disable_inlay_hints: bool,
    /// Opt-out for the navigator's proactive comment-only looks (a newly
    /// completed construct plus a typing pause hands it the floor). On by
    /// default while a navigator is seated; stored as the disable flag so
    /// the derived `Default` and an older config both mean "proactive".
    #[serde(default)]
    pub disable_proactive_navigator: bool,
    /// Copy a finished terminal mouse selection straight to the clipboard
    /// (VS Code's `terminal.integrated.copyOnSelection`). Off by default,
    /// matching VS Code.
    #[serde(default)]
    pub copy_on_select: bool,
    /// Globs hidden from the Explorer, Go to File and Search (VS Code's
    /// `files.exclude`, #1345). Matched against workspace-relative paths;
    /// a folder's match hides everything inside it.
    #[serde(default)]
    pub files_exclude: Vec<String>,
    /// Globs kept out of Search, Replace All and Go to File, on top of
    /// `files_exclude` (VS Code's `search.exclude`, #1345).
    #[serde(default)]
    pub search_exclude: Vec<String>,
    /// The language a file opens in, by glob (VS Code's
    /// `files.associations`, #1574): `{ "*.tpl": "html" }`. A glob without
    /// a `/` matches the file name, one with a `/` the workspace-relative
    /// path. Values are VS Code language ids; workspace entries win per glob.
    #[serde(default)]
    pub files_associations: std::collections::BTreeMap<String, String>,
    /// Per-language overrides (#1440), keyed by VS Code's language id
    /// (`python`, `c`, `markdown`, `shellscript`, …), VS Code's
    /// `"[python]": { … }` blocks. A value set here wins over the global
    /// one for a file in that language; see [`LanguagePrefs`].
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub languages: BTreeMap<String, LanguagePrefs>,
    /// The encoding files without a byte-order mark open in (VS Code's
    /// `files.encoding`, #1432): `windows1252`, `latin1`, `shiftjis`,
    /// `utf8bom` and the like. Empty means UTF-8. A BOM, an `.editorconfig`
    /// `charset` and a per-file "Reopen with Encoding" choice all win.
    #[serde(default)]
    pub files_encoding: String,
    /// Opt-out for tailspin highlighting in the rendered log view (#466):
    /// dates, numbers, UUIDs, IPs, URLs, paths, quotes and severity keywords
    /// are coloured on lines that carry no colour of their own. Stored as
    /// the disable flag so the derived `Default` and an older config both
    /// mean "highlighted".
    #[serde(default)]
    pub disable_log_highlight: bool,
    /// Opt-out for the built-in secret redaction rules (#360): the shapes
    /// [`crate::triggers::TriggerSet::with_builtin_redactions`] turns on are
    /// masked in terminal panes by default. Stored as the disable flag so
    /// the derived `Default` and an older config both mean "masked".
    #[serde(default)]
    pub disable_secret_redaction: bool,
    /// Per-host pane accent rules; see [`HostAccentRule`].
    #[serde(default)]
    pub host_accents: Vec<HostAccentRule>,
    /// Opt-out for the ssh-pane workspace offer (#364): when a pane's
    /// foreground becomes `ssh <host>` for a host in `~/.ssh/config`, the
    /// status bar offers to open the workspace on that host. Stored as the
    /// disable flag so the derived `Default` and an older config both mean
    /// "offer". User layers only: an offer is a prompt to connect somewhere.
    #[serde(default)]
    pub disable_remote_offer: bool,
    /// Hosts (ssh config aliases, matched case-insensitively) the offer
    /// never prompts for (#364): the per-host `auto_offer = off`. A jump
    /// host, a box you only ever tunnel through. User layers only.
    #[serde(default)]
    pub remote_offer_excluded_hosts: Vec<String>,
    /// Hosts (ssh config aliases, matched case-insensitively) that config
    /// sync (#262) never pushes to: the per-host `sync_config = off`. A shared
    /// box, or one whose keybindings are deliberately different. User layers
    /// only: a workspace must not be able to switch sync on or off.
    #[serde(default)]
    pub config_sync_excluded_hosts: Vec<String>,
    /// Syncable files, by name (`"keybindings.json"`), that never travel to
    /// any remote (#262): the per-file escape. User layers only.
    #[serde(default)]
    pub config_sync_excluded_files: Vec<String>,
    /// Named sets of SSH hosts for "Terminal: Fleet Run" (#363), so a fleet
    /// can be named once rather than retyped per run.
    ///
    /// User layers only, and for the same reason as the list above: a fleet
    /// run executes arbitrary text on every host in the set, so a group is a
    /// list of machines to run commands on. A repo-controlled layer naming
    /// one could add a production box to a group the user then broadcasts
    /// to. `WORKSPACE_ALLOWED_KEYS` refuses it, and the refusal is visible
    /// rather than silent.
    ///
    /// Ordered, so the hosts a group names come back in the same order on
    /// every run: a HashMap would shuffle them, and a fleet comparison is
    /// read by scanning down the list.
    #[serde(default)]
    pub fleet_groups: std::collections::BTreeMap<String, Vec<String>>,
    /// Whether GitHub code scanning results load by themselves (#577):
    /// `"off"` (default), `"on"` for the current branch and again on every
    /// branch change, or `"prompt"` to say so and wait. User layers only:
    /// a repository must not decide that croft calls GitHub for it.
    #[serde(default)]
    pub code_scanning: crate::sarif::github::CodeScanningMode,
    /// The agent a new worktree lane starts in its pane (#348): the name of
    /// an `agents.json` row (built in: claude, codex, aider, gemini), whose
    /// `launch` line is typed into the lane's fresh shell. Unset, a lane
    /// opens a plain shell. User layers only: it names a command to run.
    #[serde(default)]
    pub lane_agent: Option<String>,
    /// The colour depth croft draws for (#1433): "truecolor", "256" or
    /// "16". Unset, it is read from the terminal's environment; set it for
    /// a terminal that draws 24-bit colour without saying so (often over
    /// SSH, where `COLORTERM` is not passed on). Read at startup.
    #[serde(default)]
    pub color_depth: Option<String>,
    /// Scrollback lines kept per terminal pane (VS Code's
    /// `terminal.integrated.scrollback`). 0 — the default for older configs —
    /// means the built-in 5000. Applies to panes opened after the change.
    #[serde(default)]
    pub terminal_scrollback: usize,
    /// Memory, in megabytes, that terminal rewind (#357) may hold across ALL
    /// panes together (#694). Unset or `0` records nothing: no Session:
    /// Rewind exists yet to show it (#1342). Applies from the next pane
    /// opened, and re-splits the budget across the panes already open.
    #[serde(default)]
    pub terminal_rewind_mb: Option<usize>,
    /// Keep each terminal pane's shell in a process of its own (#694), so a
    /// croft that is killed or crashes leaves the shells and their jobs
    /// running, and the next croft in the workspace reattaches to them.
    /// Closing a pane or quitting croft still ends its shell. Linux and
    /// macOS; off by default. Applies to panes opened after the change.
    #[serde(default)]
    pub terminal_persistent_panes: bool,
    /// Whether a multi-line paste into a terminal asks before it is written
    /// (#1274): `auto` (the default) asks only when the pane's program has
    /// not turned on bracketed paste, `always` asks for every multi-line
    /// paste, `never` never asks. User layers only: a cloned repo must not
    /// switch the guard off.
    #[serde(default)]
    pub terminal_multiline_paste_warning: MultilinePasteWarning,
    /// What exported navigator comments start with (#368), marking them as
    /// AI-authored on GitHub. Unset means `[AI, croft navigator] `; an
    /// empty string turns the marker off.
    #[serde(default)]
    pub review_ai_prefix: Option<String>,
    /// Screen reader mode (#621): a steady caret kept on the focused text
    /// and a one-line description of each change in the status bar. Off by
    /// default.
    #[serde(default)]
    pub screen_reader: bool,
    /// A speech program croft runs with each screen reader line as its last
    /// argument (`spd-say`, `say`). User layers only: it names a command.
    #[serde(default)]
    pub screen_reader_command: Option<String>,
    /// The CodeQL CLI to run (#578), used before one on `PATH` or the copy
    /// croft downloads. User layers only: it names a program to run.
    #[serde(default)]
    pub codeql_cli_path: Option<String>,
    /// UI language (#621), such as `de` or `es`. Unset, croft follows
    /// `LC_ALL` / `LC_MESSAGES` / `LANG`.
    #[serde(default)]
    pub locale: Option<String>,
    /// Notification sinks; see [`NotificationSink`]. User layers only: not
    /// in `WORKSPACE_ALLOWED_KEYS`, so a cloned repo cannot make croft run
    /// a command or post to a URL.
    #[serde(default)]
    pub notifications: Vec<NotificationSink>,
    /// The file as it was read, kept so a save rewrites only what changed.
    #[serde(skip)]
    pub(crate) source: SourceDoc,
}

/// The raw `config.json` object a [`Prefs`] was loaded from. The settings
/// loader reads keys this struct has no field for (`extends`, the
/// `macos` / `linux` / `android` blocks, settings of newer versions), so a
/// save that wrote the struct back alone deleted them. Ignored by equality:
/// two `Prefs` with the same settings are equal wherever they came from.
#[derive(Debug, Clone, Default)]
pub(crate) struct SourceDoc(Option<serde_json::Map<String, serde_json::Value>>);

impl PartialEq for SourceDoc {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl Eq for SourceDoc {}

/// Write into `doc` (the file as read) what changed between `loaded` (its
/// typed view then) and `current` (the settings now), key by key and into
/// nested objects: a changed `layout` field must not drop keys a newer
/// version put inside `layout`. A key the current settings no longer
/// serialize (an option cleared) leaves the file too.
fn merge_changed(
    doc: &mut serde_json::Map<String, serde_json::Value>,
    loaded: &serde_json::Value,
    current: &serde_json::Value,
) {
    use serde_json::Value;
    let (Value::Object(loaded), Value::Object(current)) = (loaded, current) else {
        return;
    };
    for key in loaded.keys().filter(|k| !current.contains_key(*k)) {
        doc.remove(key);
    }
    for (key, value) in current {
        let before = loaded.get(key);
        if before == Some(value) {
            continue;
        }
        // A nested object the file does not have yet (the first `layout`
        // change in a new config.json) gets only its changed keys too, so its
        // untouched siblings keep following the defaults and any `extends`
        // base.
        if let (Some(b @ Value::Object(_)), Value::Object(_)) = (before, value)
            && !doc.contains_key(key)
            && !SERDE_ALIASES
                .iter()
                .any(|(canonical, legacy)| key == canonical && doc.contains_key(*legacy))
        {
            let mut inner = serde_json::Map::new();
            merge_changed(&mut inner, b, value);
            doc.insert(key.clone(), Value::Object(inner));
            continue;
        }
        match (doc.get_mut(key), before, value) {
            (Some(Value::Object(inner)), Some(b @ Value::Object(_)), Value::Object(_)) => {
                merge_changed(inner, b, value);
            }
            _ => {
                // The old spelling goes with it: serde rejects an object
                // holding both a field and its alias as a duplicate field,
                // so the next load would fall back to defaults.
                for (canonical, legacy) in SERDE_ALIASES {
                    if key == canonical {
                        doc.remove(*legacy);
                    }
                }
                doc.insert(key.clone(), value.clone());
            }
        }
    }
}

/// Every `#[serde(alias)]` in the settings, as (field, old key), for
/// [`merge_changed`].
const SERDE_ALIASES: &[(&str, &str)] = &[("dependencies", "rust_dependencies")];

/// The `config.json` that [`Prefs::load_or_default`] reads, or `None` in
/// test builds: the user's real `config.json` must never steer a test
/// (#624), the same rule `config_layers::load_merged` applies to the
/// settings layers.
fn saved_prefs_path() -> Option<PathBuf> {
    (!cfg!(test)).then(config_path)
}

impl Prefs {
    /// Load preferences from `config_path()`, falling back to defaults when
    /// the file is absent or unreadable. Preferences are best-effort: a
    /// corrupt config should never block startup. Test builds always get
    /// the defaults (see [`saved_prefs_path`]).
    pub fn load_or_default() -> Self {
        saved_prefs_path()
            .and_then(|p| Self::load(&p).ok())
            .unwrap_or_default()
    }

    pub fn load(path: &Path) -> Result<Self> {
        let json =
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        Self::parse(&json).with_context(|| format!("parsing {}", path.display()))
    }

    /// Parse a `config.json`, which is JSONC like every other settings file
    /// croft reads: the layer loader accepts comments and trailing commas,
    /// so a strict parse here threw away every setting in a file that
    /// merely had a comment, re-enabling disabled extensions among others.
    fn parse(json: &str) -> serde_json::Result<Self> {
        let value: serde_json::Value = serde_json::from_str(&crate::jsonc::strip_jsonc(json))?;
        let mut prefs: Self = serde_json::from_value(value.clone())?;
        if let serde_json::Value::Object(map) = value {
            prefs.source = SourceDoc(Some(map));
        }
        Ok(prefs)
    }

    /// The preferences a read-modify-write starts from: defaults only when
    /// the file does not exist. A file that exists but can't be read or
    /// parsed is an error, so saving one toggle never replaces the user's
    /// other settings with defaults.
    pub fn load_for_update(path: &Path) -> Result<Self> {
        match std::fs::read_to_string(path) {
            Ok(json) => Self::parse(&json).with_context(|| format!("parsing {}", path.display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
        }
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
        }
        let doc = self.document()?;
        // The file is edited in place, so its comments and layout survive a
        // setting changed from inside croft (#1129). Plain JSON only when
        // there is no file yet or it cannot be edited that way.
        let json = match std::fs::read_to_string(path)
            .ok()
            .and_then(|text| crate::jsonc_edit::update(&text, &doc))
        {
            Some(json) => json,
            None => serde_json::to_string_pretty(&doc).context("serializing prefs")?,
        };
        let before = crate::config_sync::stamp(path);
        // Written aside and renamed in: a reader on another thread (the MCP
        // worker's fingerprint check) must never see a truncated file, and a
        // crash mid-write must not leave one.
        let tmp = path.with_extension(format!(
            "json.{}.{:?}.tmp",
            std::process::id(),
            std::thread::current().id()
        ));
        write_keeping_mode(&tmp, path, json.as_bytes())
            .with_context(|| format!("writing {}", tmp.display()))?;
        std::fs::rename(&tmp, path).with_context(|| {
            let _ = std::fs::remove_file(&tmp);
            format!("replacing {}", path.display())
        })?;
        // croft's own write, already applied: the settings watch must not
        // re-merge it as if it came from outside (#1435).
        crate::config_sync::note_own_write(path, before);
        Ok(())
    }

    /// What [`Prefs::save`] writes: the loaded file with only the settings
    /// that changed since it was read replaced, so keys this struct does not
    /// model survive. A value is compared against the file's own typed view,
    /// so an untouched setting is left exactly as the user wrote it.
    ///
    /// With no file read, the file is an empty object, whose typed view is
    /// every default: the first save writes only the settings that differ
    /// from them (#1617). Writing them all pinned every default as a user
    /// setting, over an `extends` base and over any default a later release
    /// changes.
    fn document(&self) -> Result<serde_json::Value> {
        let current = serde_json::to_value(self).context("serializing prefs")?;
        let mut doc = self.source.0.clone().unwrap_or_default();
        let loaded: Self = serde_json::from_value(serde_json::Value::Object(doc.clone()))
            .context("re-reading prefs")?;
        let loaded = serde_json::to_value(&loaded).context("serializing prefs")?;
        merge_changed(&mut doc, &loaded, &current);
        Ok(serde_json::Value::Object(doc))
    }

    pub fn theme(&self) -> Theme {
        Theme::from_id(&self.theme)
    }

    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme.id().to_string();
    }
}

/// Persist `theme` to the config file, preserving any other settings already
/// stored. The caller says on the status line when it fails.
pub fn save_theme(theme: Theme) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.set_theme(theme);
    prefs.save(&path)
}

/// Persist the on-screen keyboard split choice, preserving other settings.
/// The caller says on the status line when it fails.
pub fn save_osk_split(split: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.osk_split = split;
    prefs.save(&path)
}

/// Persist the "don't warn about this terminal again" choice, preserving
/// other settings. The caller says on the status line when it fails.
pub fn save_suppress_terminal_warning(suppress: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.suppress_terminal_warning = suppress;
    prefs.save(&path)
}

/// Persist the Explorer sub-view visibility set, preserving other settings.
/// The caller says on the status line when it fails.
pub fn save_explorer_views(views: ExplorerViewsPrefs) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.explorer_views = views;
    prefs.save(&path)
}

/// Write `bytes` to `tmp`, created no more readable than `dest` already is
/// (0600 when `dest` is new): the file replaces `dest`, which may hold
/// notification headers, and must not widen to the umask's 0644.
pub(crate) fn write_keeping_mode(tmp: &Path, dest: &Path, bytes: &[u8]) -> std::io::Result<()> {
    use std::io::Write as _;
    // Created fresh, never opened through what is already there: the temp
    // names are predictable, and create+truncate followed a symlink planted
    // at one, writing the bytes wherever it pointed. `create_new` (O_EXCL)
    // refuses a symlink, and a stale file is removed first.
    let _ = std::fs::remove_file(tmp);
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    let mode = {
        use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
        let mode = std::fs::metadata(dest).map_or(0o600, |m| m.permissions().mode() & 0o777);
        opts.mode(mode);
        mode
    };
    let mut file = opts.open(tmp)?;
    // `mode` at creation is still narrowed by the umask: set it outright.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        file.set_permissions(std::fs::Permissions::from_mode(mode))?;
    }
    file.write_all(bytes)
}

/// Why [`replace_file_contents`] failed, and whether the file it was
/// replacing had been changed by then. Only a touched file needs its new
/// state recorded; an untouched one may still hold someone else's edit.
#[derive(Debug)]
pub(crate) struct ReplaceError {
    pub error: std::io::Error,
    pub touched: bool,
}

impl From<ReplaceError> for std::io::Error {
    fn from(e: ReplaceError) -> Self {
        e.error
    }
}

/// Replace the contents of the user's file at `path` with `bytes` so that
/// a write that fails partway (a full disk) leaves the old contents whole
/// (#1124).
///
/// The bytes go to a temp file beside it, which takes on the file's mode,
/// group and extended attributes (POSIX ACLs among them) and is then renamed
/// over it. A symlink is followed, so the link survives and its target is
/// replaced. A file that doesn't exist yet has nothing to lose and is written
/// directly, with the usual umask mode.
///
/// A rename would change more than the contents where the file is a hard
/// link (the other names keep the old text), belongs to someone else (the
/// new file would be ours), or has a group or attribute the temp file can't
/// be given; and it is impossible where the directory refuses the temp file.
/// Those are written in place, with the space for the new contents reserved
/// before the first byte changes.
///
/// So is a file with room for its new contents but not for a second copy of
/// them (#1614): on a nearly full disk, a one-character edit to a file bigger
/// than the free space could never be saved. That fallback is Linux only,
/// where the reservation is made, and only when the space is reserved, so
/// a write that doesn't fit still fails with the file whole.
pub(crate) fn replace_file_contents(path: &Path, bytes: &[u8]) -> Result<(), ReplaceError> {
    let untouched = |error| ReplaceError {
        error,
        touched: false,
    };
    let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let Ok(meta) = std::fs::metadata(&target) else {
        return std::fs::write(&target, bytes).map_err(|error| ReplaceError {
            error,
            touched: true,
        });
    };
    #[cfg(unix)]
    let in_place = {
        use std::os::unix::fs::MetadataExt;
        meta.nlink() > 1 || meta.uid() != unsafe { libc::geteuid() }
    };
    #[cfg(not(unix))]
    let in_place = false;
    if !in_place {
        match write_aside(&target, &meta, bytes) {
            Ok(tmp) => {
                return std::fs::rename(&tmp, &target).map_err(|e| {
                    let _ = std::fs::remove_file(&tmp);
                    untouched(e)
                });
            }
            #[cfg(target_os = "linux")]
            Err(Aside::Failed(e)) if is_out_of_space(&e) => {
                return write_in_place(&target, bytes, true).map_err(|r| {
                    // Nothing changed: the save failed for the reason the
                    // copy aside did, and that is what the user can act on.
                    if r.touched { r } else { untouched(e) }
                });
            }
            Err(Aside::Failed(e)) => return Err(untouched(e)),
            Err(Aside::InPlace) => {}
        }
    }
    write_in_place(&target, bytes, false)
}

/// `statfs` magic numbers of the filesystems that copy every overwritten
/// block, where reserving space does not make an overwrite safe: Btrfs, ZFS
/// and bcachefs.
#[cfg(target_os = "linux")]
const COPY_ON_WRITE_FS_MAGIC: [u32; 3] = [0x9123_683E, 0x2FC1_2FC1, 0xCA45_1A4E];

/// The disk or the user's quota is full.
#[cfg(target_os = "linux")]
fn is_out_of_space(e: &std::io::Error) -> bool {
    matches!(e.raw_os_error(), Some(libc::ENOSPC | libc::EDQUOT))
}

/// Why [`write_aside`] gave up: the write failed (a full disk), or the
/// file has to be written in place instead.
enum Aside {
    Failed(std::io::Error),
    InPlace,
}

/// Write `bytes` to a fresh temp file beside `target` that carries its mode,
/// group and extended attributes, ready to be renamed over it. The name is
/// short (a long file name would push it past the name limit) and never
/// taken over: an existing file at it is skipped, not removed or followed.
fn write_aside(target: &Path, meta: &std::fs::Metadata, bytes: &[u8]) -> Result<PathBuf, Aside> {
    use std::io::Write as _;
    use std::sync::atomic::{AtomicU64, Ordering};
    static SEQ: AtomicU64 = AtomicU64::new(0);
    let dir = target.parent().unwrap_or(Path::new("."));
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        opts.mode(0o600);
    }
    let (tmp, mut file) = 'open: {
        for _ in 0..16 {
            let nonce = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.subsec_nanos());
            let seq = SEQ.fetch_add(1, Ordering::Relaxed);
            let tmp = dir.join(format!(
                ".croft-save-{}-{seq}-{nonce:08x}",
                std::process::id()
            ));
            match opts.open(&tmp) {
                Ok(f) => break 'open (tmp, f),
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                    return Err(Aside::InPlace);
                }
                Err(e) => return Err(Aside::Failed(e)),
            }
        }
        return Err(Aside::InPlace);
    };
    let fail = |tmp: &Path, e| {
        let _ = std::fs::remove_file(tmp);
        Aside::Failed(e)
    };
    #[cfg(test)]
    if test_hooks::ASIDE_OUT_OF_SPACE.get() {
        return Err(fail(&tmp, std::io::Error::from_raw_os_error(libc::ENOSPC)));
    }
    if let Err(e) = file.write_all(bytes).and_then(|()| file.flush()) {
        return Err(fail(&tmp, e));
    }
    if let Err(e) = std::fs::set_permissions(&tmp, meta.permissions()) {
        return Err(fail(&tmp, e));
    }
    #[cfg(unix)]
    if !carry_owner_metadata(&file, target, meta) {
        let _ = std::fs::remove_file(&tmp);
        return Err(Aside::InPlace);
    }
    Ok(tmp)
}

/// Give the open temp file `file` the group and extended attributes of
/// `target`. False when one can't be carried over, so a rename would lose it.
#[cfg(unix)]
fn carry_owner_metadata(file: &std::fs::File, target: &Path, meta: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::MetadataExt as _;
    use std::os::unix::io::AsRawFd as _;
    let fd = file.as_raw_fd();
    let ours = file.metadata().map(|m| m.gid()).ok();
    if ours != Some(meta.gid()) && unsafe { libc::fchown(fd, u32::MAX, meta.gid()) } != 0 {
        return false;
    }
    copy_xattrs(fd, target)
}

/// Copy every extended attribute of `target` onto the open file `fd`.
#[cfg(target_os = "linux")]
fn copy_xattrs(fd: libc::c_int, target: &Path) -> bool {
    let Ok(c) = std::ffi::CString::new(target.as_os_str().as_encoded_bytes()) else {
        return false;
    };
    let len = unsafe { libc::listxattr(c.as_ptr(), std::ptr::null_mut(), 0) };
    if len < 0 {
        // A filesystem without xattrs has none to lose.
        return std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOTSUP);
    }
    let mut names = vec![0u8; len as usize];
    let len = unsafe { libc::listxattr(c.as_ptr(), names.as_mut_ptr().cast(), names.len()) };
    if len < 0 {
        return false;
    }
    names.truncate(len as usize);
    for name in names.split(|&b| b == 0).filter(|n| !n.is_empty()) {
        let Ok(name) = std::ffi::CString::new(name) else {
            return false;
        };
        let size = unsafe { libc::getxattr(c.as_ptr(), name.as_ptr(), std::ptr::null_mut(), 0) };
        if size < 0 {
            return false;
        }
        let mut value = vec![0u8; size as usize];
        let size = unsafe {
            libc::getxattr(
                c.as_ptr(),
                name.as_ptr(),
                value.as_mut_ptr().cast(),
                value.len(),
            )
        };
        if size < 0
            || unsafe {
                libc::fsetxattr(fd, name.as_ptr(), value.as_ptr().cast(), size as usize, 0)
            } != 0
        {
            return false;
        }
    }
    true
}

/// On macOS a file with any extended attribute is written in place rather
/// than renamed over and stripped of it.
#[cfg(target_os = "macos")]
fn copy_xattrs(_fd: libc::c_int, target: &Path) -> bool {
    let Ok(c) = std::ffi::CString::new(target.as_os_str().as_encoded_bytes()) else {
        return false;
    };
    unsafe { libc::listxattr(c.as_ptr(), std::ptr::null_mut(), 0, 0) == 0 }
}

/// Elsewhere there is no portable way to list them.
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn copy_xattrs(_fd: libc::c_int, _target: &Path) -> bool {
    true
}

/// Overwrite `target` with `bytes` without truncating it first. On Linux
/// the space a longer file needs is reserved before the first byte changes,
/// so running out of it fails with the file untouched. With `must_reserve`,
/// the whole output is reserved even when it is not longer (a sparse or
/// copy-on-write file can need new blocks to overwrite), and a filesystem
/// that can't reserve space fails the write too, untouched, instead of
/// writing on unguarded.
fn write_in_place(target: &Path, bytes: &[u8], must_reserve: bool) -> Result<(), ReplaceError> {
    use std::io::{Seek as _, Write as _};
    #[cfg(not(target_os = "linux"))]
    let _ = must_reserve;
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .open(target)
        .map_err(|error| ReplaceError {
            error,
            touched: false,
        })?;
    let new_len = bytes.len() as u64;
    // The reservation is Linux-only, and so is everything it reads: built
    // anywhere else these were unused, and the release build warned (#1463).
    #[cfg(target_os = "linux")]
    let before = file.metadata().ok();
    #[cfg(target_os = "linux")]
    let old_len = before.as_ref().map_or(0, |m| m.len());
    // Reserving space does not hold on a filesystem that writes every
    // overwritten block somewhere new (Btrfs, ZFS, bcachefs): an overwrite
    // can still run out halfway through the old contents, so the mandatory
    // fallback refuses there, untouched. XFS shares reflinked extents the
    // same way but can unshare them up front, which leaves nothing to copy
    // on write.
    #[cfg(target_os = "linux")]
    if must_reserve {
        use std::os::unix::io::AsRawFd as _;
        let fd = file.as_raw_fd();
        let refuse = |err: i32| ReplaceError {
            error: std::io::Error::from_raw_os_error(err),
            touched: false,
        };
        let mut st: libc::statfs = unsafe { std::mem::zeroed() };
        if unsafe { libc::fstatfs(fd, &mut st) } != 0 {
            return Err(refuse(libc::EOPNOTSUPP));
        }
        if COPY_ON_WRITE_FS_MAGIC.contains(&(st.f_type as u32)) {
            return Err(refuse(libc::EOPNOTSUPP));
        }
        if old_len > 0 {
            let err = unsafe {
                libc::fallocate(fd, libc::FALLOC_FL_UNSHARE_RANGE, 0, old_len as libc::off_t)
            };
            let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
            if err != 0 && errno != libc::EOPNOTSUPP && errno != libc::EINVAL {
                return Err(refuse(errno));
            }
        }
    }
    // A mandatory reservation covers the whole output even when it is no
    // longer than the file: overwriting a sparse file's holes, or any block
    // on a copy-on-write filesystem, can still need new blocks and fail
    // halfway through the old contents.
    #[cfg(target_os = "linux")]
    if new_len > old_len || (must_reserve && new_len > 0) {
        use std::os::unix::io::AsRawFd as _;
        let err = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, new_len as libc::off_t) };
        let unsupported = err == libc::EOPNOTSUPP || err == libc::EINVAL;
        if unsupported && must_reserve {
            return Err(ReplaceError {
                error: std::io::Error::from_raw_os_error(err),
                touched: false,
            });
        }
        if err != 0 && !unsupported {
            // A reservation that failed partway may have grown the file: cut
            // it back. The contents are as they were, but the attempt can
            // still have moved the file's timestamp (ext4 marks it modified
            // before checking the size), which is then croft's own doing.
            let after = file.metadata().ok();
            if after.as_ref().is_some_and(|m| m.len() != old_len) {
                let _ = file.set_len(old_len);
            }
            let stamp = |m: &std::fs::Metadata| (m.modified().ok(), m.len());
            let touched = before.as_ref().map(stamp) != file.metadata().ok().as_ref().map(stamp);
            return Err(ReplaceError {
                error: std::io::Error::from_raw_os_error(err),
                touched,
            });
        }
    }
    file.seek(std::io::SeekFrom::Start(0))
        .and_then(|_| file.write_all(bytes))
        .and_then(|()| file.set_len(new_len))
        .and_then(|()| file.flush())
        .map_err(|error| ReplaceError {
            error,
            touched: true,
        })
}

/// Faults a test can inject into the save path.
#[cfg(test)]
pub(crate) mod test_hooks {
    thread_local! {
        /// Fail the copy aside the way a full disk does (#1614).
        pub(crate) static ASIDE_OUT_OF_SPACE: std::cell::Cell<bool> =
            const { std::cell::Cell::new(false) };
    }
}

/// The settings file under `config_dir`. The real config dir means the
/// active profile's file (#618), which is what startup reads; saving
/// consent or disabled extensions to the base file instead let a revoked
/// consent survive a restart under a profile.
fn prefs_file_in(config_dir: &Path) -> PathBuf {
    if config_dir == crate::paths::config_dir() {
        config_path()
    } else {
        config_dir.join("config.json")
    }
}

/// Persist the set of disabled extension ids, preserving other settings.
/// The caller says on the status line when it fails.
pub fn save_disabled_extensions_in(config_dir: &Path, disabled: &BTreeSet<String>) -> Result<()> {
    let path = prefs_file_in(config_dir);
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disabled_extensions = disabled.clone();
    prefs.save(&path)
}

/// Record that the tour was finished or skipped (#377), under an explicit
/// config dir so a test can point it at a scratch dir.
pub fn save_tour_done_in(config_dir: &Path) -> Result<()> {
    let path = config_dir.join("config.json");
    // A config.json croft cannot read is left alone, not replaced by
    // defaults with only this flag set.
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.tour_done = true;
    prefs.save(&path)
}

/// Record a first-run consent for `ext_id` under an explicit config dir: the app carries the
/// dir it was built with, so a test can point it at a scratch dir instead
/// of mutating the process-wide environment (which races sibling tests).
pub fn save_mcp_consent_in(config_dir: &Path, ext_id: &str) -> Result<()> {
    let path = prefs_file_in(config_dir);
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.mcp_consented.insert(ext_id.to_string());
    prefs.save(&path)
}

/// Forget a recorded first-run consent under an explicit config dir; see
/// [`save_mcp_consent_in`] for why the dir is a parameter.
pub fn forget_mcp_consent_in(config_dir: &Path, ext_id: &str) -> Result<()> {
    let path = prefs_file_in(config_dir);
    let mut prefs = Prefs::load_for_update(&path)?;
    if !prefs.mcp_consented.remove(ext_id) {
        return Ok(());
    }
    prefs.save(&path)
}

/// Trust-on-first-use check of the tool a command calls, under an explicit
/// config dir (see [`save_mcp_consent_in`] for why the dir is a parameter).
/// The first fingerprint seen for `command_id` is recorded, preserving other
/// settings (best-effort: a write failure is swallowed); false when a
/// different one was recorded before, meaning the tool definition changed.
pub fn trust_mcp_tool_in(config_dir: &Path, command_id: &str, fingerprint: &str) -> bool {
    let path = prefs_file_in(config_dir);
    // An unreadable config can't vouch for a fingerprint, and saving over
    // it would lose every other setting: refuse the call instead.
    let Ok(mut prefs) = Prefs::load_for_update(&path) else {
        return false;
    };
    match prefs.mcp_tool_fingerprints.get(command_id) {
        Some(prev) => prev == fingerprint,
        None => {
            prefs
                .mcp_tool_fingerprints
                .insert(command_id.to_string(), fingerprint.to_string());
            let _ = prefs.save(&path);
            true
        }
    }
}

/// Forget the recorded tool fingerprints of `command_ids`, so each tool is
/// trusted afresh on its next run; see [`trust_mcp_tool_in`].
pub fn forget_mcp_tool_fingerprints_in(config_dir: &Path, command_ids: &[String]) -> Result<()> {
    let path = prefs_file_in(config_dir);
    let mut prefs = Prefs::load_for_update(&path)?;
    let before = prefs.mcp_tool_fingerprints.len();
    prefs
        .mcp_tool_fingerprints
        .retain(|id, _| !command_ids.contains(id));
    if prefs.mcp_tool_fingerprints.len() == before {
        return Ok(());
    }
    prefs.save(&path)
}

/// Persist the Customize Layout chrome choices, preserving other settings.
/// The caller says on the status line when it fails.
pub fn save_layout(layout: LayoutPrefs) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.layout = layout;
    prefs.save(&path)
}

/// Persist the auto-close-pairs choice, preserving other settings. Stored
/// negated (`disable_auto_close_pairs`) so an absent key means enabled.
/// The caller says on the status line when it fails.
pub fn save_auto_close_pairs(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_auto_close_pairs = !enabled;
    prefs.save(&path)
}

/// Persist the screen reader choice, preserving other settings.
pub fn save_screen_reader(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.screen_reader = enabled;
    prefs.save(&path)
}

/// Persist the format-on-type choice, preserving other settings.
/// The caller says on the status line when it fails.
pub fn save_format_on_type(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.format_on_type = enabled;
    prefs.save(&path)
}

/// Persist the format-on-save choice, preserving other settings. The caller
/// says on the status line when it fails.
pub fn save_format_on_save(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.format_on_save = enabled;
    prefs.save(&path)
}

/// Persist the secret-redaction toggle (#360), preserving other settings.
pub fn save_disable_secret_redaction(disabled: bool) -> Result<()> {
    set_disable_secret_redaction(&config_path(), disabled)
}

/// [`save_disable_secret_redaction`] against an explicit path. Goes through
/// [`prefs_for_update`] so a malformed config is refused, not replaced.
fn set_disable_secret_redaction(path: &Path, disabled: bool) -> Result<()> {
    let mut prefs = prefs_for_update(path)?;
    prefs.disable_secret_redaction = disabled;
    prefs.save(path)
}

/// Persist the log-highlight toggle (#466) as its disable flag. Goes through
/// [`prefs_for_update`] so a malformed config is refused, not replaced.
pub fn save_disable_log_highlight(disabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = prefs_for_update(&path)?;
    prefs.disable_log_highlight = disabled;
    prefs.save(&path)
}

pub fn save_copy_on_select(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.copy_on_select = enabled;
    prefs.save(&path)
}

/// The scrollback size terminal panes spawn with: the user's
/// `terminal_scrollback` when set, clamped to a sane range, else the
/// built-in default.
pub fn terminal_scrollback_lines(configured: usize, default: usize) -> usize {
    if configured == 0 {
        default
    } else {
        configured.clamp(100, 200_000)
    }
}

/// Persist the auto-save choice, preserving other settings. The caller
/// says on the status line when it fails.
pub fn save_auto_save(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.auto_save = enabled;
    prefs.save(&path)
}

/// Persist the on-focus-change auto-save choice, preserving other
/// settings. Best-effort, like [`save_auto_save`].
pub fn save_auto_save_on_focus_change(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.auto_save_on_focus_change = enabled;
    prefs.save(&path)
}

/// Persist the auto-hide side bar choice (#260), preserving other settings.
/// Best-effort, like [`save_auto_save`].
pub fn save_sidebar_auto_hide(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = prefs_for_update(&path)?;
    prefs.sidebar_auto_hide = enabled;
    prefs.save(&path)
}

/// The prefs to mutate in a `save_*` helper: the file's contents, or defaults
/// only when the file is genuinely ABSENT.
///
/// `Prefs::load` cannot tell "no config yet" from "config is malformed" —
/// both are `Err` — so `unwrap_or_default()` on a corrupt file would write
/// defaults over it and erase every unrelated setting the user had. A first
/// run must still work, so absence maps to defaults; anything else refuses,
/// leaving the file for the user to fix.
fn prefs_for_update(path: &Path) -> Result<Prefs> {
    match Prefs::load(path) {
        Ok(p) => Ok(p),
        // Branch on the error itself rather than a follow-up `path.exists()`:
        // a dangling symlink at the config path reports "does not exist" while
        // the open failed for a different reason, and defaults written through
        // it would clobber whatever it points at. `load` wraps the io error in
        // context, so the cause is in the chain rather than the top error.
        Err(e) => {
            let missing = e
                .chain()
                .filter_map(|c| c.downcast_ref::<std::io::Error>())
                .any(|io| io.kind() == std::io::ErrorKind::NotFound);
            if missing {
                return Ok(Prefs::default());
            }
            Err(e)
        }
    }
}

/// Persist whether the whole-project check may auto-run (#256).
/// Best-effort, like [`save_problems_scope`].
pub fn save_problems_project_scope(mode: &str) -> Result<()> {
    let path = config_path();
    let mut prefs = prefs_for_update(&path)?;
    prefs.problems_project_scope = mode.to_string();
    prefs.save(&path)
}

/// Persist the PROBLEMS scope (#256), preserving other settings.
/// Best-effort, like [`save_auto_save`].
pub fn save_problems_scope(mode: &str) -> Result<()> {
    let path = config_path();
    let mut prefs = prefs_for_update(&path)?;
    prefs.problems_scope = mode.to_string();
    prefs.save(&path)
}

pub fn save_inline_blame(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_inline_blame = !enabled;
    prefs.save(&path)
}

/// Persist the debugger inline-values toggle (stored as its disable flag).
pub fn save_inline_values(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_inline_values = !enabled;
    prefs.save(&path)
}

/// Persist Vim mode as the mode croft starts in (#1286), under an explicit
/// config dir so a test can point it at a scratch dir.
pub fn save_vim_mode_in(config_dir: &Path, enabled: bool) -> Result<()> {
    let path = prefs_file_in(config_dir);
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.vim_mode = enabled;
    prefs.save(&path)
}

/// Persist the whitespace rendering mode ("selection" / "all" / "none").
pub fn save_render_whitespace(mode: &str) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.render_whitespace = mode.to_string();
    prefs.save(&path)
}

/// Persist the gutter's line number mode (#1576).
pub fn save_line_numbers(mode: &str) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.line_numbers = mode.to_string();
    prefs.save(&path)
}

/// Persist the bracket-pair colorization toggle (stored as its disable flag).
pub fn save_bracket_colors(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_bracket_colors = !enabled;
    prefs.save(&path)
}

/// Persist the indentation-guides toggle (stored as its disable flag).
pub fn save_indent_guides(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_indent_guides = !enabled;
    prefs.save(&path)
}

pub fn save_inlay_hints(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_inlay_hints = !enabled;
    prefs.save(&path)
}

pub fn save_proactive_navigator(enabled: bool) -> Result<()> {
    let path = config_path();
    let mut prefs = Prefs::load_for_update(&path)?;
    prefs.disable_proactive_navigator = !enabled;
    prefs.save(&path)
}

pub fn config_path() -> PathBuf {
    // Through the active profile (#618); the config dir when there is none.
    crate::profiles::file("config.json")
}

#[cfg(test)]
mod tests {

    #[test]
    fn finishing_the_tour_leaves_an_unreadable_config_alone() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        let broken = "{ \"theme\": \"dark\", oops }";
        std::fs::write(&path, broken).unwrap();
        assert!(save_tour_done_in(dir.path()).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), broken);
        // With no file yet, it is created with the flag set.
        let fresh = tempfile::tempdir().unwrap();
        save_tour_done_in(fresh.path()).unwrap();
        assert!(
            Prefs::load(&fresh.path().join("config.json"))
                .unwrap()
                .tour_done
        );
    }
    use super::*;

    /// The keys of the `config.json` in `dir`.
    fn saved_keys(dir: &Path) -> Vec<String> {
        let doc: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.join("config.json")).unwrap())
                .unwrap();
        let mut keys: Vec<String> = doc.as_object().unwrap().keys().cloned().collect();
        keys.sort();
        keys
    }

    /// #1617: the first save on a fresh install writes the one setting that
    /// changed, not every default.
    #[test]
    fn the_first_save_writes_only_the_setting_that_changed() {
        let dir = tempfile::tempdir().unwrap();
        save_tour_done_in(dir.path()).unwrap();
        assert_eq!(saved_keys(dir.path()), vec!["tour_done"]);
        let other = tempfile::tempdir().unwrap();
        let mut prefs = Prefs::load_for_update(&other.path().join("config.json")).unwrap();
        prefs.vim_mode = true;
        prefs.suppress_terminal_warning = true;
        prefs.save(&other.path().join("config.json")).unwrap();
        assert_eq!(
            saved_keys(other.path()),
            vec!["suppress_terminal_warning", "vim_mode"]
        );
        let loaded = Prefs::load(&other.path().join("config.json")).unwrap();
        assert!(loaded.vim_mode && loaded.suppress_terminal_warning);
        assert_eq!(
            loaded,
            Prefs {
                vim_mode: true,
                suppress_terminal_warning: true,
                ..Prefs::default()
            },
            "every other setting reads back as its default"
        );
    }

    /// #1617: the first save of a nested setting writes only that field of
    /// it, so its siblings keep following the defaults.
    #[test]
    fn the_first_save_of_a_nested_setting_writes_only_its_changed_field() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        let mut prefs = Prefs::load_for_update(&path).unwrap();
        prefs.layout.status_bar = !prefs.layout.status_bar;
        prefs.save(&path).unwrap();
        let doc: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        let layout: Vec<&String> = doc["layout"].as_object().unwrap().keys().collect();
        assert_eq!(layout, vec!["status_bar"], "{doc}");
        assert_eq!(Prefs::load(&path).unwrap(), prefs);
    }

    /// #1617: an `extends` base added after the first save is not overridden
    /// by defaults that save pinned.
    #[test]
    fn an_extends_base_still_applies_after_the_first_save() {
        let dir = tempfile::tempdir().unwrap();
        save_tour_done_in(dir.path()).unwrap();
        let base = dir.path().join("base.json");
        std::fs::write(&base, r#"{ "vim_mode": true }"#).unwrap();
        let path = dir.path().join("config.json");
        let mut doc: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        doc["extends"] = serde_json::Value::String(base.display().to_string());
        std::fs::write(&path, doc.to_string()).unwrap();
        let merged = crate::config_layers::load_merged_from(dir.path(), None, "linux");
        assert!(merged.prefs.vim_mode, "{:?}", merged.warnings);
        assert!(merged.prefs.tour_done);
        assert_eq!(
            crate::config_layers::layer_of(&merged.provenance, "format_on_save"),
            crate::config_layers::LayerKind::Default,
            "a setting nobody set is not a user setting"
        );
    }

    /// #1617 negative: in a file that already exists, a key the user wrote
    /// stays even when it holds the default, and the one that changed is
    /// written.
    #[test]
    fn an_existing_file_keeps_its_keys_when_another_setting_saves() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(&path, r#"{"vim_mode": false, "theme": "dark"}"#).unwrap();
        save_tour_done_in(dir.path()).unwrap();
        assert_eq!(
            saved_keys(dir.path()),
            vec!["theme", "tour_done", "vim_mode"]
        );
        let doc: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(doc["vim_mode"], false);
        assert_eq!(doc["theme"], "dark");
    }

    #[test]
    fn saving_keeps_unknown_keys_nested_in_a_changed_object_and_drops_removed_entries() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(
            &path,
            r#"{"explorer_views": {"open_editors": false, "future_view": true},
                "mcp_tool_fingerprints": {"a": "1", "b": "2"}}"#,
        )
        .unwrap();
        let mut prefs = Prefs::load(&path).unwrap();
        prefs.explorer_views.open_editors = true;
        prefs.mcp_tool_fingerprints.remove("a");
        prefs.save(&path).unwrap();
        let doc: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(doc["explorer_views"]["open_editors"], true);
        assert_eq!(doc["explorer_views"]["future_view"], true);
        assert!(doc["mcp_tool_fingerprints"].get("a").is_none(), "{doc}");
        assert_eq!(doc["mcp_tool_fingerprints"]["b"], "2");
    }

    #[test]
    fn saving_one_setting_keeps_keys_prefs_does_not_model_and_accepts_jsonc() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(
            &path,
            r#"{
  // shared base
  "extends": "base.json",
  "macos": {"theme": "light"},
  "future_setting": 7,
  "theme": "dark",
  "osk_split": true,
}"#,
        )
        .unwrap();
        // A comment and trailing comma no longer reset everything.
        assert!(Prefs::load(&path).unwrap().osk_split);
        save_mcp_consent_in(dir.path(), "ext").unwrap();
        set_disable_secret_redaction(&path, true).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        // The comment survives the saves (#1129).
        assert!(text.contains("// shared base"), "{text}");
        let doc: serde_json::Value =
            serde_json::from_str(&crate::jsonc::strip_jsonc(&text)).unwrap();
        assert_eq!(doc["extends"], "base.json");
        assert_eq!(doc["macos"]["theme"], "light");
        assert_eq!(doc["future_setting"], 7);
        assert_eq!(doc["theme"], "dark");
        assert_eq!(doc["osk_split"], true);
        assert_eq!(doc["disable_secret_redaction"], true);
        let prefs = Prefs::load(&path).unwrap();
        assert!(prefs.mcp_consented.contains("ext"));
        assert!(prefs.disable_secret_redaction);
    }

    /// #1129: a setting changed from inside croft (File: Toggle Auto Save
    /// here) keeps the file's comments, key order and trailing commas; it
    /// used to come back as plain sorted JSON with every comment gone.
    #[test]
    fn a_setting_saved_from_croft_keeps_the_files_comments() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        let text = r#"{
  // Team defaults live in dotfiles; keep this file small.
  "theme": "dark",
  /* Format on save is OFF on purpose: prettier fights ruff here.
     See INFRA-2231 before turning it back on. */
  "format_on_save": false,
  "linux": {
    "theme": "nord", // matches the tmux theme on the build boxes
  },
}
"#;
        std::fs::write(&path, text).unwrap();
        let mut prefs = Prefs::load_for_update(&path).unwrap();
        prefs.auto_save = true;
        prefs.save(&path).unwrap();
        let saved = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            saved,
            text.replace("  },\n}", "  },\n  \"auto_save\": true,\n}"),
            "{saved}"
        );
        assert!(Prefs::load(&path).unwrap().auto_save);
    }

    /// #1129 negative: with no file yet, or one that does not parse as a
    /// settings object, the save still writes plain JSON.
    #[test]
    fn a_missing_or_unreadable_file_is_still_written_whole() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        let mut prefs = Prefs::load_for_update(&path).unwrap();
        prefs.auto_save = true;
        prefs.save(&path).unwrap();
        let doc: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(doc["auto_save"], true);
        assert!(crate::jsonc_edit::update("[]", &doc).is_none());
    }

    #[test]
    fn saving_prefs_replaces_the_file_and_leaves_no_temp_behind() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(&path, "{}").unwrap();
        save_mcp_consent_in(dir.path(), "ext").unwrap();
        assert!(
            Prefs::load_for_update(&path)
                .unwrap()
                .mcp_consented
                .contains("ext")
        );
        let names: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .flatten()
            .map(|e| e.file_name())
            .collect();
        assert_eq!(names, vec![std::ffi::OsString::from("config.json")]);
        assert_eq!(prefs_file_in(dir.path()), path);
    }

    #[cfg(unix)]
    #[test]
    fn saving_prefs_keeps_a_private_config_private() {
        use std::os::unix::fs::PermissionsExt as _;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(&path, "{}").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        save_mcp_consent_in(dir.path(), "ext").unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    /// #624: a test build reads no saved `config.json`, so the MCP
    /// consents, the terminal warning and the extension toggles that
    /// `load_or_default` feeds are the defaults on every machine.
    #[test]
    fn a_test_build_reads_no_saved_prefs() {
        assert_eq!(saved_prefs_path(), None);
        assert_eq!(Prefs::load_or_default(), Prefs::default());
    }

    #[test]
    fn an_mcp_tool_is_trusted_on_first_use_and_refused_once_it_changes() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        save_mcp_consent_in(dir, "ext").unwrap();
        assert!(trust_mcp_tool_in(dir, "ext.cmd", "fp1"));
        assert!(trust_mcp_tool_in(dir, "ext.cmd", "fp1"));
        assert!(!trust_mcp_tool_in(dir, "ext.cmd", "fp2"));
        let saved = Prefs::load(&dir.join("config.json")).unwrap();
        assert_eq!(
            saved
                .mcp_tool_fingerprints
                .get("ext.cmd")
                .map(String::as_str),
            Some("fp1")
        );
        assert!(
            saved.mcp_consented.contains("ext"),
            "other settings survive"
        );
    }

    /// Forgetting a command's fingerprint re-approves its tool: the next
    /// fingerprint seen is trusted, and other commands keep theirs.
    #[test]
    fn a_forgotten_fingerprint_is_trusted_afresh() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        assert!(trust_mcp_tool_in(dir, "ext.cmd", "fp1"));
        assert!(trust_mcp_tool_in(dir, "other.cmd", "o1"));
        forget_mcp_tool_fingerprints_in(dir, &[String::from("ext.cmd")]).unwrap();
        assert!(trust_mcp_tool_in(dir, "ext.cmd", "fp2"));
        assert!(!trust_mcp_tool_in(dir, "other.cmd", "o2"));
    }

    #[test]
    fn round_trips_theme_through_disk() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let mut prefs = Prefs::default();
        prefs.set_theme(Theme::BLACK);
        prefs.save(&path).expect("save");
        let loaded = Prefs::load(&path).expect("load");
        assert_eq!(loaded.theme(), Theme::BLACK);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_osk_split_and_old_configs_default_to_merged() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-osk-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            osk_split: true,
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        assert!(Prefs::load(&path).expect("load").osk_split);
        // A pre-split config (theme only) still parses, defaulting to merged.
        std::fs::write(&path, r#"{"theme":"black"}"#).expect("write old config");
        assert!(!Prefs::load(&path).expect("load old").osk_split);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_suppress_terminal_warning_and_old_configs_default_off() {
        let dir =
            std::env::temp_dir().join(format!("croft-prefs-warn-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            suppress_terminal_warning: true,
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        assert!(Prefs::load(&path).expect("load").suppress_terminal_warning);
        // A config written before this field existed still parses, defaulting
        // the nudge to enabled (false = not suppressed).
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        assert!(
            !Prefs::load(&path)
                .expect("load old")
                .suppress_terminal_warning
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_explorer_views_and_old_configs_default_to_vscode_defaults() {
        let dir =
            std::env::temp_dir().join(format!("croft-prefs-views-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            explorer_views: ExplorerViewsPrefs {
                open_editors: true,
                timeline: false,
                ..ExplorerViewsPrefs::default()
            },
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        let loaded = Prefs::load(&path).expect("load").explorer_views;
        assert!(loaded.open_editors);
        assert!(!loaded.timeline);
        assert!(loaded.folders);
        // A config written before the field existed parses to the VS Code
        // defaults: Open Editors hidden, every other view shown.
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        let old = Prefs::load(&path).expect("load old").explorer_views;
        assert_eq!(old, ExplorerViewsPrefs::default());
        assert!(!old.open_editors);
        assert!(old.folders && old.outline && old.timeline && old.dependencies);
        // A config written under the pre-generalization `rust_dependencies` key
        // still drives the renamed `dependencies` field via the serde alias.
        std::fs::write(&path, r#"{"explorer_views":{"rust_dependencies":false}}"#)
            .expect("write legacy config");
        let legacy = Prefs::load(&path).expect("load legacy").explorer_views;
        assert!(!legacy.dependencies, "old rust_dependencies key aliases in");
        // Turning the view back on writes the new key and drops the old one:
        // both in one object is a duplicate field, and the load after that
        // would fall back to defaults.
        let mut prefs = Prefs::load(&path).expect("load legacy");
        prefs.explorer_views.dependencies = true;
        prefs.explorer_views.timeline = false;
        prefs.save(&path).expect("save over legacy");
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(!text.contains("rust_dependencies"), "{text}");
        let reloaded = Prefs::load(&path).expect("reload").explorer_views;
        assert!(reloaded.dependencies && !reloaded.timeline, "{text}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_layout_and_old_configs_default_to_full_chrome() {
        let dir =
            std::env::temp_dir().join(format!("croft-prefs-layout-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            layout: LayoutPrefs {
                activity_bar: false,
                status_bar: false,
                minimap: false,
                side_bar_position: SideBarPosition::Right,
                secondary_side_bar: true,
                panel_alignment: PanelAlignment::Justify,
                quick_input_position: QuickInputPosition::Center,
                centered_layout: true,
                zen_center_layout: false,
                centered_layout_width: 100,
            },
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        let loaded = Prefs::load(&path).expect("load").layout;
        assert_eq!(loaded, prefs.layout);
        // A config written before this block existed parses to full chrome:
        // activity bar + status bar shown, side bar left, no secondary bar,
        // panel centered, quick input on top.
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        let old = Prefs::load(&path).expect("load old").layout;
        assert_eq!(old, LayoutPrefs::default());
        assert!(old.activity_bar && old.status_bar);
        assert!(old.minimap, "an older config keeps the minimap on");
        assert_eq!(old.side_bar_position, SideBarPosition::Left);
        assert!(!old.secondary_side_bar);
        assert_eq!(old.panel_alignment, PanelAlignment::Center);
        assert_eq!(old.quick_input_position, QuickInputPosition::Top);
        // #1585: no centred layout outside Zen, a centred Zen, 120 columns.
        assert!(!old.centered_layout && old.zen_center_layout);
        assert_eq!(old.centered_layout_width, 120);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// #1440: a language block reads its known keys and ignores the rest,
    /// and a config with no blocks writes no `languages` key.
    #[test]
    fn language_blocks_read_their_known_keys_only() {
        let p: Prefs = serde_json::from_str(
            r#"{"languages":{"c":{"format_on_save":true,"theme":"light","font_size":3}}}"#,
        )
        .unwrap();
        assert_eq!(
            p.languages.get("c"),
            Some(&LanguagePrefs {
                format_on_save: Some(true),
                ..LanguagePrefs::default()
            })
        );
        let out = serde_json::to_string(&Prefs::default()).unwrap();
        assert!(!out.contains("languages"), "{out}");
    }

    #[test]
    fn round_trips_format_on_save_and_old_configs_default_off() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-fos-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            format_on_save: true,
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        assert!(Prefs::load(&path).expect("load").format_on_save);
        // A config written before this field existed still parses, defaulting
        // format-on-save to off (matching VS Code's `editor.formatOnSave`).
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        assert!(!Prefs::load(&path).expect("load old").format_on_save);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_format_on_type_and_old_configs_default_off() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.json");
        let mut prefs = Prefs::default();
        assert!(!prefs.format_on_type, "off by default, matching VS Code");
        prefs.format_on_type = true;
        prefs.save(&path).expect("save");
        assert!(Prefs::load(&path).expect("load").format_on_type);
        std::fs::write(&path, "{}").expect("write old config");
        assert!(!Prefs::load(&path).expect("load old").format_on_type);
    }

    #[test]
    fn round_trips_inlay_hints_and_old_configs_default_on() {
        let dir =
            std::env::temp_dir().join(format!("croft-prefs-inlay-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            disable_inlay_hints: true,
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        assert!(Prefs::load(&path).expect("load").disable_inlay_hints);
        // A config written before this field existed still parses; hints
        // default ON (matching VS Code's `editor.inlayHints.enabled`).
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        assert!(!Prefs::load(&path).expect("load old").disable_inlay_hints);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_auto_save_and_old_configs_default_off() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-as-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            auto_save: true,
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        assert!(Prefs::load(&path).expect("load").auto_save);
        // A config written before this field existed still parses, defaulting
        // auto-save to off (matching VS Code's `files.autoSave`).
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        assert!(!Prefs::load(&path).expect("load old").auto_save);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn round_trips_copy_on_select_and_terminal_scrollback() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-cos-test-{}", std::process::id()));
        let path = dir.join("config.json");
        let prefs = Prefs {
            copy_on_select: true,
            terminal_scrollback: 20_000,
            ..Prefs::default()
        };
        prefs.save(&path).expect("save");
        let loaded = Prefs::load(&path).expect("load");
        assert!(loaded.copy_on_select);
        assert_eq!(loaded.terminal_scrollback, 20_000);
        // A config written before these fields existed still parses: copy on
        // selection off (VS Code's default) and the built-in scrollback.
        std::fs::write(&path, r#"{"theme":"dark"}"#).expect("write old config");
        let old = Prefs::load(&path).expect("load old");
        assert!(!old.copy_on_select);
        assert_eq!(old.terminal_scrollback, 0);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn terminal_scrollback_lines_defaults_and_clamps() {
        assert_eq!(terminal_scrollback_lines(0, 5000), 5000, "0 = unset");
        assert_eq!(terminal_scrollback_lines(20_000, 5000), 20_000);
        assert_eq!(terminal_scrollback_lines(5, 5000), 100, "floor");
        assert_eq!(terminal_scrollback_lines(9_999_999, 5000), 200_000, "cap");
    }

    #[test]
    fn missing_file_yields_default_theme() {
        let path = std::env::temp_dir().join("croft-prefs-absent-xyz/config.json");
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
        assert_eq!(
            Prefs::load(&path).unwrap_or_default().theme(),
            Theme::default()
        );
    }

    #[test]
    fn config_path_lives_under_config_croft() {
        // With XDG unset the path falls under ~/.config/croft; with it set it
        // honors the override. Exercise the default branch via a cleared env.
        let p = config_path();
        assert!(p.to_string_lossy().contains("croft"));
        assert_eq!(p.file_name().unwrap(), "config.json");
    }

    /// #294 review: a `save_*` helper must not overwrite a MALFORMED config
    /// with defaults — that silently erases every unrelated setting the user
    /// had. `Prefs::load` returns `Err` for both "absent" and "corrupt", so
    /// the distinction has to be made explicitly.
    #[test]
    fn an_update_refuses_a_corrupt_config_but_defaults_when_absent() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-update-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.json");

        // Absent: a first run must still work.
        let _ = std::fs::remove_file(&path);
        assert!(
            prefs_for_update(&path).is_ok(),
            "no config yet is not an error"
        );

        // Present but corrupt: refuse rather than clobber.
        std::fs::write(&path, "{ this is not json").unwrap();
        assert!(
            prefs_for_update(&path).is_err(),
            "a malformed config must not be replaced by defaults"
        );
        // The file is left exactly as the user wrote it.
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{ this is not json"
        );

        // Present and valid: the real contents come back.
        let p = Prefs {
            theme: String::from("some-theme"),
            ..Default::default()
        };
        p.save(&path).unwrap();
        assert_eq!(prefs_for_update(&path).unwrap().theme, "some-theme");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// #360: toggling redaction on a malformed config refuses and leaves
    /// the file byte-for-byte; on a valid one it keeps the other settings.
    #[test]
    fn the_redaction_toggle_never_clobbers_a_corrupt_config() {
        let dir = std::env::temp_dir().join(format!("croft-prefs-redact-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.json");

        std::fs::write(&path, "{ this is not json").unwrap();
        assert!(
            set_disable_secret_redaction(&path, true).is_err(),
            "a malformed config is refused, not overwritten with defaults"
        );
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{ this is not json"
        );

        let p = Prefs {
            theme: String::from("some-theme"),
            ..Default::default()
        };
        p.save(&path).unwrap();
        set_disable_secret_redaction(&path, true).unwrap();
        let back = Prefs::load(&path).unwrap();
        assert!(back.disable_secret_redaction);
        assert_eq!(
            back.theme, "some-theme",
            "unrelated settings survive the toggle"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn saving_one_setting_never_replaces_an_unreadable_config() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.json");
        std::fs::write(&path, "{ \"theme\": ").unwrap();
        assert!(Prefs::load_for_update(&path).is_err());
        assert!(
            Prefs::load_for_update(&tmp.path().join("absent.json")).is_ok(),
            "a missing file starts from defaults"
        );
        std::fs::write(&path, "{\n  // a comment\n  \"format_on_save\": true,\n}").unwrap();
        assert!(
            Prefs::load_for_update(&path).unwrap().format_on_save,
            "JSONC reads"
        );
    }
}