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