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
11/// `<config dir>/visdom/config.toml`.
12#[derive(Debug, Default, Deserialize)]
13pub struct UserConfig {
14    /// The agent `visdom` launches by default.
15    #[serde(default, deserialize_with = "de_agent")]
16    pub agent: Option<Agent>,
17    /// The bazaar MCP endpoint, when the server does not publish it.
18    #[serde(default)]
19    pub bazaar_url: Option<String>,
20    /// Per-agent executable overrides.
21    #[serde(default)]
22    pub agents: AgentCommands,
23}
24
25/// `[agents]`: the executable to run for an agent instead of the default.
26#[derive(Debug, Default, Deserialize)]
27pub struct AgentCommands {
28    #[serde(default, alias = "claude-code")]
29    pub claude_code: Option<String>,
30    #[serde(default)]
31    pub codex: Option<String>,
32}
33
34impl AgentCommands {
35    /// The configured executable for `agent`, if any.
36    pub fn program_for(&self, agent: Agent) -> Option<String> {
37        match agent {
38            Agent::ClaudeCode => self.claude_code.clone(),
39            Agent::Codex => self.codex.clone(),
40            _ => None,
41        }
42    }
43}
44
45/// `.visdom/config.toml` in a repository: a team-preferred agent.
46#[derive(Debug, Default, Deserialize)]
47pub struct RepoConfig {
48    #[serde(default, deserialize_with = "de_agent")]
49    pub agent: Option<Agent>,
50}
51
52/// The `[agents]` key that overrides `agent`'s executable.
53pub fn agent_config_key(agent: Agent) -> &'static str {
54    match agent {
55        Agent::ClaudeCode => "claude_code",
56        Agent::Codex => "codex",
57        Agent::Gsd => "gsd",
58        Agent::OpenCode => "opencode",
59        Agent::Amp => "amp",
60    }
61}
62
63/// Parse an agent name as the command line spells it (`claude-code`, `codex`).
64pub fn parse_agent(name: &str) -> Result<Agent, String> {
65    Agent::from_str(name.trim(), true)
66        .map_err(|_| format!("unknown agent `{name}` (visdom can launch claude-code and codex)"))
67}
68
69fn de_agent<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Agent>, D::Error> {
70    match Option::<String>::deserialize(d)? {
71        None => Ok(None),
72        Some(name) => parse_agent(&name)
73            .map(Some)
74            .map_err(serde::de::Error::custom),
75    }
76}
77
78pub fn user_config_path_in(config_root: &Path) -> PathBuf {
79    config_root.join("visdom").join("config.toml")
80}
81
82pub fn repo_config_path_in(project_root: &Path) -> PathBuf {
83    project_root.join(".visdom").join("config.toml")
84}
85
86fn load<T: Default + for<'de> Deserialize<'de>>(path: &Path) -> Result<T, String> {
87    let text = match std::fs::read_to_string(path) {
88        Ok(text) => text,
89        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()),
90        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
91    };
92    toml::from_str(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))
93}
94
95/// The user config under `config_root` (the platform config directory). A
96/// missing file is the default config.
97pub fn load_user_config_in(config_root: &Path) -> Result<UserConfig, String> {
98    load(&user_config_path_in(config_root))
99}
100
101/// The repository config in `project_root`. A missing file is the default.
102pub fn load_repo_config_in(project_root: &Path) -> Result<RepoConfig, String> {
103    load(&repo_config_path_in(project_root))
104}
105
106/// The agent somebody chose outside the command line: `VISDOM_AGENT`, then
107/// the repository config, then the user config. `None` when nobody did.
108pub fn configured_agent(
109    env: Option<&str>,
110    repo: &RepoConfig,
111    user: &UserConfig,
112) -> Result<Option<Agent>, String> {
113    match env.filter(|v| !v.trim().is_empty()) {
114        Some(name) => parse_agent(name)
115            .map(Some)
116            .map_err(|e| format!("VISDOM_AGENT: {e}")),
117        None => Ok(repo.agent.or(user.agent)),
118    }
119}
120
121/// Which agent to use: `--agent`, then `VISDOM_AGENT`, then the repository
122/// config, then the user config, then Claude Code. Only Claude Code and Codex
123/// can be launched.
124pub fn resolve_agent(
125    flag: Option<Agent>,
126    env: Option<&str>,
127    repo: &RepoConfig,
128    user: &UserConfig,
129) -> Result<Agent, String> {
130    let agent = match flag {
131        Some(agent) => agent,
132        None => configured_agent(env, repo, user)?.unwrap_or(Agent::ClaudeCode),
133    };
134    match agent {
135        Agent::ClaudeCode | Agent::Codex => Ok(agent),
136        other => Err(format!(
137            "visdom can launch claude-code and codex; {} is not supported yet",
138            other.tool_name()
139        )),
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn user(agent: Option<Agent>) -> UserConfig {
148        UserConfig {
149            agent,
150            ..Default::default()
151        }
152    }
153
154    #[test]
155    fn agent_precedence_flag_env_repo_user_default() {
156        let repo = RepoConfig {
157            agent: Some(Agent::Codex),
158        };
159        let none = RepoConfig::default();
160        let cases = [
161            // (flag, env, repo, user) => expected
162            (
163                Some(Agent::ClaudeCode),
164                Some("codex"),
165                &repo,
166                Some(Agent::Codex),
167                Agent::ClaudeCode,
168            ),
169            (
170                None,
171                Some("codex"),
172                &none,
173                Some(Agent::ClaudeCode),
174                Agent::Codex,
175            ),
176            (None, None, &repo, Some(Agent::ClaudeCode), Agent::Codex),
177            (None, None, &none, Some(Agent::Codex), Agent::Codex),
178            (None, None, &none, None, Agent::ClaudeCode),
179        ];
180        for (flag, env, repo, user_agent, expected) in cases {
181            assert_eq!(
182                resolve_agent(flag, env, repo, &user(user_agent)),
183                Ok(expected),
184                "flag={flag:?} env={env:?} repo={:?} user={user_agent:?}",
185                repo.agent
186            );
187        }
188        // An empty variable is the same as an unset one.
189        assert_eq!(
190            resolve_agent(None, Some(""), &none, &user(None)),
191            Ok(Agent::ClaudeCode)
192        );
193    }
194
195    #[test]
196    fn configured_agent_is_none_when_nobody_chose() {
197        let none = RepoConfig::default();
198        assert_eq!(configured_agent(None, &none, &user(None)), Ok(None));
199        assert_eq!(configured_agent(Some(" "), &none, &user(None)), Ok(None));
200        assert_eq!(
201            configured_agent(None, &none, &user(Some(Agent::Codex))),
202            Ok(Some(Agent::Codex))
203        );
204        assert_eq!(
205            configured_agent(Some("codex"), &none, &user(None)),
206            Ok(Some(Agent::Codex))
207        );
208        assert!(configured_agent(Some("emacs"), &none, &user(None)).is_err());
209    }
210
211    #[test]
212    fn unsupported_agent_is_error() {
213        let err = resolve_agent(
214            Some(Agent::Gsd),
215            None,
216            &RepoConfig::default(),
217            &UserConfig::default(),
218        )
219        .unwrap_err();
220        assert!(err.contains("gsd is not supported yet"), "{err}");
221        let err = resolve_agent(
222            None,
223            Some("emacs"),
224            &RepoConfig::default(),
225            &UserConfig::default(),
226        )
227        .unwrap_err();
228        assert!(
229            err.contains("VISDOM_AGENT") && err.contains("emacs"),
230            "{err}"
231        );
232    }
233
234    #[test]
235    fn missing_config_files_are_default() {
236        let tmp = tempfile::tempdir().unwrap();
237        let user = load_user_config_in(tmp.path()).unwrap();
238        assert!(user.agent.is_none() && user.bazaar_url.is_none());
239        assert!(load_repo_config_in(tmp.path()).unwrap().agent.is_none());
240    }
241
242    #[test]
243    fn user_config_reads_every_field() {
244        let tmp = tempfile::tempdir().unwrap();
245        let path = user_config_path_in(tmp.path());
246        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
247        std::fs::write(
248            &path,
249            "agent = \"codex\"\nbazaar_url = \"https://ctx.example.com/mcp/remote\"\n\
250             [agents]\nclaude_code = \"/opt/claude\"\ncodex = \"/opt/codex\"\n",
251        )
252        .unwrap();
253        let user = load_user_config_in(tmp.path()).unwrap();
254        assert_eq!(user.agent, Some(Agent::Codex));
255        assert_eq!(
256            user.bazaar_url.as_deref(),
257            Some("https://ctx.example.com/mcp/remote")
258        );
259        assert_eq!(
260            user.agents.program_for(Agent::ClaudeCode).as_deref(),
261            Some("/opt/claude")
262        );
263        assert_eq!(
264            user.agents.program_for(Agent::Codex).as_deref(),
265            Some("/opt/codex")
266        );
267    }
268
269    #[test]
270    fn malformed_user_config_is_error_naming_the_path() {
271        let tmp = tempfile::tempdir().unwrap();
272        let path = user_config_path_in(tmp.path());
273        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
274        std::fs::write(&path, "agent = [not toml").unwrap();
275        let err = load_user_config_in(tmp.path()).unwrap_err();
276        assert!(err.contains(&path.display().to_string()), "{err}");
277
278        std::fs::write(&path, "agent = \"emacs\"\n").unwrap();
279        let err = load_user_config_in(tmp.path()).unwrap_err();
280        assert!(err.contains("emacs"), "{err}");
281    }
282}