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 = "Option::is_none")]
22    pub user_context: Option<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: None,
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/// Root of the user-level TraceVault config dir: `~/.config/tracevault/`
68/// (beside `credentials.json` / `context.json`). Falls back to `./tracevault`.
69pub fn tv_config_root() -> PathBuf {
70    dirs::config_dir()
71        .unwrap_or_else(|| PathBuf::from("."))
72        .join("tracevault")
73}
74
75pub fn user_config_path_in(config_root: &Path) -> PathBuf {
76    config_root.join("config.toml")
77}
78pub fn user_config_path() -> PathBuf {
79    user_config_path_in(&tv_config_root())
80}
81pub fn default_user_context_path_in(config_root: &Path) -> PathBuf {
82    config_root.join("context.json")
83}
84
85/// `~/.config/tracevault/context.json`, alongside credentials.json.
86/// Public path accessor (used by tests / lib consumers as the canonical default);
87/// production resolves via `UserContext::path`/`path_in`, so the bin has no direct
88/// caller.
89#[allow(dead_code)]
90pub fn default_user_context_path() -> PathBuf {
91    default_user_context_path_in(&tv_config_root())
92}
93
94/// Load the user-level `config.toml`, distinguishing a **missing** file
95/// (`Ok(None)`) from a malformed/unreadable one (`Err`). Mirrors
96/// `TracevaultConfig::try_load` but for a direct file path (the user-level
97/// config is NOT inside a `.tracevault/` dir).
98pub fn try_load_user_config_in(config_root: &Path) -> Result<Option<TracevaultConfig>, String> {
99    let path = user_config_path_in(config_root);
100    let content = match std::fs::read_to_string(&path) {
101        Ok(c) => c,
102        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
103        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
104    };
105    toml::from_str(&content)
106        .map(Some)
107        .map_err(|e| e.to_string())
108}
109
110/// Lenient: missing OR malformed → `TracevaultConfig::default()` (warn on malformed).
111pub fn load_user_config_in(config_root: &Path) -> TracevaultConfig {
112    match try_load_user_config_in(config_root) {
113        Ok(Some(cfg)) => cfg,
114        Ok(None) => TracevaultConfig::default(),
115        Err(e) => {
116            eprintln!("tracevault: warning: malformed user config.toml: {e}");
117            TracevaultConfig::default()
118        }
119    }
120}
121
122/// Resolve the effective user-context source. A repo that *configured* it
123/// (`Some`) wins — including an explicit `Some(Toggle(false))` (hard-off, no
124/// fallback). Only when the repo did NOT configure it (`None`) does the
125/// user-level `config.toml` under `config_root` supply it.
126pub fn resolve_user_context_in(
127    repo_configured: Option<UserContext>,
128    config_root: &Path,
129) -> UserContext {
130    repo_configured.unwrap_or_else(|| {
131        load_user_config_in(config_root)
132            .user_context
133            .unwrap_or_default()
134    })
135}
136
137/// [`resolve_user_context_in`] rooted at [`tv_config_root`].
138pub fn resolve_user_context(repo_configured: Option<UserContext>) -> UserContext {
139    resolve_user_context_in(repo_configured, &tv_config_root())
140}
141
142impl UserContext {
143    /// The file this source points at (configured path or default), regardless
144    /// of whether it is enabled. Used by `--user` editing.
145    pub fn path(&self) -> PathBuf {
146        self.path_in(&tv_config_root())
147    }
148
149    /// Like [`path`](Self::path), but resolves the "no explicit path" default
150    /// relative to `config_root` instead of the process-global
151    /// [`tv_config_root`]. This matters for the user-level `config.toml` (and
152    /// for tests with an injected root): its unconfigured default is the
153    /// `context.json` colocated with it under `config_root`, which need not be
154    /// the real `tv_config_root()`.
155    pub fn path_in(&self, config_root: &Path) -> PathBuf {
156        match self {
157            UserContext::Path(p) => PathBuf::from(p),
158            UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
159            _ => default_user_context_path_in(config_root),
160        }
161    }
162
163    /// `Some(path)` when enabled (consulted by the hook); `None` when disabled.
164    pub fn resolve(&self) -> Option<PathBuf> {
165        self.resolve_in(&tv_config_root())
166    }
167
168    /// Like [`resolve`](Self::resolve), but resolves the "no explicit path"
169    /// default relative to `config_root` (via [`path_in`](Self::path_in))
170    /// instead of the process-global [`tv_config_root`]. Callers that took an
171    /// injected `config_root` MUST use this — `resolve()` would leak back to
172    /// the real `~/.config` for the default-path case.
173    pub fn resolve_in(&self, config_root: &Path) -> Option<PathBuf> {
174        let enabled = match self {
175            UserContext::Toggle(b) => *b,
176            UserContext::Path(_) => true,
177            UserContext::Full { enable, .. } => *enable,
178        };
179        enabled.then(|| self.path_in(config_root))
180    }
181
182    /// Map `init`'s `--no-user-context` / `--user-context <path>` flags to a
183    /// *requested* user-context override. `Ok(None)` means neither flag was given
184    /// (the caller decides the default/preserve behavior). Rejects an empty/blank
185    /// `--user-context` value.
186    pub fn from_init_flags(
187        no_user_context: bool,
188        user_context: Option<String>,
189    ) -> Result<Option<UserContext>, String> {
190        match (no_user_context, user_context) {
191            (true, _) => Ok(Some(UserContext::Toggle(false))),
192            (false, Some(p)) if p.trim().is_empty() => {
193                Err("--user-context path must not be empty".to_string())
194            }
195            (false, Some(p)) => Ok(Some(UserContext::Path(p))),
196            (false, None) => Ok(None),
197        }
198    }
199}
200
201impl TracevaultConfig {
202    pub fn config_dir(project_root: &Path) -> PathBuf {
203        project_root.join(".tracevault")
204    }
205
206    pub fn config_path(project_root: &Path) -> PathBuf {
207        Self::config_dir(project_root).join("config.toml")
208    }
209
210    /// Runtime artifacts inside a `.tracevault/` directory that must never be
211    /// committed (`config.toml` and the `.gitignore` itself stay tracked).
212    const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";
213
214    /// Ensure a `.gitignore` exists inside `config_dir` (a `.tracevault/` dir)
215    /// so runtime artifacts are ignored no matter where the directory was
216    /// created — including the per-subproject `.tracevault/` dirs the stream
217    /// hook may create from a nested working directory. Idempotent: an existing
218    /// `.gitignore` is never overwritten. Best-effort; callers may ignore the
219    /// result (a failure must never break the hook).
220    pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
221        let path = config_dir.join(".gitignore");
222        if path.exists() {
223            return Ok(());
224        }
225        std::fs::write(path, Self::GITIGNORE_CONTENTS)
226    }
227
228    pub fn to_toml(&self) -> String {
229        let body = toml::to_string(self).unwrap_or_default();
230        format!("# TraceVault configuration\n{body}")
231    }
232
233    /// Load `config.toml`, distinguishing a **missing** file (`Ok(None)`) from a
234    /// present-but-**malformed** one (`Err(message)`). Callers that need to react
235    /// differently to those two cases (e.g. to avoid silently writing to a
236    /// default path when a configured one failed to parse) should use this.
237    ///
238    /// Only a genuine "not found" counts as missing; any other IO error (e.g.
239    /// permission denied) is surfaced as `Err` with the path, rather than being
240    /// masked as an absent config.
241    pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
242        let path = Self::config_path(project_root);
243        let content = match std::fs::read_to_string(&path) {
244            Ok(c) => c,
245            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
246            Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
247        };
248        toml::from_str(&content)
249            .map(Some)
250            .map_err(|e| e.to_string())
251    }
252
253    /// Lenient load: a missing **or** malformed `config.toml` yields `None`, with
254    /// a warning printed for the malformed case. Kept for callers that treat "no
255    /// usable config" uniformly; prefer [`try_load`](Self::try_load) when the
256    /// missing/malformed distinction matters.
257    pub fn load(project_root: &Path) -> Option<Self> {
258        match Self::try_load(project_root) {
259            Ok(cfg) => cfg,
260            Err(e) => {
261                eprintln!("tracevault: warning: malformed config.toml: {e}");
262                None
263            }
264        }
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271    use std::fs;
272
273    #[test]
274    fn to_toml_all_fields() {
275        let cfg = TracevaultConfig {
276            agent: "claude-code".into(),
277            server_url: Some("https://example.com".into()),
278            api_key: None, // api_key not included in to_toml
279            org_slug: Some("my-org".into()),
280            repo_id: Some("repo-1".into()),
281            user_context: None,
282        };
283        let toml = cfg.to_toml();
284        assert!(toml.contains("agent = \"claude-code\""));
285        assert!(toml.contains("server_url = \"https://example.com\""));
286        assert!(toml.contains("org_slug = \"my-org\""));
287        assert!(toml.contains("repo_id = \"repo-1\""));
288        assert!(
289            !toml.contains("user_context"),
290            "None user_context must be omitted"
291        );
292    }
293
294    #[test]
295    fn to_toml_minimal() {
296        let cfg = TracevaultConfig::default();
297        let toml = cfg.to_toml();
298        assert!(toml.contains("agent = \"claude-code\""));
299        assert!(!toml.contains("server_url"));
300    }
301
302    #[test]
303    fn load_valid_config() {
304        let dir = tempfile::tempdir().unwrap();
305        let tv_dir = dir.path().join(".tracevault");
306        fs::create_dir_all(&tv_dir).unwrap();
307        fs::write(
308            tv_dir.join("config.toml"),
309            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"myorg\"\n",
310        )
311        .unwrap();
312        let cfg = TracevaultConfig::load(dir.path()).unwrap();
313        assert_eq!(cfg.agent, "claude-code");
314        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
315        assert_eq!(cfg.org_slug.unwrap(), "myorg");
316    }
317
318    #[test]
319    fn load_missing_file_returns_none() {
320        let dir = tempfile::tempdir().unwrap();
321        assert!(TracevaultConfig::load(dir.path()).is_none());
322    }
323
324    #[test]
325    fn try_load_distinguishes_missing_valid_and_malformed() {
326        // Missing file → Ok(None), not an error.
327        let missing = tempfile::tempdir().unwrap();
328        assert!(matches!(
329            TracevaultConfig::try_load(missing.path()),
330            Ok(None)
331        ));
332
333        // Valid file → Ok(Some(cfg)).
334        let valid = tempfile::tempdir().unwrap();
335        let tv_dir = valid.path().join(".tracevault");
336        fs::create_dir_all(&tv_dir).unwrap();
337        fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
338        assert!(matches!(
339            TracevaultConfig::try_load(valid.path()),
340            Ok(Some(_))
341        ));
342
343        // Present but unparseable → Err (NOT silently treated as missing).
344        let bad = tempfile::tempdir().unwrap();
345        let bad_dir = bad.path().join(".tracevault");
346        fs::create_dir_all(&bad_dir).unwrap();
347        fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
348        assert!(TracevaultConfig::try_load(bad.path()).is_err());
349
350        // Present but unreadable (a non-NotFound IO error — here config.toml is a
351        // directory) → Err, NOT masked as missing.
352        let io = tempfile::tempdir().unwrap();
353        fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
354        assert!(TracevaultConfig::try_load(io.path()).is_err());
355    }
356
357    #[test]
358    fn ensure_gitignore_creates_runtime_ignore_file() {
359        let dir = tempfile::tempdir().unwrap();
360        let config_dir = dir.path().join(".tracevault");
361        fs::create_dir_all(&config_dir).unwrap();
362
363        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
364
365        let gitignore = config_dir.join(".gitignore");
366        assert!(gitignore.exists(), ".gitignore must be created");
367        let content = fs::read_to_string(&gitignore).unwrap();
368        assert!(content.contains("sessions/"), "must ignore sessions/");
369        assert!(content.contains("cache/"), "must ignore cache/");
370        assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
371    }
372
373    #[test]
374    fn toml_round_trip_omits_api_key_and_none_fields() {
375        let cfg = TracevaultConfig {
376            agent: "claude-code".into(),
377            server_url: Some("https://example.com".into()),
378            api_key: Some("secret".into()),
379            org_slug: Some("my-org".into()),
380            repo_id: None,
381            user_context: None,
382        };
383        let toml = cfg.to_toml();
384        assert!(toml.contains("agent = \"claude-code\""));
385        assert!(toml.contains("server_url = \"https://example.com\""));
386        assert!(toml.contains("org_slug = \"my-org\""));
387        assert!(!toml.contains("api_key"), "api_key must never be written");
388        assert!(!toml.contains("repo_id"), "None fields must be omitted");
389
390        // Re-parse (api_key absent from disk) round-trips the rest.
391        let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
392        assert_eq!(parsed.agent, "claude-code");
393        assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
394        assert_eq!(parsed.org_slug.as_deref(), Some("my-org"));
395        assert_eq!(parsed.api_key, None);
396    }
397
398    #[test]
399    fn user_context_forms_resolve_correctly() {
400        // absent ⇒ unset (never configured)
401        let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
402        assert!(none_cfg.user_context.is_none());
403
404        // false ⇒ disabled
405        let f: TracevaultConfig =
406            toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
407        assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
408        assert!(f.user_context.unwrap().resolve().is_none());
409
410        // true ⇒ enabled at default path
411        let t: TracevaultConfig =
412            toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
413        assert_eq!(
414            t.user_context.unwrap().resolve(),
415            Some(default_user_context_path())
416        );
417
418        // "path" ⇒ enabled at that path
419        let p: TracevaultConfig =
420            toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
421        assert_eq!(
422            p.user_context.unwrap().resolve(),
423            Some(PathBuf::from("/tmp/ctx.json"))
424        );
425
426        // { enable = false, path = ... } ⇒ disabled but path() remembers it
427        let obj: TracevaultConfig = toml::from_str(
428            "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
429        )
430        .unwrap();
431        let obj_ctx = obj.user_context.unwrap();
432        assert!(obj_ctx.resolve().is_none());
433        assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
434    }
435
436    #[test]
437    fn explicit_disable_is_persisted_not_skipped() {
438        let cfg = TracevaultConfig {
439            user_context: Some(UserContext::Toggle(false)),
440            ..Default::default()
441        };
442        let toml = cfg.to_toml();
443        assert!(
444            toml.contains("user_context"),
445            "explicit off must serialize, got:\n{toml}"
446        );
447        let back: TracevaultConfig = toml::from_str(&toml).unwrap();
448        assert!(matches!(
449            back.user_context,
450            Some(UserContext::Toggle(false))
451        ));
452    }
453
454    #[test]
455    fn user_config_paths_are_under_config_root() {
456        let root = std::path::Path::new("/x/tracevault");
457        assert_eq!(
458            user_config_path_in(root),
459            std::path::Path::new("/x/tracevault/config.toml")
460        );
461        assert_eq!(
462            default_user_context_path_in(root),
463            std::path::Path::new("/x/tracevault/context.json")
464        );
465    }
466
467    #[test]
468    fn try_load_user_config_missing_is_ok_none() {
469        let dir = tempfile::tempdir().unwrap();
470        assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
471    }
472
473    #[test]
474    fn try_load_user_config_reads_user_context() {
475        let dir = tempfile::tempdir().unwrap();
476        std::fs::write(
477            user_config_path_in(dir.path()),
478            "agent=\"claude-code\"\nuser_context = true\n",
479        )
480        .unwrap();
481        let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
482        // Validate against the INJECTED root (resolve_in), not the real
483        // tv_config_root(): `user_context = true` resolves to the default
484        // `context.json` colocated under `dir`.
485        assert_eq!(
486            cfg.user_context.unwrap().resolve_in(dir.path()),
487            Some(default_user_context_path_in(dir.path()))
488        );
489    }
490
491    #[test]
492    fn try_load_user_config_malformed_is_err() {
493        let dir = tempfile::tempdir().unwrap();
494        std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
495        assert!(try_load_user_config_in(dir.path()).is_err());
496    }
497
498    #[test]
499    fn load_user_config_lenient_defaults_on_missing() {
500        let dir = tempfile::tempdir().unwrap();
501        assert!(load_user_config_in(dir.path()).user_context.is_none());
502    }
503
504    #[test]
505    fn load_user_config_lenient_defaults_on_malformed() {
506        // The hook depends on this fail-safe: a malformed user config.toml must
507        // degrade to a default (no user context), never propagate an error.
508        let dir = tempfile::tempdir().unwrap();
509        std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
510        assert!(load_user_config_in(dir.path()).user_context.is_none());
511    }
512
513    #[test]
514    fn resolve_user_context_prefers_repo_over_global() {
515        let dir = tempfile::tempdir().unwrap();
516        std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
517        // repo explicitly set (even explicit-off) → repo wins, NO global fallback
518        let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
519        assert!(
520            uc.resolve().is_none(),
521            "explicit repo-off must hard-disable"
522        );
523    }
524
525    #[test]
526    fn resolve_user_context_falls_back_to_global_when_repo_unset() {
527        let dir = tempfile::tempdir().unwrap();
528        std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
529        let uc = resolve_user_context_in(None, dir.path());
530        // Resolve against the injected root, not the real tv_config_root().
531        assert_eq!(
532            uc.resolve_in(dir.path()),
533            Some(default_user_context_path_in(dir.path()))
534        );
535    }
536
537    #[test]
538    fn resolve_user_context_off_when_neither_configured() {
539        let dir = tempfile::tempdir().unwrap();
540        assert!(resolve_user_context_in(None, dir.path())
541            .resolve()
542            .is_none());
543    }
544
545    #[test]
546    fn from_init_flags_maps_variants() {
547        assert!(matches!(
548            UserContext::from_init_flags(true, None),
549            Ok(Some(UserContext::Toggle(false)))
550        ));
551        assert!(matches!(
552            UserContext::from_init_flags(false, None),
553            Ok(None)
554        ));
555        assert!(matches!(
556            UserContext::from_init_flags(false, Some("/p".into())),
557            Ok(Some(UserContext::Path(_)))
558        ));
559        assert!(UserContext::from_init_flags(false, Some("  ".into())).is_err());
560    }
561
562    #[test]
563    fn ensure_gitignore_preserves_existing_file() {
564        let dir = tempfile::tempdir().unwrap();
565        let config_dir = dir.path().join(".tracevault");
566        fs::create_dir_all(&config_dir).unwrap();
567        let gitignore = config_dir.join(".gitignore");
568        fs::write(&gitignore, "custom-user-content\n").unwrap();
569
570        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
571
572        // Idempotent: an existing .gitignore is never overwritten.
573        assert_eq!(
574            fs::read_to_string(&gitignore).unwrap(),
575            "custom-user-content\n"
576        );
577    }
578}