Skip to main content

hematite/agent/
config.rs

1/// Hematite project-level configuration.
2///
3/// Read from `.hematite/settings.json` in the workspace root.
4/// Re-loaded at the start of every turn so edits take effect without restart.
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7
8fn default_true() -> bool {
9    true
10}
11
12#[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq)]
13pub enum PermissionMode {
14    #[default]
15    Developer,
16    ReadOnly,
17    SystemAdmin,
18}
19
20#[derive(Serialize, Deserialize, Default, Clone, Debug)]
21pub struct HematiteConfig {
22    /// Active authority mode.
23    #[serde(default)]
24    pub mode: PermissionMode,
25    /// Pattern-based permission overrides.
26    pub permissions: Option<PermissionRules>,
27    /// Workspace trust policy for the current project root.
28    #[serde(default)]
29    pub trust: WorkspaceTrustConfig,
30    /// Override the primary model ID (e.g. "gemma-4-e4b").
31    pub model: Option<String>,
32    /// Override the fast model ID used for read-only tasks.
33    pub fast_model: Option<String>,
34    /// Override the think model ID used for complex tasks.
35    pub think_model: Option<String>,
36    /// When true, Gemma 4 models enable native-formatting behavior automatically unless explicitly forced off.
37    #[serde(default = "default_true")]
38    pub gemma_native_auto: bool,
39    /// Force Gemma-native request shaping on for Gemma 4 models.
40    #[serde(default)]
41    pub gemma_native_formatting: bool,
42    /// Override the LLM provider base URL (e.g. "http://localhost:11434/v1" for Ollama).
43    /// Defaults to "http://localhost:1234/v1" (LM Studio). Takes precedence over --url CLI flag.
44    pub api_url: Option<String>,
45    /// Voice ID for TTS. Use /voice in the TUI to list and select. Defaults to "af_sky".
46    pub voice: Option<String>,
47    /// TTS speech speed multiplier. 1.0 = normal, 0.8 = slower, 1.3 = faster. Defaults to 1.0.
48    pub voice_speed: Option<f32>,
49    /// TTS volume. 0.0 = silent, 1.0 = normal, 2.0 = louder. Defaults to 1.0.
50    pub voice_volume: Option<f32>,
51    /// Extra text appended verbatim to the system prompt (project notes, conventions, etc.).
52    pub context_hint: Option<String>,
53    /// Override path to the Deno executable for the run_code sandbox.
54    /// If unset, Hematite checks LM Studio's bundled Deno, then system PATH.
55    /// Example: "C:/Users/you/.deno/bin/deno.exe"
56    pub deno_path: Option<String>,
57    /// Per-project verification commands for build/test/lint/fix workflows.
58    #[serde(default)]
59    pub verify: VerifyProfilesConfig,
60    /// Tool Lifecycle Hooks for automated pre/post scripts.
61    #[serde(default)]
62    pub hooks: crate::agent::hooks::RuntimeHookConfig,
63}
64
65#[derive(Serialize, Deserialize, Clone, Debug)]
66pub struct WorkspaceTrustConfig {
67    /// Workspace roots trusted for normal destructive and external tool posture.
68    #[serde(default = "default_trusted_workspace_roots")]
69    pub allow: Vec<String>,
70    /// Workspace roots explicitly denied for destructive and external tool posture.
71    #[serde(default)]
72    pub deny: Vec<String>,
73}
74
75impl Default for WorkspaceTrustConfig {
76    fn default() -> Self {
77        Self {
78            allow: default_trusted_workspace_roots(),
79            deny: Vec::new(),
80        }
81    }
82}
83
84fn default_trusted_workspace_roots() -> Vec<String> {
85    vec![".".to_string()]
86}
87
88#[derive(Serialize, Deserialize, Default, Clone, Debug)]
89pub struct VerifyProfilesConfig {
90    /// Optional default profile name to use when verify_build is called without an explicit profile.
91    pub default_profile: Option<String>,
92    /// Named verification profiles keyed by stack or workspace role.
93    #[serde(default)]
94    pub profiles: BTreeMap<String, VerifyProfile>,
95}
96
97#[derive(Serialize, Deserialize, Default, Clone, Debug)]
98pub struct VerifyProfile {
99    /// Build/compile validation command.
100    pub build: Option<String>,
101    /// Test command.
102    pub test: Option<String>,
103    /// Lint/static analysis command.
104    pub lint: Option<String>,
105    /// Optional auto-fix command, typically lint --fix or formatter repair.
106    pub fix: Option<String>,
107    /// Optional timeout override for this profile.
108    pub timeout_secs: Option<u64>,
109}
110
111#[derive(Serialize, Deserialize, Default, Clone, Debug)]
112pub struct PermissionRules {
113    /// Always auto-approve these patterns (e.g. "cargo *", "git status").
114    #[serde(default)]
115    pub allow: Vec<String>,
116    /// Always require approval for these patterns (e.g. "git push *").
117    #[serde(default)]
118    pub ask: Vec<String>,
119    /// Always deny these patterns outright (e.g. "rm -rf *").
120    #[serde(default)]
121    pub deny: Vec<String>,
122}
123
124pub fn settings_path() -> std::path::PathBuf {
125    crate::tools::file_ops::hematite_dir().join("settings.json")
126}
127
128/// Load global settings from `~/.hematite/settings.json` if present.
129fn load_global_config() -> Option<HematiteConfig> {
130    let home = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME"))?;
131    let path = std::path::PathBuf::from(home)
132        .join(".hematite")
133        .join("settings.json");
134    let data = std::fs::read_to_string(&path).ok()?;
135    serde_json::from_str(&data).ok()
136}
137
138/// Load `.hematite/settings.json` from the workspace root, with global
139/// `~/.hematite/settings.json` as a fallback for unset fields.
140/// Workspace config always wins; global fills in what workspace doesn't set.
141pub fn load_config() -> HematiteConfig {
142    let path = settings_path();
143
144    let workspace: Option<HematiteConfig> = if path.exists() {
145        std::fs::read_to_string(&path)
146            .ok()
147            .and_then(|d| serde_json::from_str(&d).ok())
148    } else {
149        write_default_config(&path);
150        None
151    };
152
153    let global = load_global_config();
154
155    match (workspace, global) {
156        (Some(ws), Some(gb)) => {
157            // Workspace wins on every field that isn't the zero/null default
158            HematiteConfig {
159                model: ws.model.or(gb.model),
160                fast_model: ws.fast_model.or(gb.fast_model),
161                think_model: ws.think_model.or(gb.think_model),
162                api_url: ws.api_url.or(gb.api_url),
163                voice: if ws.voice != HematiteConfig::default().voice {
164                    ws.voice
165                } else {
166                    gb.voice
167                },
168                voice_speed: ws.voice_speed.or(gb.voice_speed),
169                voice_volume: ws.voice_volume.or(gb.voice_volume),
170                context_hint: ws.context_hint.or(gb.context_hint),
171                gemma_native_auto: ws.gemma_native_auto,
172                gemma_native_formatting: ws.gemma_native_formatting,
173                ..ws
174            }
175        }
176        (Some(ws), None) => ws,
177        (None, Some(gb)) => gb,
178        (None, None) => HematiteConfig::default(),
179    }
180}
181
182pub fn save_config(config: &HematiteConfig) -> Result<(), String> {
183    let path = settings_path();
184    if let Some(parent) = path.parent() {
185        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
186    }
187    let json = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;
188    std::fs::write(&path, json).map_err(|e| e.to_string())
189}
190
191pub fn set_gemma_native_formatting(enabled: bool) -> Result<(), String> {
192    set_gemma_native_mode(if enabled { "on" } else { "off" })
193}
194
195pub fn set_gemma_native_mode(mode: &str) -> Result<(), String> {
196    let mut config = load_config();
197    match mode {
198        "on" => {
199            config.gemma_native_auto = false;
200            config.gemma_native_formatting = true;
201        }
202        "off" => {
203            config.gemma_native_auto = false;
204            config.gemma_native_formatting = false;
205        }
206        "auto" => {
207            config.gemma_native_auto = true;
208            config.gemma_native_formatting = false;
209        }
210        _ => return Err(format!("Unknown gemma native mode: {}", mode)),
211    }
212    save_config(&config)
213}
214
215pub fn set_voice(voice_id: &str) -> Result<(), String> {
216    let mut config = load_config();
217    config.voice = Some(voice_id.to_string());
218    save_config(&config)
219}
220
221pub fn effective_voice(config: &HematiteConfig) -> String {
222    config.voice.clone().unwrap_or_else(|| "af_sky".to_string())
223}
224
225pub fn effective_voice_speed(config: &HematiteConfig) -> f32 {
226    config.voice_speed.unwrap_or(1.0).clamp(0.5, 2.0)
227}
228
229pub fn effective_voice_volume(config: &HematiteConfig) -> f32 {
230    config.voice_volume.unwrap_or(1.0).clamp(0.0, 3.0)
231}
232
233pub fn effective_gemma_native_formatting(config: &HematiteConfig, model_name: &str) -> bool {
234    crate::agent::inference::is_gemma4_model_name(model_name)
235        && (config.gemma_native_formatting || config.gemma_native_auto)
236}
237
238pub fn gemma_native_mode_label(config: &HematiteConfig, model_name: &str) -> &'static str {
239    if !crate::agent::inference::is_gemma4_model_name(model_name) {
240        "inactive"
241    } else if config.gemma_native_formatting {
242        "on"
243    } else if config.gemma_native_auto {
244        "auto"
245    } else {
246        "off"
247    }
248}
249
250/// Write a commented default config on first run so users know what's available.
251fn write_default_config(path: &std::path::Path) {
252    if let Some(parent) = path.parent() {
253        let _ = std::fs::create_dir_all(parent);
254    }
255    let default = r#"{
256  "_comment": "Hematite settings — edit and save, changes apply immediately without restart.",
257
258  "permissions": {
259    "allow": [
260      "cargo *",
261      "git status",
262      "git log *",
263      "git diff *",
264      "git branch *"
265    ],
266    "ask": [],
267    "deny": []
268  },
269
270  "trust": {
271    "allow": ["."],
272    "deny": []
273  },
274
275  "auto_approve_moderate": false,
276
277  "api_url": null,
278  "voice": null,
279  "voice_speed": null,
280  "voice_volume": null,
281  "context_hint": null,
282  "model": null,
283  "fast_model": null,
284  "think_model": null,
285  "gemma_native_auto": true,
286  "gemma_native_formatting": false,
287
288  "verify": {
289    "default_profile": null,
290    "profiles": {
291      "rust": {
292        "build": "cargo build --color never",
293        "test": "cargo test --color never",
294        "lint": "cargo clippy --all-targets --all-features -- -D warnings",
295        "fix": "cargo fmt",
296        "timeout_secs": 120
297      }
298    }
299  },
300
301  "hooks": {
302    "pre_tool_use": [],
303    "post_tool_use": []
304  }
305}
306"#;
307    let _ = std::fs::write(path, default);
308}
309
310/// Returns the permission decision for a shell command given the loaded config.
311///
312/// Priority order (highest first):
313/// 1. deny rules  → always block (return true = needs approval / will be rejected)
314/// 2. allow rules → always approve (return false)
315/// 3. ask rules   → always ask (return true)
316/// 4. intrinsic risk classifier
317pub fn permission_for_shell(cmd: &str, config: &HematiteConfig) -> PermissionDecision {
318    if let Some(rules) = &config.permissions {
319        for pattern in &rules.deny {
320            if glob_matches(pattern, cmd) {
321                return PermissionDecision::Deny;
322            }
323        }
324        for pattern in &rules.allow {
325            if glob_matches(pattern, cmd) {
326                return PermissionDecision::Allow;
327            }
328        }
329        for pattern in &rules.ask {
330            if glob_matches(pattern, cmd) {
331                return PermissionDecision::Ask;
332            }
333        }
334    }
335    PermissionDecision::UseRiskClassifier
336}
337
338#[derive(Debug, PartialEq)]
339pub enum PermissionDecision {
340    Allow,
341    Deny,
342    Ask,
343    UseRiskClassifier,
344}
345
346/// Simple glob matcher: `*` is a wildcard, matching is case-insensitive.
347/// `cargo *` matches `cargo build`, `cargo check --all-targets`, etc.
348pub fn glob_matches(pattern: &str, text: &str) -> bool {
349    let p = pattern.to_lowercase();
350    let t = text.to_lowercase();
351    if p == "*" {
352        return true;
353    }
354    if let Some(star) = p.find('*') {
355        let prefix = &p[..star];
356        let suffix = &p[star + 1..];
357        t.starts_with(prefix) && (suffix.is_empty() || t.ends_with(suffix))
358    } else {
359        t.contains(&p)
360    }
361}