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