tinyharness-lib 0.3.3

core liblary for tinyharness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
use std::collections::HashMap;
use std::path::PathBuf;
use std::{fmt, str::FromStr};

use serde::{Deserialize, Serialize};

use crate::SecretString;
use crate::mode::AgentMode;

// ── AutoAccept Mode ────────────────────────────────────────────────────────

/// Controls how aggressively tool calls are auto-approved.
///
/// Parsed from string values for JSON config: `"off"`, `"safe"`, `"all"`.
/// Legacy boolean fields (`auto_accept_all`, `auto_accept_safe_commands`)
/// are resolved in `SettingsStore::load()` when `auto_accept_mode` is absent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AutoAcceptMode {
    Off,
    #[default]
    Safe,
    All,
}

impl<'de> Deserialize<'de> for AutoAcceptMode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct AutoAcceptModeVisitor;

        impl<'de> serde::de::Visitor<'de> for AutoAcceptModeVisitor {
            type Value = AutoAcceptMode;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter
                    .write_str("a string (\"off\", \"safe\", \"all\") or a boolean (true/false)")
            }

            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(if v {
                    AutoAcceptMode::All
                } else {
                    AutoAcceptMode::Off
                })
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                AutoAcceptMode::from_str(v).map_err(serde::de::Error::custom)
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                AutoAcceptMode::from_str(&v).map_err(serde::de::Error::custom)
            }
        }

        deserializer.deserialize_any(AutoAcceptModeVisitor)
    }
}

impl FromStr for AutoAcceptMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "off" | "false" | "no" | "0" | "disabled" => Ok(AutoAcceptMode::Off),
            "safe" | "on" => Ok(AutoAcceptMode::Safe),
            "all" | "always" | "true" | "yes" | "1" | "enabled" => Ok(AutoAcceptMode::All),
            _ => Err(format!(
                "Unknown auto-accept mode '{}'. Valid values: off, safe, all",
                s
            )),
        }
    }
}

impl fmt::Display for AutoAcceptMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AutoAcceptMode::Off => write!(f, "off"),
            AutoAcceptMode::Safe => write!(f, "safe"),
            AutoAcceptMode::All => write!(f, "all"),
        }
    }
}

// ── Project Settings ────────────────────────────────────────────────────────

/// Per-project override settings discovered from `.tinyharness/config.json`.
///
/// All fields are `Option` — only present fields override the global setting.
/// Discovery walks up from CWD, same algorithm as `discover_project_md`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProjectSettings {
    /// Override safe command prefixes (extends, doesn't replace)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safe_command_prefixes: Option<Vec<String>>,
    /// Override denied command prefixes
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub denied_command_prefixes: Option<Vec<String>>,
    /// Override auto-accept mode for this project
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_accept_mode: Option<AutoAcceptMode>,
    /// Override context_limit
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_limit: Option<u32>,
    /// Additional project-specific MD file names to include in context
    /// (e.g. ["RULES.md", ".cursorrules"]). These are loaded AFTER the main
    /// project instruction file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_md_files: Option<Vec<String>>,
    /// Override the preferred mode for this project
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preferred_mode: Option<AgentMode>,
    /// Override auto-compact enabled setting for this project
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_compact_enabled: Option<bool>,
}

/// Discover and load `.tinyharness/config.json` by walking up from CWD.
///
/// Returns `None` if no config file is found. Returns `Some(Err(...))` if
/// a file is found but cannot be parsed.
pub fn discover_project_settings(
    start_dir: &std::path::Path,
) -> Option<Result<ProjectSettings, SettingsError>> {
    let mut dir = start_dir.to_path_buf();

    loop {
        let candidate = dir.join(".tinyharness").join("config.json");
        if candidate.is_file() {
            let content = match std::fs::read_to_string(&candidate) {
                Ok(c) => c,
                Err(e) => return Some(Err(SettingsError::Io(e))),
            };
            let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
            return Some(parsed);
        }

        // Walk up one directory
        if let Some(parent) = dir.parent() {
            if parent == dir {
                break;
            }
            dir = parent.to_path_buf();
        } else {
            break;
        }
    }

    None
}

/// Source annotation for merged settings values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingSource {
    /// Value came from the global `~/.config/tinyharness/settings.json`
    Global,
    /// Value came from `.tinyharness/config.json`
    Project,
    /// Value is the hardcoded default (no config found)
    Default,
}

impl std::fmt::Display for SettingSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SettingSource::Global => f.write_str("global"),
            SettingSource::Project => f.write_str("project"),
            SettingSource::Default => f.write_str("default"),
        }
    }
}

/// Effective merged settings — the result of layering global + project settings.
///
/// This is a read-only view. Each field has a source annotation for display.
#[derive(Debug, Clone)]
pub struct MergedSettings {
    /// Merged safe command prefixes (project extends global)
    pub safe_commands: Vec<String>,
    pub safe_commands_source: SettingSource,
    /// Merged denied command prefixes (project overrides global)
    pub denied_commands: Vec<String>,
    pub denied_commands_source: SettingSource,
    pub auto_accept_mode: AutoAcceptMode,
    pub auto_accept_mode_source: SettingSource,
    pub context_limit: Option<u32>,
    pub context_limit_source: SettingSource,
    pub project_md_files: Vec<String>,
    pub project_md_files_source: SettingSource,
    pub preferred_mode: AgentMode,
    pub preferred_mode_source: SettingSource,
    pub auto_compact_enabled: bool,
    pub auto_compact_enabled_source: SettingSource,
}

/// Load and merge global + project settings.
///
/// Layering: project overrides global where specified, otherwise falls back
/// to global. For safe commands, project *extends* the global list rather
/// than replacing it.
pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
    let global = load_settings();

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project = match discover_project_settings(&cwd) {
        Some(Ok(ps)) => Some(ps),
        Some(Err(e)) => {
            tracing::warn!(
                "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
            );
            None
        }
        None => None,
    };

    let merged = merge_settings(&global, project.as_ref());
    (global, project, merged)
}

/// Merge global settings with optional project overrides.
fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
    let global_safe = global.get_safe_commands();
    let global_denied = global.get_denied_commands();

    match project {
        None => MergedSettings {
            safe_commands: global_safe,
            safe_commands_source: SettingSource::Default,
            denied_commands: global_denied,
            denied_commands_source: SettingSource::Default,
            auto_accept_mode: global.auto_accept_mode,
            auto_accept_mode_source: SettingSource::Default,
            context_limit: global.context_limit,
            context_limit_source: SettingSource::Default,
            project_md_files: Vec::new(),
            project_md_files_source: SettingSource::Default,
            preferred_mode: global.preferred_mode,
            preferred_mode_source: SettingSource::Default,
            auto_compact_enabled: global.auto_compact_enabled,
            auto_compact_enabled_source: SettingSource::Default,
        },
        Some(p) => {
            // Safe commands: project extends global
            let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
                let mut combined = global_safe.clone();
                for cmd in proj_safe {
                    if !combined.contains(cmd) {
                        combined.push(cmd.clone());
                    }
                }
                combined
            } else {
                global_safe
            };
            let safe_source = if p.safe_command_prefixes.is_some() {
                SettingSource::Project
            } else {
                SettingSource::Default
            };

            // Denied commands: project replaces global
            let (denied_commands, denied_source) =
                if let Some(ref proj_denied) = p.denied_command_prefixes {
                    (proj_denied.clone(), SettingSource::Project)
                } else {
                    (global_denied, SettingSource::Default)
                };

            let (auto_accept_mode, auto_source) = p
                .auto_accept_mode
                .map(|v| (v, SettingSource::Project))
                .unwrap_or((global.auto_accept_mode, SettingSource::Default));

            let (context_limit, ctx_source) = p
                .context_limit
                .map(|v| (Some(v), SettingSource::Project))
                .unwrap_or((global.context_limit, SettingSource::Default));

            let (project_md_files, md_source) = p
                .project_md_files
                .as_ref()
                .map(|files| (files.clone(), SettingSource::Project))
                .unwrap_or((Vec::new(), SettingSource::Default));

            let (preferred_mode, mode_source) = p
                .preferred_mode
                .map(|m| (m, SettingSource::Project))
                .unwrap_or((global.preferred_mode, SettingSource::Default));

            let (auto_compact_enabled, ac_source) = p
                .auto_compact_enabled
                .map(|v| (v, SettingSource::Project))
                .unwrap_or((global.auto_compact_enabled, SettingSource::Default));

            MergedSettings {
                safe_commands,
                safe_commands_source: safe_source,
                denied_commands,
                denied_commands_source: denied_source,
                auto_accept_mode,
                auto_accept_mode_source: auto_source,
                context_limit,
                context_limit_source: ctx_source,
                project_md_files,
                project_md_files_source: md_source,
                preferred_mode,
                preferred_mode_source: mode_source,
                auto_compact_enabled,
                auto_compact_enabled_source: ac_source,
            }
        }
    }
}

/// Generate a starter `.tinyharness/config.json` file from current settings
/// overrides that make sense for a project (safe commands, denied commands,
/// auto-accept, context limit).
pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
    ProjectSettings {
        safe_command_prefixes: settings.safe_command_prefixes.clone(),
        denied_command_prefixes: settings.denied_command_prefixes.clone(),
        auto_accept_mode: Some(settings.auto_accept_mode),
        context_limit: settings.context_limit,
        project_md_files: None, // user must fill this in
        preferred_mode: Some(settings.preferred_mode),
        auto_compact_enabled: Some(settings.auto_compact_enabled),
    }
}

/// Identifies which provider backend was used last.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum ProviderKind {
    #[default]
    Ollama,
    LlamaCpp,
    Vllm,
    /// Generic OpenAI-compatible provider for hosted gateways (OpenRouter,
    /// Together, etc.) that require a Bearer API key. Unlike LlamaCpp/Vllm
    /// which target local unauthenticated servers, this provider always
    /// sends `Authorization: Bearer <key>` and requires `--api-key` or
    /// the `OPENAI_API_KEY` env var.
    OpenAiCompat,
    Sockudo,
}

impl fmt::Display for ProviderKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProviderKind::Ollama => f.write_str("ollama"),
            ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
            ProviderKind::Vllm => f.write_str("vllm"),
            ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
            ProviderKind::Sockudo => f.write_str("sockudo"),
        }
    }
}

impl FromStr for ProviderKind {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "ollama" => Ok(ProviderKind::Ollama),
            "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
            "vllm" => Ok(ProviderKind::Vllm),
            "openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
            "sockudo" => Ok(ProviderKind::Sockudo),
            _ => Err(format!("Unknown provider '{}'", s)),
        }
    }
}

/// Controls the "think" (reasoning) level for Ollama models that support it
/// (e.g. qwen2.5 variants). Affects how much internal reasoning the model does
/// before responding.
///
/// Corresponds to Ollama's `think` parameter. Only meaningful for Ollama;
/// other providers ignore this setting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum OllamaThinkType {
    /// Disable thinking entirely (fastest, lowest quality).
    Off,
    /// Minimal reasoning (faster, lower latency).
    Low,
    /// Balanced reasoning (good default).
    #[default]
    Medium,
    /// Maximum reasoning (slowest, highest quality).
    High,
}

impl fmt::Display for OllamaThinkType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OllamaThinkType::Off => f.write_str("off"),
            OllamaThinkType::Low => f.write_str("low"),
            OllamaThinkType::Medium => f.write_str("medium"),
            OllamaThinkType::High => f.write_str("high"),
        }
    }
}

impl FromStr for OllamaThinkType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "off" | "false" | "0" => Ok(OllamaThinkType::Off),
            "low" => Ok(OllamaThinkType::Low),
            "medium" | "mid" => Ok(OllamaThinkType::Medium),
            "high" => Ok(OllamaThinkType::High),
            _ => Err(format!(
                "Unknown think type '{}'. Valid values: off, low, medium, high",
                s
            )),
        }
    }
}

/// Persisted application settings — pure data type with no I/O.
///
/// Use `SettingsStore` to load and save instances of this type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)] // fall back to field defaults if any field is missing
pub struct Settings {
    #[serde(default)]
    pub last_provider: ProviderKind,
    /// Per-provider URL overrides. Keyed by `ProviderKind` so switching
    /// providers remembers each one's last URL. Migrated from the legacy
    /// `last_provider_url` field on load.
    /// (default: empty)
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub provider_urls: HashMap<ProviderKind, String>,
    /// Per-provider model selections. Keyed by `ProviderKind` so switching
    /// providers remembers each one's last model. Migrated from the legacy
    /// `last_model` field on load.
    /// (default: empty)
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub provider_models: HashMap<ProviderKind, String>,
    #[serde(default)]
    pub preferred_mode: AgentMode,
    #[serde(default)]
    pub ollama_api_key: Option<SecretString>,
    /// API key sent as `Authorization: Bearer <key>` by the OpenAI-compatible
    /// provider (`--openai-compat`). Set via `--api-key` or `OPENAI_API_KEY`
    /// env var. Not used by Ollama, llama.cpp, vLLM, or Sockudo.
    pub openai_compat_api_key: Option<SecretString>,
    /// Sockudo app ID for the AI Transport provider.
    pub sockudo_app_id: Option<String>,
    /// Sockudo app key (used as auth_key in signed API requests and WebSocket URL).
    pub sockudo_app_key: Option<String>,
    /// Sockudo app secret (used to sign API requests via HMAC-SHA256).
    pub sockudo_app_secret: Option<SecretString>,
    /// Timeout in seconds for Ollama requests (default: 5)
    #[serde(default)]
    pub ollama_timeout_secs: u64,
    /// Maximum number of retries for Ollama requests (default: 3)
    #[serde(default)]
    pub ollama_max_retries: u32,
    /// Controls the think/reasoning level for Ollama (default: Medium)
    #[serde(default)]
    pub ollama_think_type: OllamaThinkType,
    /// Show the model's thinking/reasoning chain inline during streaming (default: true)
    #[serde(default)]
    pub show_thinking: bool,
    /// Context limit for warning calculations only (default: None, uses model default)
    pub context_limit: Option<u32>,
    /// Control how aggressively tool calls are auto-approved:
    /// - `off`   – never auto-accept (prompt for everything)
    /// - `safe`  – auto-accept read-only commands (default)
    /// - `all`   – auto-accept every tool call (dangerous)
    ///
    /// Parsed from `/autoaccept` command. Use `safe` for everyday use.
    ///
    /// Legacy boolean configs are also accepted via field resolution
    /// in `SettingsStore::load()`.
    #[serde(default)]
    pub auto_accept_mode: AutoAcceptMode,
    /// Skip the provider health check at startup (default: false).
    /// Useful for the `--openai-compat` provider when the gateway requires a
    /// separate scope on `/health`, or for any server without a `/health`
    /// endpoint. When true, the agent proceeds straight to model selection
    /// and reports any connection error on the first real request instead.
    pub skip_health_check: bool,
    /// List of command prefixes considered safe for auto-accept (default: see get_default_safe_commands)
    pub safe_command_prefixes: Option<Vec<String>>,
    /// List of command prefixes that are always denied auto-accept, even if they
    /// match a safe prefix. Takes priority over the safe list. (default: empty)
    pub denied_command_prefixes: Option<Vec<String>>,
    /// Override the project instruction file discovery list.
    /// When set, replaces the hardcoded default list (TINYHARNESS.md, AGENTS.md, etc.).
    /// Use `TINYHARNESS_MD_FILES` env var for the highest priority override.
    /// (default: None → use hardcoded defaults)
    pub project_md_files: Option<Vec<String>>,
    /// Enable auto-compact tool (default: true).
    /// When false, the auto_compact tool is not registered with the provider,
    /// so the model cannot request conversation compaction.
    #[serde(default = "default_true")]
    pub auto_compact_enabled: bool,
}

fn default_true() -> bool {
    true
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            last_provider: ProviderKind::Ollama,
            provider_urls: HashMap::new(),
            provider_models: HashMap::new(),
            preferred_mode: AgentMode::Casual,
            ollama_api_key: None,
            openai_compat_api_key: None,
            sockudo_app_id: None,
            sockudo_app_key: None,
            sockudo_app_secret: None,
            ollama_timeout_secs: 5,
            ollama_max_retries: 3,
            ollama_think_type: OllamaThinkType::Medium,
            show_thinking: true,
            context_limit: None,
            auto_accept_mode: AutoAcceptMode::Safe,
            skip_health_check: false,
            safe_command_prefixes: None,
            denied_command_prefixes: None,
            project_md_files: None,
            auto_compact_enabled: true,
        }
    }
}

/// Returns the default list of safe command prefixes.
/// These are read-only commands that don't modify the filesystem.
pub fn get_default_safe_commands() -> Vec<String> {
    vec![
        "cd".to_string(),
        "ls".to_string(),
        "grep".to_string(),
        "glob".to_string(),
        "find".to_string(),
        "cat".to_string(),
        "head".to_string(),
        "tail".to_string(),
        "wc".to_string(),
        "pwd".to_string(),
        "echo".to_string(),
        "printf".to_string(),
        "tree".to_string(),
        "file".to_string(),
        "stat".to_string(),
        "du".to_string(),
        "df".to_string(),
        "free".to_string(),
        "uptime".to_string(),
        "whoami".to_string(),
        "hostname".to_string(),
        "uname".to_string(),
        "date".to_string(),
        "cal".to_string(),
        "ps".to_string(),
        "env".to_string(),
        "printenv".to_string(),
        "which".to_string(),
        "whereis".to_string(),
        "type".to_string(),
        "git status".to_string(),
        "git diff".to_string(),
        "git log".to_string(),
        "git show".to_string(),
        "git branch".to_string(),
        "git remote".to_string(),
        "git tag".to_string(),
        "git describe".to_string(),
        "git rev-parse".to_string(),
        "cargo tree".to_string(),
        "cargo metadata".to_string(),
        "cargo doc".to_string(),
        "rustc --version".to_string(),
        "cargo --version".to_string(),
    ]
}

impl Settings {
    /// Returns the list of safe command prefixes, using defaults if not configured.
    pub fn get_safe_commands(&self) -> Vec<String> {
        self.safe_command_prefixes
            .clone()
            .unwrap_or_else(get_default_safe_commands)
    }

    /// Returns the list of always-denied command prefixes.
    /// These take priority over the safe list — if a command matches both
    /// a safe prefix and a denied prefix, it is denied.
    /// Defaults to an empty list (nothing denied).
    pub fn get_denied_commands(&self) -> Vec<String> {
        self.denied_command_prefixes.clone().unwrap_or_default()
    }

    /// Get the saved URL for a specific provider kind, if any.
    pub fn get_url_for(&self, kind: ProviderKind) -> Option<&str> {
        self.provider_urls.get(&kind).map(|s| s.as_str())
    }

    /// Set the URL for a specific provider kind.
    pub fn set_url_for(&mut self, kind: ProviderKind, url: String) {
        self.provider_urls.insert(kind, url);
    }

    /// Get the saved model for a specific provider kind, if any.
    pub fn get_model_for(&self, kind: ProviderKind) -> Option<&str> {
        self.provider_models.get(&kind).map(|s| s.as_str())
    }

    /// Set the model for a specific provider kind.
    pub fn set_model_for(&mut self, kind: ProviderKind, model: String) {
        self.provider_models.insert(kind, model);
    }

    /// Get the saved model for the current (`last_provider`) kind, if any.
    pub fn get_current_model(&self) -> Option<&str> {
        self.get_model_for(self.last_provider)
    }

    /// Get the saved URL for the current (`last_provider`) kind, if any.
    pub fn get_current_url(&self) -> Option<&str> {
        self.get_url_for(self.last_provider)
    }
}

// ── Errors ──────────────────────────────────────────────────────────────────

/// Error type for settings I/O operations.
#[derive(Debug)]
pub enum SettingsError {
    Io(std::io::Error),
    Parse(serde_json::Error),
}

impl std::fmt::Display for SettingsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SettingsError::Io(e) => write!(f, "I/O error: {}", e),
            SettingsError::Parse(e) => write!(f, "parse error: {}", e),
        }
    }
}

impl std::error::Error for SettingsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SettingsError::Io(e) => Some(e),
            SettingsError::Parse(e) => Some(e),
        }
    }
}

impl From<std::io::Error> for SettingsError {
    fn from(e: std::io::Error) -> Self {
        SettingsError::Io(e)
    }
}

impl From<serde_json::Error> for SettingsError {
    fn from(e: serde_json::Error) -> Self {
        SettingsError::Parse(e)
    }
}

// ── Settings store ─────────────────────────────────────────────────────────

/// Handles persistence of [`Settings`] to disk.
///
/// By default, uses `~/.config/tinyharness/settings.json`. This can be
/// overridden with [`SettingsStore::new`] for testing or alternative paths.
pub struct SettingsStore {
    path: std::path::PathBuf,
}

impl SettingsStore {
    /// Create a store that reads/writes from the default path
    /// (`~/.config/tinyharness/settings.json`).
    pub fn default_path() -> Self {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
        let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
        SettingsStore { path }
    }

    /// Create a store that reads/writes from a custom path.
    pub fn new(path: std::path::PathBuf) -> Self {
        SettingsStore { path }
    }

    /// Load settings from disk.
    ///
    /// Returns `Ok(Settings)` with defaults if the file doesn't exist,
    /// or an error if the file exists but cannot be parsed.
    pub fn load(&self) -> Result<Settings, SettingsError> {
        // Clean up any stale temp files from a previous interrupted save.
        // These would be named `.settings.json.tmp.<pid>.<timestamp>`.
        self.cleanup_stale_temp_files();

        if !self.path.exists() {
            return Ok(Settings::default());
        }
        let content = std::fs::read_to_string(&self.path)?;
        let mut settings: Settings = serde_json::from_str(&content)?;

        // Legacy field resolution: old configs used `auto_accept_safe_commands: bool`
        // or `auto_accept_all: bool` instead of `auto_accept_mode`.
        // Only resolve if `auto_accept_mode` was NOT present in the JSON —
        // the current value is just the default (Safe).
        if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
            && let Some(obj) = raw.as_object()
            && !obj.contains_key("auto_accept_mode")
        {
            // auto_accept_all: true → All, false → Off
            if let Some(val) = obj.get("auto_accept_all") {
                if val.as_bool() == Some(true) {
                    settings.auto_accept_mode = AutoAcceptMode::All;
                } else if val.as_bool() == Some(false) {
                    settings.auto_accept_mode = AutoAcceptMode::Off;
                }
            }
            // auto_accept_safe_commands: false → Off (was "don't auto-accept safe cmds")
            // auto_accept_safe_commands: true → Safe (already default, no change)
            else if let Some(val) = obj.get("auto_accept_safe_commands")
                && val.as_bool() == Some(false)
            {
                settings.auto_accept_mode = AutoAcceptMode::Off;
            }
        }

        // Migrate legacy `last_model` and `last_provider_url` fields into
        // the per-provider HashMaps. The key is `last_provider` (the
        // provider that was active when the old config was saved).
        if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
            && let Some(obj) = raw.as_object()
        {
            if settings.provider_models.is_empty()
                && let Some(model) = obj.get("last_model")
                && let Some(model_str) = model.as_str()
                && !model_str.is_empty()
            {
                settings
                    .provider_models
                    .insert(settings.last_provider, model_str.to_string());
            }
            if settings.provider_urls.is_empty()
                && let Some(url) = obj.get("last_provider_url")
                && let Some(url_str) = url.as_str()
                && !url_str.is_empty()
            {
                settings
                    .provider_urls
                    .insert(settings.last_provider, url_str.to_string());
            }
        }

        Ok(settings)
    }

    /// Remove stale temp files from interrupted saves.
    ///
    /// These match the pattern `.settings.json.tmp.*` in the settings
    /// directory. They're left behind if the process was killed (e.g.
    /// Ctrl+C or SIGTERM) between `File::create` and `rename`.
    fn cleanup_stale_temp_files(&self) {
        let Some(dir) = self.path.parent() else {
            return;
        };
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.starts_with(".settings.json.tmp.")
                && let Err(e) = std::fs::remove_file(entry.path())
            {
                tracing::debug!("Could not remove stale temp file {name}: {e}");
            }
        }
    }

    /// Load settings from disk, returning defaults on any error.
    ///
    /// This matches the original behaviour and is suitable for application
    /// startup where you don't want to fail on corrupt settings files.
    /// If the file is present but unparseable, it is renamed to
    /// `settings.json.corrupt` so the user can recover their data.
    pub fn load_or_default(&self) -> Settings {
        self.load().unwrap_or_else(|e| {
            tracing::warn!("Failed to load settings: {e}. Using defaults.");
            // Back up the corrupted file so the user can recover their data.
            // Without this, the next save_settings() call would silently
            // overwrite the corrupted file with defaults, permanently losing
            // the user's configuration.
            if self.path.exists() {
                let backup = self.path.with_extension("json.corrupt");
                if let Err(backup_err) = std::fs::rename(&self.path, &backup) {
                    tracing::warn!(
                        "Could not back up corrupt settings to {}: {backup_err}",
                        backup.display(),
                    );
                } else {
                    tracing::warn!("Corrupt settings backed up to {}", backup.display(),);
                }
            }
            Settings::default()
        })
    }

    /// Save settings to disk atomically (write to temp file, fsync, then rename).
    ///
    /// Uses a unique temp file name (with PID) to avoid collisions if two
    /// saves overlap. The temp file is fsync'd before the rename to ensure
    /// data durability — without this, a crash after rename but before the
    /// kernel flushes the data could leave an empty or partial file.
    pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
        let dir = self.path.parent().ok_or_else(|| {
            SettingsError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "settings path has no parent directory",
            ))
        })?;
        std::fs::create_dir_all(dir)?;

        let json = serde_json::to_string_pretty(settings)?;

        // Unique temp file name to avoid collisions between concurrent saves.
        // Using PID + a timestamp makes it extremely unlikely two processes
        // would write to the same temp path.
        let tmp_name = format!(
            ".settings.json.tmp.{}.{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0),
        );
        let tmp_path = dir.join(&tmp_name);

        // Write to the temp file, fsync its data, then close.
        {
            let mut file = std::fs::File::create(&tmp_path)?;
            std::io::Write::write_all(&mut file, json.as_bytes())?;
            std::io::Write::flush(&mut file)?;
            // fsync the file data so it's on disk before we rename.
            // This is the key to crash-safety: if the system crashes
            // after the rename but before the data is flushed, we'd
            // get an empty file. fsync ensures the data is durable.
            file.sync_all()?;
        }

        // Rename is atomic on POSIX systems (same filesystem).
        std::fs::rename(&tmp_path, &self.path)?;
        Ok(())
    }

    /// Returns the path where settings are stored.
    pub fn path(&self) -> &std::path::Path {
        &self.path
    }
}

// ── Free convenience functions ─────────────────────────────────────────────

/// Load settings from the default path, returning defaults on any error.
///
/// This is a convenience wrapper around
/// [`SettingsStore::default_path`] followed by [`SettingsStore::load_or_default`].
pub fn load_settings() -> Settings {
    SettingsStore::default_path().load_or_default()
}

/// Save settings to the default path atomically.
///
/// This is a convenience wrapper around
/// [`SettingsStore::default_path`] followed by [`SettingsStore::save`].
/// On error, prints a warning to stderr (matching the original behaviour).
pub fn save_settings(settings: &Settings) {
    let store = SettingsStore::default_path();
    if let Err(e) = store.save(settings) {
        tracing::warn!("Failed to save settings: {e}");
    }
}

// ── Prompt file management ──────────────────────────────────────────────────

/// Resolve the effective list of project instruction file names to discover.
///
/// Priority (highest first):
/// 1. `TINYHARNESS_MD_FILES` env var (comma-separated)
/// 2. `settings.project_md_files` from global settings
/// 3. Hardcoded default: TINYHARNESS.md, .tinyharness.md, AGENTS.md, CLAUDE.md
pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
    // 1. Env var takes highest priority
    if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
        let files: Vec<String> = env
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        if !files.is_empty() {
            return files;
        }
    }

    // 2. Settings override
    if let Some(s) = settings
        && let Some(ref configured) = s.project_md_files
        && !configured.is_empty()
    {
        return configured.clone();
    }

    // 3. Hardcoded defaults
    crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
        .iter()
        .map(|s| s.to_string())
        .collect()
}

/// Returns the directory where per-mode prompt `.md` files are stored.
///
/// Default: `~/.config/tinyharness/prompts/`
pub fn prompts_dir() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home)
        .join(".config")
        .join("tinyharness")
        .join("prompts")
}

/// Ensure the prompts directory exists and is seeded with `.md` files
/// containing the hardcoded defaults for each mode, plus the shared header.
///
/// On first launch, this creates `~/.config/tinyharness/prompts/` and writes
/// `header.md`, `casual.md`, `planning.md`, `agent.md`, and `research.md`.
/// Existing files are **never** overwritten — users can safely customize them.
///
/// Returns the prompts directory path.
pub fn ensure_prompts_initialized() -> PathBuf {
    let dir = prompts_dir();
    if !dir.exists() {
        std::fs::create_dir_all(&dir).ok();
    }

    // Write shared header (new in 0.2 — always writes if missing)
    {
        let header_path = dir.join("header.md");
        if !header_path.exists() {
            let header_text = include_str!("../prompts/header.md");
            if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
                tracing::warn!(
                    "Failed to write default header to {}: {e}",
                    header_path.display(),
                );
            }
        }
    }

    let modes = [
        AgentMode::Casual,
        AgentMode::Planning,
        AgentMode::Agent,
        AgentMode::Research,
    ];

    for mode in &modes {
        let file_path = dir.join(mode.prompts_filename());
        if !file_path.exists() {
            let default_text = mode.default_system_prompt();
            // Write the default, trimming leading/trailing whitespace/newlines
            if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
                tracing::warn!(
                    "Failed to write default prompt to {}: {e}",
                    file_path.display(),
                );
            }
        }
    }

    dir
}

// ── Tests ──────────────────────────────────────────────────────────────────

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

    /// User settings from a future build (with `auto_accept_mode`) must load
    /// against the current `Settings` struct without parse errors.
    #[test]
    fn load_settings_missing_fields_uses_defaults() {
        let json = r#"{
            "last_provider": "OpenAiCompat",
            "last_provider_url": "http://localhost:8080/v1",
            "last_model": "MiniMax-M3",
            "preferred_mode": "Agent",
            "ollama_api_key": null,
            "openai_compat_api_key": "sk-test",
            "ollama_timeout_secs": 5,
            "ollama_max_retries": 3,
            "ollama_think_type": "High",
            "show_thinking": true,
            "context_limit": 256000,
            "auto_accept_mode": "all",
            "skip_health_check": true
        }"#;

        let settings: Settings =
            serde_json::from_str(json).expect("missing fields should use defaults");
        assert_eq!(settings.last_provider, ProviderKind::OpenAiCompat);
        assert_eq!(settings.preferred_mode, AgentMode::Agent);
        // Missing fields default gracefully:
        assert!(settings.skip_health_check);
        assert_eq!(settings.ollama_think_type, OllamaThinkType::High);
    }

    /// An empty settings object should load with all defaults.
    #[test]
    fn load_settings_empty_object_uses_all_defaults() {
        let settings: Settings =
            serde_json::from_str("{}").expect("empty object should use defaults");
        assert_eq!(settings.last_provider, ProviderKind::Ollama);
        assert_eq!(settings.preferred_mode, AgentMode::Casual);
        assert!(!settings.skip_health_check);
    }

    #[test]
    fn auto_accept_mode_from_string() {
        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "all"}"#).unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);

        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "off"}"#).unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);

        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "safe"}"#).unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
    }

    #[test]
    fn auto_accept_mode_from_legacy_bool() {
        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": true}"#).unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);

        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": false}"#).unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
    }
    #[test]
    fn auto_accept_mode_from_legacy_all_field() {
        // auto_accept_all: true → All via load() resolution
        let store = SettingsStore::new(temp_settings_path());
        let json = r#"{"auto_accept_all": true}"#;
        std::fs::write(store.path(), json).unwrap();
        let settings = store.load().unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
        let _ = std::fs::remove_file(store.path());

        // auto_accept_all: false → Off
        let store = SettingsStore::new(temp_settings_path());
        let json = r#"{"auto_accept_all": false}"#;
        std::fs::write(store.path(), json).unwrap();
        let settings = store.load().unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
        let _ = std::fs::remove_file(store.path());
    }
    #[test]
    fn auto_accept_mode_from_legacy_safe_commands_field() {
        // auto_accept_safe_commands: false → Off via load() resolution
        let store = SettingsStore::new(temp_settings_path());
        let json = r#"{"auto_accept_safe_commands": false}"#;
        std::fs::write(store.path(), json).unwrap();
        let settings = store.load().unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
        let _ = std::fs::remove_file(store.path());

        // auto_accept_safe_commands: true → Safe (default, no change)
        let store = SettingsStore::new(temp_settings_path());
        let json = r#"{"auto_accept_safe_commands": true}"#;
        std::fs::write(store.path(), json).unwrap();
        let settings = store.load().unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
        let _ = std::fs::remove_file(store.path());
    }

    #[test]
    fn auto_accept_mode_explicit_overrides_legacy() {
        // Explicit auto_accept_mode string wins over alias
        let settings: Settings =
            serde_json::from_str(r#"{"auto_accept_mode": "off", "auto_accept_all": true}"#)
                .unwrap();
        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
    }

    #[test]
    fn migrate_legacy_last_model_and_url() {
        let store = SettingsStore::new(temp_settings_path());
        let json = r#"{"last_provider": "Ollama", "last_model": "qwen2.5:7b", "last_provider_url": "http://localhost:11434"}"#;
        std::fs::write(store.path(), json).unwrap();
        let settings = store.load().unwrap();
        assert_eq!(
            settings.get_model_for(ProviderKind::Ollama),
            Some("qwen2.5:7b")
        );
        assert_eq!(
            settings.get_url_for(ProviderKind::Ollama),
            Some("http://localhost:11434")
        );
        let _ = std::fs::remove_file(store.path());
    }

    #[test]
    fn migrate_legacy_fields_for_openai_compat() {
        let store = SettingsStore::new(temp_settings_path());
        let json = r#"{"last_provider": "OpenAiCompat", "last_model": "gpt-4o", "last_provider_url": "https://api.openai.com/v1"}"#;
        std::fs::write(store.path(), json).unwrap();
        let settings = store.load().unwrap();
        assert_eq!(
            settings.get_model_for(ProviderKind::OpenAiCompat),
            Some("gpt-4o")
        );
        assert_eq!(
            settings.get_url_for(ProviderKind::OpenAiCompat),
            Some("https://api.openai.com/v1")
        );
        // Ollama should NOT have a model from this migration
        assert_eq!(settings.get_model_for(ProviderKind::Ollama), None);
        let _ = std::fs::remove_file(store.path());
    }

    #[test]
    fn per_provider_model_and_url_accessors() {
        let mut settings = Settings::default();
        settings.set_model_for(ProviderKind::Ollama, "qwen2.5:7b".to_string());
        settings.set_model_for(ProviderKind::LlamaCpp, "llama-3.1-8b".to_string());
        settings.set_url_for(ProviderKind::LlamaCpp, "http://localhost:8080".to_string());

        assert_eq!(
            settings.get_model_for(ProviderKind::Ollama),
            Some("qwen2.5:7b")
        );
        assert_eq!(
            settings.get_model_for(ProviderKind::LlamaCpp),
            Some("llama-3.1-8b")
        );
        assert_eq!(settings.get_model_for(ProviderKind::Vllm), None);
        assert_eq!(
            settings.get_url_for(ProviderKind::LlamaCpp),
            Some("http://localhost:8080")
        );
        assert_eq!(settings.get_url_for(ProviderKind::Ollama), None);
    }

    #[test]
    fn get_current_model_and_url_use_last_provider() {
        let mut settings = Settings {
            last_provider: ProviderKind::OpenAiCompat,
            ..Settings::default()
        };
        settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
        settings.set_url_for(
            ProviderKind::OpenAiCompat,
            "https://api.openai.com/v1".to_string(),
        );

        assert_eq!(settings.get_current_model(), Some("gpt-4o"));
        assert_eq!(
            settings.get_current_url(),
            Some("https://api.openai.com/v1")
        );
    }

    fn temp_settings_path() -> std::path::PathBuf {
        // Use a unique subdirectory per test to avoid interference between
        // parallel tests (especially the stale-temp-file cleanup which scans
        // the parent directory).
        let mut dir = std::env::temp_dir();
        dir.push(format!(
            "tinyharness_test_{}_{}_{:?}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0),
            std::thread::current().id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir.push("settings.json");
        dir
    }

    // ── Config corruption resilience tests ───────────────────────────────

    /// Saving and loading should round-trip correctly.
    #[test]
    fn save_and_load_roundtrip() {
        let store = SettingsStore::new(temp_settings_path());
        let mut settings = Settings {
            last_provider: ProviderKind::OpenAiCompat,
            auto_accept_mode: AutoAcceptMode::All,
            ..Settings::default()
        };
        settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());

        store.save(&settings).unwrap();
        let loaded = store.load().unwrap();
        assert_eq!(loaded.last_provider, ProviderKind::OpenAiCompat);
        assert_eq!(
            loaded.get_model_for(ProviderKind::OpenAiCompat),
            Some("gpt-4o")
        );
        assert_eq!(loaded.auto_accept_mode, AutoAcceptMode::All);

        // Clean up
        let dir = store.path().parent().unwrap();
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Loading a corrupt settings file should return defaults and back up
    /// the corrupt file to `settings.json.corrupt`.
    #[test]
    fn corrupt_settings_backed_up_and_defaults_returned() {
        let store = SettingsStore::new(temp_settings_path());
        let corrupt_json = "{ this is not valid json !!!";
        std::fs::write(store.path(), corrupt_json).unwrap();

        let settings = store.load_or_default();
        assert_eq!(settings.last_provider, ProviderKind::Ollama);
        assert_eq!(settings.preferred_mode, AgentMode::Casual);

        // The corrupt file should have been renamed to .corrupt
        assert!(!store.path().exists());
        let backup = store.path().with_extension("json.corrupt");
        assert!(backup.exists(), "corrupt settings should be backed up");

        // Verify the backup contains the original corrupt data
        let backup_content = std::fs::read_to_string(&backup).unwrap();
        assert_eq!(backup_content, corrupt_json);

        // Clean up
        let dir = store.path().parent().unwrap();
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Stale temp files from interrupted saves should be cleaned up on load.
    #[test]
    fn stale_temp_files_cleaned_up_on_load() {
        let store = SettingsStore::new(temp_settings_path());
        let dir = store.path().parent().unwrap();
        let tmp1 = dir.join(".settings.json.tmp.12345.999999999");
        let tmp2 = dir.join(".settings.json.tmp.67890.888888888");
        std::fs::write(&tmp1, "stale data").unwrap();
        std::fs::write(&tmp2, "more stale data").unwrap();
        assert!(tmp1.exists());
        assert!(tmp2.exists());

        // Load should clean up stale temp files
        let _ = store.load();

        assert!(!tmp1.exists(), "stale temp file should be removed");
        assert!(!tmp2.exists(), "stale temp file should be removed");

        // Clean up
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Save should not leave temp files behind on success.
    #[test]
    fn save_leaves_no_temp_files() {
        let store = SettingsStore::new(temp_settings_path());
        store.save(&Settings::default()).unwrap();

        let dir = store.path().parent().unwrap();
        let entries = std::fs::read_dir(dir).unwrap();
        for entry in entries.flatten() {
            let name = entry.file_name();
            assert!(
                !name.to_string_lossy().starts_with(".settings.json.tmp."),
                "no temp files should remain after successful save"
            );
        }

        let _ = std::fs::remove_dir_all(dir);
    }

    /// Multiple saves should not corrupt the settings file.
    #[test]
    fn multiple_saves_are_consistent() {
        let store = SettingsStore::new(temp_settings_path());

        for i in 0..10 {
            let settings = Settings {
                ollama_timeout_secs: i,
                ..Settings::default()
            };
            store.save(&settings).unwrap();
        }

        let loaded = store.load().unwrap();
        assert_eq!(loaded.ollama_timeout_secs, 9);

        let dir = store.path().parent().unwrap();
        let _ = std::fs::remove_dir_all(dir);
    }
}