Skip to main content

tracevault_cli/
config.rs

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