Skip to main content

tracevault_cli/commands/
context.rs

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