Skip to main content

tinyharness_lib/config/
mod.rs

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