Skip to main content

tracevault_cli/commands/
context.rs

1use crate::config::{TracevaultConfig, UserContext};
2use crate::context::{resolve_context_paths, Context, WorktreeScope};
3use crate::program::TOP;
4use std::io;
5use std::path::{Path, PathBuf};
6
7/// Walk up from `start` to find the nearest ancestor that contains a
8/// `.visdom/` directory. Returns that ancestor. Errors if none found.
9///
10/// Kept as a public utility for integration tests and callers that need the
11/// classic "must have .visdom/" guarantee (e.g. legacy hooks, tests).
12/// Worktree-aware commands use `resolve_context_paths` directly instead.
13pub fn find_project_root(start: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
14    for ancestor in start.ancestors() {
15        if crate::layout::has_repo_dir(ancestor) {
16            return Ok(ancestor.to_path_buf());
17        }
18    }
19    Err(format!(
20        "No .visdom/ directory found in '{}' or any parent directory. \
21         Run `{TOP} init` first.",
22        start.display()
23    )
24    .into())
25}
26
27/// Parse a `--param` value of the form `key=value`.
28/// Rejects values with no `=`.
29fn parse_param(raw: &str) -> Result<(String, String), Box<dyn std::error::Error>> {
30    let pos = raw
31        .find('=')
32        .ok_or_else(|| format!("invalid --param '{raw}': expected key=value"))?;
33    let key = raw[..pos].to_string();
34    let value = raw[pos + 1..].to_string();
35    Ok((key, value))
36}
37
38/// Split a label argument on commas, trimming whitespace.
39fn split_labels(labels: &[String]) -> Vec<String> {
40    labels
41        .iter()
42        .flat_map(|l| l.split(','))
43        .map(|s| s.trim().to_string())
44        .filter(|s| !s.is_empty())
45        .collect()
46}
47
48/// Resolve the file backing the project's user-level context source
49/// (`user_context` in `config.toml`), regardless of whether it is enabled.
50///
51/// Used by `--user` on `context set/update/clear` to edit that file directly.
52fn user_context_path(cwd: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
53    user_context_path_in(cwd, &crate::config::tv_config_root())
54}
55
56/// Resolve the file backing the user-level context for `--user` edits.
57/// Precedence: a repo `config.toml` that *configured* `user_context` wins;
58/// otherwise the user-level `config.toml`; otherwise the default path. A
59/// malformed repo OR user-level config is an error (never silently misroute a
60/// `--user` write). Works with NO checkout.
61fn user_context_path_in(
62    cwd: &Path,
63    config_root: &Path,
64) -> Result<PathBuf, Box<dyn std::error::Error>> {
65    let repo_uc = match find_project_root(cwd) {
66        Ok(root) => TracevaultConfig::try_load(&root)
67            .map_err(|e| {
68                format!("cannot resolve --user path: malformed .visdom/tracing.toml: {e}")
69            })?
70            .and_then(|c| c.user_context),
71        Err(_) => None, // no checkout → fall through to the user-level config
72    };
73    if let Some(uc) = repo_uc {
74        // A bare disable expresses no opinion about WHERE the user-context file
75        // lives — fall through to the user-level config so `--user` edits target
76        // the file the hook actually reads elsewhere. A repo that set an explicit
77        // path (even while disabled) still points the edit at that path.
78        let bare_disable = matches!(uc, UserContext::Toggle(false))
79            || matches!(
80                uc,
81                UserContext::Full {
82                    enable: false,
83                    path: None
84                }
85            );
86        if !bare_disable {
87            return Ok(uc.path());
88        }
89    }
90    let user_cfg = crate::config::try_load_user_config_in(config_root)
91        .map_err(|e| format!("cannot resolve --user path: malformed user config.toml: {e}"))?;
92    Ok(user_cfg
93        .and_then(|c| c.user_context)
94        .map(|uc| uc.path_in(config_root))
95        .unwrap_or_else(|| crate::config::default_user_context_path_in(config_root)))
96}
97
98/// `tracevault context set` — build a fresh Context from flags, save it.
99/// Omitted dimensions are empty. Clears anything not explicitly provided.
100///
101/// Default scope:
102/// - Linked worktree → writes `worktrees/<key>/context.json`.
103/// - Primary checkout → writes the global `context.json`.
104///
105/// `global = true` forces the global file from any worktree.
106/// `user = true` writes the resolved user-context file instead (wins over `global`).
107pub fn run_set(
108    cwd: &Path,
109    flow: Option<String>,
110    labels: Vec<String>,
111    params: Vec<String>,
112    global: bool,
113    user: bool,
114) -> Result<(), Box<dyn std::error::Error>> {
115    let mut parsed_params = std::collections::BTreeMap::new();
116    for raw in &params {
117        let (k, v) = parse_param(raw)?;
118        parsed_params.insert(k, Some(v));
119    }
120
121    let ctx = Context {
122        flow_id: flow,
123        labels: split_labels(&labels),
124        params: parsed_params,
125    };
126
127    if user {
128        let path = user_context_path(cwd)?;
129        ctx.save_to(&path)
130            .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
131        println!("Context set.");
132        return Ok(());
133    }
134
135    let paths = resolve_context_paths(cwd);
136
137    // Require an initialised .visdom/ before mutating.
138    if !paths.is_set_up() {
139        return Err(crate::program::say("no .visdom/ found — run 'tracevault init' first").into());
140    }
141
142    if global || matches!(paths.scope, WorktreeScope::Primary) {
143        ctx.save_global(&paths)
144    } else {
145        ctx.save_worktree(&paths)
146    }
147    .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
148
149    println!("Context set.");
150    Ok(())
151}
152
153/// `tracevault context update` — load existing, apply mutations, save.
154///
155/// Default scope:
156/// - Linked worktree → reads/writes `worktrees/<key>/context.json`.
157/// - Primary checkout → reads/writes the global `context.json`.
158///
159/// `global = true` forces the global file from any worktree.
160/// `user = true` reads/writes the resolved user-context file instead (wins over `global`).
161#[allow(clippy::too_many_arguments)]
162pub fn run_update(
163    cwd: &Path,
164    flow: Option<String>,
165    labels: Vec<String>,
166    params: Vec<String>,
167    remove_labels: Vec<String>,
168    remove_params: Vec<String>,
169    global: bool,
170    user: bool,
171) -> Result<(), Box<dyn std::error::Error>> {
172    if user {
173        let path = user_context_path(cwd)?;
174        let mut ctx = Context::load_from(&path);
175        apply_update_mutations(
176            &mut ctx,
177            flow,
178            &labels,
179            &params,
180            &remove_labels,
181            &remove_params,
182        )?;
183        ctx.save_to(&path)
184            .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
185        println!("Context updated.");
186        return Ok(());
187    }
188
189    let paths = resolve_context_paths(cwd);
190
191    // Require an initialised .visdom/ before mutating.
192    if !paths.is_set_up() {
193        return Err(crate::program::say("no .visdom/ found — run 'tracevault init' first").into());
194    }
195
196    let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
197
198    let mut ctx = if use_global {
199        Context::load_global(&paths)
200    } else {
201        Context::load_worktree(&paths).unwrap_or_default()
202    };
203
204    apply_update_mutations(
205        &mut ctx,
206        flow,
207        &labels,
208        &params,
209        &remove_labels,
210        &remove_params,
211    )?;
212
213    if use_global {
214        ctx.save_global(&paths)
215    } else {
216        ctx.save_worktree(&paths)
217    }
218    .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
219
220    println!("Context updated.");
221    Ok(())
222}
223
224/// Apply the `update` flow's mutations (set flow, union labels, upsert params,
225/// remove labels/params) to an already-loaded `ctx`. Shared by the
226/// repo/worktree/global path and the `--user` path so both branches stay in sync.
227fn apply_update_mutations(
228    ctx: &mut Context,
229    flow: Option<String>,
230    labels: &[String],
231    params: &[String],
232    remove_labels: &[String],
233    remove_params: &[String],
234) -> Result<(), Box<dyn std::error::Error>> {
235    // Set flow if provided
236    if let Some(f) = flow {
237        ctx.flow_id = Some(f);
238    }
239
240    // Union-add labels (dedup guarded inline by the contains check below; save also normalises)
241    let new_labels = split_labels(labels);
242    for l in new_labels {
243        if !ctx.labels.contains(&l) {
244            ctx.labels.push(l);
245        }
246    }
247
248    // Insert/overwrite params
249    for raw in params {
250        let (k, v) = parse_param(raw)?;
251        ctx.params.insert(k, Some(v));
252    }
253
254    // Remove labels
255    let remove_set: std::collections::HashSet<String> =
256        split_labels(remove_labels).into_iter().collect();
257    ctx.labels.retain(|l| !remove_set.contains(l));
258
259    // Remove params: insert a `None` tombstone so the removal propagates through
260    // the merge and drops the key even when a lower-precedence layer sets it.
261    for k in remove_params {
262        ctx.params.insert(k.clone(), None);
263    }
264
265    Ok(())
266}
267
268/// `tracevault context show` — print four labelled sections:
269///   1. User — the cross-repo user-level context (its contents are shown only
270///      when `user_context` is enabled in `config.toml`; the header shows the
271///      resolved file path when enabled and `disabled` otherwise).
272///   2. Global — the repo-wide `context.json`.
273///   3. This worktree — the per-worktree context (Linked only; "(none)" when missing).
274///   4. Effective — the merged result that the hook stamps on every event, with
275///      each label/param annotated with the layer it came from.
276///
277/// Prints a hint if no `.visdom/` directory is found (i.e. `tracevault init` has
278/// not been run), using `find_project_root` for the diagnostic.
279pub fn run_show(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
280    run_show_in(cwd, &crate::config::tv_config_root())
281}
282
283/// [`run_show`], but resolving the user-level fallback against an injectable
284/// `config_root` instead of the process-global [`crate::config::tv_config_root`].
285/// Lets tests exercise the detached (no-checkout) path without touching the
286/// real `~/.config`.
287pub fn run_show_in(cwd: &Path, config_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
288    // Resolve the user-level context source: a repo config that configured it
289    // wins; otherwise fall back to the user-level config.toml (Task 2/3).
290    // Tolerate no project root/config existing at all, same as `user_context_path`.
291    let repo_uc = find_project_root(cwd)
292        .ok()
293        .and_then(|root| TracevaultConfig::load(&root))
294        .and_then(|c| c.user_context);
295    let user_path =
296        crate::config::resolve_user_context_in(repo_uc, config_root).resolve_in(config_root);
297    let user_enabled = user_path.is_some();
298
299    let (paths, user, global, worktree, effective) =
300        Context::effective_with_parts(cwd, user_path.as_deref());
301
302    // If the tracevault directory doesn't exist yet, hint that init is needed.
303    // find_project_root gives the classic walk-up path; if it also fails, the
304    // user has not run `tracevault init` yet.
305    if !paths.is_set_up() && find_project_root(cwd).is_err() {
306        eprintln!("hint: No .visdom/ directory found. Run `{TOP} init` first.");
307    }
308
309    let is_linked = matches!(paths.scope, WorktreeScope::Linked { .. });
310
311    print!(
312        "{}",
313        show_report(
314            user.as_ref(),
315            user_enabled,
316            user_path.as_deref(),
317            &global,
318            worktree.as_ref(),
319            is_linked,
320            &effective,
321        )
322    );
323
324    Ok(())
325}
326
327/// Layer names used in provenance annotations, precedence low→high.
328const LAYER_USER: &str = "user";
329const LAYER_REPO: &str = "repo";
330const LAYER_WORKTREE: &str = "worktree";
331
332/// Highest-precedence layer (`worktree` > `repo` > `user`) whose stored
333/// `params` map has `key` set to `Some(_)`. `None` tombstones are skipped:
334/// per `Context::merge_layers`, a key only survives into the effective
335/// params at all if the highest layer that *touches* it sets `Some`, so the
336/// highest `Some` always identifies the correct source.
337fn param_source(
338    user: Option<&Context>,
339    global: &Context,
340    worktree: Option<&Context>,
341    key: &str,
342) -> &'static str {
343    if let Some(w) = worktree {
344        if matches!(w.params.get(key), Some(Some(_))) {
345            return LAYER_WORKTREE;
346        }
347    }
348    if matches!(global.params.get(key), Some(Some(_))) {
349        return LAYER_REPO;
350    }
351    if let Some(u) = user {
352        if matches!(u.params.get(key), Some(Some(_))) {
353            return LAYER_USER;
354        }
355    }
356    "?"
357}
358
359/// First (lowest-precedence) layer whose `labels` contains `label` — labels
360/// are a union, so the *introducing* layer (not the overriding one) is the
361/// meaningful provenance.
362fn label_source(
363    user: Option<&Context>,
364    global: &Context,
365    worktree: Option<&Context>,
366    label: &str,
367) -> &'static str {
368    if let Some(u) = user {
369        if u.labels.iter().any(|l| l == label) {
370            return LAYER_USER;
371        }
372    }
373    if global.labels.iter().any(|l| l == label) {
374        return LAYER_REPO;
375    }
376    if let Some(w) = worktree {
377        if w.labels.iter().any(|l| l == label) {
378            return LAYER_WORKTREE;
379        }
380    }
381    "?"
382}
383
384/// Highest-precedence layer whose `flow_id` is `Some(_)` — same "highest
385/// wins" rule `merge_layers` uses for `flow_id`.
386fn flow_source(
387    user: Option<&Context>,
388    global: &Context,
389    worktree: Option<&Context>,
390) -> &'static str {
391    if let Some(w) = worktree {
392        if w.flow_id.is_some() {
393            return LAYER_WORKTREE;
394        }
395    }
396    if global.flow_id.is_some() {
397        return LAYER_REPO;
398    }
399    if let Some(u) = user {
400        if u.flow_id.is_some() {
401            return LAYER_USER;
402        }
403    }
404    "?"
405}
406
407/// Pure formatter for `tracevault context show`. Extracted out of `run_show`
408/// so the provenance logic is unit-testable without capturing stdout.
409///
410/// `user_enabled`/`user_path` carry the `user_context` config state needed
411/// for the `User` header (a `Context`/`EffectiveContext` alone can't tell
412/// "disabled" apart from "enabled but file missing"). `is_linked` likewise
413/// carries `ContextPaths::scope`: a bare `worktree: Option<&Context>` can't
414/// distinguish "primary checkout, no per-worktree section at all" from
415/// "linked worktree with no per-worktree file yet ('(none)')".
416#[allow(clippy::too_many_arguments)]
417fn show_report(
418    user: Option<&Context>,
419    user_enabled: bool,
420    user_path: Option<&Path>,
421    global: &Context,
422    worktree: Option<&Context>,
423    is_linked: bool,
424    eff: &crate::context::EffectiveContext,
425) -> String {
426    use std::fmt::Write;
427    let mut out = String::new();
428
429    let file_desc = match user_path {
430        Some(p) if user_enabled => p.display().to_string(),
431        _ => "disabled".to_string(),
432    };
433    let _ = writeln!(
434        out,
435        "=== User (enabled: {user_enabled}, file: {file_desc}) ==="
436    );
437    match user {
438        Some(u) => {
439            let _ = writeln!(
440                out,
441                "{}",
442                serde_json::to_string_pretty(u).unwrap_or_default()
443            );
444        }
445        None => {
446            let _ = writeln!(out, "(none)");
447        }
448    }
449
450    let _ = writeln!(out, "\n=== Global ===");
451    let _ = writeln!(
452        out,
453        "{}",
454        serde_json::to_string_pretty(global).unwrap_or_default()
455    );
456
457    if is_linked {
458        let _ = writeln!(out, "\n=== This worktree ===");
459        match worktree {
460            Some(wt) => {
461                let _ = writeln!(
462                    out,
463                    "{}",
464                    serde_json::to_string_pretty(wt).unwrap_or_default()
465                );
466            }
467            None => {
468                let _ = writeln!(out, "(none)");
469            }
470        }
471    }
472
473    let _ = writeln!(out, "\n=== Effective ===");
474    match &eff.flow_id {
475        Some(f) => {
476            let source = flow_source(user, global, worktree);
477            let _ = writeln!(out, "flow_id = {f}   [from {source}]");
478        }
479        None => {
480            let _ = writeln!(out, "flow_id = (none)");
481        }
482    }
483
484    let _ = writeln!(out, "labels:");
485    if eff.labels.is_empty() {
486        let _ = writeln!(out, "  (none)");
487    } else {
488        for label in &eff.labels {
489            let source = label_source(user, global, worktree, label);
490            let _ = writeln!(out, "  {label}   [from {source}]");
491        }
492    }
493
494    let _ = writeln!(out, "params:");
495    if eff.params.is_empty() {
496        let _ = writeln!(out, "  (none)");
497    } else {
498        for (k, v) in &eff.params {
499            let source = param_source(user, global, worktree, k);
500            let _ = writeln!(out, "  {k} = {v}   [from {source}]");
501        }
502    }
503
504    out
505}
506
507/// `tracevault context clear` — remove/reset the context for the chosen scope.
508///
509/// Default scope:
510/// - Linked worktree → DELETE `worktrees/<key>/context.json` if it exists.
511///   A missing file means "no per-worktree context" (`load_worktree` returns
512///   `None`, `show` prints "(none)"), so deleting preserves the absent-vs-empty
513///   distinction that the rest of the design relies on.
514/// - Primary checkout → write an empty (default) `context.json`.
515///   The global file is the canonical one; there is no absent-vs-empty
516///   distinction to preserve, and `show`/`effective` always read it.
517///
518/// `global = true` forces clearing the global file from any worktree.
519/// `user = true` clears the resolved user-context file instead (wins over `global`);
520/// like the global file, the user file is canonical, so it is overwritten with an
521/// empty context rather than deleted.
522pub fn run_clear(cwd: &Path, global: bool, user: bool) -> Result<(), Box<dyn std::error::Error>> {
523    if user {
524        let path = user_context_path(cwd)?;
525        Context::default()
526            .save_to(&path)
527            .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
528        println!("Context cleared.");
529        return Ok(());
530    }
531
532    let paths = resolve_context_paths(cwd);
533
534    // Require an initialised .visdom/ before mutating.
535    if !paths.is_set_up() {
536        return Err(crate::program::say("no .visdom/ found — run 'tracevault init' first").into());
537    }
538
539    let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
540
541    if use_global {
542        // Global scope: overwrite with an empty context so `show`/`effective`
543        // continue to find a well-formed file.
544        Context::default()
545            .save_global(&paths)
546            .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
547    } else {
548        // Per-worktree scope: delete the file so that `load_worktree` returns
549        // `None` and `show` prints "(none)" — preserving the absent-vs-empty
550        // distinction.
551        // (And the file an earlier release left, or it would come back.)
552        let wt_path = paths.worktree_path();
553        let legacy = wt_path.as_deref().and_then(crate::layout::legacy_twin);
554        for path in wt_path.into_iter().chain(legacy) {
555            match std::fs::remove_file(&path) {
556                Ok(()) => {}
557                Err(e) if e.kind() == io::ErrorKind::NotFound => {} // already absent — fine
558                Err(e) => return Err(format!("failed to clear context: {e}").into()),
559            }
560        }
561    }
562
563    println!("Context cleared.");
564    Ok(())
565}
566
567/// `tracevault context source` — enable/disable or point the project's
568/// user-level context source (`user_context` in `config.toml`).
569///
570/// The mode flags (`--enable`, `--disable`, `--path <p>`, `--default`) are
571/// mutually exclusive — enforced at the CLI layer — so exactly one mode is set:
572/// `--path` points at an explicit file; `--enable`/`--default` both mean
573/// "enabled at the default path"; `--disable` turns it off. If none are given,
574/// errors rather than silently no-op'ing.
575pub fn run_source(
576    cwd: &Path,
577    enable: bool,
578    disable: bool,
579    path: Option<String>,
580    default: bool,
581) -> Result<(), Box<dyn std::error::Error>> {
582    let root = find_project_root(cwd)?;
583    // Editing `user_context`, so distinguish a missing config from a malformed
584    // one (same as `run_stream` / `user_context_path`) rather than reporting a
585    // malformed file as "not found".
586    let mut config = match TracevaultConfig::try_load(&root) {
587        Ok(Some(cfg)) => cfg,
588        Ok(None) => {
589            return Err(crate::program::say(
590                "no .visdom/tracing.toml found — run 'tracevault init' first",
591            )
592            .into())
593        }
594        Err(e) => return Err(format!("malformed .visdom/tracing.toml: {e}").into()),
595    };
596
597    let new_user_context = if disable {
598        UserContext::Toggle(false)
599    } else if let Some(p) = path {
600        UserContext::Path(p)
601    } else if default || enable {
602        UserContext::Toggle(true)
603    } else {
604        return Err("specify one of --enable, --disable, --path <file>, --default".into());
605    };
606    config.user_context = Some(new_user_context);
607
608    config.save(&root)?;
609    println!("Updated user_context.");
610    Ok(())
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616    use std::collections::BTreeMap;
617    use std::fs;
618
619    #[test]
620    fn show_report_includes_user_section_and_repo_provenance() {
621        let user = Context {
622            flow_id: None,
623            labels: vec![],
624            params: BTreeMap::from([("owner".to_string(), Some("alice".to_string()))]),
625        };
626        let global = Context {
627            flow_id: None,
628            labels: vec![],
629            params: BTreeMap::from([("owner".to_string(), Some("bob".to_string()))]),
630        };
631        let eff = Context::merge_layers(&[&user, &global]);
632
633        let report = show_report(
634            Some(&user),
635            true,
636            Some(Path::new("/tmp/user.json")),
637            &global,
638            None,
639            false,
640            &eff,
641        );
642
643        assert!(
644            report.contains("=== User"),
645            "missing User section: {report}"
646        );
647        assert!(
648            report.contains("owner = bob   [from repo]"),
649            "missing repo provenance for overridden param: {report}"
650        );
651    }
652
653    /// Create a temp project with a `.visdom/tracing.toml` for `run_source` tests.
654    fn temp_project() -> tempfile::TempDir {
655        let dir = tempfile::tempdir().unwrap();
656        let tv_dir = dir.path().join(".visdom");
657        fs::create_dir_all(&tv_dir).unwrap();
658        fs::write(
659            tv_dir.join("tracing.toml"),
660            TracevaultConfig::default().to_toml(),
661        )
662        .unwrap();
663        dir
664    }
665
666    #[test]
667    fn source_enable_disable_and_path() {
668        let dir = temp_project();
669
670        run_source(dir.path(), true, false, None, false).unwrap();
671        let cfg = TracevaultConfig::load(dir.path()).unwrap();
672        assert!(cfg.user_context.unwrap().resolve().is_some());
673
674        run_source(dir.path(), false, true, None, false).unwrap();
675        let cfg = TracevaultConfig::load(dir.path()).unwrap();
676        assert!(cfg.user_context.unwrap().resolve().is_none());
677
678        run_source(dir.path(), false, false, Some("/p".to_string()), false).unwrap();
679        let cfg = TracevaultConfig::load(dir.path()).unwrap();
680        assert_eq!(
681            cfg.user_context.unwrap().resolve(),
682            Some(std::path::PathBuf::from("/p"))
683        );
684    }
685
686    #[test]
687    fn source_default_flag_enables() {
688        let dir = temp_project();
689        run_source(dir.path(), false, false, None, true).unwrap();
690        let cfg = TracevaultConfig::load(dir.path()).unwrap();
691        assert!(cfg.user_context.unwrap().resolve().is_some());
692    }
693
694    /// Only `user_context` changes: a hand-written `api_key`, the other
695    /// fields, unknown keys and the key order all survive (VIS-1046).
696    #[test]
697    fn source_keeps_the_rest_of_the_config() {
698        let dir = tempfile::tempdir().unwrap();
699        fs::create_dir_all(dir.path().join(".visdom")).unwrap();
700        let original = "repo_id = \"r1\"\napi_key = \"tvk_x\"\nuser_context = true\n\
701                        default_project = \"payments\"\nfuture_setting = 1\n";
702        fs::write(dir.path().join(".visdom/tracing.toml"), original).unwrap();
703
704        run_source(dir.path(), false, true, None, false).unwrap();
705
706        let content = fs::read_to_string(dir.path().join(".visdom/tracing.toml")).unwrap();
707        assert_eq!(
708            content,
709            format!(
710                "# Visdom tracing configuration (this checkout's own)\n{}agent = \"claude-code\"\n",
711                original.replace("user_context = true", "user_context = false")
712            )
713        );
714    }
715
716    #[test]
717    fn source_no_flags_errors() {
718        let dir = temp_project();
719        let err = run_source(dir.path(), false, false, None, false).unwrap_err();
720        assert!(err.to_string().contains("--enable"));
721    }
722
723    #[test]
724    fn parse_param_valid() {
725        assert_eq!(
726            parse_param("key=value").unwrap(),
727            ("key".to_string(), "value".to_string())
728        );
729    }
730
731    #[test]
732    fn parse_param_value_contains_equals() {
733        // Only split on the FIRST =
734        assert_eq!(
735            parse_param("key=a=b").unwrap(),
736            ("key".to_string(), "a=b".to_string())
737        );
738    }
739
740    #[test]
741    fn parse_param_no_equals_errors() {
742        let err = parse_param("noequals").unwrap_err();
743        assert!(err.to_string().contains("expected key=value"));
744        assert!(err.to_string().contains("noequals"));
745    }
746
747    #[test]
748    fn split_labels_comma_separated() {
749        let result = split_labels(&["a,b,c".to_string(), "d".to_string()]);
750        assert_eq!(result, vec!["a", "b", "c", "d"]);
751    }
752
753    /// Create a temp project whose `config.toml` points `user_context` at an
754    /// explicit path outside the project (`uc_path`).
755    fn temp_project_with_user_context(uc_path: &Path) -> tempfile::TempDir {
756        let dir = tempfile::tempdir().unwrap();
757        let tv_dir = dir.path().join(".visdom");
758        fs::create_dir_all(&tv_dir).unwrap();
759        let config = TracevaultConfig {
760            user_context: Some(UserContext::Path(uc_path.display().to_string())),
761            ..TracevaultConfig::default()
762        };
763        fs::write(tv_dir.join("tracing.toml"), config.to_toml()).unwrap();
764        dir
765    }
766
767    #[test]
768    fn set_user_writes_resolved_user_context_file() {
769        let uc_dir = tempfile::tempdir().unwrap();
770        let uc_path = uc_dir.path().join("uc.json");
771        let project = temp_project_with_user_context(&uc_path);
772
773        run_set(
774            project.path(),
775            None,
776            vec!["team".to_string()],
777            vec!["env=prod".to_string()],
778            false,
779            true,
780        )
781        .unwrap();
782
783        let ctx = Context::load_from(&uc_path);
784        assert_eq!(ctx.labels, vec!["team".to_string()]);
785        assert_eq!(ctx.params.get("env"), Some(&Some("prod".to_string())));
786    }
787
788    #[test]
789    fn update_user_merges_into_resolved_user_context_file() {
790        let uc_dir = tempfile::tempdir().unwrap();
791        let uc_path = uc_dir.path().join("uc.json");
792        let project = temp_project_with_user_context(&uc_path);
793
794        run_set(
795            project.path(),
796            None,
797            vec!["team".to_string()],
798            vec!["env=prod".to_string()],
799            false,
800            true,
801        )
802        .unwrap();
803
804        run_update(
805            project.path(),
806            None,
807            vec!["extra".to_string()],
808            vec![],
809            vec![],
810            vec!["env".to_string()],
811            false,
812            true,
813        )
814        .unwrap();
815
816        let ctx = Context::load_from(&uc_path);
817        assert_eq!(ctx.labels, vec!["team".to_string(), "extra".to_string()]);
818        assert_eq!(ctx.params.get("env"), Some(&None));
819    }
820
821    #[test]
822    fn user_context_path_no_checkout_uses_global_config() {
823        let cfg_root = tempfile::tempdir().unwrap();
824        std::fs::write(
825            crate::config::user_config_path_in(cfg_root.path()),
826            "user_context = true\n",
827        )
828        .unwrap();
829        let cwd = tempfile::tempdir().unwrap(); // no .visdom/ anywhere above
830        let p = user_context_path_in(cwd.path(), cfg_root.path()).unwrap();
831        assert_eq!(
832            p,
833            crate::config::default_user_context_path_in(cfg_root.path())
834        );
835    }
836
837    #[test]
838    fn user_context_path_no_checkout_defaults_when_global_absent() {
839        let cfg_root = tempfile::tempdir().unwrap();
840        let cwd = tempfile::tempdir().unwrap();
841        let p = user_context_path_in(cwd.path(), cfg_root.path()).unwrap();
842        assert_eq!(
843            p,
844            crate::config::default_user_context_path_in(cfg_root.path())
845        );
846    }
847
848    #[test]
849    fn run_show_in_detached_uses_user_level_config_without_error() {
850        let cfg_root = tempfile::tempdir().unwrap();
851        std::fs::write(
852            crate::config::user_config_path_in(cfg_root.path()),
853            "user_context = true\n",
854        )
855        .unwrap();
856        // Seed the referenced default context file so the enabled layer has content.
857        let ctx = crate::config::default_user_context_path_in(cfg_root.path());
858        crate::context::Context::default().save_to(&ctx).unwrap();
859        let cwd = tempfile::tempdir().unwrap(); // no .visdom/ anywhere above
860                                                // Must resolve against the injected root (NOT ~/.config) and not error.
861        assert!(run_show_in(cwd.path(), cfg_root.path()).is_ok());
862    }
863
864    #[test]
865    fn user_context_path_explicit_off_repo_falls_through_to_user_level() {
866        // A checkout whose repo config explicitly disables the user layer.
867        let repo = tempfile::tempdir().unwrap();
868        let tv = repo.path().join(".visdom");
869        std::fs::create_dir_all(&tv).unwrap();
870        std::fs::write(
871            tv.join("tracing.toml"),
872            "agent = \"claude-code\"\nuser_context = false\n",
873        )
874        .unwrap();
875        // A user-level config that points the user context at a custom path.
876        let cfg_root = tempfile::tempdir().unwrap();
877        let custom = cfg_root.path().join("mine.json");
878        std::fs::write(
879            crate::config::user_config_path_in(cfg_root.path()),
880            format!("user_context = \"{}\"\n", custom.display()),
881        )
882        .unwrap();
883        let p = user_context_path_in(repo.path(), cfg_root.path()).unwrap();
884        assert_eq!(
885            p, custom,
886            "explicit-off repo must not hijack the --user edit to the default file"
887        );
888    }
889
890    #[test]
891    fn clear_user_resets_resolved_user_context_file() {
892        let uc_dir = tempfile::tempdir().unwrap();
893        let uc_path = uc_dir.path().join("uc.json");
894        let project = temp_project_with_user_context(&uc_path);
895
896        run_set(
897            project.path(),
898            None,
899            vec!["team".to_string()],
900            vec![],
901            false,
902            true,
903        )
904        .unwrap();
905
906        run_clear(project.path(), false, true).unwrap();
907
908        let ctx = Context::load_from(&uc_path);
909        assert_eq!(ctx, Context::default());
910    }
911}