Skip to main content

tracevault_cli/
config.rs

1use serde::{Deserialize, Serialize};
2use std::path::{Path, PathBuf};
3
4#[derive(Debug, Serialize, Deserialize)]
5pub struct TracevaultConfig {
6    #[serde(default = "default_agent")]
7    pub agent: String,
8    #[serde(default, skip_serializing_if = "Option::is_none")]
9    pub server_url: Option<String>,
10    // Never persisted; may still be parsed if present in a hand-authored file.
11    // No production code reads this field today (credentials are resolved
12    // independently in api_client.rs::resolve_credentials); kept on the
13    // struct for forward-compat / round-trip parsing of existing files.
14    #[serde(default, skip_serializing)]
15    #[allow(dead_code)]
16    pub api_key: Option<String>,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub org_slug: Option<String>,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub repo_id: Option<String>,
21    #[serde(default, skip_serializing_if = "is_default_user_context")]
22    pub user_context: UserContext,
23}
24
25fn default_agent() -> String {
26    "claude-code".to_string()
27}
28
29impl Default for TracevaultConfig {
30    fn default() -> Self {
31        Self {
32            agent: "claude-code".to_string(),
33            server_url: None,
34            api_key: None,
35            org_slug: None,
36            repo_id: None,
37            user_context: UserContext::default(),
38        }
39    }
40}
41
42/// Cross-repo user context source. Cargo-`dependency`-style shorthand:
43/// bool toggles enable at the default path; a string is enable + that path.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45#[serde(untagged)]
46pub enum UserContext {
47    Toggle(bool),
48    Path(String),
49    Full {
50        #[serde(default = "crate::config::enable_default")]
51        enable: bool,
52        #[serde(default)]
53        path: Option<String>,
54    },
55}
56
57impl Default for UserContext {
58    fn default() -> Self {
59        UserContext::Toggle(false)
60    }
61}
62
63pub(crate) fn enable_default() -> bool {
64    true
65}
66
67/// `~/.config/tracevault/context.json`, alongside credentials.json.
68pub fn default_user_context_path() -> PathBuf {
69    dirs::config_dir()
70        .unwrap_or_else(|| PathBuf::from("."))
71        .join("tracevault")
72        .join("context.json")
73}
74
75impl UserContext {
76    /// The file this source points at (configured path or default), regardless
77    /// of whether it is enabled. Used by `--user` editing.
78    pub fn path(&self) -> PathBuf {
79        match self {
80            UserContext::Path(p) => PathBuf::from(p),
81            UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
82            _ => default_user_context_path(),
83        }
84    }
85
86    /// `Some(path)` when enabled (consulted by the hook); `None` when disabled.
87    pub fn resolve(&self) -> Option<PathBuf> {
88        let enabled = match self {
89            UserContext::Toggle(b) => *b,
90            UserContext::Path(_) => true,
91            UserContext::Full { enable, .. } => *enable,
92        };
93        enabled.then(|| self.path())
94    }
95}
96
97fn is_default_user_context(uc: &UserContext) -> bool {
98    matches!(uc, UserContext::Toggle(false))
99}
100
101impl TracevaultConfig {
102    pub fn config_dir(project_root: &Path) -> PathBuf {
103        project_root.join(".tracevault")
104    }
105
106    pub fn config_path(project_root: &Path) -> PathBuf {
107        Self::config_dir(project_root).join("config.toml")
108    }
109
110    /// Runtime artifacts inside a `.tracevault/` directory that must never be
111    /// committed (`config.toml` and the `.gitignore` itself stay tracked).
112    const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";
113
114    /// Ensure a `.gitignore` exists inside `config_dir` (a `.tracevault/` dir)
115    /// so runtime artifacts are ignored no matter where the directory was
116    /// created — including the per-subproject `.tracevault/` dirs the stream
117    /// hook may create from a nested working directory. Idempotent: an existing
118    /// `.gitignore` is never overwritten. Best-effort; callers may ignore the
119    /// result (a failure must never break the hook).
120    pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
121        let path = config_dir.join(".gitignore");
122        if path.exists() {
123            return Ok(());
124        }
125        std::fs::write(path, Self::GITIGNORE_CONTENTS)
126    }
127
128    pub fn to_toml(&self) -> String {
129        let body = toml::to_string(self).unwrap_or_default();
130        format!("# TraceVault configuration\n{body}")
131    }
132
133    /// Load `config.toml`, distinguishing a **missing** file (`Ok(None)`) from a
134    /// present-but-**malformed** one (`Err(message)`). Callers that need to react
135    /// differently to those two cases (e.g. to avoid silently writing to a
136    /// default path when a configured one failed to parse) should use this.
137    ///
138    /// Only a genuine "not found" counts as missing; any other IO error (e.g.
139    /// permission denied) is surfaced as `Err` with the path, rather than being
140    /// masked as an absent config.
141    pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
142        let path = Self::config_path(project_root);
143        let content = match std::fs::read_to_string(&path) {
144            Ok(c) => c,
145            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
146            Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
147        };
148        toml::from_str(&content)
149            .map(Some)
150            .map_err(|e| e.to_string())
151    }
152
153    /// Lenient load: a missing **or** malformed `config.toml` yields `None`, with
154    /// a warning printed for the malformed case. Kept for callers that treat "no
155    /// usable config" uniformly; prefer [`try_load`](Self::try_load) when the
156    /// missing/malformed distinction matters.
157    pub fn load(project_root: &Path) -> Option<Self> {
158        match Self::try_load(project_root) {
159            Ok(cfg) => cfg,
160            Err(e) => {
161                eprintln!("tracevault: warning: malformed config.toml: {e}");
162                None
163            }
164        }
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use std::fs;
172
173    #[test]
174    fn to_toml_all_fields() {
175        let cfg = TracevaultConfig {
176            agent: "claude-code".into(),
177            server_url: Some("https://example.com".into()),
178            api_key: None, // api_key not included in to_toml
179            org_slug: Some("my-org".into()),
180            repo_id: Some("repo-1".into()),
181            user_context: UserContext::default(),
182        };
183        let toml = cfg.to_toml();
184        assert!(toml.contains("agent = \"claude-code\""));
185        assert!(toml.contains("server_url = \"https://example.com\""));
186        assert!(toml.contains("org_slug = \"my-org\""));
187        assert!(toml.contains("repo_id = \"repo-1\""));
188    }
189
190    #[test]
191    fn to_toml_minimal() {
192        let cfg = TracevaultConfig::default();
193        let toml = cfg.to_toml();
194        assert!(toml.contains("agent = \"claude-code\""));
195        assert!(!toml.contains("server_url"));
196    }
197
198    #[test]
199    fn load_valid_config() {
200        let dir = tempfile::tempdir().unwrap();
201        let tv_dir = dir.path().join(".tracevault");
202        fs::create_dir_all(&tv_dir).unwrap();
203        fs::write(
204            tv_dir.join("config.toml"),
205            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"myorg\"\n",
206        )
207        .unwrap();
208        let cfg = TracevaultConfig::load(dir.path()).unwrap();
209        assert_eq!(cfg.agent, "claude-code");
210        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
211        assert_eq!(cfg.org_slug.unwrap(), "myorg");
212    }
213
214    #[test]
215    fn load_missing_file_returns_none() {
216        let dir = tempfile::tempdir().unwrap();
217        assert!(TracevaultConfig::load(dir.path()).is_none());
218    }
219
220    #[test]
221    fn try_load_distinguishes_missing_valid_and_malformed() {
222        // Missing file → Ok(None), not an error.
223        let missing = tempfile::tempdir().unwrap();
224        assert!(matches!(
225            TracevaultConfig::try_load(missing.path()),
226            Ok(None)
227        ));
228
229        // Valid file → Ok(Some(cfg)).
230        let valid = tempfile::tempdir().unwrap();
231        let tv_dir = valid.path().join(".tracevault");
232        fs::create_dir_all(&tv_dir).unwrap();
233        fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
234        assert!(matches!(
235            TracevaultConfig::try_load(valid.path()),
236            Ok(Some(_))
237        ));
238
239        // Present but unparseable → Err (NOT silently treated as missing).
240        let bad = tempfile::tempdir().unwrap();
241        let bad_dir = bad.path().join(".tracevault");
242        fs::create_dir_all(&bad_dir).unwrap();
243        fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
244        assert!(TracevaultConfig::try_load(bad.path()).is_err());
245
246        // Present but unreadable (a non-NotFound IO error — here config.toml is a
247        // directory) → Err, NOT masked as missing.
248        let io = tempfile::tempdir().unwrap();
249        fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
250        assert!(TracevaultConfig::try_load(io.path()).is_err());
251    }
252
253    #[test]
254    fn ensure_gitignore_creates_runtime_ignore_file() {
255        let dir = tempfile::tempdir().unwrap();
256        let config_dir = dir.path().join(".tracevault");
257        fs::create_dir_all(&config_dir).unwrap();
258
259        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
260
261        let gitignore = config_dir.join(".gitignore");
262        assert!(gitignore.exists(), ".gitignore must be created");
263        let content = fs::read_to_string(&gitignore).unwrap();
264        assert!(content.contains("sessions/"), "must ignore sessions/");
265        assert!(content.contains("cache/"), "must ignore cache/");
266        assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
267    }
268
269    #[test]
270    fn toml_round_trip_omits_api_key_and_none_fields() {
271        let cfg = TracevaultConfig {
272            agent: "claude-code".into(),
273            server_url: Some("https://example.com".into()),
274            api_key: Some("secret".into()),
275            org_slug: Some("my-org".into()),
276            repo_id: None,
277            user_context: UserContext::default(),
278        };
279        let toml = cfg.to_toml();
280        assert!(toml.contains("agent = \"claude-code\""));
281        assert!(toml.contains("server_url = \"https://example.com\""));
282        assert!(toml.contains("org_slug = \"my-org\""));
283        assert!(!toml.contains("api_key"), "api_key must never be written");
284        assert!(!toml.contains("repo_id"), "None fields must be omitted");
285
286        // Re-parse (api_key absent from disk) round-trips the rest.
287        let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
288        assert_eq!(parsed.agent, "claude-code");
289        assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
290        assert_eq!(parsed.org_slug.as_deref(), Some("my-org"));
291        assert_eq!(parsed.api_key, None);
292    }
293
294    #[test]
295    fn user_context_forms_resolve_correctly() {
296        // absent ⇒ default ⇒ disabled
297        let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
298        assert!(none_cfg.user_context.resolve().is_none());
299
300        // false ⇒ disabled
301        let f: TracevaultConfig =
302            toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
303        assert!(f.user_context.resolve().is_none());
304
305        // true ⇒ enabled at default path
306        let t: TracevaultConfig =
307            toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
308        assert_eq!(t.user_context.resolve(), Some(default_user_context_path()));
309
310        // "path" ⇒ enabled at that path
311        let p: TracevaultConfig =
312            toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
313        assert_eq!(
314            p.user_context.resolve(),
315            Some(PathBuf::from("/tmp/ctx.json"))
316        );
317
318        // { enable = false, path = ... } ⇒ disabled but path() remembers it
319        let obj: TracevaultConfig = toml::from_str(
320            "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
321        )
322        .unwrap();
323        assert!(obj.user_context.resolve().is_none());
324        assert_eq!(obj.user_context.path(), PathBuf::from("/tmp/x.json"));
325    }
326
327    #[test]
328    fn ensure_gitignore_preserves_existing_file() {
329        let dir = tempfile::tempdir().unwrap();
330        let config_dir = dir.path().join(".tracevault");
331        fs::create_dir_all(&config_dir).unwrap();
332        let gitignore = config_dir.join(".gitignore");
333        fs::write(&gitignore, "custom-user-content\n").unwrap();
334
335        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
336
337        // Idempotent: an existing .gitignore is never overwritten.
338        assert_eq!(
339            fs::read_to_string(&gitignore).unwrap(),
340            "custom-user-content\n"
341        );
342    }
343}