tracevault-cli 0.29.3

CLI tool for Visdom Trace - AI code tracing and attribution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

#[derive(Debug, Serialize, Deserialize)]
pub struct TracevaultConfig {
    #[serde(default = "default_agent")]
    pub agent: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_url: Option<String>,
    /// Never persisted by this CLI (`skip_serializing`), but read back when a
    /// hand-authored file supplies one: `resolve_credentials` uses it as the
    /// lowest-precedence credential source. Not guarded by the server-URL
    /// scoping there, since committing a key next to this config's own
    /// `server_url` is a deliberate act.
    #[serde(default, skip_serializing)]
    pub api_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repo_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_context: Option<UserContext>,
    /// The remote (codebase)'s server-side id, resolved by `init` (best-effort)
    /// via `resolve_remote`. Display-only today — `repo_id` stays authoritative
    /// for ingest — but recorded so a future caller doesn't have to re-resolve.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote_id: Option<String>,
    /// The codebase's registered name, resolved by `init` alongside `remote_id`.
    /// Display-only — lets bound-mode `status` print the codebase without an
    /// extra network round-trip.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub codebase_name: Option<String>,
    /// Client-side default project **name** for this repo (no server counterpart).
    /// Resolution precedence rung 3; resolved to an id at use time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_project: Option<String>,
}

fn default_agent() -> String {
    "claude-code".to_string()
}

impl Default for TracevaultConfig {
    fn default() -> Self {
        Self {
            agent: "claude-code".to_string(),
            server_url: None,
            api_key: None,
            repo_id: None,
            user_context: None,
            remote_id: None,
            codebase_name: None,
            default_project: None,
        }
    }
}

/// Cross-repo user context source. Cargo-`dependency`-style shorthand:
/// bool toggles enable at the default path; a string is enable + that path.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UserContext {
    Toggle(bool),
    Path(String),
    Full {
        #[serde(default = "crate::config::enable_default")]
        enable: bool,
        #[serde(default)]
        path: Option<String>,
    },
}

impl Default for UserContext {
    fn default() -> Self {
        UserContext::Toggle(false)
    }
}

pub(crate) fn enable_default() -> bool {
    true
}

/// Root of the user-level TraceVault config dir: `~/.config/tracevault/`
/// (beside `credentials.json` / `context.json`). Falls back to `./tracevault`.
pub fn tv_config_root() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("tracevault")
}

pub fn user_config_path_in(config_root: &Path) -> PathBuf {
    config_root.join("config.toml")
}
pub fn user_config_path() -> PathBuf {
    user_config_path_in(&tv_config_root())
}
pub fn default_user_context_path_in(config_root: &Path) -> PathBuf {
    config_root.join("context.json")
}

/// `~/.config/tracevault/context.json`, alongside credentials.json.
/// Public path accessor (used by tests / lib consumers as the canonical default);
/// production resolves via `UserContext::path`/`path_in`, so the bin has no direct
/// caller.
#[allow(dead_code)]
pub fn default_user_context_path() -> PathBuf {
    default_user_context_path_in(&tv_config_root())
}

/// Load the user-level `config.toml`, distinguishing a **missing** file
/// (`Ok(None)`) from a malformed/unreadable one (`Err`). Mirrors
/// `TracevaultConfig::try_load` but for a direct file path (the user-level
/// config is NOT inside a `.tracevault/` dir).
pub fn try_load_user_config_in(config_root: &Path) -> Result<Option<TracevaultConfig>, String> {
    let path = user_config_path_in(config_root);
    let content = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
    };
    toml::from_str(&content)
        .map(Some)
        .map_err(|e| e.to_string())
}

/// Lenient: missing OR malformed → `TracevaultConfig::default()` (warn on malformed).
pub fn load_user_config_in(config_root: &Path) -> TracevaultConfig {
    match try_load_user_config_in(config_root) {
        Ok(Some(cfg)) => cfg,
        Ok(None) => TracevaultConfig::default(),
        Err(e) => {
            eprintln!("tracevault: warning: malformed user config.toml: {e}");
            TracevaultConfig::default()
        }
    }
}

/// Resolve the effective user-context source. A repo that *configured* it
/// (`Some`) wins — including an explicit `Some(Toggle(false))` (hard-off, no
/// fallback). Only when the repo did NOT configure it (`None`) does the
/// user-level `config.toml` under `config_root` supply it.
pub fn resolve_user_context_in(
    repo_configured: Option<UserContext>,
    config_root: &Path,
) -> UserContext {
    repo_configured.unwrap_or_else(|| {
        load_user_config_in(config_root)
            .user_context
            .unwrap_or_default()
    })
}

/// [`resolve_user_context_in`] rooted at [`tv_config_root`].
pub fn resolve_user_context(repo_configured: Option<UserContext>) -> UserContext {
    resolve_user_context_in(repo_configured, &tv_config_root())
}

impl UserContext {
    /// The file this source points at (configured path or default), regardless
    /// of whether it is enabled. Used by `--user` editing.
    pub fn path(&self) -> PathBuf {
        self.path_in(&tv_config_root())
    }

    /// Like [`path`](Self::path), but resolves the "no explicit path" default
    /// relative to `config_root` instead of the process-global
    /// [`tv_config_root`]. This matters for the user-level `config.toml` (and
    /// for tests with an injected root): its unconfigured default is the
    /// `context.json` colocated with it under `config_root`, which need not be
    /// the real `tv_config_root()`.
    pub fn path_in(&self, config_root: &Path) -> PathBuf {
        match self {
            UserContext::Path(p) => PathBuf::from(p),
            UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
            _ => default_user_context_path_in(config_root),
        }
    }

    /// `Some(path)` when enabled (consulted by the hook); `None` when disabled.
    pub fn resolve(&self) -> Option<PathBuf> {
        self.resolve_in(&tv_config_root())
    }

    /// Like [`resolve`](Self::resolve), but resolves the "no explicit path"
    /// default relative to `config_root` (via [`path_in`](Self::path_in))
    /// instead of the process-global [`tv_config_root`]. Callers that took an
    /// injected `config_root` MUST use this — `resolve()` would leak back to
    /// the real `~/.config` for the default-path case.
    pub fn resolve_in(&self, config_root: &Path) -> Option<PathBuf> {
        let enabled = match self {
            UserContext::Toggle(b) => *b,
            UserContext::Path(_) => true,
            UserContext::Full { enable, .. } => *enable,
        };
        enabled.then(|| self.path_in(config_root))
    }

    /// Map `init`'s `--no-user-context` / `--user-context <path>` flags to a
    /// *requested* user-context override. `Ok(None)` means neither flag was given
    /// (the caller decides the default/preserve behavior). Rejects an empty/blank
    /// `--user-context` value.
    pub fn from_init_flags(
        no_user_context: bool,
        user_context: Option<String>,
    ) -> Result<Option<UserContext>, String> {
        match (no_user_context, user_context) {
            (true, _) => Ok(Some(UserContext::Toggle(false))),
            (false, Some(p)) if p.trim().is_empty() => {
                Err("--user-context path must not be empty".to_string())
            }
            (false, Some(p)) => Ok(Some(UserContext::Path(p))),
            (false, None) => Ok(None),
        }
    }
}

impl TracevaultConfig {
    pub fn config_dir(project_root: &Path) -> PathBuf {
        project_root.join(".tracevault")
    }

    pub fn config_path(project_root: &Path) -> PathBuf {
        Self::config_dir(project_root).join("config.toml")
    }

    /// Runtime artifacts inside a `.tracevault/` directory that must never be
    /// committed (`config.toml` and the `.gitignore` itself stay tracked).
    const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";

    /// Ensure a `.gitignore` exists inside `config_dir` (a `.tracevault/` dir)
    /// so runtime artifacts are ignored no matter where the directory was
    /// created — including the per-subproject `.tracevault/` dirs the stream
    /// hook may create from a nested working directory. Idempotent: an existing
    /// `.gitignore` is never overwritten. Best-effort; callers may ignore the
    /// result (a failure must never break the hook).
    pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
        let path = config_dir.join(".gitignore");
        if path.exists() {
            return Ok(());
        }
        std::fs::write(path, Self::GITIGNORE_CONTENTS)
    }

    pub fn to_toml(&self) -> String {
        let body = toml::to_string(self).unwrap_or_default();
        format!("# TraceVault configuration\n{body}")
    }

    /// Every key this struct reads from `config.toml`. Kept in step with the
    /// fields by `fields_lists_every_serialized_key`.
    const FIELDS: &'static [&'static str] = &[
        "agent",
        "server_url",
        "api_key",
        "repo_id",
        "user_context",
        "remote_id",
        "codebase_name",
        "default_project",
    ];

    /// Write this config to `project_root`'s `config.toml`. Unlike a plain
    /// [`to_toml`](Self::to_toml) rewrite, it keeps what the struct cannot
    /// carry through a round trip (VIS-1046): the `api_key` it was loaded with
    /// (otherwise never serialized, see the field) and keys this CLI version
    /// does not know. Every other key follows the struct, so a `None` field
    /// removes it, but a field this config holds unchanged keeps the file's
    /// own spelling (e.g. unknown keys inside `[user_context]`). The file's key
    /// order is kept. An unreadable or malformed file is replaced.
    pub fn save(&self, project_root: &Path) -> std::io::Result<()> {
        let path = Self::config_path(project_root);
        let mut table: toml::Table = std::fs::read_to_string(&path)
            .ok()
            .and_then(|content| content.parse().ok())
            .unwrap_or_default();
        let ours = toml::Table::try_from(self).map_err(std::io::Error::other)?;
        // The file's fields as this struct reads them, to tell which ones the
        // caller changed.
        let as_loaded = table
            .clone()
            .try_into::<Self>()
            .ok()
            .and_then(|cfg| toml::Table::try_from(&cfg).ok())
            .unwrap_or_default();
        // `api_key` is settled below, in place.
        table.retain(|key, _| {
            key == "api_key" || !Self::FIELDS.contains(&key) || ours.contains_key(key)
        });
        for (key, value) in ours {
            // A serde default (`agent`) matches as loaded without being in
            // the file: still written.
            if !table.contains_key(&key) || as_loaded.get(&key) != Some(&value) {
                table.insert(key, value);
            }
        }
        match &self.api_key {
            Some(key) => {
                table.insert("api_key".into(), key.clone().into());
            }
            None => {
                table.remove("api_key");
            }
        }
        let body = toml::to_string(&table).map_err(std::io::Error::other)?;
        std::fs::write(path, format!("# TraceVault configuration\n{body}"))
    }

    /// Load `config.toml`, distinguishing a **missing** file (`Ok(None)`) from a
    /// present-but-**malformed** one (`Err(message)`). Callers that need to react
    /// differently to those two cases (e.g. to avoid silently writing to a
    /// default path when a configured one failed to parse) should use this.
    ///
    /// Only a genuine "not found" counts as missing; any other IO error (e.g.
    /// permission denied) is surfaced as `Err` with the path, rather than being
    /// masked as an absent config.
    pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
        let path = Self::config_path(project_root);
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
        };
        toml::from_str(&content)
            .map(Some)
            .map_err(|e| e.to_string())
    }

    /// Lenient load: a missing **or** malformed `config.toml` yields `None`, with
    /// a warning printed for the malformed case. Kept for callers that treat "no
    /// usable config" uniformly; prefer [`try_load`](Self::try_load) when the
    /// missing/malformed distinction matters.
    pub fn load(project_root: &Path) -> Option<Self> {
        match Self::try_load(project_root) {
            Ok(cfg) => cfg,
            Err(e) => {
                eprintln!("tracevault: warning: malformed config.toml: {e}");
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn to_toml_all_fields() {
        let cfg = TracevaultConfig {
            agent: "claude-code".into(),
            server_url: Some("https://example.com".into()),
            api_key: None, // api_key not included in to_toml
            repo_id: Some("repo-1".into()),
            user_context: None,
            remote_id: None,
            codebase_name: None,
            default_project: None,
        };
        let toml = cfg.to_toml();
        assert!(toml.contains("agent = \"claude-code\""));
        assert!(toml.contains("server_url = \"https://example.com\""));
        assert!(toml.contains("repo_id = \"repo-1\""));
        assert!(
            !toml.contains("user_context"),
            "None user_context must be omitted"
        );
    }

    #[test]
    fn to_toml_minimal() {
        let cfg = TracevaultConfig::default();
        let toml = cfg.to_toml();
        assert!(toml.contains("agent = \"claude-code\""));
        assert!(!toml.contains("server_url"));
    }

    #[test]
    fn load_valid_config() {
        let dir = tempfile::tempdir().unwrap();
        let tv_dir = dir.path().join(".tracevault");
        fs::create_dir_all(&tv_dir).unwrap();
        fs::write(
            tv_dir.join("config.toml"),
            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\n",
        )
        .unwrap();
        let cfg = TracevaultConfig::load(dir.path()).unwrap();
        assert_eq!(cfg.agent, "claude-code");
        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
    }

    #[test]
    fn load_old_config_with_org_slug_still_parses() {
        // Old on-disk files may still contain `org_slug` from before the
        // single-tenant org removal. serde must silently ignore the unknown
        // field rather than fail to parse (no `deny_unknown_fields`).
        let dir = tempfile::tempdir().unwrap();
        let tv_dir = dir.path().join(".tracevault");
        fs::create_dir_all(&tv_dir).unwrap();
        fs::write(
            tv_dir.join("config.toml"),
            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"x\"\n",
        )
        .unwrap();
        let cfg = TracevaultConfig::load(dir.path()).unwrap();
        assert_eq!(cfg.agent, "claude-code");
        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
    }

    #[test]
    fn load_missing_file_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        assert!(TracevaultConfig::load(dir.path()).is_none());
    }

    #[test]
    fn try_load_distinguishes_missing_valid_and_malformed() {
        // Missing file → Ok(None), not an error.
        let missing = tempfile::tempdir().unwrap();
        assert!(matches!(
            TracevaultConfig::try_load(missing.path()),
            Ok(None)
        ));

        // Valid file → Ok(Some(cfg)).
        let valid = tempfile::tempdir().unwrap();
        let tv_dir = valid.path().join(".tracevault");
        fs::create_dir_all(&tv_dir).unwrap();
        fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
        assert!(matches!(
            TracevaultConfig::try_load(valid.path()),
            Ok(Some(_))
        ));

        // Present but unparseable → Err (NOT silently treated as missing).
        let bad = tempfile::tempdir().unwrap();
        let bad_dir = bad.path().join(".tracevault");
        fs::create_dir_all(&bad_dir).unwrap();
        fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
        assert!(TracevaultConfig::try_load(bad.path()).is_err());

        // Present but unreadable (a non-NotFound IO error — here config.toml is a
        // directory) → Err, NOT masked as missing.
        let io = tempfile::tempdir().unwrap();
        fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
        assert!(TracevaultConfig::try_load(io.path()).is_err());
    }

    #[test]
    fn ensure_gitignore_creates_runtime_ignore_file() {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join(".tracevault");
        fs::create_dir_all(&config_dir).unwrap();

        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();

        let gitignore = config_dir.join(".gitignore");
        assert!(gitignore.exists(), ".gitignore must be created");
        let content = fs::read_to_string(&gitignore).unwrap();
        assert!(content.contains("sessions/"), "must ignore sessions/");
        assert!(content.contains("cache/"), "must ignore cache/");
        assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
    }

    #[test]
    fn toml_round_trip_omits_api_key_and_none_fields() {
        let cfg = TracevaultConfig {
            agent: "claude-code".into(),
            server_url: Some("https://example.com".into()),
            api_key: Some("secret".into()),
            repo_id: None,
            user_context: None,
            remote_id: None,
            codebase_name: None,
            default_project: None,
        };
        let toml = cfg.to_toml();
        assert!(toml.contains("agent = \"claude-code\""));
        assert!(toml.contains("server_url = \"https://example.com\""));
        assert!(!toml.contains("api_key"), "api_key must never be written");
        assert!(!toml.contains("repo_id"), "None fields must be omitted");

        // Re-parse (api_key absent from disk) round-trips the rest.
        let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
        assert_eq!(parsed.agent, "claude-code");
        assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
        assert_eq!(parsed.api_key, None);
    }

    #[test]
    fn user_context_forms_resolve_correctly() {
        // absent ⇒ unset (never configured)
        let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
        assert!(none_cfg.user_context.is_none());

        // false ⇒ disabled
        let f: TracevaultConfig =
            toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
        assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
        assert!(f.user_context.unwrap().resolve().is_none());

        // true ⇒ enabled at default path
        let t: TracevaultConfig =
            toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
        assert_eq!(
            t.user_context.unwrap().resolve(),
            Some(default_user_context_path())
        );

        // "path" ⇒ enabled at that path
        let p: TracevaultConfig =
            toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
        assert_eq!(
            p.user_context.unwrap().resolve(),
            Some(PathBuf::from("/tmp/ctx.json"))
        );

        // { enable = false, path = ... } ⇒ disabled but path() remembers it
        let obj: TracevaultConfig = toml::from_str(
            "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
        )
        .unwrap();
        let obj_ctx = obj.user_context.unwrap();
        assert!(obj_ctx.resolve().is_none());
        assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
    }

    #[test]
    fn explicit_disable_is_persisted_not_skipped() {
        let cfg = TracevaultConfig {
            user_context: Some(UserContext::Toggle(false)),
            ..Default::default()
        };
        let toml = cfg.to_toml();
        assert!(
            toml.contains("user_context"),
            "explicit off must serialize, got:\n{toml}"
        );
        let back: TracevaultConfig = toml::from_str(&toml).unwrap();
        assert!(matches!(
            back.user_context,
            Some(UserContext::Toggle(false))
        ));
    }

    #[test]
    fn user_config_paths_are_under_config_root() {
        let root = std::path::Path::new("/x/tracevault");
        assert_eq!(
            user_config_path_in(root),
            std::path::Path::new("/x/tracevault/config.toml")
        );
        assert_eq!(
            default_user_context_path_in(root),
            std::path::Path::new("/x/tracevault/context.json")
        );
    }

    #[test]
    fn try_load_user_config_missing_is_ok_none() {
        let dir = tempfile::tempdir().unwrap();
        assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
    }

    #[test]
    fn try_load_user_config_reads_user_context() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            user_config_path_in(dir.path()),
            "agent=\"claude-code\"\nuser_context = true\n",
        )
        .unwrap();
        let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
        // Validate against the INJECTED root (resolve_in), not the real
        // tv_config_root(): `user_context = true` resolves to the default
        // `context.json` colocated under `dir`.
        assert_eq!(
            cfg.user_context.unwrap().resolve_in(dir.path()),
            Some(default_user_context_path_in(dir.path()))
        );
    }

    #[test]
    fn try_load_user_config_malformed_is_err() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
        assert!(try_load_user_config_in(dir.path()).is_err());
    }

    #[test]
    fn load_user_config_lenient_defaults_on_missing() {
        let dir = tempfile::tempdir().unwrap();
        assert!(load_user_config_in(dir.path()).user_context.is_none());
    }

    #[test]
    fn load_user_config_lenient_defaults_on_malformed() {
        // The hook depends on this fail-safe: a malformed user config.toml must
        // degrade to a default (no user context), never propagate an error.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
        assert!(load_user_config_in(dir.path()).user_context.is_none());
    }

    #[test]
    fn resolve_user_context_prefers_repo_over_global() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
        // repo explicitly set (even explicit-off) → repo wins, NO global fallback
        let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
        assert!(
            uc.resolve().is_none(),
            "explicit repo-off must hard-disable"
        );
    }

    #[test]
    fn resolve_user_context_falls_back_to_global_when_repo_unset() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
        let uc = resolve_user_context_in(None, dir.path());
        // Resolve against the injected root, not the real tv_config_root().
        assert_eq!(
            uc.resolve_in(dir.path()),
            Some(default_user_context_path_in(dir.path()))
        );
    }

    #[test]
    fn resolve_user_context_off_when_neither_configured() {
        let dir = tempfile::tempdir().unwrap();
        assert!(resolve_user_context_in(None, dir.path())
            .resolve()
            .is_none());
    }

    #[test]
    fn from_init_flags_maps_variants() {
        assert!(matches!(
            UserContext::from_init_flags(true, None),
            Ok(Some(UserContext::Toggle(false)))
        ));
        assert!(matches!(
            UserContext::from_init_flags(false, None),
            Ok(None)
        ));
        assert!(matches!(
            UserContext::from_init_flags(false, Some("/p".into())),
            Ok(Some(UserContext::Path(_)))
        ));
        assert!(UserContext::from_init_flags(false, Some("  ".into())).is_err());
    }

    #[test]
    fn ensure_gitignore_preserves_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join(".tracevault");
        fs::create_dir_all(&config_dir).unwrap();
        let gitignore = config_dir.join(".gitignore");
        fs::write(&gitignore, "custom-user-content\n").unwrap();

        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();

        // Idempotent: an existing .gitignore is never overwritten.
        assert_eq!(
            fs::read_to_string(&gitignore).unwrap(),
            "custom-user-content\n"
        );
    }

    #[test]
    fn default_project_roundtrips_through_toml() {
        let cfg = TracevaultConfig {
            default_project: Some("payments-platform".into()),
            ..Default::default()
        };
        let toml = cfg.to_toml();
        assert!(toml.contains("default_project = \"payments-platform\""));
        let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
        assert_eq!(parsed.default_project.as_deref(), Some("payments-platform"));
    }

    #[test]
    fn default_project_absent_is_omitted_from_toml() {
        let toml = TracevaultConfig::default().to_toml();
        assert!(!toml.contains("default_project"));
    }

    #[test]
    fn fields_lists_every_serialized_key() {
        let cfg = TracevaultConfig {
            agent: "claude-code".into(),
            server_url: Some("https://example.com".into()),
            api_key: Some("tvk_x".into()),
            repo_id: Some("r".into()),
            user_context: Some(UserContext::Toggle(true)),
            remote_id: Some("rm".into()),
            codebase_name: Some("cb".into()),
            default_project: Some("p".into()),
        };
        let mut keys: Vec<String> = toml::Table::try_from(&cfg)
            .unwrap()
            .keys()
            .cloned()
            .collect();
        keys.push("api_key".into()); // read but never serialized
        keys.sort();
        let mut fields: Vec<&str> = TracevaultConfig::FIELDS.to_vec();
        fields.sort();
        assert_eq!(keys, fields);
    }

    fn write_config(root: &Path, content: &str) {
        fs::create_dir_all(root.join(".tracevault")).unwrap();
        fs::write(root.join(".tracevault/config.toml"), content).unwrap();
    }

    #[test]
    fn save_keeps_api_key_unknown_keys_and_key_order() {
        let dir = tempfile::tempdir().unwrap();
        write_config(
            dir.path(),
            "repo_id = \"r1\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n",
        );

        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
        cfg.repo_id = Some("r2".into());
        cfg.save(dir.path()).unwrap();

        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
        assert_eq!(
            content,
            "# TraceVault configuration\nrepo_id = \"r2\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n"
        );
    }

    #[test]
    fn save_removes_a_known_key_set_to_none() {
        let dir = tempfile::tempdir().unwrap();
        write_config(dir.path(), "codebase_name = \"old\"\nrepo_id = \"r1\"\n");

        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
        cfg.codebase_name = None;
        cfg.save(dir.path()).unwrap();

        let reloaded = TracevaultConfig::load(dir.path()).unwrap();
        assert_eq!(reloaded.codebase_name, None);
        assert_eq!(reloaded.repo_id.as_deref(), Some("r1"));
    }

    #[test]
    fn save_puts_scalars_before_a_table_valued_user_context() {
        let dir = tempfile::tempdir().unwrap();
        write_config(
            dir.path(),
            "[user_context]\nenable = false\npath = \"/x.json\"\n",
        );

        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
        cfg.api_key = Some("tvk_y".into());
        cfg.repo_id = Some("r".into());
        cfg.save(dir.path()).unwrap();

        let reloaded = TracevaultConfig::load(dir.path()).unwrap();
        assert_eq!(reloaded.api_key.as_deref(), Some("tvk_y"));
        assert_eq!(reloaded.repo_id.as_deref(), Some("r"));
        assert!(matches!(
            reloaded.user_context,
            Some(UserContext::Full { enable: false, path: Some(ref p) }) if p == "/x.json"
        ));
    }

    #[test]
    fn save_keeps_an_unchanged_user_context_table_verbatim() {
        let dir = tempfile::tempdir().unwrap();
        let original = "repo_id = \"r1\"\nagent = \"claude-code\"\n\n[user_context]\npath = \"/x.json\"\nfuture_setting = 1\nenable = true\n";
        write_config(dir.path(), original);

        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
        cfg.repo_id = Some("r2".into());
        cfg.save(dir.path()).unwrap();

        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
        assert_eq!(
            content,
            format!(
                "# TraceVault configuration\n{}",
                original.replace("r1", "r2")
            )
        );
    }

    #[test]
    fn save_replaces_a_changed_user_context() {
        let dir = tempfile::tempdir().unwrap();
        write_config(
            dir.path(),
            "[user_context]\npath = \"/x.json\"\nfuture_setting = 1\n",
        );

        let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
        cfg.user_context = Some(UserContext::Toggle(false));
        cfg.save(dir.path()).unwrap();

        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
        assert_eq!(
            content,
            "# TraceVault configuration\nuser_context = false\nagent = \"claude-code\"\n"
        );
    }

    #[test]
    fn save_writes_the_default_agent_into_a_file_without_one() {
        let dir = tempfile::tempdir().unwrap();
        write_config(dir.path(), "repo_id = \"r1\"\n");

        TracevaultConfig::load(dir.path())
            .unwrap()
            .save(dir.path())
            .unwrap();

        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
        assert!(content.contains("agent = \"claude-code\""), "{content}");
    }

    #[test]
    fn save_creates_a_missing_config() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
        TracevaultConfig::default().save(dir.path()).unwrap();
        let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
        assert_eq!(content, TracevaultConfig::default().to_toml());
    }
}