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