tinyharness-lib 0.1.2

core liblary for tinyharness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use std::path::PathBuf;
use std::{fmt, str::FromStr};

use serde::{Deserialize, Serialize};

use crate::mode::AgentMode;

// ── Project Settings ────────────────────────────────────────────────────────

/// Per-project override settings discovered from `.tinyharness/config.json`.
///
/// All fields are `Option` — only present fields override the global setting.
/// Discovery walks up from CWD, same algorithm as `discover_project_md`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProjectSettings {
    /// Override safe command prefixes (extends, doesn't replace)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safe_command_prefixes: Option<Vec<String>>,
    /// Override denied command prefixes
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub denied_command_prefixes: Option<Vec<String>>,
    /// Override auto_accept_safe_commands
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_accept_safe_commands: Option<bool>,
    /// Override context_limit
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_limit: Option<u32>,
    /// Additional project-specific MD file names to include in context
    /// (e.g. ["RULES.md", ".cursorrules"]). These are loaded AFTER the main
    /// project instruction file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_md_files: Option<Vec<String>>,
    /// Override the preferred mode for this project
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preferred_mode: Option<AgentMode>,
}

/// Discover and load `.tinyharness/config.json` by walking up from CWD.
///
/// Returns `None` if no config file is found. Returns `Some(Err(...))` if
/// a file is found but cannot be parsed.
pub fn discover_project_settings(
    start_dir: &std::path::Path,
) -> Option<Result<ProjectSettings, SettingsError>> {
    let mut dir = start_dir.to_path_buf();

    loop {
        let candidate = dir.join(".tinyharness").join("config.json");
        if candidate.is_file() {
            let content = match std::fs::read_to_string(&candidate) {
                Ok(c) => c,
                Err(e) => return Some(Err(SettingsError::Io(e))),
            };
            let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
            return Some(parsed);
        }

        // Walk up one directory
        if let Some(parent) = dir.parent() {
            if parent == dir {
                break;
            }
            dir = parent.to_path_buf();
        } else {
            break;
        }
    }

    None
}

/// Source annotation for merged settings values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingSource {
    /// Value came from the global `~/.config/tinyharness/settings.json`
    Global,
    /// Value came from `.tinyharness/config.json`
    Project,
    /// Value is the hardcoded default (no config found)
    Default,
}

impl std::fmt::Display for SettingSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SettingSource::Global => f.write_str("global"),
            SettingSource::Project => f.write_str("project"),
            SettingSource::Default => f.write_str("default"),
        }
    }
}

/// Effective merged settings — the result of layering global + project settings.
///
/// This is a read-only view. Each field has a source annotation for display.
#[derive(Debug, Clone)]
pub struct MergedSettings {
    /// Merged safe command prefixes (project extends global)
    pub safe_commands: Vec<String>,
    pub safe_commands_source: SettingSource,
    /// Merged denied command prefixes (project overrides global)
    pub denied_commands: Vec<String>,
    pub denied_commands_source: SettingSource,
    pub auto_accept_safe_commands: bool,
    pub auto_accept_source: SettingSource,
    pub context_limit: Option<u32>,
    pub context_limit_source: SettingSource,
    pub project_md_files: Vec<String>,
    pub project_md_files_source: SettingSource,
    pub preferred_mode: AgentMode,
    pub preferred_mode_source: SettingSource,
}

/// Load and merge global + project settings.
///
/// Layering: project overrides global where specified, otherwise falls back
/// to global. For safe commands, project *extends* the global list rather
/// than replacing it.
pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
    let global = load_settings();

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project = match discover_project_settings(&cwd) {
        Some(Ok(ps)) => Some(ps),
        Some(Err(e)) => {
            tracing::warn!(
                "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
            );
            None
        }
        None => None,
    };

    let merged = merge_settings(&global, project.as_ref());
    (global, project, merged)
}

/// Merge global settings with optional project overrides.
fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
    let global_safe = global.get_safe_commands();
    let global_denied = global.get_denied_commands();

    match project {
        None => MergedSettings {
            safe_commands: global_safe,
            safe_commands_source: SettingSource::Default,
            denied_commands: global_denied,
            denied_commands_source: SettingSource::Default,
            auto_accept_safe_commands: global.auto_accept_safe_commands,
            auto_accept_source: SettingSource::Default,
            context_limit: global.context_limit,
            context_limit_source: SettingSource::Default,
            project_md_files: Vec::new(),
            project_md_files_source: SettingSource::Default,
            preferred_mode: global.preferred_mode,
            preferred_mode_source: SettingSource::Default,
        },
        Some(p) => {
            // Safe commands: project extends global
            let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
                let mut combined = global_safe.clone();
                for cmd in proj_safe {
                    if !combined.contains(cmd) {
                        combined.push(cmd.clone());
                    }
                }
                combined
            } else {
                global_safe
            };
            let safe_source = if p.safe_command_prefixes.is_some() {
                SettingSource::Project
            } else {
                SettingSource::Default
            };

            // Denied commands: project replaces global
            let (denied_commands, denied_source) =
                if let Some(ref proj_denied) = p.denied_command_prefixes {
                    (proj_denied.clone(), SettingSource::Project)
                } else {
                    (global_denied, SettingSource::Default)
                };

            let (auto_accept, auto_source) = p
                .auto_accept_safe_commands
                .map(|v| (v, SettingSource::Project))
                .unwrap_or((global.auto_accept_safe_commands, SettingSource::Default));

            let (context_limit, ctx_source) = p
                .context_limit
                .map(|v| (Some(v), SettingSource::Project))
                .unwrap_or((global.context_limit, SettingSource::Default));

            let (project_md_files, md_source) = p
                .project_md_files
                .as_ref()
                .map(|files| (files.clone(), SettingSource::Project))
                .unwrap_or((Vec::new(), SettingSource::Default));

            let (preferred_mode, mode_source) = p
                .preferred_mode
                .map(|m| (m, SettingSource::Project))
                .unwrap_or((global.preferred_mode, SettingSource::Default));

            MergedSettings {
                safe_commands,
                safe_commands_source: safe_source,
                denied_commands,
                denied_commands_source: denied_source,
                auto_accept_safe_commands: auto_accept,
                auto_accept_source: auto_source,
                context_limit,
                context_limit_source: ctx_source,
                project_md_files,
                project_md_files_source: md_source,
                preferred_mode,
                preferred_mode_source: mode_source,
            }
        }
    }
}

/// Generate a starter `.tinyharness/config.json` file from current settings
/// overrides that make sense for a project (safe commands, denied commands,
/// auto-accept, context limit).
pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
    ProjectSettings {
        safe_command_prefixes: settings.safe_command_prefixes.clone(),
        denied_command_prefixes: settings.denied_command_prefixes.clone(),
        auto_accept_safe_commands: Some(settings.auto_accept_safe_commands),
        context_limit: settings.context_limit,
        project_md_files: None, // user must fill this in
        preferred_mode: Some(settings.preferred_mode),
    }
}

/// Identifies which provider backend was used last.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ProviderKind {
    Ollama,
    LlamaCpp,
    Vllm,
}

impl fmt::Display for ProviderKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProviderKind::Ollama => f.write_str("ollama"),
            ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
            ProviderKind::Vllm => f.write_str("vllm"),
        }
    }
}

impl FromStr for ProviderKind {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "ollama" => Ok(ProviderKind::Ollama),
            "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
            "vllm" => Ok(ProviderKind::Vllm),
            _ => Err(format!("Unknown provider '{}'", s)),
        }
    }
}

/// Controls the "think" (reasoning) level for Ollama models that support it
/// (e.g. qwen2.5 variants). Affects how much internal reasoning the model does
/// before responding.
///
/// Corresponds to Ollama's `think` parameter. Only meaningful for Ollama;
/// other providers ignore this setting.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum OllamaThinkType {
    /// Disable thinking entirely (fastest, lowest quality).
    Off,
    /// Minimal reasoning (faster, lower latency).
    Low,
    /// Balanced reasoning (good default).
    Medium,
    /// Maximum reasoning (slowest, highest quality).
    High,
}

impl fmt::Display for OllamaThinkType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OllamaThinkType::Off => f.write_str("off"),
            OllamaThinkType::Low => f.write_str("low"),
            OllamaThinkType::Medium => f.write_str("medium"),
            OllamaThinkType::High => f.write_str("high"),
        }
    }
}

impl FromStr for OllamaThinkType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "off" | "false" | "0" => Ok(OllamaThinkType::Off),
            "low" => Ok(OllamaThinkType::Low),
            "medium" | "mid" => Ok(OllamaThinkType::Medium),
            "high" => Ok(OllamaThinkType::High),
            _ => Err(format!(
                "Unknown think type '{}'. Valid values: off, low, medium, high",
                s
            )),
        }
    }
}

/// Persisted application settings — pure data type with no I/O.
///
/// Use `SettingsStore` to load and save instances of this type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
    pub last_provider: ProviderKind,
    /// Last URL used for the active provider. Set automatically by `--config`
    /// or by passing `--url`. Persisted so subsequent runs don't re-prompt.
    /// (default: None)
    #[serde(default)]
    pub last_provider_url: Option<String>,
    pub last_model: Option<String>,
    pub preferred_mode: AgentMode,
    pub ollama_api_key: Option<String>,
    /// Timeout in seconds for Ollama requests (default: 5)
    pub ollama_timeout_secs: u64,
    /// Maximum number of retries for Ollama requests (default: 3)
    pub ollama_max_retries: u32,
    /// Controls the think/reasoning level for Ollama (default: Medium)
    pub ollama_think_type: OllamaThinkType,
    /// Show the model's thinking/reasoning chain inline during streaming (default: false)
    pub show_thinking: bool,
    /// Context limit for warning calculations only (default: None, uses model default)
    pub context_limit: Option<u32>,
    /// Automatically accept safe read-only commands in the run tool (default: true)
    pub auto_accept_safe_commands: bool,
    /// List of command prefixes considered safe for auto-accept (default: see get_default_safe_commands)
    pub safe_command_prefixes: Option<Vec<String>>,
    /// List of command prefixes that are always denied auto-accept, even if they
    /// match a safe prefix. Takes priority over the safe list. (default: empty)
    pub denied_command_prefixes: Option<Vec<String>>,
    /// Override the project instruction file discovery list.
    /// When set, replaces the hardcoded default list (TINYHARNESS.md, AGENTS.md, etc.).
    /// Use `TINYHARNESS_MD_FILES` env var for the highest priority override.
    /// (default: None → use hardcoded defaults)
    #[serde(default)]
    pub project_md_files: Option<Vec<String>>,
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            last_provider: ProviderKind::Ollama,
            last_provider_url: None,
            last_model: None,
            preferred_mode: AgentMode::Casual,
            ollama_api_key: None,
            ollama_timeout_secs: 5,
            ollama_max_retries: 3,
            ollama_think_type: OllamaThinkType::Medium,
            show_thinking: false,
            context_limit: None,
            auto_accept_safe_commands: true,
            safe_command_prefixes: None,
            denied_command_prefixes: None,
            project_md_files: None,
        }
    }
}

/// Returns the default list of safe command prefixes.
/// These are read-only commands that don't modify the filesystem.
pub fn get_default_safe_commands() -> Vec<String> {
    vec![
        "cd".to_string(),
        "ls".to_string(),
        "grep".to_string(),
        "glob".to_string(),
        "find".to_string(),
        "cat".to_string(),
        "head".to_string(),
        "tail".to_string(),
        "wc".to_string(),
        "pwd".to_string(),
        "echo".to_string(),
        "printf".to_string(),
        "tree".to_string(),
        "file".to_string(),
        "stat".to_string(),
        "du".to_string(),
        "df".to_string(),
        "free".to_string(),
        "uptime".to_string(),
        "whoami".to_string(),
        "hostname".to_string(),
        "uname".to_string(),
        "date".to_string(),
        "cal".to_string(),
        "ps".to_string(),
        "env".to_string(),
        "printenv".to_string(),
        "which".to_string(),
        "whereis".to_string(),
        "type".to_string(),
        "git status".to_string(),
        "git diff".to_string(),
        "git log".to_string(),
        "git show".to_string(),
        "git branch".to_string(),
        "git remote".to_string(),
        "git tag".to_string(),
        "git describe".to_string(),
        "git rev-parse".to_string(),
        "cargo tree".to_string(),
        "cargo metadata".to_string(),
        "cargo doc".to_string(),
        "rustc --version".to_string(),
        "cargo --version".to_string(),
    ]
}

impl Settings {
    /// Returns the list of safe command prefixes, using defaults if not configured.
    pub fn get_safe_commands(&self) -> Vec<String> {
        self.safe_command_prefixes
            .clone()
            .unwrap_or_else(get_default_safe_commands)
    }

    /// Returns the list of always-denied command prefixes.
    /// These take priority over the safe list — if a command matches both
    /// a safe prefix and a denied prefix, it is denied.
    /// Defaults to an empty list (nothing denied).
    pub fn get_denied_commands(&self) -> Vec<String> {
        self.denied_command_prefixes.clone().unwrap_or_default()
    }
}

// ── Errors ──────────────────────────────────────────────────────────────────

/// Error type for settings I/O operations.
#[derive(Debug)]
pub enum SettingsError {
    Io(std::io::Error),
    Parse(serde_json::Error),
}

impl std::fmt::Display for SettingsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SettingsError::Io(e) => write!(f, "I/O error: {}", e),
            SettingsError::Parse(e) => write!(f, "parse error: {}", e),
        }
    }
}

impl std::error::Error for SettingsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SettingsError::Io(e) => Some(e),
            SettingsError::Parse(e) => Some(e),
        }
    }
}

impl From<std::io::Error> for SettingsError {
    fn from(e: std::io::Error) -> Self {
        SettingsError::Io(e)
    }
}

impl From<serde_json::Error> for SettingsError {
    fn from(e: serde_json::Error) -> Self {
        SettingsError::Parse(e)
    }
}

// ── Settings store ─────────────────────────────────────────────────────────

/// Handles persistence of [`Settings`] to disk.
///
/// By default, uses `~/.config/tinyharness/settings.json`. This can be
/// overridden with [`SettingsStore::new`] for testing or alternative paths.
pub struct SettingsStore {
    path: std::path::PathBuf,
}

impl SettingsStore {
    /// Create a store that reads/writes from the default path
    /// (`~/.config/tinyharness/settings.json`).
    pub fn default_path() -> Self {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
        let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
        SettingsStore { path }
    }

    /// Create a store that reads/writes from a custom path.
    pub fn new(path: std::path::PathBuf) -> Self {
        SettingsStore { path }
    }

    /// Load settings from disk.
    ///
    /// Returns `Ok(Settings)` with defaults if the file doesn't exist,
    /// or an error if the file exists but cannot be parsed.
    pub fn load(&self) -> Result<Settings, SettingsError> {
        if !self.path.exists() {
            return Ok(Settings::default());
        }
        let content = std::fs::read_to_string(&self.path)?;
        let settings = serde_json::from_str(&content)?;
        Ok(settings)
    }

    /// Load settings from disk, returning defaults on any error.
    ///
    /// This matches the original behaviour and is suitable for application
    /// startup where you don't want to fail on corrupt settings files.
    pub fn load_or_default(&self) -> Settings {
        self.load().unwrap_or_else(|e| {
            tracing::warn!("Failed to load settings: {e}. Using defaults.");
            Settings::default()
        })
    }

    /// Save settings to disk atomically (write to temp file, then rename).
    pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
        let dir = self.path.parent().ok_or_else(|| {
            SettingsError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "settings path has no parent directory",
            ))
        })?;
        std::fs::create_dir_all(dir)?;

        let json = serde_json::to_string_pretty(settings)?;
        let tmp_path = dir.join("settings.json.tmp");

        {
            let mut file = std::fs::File::create(&tmp_path)?;
            std::io::Write::write_all(&mut file, json.as_bytes())?;
            std::io::Write::flush(&mut file)?;
        }

        std::fs::rename(&tmp_path, &self.path)?;
        Ok(())
    }

    /// Returns the path where settings are stored.
    pub fn path(&self) -> &std::path::Path {
        &self.path
    }
}

// ── Free convenience functions ─────────────────────────────────────────────

/// Load settings from the default path, returning defaults on any error.
///
/// This is a convenience wrapper around [`SettingsStore::default_path().load_or_default()`].
pub fn load_settings() -> Settings {
    SettingsStore::default_path().load_or_default()
}

/// Save settings to the default path atomically.
///
/// This is a convenience wrapper around [`SettingsStore::default_path().save()`].
/// On error, prints a warning to stderr (matching the original behaviour).
pub fn save_settings(settings: &Settings) {
    let store = SettingsStore::default_path();
    if let Err(e) = store.save(settings) {
        tracing::warn!("Failed to save settings: {e}");
    }
}

// ── Prompt file management ──────────────────────────────────────────────────

/// Resolve the effective list of project instruction file names to discover.
///
/// Priority (highest first):
/// 1. `TINYHARNESS_MD_FILES` env var (comma-separated)
/// 2. `settings.project_md_files` from global settings
/// 3. Hardcoded default: TINYHARNESS.md, .tinyharness.md, AGENTS.md, CLAUDE.md
pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
    // 1. Env var takes highest priority
    if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
        let files: Vec<String> = env
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        if !files.is_empty() {
            return files;
        }
    }

    // 2. Settings override
    if let Some(s) = settings
        && let Some(ref configured) = s.project_md_files
        && !configured.is_empty()
    {
        return configured.clone();
    }

    // 3. Hardcoded defaults
    crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
        .iter()
        .map(|s| s.to_string())
        .collect()
}

/// Returns the directory where per-mode prompt `.md` files are stored.
///
/// Default: `~/.config/tinyharness/prompts/`
pub fn prompts_dir() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home)
        .join(".config")
        .join("tinyharness")
        .join("prompts")
}

/// Ensure the prompts directory exists and is seeded with `.md` files
/// containing the hardcoded defaults for each mode, plus the shared header.
///
/// On first launch, this creates `~/.config/tinyharness/prompts/` and writes
/// `header.md`, `casual.md`, `planning.md`, `agent.md`, and `research.md`.
/// Existing files are **never** overwritten — users can safely customize them.
///
/// Returns the prompts directory path.
pub fn ensure_prompts_initialized() -> PathBuf {
    let dir = prompts_dir();
    if !dir.exists() {
        std::fs::create_dir_all(&dir).ok();
    }

    // Write shared header (new in 0.2 — always writes if missing)
    {
        let header_path = dir.join("header.md");
        if !header_path.exists() {
            let header_text = include_str!("../prompts/header.md");
            if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
                tracing::warn!(
                    "Failed to write default header to {}: {e}",
                    header_path.display(),
                );
            }
        }
    }

    let modes = [
        AgentMode::Casual,
        AgentMode::Planning,
        AgentMode::Agent,
        AgentMode::Research,
    ];

    for mode in &modes {
        let file_path = dir.join(mode.prompts_filename());
        if !file_path.exists() {
            let default_text = mode.default_system_prompt();
            // Write the default, trimming leading/trailing whitespace/newlines
            if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
                tracing::warn!(
                    "Failed to write default prompt to {}: {e}",
                    file_path.display(),
                );
            }
        }
    }

    dir
}