Skip to main content

visdom_cli/
config.rs

1//! visdom's own settings: the user file (`<config dir>/visdom/config.toml`)
2//! and the optional committed repository file (`.visdom/config.toml`), plus
3//! the choice of agent.
4
5use std::path::{Path, PathBuf};
6
7use clap::ValueEnum;
8use serde::{Deserialize, Deserializer};
9use tracevault_cli::agent::Agent;
10
11use crate::mode::{parse_mode, TracingMode};
12
13/// `<config dir>/visdom/config.toml`.
14#[derive(Debug, Default, Deserialize)]
15pub struct UserConfig {
16    /// The agent `visdom` launches by default.
17    #[serde(default, deserialize_with = "de_agent")]
18    pub agent: Option<Agent>,
19    /// The bazaar MCP endpoint, when the server does not publish it.
20    #[serde(default)]
21    pub bazaar_url: Option<String>,
22    /// How this developer's sessions are traced: `hooks` or `gateway`.
23    #[serde(default, deserialize_with = "de_mode")]
24    pub tracing_mode: Option<TracingMode>,
25    /// Control Plane's address, when the server does not publish it.
26    #[serde(default)]
27    pub control_plane_url: Option<String>,
28    /// Per-agent executable overrides.
29    #[serde(default)]
30    pub agents: AgentCommands,
31    /// The AI Gateway, for `tracing_mode = "gateway"`.
32    #[serde(default)]
33    pub gateway: GatewayConfig,
34}
35
36/// `[gateway]`: how to reach and use the AI Gateway.
37#[derive(Debug, Default, Deserialize)]
38pub struct GatewayConfig {
39    /// The gateway console's address, when the server does not publish it.
40    #[serde(default)]
41    pub url: Option<String>,
42    /// The gateway project (its slug) whose personal key the agent uses.
43    #[serde(default)]
44    pub project: Option<String>,
45    /// The model alias Claude Code asks the gateway for.
46    #[serde(default, alias = "claude-code-model")]
47    pub claude_code_model: Option<String>,
48    /// The model alias Codex asks the gateway for.
49    #[serde(default, alias = "codex-model")]
50    pub codex_model: Option<String>,
51}
52
53impl GatewayConfig {
54    /// The configured model alias for `agent`, if any.
55    pub fn model_for(&self, agent: Agent) -> Option<String> {
56        match agent {
57            Agent::ClaudeCode => self.claude_code_model.clone(),
58            Agent::Codex => self.codex_model.clone(),
59            _ => None,
60        }
61    }
62}
63
64/// `[agents]`: the executable to run for an agent instead of the default.
65#[derive(Debug, Default, Deserialize)]
66pub struct AgentCommands {
67    #[serde(default, alias = "claude-code")]
68    pub claude_code: Option<String>,
69    #[serde(default)]
70    pub codex: Option<String>,
71}
72
73impl AgentCommands {
74    /// The configured executable for `agent`, if any.
75    pub fn program_for(&self, agent: Agent) -> Option<String> {
76        match agent {
77            Agent::ClaudeCode => self.claude_code.clone(),
78            Agent::Codex => self.codex.clone(),
79            _ => None,
80        }
81    }
82}
83
84/// `.visdom/config.toml` in a repository: what the team prefers for it.
85#[derive(Debug, Default, Deserialize)]
86pub struct RepoConfig {
87    #[serde(default, deserialize_with = "de_agent")]
88    pub agent: Option<Agent>,
89    /// The tracing mode the team prefers here; a developer's own choice on
90    /// the command line or in the environment still wins.
91    #[serde(default, deserialize_with = "de_mode")]
92    pub tracing_mode: Option<TracingMode>,
93    #[serde(default)]
94    pub gateway: RepoGatewayConfig,
95}
96
97/// `[gateway]` in a repository: the gateway project this repository belongs to.
98#[derive(Debug, Default, Deserialize)]
99pub struct RepoGatewayConfig {
100    #[serde(default)]
101    pub project: Option<String>,
102}
103
104/// The `[agents]` key that overrides `agent`'s executable.
105pub fn agent_config_key(agent: Agent) -> &'static str {
106    match agent {
107        Agent::ClaudeCode => "claude_code",
108        Agent::Codex => "codex",
109        Agent::Gsd => "gsd",
110        Agent::OpenCode => "opencode",
111        Agent::Amp => "amp",
112    }
113}
114
115/// Parse an agent name as the command line spells it (`claude-code`, `codex`).
116pub fn parse_agent(name: &str) -> Result<Agent, String> {
117    Agent::from_str(name.trim(), true)
118        .map_err(|_| format!("unknown agent `{name}` (visdom can launch claude-code and codex)"))
119}
120
121fn de_agent<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Agent>, D::Error> {
122    match Option::<String>::deserialize(d)? {
123        None => Ok(None),
124        Some(name) => parse_agent(&name)
125            .map(Some)
126            .map_err(serde::de::Error::custom),
127    }
128}
129
130fn de_mode<'de, D: Deserializer<'de>>(d: D) -> Result<Option<TracingMode>, D::Error> {
131    match Option::<String>::deserialize(d)? {
132        None => Ok(None),
133        Some(name) => parse_mode(&name)
134            .map(Some)
135            .map_err(serde::de::Error::custom),
136    }
137}
138
139pub fn user_config_path_in(config_root: &Path) -> PathBuf {
140    config_root.join("visdom").join("config.toml")
141}
142
143pub fn repo_config_path_in(project_root: &Path) -> PathBuf {
144    project_root.join(".visdom").join("config.toml")
145}
146
147fn load<T: Default + for<'de> Deserialize<'de>>(path: &Path) -> Result<T, String> {
148    let text = match std::fs::read_to_string(path) {
149        Ok(text) => text,
150        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()),
151        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
152    };
153    toml::from_str(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))
154}
155
156/// The user config under `config_root` (the platform config directory). A
157/// missing file is the default config.
158pub fn load_user_config_in(config_root: &Path) -> Result<UserConfig, String> {
159    load(&user_config_path_in(config_root))
160}
161
162/// The repository config in `project_root`. A missing file is the default.
163pub fn load_repo_config_in(project_root: &Path) -> Result<RepoConfig, String> {
164    load(&repo_config_path_in(project_root))
165}
166
167/// The agent somebody chose outside the command line: `VISDOM_AGENT`, then
168/// the repository config, then the user config. `None` when nobody did.
169pub fn configured_agent(
170    env: Option<&str>,
171    repo: &RepoConfig,
172    user: &UserConfig,
173) -> Result<Option<Agent>, String> {
174    match env.filter(|v| !v.trim().is_empty()) {
175        Some(name) => parse_agent(name)
176            .map(Some)
177            .map_err(|e| format!("VISDOM_AGENT: {e}")),
178        None => Ok(repo.agent.or(user.agent)),
179    }
180}
181
182/// Which agent to use: `--agent`, then `VISDOM_AGENT`, then the repository
183/// config, then the user config, then Claude Code. Only Claude Code and Codex
184/// can be launched.
185pub fn resolve_agent(
186    flag: Option<Agent>,
187    env: Option<&str>,
188    repo: &RepoConfig,
189    user: &UserConfig,
190) -> Result<Agent, String> {
191    let agent = match flag {
192        Some(agent) => agent,
193        None => configured_agent(env, repo, user)?.unwrap_or(Agent::ClaudeCode),
194    };
195    match agent {
196        Agent::ClaudeCode | Agent::Codex => Ok(agent),
197        other => Err(format!(
198            "visdom can launch claude-code and codex; {} is not supported yet",
199            other.tool_name()
200        )),
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    fn user(agent: Option<Agent>) -> UserConfig {
209        UserConfig {
210            agent,
211            ..Default::default()
212        }
213    }
214
215    #[test]
216    fn agent_precedence_flag_env_repo_user_default() {
217        let repo = RepoConfig {
218            agent: Some(Agent::Codex),
219            ..Default::default()
220        };
221        let none = RepoConfig::default();
222        let cases = [
223            // (flag, env, repo, user) => expected
224            (
225                Some(Agent::ClaudeCode),
226                Some("codex"),
227                &repo,
228                Some(Agent::Codex),
229                Agent::ClaudeCode,
230            ),
231            (
232                None,
233                Some("codex"),
234                &none,
235                Some(Agent::ClaudeCode),
236                Agent::Codex,
237            ),
238            (None, None, &repo, Some(Agent::ClaudeCode), Agent::Codex),
239            (None, None, &none, Some(Agent::Codex), Agent::Codex),
240            (None, None, &none, None, Agent::ClaudeCode),
241        ];
242        for (flag, env, repo, user_agent, expected) in cases {
243            assert_eq!(
244                resolve_agent(flag, env, repo, &user(user_agent)),
245                Ok(expected),
246                "flag={flag:?} env={env:?} repo={:?} user={user_agent:?}",
247                repo.agent
248            );
249        }
250        // An empty variable is the same as an unset one.
251        assert_eq!(
252            resolve_agent(None, Some(""), &none, &user(None)),
253            Ok(Agent::ClaudeCode)
254        );
255    }
256
257    #[test]
258    fn configured_agent_is_none_when_nobody_chose() {
259        let none = RepoConfig::default();
260        assert_eq!(configured_agent(None, &none, &user(None)), Ok(None));
261        assert_eq!(configured_agent(Some(" "), &none, &user(None)), Ok(None));
262        assert_eq!(
263            configured_agent(None, &none, &user(Some(Agent::Codex))),
264            Ok(Some(Agent::Codex))
265        );
266        assert_eq!(
267            configured_agent(Some("codex"), &none, &user(None)),
268            Ok(Some(Agent::Codex))
269        );
270        assert!(configured_agent(Some("emacs"), &none, &user(None)).is_err());
271    }
272
273    #[test]
274    fn unsupported_agent_is_error() {
275        let err = resolve_agent(
276            Some(Agent::Gsd),
277            None,
278            &RepoConfig::default(),
279            &UserConfig::default(),
280        )
281        .unwrap_err();
282        assert!(err.contains("gsd is not supported yet"), "{err}");
283        let err = resolve_agent(
284            None,
285            Some("emacs"),
286            &RepoConfig::default(),
287            &UserConfig::default(),
288        )
289        .unwrap_err();
290        assert!(
291            err.contains("VISDOM_AGENT") && err.contains("emacs"),
292            "{err}"
293        );
294    }
295
296    #[test]
297    fn missing_config_files_are_default() {
298        let tmp = tempfile::tempdir().unwrap();
299        let user = load_user_config_in(tmp.path()).unwrap();
300        assert!(user.agent.is_none() && user.bazaar_url.is_none());
301        assert!(load_repo_config_in(tmp.path()).unwrap().agent.is_none());
302    }
303
304    #[test]
305    fn user_config_reads_every_field() {
306        let tmp = tempfile::tempdir().unwrap();
307        let path = user_config_path_in(tmp.path());
308        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
309        std::fs::write(
310            &path,
311            "agent = \"codex\"\nbazaar_url = \"https://ctx.example.com/mcp/remote\"\n\
312             [agents]\nclaude_code = \"/opt/claude\"\ncodex = \"/opt/codex\"\n",
313        )
314        .unwrap();
315        let user = load_user_config_in(tmp.path()).unwrap();
316        assert_eq!(user.agent, Some(Agent::Codex));
317        assert_eq!(
318            user.bazaar_url.as_deref(),
319            Some("https://ctx.example.com/mcp/remote")
320        );
321        assert_eq!(
322            user.agents.program_for(Agent::ClaudeCode).as_deref(),
323            Some("/opt/claude")
324        );
325        assert_eq!(
326            user.agents.program_for(Agent::Codex).as_deref(),
327            Some("/opt/codex")
328        );
329    }
330
331    #[test]
332    fn malformed_user_config_is_error_naming_the_path() {
333        let tmp = tempfile::tempdir().unwrap();
334        let path = user_config_path_in(tmp.path());
335        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
336        std::fs::write(&path, "agent = [not toml").unwrap();
337        let err = load_user_config_in(tmp.path()).unwrap_err();
338        assert!(err.contains(&path.display().to_string()), "{err}");
339
340        std::fs::write(&path, "agent = \"emacs\"\n").unwrap();
341        let err = load_user_config_in(tmp.path()).unwrap_err();
342        assert!(err.contains("emacs"), "{err}");
343    }
344
345    #[test]
346    fn the_tracing_mode_and_gateway_settings_are_read() {
347        let tmp = tempfile::tempdir().unwrap();
348        let path = user_config_path_in(tmp.path());
349        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
350        std::fs::write(
351            &path,
352            "tracing_mode = \"gateway\"\ncontrol_plane_url = \"https://cp.example.com\"\n\n\
353             [gateway]\nurl = \"https://gw.example.com\"\nproject = \"alpha\"\n\
354             claude_code_model = \"claude-sonnet\"\ncodex-model = \"gpt-general\"\n",
355        )
356        .unwrap();
357        let user = load_user_config_in(tmp.path()).unwrap();
358        assert_eq!(user.tracing_mode, Some(TracingMode::Gateway));
359        assert_eq!(
360            user.control_plane_url.as_deref(),
361            Some("https://cp.example.com")
362        );
363        assert_eq!(user.gateway.url.as_deref(), Some("https://gw.example.com"));
364        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
365        assert_eq!(
366            user.gateway.model_for(Agent::ClaudeCode).as_deref(),
367            Some("claude-sonnet")
368        );
369        assert_eq!(
370            user.gateway.model_for(Agent::Codex).as_deref(),
371            Some("gpt-general")
372        );
373        assert_eq!(user.gateway.model_for(Agent::Amp), None);
374    }
375
376    #[test]
377    fn a_repository_names_its_mode_and_gateway_project() {
378        let tmp = tempfile::tempdir().unwrap();
379        let path = repo_config_path_in(tmp.path());
380        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
381        std::fs::write(
382            &path,
383            "tracing_mode = \"hooks\"\n\n[gateway]\nproject = \"beta\"\n",
384        )
385        .unwrap();
386        let repo = load_repo_config_in(tmp.path()).unwrap();
387        assert_eq!(repo.tracing_mode, Some(TracingMode::Hooks));
388        assert_eq!(repo.gateway.project.as_deref(), Some("beta"));
389        assert_eq!(repo.agent, None);
390    }
391
392    #[test]
393    fn an_unknown_tracing_mode_is_a_config_error() {
394        let tmp = tempfile::tempdir().unwrap();
395        let path = user_config_path_in(tmp.path());
396        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
397        std::fs::write(&path, "tracing_mode = \"proxy\"\n").unwrap();
398        let err = load_user_config_in(tmp.path()).unwrap_err();
399        assert!(err.contains("hooks or gateway"), "{err}");
400    }
401}