Skip to main content

tinyharness_lib/config/
mod.rs

1use std::path::PathBuf;
2use std::{fmt, str::FromStr};
3
4use serde::{Deserialize, Serialize};
5
6use crate::mode::AgentMode;
7
8// ── Project Settings ────────────────────────────────────────────────────────
9
10/// Per-project override settings discovered from `.tinyharness/config.json`.
11///
12/// All fields are `Option` — only present fields override the global setting.
13/// Discovery walks up from CWD, same algorithm as `discover_project_md`.
14#[derive(Debug, Clone, Serialize, Deserialize, Default)]
15pub struct ProjectSettings {
16    /// Override safe command prefixes (extends, doesn't replace)
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub safe_command_prefixes: Option<Vec<String>>,
19    /// Override denied command prefixes
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub denied_command_prefixes: Option<Vec<String>>,
22    /// Override auto_accept_safe_commands
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub auto_accept_safe_commands: Option<bool>,
25    /// Override context_limit
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub context_limit: Option<u32>,
28    /// Additional project-specific MD file names to include in context
29    /// (e.g. ["RULES.md", ".cursorrules"]). These are loaded AFTER the main
30    /// project instruction file.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub project_md_files: Option<Vec<String>>,
33    /// Override the preferred mode for this project
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub preferred_mode: Option<AgentMode>,
36}
37
38/// Discover and load `.tinyharness/config.json` by walking up from CWD.
39///
40/// Returns `None` if no config file is found. Returns `Some(Err(...))` if
41/// a file is found but cannot be parsed.
42pub fn discover_project_settings(
43    start_dir: &std::path::Path,
44) -> Option<Result<ProjectSettings, SettingsError>> {
45    let mut dir = start_dir.to_path_buf();
46
47    loop {
48        let candidate = dir.join(".tinyharness").join("config.json");
49        if candidate.is_file() {
50            let content = match std::fs::read_to_string(&candidate) {
51                Ok(c) => c,
52                Err(e) => return Some(Err(SettingsError::Io(e))),
53            };
54            let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
55            return Some(parsed);
56        }
57
58        // Walk up one directory
59        if let Some(parent) = dir.parent() {
60            if parent == dir {
61                break;
62            }
63            dir = parent.to_path_buf();
64        } else {
65            break;
66        }
67    }
68
69    None
70}
71
72/// Source annotation for merged settings values.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum SettingSource {
75    /// Value came from the global `~/.config/tinyharness/settings.json`
76    Global,
77    /// Value came from `.tinyharness/config.json`
78    Project,
79    /// Value is the hardcoded default (no config found)
80    Default,
81}
82
83impl std::fmt::Display for SettingSource {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        match self {
86            SettingSource::Global => f.write_str("global"),
87            SettingSource::Project => f.write_str("project"),
88            SettingSource::Default => f.write_str("default"),
89        }
90    }
91}
92
93/// Effective merged settings — the result of layering global + project settings.
94///
95/// This is a read-only view. Each field has a source annotation for display.
96#[derive(Debug, Clone)]
97pub struct MergedSettings {
98    /// Merged safe command prefixes (project extends global)
99    pub safe_commands: Vec<String>,
100    pub safe_commands_source: SettingSource,
101    /// Merged denied command prefixes (project overrides global)
102    pub denied_commands: Vec<String>,
103    pub denied_commands_source: SettingSource,
104    pub auto_accept_safe_commands: bool,
105    pub auto_accept_source: SettingSource,
106    pub context_limit: Option<u32>,
107    pub context_limit_source: SettingSource,
108    pub project_md_files: Vec<String>,
109    pub project_md_files_source: SettingSource,
110    pub preferred_mode: AgentMode,
111    pub preferred_mode_source: SettingSource,
112}
113
114/// Load and merge global + project settings.
115///
116/// Layering: project overrides global where specified, otherwise falls back
117/// to global. For safe commands, project *extends* the global list rather
118/// than replacing it.
119pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
120    let global = load_settings();
121
122    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
123    let project = match discover_project_settings(&cwd) {
124        Some(Ok(ps)) => Some(ps),
125        Some(Err(e)) => {
126            tracing::warn!(
127                "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
128            );
129            None
130        }
131        None => None,
132    };
133
134    let merged = merge_settings(&global, project.as_ref());
135    (global, project, merged)
136}
137
138/// Merge global settings with optional project overrides.
139fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
140    let global_safe = global.get_safe_commands();
141    let global_denied = global.get_denied_commands();
142
143    match project {
144        None => MergedSettings {
145            safe_commands: global_safe,
146            safe_commands_source: SettingSource::Default,
147            denied_commands: global_denied,
148            denied_commands_source: SettingSource::Default,
149            auto_accept_safe_commands: global.auto_accept_safe_commands,
150            auto_accept_source: SettingSource::Default,
151            context_limit: global.context_limit,
152            context_limit_source: SettingSource::Default,
153            project_md_files: Vec::new(),
154            project_md_files_source: SettingSource::Default,
155            preferred_mode: global.preferred_mode,
156            preferred_mode_source: SettingSource::Default,
157        },
158        Some(p) => {
159            // Safe commands: project extends global
160            let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
161                let mut combined = global_safe.clone();
162                for cmd in proj_safe {
163                    if !combined.contains(cmd) {
164                        combined.push(cmd.clone());
165                    }
166                }
167                combined
168            } else {
169                global_safe
170            };
171            let safe_source = if p.safe_command_prefixes.is_some() {
172                SettingSource::Project
173            } else {
174                SettingSource::Default
175            };
176
177            // Denied commands: project replaces global
178            let (denied_commands, denied_source) =
179                if let Some(ref proj_denied) = p.denied_command_prefixes {
180                    (proj_denied.clone(), SettingSource::Project)
181                } else {
182                    (global_denied, SettingSource::Default)
183                };
184
185            let (auto_accept, auto_source) = p
186                .auto_accept_safe_commands
187                .map(|v| (v, SettingSource::Project))
188                .unwrap_or((global.auto_accept_safe_commands, SettingSource::Default));
189
190            let (context_limit, ctx_source) = p
191                .context_limit
192                .map(|v| (Some(v), SettingSource::Project))
193                .unwrap_or((global.context_limit, SettingSource::Default));
194
195            let (project_md_files, md_source) = p
196                .project_md_files
197                .as_ref()
198                .map(|files| (files.clone(), SettingSource::Project))
199                .unwrap_or((Vec::new(), SettingSource::Default));
200
201            let (preferred_mode, mode_source) = p
202                .preferred_mode
203                .map(|m| (m, SettingSource::Project))
204                .unwrap_or((global.preferred_mode, SettingSource::Default));
205
206            MergedSettings {
207                safe_commands,
208                safe_commands_source: safe_source,
209                denied_commands,
210                denied_commands_source: denied_source,
211                auto_accept_safe_commands: auto_accept,
212                auto_accept_source: auto_source,
213                context_limit,
214                context_limit_source: ctx_source,
215                project_md_files,
216                project_md_files_source: md_source,
217                preferred_mode,
218                preferred_mode_source: mode_source,
219            }
220        }
221    }
222}
223
224/// Generate a starter `.tinyharness/config.json` file from current settings
225/// overrides that make sense for a project (safe commands, denied commands,
226/// auto-accept, context limit).
227pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
228    ProjectSettings {
229        safe_command_prefixes: settings.safe_command_prefixes.clone(),
230        denied_command_prefixes: settings.denied_command_prefixes.clone(),
231        auto_accept_safe_commands: Some(settings.auto_accept_safe_commands),
232        context_limit: settings.context_limit,
233        project_md_files: None, // user must fill this in
234        preferred_mode: Some(settings.preferred_mode),
235    }
236}
237
238/// Identifies which provider backend was used last.
239#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
240pub enum ProviderKind {
241    Ollama,
242    LlamaCpp,
243    Vllm,
244}
245
246impl fmt::Display for ProviderKind {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        match self {
249            ProviderKind::Ollama => f.write_str("ollama"),
250            ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
251            ProviderKind::Vllm => f.write_str("vllm"),
252        }
253    }
254}
255
256impl FromStr for ProviderKind {
257    type Err = String;
258
259    fn from_str(s: &str) -> Result<Self, Self::Err> {
260        match s.trim().to_lowercase().as_str() {
261            "ollama" => Ok(ProviderKind::Ollama),
262            "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
263            "vllm" => Ok(ProviderKind::Vllm),
264            _ => Err(format!("Unknown provider '{}'", s)),
265        }
266    }
267}
268
269/// Controls the "think" (reasoning) level for Ollama models that support it
270/// (e.g. qwen2.5 variants). Affects how much internal reasoning the model does
271/// before responding.
272///
273/// Corresponds to Ollama's `think` parameter. Only meaningful for Ollama;
274/// other providers ignore this setting.
275#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
276pub enum OllamaThinkType {
277    /// Disable thinking entirely (fastest, lowest quality).
278    Off,
279    /// Minimal reasoning (faster, lower latency).
280    Low,
281    /// Balanced reasoning (good default).
282    Medium,
283    /// Maximum reasoning (slowest, highest quality).
284    High,
285}
286
287impl fmt::Display for OllamaThinkType {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        match self {
290            OllamaThinkType::Off => f.write_str("off"),
291            OllamaThinkType::Low => f.write_str("low"),
292            OllamaThinkType::Medium => f.write_str("medium"),
293            OllamaThinkType::High => f.write_str("high"),
294        }
295    }
296}
297
298impl FromStr for OllamaThinkType {
299    type Err = String;
300
301    fn from_str(s: &str) -> Result<Self, Self::Err> {
302        match s.trim().to_lowercase().as_str() {
303            "off" | "false" | "0" => Ok(OllamaThinkType::Off),
304            "low" => Ok(OllamaThinkType::Low),
305            "medium" | "mid" => Ok(OllamaThinkType::Medium),
306            "high" => Ok(OllamaThinkType::High),
307            _ => Err(format!(
308                "Unknown think type '{}'. Valid values: off, low, medium, high",
309                s
310            )),
311        }
312    }
313}
314
315/// Persisted application settings — pure data type with no I/O.
316///
317/// Use `SettingsStore` to load and save instances of this type.
318#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct Settings {
320    pub last_provider: ProviderKind,
321    /// Last URL used for the active provider. Set automatically by `--config`
322    /// or by passing `--url`. Persisted so subsequent runs don't re-prompt.
323    /// (default: None)
324    #[serde(default)]
325    pub last_provider_url: Option<String>,
326    pub last_model: Option<String>,
327    pub preferred_mode: AgentMode,
328    pub ollama_api_key: Option<String>,
329    /// Timeout in seconds for Ollama requests (default: 5)
330    pub ollama_timeout_secs: u64,
331    /// Maximum number of retries for Ollama requests (default: 3)
332    pub ollama_max_retries: u32,
333    /// Controls the think/reasoning level for Ollama (default: Medium)
334    pub ollama_think_type: OllamaThinkType,
335    /// Show the model's thinking/reasoning chain inline during streaming (default: false)
336    pub show_thinking: bool,
337    /// Context limit for warning calculations only (default: None, uses model default)
338    pub context_limit: Option<u32>,
339    /// Automatically accept safe read-only commands in the run tool (default: true)
340    pub auto_accept_safe_commands: bool,
341    /// List of command prefixes considered safe for auto-accept (default: see get_default_safe_commands)
342    pub safe_command_prefixes: Option<Vec<String>>,
343    /// List of command prefixes that are always denied auto-accept, even if they
344    /// match a safe prefix. Takes priority over the safe list. (default: empty)
345    pub denied_command_prefixes: Option<Vec<String>>,
346    /// Override the project instruction file discovery list.
347    /// When set, replaces the hardcoded default list (TINYHARNESS.md, AGENTS.md, etc.).
348    /// Use `TINYHARNESS_MD_FILES` env var for the highest priority override.
349    /// (default: None → use hardcoded defaults)
350    #[serde(default)]
351    pub project_md_files: Option<Vec<String>>,
352}
353
354impl Default for Settings {
355    fn default() -> Self {
356        Settings {
357            last_provider: ProviderKind::Ollama,
358            last_provider_url: None,
359            last_model: None,
360            preferred_mode: AgentMode::Casual,
361            ollama_api_key: None,
362            ollama_timeout_secs: 5,
363            ollama_max_retries: 3,
364            ollama_think_type: OllamaThinkType::Medium,
365            show_thinking: false,
366            context_limit: None,
367            auto_accept_safe_commands: true,
368            safe_command_prefixes: None,
369            denied_command_prefixes: None,
370            project_md_files: None,
371        }
372    }
373}
374
375/// Returns the default list of safe command prefixes.
376/// These are read-only commands that don't modify the filesystem.
377pub fn get_default_safe_commands() -> Vec<String> {
378    vec![
379        "cd".to_string(),
380        "ls".to_string(),
381        "grep".to_string(),
382        "glob".to_string(),
383        "find".to_string(),
384        "cat".to_string(),
385        "head".to_string(),
386        "tail".to_string(),
387        "wc".to_string(),
388        "pwd".to_string(),
389        "echo".to_string(),
390        "printf".to_string(),
391        "tree".to_string(),
392        "file".to_string(),
393        "stat".to_string(),
394        "du".to_string(),
395        "df".to_string(),
396        "free".to_string(),
397        "uptime".to_string(),
398        "whoami".to_string(),
399        "hostname".to_string(),
400        "uname".to_string(),
401        "date".to_string(),
402        "cal".to_string(),
403        "ps".to_string(),
404        "env".to_string(),
405        "printenv".to_string(),
406        "which".to_string(),
407        "whereis".to_string(),
408        "type".to_string(),
409        "git status".to_string(),
410        "git diff".to_string(),
411        "git log".to_string(),
412        "git show".to_string(),
413        "git branch".to_string(),
414        "git remote".to_string(),
415        "git tag".to_string(),
416        "git describe".to_string(),
417        "git rev-parse".to_string(),
418        "cargo tree".to_string(),
419        "cargo metadata".to_string(),
420        "cargo doc".to_string(),
421        "rustc --version".to_string(),
422        "cargo --version".to_string(),
423    ]
424}
425
426impl Settings {
427    /// Returns the list of safe command prefixes, using defaults if not configured.
428    pub fn get_safe_commands(&self) -> Vec<String> {
429        self.safe_command_prefixes
430            .clone()
431            .unwrap_or_else(get_default_safe_commands)
432    }
433
434    /// Returns the list of always-denied command prefixes.
435    /// These take priority over the safe list — if a command matches both
436    /// a safe prefix and a denied prefix, it is denied.
437    /// Defaults to an empty list (nothing denied).
438    pub fn get_denied_commands(&self) -> Vec<String> {
439        self.denied_command_prefixes.clone().unwrap_or_default()
440    }
441}
442
443// ── Errors ──────────────────────────────────────────────────────────────────
444
445/// Error type for settings I/O operations.
446#[derive(Debug)]
447pub enum SettingsError {
448    Io(std::io::Error),
449    Parse(serde_json::Error),
450}
451
452impl std::fmt::Display for SettingsError {
453    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        match self {
455            SettingsError::Io(e) => write!(f, "I/O error: {}", e),
456            SettingsError::Parse(e) => write!(f, "parse error: {}", e),
457        }
458    }
459}
460
461impl std::error::Error for SettingsError {
462    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
463        match self {
464            SettingsError::Io(e) => Some(e),
465            SettingsError::Parse(e) => Some(e),
466        }
467    }
468}
469
470impl From<std::io::Error> for SettingsError {
471    fn from(e: std::io::Error) -> Self {
472        SettingsError::Io(e)
473    }
474}
475
476impl From<serde_json::Error> for SettingsError {
477    fn from(e: serde_json::Error) -> Self {
478        SettingsError::Parse(e)
479    }
480}
481
482// ── Settings store ─────────────────────────────────────────────────────────
483
484/// Handles persistence of [`Settings`] to disk.
485///
486/// By default, uses `~/.config/tinyharness/settings.json`. This can be
487/// overridden with [`SettingsStore::new`] for testing or alternative paths.
488pub struct SettingsStore {
489    path: std::path::PathBuf,
490}
491
492impl SettingsStore {
493    /// Create a store that reads/writes from the default path
494    /// (`~/.config/tinyharness/settings.json`).
495    pub fn default_path() -> Self {
496        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
497        let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
498        SettingsStore { path }
499    }
500
501    /// Create a store that reads/writes from a custom path.
502    pub fn new(path: std::path::PathBuf) -> Self {
503        SettingsStore { path }
504    }
505
506    /// Load settings from disk.
507    ///
508    /// Returns `Ok(Settings)` with defaults if the file doesn't exist,
509    /// or an error if the file exists but cannot be parsed.
510    pub fn load(&self) -> Result<Settings, SettingsError> {
511        if !self.path.exists() {
512            return Ok(Settings::default());
513        }
514        let content = std::fs::read_to_string(&self.path)?;
515        let settings = serde_json::from_str(&content)?;
516        Ok(settings)
517    }
518
519    /// Load settings from disk, returning defaults on any error.
520    ///
521    /// This matches the original behaviour and is suitable for application
522    /// startup where you don't want to fail on corrupt settings files.
523    pub fn load_or_default(&self) -> Settings {
524        self.load().unwrap_or_else(|e| {
525            tracing::warn!("Failed to load settings: {e}. Using defaults.");
526            Settings::default()
527        })
528    }
529
530    /// Save settings to disk atomically (write to temp file, then rename).
531    pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
532        let dir = self.path.parent().ok_or_else(|| {
533            SettingsError::Io(std::io::Error::new(
534                std::io::ErrorKind::InvalidInput,
535                "settings path has no parent directory",
536            ))
537        })?;
538        std::fs::create_dir_all(dir)?;
539
540        let json = serde_json::to_string_pretty(settings)?;
541        let tmp_path = dir.join("settings.json.tmp");
542
543        {
544            let mut file = std::fs::File::create(&tmp_path)?;
545            std::io::Write::write_all(&mut file, json.as_bytes())?;
546            std::io::Write::flush(&mut file)?;
547        }
548
549        std::fs::rename(&tmp_path, &self.path)?;
550        Ok(())
551    }
552
553    /// Returns the path where settings are stored.
554    pub fn path(&self) -> &std::path::Path {
555        &self.path
556    }
557}
558
559// ── Free convenience functions ─────────────────────────────────────────────
560
561/// Load settings from the default path, returning defaults on any error.
562///
563/// This is a convenience wrapper around [`SettingsStore::default_path().load_or_default()`].
564pub fn load_settings() -> Settings {
565    SettingsStore::default_path().load_or_default()
566}
567
568/// Save settings to the default path atomically.
569///
570/// This is a convenience wrapper around [`SettingsStore::default_path().save()`].
571/// On error, prints a warning to stderr (matching the original behaviour).
572pub fn save_settings(settings: &Settings) {
573    let store = SettingsStore::default_path();
574    if let Err(e) = store.save(settings) {
575        tracing::warn!("Failed to save settings: {e}");
576    }
577}
578
579// ── Prompt file management ──────────────────────────────────────────────────
580
581/// Resolve the effective list of project instruction file names to discover.
582///
583/// Priority (highest first):
584/// 1. `TINYHARNESS_MD_FILES` env var (comma-separated)
585/// 2. `settings.project_md_files` from global settings
586/// 3. Hardcoded default: TINYHARNESS.md, .tinyharness.md, AGENTS.md, CLAUDE.md
587pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
588    // 1. Env var takes highest priority
589    if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
590        let files: Vec<String> = env
591            .split(',')
592            .map(|s| s.trim().to_string())
593            .filter(|s| !s.is_empty())
594            .collect();
595        if !files.is_empty() {
596            return files;
597        }
598    }
599
600    // 2. Settings override
601    if let Some(s) = settings
602        && let Some(ref configured) = s.project_md_files
603        && !configured.is_empty()
604    {
605        return configured.clone();
606    }
607
608    // 3. Hardcoded defaults
609    crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
610        .iter()
611        .map(|s| s.to_string())
612        .collect()
613}
614
615/// Returns the directory where per-mode prompt `.md` files are stored.
616///
617/// Default: `~/.config/tinyharness/prompts/`
618pub fn prompts_dir() -> PathBuf {
619    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
620    PathBuf::from(home)
621        .join(".config")
622        .join("tinyharness")
623        .join("prompts")
624}
625
626/// Ensure the prompts directory exists and is seeded with `.md` files
627/// containing the hardcoded defaults for each mode, plus the shared header.
628///
629/// On first launch, this creates `~/.config/tinyharness/prompts/` and writes
630/// `header.md`, `casual.md`, `planning.md`, `agent.md`, and `research.md`.
631/// Existing files are **never** overwritten — users can safely customize them.
632///
633/// Returns the prompts directory path.
634pub fn ensure_prompts_initialized() -> PathBuf {
635    let dir = prompts_dir();
636    if !dir.exists() {
637        std::fs::create_dir_all(&dir).ok();
638    }
639
640    // Write shared header (new in 0.2 — always writes if missing)
641    {
642        let header_path = dir.join("header.md");
643        if !header_path.exists() {
644            let header_text = include_str!("../prompts/header.md");
645            if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
646                tracing::warn!(
647                    "Failed to write default header to {}: {e}",
648                    header_path.display(),
649                );
650            }
651        }
652    }
653
654    let modes = [
655        AgentMode::Casual,
656        AgentMode::Planning,
657        AgentMode::Agent,
658        AgentMode::Research,
659    ];
660
661    for mode in &modes {
662        let file_path = dir.join(mode.prompts_filename());
663        if !file_path.exists() {
664            let default_text = mode.default_system_prompt();
665            // Write the default, trimming leading/trailing whitespace/newlines
666            if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
667                tracing::warn!(
668                    "Failed to write default prompt to {}: {e}",
669                    file_path.display(),
670                );
671            }
672        }
673    }
674
675    dir
676}