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