Skip to main content

tinyharness_lib/config/
mod.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::{fmt, str::FromStr};
4
5use serde::{Deserialize, Serialize};
6
7use crate::SecretString;
8use crate::mode::AgentMode;
9
10// ── AutoAccept Mode ────────────────────────────────────────────────────────
11
12/// Controls how aggressively tool calls are auto-approved.
13///
14/// Parsed from string values for JSON config: `"off"`, `"safe"`, `"all"`.
15/// Legacy boolean fields (`auto_accept_all`, `auto_accept_safe_commands`)
16/// are resolved in `SettingsStore::load()` when `auto_accept_mode` is absent.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
18#[serde(rename_all = "lowercase")]
19pub enum AutoAcceptMode {
20    Off,
21    #[default]
22    Safe,
23    All,
24}
25
26impl<'de> Deserialize<'de> for AutoAcceptMode {
27    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
28    where
29        D: serde::Deserializer<'de>,
30    {
31        struct AutoAcceptModeVisitor;
32
33        impl<'de> serde::de::Visitor<'de> for AutoAcceptModeVisitor {
34            type Value = AutoAcceptMode;
35
36            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
37                formatter
38                    .write_str("a string (\"off\", \"safe\", \"all\") or a boolean (true/false)")
39            }
40
41            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
42            where
43                E: serde::de::Error,
44            {
45                Ok(if v {
46                    AutoAcceptMode::All
47                } else {
48                    AutoAcceptMode::Off
49                })
50            }
51
52            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
53            where
54                E: serde::de::Error,
55            {
56                AutoAcceptMode::from_str(v).map_err(serde::de::Error::custom)
57            }
58
59            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
60            where
61                E: serde::de::Error,
62            {
63                AutoAcceptMode::from_str(&v).map_err(serde::de::Error::custom)
64            }
65        }
66
67        deserializer.deserialize_any(AutoAcceptModeVisitor)
68    }
69}
70
71impl FromStr for AutoAcceptMode {
72    type Err = String;
73
74    fn from_str(s: &str) -> Result<Self, Self::Err> {
75        match s.to_lowercase().as_str() {
76            "off" | "false" | "no" | "0" | "disabled" => Ok(AutoAcceptMode::Off),
77            "safe" | "on" => Ok(AutoAcceptMode::Safe),
78            "all" | "always" | "true" | "yes" | "1" | "enabled" => Ok(AutoAcceptMode::All),
79            _ => Err(format!(
80                "Unknown auto-accept mode '{}'. Valid values: off, safe, all",
81                s
82            )),
83        }
84    }
85}
86
87impl fmt::Display for AutoAcceptMode {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            AutoAcceptMode::Off => write!(f, "off"),
91            AutoAcceptMode::Safe => write!(f, "safe"),
92            AutoAcceptMode::All => write!(f, "all"),
93        }
94    }
95}
96
97// ── Project Settings ────────────────────────────────────────────────────────
98
99/// Per-project override settings discovered from `.tinyharness/config.json`.
100///
101/// All fields are `Option` — only present fields override the global setting.
102/// Discovery walks up from CWD, same algorithm as `discover_project_md`.
103#[derive(Debug, Clone, Serialize, Deserialize, Default)]
104pub struct ProjectSettings {
105    /// Override safe command prefixes (extends, doesn't replace)
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub safe_command_prefixes: Option<Vec<String>>,
108    /// Override denied command prefixes
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub denied_command_prefixes: Option<Vec<String>>,
111    /// Override auto-accept mode for this project
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub auto_accept_mode: Option<AutoAcceptMode>,
114    /// Override context_limit
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub context_limit: Option<u32>,
117    /// Additional project-specific MD file names to include in context
118    /// (e.g. ["RULES.md", ".cursorrules"]). These are loaded AFTER the main
119    /// project instruction file.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub project_md_files: Option<Vec<String>>,
122    /// Override the preferred mode for this project
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub preferred_mode: Option<AgentMode>,
125    /// Override auto-compact enabled setting for this project
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub auto_compact_enabled: Option<bool>,
128    /// Override whether the model may ask questions for this project
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub questions_enabled: Option<bool>,
131}
132
133/// Discover and load `.tinyharness/config.json` by walking up from CWD.
134///
135/// Returns `None` if no config file is found. Returns `Some(Err(...))` if
136/// a file is found but cannot be parsed.
137pub fn discover_project_settings(
138    start_dir: &std::path::Path,
139) -> Option<Result<ProjectSettings, SettingsError>> {
140    let mut dir = start_dir.to_path_buf();
141
142    loop {
143        let candidate = dir.join(".tinyharness").join("config.json");
144        if candidate.is_file() {
145            let content = match std::fs::read_to_string(&candidate) {
146                Ok(c) => c,
147                Err(e) => return Some(Err(SettingsError::Io(e))),
148            };
149            let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
150            return Some(parsed);
151        }
152
153        // Walk up one directory
154        if let Some(parent) = dir.parent() {
155            if parent == dir {
156                break;
157            }
158            dir = parent.to_path_buf();
159        } else {
160            break;
161        }
162    }
163
164    None
165}
166
167/// Source annotation for merged settings values.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum SettingSource {
170    /// Value came from the global `~/.config/tinyharness/settings.json`
171    Global,
172    /// Value came from `.tinyharness/config.json`
173    Project,
174    /// Value is the hardcoded default (no config found)
175    Default,
176}
177
178impl std::fmt::Display for SettingSource {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        match self {
181            SettingSource::Global => f.write_str("global"),
182            SettingSource::Project => f.write_str("project"),
183            SettingSource::Default => f.write_str("default"),
184        }
185    }
186}
187
188/// Effective merged settings — the result of layering global + project settings.
189///
190/// This is a read-only view. Each field has a source annotation for display.
191#[derive(Debug, Clone)]
192pub struct MergedSettings {
193    /// Merged safe command prefixes (project extends global)
194    pub safe_commands: Vec<String>,
195    pub safe_commands_source: SettingSource,
196    /// Merged denied command prefixes (project overrides global)
197    pub denied_commands: Vec<String>,
198    pub denied_commands_source: SettingSource,
199    pub auto_accept_mode: AutoAcceptMode,
200    pub auto_accept_mode_source: SettingSource,
201    pub context_limit: Option<u32>,
202    pub context_limit_source: SettingSource,
203    pub project_md_files: Vec<String>,
204    pub project_md_files_source: SettingSource,
205    pub preferred_mode: AgentMode,
206    pub preferred_mode_source: SettingSource,
207    pub auto_compact_enabled: bool,
208    pub auto_compact_enabled_source: SettingSource,
209    pub questions_enabled: bool,
210    pub questions_enabled_source: SettingSource,
211}
212
213/// Load and merge global + project settings.
214///
215/// Layering: project overrides global where specified, otherwise falls back
216/// to global. For safe commands, project *extends* the global list rather
217/// than replacing it.
218pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
219    let global = load_settings();
220
221    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
222    let project = match discover_project_settings(&cwd) {
223        Some(Ok(ps)) => Some(ps),
224        Some(Err(e)) => {
225            tracing::warn!(
226                "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
227            );
228            None
229        }
230        None => None,
231    };
232
233    let merged = merge_settings(&global, project.as_ref());
234    (global, project, merged)
235}
236
237/// Merge global settings with optional project overrides.
238fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
239    let global_safe = global.get_safe_commands();
240    let global_denied = global.get_denied_commands();
241
242    match project {
243        None => MergedSettings {
244            safe_commands: global_safe,
245            safe_commands_source: SettingSource::Default,
246            denied_commands: global_denied,
247            denied_commands_source: SettingSource::Default,
248            auto_accept_mode: global.auto_accept_mode,
249            auto_accept_mode_source: SettingSource::Default,
250            context_limit: global.context_limit,
251            context_limit_source: SettingSource::Default,
252            project_md_files: Vec::new(),
253            project_md_files_source: SettingSource::Default,
254            preferred_mode: global.preferred_mode,
255            preferred_mode_source: SettingSource::Default,
256            auto_compact_enabled: global.auto_compact_enabled,
257            auto_compact_enabled_source: SettingSource::Default,
258            questions_enabled: global.questions_enabled,
259            questions_enabled_source: SettingSource::Default,
260        },
261        Some(p) => {
262            // Safe commands: project extends global
263            let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
264                let mut combined = global_safe.clone();
265                for cmd in proj_safe {
266                    if !combined.contains(cmd) {
267                        combined.push(cmd.clone());
268                    }
269                }
270                combined
271            } else {
272                global_safe
273            };
274            let safe_source = if p.safe_command_prefixes.is_some() {
275                SettingSource::Project
276            } else {
277                SettingSource::Default
278            };
279
280            // Denied commands: project replaces global
281            let (denied_commands, denied_source) =
282                if let Some(ref proj_denied) = p.denied_command_prefixes {
283                    (proj_denied.clone(), SettingSource::Project)
284                } else {
285                    (global_denied, SettingSource::Default)
286                };
287
288            let (auto_accept_mode, auto_source) = p
289                .auto_accept_mode
290                .map(|v| (v, SettingSource::Project))
291                .unwrap_or((global.auto_accept_mode, SettingSource::Default));
292
293            let (context_limit, ctx_source) = p
294                .context_limit
295                .map(|v| (Some(v), SettingSource::Project))
296                .unwrap_or((global.context_limit, SettingSource::Default));
297
298            let (project_md_files, md_source) = p
299                .project_md_files
300                .as_ref()
301                .map(|files| (files.clone(), SettingSource::Project))
302                .unwrap_or((Vec::new(), SettingSource::Default));
303
304            let (preferred_mode, mode_source) = p
305                .preferred_mode
306                .map(|m| (m, SettingSource::Project))
307                .unwrap_or((global.preferred_mode, SettingSource::Default));
308
309            let (auto_compact_enabled, ac_source) = p
310                .auto_compact_enabled
311                .map(|v| (v, SettingSource::Project))
312                .unwrap_or((global.auto_compact_enabled, SettingSource::Default));
313
314            let (questions_enabled, q_source) = p
315                .questions_enabled
316                .map(|v| (v, SettingSource::Project))
317                .unwrap_or((global.questions_enabled, SettingSource::Default));
318
319            MergedSettings {
320                safe_commands,
321                safe_commands_source: safe_source,
322                denied_commands,
323                denied_commands_source: denied_source,
324                auto_accept_mode,
325                auto_accept_mode_source: auto_source,
326                context_limit,
327                context_limit_source: ctx_source,
328                project_md_files,
329                project_md_files_source: md_source,
330                preferred_mode,
331                preferred_mode_source: mode_source,
332                auto_compact_enabled,
333                auto_compact_enabled_source: ac_source,
334                questions_enabled,
335                questions_enabled_source: q_source,
336            }
337        }
338    }
339}
340
341impl MergedSettings {
342    /// Which optional tools the model is allowed to use, per merged settings.
343    pub fn tool_availability(&self) -> crate::tools::ToolAvailability {
344        crate::tools::ToolAvailability {
345            auto_compact: self.auto_compact_enabled,
346            question: self.questions_enabled,
347        }
348    }
349}
350
351/// Generate a starter `.tinyharness/config.json` file from current settings
352/// overrides that make sense for a project (safe commands, denied commands,
353/// auto-accept, context limit).
354pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
355    ProjectSettings {
356        safe_command_prefixes: settings.safe_command_prefixes.clone(),
357        denied_command_prefixes: settings.denied_command_prefixes.clone(),
358        auto_accept_mode: Some(settings.auto_accept_mode),
359        context_limit: settings.context_limit,
360        project_md_files: None, // user must fill this in
361        preferred_mode: Some(settings.preferred_mode),
362        auto_compact_enabled: Some(settings.auto_compact_enabled),
363        questions_enabled: Some(settings.questions_enabled),
364    }
365}
366
367/// Identifies which provider backend was used last.
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
369pub enum ProviderKind {
370    #[default]
371    Ollama,
372    LlamaCpp,
373    Vllm,
374    /// Generic OpenAI-compatible provider for hosted gateways (OpenRouter,
375    /// Together, etc.) that require a Bearer API key. Unlike LlamaCpp/Vllm
376    /// which target local unauthenticated servers, this provider always
377    /// sends `Authorization: Bearer <key>` and requires `--api-key` or
378    /// the `OPENAI_API_KEY` env var.
379    OpenAiCompat,
380    Sockudo,
381}
382
383impl fmt::Display for ProviderKind {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        match self {
386            ProviderKind::Ollama => f.write_str("ollama"),
387            ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
388            ProviderKind::Vllm => f.write_str("vllm"),
389            ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
390            ProviderKind::Sockudo => f.write_str("sockudo"),
391        }
392    }
393}
394
395impl FromStr for ProviderKind {
396    type Err = String;
397
398    fn from_str(s: &str) -> Result<Self, Self::Err> {
399        match s.trim().to_lowercase().as_str() {
400            "ollama" => Ok(ProviderKind::Ollama),
401            "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
402            "vllm" => Ok(ProviderKind::Vllm),
403            "openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
404            "sockudo" => Ok(ProviderKind::Sockudo),
405            _ => Err(format!("Unknown provider '{}'", s)),
406        }
407    }
408}
409
410/// Controls the "think" (reasoning) level for Ollama models that support it
411/// (e.g. qwen2.5 variants). Affects how much internal reasoning the model does
412/// before responding.
413///
414/// Corresponds to Ollama's `think` parameter. Only meaningful for Ollama;
415/// other providers ignore this setting.
416#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
417pub enum OllamaThinkType {
418    /// Disable thinking entirely (fastest, lowest quality).
419    Off,
420    /// Minimal reasoning (faster, lower latency).
421    Low,
422    /// Balanced reasoning (good default).
423    #[default]
424    Medium,
425    /// Maximum reasoning (slowest, highest quality).
426    High,
427}
428
429impl fmt::Display for OllamaThinkType {
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        match self {
432            OllamaThinkType::Off => f.write_str("off"),
433            OllamaThinkType::Low => f.write_str("low"),
434            OllamaThinkType::Medium => f.write_str("medium"),
435            OllamaThinkType::High => f.write_str("high"),
436        }
437    }
438}
439
440impl FromStr for OllamaThinkType {
441    type Err = String;
442
443    fn from_str(s: &str) -> Result<Self, Self::Err> {
444        match s.trim().to_lowercase().as_str() {
445            "off" | "false" | "0" => Ok(OllamaThinkType::Off),
446            "low" => Ok(OllamaThinkType::Low),
447            "medium" | "mid" => Ok(OllamaThinkType::Medium),
448            "high" => Ok(OllamaThinkType::High),
449            _ => Err(format!(
450                "Unknown think type '{}'. Valid values: off, low, medium, high",
451                s
452            )),
453        }
454    }
455}
456
457/// Persisted application settings — pure data type with no I/O.
458///
459/// Use `SettingsStore` to load and save instances of this type.
460#[derive(Debug, Clone, Serialize, Deserialize)]
461#[serde(default)] // fall back to field defaults if any field is missing
462pub struct Settings {
463    #[serde(default)]
464    pub last_provider: ProviderKind,
465    /// Per-provider URL overrides. Keyed by `ProviderKind` so switching
466    /// providers remembers each one's last URL. Migrated from the legacy
467    /// `last_provider_url` field on load.
468    /// (default: empty)
469    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
470    pub provider_urls: HashMap<ProviderKind, String>,
471    /// Per-provider model selections. Keyed by `ProviderKind` so switching
472    /// providers remembers each one's last model. Migrated from the legacy
473    /// `last_model` field on load.
474    /// (default: empty)
475    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
476    pub provider_models: HashMap<ProviderKind, String>,
477    #[serde(default)]
478    pub preferred_mode: AgentMode,
479    #[serde(default)]
480    pub ollama_api_key: Option<SecretString>,
481    /// API key sent as `Authorization: Bearer <key>` by the OpenAI-compatible
482    /// provider (`--openai-compat`). Set via `--api-key` or `OPENAI_API_KEY`
483    /// env var. Not used by Ollama, llama.cpp, vLLM, or Sockudo.
484    pub openai_compat_api_key: Option<SecretString>,
485    /// Sockudo app ID for the AI Transport provider.
486    pub sockudo_app_id: Option<String>,
487    /// Sockudo app key (used as auth_key in signed API requests and WebSocket URL).
488    pub sockudo_app_key: Option<String>,
489    /// Sockudo app secret (used to sign API requests via HMAC-SHA256).
490    pub sockudo_app_secret: Option<SecretString>,
491    /// Timeout in seconds for Ollama requests (default: 5)
492    #[serde(default)]
493    pub ollama_timeout_secs: u64,
494    /// Maximum number of retries for Ollama requests (default: 3)
495    #[serde(default)]
496    pub ollama_max_retries: u32,
497    /// Controls the think/reasoning level for Ollama (default: Medium)
498    #[serde(default)]
499    pub ollama_think_type: OllamaThinkType,
500    /// Show the model's thinking/reasoning chain inline during streaming (default: true)
501    #[serde(default)]
502    pub show_thinking: bool,
503    /// Context limit for warning calculations only (default: None, uses model default)
504    pub context_limit: Option<u32>,
505    /// Control how aggressively tool calls are auto-approved:
506    /// - `off`   – never auto-accept (prompt for everything)
507    /// - `safe`  – auto-accept read-only commands (default)
508    /// - `all`   – auto-accept every tool call (dangerous)
509    ///
510    /// Parsed from `/autoaccept` command. Use `safe` for everyday use.
511    ///
512    /// Legacy boolean configs are also accepted via field resolution
513    /// in `SettingsStore::load()`.
514    #[serde(default)]
515    pub auto_accept_mode: AutoAcceptMode,
516    /// Skip the provider health check at startup (default: false).
517    /// Useful for the `--openai-compat` provider when the gateway requires a
518    /// separate scope on `/health`, or for any server without a `/health`
519    /// endpoint. When true, the agent proceeds straight to model selection
520    /// and reports any connection error on the first real request instead.
521    pub skip_health_check: bool,
522    /// List of command prefixes considered safe for auto-accept (default: see get_default_safe_commands)
523    pub safe_command_prefixes: Option<Vec<String>>,
524    /// List of command prefixes that are always denied auto-accept, even if they
525    /// match a safe prefix. Takes priority over the safe list. (default: empty)
526    pub denied_command_prefixes: Option<Vec<String>>,
527    /// Override the project instruction file discovery list.
528    /// When set, replaces the hardcoded default list (TINYHARNESS.md, AGENTS.md, etc.).
529    /// Use `TINYHARNESS_MD_FILES` env var for the highest priority override.
530    /// (default: None → use hardcoded defaults)
531    pub project_md_files: Option<Vec<String>>,
532    /// Enable auto-compact tool (default: true).
533    /// When false, the auto_compact tool is not registered with the provider,
534    /// so the model cannot request conversation compaction.
535    #[serde(default = "default_true")]
536    pub auto_compact_enabled: bool,
537    /// Enable the question tool (default: true).
538    /// When false, the `question` tool is not advertised to the provider, so
539    /// the model cannot stop the agent to ask the user a multiple-choice
540    /// question. Toggle with `/questions`.
541    #[serde(default = "default_true")]
542    pub questions_enabled: bool,
543}
544
545fn default_true() -> bool {
546    true
547}
548
549impl Default for Settings {
550    fn default() -> Self {
551        Settings {
552            last_provider: ProviderKind::Ollama,
553            provider_urls: HashMap::new(),
554            provider_models: HashMap::new(),
555            preferred_mode: AgentMode::Casual,
556            ollama_api_key: None,
557            openai_compat_api_key: None,
558            sockudo_app_id: None,
559            sockudo_app_key: None,
560            sockudo_app_secret: None,
561            ollama_timeout_secs: 5,
562            ollama_max_retries: 3,
563            ollama_think_type: OllamaThinkType::Medium,
564            show_thinking: true,
565            context_limit: None,
566            auto_accept_mode: AutoAcceptMode::Safe,
567            skip_health_check: false,
568            safe_command_prefixes: None,
569            denied_command_prefixes: None,
570            project_md_files: None,
571            auto_compact_enabled: true,
572            questions_enabled: true,
573        }
574    }
575}
576
577/// Returns the default list of safe command prefixes.
578/// These are read-only commands that don't modify the filesystem.
579pub fn get_default_safe_commands() -> Vec<String> {
580    vec![
581        "cd".to_string(),
582        "ls".to_string(),
583        "grep".to_string(),
584        "glob".to_string(),
585        "find".to_string(),
586        "cat".to_string(),
587        "head".to_string(),
588        "tail".to_string(),
589        "wc".to_string(),
590        "pwd".to_string(),
591        "echo".to_string(),
592        "printf".to_string(),
593        "tree".to_string(),
594        "file".to_string(),
595        "stat".to_string(),
596        "du".to_string(),
597        "df".to_string(),
598        "free".to_string(),
599        "uptime".to_string(),
600        "whoami".to_string(),
601        "hostname".to_string(),
602        "uname".to_string(),
603        "date".to_string(),
604        "cal".to_string(),
605        "ps".to_string(),
606        "env".to_string(),
607        "printenv".to_string(),
608        "which".to_string(),
609        "whereis".to_string(),
610        "type".to_string(),
611        "git status".to_string(),
612        "git diff".to_string(),
613        "git log".to_string(),
614        "git show".to_string(),
615        "git branch".to_string(),
616        "git remote".to_string(),
617        "git tag".to_string(),
618        "git describe".to_string(),
619        "git rev-parse".to_string(),
620        "cargo tree".to_string(),
621        "cargo metadata".to_string(),
622        "cargo doc".to_string(),
623        "rustc --version".to_string(),
624        "cargo --version".to_string(),
625    ]
626}
627
628impl Settings {
629    /// Returns the list of safe command prefixes, using defaults if not configured.
630    pub fn get_safe_commands(&self) -> Vec<String> {
631        self.safe_command_prefixes
632            .clone()
633            .unwrap_or_else(get_default_safe_commands)
634    }
635
636    /// Returns the list of always-denied command prefixes.
637    /// These take priority over the safe list — if a command matches both
638    /// a safe prefix and a denied prefix, it is denied.
639    /// Defaults to an empty list (nothing denied).
640    pub fn get_denied_commands(&self) -> Vec<String> {
641        self.denied_command_prefixes.clone().unwrap_or_default()
642    }
643
644    /// Get the saved URL for a specific provider kind, if any.
645    pub fn get_url_for(&self, kind: ProviderKind) -> Option<&str> {
646        self.provider_urls.get(&kind).map(|s| s.as_str())
647    }
648
649    /// Set the URL for a specific provider kind.
650    pub fn set_url_for(&mut self, kind: ProviderKind, url: String) {
651        self.provider_urls.insert(kind, url);
652    }
653
654    /// Get the saved model for a specific provider kind, if any.
655    pub fn get_model_for(&self, kind: ProviderKind) -> Option<&str> {
656        self.provider_models.get(&kind).map(|s| s.as_str())
657    }
658
659    /// Set the model for a specific provider kind.
660    pub fn set_model_for(&mut self, kind: ProviderKind, model: String) {
661        self.provider_models.insert(kind, model);
662    }
663
664    /// Get the saved model for the current (`last_provider`) kind, if any.
665    pub fn get_current_model(&self) -> Option<&str> {
666        self.get_model_for(self.last_provider)
667    }
668
669    /// Get the saved URL for the current (`last_provider`) kind, if any.
670    pub fn get_current_url(&self) -> Option<&str> {
671        self.get_url_for(self.last_provider)
672    }
673}
674
675// ── Errors ──────────────────────────────────────────────────────────────────
676
677/// Error type for settings I/O operations.
678#[derive(Debug)]
679pub enum SettingsError {
680    Io(std::io::Error),
681    Parse(serde_json::Error),
682}
683
684impl std::fmt::Display for SettingsError {
685    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686        match self {
687            SettingsError::Io(e) => write!(f, "I/O error: {}", e),
688            SettingsError::Parse(e) => write!(f, "parse error: {}", e),
689        }
690    }
691}
692
693impl std::error::Error for SettingsError {
694    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
695        match self {
696            SettingsError::Io(e) => Some(e),
697            SettingsError::Parse(e) => Some(e),
698        }
699    }
700}
701
702impl From<std::io::Error> for SettingsError {
703    fn from(e: std::io::Error) -> Self {
704        SettingsError::Io(e)
705    }
706}
707
708impl From<serde_json::Error> for SettingsError {
709    fn from(e: serde_json::Error) -> Self {
710        SettingsError::Parse(e)
711    }
712}
713
714// ── Settings store ─────────────────────────────────────────────────────────
715
716/// Handles persistence of [`Settings`] to disk.
717///
718/// By default, uses `~/.config/tinyharness/settings.json`. This can be
719/// overridden with [`SettingsStore::new`] for testing or alternative paths.
720pub struct SettingsStore {
721    path: std::path::PathBuf,
722}
723
724impl SettingsStore {
725    /// Create a store that reads/writes from the default path
726    /// (`~/.config/tinyharness/settings.json`).
727    pub fn default_path() -> Self {
728        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
729        let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
730        SettingsStore { path }
731    }
732
733    /// Create a store that reads/writes from a custom path.
734    pub fn new(path: std::path::PathBuf) -> Self {
735        SettingsStore { path }
736    }
737
738    /// Load settings from disk.
739    ///
740    /// Returns `Ok(Settings)` with defaults if the file doesn't exist,
741    /// or an error if the file exists but cannot be parsed.
742    pub fn load(&self) -> Result<Settings, SettingsError> {
743        // Clean up any stale temp files from a previous interrupted save.
744        // These would be named `.settings.json.tmp.<pid>.<timestamp>`.
745        self.cleanup_stale_temp_files();
746
747        if !self.path.exists() {
748            return Ok(Settings::default());
749        }
750        let content = std::fs::read_to_string(&self.path)?;
751        let mut settings: Settings = serde_json::from_str(&content)?;
752
753        // Legacy field resolution: old configs used `auto_accept_safe_commands: bool`
754        // or `auto_accept_all: bool` instead of `auto_accept_mode`.
755        // Only resolve if `auto_accept_mode` was NOT present in the JSON —
756        // the current value is just the default (Safe).
757        if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
758            && let Some(obj) = raw.as_object()
759            && !obj.contains_key("auto_accept_mode")
760        {
761            // auto_accept_all: true → All, false → Off
762            if let Some(val) = obj.get("auto_accept_all") {
763                if val.as_bool() == Some(true) {
764                    settings.auto_accept_mode = AutoAcceptMode::All;
765                } else if val.as_bool() == Some(false) {
766                    settings.auto_accept_mode = AutoAcceptMode::Off;
767                }
768            }
769            // auto_accept_safe_commands: false → Off (was "don't auto-accept safe cmds")
770            // auto_accept_safe_commands: true → Safe (already default, no change)
771            else if let Some(val) = obj.get("auto_accept_safe_commands")
772                && val.as_bool() == Some(false)
773            {
774                settings.auto_accept_mode = AutoAcceptMode::Off;
775            }
776        }
777
778        // Migrate legacy `last_model` and `last_provider_url` fields into
779        // the per-provider HashMaps. The key is `last_provider` (the
780        // provider that was active when the old config was saved).
781        if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
782            && let Some(obj) = raw.as_object()
783        {
784            if settings.provider_models.is_empty()
785                && let Some(model) = obj.get("last_model")
786                && let Some(model_str) = model.as_str()
787                && !model_str.is_empty()
788            {
789                settings
790                    .provider_models
791                    .insert(settings.last_provider, model_str.to_string());
792            }
793            if settings.provider_urls.is_empty()
794                && let Some(url) = obj.get("last_provider_url")
795                && let Some(url_str) = url.as_str()
796                && !url_str.is_empty()
797            {
798                settings
799                    .provider_urls
800                    .insert(settings.last_provider, url_str.to_string());
801            }
802        }
803
804        Ok(settings)
805    }
806
807    /// Remove stale temp files from interrupted saves.
808    ///
809    /// These match the pattern `.settings.json.tmp.*` in the settings
810    /// directory. They're left behind if the process was killed (e.g.
811    /// Ctrl+C or SIGTERM) between `File::create` and `rename`.
812    fn cleanup_stale_temp_files(&self) {
813        let Some(dir) = self.path.parent() else {
814            return;
815        };
816        let Ok(entries) = std::fs::read_dir(dir) else {
817            return;
818        };
819        for entry in entries.flatten() {
820            let name = entry.file_name();
821            let name = name.to_string_lossy();
822            if name.starts_with(".settings.json.tmp.")
823                && let Err(e) = std::fs::remove_file(entry.path())
824            {
825                tracing::debug!("Could not remove stale temp file {name}: {e}");
826            }
827        }
828    }
829
830    /// Load settings from disk, returning defaults on any error.
831    ///
832    /// This matches the original behaviour and is suitable for application
833    /// startup where you don't want to fail on corrupt settings files.
834    /// If the file is present but unparseable, it is renamed to
835    /// `settings.json.corrupt` so the user can recover their data.
836    pub fn load_or_default(&self) -> Settings {
837        self.load().unwrap_or_else(|e| {
838            tracing::warn!("Failed to load settings: {e}. Using defaults.");
839            // Back up the corrupted file so the user can recover their data.
840            // Without this, the next save_settings() call would silently
841            // overwrite the corrupted file with defaults, permanently losing
842            // the user's configuration.
843            if self.path.exists() {
844                let backup = self.path.with_extension("json.corrupt");
845                if let Err(backup_err) = std::fs::rename(&self.path, &backup) {
846                    tracing::warn!(
847                        "Could not back up corrupt settings to {}: {backup_err}",
848                        backup.display(),
849                    );
850                } else {
851                    tracing::warn!("Corrupt settings backed up to {}", backup.display(),);
852                }
853            }
854            Settings::default()
855        })
856    }
857
858    /// Save settings to disk atomically (write to temp file, fsync, then rename).
859    ///
860    /// Uses a unique temp file name (with PID) to avoid collisions if two
861    /// saves overlap. The temp file is fsync'd before the rename to ensure
862    /// data durability — without this, a crash after rename but before the
863    /// kernel flushes the data could leave an empty or partial file.
864    pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
865        let dir = self.path.parent().ok_or_else(|| {
866            SettingsError::Io(std::io::Error::new(
867                std::io::ErrorKind::InvalidInput,
868                "settings path has no parent directory",
869            ))
870        })?;
871        std::fs::create_dir_all(dir)?;
872
873        let json = serde_json::to_string_pretty(settings)?;
874
875        // Unique temp file name to avoid collisions between concurrent saves.
876        // Using PID + a timestamp makes it extremely unlikely two processes
877        // would write to the same temp path.
878        let tmp_name = format!(
879            ".settings.json.tmp.{}.{}",
880            std::process::id(),
881            std::time::SystemTime::now()
882                .duration_since(std::time::UNIX_EPOCH)
883                .map(|d| d.as_nanos())
884                .unwrap_or(0),
885        );
886        let tmp_path = dir.join(&tmp_name);
887
888        // Write to the temp file, fsync its data, then close.
889        {
890            let mut file = std::fs::File::create(&tmp_path)?;
891            std::io::Write::write_all(&mut file, json.as_bytes())?;
892            std::io::Write::flush(&mut file)?;
893            // fsync the file data so it's on disk before we rename.
894            // This is the key to crash-safety: if the system crashes
895            // after the rename but before the data is flushed, we'd
896            // get an empty file. fsync ensures the data is durable.
897            file.sync_all()?;
898        }
899
900        // Rename is atomic on POSIX systems (same filesystem).
901        std::fs::rename(&tmp_path, &self.path)?;
902        Ok(())
903    }
904
905    /// Returns the path where settings are stored.
906    pub fn path(&self) -> &std::path::Path {
907        &self.path
908    }
909}
910
911// ── Free convenience functions ─────────────────────────────────────────────
912
913/// Load settings from the default path, returning defaults on any error.
914///
915/// This is a convenience wrapper around
916/// [`SettingsStore::default_path`] followed by [`SettingsStore::load_or_default`].
917pub fn load_settings() -> Settings {
918    SettingsStore::default_path().load_or_default()
919}
920
921/// Save settings to the default path atomically.
922///
923/// This is a convenience wrapper around
924/// [`SettingsStore::default_path`] followed by [`SettingsStore::save`].
925/// On error, prints a warning to stderr (matching the original behaviour).
926pub fn save_settings(settings: &Settings) {
927    let store = SettingsStore::default_path();
928    if let Err(e) = store.save(settings) {
929        tracing::warn!("Failed to save settings: {e}");
930    }
931}
932
933// ── Prompt file management ──────────────────────────────────────────────────
934
935/// Resolve the effective list of project instruction file names to discover.
936///
937/// Priority (highest first):
938/// 1. `TINYHARNESS_MD_FILES` env var (comma-separated)
939/// 2. `settings.project_md_files` from global settings
940/// 3. Hardcoded default: TINYHARNESS.md, .tinyharness.md, AGENTS.md, CLAUDE.md
941pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
942    // 1. Env var takes highest priority
943    if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
944        let files: Vec<String> = env
945            .split(',')
946            .map(|s| s.trim().to_string())
947            .filter(|s| !s.is_empty())
948            .collect();
949        if !files.is_empty() {
950            return files;
951        }
952    }
953
954    // 2. Settings override
955    if let Some(s) = settings
956        && let Some(ref configured) = s.project_md_files
957        && !configured.is_empty()
958    {
959        return configured.clone();
960    }
961
962    // 3. Hardcoded defaults
963    crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
964        .iter()
965        .map(|s| s.to_string())
966        .collect()
967}
968
969/// Returns the directory where per-mode prompt `.md` files are stored.
970///
971/// Default: `~/.config/tinyharness/prompts/`
972pub fn prompts_dir() -> PathBuf {
973    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
974    PathBuf::from(home)
975        .join(".config")
976        .join("tinyharness")
977        .join("prompts")
978}
979
980/// Ensure the prompts directory exists and is seeded with `.md` files
981/// containing the hardcoded defaults for each mode, plus the shared header.
982///
983/// On first launch, this creates `~/.config/tinyharness/prompts/` and writes
984/// `header.md`, `casual.md`, `planning.md`, `agent.md`, and `research.md`.
985/// Existing files are **never** overwritten — users can safely customize them.
986///
987/// Returns the prompts directory path.
988pub fn ensure_prompts_initialized() -> PathBuf {
989    let dir = prompts_dir();
990    if !dir.exists() {
991        std::fs::create_dir_all(&dir).ok();
992    }
993
994    // Write shared header (new in 0.2 — always writes if missing)
995    {
996        let header_path = dir.join("header.md");
997        if !header_path.exists() {
998            let header_text = include_str!("../prompts/header.md");
999            if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
1000                tracing::warn!(
1001                    "Failed to write default header to {}: {e}",
1002                    header_path.display(),
1003                );
1004            }
1005        }
1006    }
1007
1008    let modes = [
1009        AgentMode::Casual,
1010        AgentMode::Planning,
1011        AgentMode::Agent,
1012        AgentMode::Research,
1013    ];
1014
1015    for mode in &modes {
1016        let file_path = dir.join(mode.prompts_filename());
1017        if !file_path.exists() {
1018            let default_text = mode.default_system_prompt();
1019            // Write the default, trimming leading/trailing whitespace/newlines
1020            if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
1021                tracing::warn!(
1022                    "Failed to write default prompt to {}: {e}",
1023                    file_path.display(),
1024                );
1025            }
1026        }
1027    }
1028
1029    dir
1030}
1031
1032// ── Tests ──────────────────────────────────────────────────────────────────
1033
1034#[cfg(test)]
1035mod tests {
1036    use super::*;
1037
1038    /// User settings from a future build (with `auto_accept_mode`) must load
1039    /// against the current `Settings` struct without parse errors.
1040    #[test]
1041    fn load_settings_missing_fields_uses_defaults() {
1042        let json = r#"{
1043            "last_provider": "OpenAiCompat",
1044            "last_provider_url": "http://localhost:8080/v1",
1045            "last_model": "MiniMax-M3",
1046            "preferred_mode": "Agent",
1047            "ollama_api_key": null,
1048            "openai_compat_api_key": "sk-test",
1049            "ollama_timeout_secs": 5,
1050            "ollama_max_retries": 3,
1051            "ollama_think_type": "High",
1052            "show_thinking": true,
1053            "context_limit": 256000,
1054            "auto_accept_mode": "all",
1055            "skip_health_check": true
1056        }"#;
1057
1058        let settings: Settings =
1059            serde_json::from_str(json).expect("missing fields should use defaults");
1060        assert_eq!(settings.last_provider, ProviderKind::OpenAiCompat);
1061        assert_eq!(settings.preferred_mode, AgentMode::Agent);
1062        // Missing fields default gracefully:
1063        assert!(settings.skip_health_check);
1064        assert_eq!(settings.ollama_think_type, OllamaThinkType::High);
1065    }
1066
1067    /// An empty settings object should load with all defaults.
1068    #[test]
1069    fn load_settings_empty_object_uses_all_defaults() {
1070        let settings: Settings =
1071            serde_json::from_str("{}").expect("empty object should use defaults");
1072        assert_eq!(settings.last_provider, ProviderKind::Ollama);
1073        assert_eq!(settings.preferred_mode, AgentMode::Casual);
1074        assert!(!settings.skip_health_check);
1075    }
1076
1077    #[test]
1078    fn questions_enabled_defaults_to_true() {
1079        let settings: Settings =
1080            serde_json::from_str("{}").expect("empty object should use defaults");
1081        assert!(settings.questions_enabled);
1082        assert!(settings.auto_compact_enabled);
1083        assert!(Settings::default().questions_enabled);
1084    }
1085
1086    #[test]
1087    fn questions_enabled_can_be_disabled_and_roundtrips() {
1088        let store = SettingsStore::new(temp_settings_path());
1089        let settings = Settings {
1090            questions_enabled: false,
1091            ..Settings::default()
1092        };
1093        store.save(&settings).unwrap();
1094        let loaded = store.load().unwrap();
1095        assert!(!loaded.questions_enabled);
1096        // Other tool availability flag is independent
1097        assert!(loaded.auto_compact_enabled);
1098        let _ = std::fs::remove_dir_all(store.path().parent().unwrap());
1099    }
1100
1101    #[test]
1102    fn project_settings_override_questions_enabled() {
1103        let global = Settings {
1104            questions_enabled: true,
1105            ..Settings::default()
1106        };
1107
1108        // No project settings → global value, source = Default
1109        let merged = merge_settings(&global, None);
1110        assert!(merged.questions_enabled);
1111        assert_eq!(merged.questions_enabled_source, SettingSource::Default);
1112
1113        // Project sets false → overrides global
1114        let project = ProjectSettings {
1115            questions_enabled: Some(false),
1116            ..ProjectSettings::default()
1117        };
1118        let merged = merge_settings(&global, Some(&project));
1119        assert!(!merged.questions_enabled);
1120        assert_eq!(merged.questions_enabled_source, SettingSource::Project);
1121    }
1122
1123    #[test]
1124    fn project_settings_questions_absent_falls_back_to_global() {
1125        let global = Settings {
1126            questions_enabled: false,
1127            ..Settings::default()
1128        };
1129        let project = ProjectSettings::default();
1130        let merged = merge_settings(&global, Some(&project));
1131        assert!(!merged.questions_enabled);
1132        assert_eq!(merged.questions_enabled_source, SettingSource::Default);
1133    }
1134
1135    #[test]
1136    fn merged_settings_produce_tool_availability() {
1137        let global = Settings {
1138            questions_enabled: false,
1139            auto_compact_enabled: true,
1140            ..Settings::default()
1141        };
1142        let availability = merge_settings(&global, None).tool_availability();
1143        assert!(!availability.question);
1144        assert!(availability.auto_compact);
1145
1146        let global = Settings::default();
1147        let availability = merge_settings(&global, None).tool_availability();
1148        assert_eq!(availability, crate::tools::ToolAvailability::all());
1149    }
1150
1151    #[test]
1152    fn discover_project_settings_parses_questions_enabled() {
1153        let tmp = tempfile::tempdir().unwrap();
1154        let dir = tmp.path().join(".tinyharness");
1155        std::fs::create_dir_all(&dir).unwrap();
1156        std::fs::write(dir.join("config.json"), r#"{"questions_enabled": false}"#).unwrap();
1157
1158        let found = discover_project_settings(tmp.path()).expect("config should be discovered");
1159        let settings = found.expect("config should parse");
1160        assert_eq!(settings.questions_enabled, Some(false));
1161        assert_eq!(settings.auto_compact_enabled, None);
1162    }
1163
1164    #[test]
1165    fn generate_project_config_template_includes_questions() {
1166        let settings = Settings {
1167            questions_enabled: false,
1168            ..Settings::default()
1169        };
1170        let template = generate_project_config_template(&settings);
1171        assert_eq!(template.questions_enabled, Some(false));
1172        assert_eq!(template.auto_compact_enabled, Some(true));
1173    }
1174
1175    #[test]
1176    fn auto_accept_mode_from_string() {
1177        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "all"}"#).unwrap();
1178        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1179
1180        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "off"}"#).unwrap();
1181        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1182
1183        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "safe"}"#).unwrap();
1184        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
1185    }
1186
1187    #[test]
1188    fn auto_accept_mode_from_legacy_bool() {
1189        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": true}"#).unwrap();
1190        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1191
1192        let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": false}"#).unwrap();
1193        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1194    }
1195    #[test]
1196    fn auto_accept_mode_from_legacy_all_field() {
1197        // auto_accept_all: true → All via load() resolution
1198        let store = SettingsStore::new(temp_settings_path());
1199        let json = r#"{"auto_accept_all": true}"#;
1200        std::fs::write(store.path(), json).unwrap();
1201        let settings = store.load().unwrap();
1202        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1203        let _ = std::fs::remove_file(store.path());
1204
1205        // auto_accept_all: false → Off
1206        let store = SettingsStore::new(temp_settings_path());
1207        let json = r#"{"auto_accept_all": false}"#;
1208        std::fs::write(store.path(), json).unwrap();
1209        let settings = store.load().unwrap();
1210        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1211        let _ = std::fs::remove_file(store.path());
1212    }
1213    #[test]
1214    fn auto_accept_mode_from_legacy_safe_commands_field() {
1215        // auto_accept_safe_commands: false → Off via load() resolution
1216        let store = SettingsStore::new(temp_settings_path());
1217        let json = r#"{"auto_accept_safe_commands": false}"#;
1218        std::fs::write(store.path(), json).unwrap();
1219        let settings = store.load().unwrap();
1220        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1221        let _ = std::fs::remove_file(store.path());
1222
1223        // auto_accept_safe_commands: true → Safe (default, no change)
1224        let store = SettingsStore::new(temp_settings_path());
1225        let json = r#"{"auto_accept_safe_commands": true}"#;
1226        std::fs::write(store.path(), json).unwrap();
1227        let settings = store.load().unwrap();
1228        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
1229        let _ = std::fs::remove_file(store.path());
1230    }
1231
1232    #[test]
1233    fn auto_accept_mode_explicit_overrides_legacy() {
1234        // Explicit auto_accept_mode string wins over alias
1235        let settings: Settings =
1236            serde_json::from_str(r#"{"auto_accept_mode": "off", "auto_accept_all": true}"#)
1237                .unwrap();
1238        assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1239    }
1240
1241    #[test]
1242    fn migrate_legacy_last_model_and_url() {
1243        let store = SettingsStore::new(temp_settings_path());
1244        let json = r#"{"last_provider": "Ollama", "last_model": "qwen2.5:7b", "last_provider_url": "http://localhost:11434"}"#;
1245        std::fs::write(store.path(), json).unwrap();
1246        let settings = store.load().unwrap();
1247        assert_eq!(
1248            settings.get_model_for(ProviderKind::Ollama),
1249            Some("qwen2.5:7b")
1250        );
1251        assert_eq!(
1252            settings.get_url_for(ProviderKind::Ollama),
1253            Some("http://localhost:11434")
1254        );
1255        let _ = std::fs::remove_file(store.path());
1256    }
1257
1258    #[test]
1259    fn migrate_legacy_fields_for_openai_compat() {
1260        let store = SettingsStore::new(temp_settings_path());
1261        let json = r#"{"last_provider": "OpenAiCompat", "last_model": "gpt-4o", "last_provider_url": "https://api.openai.com/v1"}"#;
1262        std::fs::write(store.path(), json).unwrap();
1263        let settings = store.load().unwrap();
1264        assert_eq!(
1265            settings.get_model_for(ProviderKind::OpenAiCompat),
1266            Some("gpt-4o")
1267        );
1268        assert_eq!(
1269            settings.get_url_for(ProviderKind::OpenAiCompat),
1270            Some("https://api.openai.com/v1")
1271        );
1272        // Ollama should NOT have a model from this migration
1273        assert_eq!(settings.get_model_for(ProviderKind::Ollama), None);
1274        let _ = std::fs::remove_file(store.path());
1275    }
1276
1277    #[test]
1278    fn per_provider_model_and_url_accessors() {
1279        let mut settings = Settings::default();
1280        settings.set_model_for(ProviderKind::Ollama, "qwen2.5:7b".to_string());
1281        settings.set_model_for(ProviderKind::LlamaCpp, "llama-3.1-8b".to_string());
1282        settings.set_url_for(ProviderKind::LlamaCpp, "http://localhost:8080".to_string());
1283
1284        assert_eq!(
1285            settings.get_model_for(ProviderKind::Ollama),
1286            Some("qwen2.5:7b")
1287        );
1288        assert_eq!(
1289            settings.get_model_for(ProviderKind::LlamaCpp),
1290            Some("llama-3.1-8b")
1291        );
1292        assert_eq!(settings.get_model_for(ProviderKind::Vllm), None);
1293        assert_eq!(
1294            settings.get_url_for(ProviderKind::LlamaCpp),
1295            Some("http://localhost:8080")
1296        );
1297        assert_eq!(settings.get_url_for(ProviderKind::Ollama), None);
1298    }
1299
1300    #[test]
1301    fn get_current_model_and_url_use_last_provider() {
1302        let mut settings = Settings {
1303            last_provider: ProviderKind::OpenAiCompat,
1304            ..Settings::default()
1305        };
1306        settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
1307        settings.set_url_for(
1308            ProviderKind::OpenAiCompat,
1309            "https://api.openai.com/v1".to_string(),
1310        );
1311
1312        assert_eq!(settings.get_current_model(), Some("gpt-4o"));
1313        assert_eq!(
1314            settings.get_current_url(),
1315            Some("https://api.openai.com/v1")
1316        );
1317    }
1318
1319    fn temp_settings_path() -> std::path::PathBuf {
1320        // Use a unique subdirectory per test to avoid interference between
1321        // parallel tests (especially the stale-temp-file cleanup which scans
1322        // the parent directory).
1323        let mut dir = std::env::temp_dir();
1324        dir.push(format!(
1325            "tinyharness_test_{}_{}_{:?}",
1326            std::process::id(),
1327            std::time::SystemTime::now()
1328                .duration_since(std::time::UNIX_EPOCH)
1329                .map(|d| d.as_nanos())
1330                .unwrap_or(0),
1331            std::thread::current().id()
1332        ));
1333        std::fs::create_dir_all(&dir).unwrap();
1334        dir.push("settings.json");
1335        dir
1336    }
1337
1338    // ── Config corruption resilience tests ───────────────────────────────
1339
1340    /// Saving and loading should round-trip correctly.
1341    #[test]
1342    fn save_and_load_roundtrip() {
1343        let store = SettingsStore::new(temp_settings_path());
1344        let mut settings = Settings {
1345            last_provider: ProviderKind::OpenAiCompat,
1346            auto_accept_mode: AutoAcceptMode::All,
1347            ..Settings::default()
1348        };
1349        settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
1350
1351        store.save(&settings).unwrap();
1352        let loaded = store.load().unwrap();
1353        assert_eq!(loaded.last_provider, ProviderKind::OpenAiCompat);
1354        assert_eq!(
1355            loaded.get_model_for(ProviderKind::OpenAiCompat),
1356            Some("gpt-4o")
1357        );
1358        assert_eq!(loaded.auto_accept_mode, AutoAcceptMode::All);
1359
1360        // Clean up
1361        let dir = store.path().parent().unwrap();
1362        let _ = std::fs::remove_dir_all(dir);
1363    }
1364
1365    /// Loading a corrupt settings file should return defaults and back up
1366    /// the corrupt file to `settings.json.corrupt`.
1367    #[test]
1368    fn corrupt_settings_backed_up_and_defaults_returned() {
1369        let store = SettingsStore::new(temp_settings_path());
1370        let corrupt_json = "{ this is not valid json !!!";
1371        std::fs::write(store.path(), corrupt_json).unwrap();
1372
1373        let settings = store.load_or_default();
1374        assert_eq!(settings.last_provider, ProviderKind::Ollama);
1375        assert_eq!(settings.preferred_mode, AgentMode::Casual);
1376
1377        // The corrupt file should have been renamed to .corrupt
1378        assert!(!store.path().exists());
1379        let backup = store.path().with_extension("json.corrupt");
1380        assert!(backup.exists(), "corrupt settings should be backed up");
1381
1382        // Verify the backup contains the original corrupt data
1383        let backup_content = std::fs::read_to_string(&backup).unwrap();
1384        assert_eq!(backup_content, corrupt_json);
1385
1386        // Clean up
1387        let dir = store.path().parent().unwrap();
1388        let _ = std::fs::remove_dir_all(dir);
1389    }
1390
1391    /// Stale temp files from interrupted saves should be cleaned up on load.
1392    #[test]
1393    fn stale_temp_files_cleaned_up_on_load() {
1394        let store = SettingsStore::new(temp_settings_path());
1395        let dir = store.path().parent().unwrap();
1396        let tmp1 = dir.join(".settings.json.tmp.12345.999999999");
1397        let tmp2 = dir.join(".settings.json.tmp.67890.888888888");
1398        std::fs::write(&tmp1, "stale data").unwrap();
1399        std::fs::write(&tmp2, "more stale data").unwrap();
1400        assert!(tmp1.exists());
1401        assert!(tmp2.exists());
1402
1403        // Load should clean up stale temp files
1404        let _ = store.load();
1405
1406        assert!(!tmp1.exists(), "stale temp file should be removed");
1407        assert!(!tmp2.exists(), "stale temp file should be removed");
1408
1409        // Clean up
1410        let _ = std::fs::remove_dir_all(dir);
1411    }
1412
1413    /// Save should not leave temp files behind on success.
1414    #[test]
1415    fn save_leaves_no_temp_files() {
1416        let store = SettingsStore::new(temp_settings_path());
1417        store.save(&Settings::default()).unwrap();
1418
1419        let dir = store.path().parent().unwrap();
1420        let entries = std::fs::read_dir(dir).unwrap();
1421        for entry in entries.flatten() {
1422            let name = entry.file_name();
1423            assert!(
1424                !name.to_string_lossy().starts_with(".settings.json.tmp."),
1425                "no temp files should remain after successful save"
1426            );
1427        }
1428
1429        let _ = std::fs::remove_dir_all(dir);
1430    }
1431
1432    /// Multiple saves should not corrupt the settings file.
1433    #[test]
1434    fn multiple_saves_are_consistent() {
1435        let store = SettingsStore::new(temp_settings_path());
1436
1437        for i in 0..10 {
1438            let settings = Settings {
1439                ollama_timeout_secs: i,
1440                ..Settings::default()
1441            };
1442            store.save(&settings).unwrap();
1443        }
1444
1445        let loaded = store.load().unwrap();
1446        assert_eq!(loaded.ollama_timeout_secs, 9);
1447
1448        let dir = store.path().parent().unwrap();
1449        let _ = std::fs::remove_dir_all(dir);
1450    }
1451}