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    /// Generic OpenAI-compatible provider for hosted gateways (OpenRouter,
245    /// Together, etc.) that require a Bearer API key. Unlike LlamaCpp/Vllm
246    /// which target local unauthenticated servers, this provider always
247    /// sends `Authorization: Bearer <key>` and requires `--api-key` or
248    /// the `OPENAI_API_KEY` env var.
249    OpenAiCompat,
250    Sockudo,
251}
252
253impl fmt::Display for ProviderKind {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        match self {
256            ProviderKind::Ollama => f.write_str("ollama"),
257            ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
258            ProviderKind::Vllm => f.write_str("vllm"),
259            ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
260            ProviderKind::Sockudo => f.write_str("sockudo"),
261        }
262    }
263}
264
265impl FromStr for ProviderKind {
266    type Err = String;
267
268    fn from_str(s: &str) -> Result<Self, Self::Err> {
269        match s.trim().to_lowercase().as_str() {
270            "ollama" => Ok(ProviderKind::Ollama),
271            "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
272            "vllm" => Ok(ProviderKind::Vllm),
273            "openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
274            "sockudo" => Ok(ProviderKind::Sockudo),
275            _ => Err(format!("Unknown provider '{}'", s)),
276        }
277    }
278}
279
280/// Controls the "think" (reasoning) level for Ollama models that support it
281/// (e.g. qwen2.5 variants). Affects how much internal reasoning the model does
282/// before responding.
283///
284/// Corresponds to Ollama's `think` parameter. Only meaningful for Ollama;
285/// other providers ignore this setting.
286#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
287pub enum OllamaThinkType {
288    /// Disable thinking entirely (fastest, lowest quality).
289    Off,
290    /// Minimal reasoning (faster, lower latency).
291    Low,
292    /// Balanced reasoning (good default).
293    Medium,
294    /// Maximum reasoning (slowest, highest quality).
295    High,
296}
297
298impl fmt::Display for OllamaThinkType {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        match self {
301            OllamaThinkType::Off => f.write_str("off"),
302            OllamaThinkType::Low => f.write_str("low"),
303            OllamaThinkType::Medium => f.write_str("medium"),
304            OllamaThinkType::High => f.write_str("high"),
305        }
306    }
307}
308
309impl FromStr for OllamaThinkType {
310    type Err = String;
311
312    fn from_str(s: &str) -> Result<Self, Self::Err> {
313        match s.trim().to_lowercase().as_str() {
314            "off" | "false" | "0" => Ok(OllamaThinkType::Off),
315            "low" => Ok(OllamaThinkType::Low),
316            "medium" | "mid" => Ok(OllamaThinkType::Medium),
317            "high" => Ok(OllamaThinkType::High),
318            _ => Err(format!(
319                "Unknown think type '{}'. Valid values: off, low, medium, high",
320                s
321            )),
322        }
323    }
324}
325
326/// Persisted application settings — pure data type with no I/O.
327///
328/// Use `SettingsStore` to load and save instances of this type.
329#[derive(Debug, Clone, Serialize, Deserialize)]
330pub struct Settings {
331    pub last_provider: ProviderKind,
332    /// Last URL used for the active provider. Set automatically by `--config`
333    /// or by passing `--url`. Persisted so subsequent runs don't re-prompt.
334    /// (default: None)
335    #[serde(default)]
336    pub last_provider_url: Option<String>,
337    pub last_model: Option<String>,
338    pub preferred_mode: AgentMode,
339    pub ollama_api_key: Option<String>,
340    /// API key sent as `Authorization: Bearer <key>` by the OpenAI-compatible
341    /// provider (`--openai-compat`). Set via `--api-key` or `OPENAI_API_KEY`
342    /// env var. Not used by Ollama, llama.cpp, vLLM, or Sockudo.
343    #[serde(default)]
344    pub openai_compat_api_key: Option<String>,
345    /// Sockudo app ID for the AI Transport provider.
346    #[serde(default)]
347    pub sockudo_app_id: Option<String>,
348    /// Sockudo app key (used as auth_key in signed API requests and WebSocket URL).
349    #[serde(default)]
350    pub sockudo_app_key: Option<String>,
351    /// Sockudo app secret (used to sign API requests via HMAC-SHA256).
352    #[serde(default)]
353    pub sockudo_app_secret: Option<String>,
354    /// Timeout in seconds for Ollama requests (default: 5)
355    pub ollama_timeout_secs: u64,
356    /// Maximum number of retries for Ollama requests (default: 3)
357    pub ollama_max_retries: u32,
358    /// Controls the think/reasoning level for Ollama (default: Medium)
359    pub ollama_think_type: OllamaThinkType,
360    /// Show the model's thinking/reasoning chain inline during streaming (default: false)
361    pub show_thinking: bool,
362    /// Context limit for warning calculations only (default: None, uses model default)
363    pub context_limit: Option<u32>,
364    /// Automatically accept safe read-only commands in the run tool (default: true)
365    pub auto_accept_safe_commands: bool,
366    /// Skip the provider health check at startup (default: false).
367    /// Useful for the `--openai-compat` provider when the gateway requires a
368    /// separate scope on `/health`, or for any server without a `/health`
369    /// endpoint. When true, the agent proceeds straight to model selection
370    /// and reports any connection error on the first real request instead.
371    #[serde(default)]
372    pub skip_health_check: bool,
373    /// List of command prefixes considered safe for auto-accept (default: see get_default_safe_commands)
374    pub safe_command_prefixes: Option<Vec<String>>,
375    /// List of command prefixes that are always denied auto-accept, even if they
376    /// match a safe prefix. Takes priority over the safe list. (default: empty)
377    pub denied_command_prefixes: Option<Vec<String>>,
378    /// Override the project instruction file discovery list.
379    /// When set, replaces the hardcoded default list (TINYHARNESS.md, AGENTS.md, etc.).
380    /// Use `TINYHARNESS_MD_FILES` env var for the highest priority override.
381    /// (default: None → use hardcoded defaults)
382    #[serde(default)]
383    pub project_md_files: Option<Vec<String>>,
384}
385
386impl Default for Settings {
387    fn default() -> Self {
388        Settings {
389            last_provider: ProviderKind::Ollama,
390            last_provider_url: None,
391            last_model: None,
392            preferred_mode: AgentMode::Casual,
393            ollama_api_key: None,
394            openai_compat_api_key: None,
395            sockudo_app_id: None,
396            sockudo_app_key: None,
397            sockudo_app_secret: None,
398            ollama_timeout_secs: 5,
399            ollama_max_retries: 3,
400            ollama_think_type: OllamaThinkType::Medium,
401            show_thinking: false,
402            context_limit: None,
403            auto_accept_safe_commands: true,
404            skip_health_check: false,
405            safe_command_prefixes: None,
406            denied_command_prefixes: None,
407            project_md_files: None,
408        }
409    }
410}
411
412/// Returns the default list of safe command prefixes.
413/// These are read-only commands that don't modify the filesystem.
414pub fn get_default_safe_commands() -> Vec<String> {
415    vec![
416        "cd".to_string(),
417        "ls".to_string(),
418        "grep".to_string(),
419        "glob".to_string(),
420        "find".to_string(),
421        "cat".to_string(),
422        "head".to_string(),
423        "tail".to_string(),
424        "wc".to_string(),
425        "pwd".to_string(),
426        "echo".to_string(),
427        "printf".to_string(),
428        "tree".to_string(),
429        "file".to_string(),
430        "stat".to_string(),
431        "du".to_string(),
432        "df".to_string(),
433        "free".to_string(),
434        "uptime".to_string(),
435        "whoami".to_string(),
436        "hostname".to_string(),
437        "uname".to_string(),
438        "date".to_string(),
439        "cal".to_string(),
440        "ps".to_string(),
441        "env".to_string(),
442        "printenv".to_string(),
443        "which".to_string(),
444        "whereis".to_string(),
445        "type".to_string(),
446        "git status".to_string(),
447        "git diff".to_string(),
448        "git log".to_string(),
449        "git show".to_string(),
450        "git branch".to_string(),
451        "git remote".to_string(),
452        "git tag".to_string(),
453        "git describe".to_string(),
454        "git rev-parse".to_string(),
455        "cargo tree".to_string(),
456        "cargo metadata".to_string(),
457        "cargo doc".to_string(),
458        "rustc --version".to_string(),
459        "cargo --version".to_string(),
460    ]
461}
462
463impl Settings {
464    /// Returns the list of safe command prefixes, using defaults if not configured.
465    pub fn get_safe_commands(&self) -> Vec<String> {
466        self.safe_command_prefixes
467            .clone()
468            .unwrap_or_else(get_default_safe_commands)
469    }
470
471    /// Returns the list of always-denied command prefixes.
472    /// These take priority over the safe list — if a command matches both
473    /// a safe prefix and a denied prefix, it is denied.
474    /// Defaults to an empty list (nothing denied).
475    pub fn get_denied_commands(&self) -> Vec<String> {
476        self.denied_command_prefixes.clone().unwrap_or_default()
477    }
478}
479
480// ── Errors ──────────────────────────────────────────────────────────────────
481
482/// Error type for settings I/O operations.
483#[derive(Debug)]
484pub enum SettingsError {
485    Io(std::io::Error),
486    Parse(serde_json::Error),
487}
488
489impl std::fmt::Display for SettingsError {
490    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491        match self {
492            SettingsError::Io(e) => write!(f, "I/O error: {}", e),
493            SettingsError::Parse(e) => write!(f, "parse error: {}", e),
494        }
495    }
496}
497
498impl std::error::Error for SettingsError {
499    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
500        match self {
501            SettingsError::Io(e) => Some(e),
502            SettingsError::Parse(e) => Some(e),
503        }
504    }
505}
506
507impl From<std::io::Error> for SettingsError {
508    fn from(e: std::io::Error) -> Self {
509        SettingsError::Io(e)
510    }
511}
512
513impl From<serde_json::Error> for SettingsError {
514    fn from(e: serde_json::Error) -> Self {
515        SettingsError::Parse(e)
516    }
517}
518
519// ── Settings store ─────────────────────────────────────────────────────────
520
521/// Handles persistence of [`Settings`] to disk.
522///
523/// By default, uses `~/.config/tinyharness/settings.json`. This can be
524/// overridden with [`SettingsStore::new`] for testing or alternative paths.
525pub struct SettingsStore {
526    path: std::path::PathBuf,
527}
528
529impl SettingsStore {
530    /// Create a store that reads/writes from the default path
531    /// (`~/.config/tinyharness/settings.json`).
532    pub fn default_path() -> Self {
533        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
534        let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
535        SettingsStore { path }
536    }
537
538    /// Create a store that reads/writes from a custom path.
539    pub fn new(path: std::path::PathBuf) -> Self {
540        SettingsStore { path }
541    }
542
543    /// Load settings from disk.
544    ///
545    /// Returns `Ok(Settings)` with defaults if the file doesn't exist,
546    /// or an error if the file exists but cannot be parsed.
547    pub fn load(&self) -> Result<Settings, SettingsError> {
548        if !self.path.exists() {
549            return Ok(Settings::default());
550        }
551        let content = std::fs::read_to_string(&self.path)?;
552        let settings = serde_json::from_str(&content)?;
553        Ok(settings)
554    }
555
556    /// Load settings from disk, returning defaults on any error.
557    ///
558    /// This matches the original behaviour and is suitable for application
559    /// startup where you don't want to fail on corrupt settings files.
560    pub fn load_or_default(&self) -> Settings {
561        self.load().unwrap_or_else(|e| {
562            tracing::warn!("Failed to load settings: {e}. Using defaults.");
563            Settings::default()
564        })
565    }
566
567    /// Save settings to disk atomically (write to temp file, then rename).
568    pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
569        let dir = self.path.parent().ok_or_else(|| {
570            SettingsError::Io(std::io::Error::new(
571                std::io::ErrorKind::InvalidInput,
572                "settings path has no parent directory",
573            ))
574        })?;
575        std::fs::create_dir_all(dir)?;
576
577        let json = serde_json::to_string_pretty(settings)?;
578        let tmp_path = dir.join("settings.json.tmp");
579
580        {
581            let mut file = std::fs::File::create(&tmp_path)?;
582            std::io::Write::write_all(&mut file, json.as_bytes())?;
583            std::io::Write::flush(&mut file)?;
584        }
585
586        std::fs::rename(&tmp_path, &self.path)?;
587        Ok(())
588    }
589
590    /// Returns the path where settings are stored.
591    pub fn path(&self) -> &std::path::Path {
592        &self.path
593    }
594}
595
596// ── Free convenience functions ─────────────────────────────────────────────
597
598/// Load settings from the default path, returning defaults on any error.
599///
600/// This is a convenience wrapper around [`SettingsStore::default_path().load_or_default()`].
601pub fn load_settings() -> Settings {
602    SettingsStore::default_path().load_or_default()
603}
604
605/// Save settings to the default path atomically.
606///
607/// This is a convenience wrapper around [`SettingsStore::default_path().save()`].
608/// On error, prints a warning to stderr (matching the original behaviour).
609pub fn save_settings(settings: &Settings) {
610    let store = SettingsStore::default_path();
611    if let Err(e) = store.save(settings) {
612        tracing::warn!("Failed to save settings: {e}");
613    }
614}
615
616// ── Prompt file management ──────────────────────────────────────────────────
617
618/// Resolve the effective list of project instruction file names to discover.
619///
620/// Priority (highest first):
621/// 1. `TINYHARNESS_MD_FILES` env var (comma-separated)
622/// 2. `settings.project_md_files` from global settings
623/// 3. Hardcoded default: TINYHARNESS.md, .tinyharness.md, AGENTS.md, CLAUDE.md
624pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
625    // 1. Env var takes highest priority
626    if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
627        let files: Vec<String> = env
628            .split(',')
629            .map(|s| s.trim().to_string())
630            .filter(|s| !s.is_empty())
631            .collect();
632        if !files.is_empty() {
633            return files;
634        }
635    }
636
637    // 2. Settings override
638    if let Some(s) = settings
639        && let Some(ref configured) = s.project_md_files
640        && !configured.is_empty()
641    {
642        return configured.clone();
643    }
644
645    // 3. Hardcoded defaults
646    crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
647        .iter()
648        .map(|s| s.to_string())
649        .collect()
650}
651
652/// Returns the directory where per-mode prompt `.md` files are stored.
653///
654/// Default: `~/.config/tinyharness/prompts/`
655pub fn prompts_dir() -> PathBuf {
656    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
657    PathBuf::from(home)
658        .join(".config")
659        .join("tinyharness")
660        .join("prompts")
661}
662
663/// Ensure the prompts directory exists and is seeded with `.md` files
664/// containing the hardcoded defaults for each mode, plus the shared header.
665///
666/// On first launch, this creates `~/.config/tinyharness/prompts/` and writes
667/// `header.md`, `casual.md`, `planning.md`, `agent.md`, and `research.md`.
668/// Existing files are **never** overwritten — users can safely customize them.
669///
670/// Returns the prompts directory path.
671pub fn ensure_prompts_initialized() -> PathBuf {
672    let dir = prompts_dir();
673    if !dir.exists() {
674        std::fs::create_dir_all(&dir).ok();
675    }
676
677    // Write shared header (new in 0.2 — always writes if missing)
678    {
679        let header_path = dir.join("header.md");
680        if !header_path.exists() {
681            let header_text = include_str!("../prompts/header.md");
682            if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
683                tracing::warn!(
684                    "Failed to write default header to {}: {e}",
685                    header_path.display(),
686                );
687            }
688        }
689    }
690
691    let modes = [
692        AgentMode::Casual,
693        AgentMode::Planning,
694        AgentMode::Agent,
695        AgentMode::Research,
696    ];
697
698    for mode in &modes {
699        let file_path = dir.join(mode.prompts_filename());
700        if !file_path.exists() {
701            let default_text = mode.default_system_prompt();
702            // Write the default, trimming leading/trailing whitespace/newlines
703            if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
704                tracing::warn!(
705                    "Failed to write default prompt to {}: {e}",
706                    file_path.display(),
707                );
708            }
709        }
710    }
711
712    dir
713}