1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::{fmt, str::FromStr};
4
5use serde::{Deserialize, Serialize};
6
7use crate::SecretString;
8use crate::mode::AgentMode;
9
10#[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#[derive(Debug, Clone, Serialize, Deserialize, Default)]
104pub struct ProjectSettings {
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub safe_command_prefixes: Option<Vec<String>>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub denied_command_prefixes: Option<Vec<String>>,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub auto_accept_mode: Option<AutoAcceptMode>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub context_limit: Option<u32>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub project_md_files: Option<Vec<String>>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub preferred_mode: Option<AgentMode>,
125 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub auto_compact_enabled: Option<bool>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub questions_enabled: Option<bool>,
131}
132
133pub fn discover_project_settings(
138 start_dir: &std::path::Path,
139) -> Option<Result<ProjectSettings, SettingsError>> {
140 let mut dir = start_dir.to_path_buf();
141
142 loop {
143 let candidate = dir.join(".tinyharness").join("config.json");
144 if candidate.is_file() {
145 let content = match std::fs::read_to_string(&candidate) {
146 Ok(c) => c,
147 Err(e) => return Some(Err(SettingsError::Io(e))),
148 };
149 let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
150 return Some(parsed);
151 }
152
153 if let Some(parent) = dir.parent() {
155 if parent == dir {
156 break;
157 }
158 dir = parent.to_path_buf();
159 } else {
160 break;
161 }
162 }
163
164 None
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum SettingSource {
170 Global,
172 Project,
174 Default,
176}
177
178impl std::fmt::Display for SettingSource {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 match self {
181 SettingSource::Global => f.write_str("global"),
182 SettingSource::Project => f.write_str("project"),
183 SettingSource::Default => f.write_str("default"),
184 }
185 }
186}
187
188#[derive(Debug, Clone)]
192pub struct MergedSettings {
193 pub safe_commands: Vec<String>,
195 pub safe_commands_source: SettingSource,
196 pub denied_commands: Vec<String>,
198 pub denied_commands_source: SettingSource,
199 pub auto_accept_mode: AutoAcceptMode,
200 pub auto_accept_mode_source: SettingSource,
201 pub context_limit: Option<u32>,
202 pub context_limit_source: SettingSource,
203 pub project_md_files: Vec<String>,
204 pub project_md_files_source: SettingSource,
205 pub preferred_mode: AgentMode,
206 pub preferred_mode_source: SettingSource,
207 pub auto_compact_enabled: bool,
208 pub auto_compact_enabled_source: SettingSource,
209 pub questions_enabled: bool,
210 pub questions_enabled_source: SettingSource,
211}
212
213pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
219 let global = load_settings();
220
221 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
222 let project = match discover_project_settings(&cwd) {
223 Some(Ok(ps)) => Some(ps),
224 Some(Err(e)) => {
225 tracing::warn!(
226 "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
227 );
228 None
229 }
230 None => None,
231 };
232
233 let merged = merge_settings(&global, project.as_ref());
234 (global, project, merged)
235}
236
237fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
239 let global_safe = global.get_safe_commands();
240 let global_denied = global.get_denied_commands();
241
242 match project {
243 None => MergedSettings {
244 safe_commands: global_safe,
245 safe_commands_source: SettingSource::Default,
246 denied_commands: global_denied,
247 denied_commands_source: SettingSource::Default,
248 auto_accept_mode: global.auto_accept_mode,
249 auto_accept_mode_source: SettingSource::Default,
250 context_limit: global.context_limit,
251 context_limit_source: SettingSource::Default,
252 project_md_files: Vec::new(),
253 project_md_files_source: SettingSource::Default,
254 preferred_mode: global.preferred_mode,
255 preferred_mode_source: SettingSource::Default,
256 auto_compact_enabled: global.auto_compact_enabled,
257 auto_compact_enabled_source: SettingSource::Default,
258 questions_enabled: global.questions_enabled,
259 questions_enabled_source: SettingSource::Default,
260 },
261 Some(p) => {
262 let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
264 let mut combined = global_safe.clone();
265 for cmd in proj_safe {
266 if !combined.contains(cmd) {
267 combined.push(cmd.clone());
268 }
269 }
270 combined
271 } else {
272 global_safe
273 };
274 let safe_source = if p.safe_command_prefixes.is_some() {
275 SettingSource::Project
276 } else {
277 SettingSource::Default
278 };
279
280 let (denied_commands, denied_source) =
282 if let Some(ref proj_denied) = p.denied_command_prefixes {
283 (proj_denied.clone(), SettingSource::Project)
284 } else {
285 (global_denied, SettingSource::Default)
286 };
287
288 let (auto_accept_mode, auto_source) = p
289 .auto_accept_mode
290 .map(|v| (v, SettingSource::Project))
291 .unwrap_or((global.auto_accept_mode, SettingSource::Default));
292
293 let (context_limit, ctx_source) = p
294 .context_limit
295 .map(|v| (Some(v), SettingSource::Project))
296 .unwrap_or((global.context_limit, SettingSource::Default));
297
298 let (project_md_files, md_source) = p
299 .project_md_files
300 .as_ref()
301 .map(|files| (files.clone(), SettingSource::Project))
302 .unwrap_or((Vec::new(), SettingSource::Default));
303
304 let (preferred_mode, mode_source) = p
305 .preferred_mode
306 .map(|m| (m, SettingSource::Project))
307 .unwrap_or((global.preferred_mode, SettingSource::Default));
308
309 let (auto_compact_enabled, ac_source) = p
310 .auto_compact_enabled
311 .map(|v| (v, SettingSource::Project))
312 .unwrap_or((global.auto_compact_enabled, SettingSource::Default));
313
314 let (questions_enabled, q_source) = p
315 .questions_enabled
316 .map(|v| (v, SettingSource::Project))
317 .unwrap_or((global.questions_enabled, SettingSource::Default));
318
319 MergedSettings {
320 safe_commands,
321 safe_commands_source: safe_source,
322 denied_commands,
323 denied_commands_source: denied_source,
324 auto_accept_mode,
325 auto_accept_mode_source: auto_source,
326 context_limit,
327 context_limit_source: ctx_source,
328 project_md_files,
329 project_md_files_source: md_source,
330 preferred_mode,
331 preferred_mode_source: mode_source,
332 auto_compact_enabled,
333 auto_compact_enabled_source: ac_source,
334 questions_enabled,
335 questions_enabled_source: q_source,
336 }
337 }
338 }
339}
340
341impl MergedSettings {
342 pub fn tool_availability(&self) -> crate::tools::ToolAvailability {
344 crate::tools::ToolAvailability {
345 auto_compact: self.auto_compact_enabled,
346 question: self.questions_enabled,
347 }
348 }
349}
350
351pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
355 ProjectSettings {
356 safe_command_prefixes: settings.safe_command_prefixes.clone(),
357 denied_command_prefixes: settings.denied_command_prefixes.clone(),
358 auto_accept_mode: Some(settings.auto_accept_mode),
359 context_limit: settings.context_limit,
360 project_md_files: None, preferred_mode: Some(settings.preferred_mode),
362 auto_compact_enabled: Some(settings.auto_compact_enabled),
363 questions_enabled: Some(settings.questions_enabled),
364 }
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
369pub enum ProviderKind {
370 #[default]
371 Ollama,
372 LlamaCpp,
373 Vllm,
374 OpenAiCompat,
380 Sockudo,
381}
382
383impl fmt::Display for ProviderKind {
384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385 match self {
386 ProviderKind::Ollama => f.write_str("ollama"),
387 ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
388 ProviderKind::Vllm => f.write_str("vllm"),
389 ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
390 ProviderKind::Sockudo => f.write_str("sockudo"),
391 }
392 }
393}
394
395impl FromStr for ProviderKind {
396 type Err = String;
397
398 fn from_str(s: &str) -> Result<Self, Self::Err> {
399 match s.trim().to_lowercase().as_str() {
400 "ollama" => Ok(ProviderKind::Ollama),
401 "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
402 "vllm" => Ok(ProviderKind::Vllm),
403 "openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
404 "sockudo" => Ok(ProviderKind::Sockudo),
405 _ => Err(format!("Unknown provider '{}'", s)),
406 }
407 }
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
417pub enum OllamaThinkType {
418 Off,
420 Low,
422 #[default]
424 Medium,
425 High,
427}
428
429impl fmt::Display for OllamaThinkType {
430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431 match self {
432 OllamaThinkType::Off => f.write_str("off"),
433 OllamaThinkType::Low => f.write_str("low"),
434 OllamaThinkType::Medium => f.write_str("medium"),
435 OllamaThinkType::High => f.write_str("high"),
436 }
437 }
438}
439
440impl FromStr for OllamaThinkType {
441 type Err = String;
442
443 fn from_str(s: &str) -> Result<Self, Self::Err> {
444 match s.trim().to_lowercase().as_str() {
445 "off" | "false" | "0" => Ok(OllamaThinkType::Off),
446 "low" => Ok(OllamaThinkType::Low),
447 "medium" | "mid" => Ok(OllamaThinkType::Medium),
448 "high" => Ok(OllamaThinkType::High),
449 _ => Err(format!(
450 "Unknown think type '{}'. Valid values: off, low, medium, high",
451 s
452 )),
453 }
454 }
455}
456
457#[derive(Debug, Clone, Serialize, Deserialize)]
461#[serde(default)] pub struct Settings {
463 #[serde(default)]
464 pub last_provider: ProviderKind,
465 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
470 pub provider_urls: HashMap<ProviderKind, String>,
471 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
476 pub provider_models: HashMap<ProviderKind, String>,
477 #[serde(default)]
478 pub preferred_mode: AgentMode,
479 #[serde(default)]
480 pub ollama_api_key: Option<SecretString>,
481 pub openai_compat_api_key: Option<SecretString>,
485 pub sockudo_app_id: Option<String>,
487 pub sockudo_app_key: Option<String>,
489 pub sockudo_app_secret: Option<SecretString>,
491 #[serde(default)]
493 pub ollama_timeout_secs: u64,
494 #[serde(default)]
496 pub ollama_max_retries: u32,
497 #[serde(default)]
499 pub ollama_think_type: OllamaThinkType,
500 #[serde(default)]
502 pub show_thinking: bool,
503 pub context_limit: Option<u32>,
505 #[serde(default)]
515 pub auto_accept_mode: AutoAcceptMode,
516 pub skip_health_check: bool,
522 pub safe_command_prefixes: Option<Vec<String>>,
524 pub denied_command_prefixes: Option<Vec<String>>,
527 pub project_md_files: Option<Vec<String>>,
532 #[serde(default = "default_true")]
536 pub auto_compact_enabled: bool,
537 #[serde(default = "default_true")]
542 pub questions_enabled: bool,
543}
544
545fn default_true() -> bool {
546 true
547}
548
549impl Default for Settings {
550 fn default() -> Self {
551 Settings {
552 last_provider: ProviderKind::Ollama,
553 provider_urls: HashMap::new(),
554 provider_models: HashMap::new(),
555 preferred_mode: AgentMode::Casual,
556 ollama_api_key: None,
557 openai_compat_api_key: None,
558 sockudo_app_id: None,
559 sockudo_app_key: None,
560 sockudo_app_secret: None,
561 ollama_timeout_secs: 5,
562 ollama_max_retries: 3,
563 ollama_think_type: OllamaThinkType::Medium,
564 show_thinking: true,
565 context_limit: None,
566 auto_accept_mode: AutoAcceptMode::Safe,
567 skip_health_check: false,
568 safe_command_prefixes: None,
569 denied_command_prefixes: None,
570 project_md_files: None,
571 auto_compact_enabled: true,
572 questions_enabled: true,
573 }
574 }
575}
576
577pub fn get_default_safe_commands() -> Vec<String> {
580 vec![
581 "cd".to_string(),
582 "ls".to_string(),
583 "grep".to_string(),
584 "glob".to_string(),
585 "find".to_string(),
586 "cat".to_string(),
587 "head".to_string(),
588 "tail".to_string(),
589 "wc".to_string(),
590 "pwd".to_string(),
591 "echo".to_string(),
592 "printf".to_string(),
593 "tree".to_string(),
594 "file".to_string(),
595 "stat".to_string(),
596 "du".to_string(),
597 "df".to_string(),
598 "free".to_string(),
599 "uptime".to_string(),
600 "whoami".to_string(),
601 "hostname".to_string(),
602 "uname".to_string(),
603 "date".to_string(),
604 "cal".to_string(),
605 "ps".to_string(),
606 "env".to_string(),
607 "printenv".to_string(),
608 "which".to_string(),
609 "whereis".to_string(),
610 "type".to_string(),
611 "git status".to_string(),
612 "git diff".to_string(),
613 "git log".to_string(),
614 "git show".to_string(),
615 "git branch".to_string(),
616 "git remote".to_string(),
617 "git tag".to_string(),
618 "git describe".to_string(),
619 "git rev-parse".to_string(),
620 "cargo tree".to_string(),
621 "cargo metadata".to_string(),
622 "cargo doc".to_string(),
623 "rustc --version".to_string(),
624 "cargo --version".to_string(),
625 ]
626}
627
628impl Settings {
629 pub fn get_safe_commands(&self) -> Vec<String> {
631 self.safe_command_prefixes
632 .clone()
633 .unwrap_or_else(get_default_safe_commands)
634 }
635
636 pub fn get_denied_commands(&self) -> Vec<String> {
641 self.denied_command_prefixes.clone().unwrap_or_default()
642 }
643
644 pub fn get_url_for(&self, kind: ProviderKind) -> Option<&str> {
646 self.provider_urls.get(&kind).map(|s| s.as_str())
647 }
648
649 pub fn set_url_for(&mut self, kind: ProviderKind, url: String) {
651 self.provider_urls.insert(kind, url);
652 }
653
654 pub fn get_model_for(&self, kind: ProviderKind) -> Option<&str> {
656 self.provider_models.get(&kind).map(|s| s.as_str())
657 }
658
659 pub fn set_model_for(&mut self, kind: ProviderKind, model: String) {
661 self.provider_models.insert(kind, model);
662 }
663
664 pub fn get_current_model(&self) -> Option<&str> {
666 self.get_model_for(self.last_provider)
667 }
668
669 pub fn get_current_url(&self) -> Option<&str> {
671 self.get_url_for(self.last_provider)
672 }
673}
674
675#[derive(Debug)]
679pub enum SettingsError {
680 Io(std::io::Error),
681 Parse(serde_json::Error),
682}
683
684impl std::fmt::Display for SettingsError {
685 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686 match self {
687 SettingsError::Io(e) => write!(f, "I/O error: {}", e),
688 SettingsError::Parse(e) => write!(f, "parse error: {}", e),
689 }
690 }
691}
692
693impl std::error::Error for SettingsError {
694 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
695 match self {
696 SettingsError::Io(e) => Some(e),
697 SettingsError::Parse(e) => Some(e),
698 }
699 }
700}
701
702impl From<std::io::Error> for SettingsError {
703 fn from(e: std::io::Error) -> Self {
704 SettingsError::Io(e)
705 }
706}
707
708impl From<serde_json::Error> for SettingsError {
709 fn from(e: serde_json::Error) -> Self {
710 SettingsError::Parse(e)
711 }
712}
713
714pub struct SettingsStore {
721 path: std::path::PathBuf,
722}
723
724impl SettingsStore {
725 pub fn default_path() -> Self {
728 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
729 let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
730 SettingsStore { path }
731 }
732
733 pub fn new(path: std::path::PathBuf) -> Self {
735 SettingsStore { path }
736 }
737
738 pub fn load(&self) -> Result<Settings, SettingsError> {
743 self.cleanup_stale_temp_files();
746
747 if !self.path.exists() {
748 return Ok(Settings::default());
749 }
750 let content = std::fs::read_to_string(&self.path)?;
751 let mut settings: Settings = serde_json::from_str(&content)?;
752
753 if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
758 && let Some(obj) = raw.as_object()
759 && !obj.contains_key("auto_accept_mode")
760 {
761 if let Some(val) = obj.get("auto_accept_all") {
763 if val.as_bool() == Some(true) {
764 settings.auto_accept_mode = AutoAcceptMode::All;
765 } else if val.as_bool() == Some(false) {
766 settings.auto_accept_mode = AutoAcceptMode::Off;
767 }
768 }
769 else if let Some(val) = obj.get("auto_accept_safe_commands")
772 && val.as_bool() == Some(false)
773 {
774 settings.auto_accept_mode = AutoAcceptMode::Off;
775 }
776 }
777
778 if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
782 && let Some(obj) = raw.as_object()
783 {
784 if settings.provider_models.is_empty()
785 && let Some(model) = obj.get("last_model")
786 && let Some(model_str) = model.as_str()
787 && !model_str.is_empty()
788 {
789 settings
790 .provider_models
791 .insert(settings.last_provider, model_str.to_string());
792 }
793 if settings.provider_urls.is_empty()
794 && let Some(url) = obj.get("last_provider_url")
795 && let Some(url_str) = url.as_str()
796 && !url_str.is_empty()
797 {
798 settings
799 .provider_urls
800 .insert(settings.last_provider, url_str.to_string());
801 }
802 }
803
804 Ok(settings)
805 }
806
807 fn cleanup_stale_temp_files(&self) {
813 let Some(dir) = self.path.parent() else {
814 return;
815 };
816 let Ok(entries) = std::fs::read_dir(dir) else {
817 return;
818 };
819 for entry in entries.flatten() {
820 let name = entry.file_name();
821 let name = name.to_string_lossy();
822 if name.starts_with(".settings.json.tmp.")
823 && let Err(e) = std::fs::remove_file(entry.path())
824 {
825 tracing::debug!("Could not remove stale temp file {name}: {e}");
826 }
827 }
828 }
829
830 pub fn load_or_default(&self) -> Settings {
837 self.load().unwrap_or_else(|e| {
838 tracing::warn!("Failed to load settings: {e}. Using defaults.");
839 if self.path.exists() {
844 let backup = self.path.with_extension("json.corrupt");
845 if let Err(backup_err) = std::fs::rename(&self.path, &backup) {
846 tracing::warn!(
847 "Could not back up corrupt settings to {}: {backup_err}",
848 backup.display(),
849 );
850 } else {
851 tracing::warn!("Corrupt settings backed up to {}", backup.display(),);
852 }
853 }
854 Settings::default()
855 })
856 }
857
858 pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
865 let dir = self.path.parent().ok_or_else(|| {
866 SettingsError::Io(std::io::Error::new(
867 std::io::ErrorKind::InvalidInput,
868 "settings path has no parent directory",
869 ))
870 })?;
871 std::fs::create_dir_all(dir)?;
872
873 let json = serde_json::to_string_pretty(settings)?;
874
875 let tmp_name = format!(
879 ".settings.json.tmp.{}.{}",
880 std::process::id(),
881 std::time::SystemTime::now()
882 .duration_since(std::time::UNIX_EPOCH)
883 .map(|d| d.as_nanos())
884 .unwrap_or(0),
885 );
886 let tmp_path = dir.join(&tmp_name);
887
888 {
890 let mut file = std::fs::File::create(&tmp_path)?;
891 std::io::Write::write_all(&mut file, json.as_bytes())?;
892 std::io::Write::flush(&mut file)?;
893 file.sync_all()?;
898 }
899
900 std::fs::rename(&tmp_path, &self.path)?;
902 Ok(())
903 }
904
905 pub fn path(&self) -> &std::path::Path {
907 &self.path
908 }
909}
910
911pub fn load_settings() -> Settings {
918 SettingsStore::default_path().load_or_default()
919}
920
921pub fn save_settings(settings: &Settings) {
927 let store = SettingsStore::default_path();
928 if let Err(e) = store.save(settings) {
929 tracing::warn!("Failed to save settings: {e}");
930 }
931}
932
933pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
942 if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
944 let files: Vec<String> = env
945 .split(',')
946 .map(|s| s.trim().to_string())
947 .filter(|s| !s.is_empty())
948 .collect();
949 if !files.is_empty() {
950 return files;
951 }
952 }
953
954 if let Some(s) = settings
956 && let Some(ref configured) = s.project_md_files
957 && !configured.is_empty()
958 {
959 return configured.clone();
960 }
961
962 crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
964 .iter()
965 .map(|s| s.to_string())
966 .collect()
967}
968
969pub fn prompts_dir() -> PathBuf {
973 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
974 PathBuf::from(home)
975 .join(".config")
976 .join("tinyharness")
977 .join("prompts")
978}
979
980pub fn ensure_prompts_initialized() -> PathBuf {
989 let dir = prompts_dir();
990 if !dir.exists() {
991 std::fs::create_dir_all(&dir).ok();
992 }
993
994 {
996 let header_path = dir.join("header.md");
997 if !header_path.exists() {
998 let header_text = include_str!("../prompts/header.md");
999 if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
1000 tracing::warn!(
1001 "Failed to write default header to {}: {e}",
1002 header_path.display(),
1003 );
1004 }
1005 }
1006 }
1007
1008 let modes = [
1009 AgentMode::Casual,
1010 AgentMode::Planning,
1011 AgentMode::Agent,
1012 AgentMode::Research,
1013 ];
1014
1015 for mode in &modes {
1016 let file_path = dir.join(mode.prompts_filename());
1017 if !file_path.exists() {
1018 let default_text = mode.default_system_prompt();
1019 if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
1021 tracing::warn!(
1022 "Failed to write default prompt to {}: {e}",
1023 file_path.display(),
1024 );
1025 }
1026 }
1027 }
1028
1029 dir
1030}
1031
1032#[cfg(test)]
1035mod tests {
1036 use super::*;
1037
1038 #[test]
1041 fn load_settings_missing_fields_uses_defaults() {
1042 let json = r#"{
1043 "last_provider": "OpenAiCompat",
1044 "last_provider_url": "http://localhost:8080/v1",
1045 "last_model": "MiniMax-M3",
1046 "preferred_mode": "Agent",
1047 "ollama_api_key": null,
1048 "openai_compat_api_key": "sk-test",
1049 "ollama_timeout_secs": 5,
1050 "ollama_max_retries": 3,
1051 "ollama_think_type": "High",
1052 "show_thinking": true,
1053 "context_limit": 256000,
1054 "auto_accept_mode": "all",
1055 "skip_health_check": true
1056 }"#;
1057
1058 let settings: Settings =
1059 serde_json::from_str(json).expect("missing fields should use defaults");
1060 assert_eq!(settings.last_provider, ProviderKind::OpenAiCompat);
1061 assert_eq!(settings.preferred_mode, AgentMode::Agent);
1062 assert!(settings.skip_health_check);
1064 assert_eq!(settings.ollama_think_type, OllamaThinkType::High);
1065 }
1066
1067 #[test]
1069 fn load_settings_empty_object_uses_all_defaults() {
1070 let settings: Settings =
1071 serde_json::from_str("{}").expect("empty object should use defaults");
1072 assert_eq!(settings.last_provider, ProviderKind::Ollama);
1073 assert_eq!(settings.preferred_mode, AgentMode::Casual);
1074 assert!(!settings.skip_health_check);
1075 }
1076
1077 #[test]
1078 fn questions_enabled_defaults_to_true() {
1079 let settings: Settings =
1080 serde_json::from_str("{}").expect("empty object should use defaults");
1081 assert!(settings.questions_enabled);
1082 assert!(settings.auto_compact_enabled);
1083 assert!(Settings::default().questions_enabled);
1084 }
1085
1086 #[test]
1087 fn questions_enabled_can_be_disabled_and_roundtrips() {
1088 let store = SettingsStore::new(temp_settings_path());
1089 let settings = Settings {
1090 questions_enabled: false,
1091 ..Settings::default()
1092 };
1093 store.save(&settings).unwrap();
1094 let loaded = store.load().unwrap();
1095 assert!(!loaded.questions_enabled);
1096 assert!(loaded.auto_compact_enabled);
1098 let _ = std::fs::remove_dir_all(store.path().parent().unwrap());
1099 }
1100
1101 #[test]
1102 fn project_settings_override_questions_enabled() {
1103 let global = Settings {
1104 questions_enabled: true,
1105 ..Settings::default()
1106 };
1107
1108 let merged = merge_settings(&global, None);
1110 assert!(merged.questions_enabled);
1111 assert_eq!(merged.questions_enabled_source, SettingSource::Default);
1112
1113 let project = ProjectSettings {
1115 questions_enabled: Some(false),
1116 ..ProjectSettings::default()
1117 };
1118 let merged = merge_settings(&global, Some(&project));
1119 assert!(!merged.questions_enabled);
1120 assert_eq!(merged.questions_enabled_source, SettingSource::Project);
1121 }
1122
1123 #[test]
1124 fn project_settings_questions_absent_falls_back_to_global() {
1125 let global = Settings {
1126 questions_enabled: false,
1127 ..Settings::default()
1128 };
1129 let project = ProjectSettings::default();
1130 let merged = merge_settings(&global, Some(&project));
1131 assert!(!merged.questions_enabled);
1132 assert_eq!(merged.questions_enabled_source, SettingSource::Default);
1133 }
1134
1135 #[test]
1136 fn merged_settings_produce_tool_availability() {
1137 let global = Settings {
1138 questions_enabled: false,
1139 auto_compact_enabled: true,
1140 ..Settings::default()
1141 };
1142 let availability = merge_settings(&global, None).tool_availability();
1143 assert!(!availability.question);
1144 assert!(availability.auto_compact);
1145
1146 let global = Settings::default();
1147 let availability = merge_settings(&global, None).tool_availability();
1148 assert_eq!(availability, crate::tools::ToolAvailability::all());
1149 }
1150
1151 #[test]
1152 fn discover_project_settings_parses_questions_enabled() {
1153 let tmp = tempfile::tempdir().unwrap();
1154 let dir = tmp.path().join(".tinyharness");
1155 std::fs::create_dir_all(&dir).unwrap();
1156 std::fs::write(dir.join("config.json"), r#"{"questions_enabled": false}"#).unwrap();
1157
1158 let found = discover_project_settings(tmp.path()).expect("config should be discovered");
1159 let settings = found.expect("config should parse");
1160 assert_eq!(settings.questions_enabled, Some(false));
1161 assert_eq!(settings.auto_compact_enabled, None);
1162 }
1163
1164 #[test]
1165 fn generate_project_config_template_includes_questions() {
1166 let settings = Settings {
1167 questions_enabled: false,
1168 ..Settings::default()
1169 };
1170 let template = generate_project_config_template(&settings);
1171 assert_eq!(template.questions_enabled, Some(false));
1172 assert_eq!(template.auto_compact_enabled, Some(true));
1173 }
1174
1175 #[test]
1176 fn auto_accept_mode_from_string() {
1177 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "all"}"#).unwrap();
1178 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1179
1180 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "off"}"#).unwrap();
1181 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1182
1183 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "safe"}"#).unwrap();
1184 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
1185 }
1186
1187 #[test]
1188 fn auto_accept_mode_from_legacy_bool() {
1189 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": true}"#).unwrap();
1190 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1191
1192 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": false}"#).unwrap();
1193 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1194 }
1195 #[test]
1196 fn auto_accept_mode_from_legacy_all_field() {
1197 let store = SettingsStore::new(temp_settings_path());
1199 let json = r#"{"auto_accept_all": true}"#;
1200 std::fs::write(store.path(), json).unwrap();
1201 let settings = store.load().unwrap();
1202 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1203 let _ = std::fs::remove_file(store.path());
1204
1205 let store = SettingsStore::new(temp_settings_path());
1207 let json = r#"{"auto_accept_all": false}"#;
1208 std::fs::write(store.path(), json).unwrap();
1209 let settings = store.load().unwrap();
1210 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1211 let _ = std::fs::remove_file(store.path());
1212 }
1213 #[test]
1214 fn auto_accept_mode_from_legacy_safe_commands_field() {
1215 let store = SettingsStore::new(temp_settings_path());
1217 let json = r#"{"auto_accept_safe_commands": false}"#;
1218 std::fs::write(store.path(), json).unwrap();
1219 let settings = store.load().unwrap();
1220 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1221 let _ = std::fs::remove_file(store.path());
1222
1223 let store = SettingsStore::new(temp_settings_path());
1225 let json = r#"{"auto_accept_safe_commands": true}"#;
1226 std::fs::write(store.path(), json).unwrap();
1227 let settings = store.load().unwrap();
1228 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
1229 let _ = std::fs::remove_file(store.path());
1230 }
1231
1232 #[test]
1233 fn auto_accept_mode_explicit_overrides_legacy() {
1234 let settings: Settings =
1236 serde_json::from_str(r#"{"auto_accept_mode": "off", "auto_accept_all": true}"#)
1237 .unwrap();
1238 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1239 }
1240
1241 #[test]
1242 fn migrate_legacy_last_model_and_url() {
1243 let store = SettingsStore::new(temp_settings_path());
1244 let json = r#"{"last_provider": "Ollama", "last_model": "qwen2.5:7b", "last_provider_url": "http://localhost:11434"}"#;
1245 std::fs::write(store.path(), json).unwrap();
1246 let settings = store.load().unwrap();
1247 assert_eq!(
1248 settings.get_model_for(ProviderKind::Ollama),
1249 Some("qwen2.5:7b")
1250 );
1251 assert_eq!(
1252 settings.get_url_for(ProviderKind::Ollama),
1253 Some("http://localhost:11434")
1254 );
1255 let _ = std::fs::remove_file(store.path());
1256 }
1257
1258 #[test]
1259 fn migrate_legacy_fields_for_openai_compat() {
1260 let store = SettingsStore::new(temp_settings_path());
1261 let json = r#"{"last_provider": "OpenAiCompat", "last_model": "gpt-4o", "last_provider_url": "https://api.openai.com/v1"}"#;
1262 std::fs::write(store.path(), json).unwrap();
1263 let settings = store.load().unwrap();
1264 assert_eq!(
1265 settings.get_model_for(ProviderKind::OpenAiCompat),
1266 Some("gpt-4o")
1267 );
1268 assert_eq!(
1269 settings.get_url_for(ProviderKind::OpenAiCompat),
1270 Some("https://api.openai.com/v1")
1271 );
1272 assert_eq!(settings.get_model_for(ProviderKind::Ollama), None);
1274 let _ = std::fs::remove_file(store.path());
1275 }
1276
1277 #[test]
1278 fn per_provider_model_and_url_accessors() {
1279 let mut settings = Settings::default();
1280 settings.set_model_for(ProviderKind::Ollama, "qwen2.5:7b".to_string());
1281 settings.set_model_for(ProviderKind::LlamaCpp, "llama-3.1-8b".to_string());
1282 settings.set_url_for(ProviderKind::LlamaCpp, "http://localhost:8080".to_string());
1283
1284 assert_eq!(
1285 settings.get_model_for(ProviderKind::Ollama),
1286 Some("qwen2.5:7b")
1287 );
1288 assert_eq!(
1289 settings.get_model_for(ProviderKind::LlamaCpp),
1290 Some("llama-3.1-8b")
1291 );
1292 assert_eq!(settings.get_model_for(ProviderKind::Vllm), None);
1293 assert_eq!(
1294 settings.get_url_for(ProviderKind::LlamaCpp),
1295 Some("http://localhost:8080")
1296 );
1297 assert_eq!(settings.get_url_for(ProviderKind::Ollama), None);
1298 }
1299
1300 #[test]
1301 fn get_current_model_and_url_use_last_provider() {
1302 let mut settings = Settings {
1303 last_provider: ProviderKind::OpenAiCompat,
1304 ..Settings::default()
1305 };
1306 settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
1307 settings.set_url_for(
1308 ProviderKind::OpenAiCompat,
1309 "https://api.openai.com/v1".to_string(),
1310 );
1311
1312 assert_eq!(settings.get_current_model(), Some("gpt-4o"));
1313 assert_eq!(
1314 settings.get_current_url(),
1315 Some("https://api.openai.com/v1")
1316 );
1317 }
1318
1319 fn temp_settings_path() -> std::path::PathBuf {
1320 let mut dir = std::env::temp_dir();
1324 dir.push(format!(
1325 "tinyharness_test_{}_{}_{:?}",
1326 std::process::id(),
1327 std::time::SystemTime::now()
1328 .duration_since(std::time::UNIX_EPOCH)
1329 .map(|d| d.as_nanos())
1330 .unwrap_or(0),
1331 std::thread::current().id()
1332 ));
1333 std::fs::create_dir_all(&dir).unwrap();
1334 dir.push("settings.json");
1335 dir
1336 }
1337
1338 #[test]
1342 fn save_and_load_roundtrip() {
1343 let store = SettingsStore::new(temp_settings_path());
1344 let mut settings = Settings {
1345 last_provider: ProviderKind::OpenAiCompat,
1346 auto_accept_mode: AutoAcceptMode::All,
1347 ..Settings::default()
1348 };
1349 settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
1350
1351 store.save(&settings).unwrap();
1352 let loaded = store.load().unwrap();
1353 assert_eq!(loaded.last_provider, ProviderKind::OpenAiCompat);
1354 assert_eq!(
1355 loaded.get_model_for(ProviderKind::OpenAiCompat),
1356 Some("gpt-4o")
1357 );
1358 assert_eq!(loaded.auto_accept_mode, AutoAcceptMode::All);
1359
1360 let dir = store.path().parent().unwrap();
1362 let _ = std::fs::remove_dir_all(dir);
1363 }
1364
1365 #[test]
1368 fn corrupt_settings_backed_up_and_defaults_returned() {
1369 let store = SettingsStore::new(temp_settings_path());
1370 let corrupt_json = "{ this is not valid json !!!";
1371 std::fs::write(store.path(), corrupt_json).unwrap();
1372
1373 let settings = store.load_or_default();
1374 assert_eq!(settings.last_provider, ProviderKind::Ollama);
1375 assert_eq!(settings.preferred_mode, AgentMode::Casual);
1376
1377 assert!(!store.path().exists());
1379 let backup = store.path().with_extension("json.corrupt");
1380 assert!(backup.exists(), "corrupt settings should be backed up");
1381
1382 let backup_content = std::fs::read_to_string(&backup).unwrap();
1384 assert_eq!(backup_content, corrupt_json);
1385
1386 let dir = store.path().parent().unwrap();
1388 let _ = std::fs::remove_dir_all(dir);
1389 }
1390
1391 #[test]
1393 fn stale_temp_files_cleaned_up_on_load() {
1394 let store = SettingsStore::new(temp_settings_path());
1395 let dir = store.path().parent().unwrap();
1396 let tmp1 = dir.join(".settings.json.tmp.12345.999999999");
1397 let tmp2 = dir.join(".settings.json.tmp.67890.888888888");
1398 std::fs::write(&tmp1, "stale data").unwrap();
1399 std::fs::write(&tmp2, "more stale data").unwrap();
1400 assert!(tmp1.exists());
1401 assert!(tmp2.exists());
1402
1403 let _ = store.load();
1405
1406 assert!(!tmp1.exists(), "stale temp file should be removed");
1407 assert!(!tmp2.exists(), "stale temp file should be removed");
1408
1409 let _ = std::fs::remove_dir_all(dir);
1411 }
1412
1413 #[test]
1415 fn save_leaves_no_temp_files() {
1416 let store = SettingsStore::new(temp_settings_path());
1417 store.save(&Settings::default()).unwrap();
1418
1419 let dir = store.path().parent().unwrap();
1420 let entries = std::fs::read_dir(dir).unwrap();
1421 for entry in entries.flatten() {
1422 let name = entry.file_name();
1423 assert!(
1424 !name.to_string_lossy().starts_with(".settings.json.tmp."),
1425 "no temp files should remain after successful save"
1426 );
1427 }
1428
1429 let _ = std::fs::remove_dir_all(dir);
1430 }
1431
1432 #[test]
1434 fn multiple_saves_are_consistent() {
1435 let store = SettingsStore::new(temp_settings_path());
1436
1437 for i in 0..10 {
1438 let settings = Settings {
1439 ollama_timeout_secs: i,
1440 ..Settings::default()
1441 };
1442 store.save(&settings).unwrap();
1443 }
1444
1445 let loaded = store.load().unwrap();
1446 assert_eq!(loaded.ollama_timeout_secs, 9);
1447
1448 let dir = store.path().parent().unwrap();
1449 let _ = std::fs::remove_dir_all(dir);
1450 }
1451}