arf-console 0.5.1

A cross-platform R console 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
//! Configuration management following XDG Base Directory specification.

mod colors;
mod completion;
mod editor;
mod experimental;
mod history;
mod ipc;
pub(crate) mod prompt;
mod r;
mod reprex;
mod startup;

pub use colors::{ColorsConfig, MetaColorConfig, RColorConfig, StatusColorConfig, ViColorConfig};
pub use completion::CompletionConfig;
pub use editor::{AutoSuggestions, EditorConfig, EditorMode};
pub use experimental::{
    ExperimentalConfig, HistoryForgetConfig, PromptDurationConfig, RSourceOverride, SpinnerConfig,
};
pub use history::{HistoryConfig, HistoryMode};
pub use ipc::IpcConfig;
#[allow(unused_imports)]
// StatusSymbol is part of public API for programmatic StatusConfig construction
pub use prompt::{
    Indicators, ModeIndicatorPosition, PromptConfig, StatusConfig, StatusSymbol, ViConfig,
};
pub use r::RConfig;
pub use reprex::{FormatterBackend, ReprexConfig, ReprexFormatter};
pub use startup::{
    RSource, RSourceMode, RSourceOverrideInfo, RSourceStatus, ReprexMode, StartupConfig,
};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// Status of config file loading, for display in `:info`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigStatus {
    /// Config loaded successfully (or no config file exists).
    Ok,
    /// Config file could not be read (e.g., permission denied).
    ReadError,
    /// Config file has TOML syntax or schema errors.
    ParseError,
}

/// Error type for configuration loading failures.
#[derive(Debug)]
pub enum ConfigLoadError {
    /// Failed to read the config file from disk.
    Read {
        source: std::io::Error,
        path: PathBuf,
    },
    /// Failed to parse the TOML content.
    Parse {
        source: toml::de::Error,
        path: PathBuf,
    },
    /// A removed configuration key was found.
    Validation { message: String, path: PathBuf },
}

/// Configuration metadata collected while loading the file contents.
#[derive(Debug)]
pub(crate) struct ConfigLoadProvenance {
    pub(crate) path: PathBuf,
    pub(crate) startup_r_source_present: bool,
    pub(crate) history_migration_warning: Option<String>,
}

impl std::fmt::Display for ConfigLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigLoadError::Read { source, path } => {
                write!(
                    f,
                    "Failed to read config file {}: {}",
                    path.display(),
                    source
                )
            }
            ConfigLoadError::Parse { source, path } => {
                write!(
                    f,
                    "Failed to parse config file {}: {}",
                    path.display(),
                    source
                )
            }
            ConfigLoadError::Validation { message, path } => {
                write!(f, "Invalid config file {}: {}", path.display(), message)
            }
        }
    }
}

impl std::error::Error for ConfigLoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ConfigLoadError::Read { source, .. } => Some(source),
            ConfigLoadError::Parse { source, .. } => Some(source),
            ConfigLoadError::Validation { .. } => None,
        }
    }
}

/// Application name for XDG directories.
const APP_NAME: &str = "arf";

/// Main configuration structure.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
#[derive(Default)]
pub struct Config {
    pub startup: StartupConfig,
    pub editor: EditorConfig,
    pub prompt: PromptConfig,
    pub completion: CompletionConfig,
    pub history: HistoryConfig,
    /// IPC evaluation policy configuration.
    pub ipc: IpcConfig,
    /// R runtime configuration.
    pub r: RConfig,
    /// Static reprex configuration.
    pub reprex: ReprexConfig,
    pub colors: ColorsConfig,
    #[serde(default)]
    pub experimental: ExperimentalConfig,
    #[serde(skip)]
    pub(crate) history_migration_warning: Option<String>,
}

/// Get the XDG config directory for this application.
pub fn config_dir() -> Option<PathBuf> {
    dirs::config_dir().map(|p| p.join(APP_NAME))
}

/// Get the XDG data directory for this application.
pub fn data_dir() -> Option<PathBuf> {
    dirs::data_dir().map(|p| p.join(APP_NAME))
}

/// Get the XDG cache directory for this application.
pub fn cache_dir() -> Option<PathBuf> {
    dirs::cache_dir().map(|p| p.join(APP_NAME))
}

/// Get the path to the config file.
pub fn config_file_path() -> Option<PathBuf> {
    config_dir().map(|p| p.join("arf.toml"))
}

/// Get the history directory path.
///
/// History files are stored in a subdirectory: `~/.local/share/arf/history/`
/// - R mode: `history/r.db`
/// - Shell mode: `history/shell.db`
pub fn history_dir() -> Option<PathBuf> {
    data_dir().map(|p| p.join("history"))
}

/// Resolve the on-disk history directory for a configured mode.
///
/// Volatile history deliberately has no path: it must not expose, read, or
/// create the persistent XDG directory. Persistent mode uses its explicit
/// directory when present and otherwise the XDG default.
pub fn history_dir_for_mode(mode: &HistoryMode) -> Option<PathBuf> {
    match mode {
        HistoryMode::Persistent { .. } => mode.persistent_dir().cloned().or_else(history_dir),
        HistoryMode::Volatile => None,
    }
}

/// Mask home directory in path with `~` for privacy.
///
/// Replaces the user's home directory prefix with `~` to avoid displaying
/// usernames in paths. Works on both Unix and Windows (PowerShell supports `~`).
/// Uses platform-native path separators.
pub fn mask_home_path(path: &std::path::Path) -> String {
    if let Some(home) = dirs::home_dir()
        && let Ok(stripped) = path.strip_prefix(&home)
    {
        return format!("~{}{}", std::path::MAIN_SEPARATOR, stripped.display());
    }
    path.display().to_string()
}

/// Load configuration from the default XDG config file.
///
/// Returns `Ok(Config::default())` if no config file exists.
/// Returns `Err` if the file exists but cannot be read or parsed.
pub fn load_config() -> Result<Config, ConfigLoadError> {
    let Some(config_path) = config_file_path() else {
        return Ok(Config::default());
    };

    if !config_path.exists() {
        return Ok(Config::default());
    }

    load_config_from_path(&config_path)
}

/// Load configuration from a specific path.
///
/// Returns `Ok(Config::default())` if the file does not exist.
/// Returns `Err` if the file exists but cannot be read or parsed.
pub fn load_config_from_path(path: &std::path::Path) -> Result<Config, ConfigLoadError> {
    load_config_from_path_with_provenance(path).map(|(config, _)| config)
}

/// Load configuration and report metadata from the same file read.
pub(crate) fn load_config_from_path_with_provenance(
    path: &std::path::Path,
) -> Result<(Config, Option<ConfigLoadProvenance>), ConfigLoadError> {
    if !path.exists() {
        log::warn!("Config file not found: {:?}", path);
        return Ok((Config::default(), None));
    }

    let content = fs::read_to_string(path).map_err(|e| ConfigLoadError::Read {
        source: e,
        path: path.to_path_buf(),
    })?;

    let document = toml::from_str::<toml::Value>(&content).map_err(|e| ConfigLoadError::Parse {
        source: e,
        path: path.to_path_buf(),
    })?;
    let startup_r_source_present = document
        .get("startup")
        .and_then(|startup| startup.get("r_source"))
        .is_some();
    if let Some(message) = removed_reprex_keys(&document) {
        return Err(ConfigLoadError::Validation {
            message,
            path: path.to_path_buf(),
        });
    }
    let mut config = toml::from_str::<Config>(&content).map_err(|e| ConfigLoadError::Parse {
        source: e,
        path: path.to_path_buf(),
    })?;
    config.history_migration_warning = history_migration_warning(&document);
    let migration_warning = config.history_migration_warning.clone();

    Ok((
        config,
        Some(ConfigLoadProvenance {
            path: path.to_path_buf(),
            startup_r_source_present,
            history_migration_warning: migration_warning,
        }),
    ))
}

fn removed_reprex_keys(document: &toml::Value) -> Option<String> {
    let mut messages = Vec::new();

    if document
        .get("startup")
        .and_then(|value| value.get("mode"))
        .is_some()
    {
        messages
            .push("[startup.mode] was removed; use [startup] reprex = \"off\"|\"on\"|\"format\"");
    }
    if document
        .get("mode")
        .and_then(|value| value.get("reprex"))
        .is_some()
    {
        messages.push("[mode.reprex] was removed; use [reprex]");
    }
    if let Some(table) = document.get("reprex").and_then(toml::Value::as_table) {
        if table.contains_key("enabled") {
            messages.push("reprex.enabled was removed; use startup.reprex");
        }
        if table.contains_key("autoformat") {
            messages.push("reprex.autoformat was removed; use startup.reprex");
        }
    }
    if document
        .get("prompt")
        .and_then(|value| value.get("indicators"))
        .and_then(toml::Value::as_table)
        .is_some_and(|table| table.contains_key("autoformat"))
    {
        messages
            .push("prompt.indicators.autoformat was removed; use prompt.indicators.reprex_format");
    }

    (!messages.is_empty()).then(|| messages.join("\n  "))
}

fn history_migration_warning(document: &toml::Value) -> Option<String> {
    let history = document.get("history")?.as_table()?;
    let has_mode = history.contains_key("mode");
    let disabled = history.get("disabled").and_then(toml::Value::as_bool);
    let has_legacy_dir = history.contains_key("dir");
    match (has_mode, has_legacy_dir, disabled) {
        (true, _, Some(_)) => Some("Config key history.disabled is deprecated and ignored because history.mode is set; use history.mode only.".to_string()),
        (false, true, Some(true)) => Some("Config keys history.disabled and history.dir are deprecated; use history.mode = \"volatile\" instead.".to_string()),
        (false, true, Some(false)) => Some("Config keys history.disabled and history.dir are deprecated; use persistent history.mode = { dir = \"...\" } instead.".to_string()),
        (false, true, None) => Some("Config key history.dir is deprecated; use history.mode = { dir = \"...\" } instead.".to_string()),
        (false, false, Some(true)) => Some("Config key history.disabled is deprecated; use history.mode = \"volatile\" instead.".to_string()),
        (false, false, Some(false)) => Some("Config key history.disabled is deprecated; use history.mode = \"persistent\" instead.".to_string()),
        _ => None,
    }
}

/// Generate default configuration as a TOML string with comments.
pub fn generate_default_config() -> String {
    let config = Config::default();
    let toml_content = toml::to_string_pretty(&config).expect("Failed to serialize default config");

    // Add Tombi Schema Document Directive on the first line
    // See: https://tombi-toml.github.io/tombi/docs/comment-directive/schema-document-directive/
    let header = r#"#:schema https://raw.githubusercontent.com/eitsupi/arf/main/artifacts/arf.schema.json
# arf configuration file
#
# Documentation: https://github.com/eitsupi/arf

"#;

    format!("{}{}", header, toml_content)
}

/// Initialize a default configuration file at the XDG config location.
///
/// Returns the path where the config was written.
pub fn init_config(force: bool) -> anyhow::Result<std::path::PathBuf> {
    let config_path = config_file_path()
        .ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?;

    // Check if file already exists
    if config_path.exists() && !force {
        anyhow::bail!(
            "Configuration file already exists at: {}\nUse --force to overwrite.",
            config_path.display()
        );
    }

    // Ensure parent directory exists
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Generate and write config
    let content = generate_default_config();
    fs::write(&config_path, content)?;

    Ok(config_path)
}

/// Ensure all XDG directories exist.
pub fn ensure_directories() -> anyhow::Result<()> {
    if let Some(dir) = config_dir() {
        fs::create_dir_all(&dir)?;
    }
    if let Some(dir) = data_dir() {
        fs::create_dir_all(&dir)?;
    }
    if let Some(dir) = cache_dir() {
        fs::create_dir_all(&dir)?;
    }
    Ok(())
}

/// Schema generation for configuration.
#[allow(dead_code)]
pub mod schema {
    use super::Config;
    use schemars::schema_for;
    use std::path::PathBuf;

    /// Root directory for artifacts (relative to crate root).
    const ARTIFACTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../artifacts");

    /// Generate JSON schema for the configuration.
    pub fn generate_schema() -> String {
        let schema = schema_for!(Config);
        serde_json::to_string_pretty(&schema).expect("Failed to serialize schema")
    }

    /// Get the path to the schema file.
    pub fn schema_path() -> PathBuf {
        PathBuf::from(ARTIFACTS_DIR).join("arf.schema.json")
    }

    /// Write the schema to the artifacts directory.
    pub fn write_schema() -> std::io::Result<()> {
        let schema = generate_schema();
        let path = schema_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, schema)
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert!(
            config.editor.auto_match,
            "auto_match should be enabled by default"
        );
        assert_eq!(config.editor.mode, EditorMode::Emacs);
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
        assert!(config.startup.show_banner);
        assert_eq!(config.reprex.formatter, ReprexFormatter::Auto);
    }

    #[test]
    fn test_default_r_auto_width() {
        let config = Config::default();
        assert!(
            config.r.auto_width,
            "auto_width should be enabled by default"
        );
    }

    #[test]
    fn test_parse_r_auto_width_disabled() {
        let toml_str = r#"
[r]
auto_width = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(!config.r.auto_width);
    }

    #[test]
    fn test_parse_r_auto_width_default_when_omitted() {
        let toml_str = r#"
[editor]
mode = "vi"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            config.r.auto_width,
            "auto_width should default to true when [r] section is omitted"
        );
    }

    #[test]
    fn test_parse_config_with_auto_match_enabled() {
        let toml_str = r#"
[editor]
auto_match = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.editor.auto_match);
    }

    #[test]
    fn test_parse_config_with_auto_match_disabled() {
        let toml_str = r#"
[editor]
auto_match = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(!config.editor.auto_match);
    }

    #[test]
    fn test_parse_startup_section_config() {
        let toml_str = r##"
[startup]
r_source = "rig"
show_banner = false
reprex = "on"

[editor]
mode = "vi"
auto_match = false

[prompt]
format = "R> "
continuation = ".. "

[completion]
enabled = true
timeout_ms = 100

[reprex]
comment = "# "
formatter = "air"
"##;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Rig)
        ));
        assert!(!config.startup.show_banner);
        assert_eq!(config.editor.mode, EditorMode::Vi);
        assert!(!config.editor.auto_match);
        assert_eq!(config.prompt.format, "R> ");
        assert_eq!(config.startup.reprex, ReprexMode::On);
        assert_eq!(config.reprex.comment, "# ");
        assert_eq!(config.reprex.formatter, ReprexFormatter::Air);
    }

    #[test]
    fn reprex_formatter_accepts_supported_selectors() {
        for (source, expected) in [
            ("[reprex]\nformatter = \"auto\"", ReprexFormatter::Auto),
            ("[reprex]\nformatter = \"air\"", ReprexFormatter::Air),
            ("[reprex]\nformatter = \"arity\"", ReprexFormatter::Arity),
        ] {
            let config: Config = toml::from_str(source).unwrap();
            assert_eq!(config.reprex.formatter, expected);
        }
    }

    #[test]
    fn reprex_formatter_rejects_unknown_backends() {
        let source = "[reprex]\nformatter = \"unknown\"";
        assert!(toml::from_str::<Config>(source).is_err());
    }

    #[test]
    fn reprex_formatter_metadata_describes_air_backend() {
        let formatter = FormatterBackend::Air;
        assert_eq!(formatter.display_name(), "Air");
        assert_eq!(formatter.command(), "air");
        assert_eq!(formatter.install_url(), "https://github.com/posit-dev/air");
        assert_eq!(formatter.minimum_version(), "0.9.0");
        assert_eq!(formatter.to_string(), "air");
    }

    #[test]
    fn reprex_formatter_metadata_describes_arity_backend() {
        let formatter = FormatterBackend::Arity;
        assert_eq!(formatter.display_name(), "Arity");
        assert_eq!(formatter.command(), "arity");
        assert_eq!(formatter.install_url(), "https://github.com/jolars/arity");
        assert_eq!(formatter.minimum_version(), "0.18.0");
        assert_eq!(formatter.to_string(), "arity");
    }

    #[test]
    fn removed_reprex_configuration_keys_are_rejected_explicitly() {
        for source in [
            r#"[startup.mode]
reprex = true"#,
            r##"[mode.reprex]
comment = "#> ""##,
            r#"[reprex]
enabled = true"#,
        ] {
            let document: toml::Value = toml::from_str(source).unwrap();
            let message = removed_reprex_keys(&document).expect("removed key should be found");
            assert!(!message.is_empty());
        }
    }

    #[test]
    fn removed_reprex_configuration_keys_are_all_reported() {
        let source = r##"
[startup.mode]
reprex = true

[mode.reprex]
comment = "#> "

[reprex]
enabled = true
autoformat = true

[prompt.indicators]
autoformat = true
"##;
        let document: toml::Value = toml::from_str(source).unwrap();
        let message = removed_reprex_keys(&document).expect("removed keys should be found");

        insta::assert_snapshot!(message, @r###"
[startup.mode] was removed; use [startup] reprex = "off"|"on"|"format"
  [mode.reprex] was removed; use [reprex]
  reprex.enabled was removed; use startup.reprex
  reprex.autoformat was removed; use startup.reprex
  prompt.indicators.autoformat was removed; use prompt.indicators.reprex_format
"###);
    }

    #[test]
    fn removed_reprex_configuration_keys_are_rejected_by_file_loader() {
        let cases = [
            r#"[startup.mode]
reprex = true"#,
            r##"[mode.reprex]
comment = "#> ""##,
            r#"[reprex]
enabled = true"#,
            r#"[reprex]
autoformat = true"#,
        ];

        for source in cases {
            let file = tempfile::NamedTempFile::new().unwrap();
            std::fs::write(file.path(), source).unwrap();
            let error = load_config_from_path(file.path()).expect_err(source);
            assert!(
                matches!(error, ConfigLoadError::Validation { .. }),
                "removed key must fail validation through the loader: {source}"
            );
        }
    }

    #[test]
    fn test_parse_new_key_map_config() {
        let toml_str = r#"
[editor]
mode = "emacs"

[editor.key_map]
"alt-hyphen" = " <- "
"ctrl-shift-m" = " |> "
"alt-=" = " == "
"#;
        let config: Config = toml::from_str(toml_str).unwrap();

        let alt_hyphen: KeyCombination = "alt-hyphen".parse().unwrap();
        let ctrl_shift_m: KeyCombination = "ctrl-shift-m".parse().unwrap();
        let alt_eq: KeyCombination = "alt-=".parse().unwrap();

        assert_eq!(
            config.editor.key_map.get(&alt_hyphen),
            Some(&" <- ".to_string())
        );
        assert_eq!(
            config.editor.key_map.get(&ctrl_shift_m),
            Some(&" |> ".to_string())
        );
        assert_eq!(
            config.editor.key_map.get(&alt_eq),
            Some(&" == ".to_string())
        );
    }

    #[test]
    fn test_default_key_map() {
        let config = Config::default();

        let alt_hyphen: KeyCombination = "alt-hyphen".parse().unwrap();
        let alt_p: KeyCombination = "alt-p".parse().unwrap();

        assert_eq!(
            config.editor.key_map.get(&alt_hyphen),
            Some(&" <- ".to_string())
        );
        assert_eq!(config.editor.key_map.get(&alt_p), Some(&" |> ".to_string()));
    }

    #[test]
    fn test_default_mode_indicator() {
        let config = Config::default();
        assert_eq!(config.prompt.mode_indicator, ModeIndicatorPosition::Prefix);
        assert_eq!(config.prompt.indicators.reprex, "[reprex] ");
        assert_eq!(config.prompt.indicators.reprex_format, "[format] ");
    }

    #[test]
    fn test_parse_mode_indicator_suffix() {
        let toml_str = r#"
[prompt]
mode_indicator = "suffix"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.prompt.mode_indicator, ModeIndicatorPosition::Suffix);
    }

    #[test]
    fn test_parse_mode_indicator_none() {
        let toml_str = r#"
[prompt]
mode_indicator = "none"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.prompt.mode_indicator, ModeIndicatorPosition::None);
    }

    #[test]
    fn test_parse_history_mode_volatile() {
        let toml_str = r#"
[history]
mode = "volatile"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(config.history.mode, HistoryMode::Volatile));
    }

    #[test]
    fn test_parse_history_mode_with_directory_object() {
        let config: Config =
            toml::from_str("[history]\nmode = { dir = \"/custom/history\" }\n").unwrap();
        assert!(matches!(
            config.history.mode,
            HistoryMode::Persistent { dir: Some(ref dir) }
                if dir == std::path::Path::new("/custom/history")
        ));

        let serialized = toml::to_string(&config).unwrap();
        assert!(
            serialized.contains("[history.mode]")
                && serialized.contains("dir = \"/custom/history\""),
            "serialized history config used an unexpected TOML shape: {serialized}"
        );
        assert!(!serialized.contains("[history]\ndir = "));
    }

    #[test]
    fn test_history_mode_object_requires_dir_and_rejects_unknown_fields() {
        assert!(toml::from_str::<Config>("[history]\nmode = {}\n").is_err());
        assert!(
            toml::from_str::<Config>("[history]\nmode = { dir = \"/tmp\", extra = true }\n")
                .is_err()
        );
    }

    #[test]
    fn test_history_mode_rejects_legacy_dir_when_explicit() {
        let result =
            toml::from_str::<Config>("[history]\nmode = \"persistent\"\ndir = \"/tmp/history\"\n");
        assert!(result.is_err());
    }

    #[test]
    fn test_legacy_history_disabled_migrates_with_warning() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("arf.toml");
        fs::write(&path, "[history]\ndisabled = true\n").unwrap();
        let (config, provenance) = load_config_from_path_with_provenance(&path).unwrap();
        assert!(matches!(config.history.mode, HistoryMode::Volatile));
        assert!(config.history_migration_warning.is_some());
        assert!(provenance.unwrap().history_migration_warning.is_some());
    }

    #[test]
    fn test_legacy_history_disabled_false_preserves_directory() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("arf.toml");
        fs::write(
            &path,
            "[history]\ndisabled = false\ndir = \"/tmp/arf-history\"\n",
        )
        .unwrap();
        let (loaded, provenance) = load_config_from_path_with_provenance(&path).unwrap();
        assert!(
            provenance
                .unwrap()
                .history_migration_warning
                .unwrap()
                .contains("persistent")
        );
        assert!(matches!(
            loaded.history.mode,
            HistoryMode::Persistent { .. }
        ));

        let config: Config =
            toml::from_str("[history]\ndisabled = false\ndir = \"/tmp/arf-history\"\n").unwrap();
        assert!(matches!(
            config.history.mode,
            HistoryMode::Persistent { dir: Some(ref dir) } if dir == std::path::Path::new("/tmp/arf-history")
        ));
    }

    #[test]
    fn test_legacy_history_dir_without_disabled_migrates_to_persistent() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("arf.toml");
        fs::write(&path, "[history]\ndir = \"/tmp/arf-history\"\n").unwrap();
        let (config, provenance) = load_config_from_path_with_provenance(&path).unwrap();
        assert!(matches!(
            config.history.mode,
            HistoryMode::Persistent { dir: Some(ref dir) }
                if dir == std::path::Path::new("/tmp/arf-history")
        ));
        assert!(
            provenance
                .unwrap()
                .history_migration_warning
                .unwrap()
                .contains("deprecated")
        );
    }

    #[test]
    fn test_history_mode_wins_over_legacy_disabled() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("arf.toml");
        fs::write(&path, "[history]\nmode = \"volatile\"\ndisabled = false\n").unwrap();
        let (config, provenance) = load_config_from_path_with_provenance(&path).unwrap();
        assert!(
            provenance
                .unwrap()
                .history_migration_warning
                .unwrap()
                .contains("ignored")
        );
        assert!(matches!(config.history.mode, HistoryMode::Volatile));
    }

    #[test]
    fn test_history_mode_object_wins_over_legacy_disabled() {
        for disabled in [true, false] {
            let temp = tempfile::tempdir().unwrap();
            let path = temp.path().join("arf.toml");
            fs::write(
                &path,
                format!(
                    "[history]\nmode = {{ dir = \"/tmp/payload-history\" }}\ndisabled = {disabled}\n"
                ),
            )
            .unwrap();
            let (config, provenance) = load_config_from_path_with_provenance(&path).unwrap();
            assert!(matches!(
                config.history.mode,
                HistoryMode::Persistent { dir: Some(ref dir) }
                    if dir == std::path::Path::new("/tmp/payload-history")
            ));
            assert!(
                provenance
                    .unwrap()
                    .history_migration_warning
                    .unwrap()
                    .contains("ignored")
            );
        }
    }

    #[test]
    fn test_history_mode_wrong_type_is_parse_error() {
        let result = toml::from_str::<Config>("[history]\nmode = 1\n");
        assert!(result.is_err());
        let result = toml::from_str::<Config>("[history]\ndisabled = \"true\"\n");
        assert!(result.is_err());
    }

    #[test]
    fn test_history_dir_for_mode_never_exposes_a_volatile_path() {
        assert_eq!(
            history_dir_for_mode(&HistoryMode::Volatile),
            None,
            "volatile history must not expose the persistent XDG directory"
        );
        let explicit = std::path::PathBuf::from("/tmp/arf-history");
        assert_eq!(
            history_dir_for_mode(&HistoryMode::Persistent {
                dir: Some(explicit.clone()),
            }),
            Some(explicit)
        );
    }

    #[test]
    fn test_default_history_forget_config() {
        let config = Config::default();
        assert!(!config.experimental.history_forget.enabled);
        assert_eq!(config.experimental.history_forget.delay, 2);
        assert!(!config.experimental.history_forget.on_exit_only);
    }

    #[test]
    fn test_parse_history_forget_config() {
        let toml_str = r#"
[experimental.history_forget]
enabled = true
delay = 5
on_exit_only = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.history_forget.enabled);
        assert_eq!(config.experimental.history_forget.delay, 5);
        assert!(config.experimental.history_forget.on_exit_only);
    }

    #[test]
    fn test_auto_suggestions_default_is_all() {
        let config = Config::default();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::All);
    }

    #[test]
    fn test_parse_auto_suggestions_none_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "none"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::None);
    }

    #[test]
    fn test_parse_auto_suggestions_all_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "all"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::All);
    }

    #[test]
    fn test_parse_auto_suggestions_cwd_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "cwd"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::Cwd);
    }

    #[test]
    fn test_parse_auto_suggestions_bool_true() {
        let toml_str = r#"
[editor]
auto_suggestions = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::All);
    }

    #[test]
    fn test_parse_auto_suggestions_bool_false() {
        let toml_str = r#"
[editor]
auto_suggestions = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::None);
    }

    #[test]
    fn test_parse_auto_suggestions_invalid_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "invalid"
"#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("unknown variant"),
            "Error should mention unknown variant: {}",
            err
        );
    }

    #[test]
    fn test_parse_auto_suggestions_string_true_rejected() {
        // String "true" should be rejected (use boolean true instead)
        let toml_str = r#"
[editor]
auto_suggestions = "true"
"#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "String 'true' should be rejected");
    }

    #[test]
    fn test_parse_auto_suggestions_string_false_rejected() {
        // String "false" should be rejected (use boolean false instead)
        let toml_str = r#"
[editor]
auto_suggestions = "false"
"#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "String 'false' should be rejected");
    }

    #[test]
    fn test_parse_r_source_auto() {
        let toml_str = r#"
[startup]
r_source = "auto"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
    }

    #[test]
    fn test_parse_r_source_rig() {
        let toml_str = r#"
[startup]
r_source = "rig"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Rig)
        ));
    }

    #[test]
    fn test_parse_r_source_path() {
        let toml_str = r#"
[startup]
r_source = { path = "/opt/R/4.5.2" }
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        match &config.startup.r_source {
            RSource::Path { path } => {
                assert_eq!(path, &PathBuf::from("/opt/R/4.5.2"));
            }
            _ => panic!("Expected RSource::Path"),
        }
    }

    #[test]
    fn test_parse_r_source_default_when_omitted() {
        let toml_str = r#"
[startup]
show_banner = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
    }

    #[test]
    fn test_parse_ipc_eval_allowed_functions() {
        let config: Config = toml::from_str(
            r#"
[ipc.eval]
allowed_functions = ["mean", "stats::median", "+"]
"#,
        )
        .unwrap();
        assert_eq!(
            config.ipc.eval.allowed_functions,
            ["mean", "stats::median", "+"]
        );
        assert!(Config::default().ipc.eval.allowed_functions.is_empty());
    }

    #[test]
    fn test_generate_default_config() {
        let config_str = generate_default_config();

        // Should have Tombi Schema Document Directive on first line
        assert!(config_str.starts_with(
            "#:schema https://raw.githubusercontent.com/eitsupi/arf/main/artifacts/arf.schema.json"
        ));

        // Should be valid TOML
        let parsed: Config =
            toml::from_str(&config_str).expect("Generated config should be valid TOML");

        // Should have default values
        assert!(matches!(
            parsed.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
        assert!(parsed.startup.show_banner);
        assert_eq!(parsed.editor.mode, EditorMode::Emacs);
    }

    #[test]
    fn test_generate_default_config_has_new_structure() {
        let config_str = generate_default_config();

        // Should have [startup] section with r_source and show_banner
        assert!(
            config_str.contains("[startup]"),
            "Should have [startup] section"
        );
        assert!(
            config_str.contains("r_source = "),
            "Should have r_source in startup section"
        );
        assert!(
            config_str.contains("show_banner = "),
            "Should have show_banner in startup section"
        );

        // Reprex mode is part of the startup section.
        assert!(
            config_str.contains("reprex = \"off\""),
            "Should have reprex mode in startup section"
        );

        // Should have [reprex] section
        assert!(
            config_str.contains("[reprex]"),
            "Should have [reprex] section"
        );

        // Should NOT have old sections
        assert!(
            !config_str.contains("[general]"),
            "Should NOT have [general] section"
        );
        assert!(
            !config_str.contains("[shortcuts]"),
            "Should NOT have [shortcuts] section"
        );
        assert!(
            !config_str.contains("[formatter]"),
            "Should NOT have [formatter] section"
        );

        // Should have other sections
        assert!(
            config_str.contains("[editor]"),
            "Should have [editor] section"
        );
        assert!(
            config_str.contains("mode = \"persistent\""),
            "History should default to persistent mode"
        );
        assert!(
            !config_str.contains("disabled"),
            "Deprecated history.disabled must not be serialized"
        );
    }

    mod schema_tests {
        use crate::config::schema::{generate_schema, schema_path, write_schema};

        #[test]
        fn test_schema_snapshot() {
            let schema = generate_schema();
            insta::assert_snapshot!("config_schema", schema);
        }

        /// Snapshot test for the default configuration file.
        /// This ensures we notice when the config structure changes.
        #[test]
        fn test_default_config_snapshot() {
            let config = crate::config::generate_default_config();
            insta::assert_snapshot!("default_config", config);
        }

        #[test]
        fn test_schema_matches_artifact() {
            let schema = generate_schema();
            let path = schema_path();

            // If the artifact file exists, verify it matches the generated schema
            if path.exists() {
                let contents = std::fs::read_to_string(&path).expect("Failed to read schema file");
                assert_eq!(
                    schema, contents,
                    "Schema file is out of date. Run the generate_schema_file test to update."
                );
            }
        }

        /// Generate the schema file in artifacts/.
        /// Run with: cargo test -p arf-console generate_schema_file -- --ignored
        #[test]
        #[ignore]
        fn generate_schema_file() {
            write_schema().expect("Failed to write schema file");
            println!("Schema written to {:?}", schema_path());
        }

        #[test]
        fn test_schema_is_valid_json() {
            let schema = generate_schema();
            let parsed: serde_json::Value =
                serde_json::from_str(&schema).expect("Schema should be valid JSON");

            // Verify it has expected top-level fields
            assert!(
                parsed.get("$schema").is_some(),
                "Schema should have $schema field"
            );
            assert!(
                parsed.get("title").is_some(),
                "Schema should have title field"
            );
            assert!(
                parsed.get("type").is_some(),
                "Schema should have type field"
            );
            assert!(
                parsed.get("properties").is_some(),
                "Schema should have properties field"
            );
        }

        #[test]
        fn test_schema_has_new_structure() {
            let schema = generate_schema();
            let parsed: serde_json::Value =
                serde_json::from_str(&schema).expect("Schema should be valid JSON");

            let properties = parsed
                .get("properties")
                .expect("Schema should have properties");

            let history = properties
                .get("history")
                .and_then(|value| value.get("$ref"))
                .and_then(|value| value.as_str())
                .and_then(|reference| reference.strip_prefix("#/$defs/"))
                .and_then(|name| parsed.get("$defs").and_then(|defs| defs.get(name)))
                .expect("Schema should define history");
            let history_properties = history
                .get("properties")
                .expect("History schema should have properties");
            assert!(history_properties.get("disabled").is_none());
            assert!(history_properties.get("dir").is_none());
            let mode = history_properties
                .get("mode")
                .expect("History mode should be present in schema");
            assert!(
                history
                    .get("required")
                    .and_then(|required| required.as_array())
                    .is_none_or(|required| !required.iter().any(|name| name == "mode")),
                "History mode must remain optional for the default persistent mode"
            );
            assert_eq!(mode["default"], "persistent");
            let variants = mode
                .get("oneOf")
                .and_then(|variants| variants.as_array())
                .expect("History mode should have string and object variants");
            assert!(variants.iter().any(|variant| {
                variant["type"] == "string"
                    && variant["enum"]
                        .as_array()
                        .is_some_and(|values| values.iter().any(|value| value == "persistent"))
            }));
            assert!(variants.iter().any(|variant| {
                variant["type"] == "object"
                    && variant["additionalProperties"] == false
                    && variant["required"]
                        .as_array()
                        .is_some_and(|required| required.iter().any(|name| name == "dir"))
            }));

            // Should have startup section (contains r_source, show_banner, reprex)
            assert!(
                properties.get("startup").is_some(),
                "Schema should have startup section"
            );

            // Should have reprex section (contains static configuration)
            assert!(
                properties.get("reprex").is_some(),
                "Schema should have reprex section"
            );

            // Should have other sections
            assert!(
                properties.get("editor").is_some(),
                "Schema should have editor section"
            );
            assert!(
                properties.get("prompt").is_some(),
                "Schema should have prompt section"
            );
            assert!(
                properties.get("completion").is_some(),
                "Schema should have completion section"
            );
            assert!(
                properties.get("experimental").is_some(),
                "Schema should have experimental section"
            );

            // Should NOT have legacy sections or top-level fields that moved
            assert!(
                properties.get("general").is_none(),
                "Schema should NOT have general section"
            );
            assert!(
                properties.get("reprex").is_some(),
                "reprex should be in its top-level section"
            );
            assert!(
                properties.get("r_version").is_none(),
                "r_version should be in startup section, not top-level"
            );
            assert!(
                properties.get("show_banner").is_none(),
                "show_banner should be in startup section, not top-level"
            );
            assert!(
                properties.get("shortcuts").is_none(),
                "Schema should NOT have shortcuts section"
            );
            assert!(
                properties.get("formatter").is_none(),
                "Schema should NOT have formatter section"
            );
        }

        #[test]
        fn test_schema_has_r_source_overrides() {
            let schema = generate_schema();
            let parsed: serde_json::Value =
                serde_json::from_str(&schema).expect("Schema should be valid JSON");

            let experimental = parsed
                .get("$defs")
                .and_then(|defs| defs.get("ExperimentalConfigSchema"))
                .and_then(|schema| schema.get("properties"))
                .expect("Schema should define experimental properties");
            assert!(
                experimental.get("r_source_overrides").is_some(),
                "Schema should have r_source_overrides"
            );
        }
    }

    #[test]
    fn test_mask_home_path_with_home_prefix() {
        // mask_home_path reads HOME indirectly through dirs::home_dir.
        let _guard = crate::test_utils::lock_env();
        if let Some(home) = dirs::home_dir() {
            let test_path = home.join("test").join("file.txt");
            let masked = mask_home_path(&test_path);
            assert!(
                masked.starts_with("~"),
                "Path should start with ~: {}",
                masked
            );
            assert!(
                masked.contains("test"),
                "Path should contain 'test': {}",
                masked
            );
            assert!(
                masked.contains("file.txt"),
                "Path should contain 'file.txt': {}",
                masked
            );
        }
    }

    #[test]
    fn test_mask_home_path_without_home_prefix() {
        // mask_home_path reads HOME indirectly through dirs::home_dir.
        let _guard = crate::test_utils::lock_env();
        let test_path = PathBuf::from("/opt/R/4.5.0");
        let expected = test_path.display().to_string();
        let masked = mask_home_path(&test_path);
        assert_eq!(
            masked, expected,
            "Path without home prefix should be unchanged"
        );
    }

    #[test]
    fn test_mask_home_path_exact_home() {
        // mask_home_path reads HOME indirectly through dirs::home_dir.
        let _guard = crate::test_utils::lock_env();
        if let Some(home) = dirs::home_dir() {
            let masked = mask_home_path(&home);
            // Should be just "~/" or "~\" depending on platform
            assert!(
                masked.starts_with("~"),
                "Home path should start with ~: {}",
                masked
            );
        }
    }

    #[test]
    fn test_load_config_from_path_parse_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.toml");
        std::fs::write(&path, "[editor\nauto_match = true").unwrap();

        let result = load_config_from_path(&path);
        assert!(result.is_err(), "Invalid TOML should return Err");

        let err = result.unwrap_err();
        assert!(
            matches!(err, ConfigLoadError::Parse { .. }),
            "Should be a ParseError: {:?}",
            err
        );
        let msg = err.to_string();
        assert!(
            msg.contains("bad.toml"),
            "Error should mention the file path: {}",
            msg
        );
    }

    #[test]
    fn test_load_config_from_path_type_error_includes_location() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("invalid-type.toml");
        std::fs::write(
            &path,
            r#"
[editor]
mode = 42
"#,
        )
        .unwrap();

        let error = load_config_from_path(&path).expect_err("invalid config type should fail");
        let message = error.to_string();

        assert!(
            message.contains("line 3, column 8"),
            "Type error should include source location: {message}"
        );
    }

    #[test]
    fn test_load_config_from_path_valid() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("good.toml");
        std::fs::write(
            &path,
            r#"
[editor]
auto_match = false
"#,
        )
        .unwrap();

        let result = load_config_from_path(&path);
        assert!(result.is_ok(), "Valid TOML should return Ok");
        let config = result.unwrap();
        assert!(!config.editor.auto_match);
    }

    #[test]
    fn test_load_config_from_path_not_found() {
        let path = PathBuf::from("/nonexistent/config.toml");
        let result = load_config_from_path(&path);
        assert!(result.is_ok(), "Missing file should return Ok(default)");
        let config = result.unwrap();
        assert!(config.editor.auto_match, "Should be default config");
    }

    #[test]
    fn test_config_load_error_display() {
        let err = ConfigLoadError::Parse {
            source: toml::from_str::<Config>("[bad\n").unwrap_err(),
            path: PathBuf::from("/home/user/.config/arf/arf.toml"),
        };
        let msg = err.to_string();
        assert!(msg.contains("parse"), "Should mention parse: {}", msg);
        assert!(msg.contains("arf.toml"), "Should mention path: {}", msg);
    }

    #[cfg(unix)]
    #[test]
    fn test_load_config_from_path_read_error() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("unreadable.toml");
        std::fs::write(&path, "[editor]\nauto_match = true").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();

        let result = load_config_from_path(&path);
        assert!(result.is_err(), "Unreadable file should return Err");

        let err = result.unwrap_err();
        assert!(
            matches!(err, ConfigLoadError::Read { .. }),
            "Should be a ReadError: {:?}",
            err
        );

        // Restore permissions so tempdir cleanup succeeds
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
    }
}