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 by this CLI (`skip_serializing`), but read back when a
11    /// hand-authored file supplies one: `resolve_credentials` uses it as the
12    /// lowest-precedence credential source. Not guarded by the server-URL
13    /// scoping there, since committing a key next to this config's own
14    /// `server_url` is a deliberate act.
15    #[serde(default, skip_serializing)]
16    pub api_key: Option<String>,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub repo_id: Option<String>,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub user_context: Option<UserContext>,
21    /// The remote (codebase)'s server-side id, resolved by `init` (best-effort)
22    /// via `resolve_remote`. Display-only today — `repo_id` stays authoritative
23    /// for ingest — but recorded so a future caller doesn't have to re-resolve.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub remote_id: Option<String>,
26    /// The codebase's registered name, resolved by `init` alongside `remote_id`.
27    /// Display-only — lets bound-mode `status` print the codebase without an
28    /// extra network round-trip.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub codebase_name: Option<String>,
31    /// LEGACY: a project **name**. Never written by this CLI any more (VIS-1256)
32    /// and never used for capture — resolving a name would cost a network call
33    /// per hook event. It is read only so `init` and `sync` can migrate it to
34    /// [`project_id`](Self::project_id) + [`project_name`](Self::project_name)
35    /// (see `commands::migrate`), and so `project status` can flag a config
36    /// that has not been migrated yet.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub default_project: Option<String>,
39    /// The project every session under this directory is attributed to (a
40    /// server UUID), written by `tracevault init --workspace --project <name>`
41    /// or by the `default_project` migration. The `workspace` tier of the
42    /// capture chain (`resolution::capture_project_binding`): below a
43    /// session's own `project switch`, above the user-level default. Read
44    /// locally, so the per-event hook needs no network call for it.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub project_id: Option<String>,
47    /// Display-only name of [`project_id`](Self::project_id), recorded when
48    /// it was resolved. Never used to resolve anything.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub project_name: Option<String>,
51}
52
53fn default_agent() -> String {
54    "claude-code".to_string()
55}
56
57impl Default for TracevaultConfig {
58    fn default() -> Self {
59        Self {
60            agent: "claude-code".to_string(),
61            server_url: None,
62            api_key: None,
63            repo_id: None,
64            user_context: None,
65            remote_id: None,
66            codebase_name: None,
67            default_project: None,
68            project_id: None,
69            project_name: None,
70        }
71    }
72}
73
74/// Cross-repo user context source. Cargo-`dependency`-style shorthand:
75/// bool toggles enable at the default path; a string is enable + that path.
76#[derive(Debug, Clone, Serialize, Deserialize)]
77#[serde(untagged)]
78pub enum UserContext {
79    Toggle(bool),
80    Path(String),
81    Full {
82        #[serde(default = "crate::config::enable_default")]
83        enable: bool,
84        #[serde(default)]
85        path: Option<String>,
86    },
87}
88
89impl Default for UserContext {
90    fn default() -> Self {
91        UserContext::Toggle(false)
92    }
93}
94
95pub(crate) fn enable_default() -> bool {
96    true
97}
98
99/// Root of the user-level TraceVault config dir: `~/.config/tracevault/`
100/// (beside `credentials.json` / `context.json`). Falls back to `./tracevault`.
101pub fn tv_config_root() -> PathBuf {
102    dirs::config_dir()
103        .unwrap_or_else(|| PathBuf::from("."))
104        .join("tracevault")
105}
106
107pub fn user_config_path_in(config_root: &Path) -> PathBuf {
108    config_root.join("config.toml")
109}
110pub fn user_config_path() -> PathBuf {
111    user_config_path_in(&tv_config_root())
112}
113pub fn default_user_context_path_in(config_root: &Path) -> PathBuf {
114    config_root.join("context.json")
115}
116
117/// `~/.config/tracevault/context.json`, alongside credentials.json.
118/// Public path accessor (used by tests / lib consumers as the canonical default);
119/// production resolves via `UserContext::path`/`path_in`, so the bin has no direct
120/// caller.
121#[allow(dead_code)]
122pub fn default_user_context_path() -> PathBuf {
123    default_user_context_path_in(&tv_config_root())
124}
125
126/// Load the user-level `config.toml`, distinguishing a **missing** file
127/// (`Ok(None)`) from a malformed/unreadable one (`Err`). Mirrors
128/// `TracevaultConfig::try_load` but for a direct file path (the user-level
129/// config is NOT inside a `.tracevault/` dir).
130pub fn try_load_user_config_in(config_root: &Path) -> Result<Option<TracevaultConfig>, String> {
131    let path = user_config_path_in(config_root);
132    let content = match std::fs::read_to_string(&path) {
133        Ok(c) => c,
134        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
135        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
136    };
137    toml::from_str(&content)
138        .map(Some)
139        .map_err(|e| e.to_string())
140}
141
142/// Lenient: missing OR malformed → `TracevaultConfig::default()` (warn on malformed).
143pub fn load_user_config_in(config_root: &Path) -> TracevaultConfig {
144    match try_load_user_config_in(config_root) {
145        Ok(Some(cfg)) => cfg,
146        Ok(None) => TracevaultConfig::default(),
147        Err(e) => {
148            eprintln!("tracevault: warning: malformed user config.toml: {e}");
149            TracevaultConfig::default()
150        }
151    }
152}
153
154/// Resolve the effective user-context source. A repo that *configured* it
155/// (`Some`) wins — including an explicit `Some(Toggle(false))` (hard-off, no
156/// fallback). Only when the repo did NOT configure it (`None`) does the
157/// user-level `config.toml` under `config_root` supply it.
158pub fn resolve_user_context_in(
159    repo_configured: Option<UserContext>,
160    config_root: &Path,
161) -> UserContext {
162    repo_configured.unwrap_or_else(|| {
163        load_user_config_in(config_root)
164            .user_context
165            .unwrap_or_default()
166    })
167}
168
169/// [`resolve_user_context_in`] rooted at [`tv_config_root`].
170pub fn resolve_user_context(repo_configured: Option<UserContext>) -> UserContext {
171    resolve_user_context_in(repo_configured, &tv_config_root())
172}
173
174impl UserContext {
175    /// The file this source points at (configured path or default), regardless
176    /// of whether it is enabled. Used by `--user` editing.
177    pub fn path(&self) -> PathBuf {
178        self.path_in(&tv_config_root())
179    }
180
181    /// Like [`path`](Self::path), but resolves the "no explicit path" default
182    /// relative to `config_root` instead of the process-global
183    /// [`tv_config_root`]. This matters for the user-level `config.toml` (and
184    /// for tests with an injected root): its unconfigured default is the
185    /// `context.json` colocated with it under `config_root`, which need not be
186    /// the real `tv_config_root()`.
187    pub fn path_in(&self, config_root: &Path) -> PathBuf {
188        match self {
189            UserContext::Path(p) => PathBuf::from(p),
190            UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
191            _ => default_user_context_path_in(config_root),
192        }
193    }
194
195    /// `Some(path)` when enabled (consulted by the hook); `None` when disabled.
196    pub fn resolve(&self) -> Option<PathBuf> {
197        self.resolve_in(&tv_config_root())
198    }
199
200    /// Like [`resolve`](Self::resolve), but resolves the "no explicit path"
201    /// default relative to `config_root` (via [`path_in`](Self::path_in))
202    /// instead of the process-global [`tv_config_root`]. Callers that took an
203    /// injected `config_root` MUST use this — `resolve()` would leak back to
204    /// the real `~/.config` for the default-path case.
205    pub fn resolve_in(&self, config_root: &Path) -> Option<PathBuf> {
206        let enabled = match self {
207            UserContext::Toggle(b) => *b,
208            UserContext::Path(_) => true,
209            UserContext::Full { enable, .. } => *enable,
210        };
211        enabled.then(|| self.path_in(config_root))
212    }
213
214    /// Map `init`'s `--no-user-context` / `--user-context <path>` flags to a
215    /// *requested* user-context override. `Ok(None)` means neither flag was given
216    /// (the caller decides the default/preserve behavior). Rejects an empty/blank
217    /// `--user-context` value.
218    pub fn from_init_flags(
219        no_user_context: bool,
220        user_context: Option<String>,
221    ) -> Result<Option<UserContext>, String> {
222        match (no_user_context, user_context) {
223            (true, _) => Ok(Some(UserContext::Toggle(false))),
224            (false, Some(p)) if p.trim().is_empty() => {
225                Err("--user-context path must not be empty".to_string())
226            }
227            (false, Some(p)) => Ok(Some(UserContext::Path(p))),
228            (false, None) => Ok(None),
229        }
230    }
231}
232
233impl TracevaultConfig {
234    pub fn config_dir(project_root: &Path) -> PathBuf {
235        project_root.join(".tracevault")
236    }
237
238    pub fn config_path(project_root: &Path) -> PathBuf {
239        Self::config_dir(project_root).join("config.toml")
240    }
241
242    /// Runtime artifacts inside a `.tracevault/` directory that must never be
243    /// committed (`config.toml` and the `.gitignore` itself stay tracked).
244    const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";
245
246    /// Ensure a `.gitignore` exists inside `config_dir` (a `.tracevault/` dir)
247    /// so runtime artifacts are ignored no matter where the directory was
248    /// created — including the per-subproject `.tracevault/` dirs the stream
249    /// hook may create from a nested working directory. Idempotent: an existing
250    /// `.gitignore` is never overwritten. Best-effort; callers may ignore the
251    /// result (a failure must never break the hook).
252    pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
253        let path = config_dir.join(".gitignore");
254        if path.exists() {
255            return Ok(());
256        }
257        std::fs::write(path, Self::GITIGNORE_CONTENTS)
258    }
259
260    pub fn to_toml(&self) -> String {
261        let body = toml::to_string(self).unwrap_or_default();
262        format!("# TraceVault configuration\n{body}")
263    }
264
265    /// Every key this struct reads from `config.toml`. Kept in step with the
266    /// fields by `fields_lists_every_serialized_key`.
267    const FIELDS: &'static [&'static str] = &[
268        "agent",
269        "server_url",
270        "api_key",
271        "repo_id",
272        "user_context",
273        "remote_id",
274        "codebase_name",
275        "default_project",
276        "project_id",
277        "project_name",
278    ];
279
280    /// Write this config to `project_root`'s `config.toml`. Unlike a plain
281    /// [`to_toml`](Self::to_toml) rewrite, it keeps what the struct cannot
282    /// carry through a round trip (VIS-1046): the `api_key` it was loaded with
283    /// (otherwise never serialized, see the field) and keys this CLI version
284    /// does not know. Every other key follows the struct, so a `None` field
285    /// removes it, but a field this config holds unchanged keeps the file's
286    /// own spelling (e.g. unknown keys inside `[user_context]`). The file's key
287    /// order is kept. An unreadable or malformed file is replaced.
288    pub fn save(&self, project_root: &Path) -> std::io::Result<()> {
289        let path = Self::config_path(project_root);
290        let mut table: toml::Table = std::fs::read_to_string(&path)
291            .ok()
292            .and_then(|content| content.parse().ok())
293            .unwrap_or_default();
294        let ours = toml::Table::try_from(self).map_err(std::io::Error::other)?;
295        // The file's fields as this struct reads them, to tell which ones the
296        // caller changed.
297        let as_loaded = table
298            .clone()
299            .try_into::<Self>()
300            .ok()
301            .and_then(|cfg| toml::Table::try_from(&cfg).ok())
302            .unwrap_or_default();
303        // `api_key` is settled below, in place.
304        table.retain(|key, _| {
305            key == "api_key" || !Self::FIELDS.contains(&key) || ours.contains_key(key)
306        });
307        for (key, value) in ours {
308            // A serde default (`agent`) matches as loaded without being in
309            // the file: still written.
310            if !table.contains_key(&key) || as_loaded.get(&key) != Some(&value) {
311                table.insert(key, value);
312            }
313        }
314        match &self.api_key {
315            Some(key) => {
316                table.insert("api_key".into(), key.clone().into());
317            }
318            None => {
319                table.remove("api_key");
320            }
321        }
322        let body = toml::to_string(&table).map_err(std::io::Error::other)?;
323        std::fs::write(path, format!("# TraceVault configuration\n{body}"))
324    }
325
326    /// Load `config.toml`, distinguishing a **missing** file (`Ok(None)`) from a
327    /// present-but-**malformed** one (`Err(message)`). Callers that need to react
328    /// differently to those two cases (e.g. to avoid silently writing to a
329    /// default path when a configured one failed to parse) should use this.
330    ///
331    /// Only a genuine "not found" counts as missing; any other IO error (e.g.
332    /// permission denied) is surfaced as `Err` with the path, rather than being
333    /// masked as an absent config.
334    pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
335        let path = Self::config_path(project_root);
336        let content = match std::fs::read_to_string(&path) {
337            Ok(c) => c,
338            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
339            Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
340        };
341        toml::from_str(&content)
342            .map(Some)
343            .map_err(|e| e.to_string())
344    }
345
346    /// Lenient load: a missing **or** malformed `config.toml` yields `None`, with
347    /// a warning printed for the malformed case. Kept for callers that treat "no
348    /// usable config" uniformly; prefer [`try_load`](Self::try_load) when the
349    /// missing/malformed distinction matters.
350    pub fn load(project_root: &Path) -> Option<Self> {
351        match Self::try_load(project_root) {
352            Ok(cfg) => cfg,
353            Err(e) => {
354                eprintln!("tracevault: warning: malformed config.toml: {e}");
355                None
356            }
357        }
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use std::fs;
365
366    #[test]
367    fn to_toml_all_fields() {
368        let cfg = TracevaultConfig {
369            agent: "claude-code".into(),
370            server_url: Some("https://example.com".into()),
371            api_key: None, // api_key not included in to_toml
372            repo_id: Some("repo-1".into()),
373            user_context: None,
374            remote_id: None,
375            codebase_name: None,
376            default_project: None,
377            project_id: None,
378            project_name: None,
379        };
380        let toml = cfg.to_toml();
381        assert!(toml.contains("agent = \"claude-code\""));
382        assert!(toml.contains("server_url = \"https://example.com\""));
383        assert!(toml.contains("repo_id = \"repo-1\""));
384        assert!(
385            !toml.contains("user_context"),
386            "None user_context must be omitted"
387        );
388    }
389
390    #[test]
391    fn to_toml_minimal() {
392        let cfg = TracevaultConfig::default();
393        let toml = cfg.to_toml();
394        assert!(toml.contains("agent = \"claude-code\""));
395        assert!(!toml.contains("server_url"));
396    }
397
398    #[test]
399    fn load_valid_config() {
400        let dir = tempfile::tempdir().unwrap();
401        let tv_dir = dir.path().join(".tracevault");
402        fs::create_dir_all(&tv_dir).unwrap();
403        fs::write(
404            tv_dir.join("config.toml"),
405            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\n",
406        )
407        .unwrap();
408        let cfg = TracevaultConfig::load(dir.path()).unwrap();
409        assert_eq!(cfg.agent, "claude-code");
410        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
411    }
412
413    #[test]
414    fn load_old_config_with_org_slug_still_parses() {
415        // Old on-disk files may still contain `org_slug` from before the
416        // single-tenant org removal. serde must silently ignore the unknown
417        // field rather than fail to parse (no `deny_unknown_fields`).
418        let dir = tempfile::tempdir().unwrap();
419        let tv_dir = dir.path().join(".tracevault");
420        fs::create_dir_all(&tv_dir).unwrap();
421        fs::write(
422            tv_dir.join("config.toml"),
423            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"x\"\n",
424        )
425        .unwrap();
426        let cfg = TracevaultConfig::load(dir.path()).unwrap();
427        assert_eq!(cfg.agent, "claude-code");
428        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
429    }
430
431    #[test]
432    fn load_missing_file_returns_none() {
433        let dir = tempfile::tempdir().unwrap();
434        assert!(TracevaultConfig::load(dir.path()).is_none());
435    }
436
437    #[test]
438    fn try_load_distinguishes_missing_valid_and_malformed() {
439        // Missing file → Ok(None), not an error.
440        let missing = tempfile::tempdir().unwrap();
441        assert!(matches!(
442            TracevaultConfig::try_load(missing.path()),
443            Ok(None)
444        ));
445
446        // Valid file → Ok(Some(cfg)).
447        let valid = tempfile::tempdir().unwrap();
448        let tv_dir = valid.path().join(".tracevault");
449        fs::create_dir_all(&tv_dir).unwrap();
450        fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
451        assert!(matches!(
452            TracevaultConfig::try_load(valid.path()),
453            Ok(Some(_))
454        ));
455
456        // Present but unparseable → Err (NOT silently treated as missing).
457        let bad = tempfile::tempdir().unwrap();
458        let bad_dir = bad.path().join(".tracevault");
459        fs::create_dir_all(&bad_dir).unwrap();
460        fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
461        assert!(TracevaultConfig::try_load(bad.path()).is_err());
462
463        // Present but unreadable (a non-NotFound IO error — here config.toml is a
464        // directory) → Err, NOT masked as missing.
465        let io = tempfile::tempdir().unwrap();
466        fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
467        assert!(TracevaultConfig::try_load(io.path()).is_err());
468    }
469
470    #[test]
471    fn ensure_gitignore_creates_runtime_ignore_file() {
472        let dir = tempfile::tempdir().unwrap();
473        let config_dir = dir.path().join(".tracevault");
474        fs::create_dir_all(&config_dir).unwrap();
475
476        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
477
478        let gitignore = config_dir.join(".gitignore");
479        assert!(gitignore.exists(), ".gitignore must be created");
480        let content = fs::read_to_string(&gitignore).unwrap();
481        assert!(content.contains("sessions/"), "must ignore sessions/");
482        assert!(content.contains("cache/"), "must ignore cache/");
483        assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
484    }
485
486    #[test]
487    fn toml_round_trip_omits_api_key_and_none_fields() {
488        let cfg = TracevaultConfig {
489            agent: "claude-code".into(),
490            server_url: Some("https://example.com".into()),
491            api_key: Some("secret".into()),
492            repo_id: None,
493            user_context: None,
494            remote_id: None,
495            codebase_name: None,
496            default_project: None,
497            project_id: None,
498            project_name: None,
499        };
500        let toml = cfg.to_toml();
501        assert!(toml.contains("agent = \"claude-code\""));
502        assert!(toml.contains("server_url = \"https://example.com\""));
503        assert!(!toml.contains("api_key"), "api_key must never be written");
504        assert!(!toml.contains("repo_id"), "None fields must be omitted");
505
506        // Re-parse (api_key absent from disk) round-trips the rest.
507        let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
508        assert_eq!(parsed.agent, "claude-code");
509        assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
510        assert_eq!(parsed.api_key, None);
511    }
512
513    #[test]
514    fn user_context_forms_resolve_correctly() {
515        // absent ⇒ unset (never configured)
516        let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
517        assert!(none_cfg.user_context.is_none());
518
519        // false ⇒ disabled
520        let f: TracevaultConfig =
521            toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
522        assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
523        assert!(f.user_context.unwrap().resolve().is_none());
524
525        // true ⇒ enabled at default path
526        let t: TracevaultConfig =
527            toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
528        assert_eq!(
529            t.user_context.unwrap().resolve(),
530            Some(default_user_context_path())
531        );
532
533        // "path" ⇒ enabled at that path
534        let p: TracevaultConfig =
535            toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
536        assert_eq!(
537            p.user_context.unwrap().resolve(),
538            Some(PathBuf::from("/tmp/ctx.json"))
539        );
540
541        // { enable = false, path = ... } ⇒ disabled but path() remembers it
542        let obj: TracevaultConfig = toml::from_str(
543            "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
544        )
545        .unwrap();
546        let obj_ctx = obj.user_context.unwrap();
547        assert!(obj_ctx.resolve().is_none());
548        assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
549    }
550
551    #[test]
552    fn explicit_disable_is_persisted_not_skipped() {
553        let cfg = TracevaultConfig {
554            user_context: Some(UserContext::Toggle(false)),
555            ..Default::default()
556        };
557        let toml = cfg.to_toml();
558        assert!(
559            toml.contains("user_context"),
560            "explicit off must serialize, got:\n{toml}"
561        );
562        let back: TracevaultConfig = toml::from_str(&toml).unwrap();
563        assert!(matches!(
564            back.user_context,
565            Some(UserContext::Toggle(false))
566        ));
567    }
568
569    #[test]
570    fn user_config_paths_are_under_config_root() {
571        let root = std::path::Path::new("/x/tracevault");
572        assert_eq!(
573            user_config_path_in(root),
574            std::path::Path::new("/x/tracevault/config.toml")
575        );
576        assert_eq!(
577            default_user_context_path_in(root),
578            std::path::Path::new("/x/tracevault/context.json")
579        );
580    }
581
582    #[test]
583    fn try_load_user_config_missing_is_ok_none() {
584        let dir = tempfile::tempdir().unwrap();
585        assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
586    }
587
588    #[test]
589    fn try_load_user_config_reads_user_context() {
590        let dir = tempfile::tempdir().unwrap();
591        std::fs::write(
592            user_config_path_in(dir.path()),
593            "agent=\"claude-code\"\nuser_context = true\n",
594        )
595        .unwrap();
596        let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
597        // Validate against the INJECTED root (resolve_in), not the real
598        // tv_config_root(): `user_context = true` resolves to the default
599        // `context.json` colocated under `dir`.
600        assert_eq!(
601            cfg.user_context.unwrap().resolve_in(dir.path()),
602            Some(default_user_context_path_in(dir.path()))
603        );
604    }
605
606    #[test]
607    fn try_load_user_config_malformed_is_err() {
608        let dir = tempfile::tempdir().unwrap();
609        std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
610        assert!(try_load_user_config_in(dir.path()).is_err());
611    }
612
613    #[test]
614    fn load_user_config_lenient_defaults_on_missing() {
615        let dir = tempfile::tempdir().unwrap();
616        assert!(load_user_config_in(dir.path()).user_context.is_none());
617    }
618
619    #[test]
620    fn load_user_config_lenient_defaults_on_malformed() {
621        // The hook depends on this fail-safe: a malformed user config.toml must
622        // degrade to a default (no user context), never propagate an error.
623        let dir = tempfile::tempdir().unwrap();
624        std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
625        assert!(load_user_config_in(dir.path()).user_context.is_none());
626    }
627
628    #[test]
629    fn resolve_user_context_prefers_repo_over_global() {
630        let dir = tempfile::tempdir().unwrap();
631        std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
632        // repo explicitly set (even explicit-off) → repo wins, NO global fallback
633        let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
634        assert!(
635            uc.resolve().is_none(),
636            "explicit repo-off must hard-disable"
637        );
638    }
639
640    #[test]
641    fn resolve_user_context_falls_back_to_global_when_repo_unset() {
642        let dir = tempfile::tempdir().unwrap();
643        std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
644        let uc = resolve_user_context_in(None, dir.path());
645        // Resolve against the injected root, not the real tv_config_root().
646        assert_eq!(
647            uc.resolve_in(dir.path()),
648            Some(default_user_context_path_in(dir.path()))
649        );
650    }
651
652    #[test]
653    fn resolve_user_context_off_when_neither_configured() {
654        let dir = tempfile::tempdir().unwrap();
655        assert!(resolve_user_context_in(None, dir.path())
656            .resolve()
657            .is_none());
658    }
659
660    #[test]
661    fn from_init_flags_maps_variants() {
662        assert!(matches!(
663            UserContext::from_init_flags(true, None),
664            Ok(Some(UserContext::Toggle(false)))
665        ));
666        assert!(matches!(
667            UserContext::from_init_flags(false, None),
668            Ok(None)
669        ));
670        assert!(matches!(
671            UserContext::from_init_flags(false, Some("/p".into())),
672            Ok(Some(UserContext::Path(_)))
673        ));
674        assert!(UserContext::from_init_flags(false, Some("  ".into())).is_err());
675    }
676
677    #[test]
678    fn ensure_gitignore_preserves_existing_file() {
679        let dir = tempfile::tempdir().unwrap();
680        let config_dir = dir.path().join(".tracevault");
681        fs::create_dir_all(&config_dir).unwrap();
682        let gitignore = config_dir.join(".gitignore");
683        fs::write(&gitignore, "custom-user-content\n").unwrap();
684
685        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
686
687        // Idempotent: an existing .gitignore is never overwritten.
688        assert_eq!(
689            fs::read_to_string(&gitignore).unwrap(),
690            "custom-user-content\n"
691        );
692    }
693
694    #[test]
695    fn default_project_roundtrips_through_toml() {
696        let cfg = TracevaultConfig {
697            default_project: Some("payments-platform".into()),
698            ..Default::default()
699        };
700        let toml = cfg.to_toml();
701        assert!(toml.contains("default_project = \"payments-platform\""));
702        let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
703        assert_eq!(parsed.default_project.as_deref(), Some("payments-platform"));
704    }
705
706    #[test]
707    fn default_project_absent_is_omitted_from_toml() {
708        let toml = TracevaultConfig::default().to_toml();
709        assert!(!toml.contains("default_project"));
710    }
711
712    #[test]
713    fn fields_lists_every_serialized_key() {
714        let cfg = TracevaultConfig {
715            agent: "claude-code".into(),
716            server_url: Some("https://example.com".into()),
717            api_key: Some("tvk_x".into()),
718            repo_id: Some("r".into()),
719            user_context: Some(UserContext::Toggle(true)),
720            remote_id: Some("rm".into()),
721            codebase_name: Some("cb".into()),
722            default_project: Some("p".into()),
723            project_id: Some("00000000-0000-4000-8000-000000000001".into()),
724            project_name: Some("p".into()),
725        };
726        let mut keys: Vec<String> = toml::Table::try_from(&cfg)
727            .unwrap()
728            .keys()
729            .cloned()
730            .collect();
731        keys.push("api_key".into()); // read but never serialized
732        keys.sort();
733        let mut fields: Vec<&str> = TracevaultConfig::FIELDS.to_vec();
734        fields.sort();
735        assert_eq!(keys, fields);
736    }
737
738    fn write_config(root: &Path, content: &str) {
739        fs::create_dir_all(root.join(".tracevault")).unwrap();
740        fs::write(root.join(".tracevault/config.toml"), content).unwrap();
741    }
742
743    #[test]
744    fn save_keeps_api_key_unknown_keys_and_key_order() {
745        let dir = tempfile::tempdir().unwrap();
746        write_config(
747            dir.path(),
748            "repo_id = \"r1\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n",
749        );
750
751        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
752        cfg.repo_id = Some("r2".into());
753        cfg.save(dir.path()).unwrap();
754
755        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
756        assert_eq!(
757            content,
758            "# TraceVault configuration\nrepo_id = \"r2\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n"
759        );
760    }
761
762    #[test]
763    fn save_removes_a_known_key_set_to_none() {
764        let dir = tempfile::tempdir().unwrap();
765        write_config(dir.path(), "codebase_name = \"old\"\nrepo_id = \"r1\"\n");
766
767        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
768        cfg.codebase_name = None;
769        cfg.save(dir.path()).unwrap();
770
771        let reloaded = TracevaultConfig::load(dir.path()).unwrap();
772        assert_eq!(reloaded.codebase_name, None);
773        assert_eq!(reloaded.repo_id.as_deref(), Some("r1"));
774    }
775
776    #[test]
777    fn save_puts_scalars_before_a_table_valued_user_context() {
778        let dir = tempfile::tempdir().unwrap();
779        write_config(
780            dir.path(),
781            "[user_context]\nenable = false\npath = \"/x.json\"\n",
782        );
783
784        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
785        cfg.api_key = Some("tvk_y".into());
786        cfg.repo_id = Some("r".into());
787        cfg.save(dir.path()).unwrap();
788
789        let reloaded = TracevaultConfig::load(dir.path()).unwrap();
790        assert_eq!(reloaded.api_key.as_deref(), Some("tvk_y"));
791        assert_eq!(reloaded.repo_id.as_deref(), Some("r"));
792        assert!(matches!(
793            reloaded.user_context,
794            Some(UserContext::Full { enable: false, path: Some(ref p) }) if p == "/x.json"
795        ));
796    }
797
798    #[test]
799    fn save_keeps_an_unchanged_user_context_table_verbatim() {
800        let dir = tempfile::tempdir().unwrap();
801        let original = "repo_id = \"r1\"\nagent = \"claude-code\"\n\n[user_context]\npath = \"/x.json\"\nfuture_setting = 1\nenable = true\n";
802        write_config(dir.path(), original);
803
804        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
805        cfg.repo_id = Some("r2".into());
806        cfg.save(dir.path()).unwrap();
807
808        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
809        assert_eq!(
810            content,
811            format!(
812                "# TraceVault configuration\n{}",
813                original.replace("r1", "r2")
814            )
815        );
816    }
817
818    #[test]
819    fn save_replaces_a_changed_user_context() {
820        let dir = tempfile::tempdir().unwrap();
821        write_config(
822            dir.path(),
823            "[user_context]\npath = \"/x.json\"\nfuture_setting = 1\n",
824        );
825
826        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
827        cfg.user_context = Some(UserContext::Toggle(false));
828        cfg.save(dir.path()).unwrap();
829
830        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
831        assert_eq!(
832            content,
833            "# TraceVault configuration\nuser_context = false\nagent = \"claude-code\"\n"
834        );
835    }
836
837    #[test]
838    fn save_writes_the_default_agent_into_a_file_without_one() {
839        let dir = tempfile::tempdir().unwrap();
840        write_config(dir.path(), "repo_id = \"r1\"\n");
841
842        TracevaultConfig::load(dir.path())
843            .unwrap()
844            .save(dir.path())
845            .unwrap();
846
847        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
848        assert!(content.contains("agent = \"claude-code\""), "{content}");
849    }
850
851    #[test]
852    fn save_creates_a_missing_config() {
853        let dir = tempfile::tempdir().unwrap();
854        fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
855        TracevaultConfig::default().save(dir.path()).unwrap();
856        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
857        assert_eq!(content, TracevaultConfig::default().to_toml());
858    }
859}