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    let root = find_project_root(cwd)?;
53    // A *malformed* config.toml must not silently fall back to the default path:
54    // that could route a `--user` edit to the wrong file when the user actually
55    // configured a custom path we failed to parse. A *missing* config is fine —
56    // there is no configured override, so the default path is correct.
57    let config = TracevaultConfig::try_load(&root)
58        .map_err(|e| format!("cannot resolve --user path: malformed .tracevault/config.toml: {e}"))?
59        .unwrap_or_default();
60    Ok(config.user_context.path())
61}
62
63/// `tracevault context set` — build a fresh Context from flags, save it.
64/// Omitted dimensions are empty. Clears anything not explicitly provided.
65///
66/// Default scope:
67/// - Linked worktree → writes `worktrees/<key>/context.json`.
68/// - Primary checkout → writes the global `context.json`.
69///
70/// `global = true` forces the global file from any worktree.
71/// `user = true` writes the resolved user-context file instead (wins over `global`).
72pub fn run_set(
73    cwd: &Path,
74    flow: Option<String>,
75    labels: Vec<String>,
76    params: Vec<String>,
77    global: bool,
78    user: bool,
79) -> Result<(), Box<dyn std::error::Error>> {
80    let mut parsed_params = std::collections::BTreeMap::new();
81    for raw in &params {
82        let (k, v) = parse_param(raw)?;
83        parsed_params.insert(k, Some(v));
84    }
85
86    let ctx = Context {
87        flow_id: flow,
88        labels: split_labels(&labels),
89        params: parsed_params,
90    };
91
92    if user {
93        let path = user_context_path(cwd)?;
94        ctx.save_to(&path)
95            .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
96        println!("Context set.");
97        return Ok(());
98    }
99
100    let paths = resolve_context_paths(cwd);
101
102    // Require an initialised .tracevault/ before mutating.
103    if !paths.tracevault_dir.exists() {
104        return Err("no .tracevault/ found — run 'tracevault init' first".into());
105    }
106
107    if global || matches!(paths.scope, WorktreeScope::Primary) {
108        ctx.save_global(&paths)
109    } else {
110        ctx.save_worktree(&paths)
111    }
112    .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
113
114    println!("Context set.");
115    Ok(())
116}
117
118/// `tracevault context update` — load existing, apply mutations, save.
119///
120/// Default scope:
121/// - Linked worktree → reads/writes `worktrees/<key>/context.json`.
122/// - Primary checkout → reads/writes the global `context.json`.
123///
124/// `global = true` forces the global file from any worktree.
125/// `user = true` reads/writes the resolved user-context file instead (wins over `global`).
126#[allow(clippy::too_many_arguments)]
127pub fn run_update(
128    cwd: &Path,
129    flow: Option<String>,
130    labels: Vec<String>,
131    params: Vec<String>,
132    remove_labels: Vec<String>,
133    remove_params: Vec<String>,
134    global: bool,
135    user: bool,
136) -> Result<(), Box<dyn std::error::Error>> {
137    if user {
138        let path = user_context_path(cwd)?;
139        let mut ctx = Context::load_from(&path);
140        apply_update_mutations(
141            &mut ctx,
142            flow,
143            &labels,
144            &params,
145            &remove_labels,
146            &remove_params,
147        )?;
148        ctx.save_to(&path)
149            .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
150        println!("Context updated.");
151        return Ok(());
152    }
153
154    let paths = resolve_context_paths(cwd);
155
156    // Require an initialised .tracevault/ before mutating.
157    if !paths.tracevault_dir.exists() {
158        return Err("no .tracevault/ found — run 'tracevault init' first".into());
159    }
160
161    let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
162
163    let mut ctx = if use_global {
164        Context::load_global(&paths)
165    } else {
166        Context::load_worktree(&paths).unwrap_or_default()
167    };
168
169    apply_update_mutations(
170        &mut ctx,
171        flow,
172        &labels,
173        &params,
174        &remove_labels,
175        &remove_params,
176    )?;
177
178    if use_global {
179        ctx.save_global(&paths)
180    } else {
181        ctx.save_worktree(&paths)
182    }
183    .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
184
185    println!("Context updated.");
186    Ok(())
187}
188
189/// Apply the `update` flow's mutations (set flow, union labels, upsert params,
190/// remove labels/params) to an already-loaded `ctx`. Shared by the
191/// repo/worktree/global path and the `--user` path so both branches stay in sync.
192fn apply_update_mutations(
193    ctx: &mut Context,
194    flow: Option<String>,
195    labels: &[String],
196    params: &[String],
197    remove_labels: &[String],
198    remove_params: &[String],
199) -> Result<(), Box<dyn std::error::Error>> {
200    // Set flow if provided
201    if let Some(f) = flow {
202        ctx.flow_id = Some(f);
203    }
204
205    // Union-add labels (dedup guarded inline by the contains check below; save also normalises)
206    let new_labels = split_labels(labels);
207    for l in new_labels {
208        if !ctx.labels.contains(&l) {
209            ctx.labels.push(l);
210        }
211    }
212
213    // Insert/overwrite params
214    for raw in params {
215        let (k, v) = parse_param(raw)?;
216        ctx.params.insert(k, Some(v));
217    }
218
219    // Remove labels
220    let remove_set: std::collections::HashSet<String> =
221        split_labels(remove_labels).into_iter().collect();
222    ctx.labels.retain(|l| !remove_set.contains(l));
223
224    // Remove params: insert a `None` tombstone so the removal propagates through
225    // the merge and drops the key even when a lower-precedence layer sets it.
226    for k in remove_params {
227        ctx.params.insert(k.clone(), None);
228    }
229
230    Ok(())
231}
232
233/// `tracevault context show` — print four labelled sections:
234///   1. User — the cross-repo user-level context (its contents are shown only
235///      when `user_context` is enabled in `config.toml`; the header shows the
236///      resolved file path when enabled and `disabled` otherwise).
237///   2. Global — the repo-wide `context.json`.
238///   3. This worktree — the per-worktree context (Linked only; "(none)" when missing).
239///   4. Effective — the merged result that the hook stamps on every event, with
240///      each label/param annotated with the layer it came from.
241///
242/// Prints a hint if no `.tracevault/` directory is found (i.e. `tracevault init` has
243/// not been run), using `find_project_root` for the diagnostic.
244pub fn run_show(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
245    // Resolve the user-level context source from config.toml (if any project
246    // root/config exists yet — tolerate neither being present, same as
247    // `user_context_path`).
248    let config = find_project_root(cwd)
249        .ok()
250        .and_then(|root| TracevaultConfig::load(&root))
251        .unwrap_or_default();
252    let user_path = config.user_context.resolve();
253    let user_enabled = user_path.is_some();
254
255    let (paths, user, global, worktree, effective) =
256        Context::effective_with_parts(cwd, user_path.as_deref());
257
258    // If the tracevault directory doesn't exist yet, hint that init is needed.
259    // find_project_root gives the classic walk-up path; if it also fails, the
260    // user has not run `tracevault init` yet.
261    if !paths.tracevault_dir.exists() && find_project_root(cwd).is_err() {
262        eprintln!("hint: No .tracevault/ directory found. Run `tracevault init` first.");
263    }
264
265    let is_linked = matches!(paths.scope, WorktreeScope::Linked { .. });
266
267    print!(
268        "{}",
269        show_report(
270            user.as_ref(),
271            user_enabled,
272            user_path.as_deref(),
273            &global,
274            worktree.as_ref(),
275            is_linked,
276            &effective,
277        )
278    );
279
280    Ok(())
281}
282
283/// Layer names used in provenance annotations, precedence low→high.
284const LAYER_USER: &str = "user";
285const LAYER_REPO: &str = "repo";
286const LAYER_WORKTREE: &str = "worktree";
287
288/// Highest-precedence layer (`worktree` > `repo` > `user`) whose stored
289/// `params` map has `key` set to `Some(_)`. `None` tombstones are skipped:
290/// per `Context::merge_layers`, a key only survives into the effective
291/// params at all if the highest layer that *touches* it sets `Some`, so the
292/// highest `Some` always identifies the correct source.
293fn param_source(
294    user: Option<&Context>,
295    global: &Context,
296    worktree: Option<&Context>,
297    key: &str,
298) -> &'static str {
299    if let Some(w) = worktree {
300        if matches!(w.params.get(key), Some(Some(_))) {
301            return LAYER_WORKTREE;
302        }
303    }
304    if matches!(global.params.get(key), Some(Some(_))) {
305        return LAYER_REPO;
306    }
307    if let Some(u) = user {
308        if matches!(u.params.get(key), Some(Some(_))) {
309            return LAYER_USER;
310        }
311    }
312    "?"
313}
314
315/// First (lowest-precedence) layer whose `labels` contains `label` — labels
316/// are a union, so the *introducing* layer (not the overriding one) is the
317/// meaningful provenance.
318fn label_source(
319    user: Option<&Context>,
320    global: &Context,
321    worktree: Option<&Context>,
322    label: &str,
323) -> &'static str {
324    if let Some(u) = user {
325        if u.labels.iter().any(|l| l == label) {
326            return LAYER_USER;
327        }
328    }
329    if global.labels.iter().any(|l| l == label) {
330        return LAYER_REPO;
331    }
332    if let Some(w) = worktree {
333        if w.labels.iter().any(|l| l == label) {
334            return LAYER_WORKTREE;
335        }
336    }
337    "?"
338}
339
340/// Highest-precedence layer whose `flow_id` is `Some(_)` — same "highest
341/// wins" rule `merge_layers` uses for `flow_id`.
342fn flow_source(
343    user: Option<&Context>,
344    global: &Context,
345    worktree: Option<&Context>,
346) -> &'static str {
347    if let Some(w) = worktree {
348        if w.flow_id.is_some() {
349            return LAYER_WORKTREE;
350        }
351    }
352    if global.flow_id.is_some() {
353        return LAYER_REPO;
354    }
355    if let Some(u) = user {
356        if u.flow_id.is_some() {
357            return LAYER_USER;
358        }
359    }
360    "?"
361}
362
363/// Pure formatter for `tracevault context show`. Extracted out of `run_show`
364/// so the provenance logic is unit-testable without capturing stdout.
365///
366/// `user_enabled`/`user_path` carry the `user_context` config state needed
367/// for the `User` header (a `Context`/`EffectiveContext` alone can't tell
368/// "disabled" apart from "enabled but file missing"). `is_linked` likewise
369/// carries `ContextPaths::scope`: a bare `worktree: Option<&Context>` can't
370/// distinguish "primary checkout, no per-worktree section at all" from
371/// "linked worktree with no per-worktree file yet ('(none)')".
372#[allow(clippy::too_many_arguments)]
373fn show_report(
374    user: Option<&Context>,
375    user_enabled: bool,
376    user_path: Option<&Path>,
377    global: &Context,
378    worktree: Option<&Context>,
379    is_linked: bool,
380    eff: &crate::context::EffectiveContext,
381) -> String {
382    use std::fmt::Write;
383    let mut out = String::new();
384
385    let file_desc = match user_path {
386        Some(p) if user_enabled => p.display().to_string(),
387        _ => "disabled".to_string(),
388    };
389    let _ = writeln!(
390        out,
391        "=== User (enabled: {user_enabled}, file: {file_desc}) ==="
392    );
393    match user {
394        Some(u) => {
395            let _ = writeln!(
396                out,
397                "{}",
398                serde_json::to_string_pretty(u).unwrap_or_default()
399            );
400        }
401        None => {
402            let _ = writeln!(out, "(none)");
403        }
404    }
405
406    let _ = writeln!(out, "\n=== Global ===");
407    let _ = writeln!(
408        out,
409        "{}",
410        serde_json::to_string_pretty(global).unwrap_or_default()
411    );
412
413    if is_linked {
414        let _ = writeln!(out, "\n=== This worktree ===");
415        match worktree {
416            Some(wt) => {
417                let _ = writeln!(
418                    out,
419                    "{}",
420                    serde_json::to_string_pretty(wt).unwrap_or_default()
421                );
422            }
423            None => {
424                let _ = writeln!(out, "(none)");
425            }
426        }
427    }
428
429    let _ = writeln!(out, "\n=== Effective ===");
430    match &eff.flow_id {
431        Some(f) => {
432            let source = flow_source(user, global, worktree);
433            let _ = writeln!(out, "flow_id = {f}   [from {source}]");
434        }
435        None => {
436            let _ = writeln!(out, "flow_id = (none)");
437        }
438    }
439
440    let _ = writeln!(out, "labels:");
441    if eff.labels.is_empty() {
442        let _ = writeln!(out, "  (none)");
443    } else {
444        for label in &eff.labels {
445            let source = label_source(user, global, worktree, label);
446            let _ = writeln!(out, "  {label}   [from {source}]");
447        }
448    }
449
450    let _ = writeln!(out, "params:");
451    if eff.params.is_empty() {
452        let _ = writeln!(out, "  (none)");
453    } else {
454        for (k, v) in &eff.params {
455            let source = param_source(user, global, worktree, k);
456            let _ = writeln!(out, "  {k} = {v}   [from {source}]");
457        }
458    }
459
460    out
461}
462
463/// `tracevault context clear` — remove/reset the context for the chosen scope.
464///
465/// Default scope:
466/// - Linked worktree → DELETE `worktrees/<key>/context.json` if it exists.
467///   A missing file means "no per-worktree context" (`load_worktree` returns
468///   `None`, `show` prints "(none)"), so deleting preserves the absent-vs-empty
469///   distinction that the rest of the design relies on.
470/// - Primary checkout → write an empty (default) `context.json`.
471///   The global file is the canonical one; there is no absent-vs-empty
472///   distinction to preserve, and `show`/`effective` always read it.
473///
474/// `global = true` forces clearing the global file from any worktree.
475/// `user = true` clears the resolved user-context file instead (wins over `global`);
476/// like the global file, the user file is canonical, so it is overwritten with an
477/// empty context rather than deleted.
478pub fn run_clear(cwd: &Path, global: bool, user: bool) -> Result<(), Box<dyn std::error::Error>> {
479    if user {
480        let path = user_context_path(cwd)?;
481        Context::default()
482            .save_to(&path)
483            .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
484        println!("Context cleared.");
485        return Ok(());
486    }
487
488    let paths = resolve_context_paths(cwd);
489
490    // Require an initialised .tracevault/ before mutating.
491    if !paths.tracevault_dir.exists() {
492        return Err("no .tracevault/ found — run 'tracevault init' first".into());
493    }
494
495    let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
496
497    if use_global {
498        // Global scope: overwrite with an empty context so `show`/`effective`
499        // continue to find a well-formed file.
500        Context::default()
501            .save_global(&paths)
502            .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
503    } else {
504        // Per-worktree scope: delete the file so that `load_worktree` returns
505        // `None` and `show` prints "(none)" — preserving the absent-vs-empty
506        // distinction.
507        if let Some(wt_path) = paths.worktree_path() {
508            match std::fs::remove_file(&wt_path) {
509                Ok(()) => {}
510                Err(e) if e.kind() == io::ErrorKind::NotFound => {} // already absent — fine
511                Err(e) => return Err(format!("failed to clear context: {e}").into()),
512            }
513        }
514    }
515
516    println!("Context cleared.");
517    Ok(())
518}
519
520/// `tracevault context source` — enable/disable or point the project's
521/// user-level context source (`user_context` in `config.toml`).
522///
523/// The mode flags (`--enable`, `--disable`, `--path <p>`, `--default`) are
524/// mutually exclusive — enforced at the CLI layer — so exactly one mode is set:
525/// `--path` points at an explicit file; `--enable`/`--default` both mean
526/// "enabled at the default path"; `--disable` turns it off. If none are given,
527/// errors rather than silently no-op'ing.
528pub fn run_source(
529    cwd: &Path,
530    enable: bool,
531    disable: bool,
532    path: Option<String>,
533    default: bool,
534) -> Result<(), Box<dyn std::error::Error>> {
535    let root = find_project_root(cwd)?;
536    // Editing `user_context`, so distinguish a missing config from a malformed
537    // one (same as `run_stream` / `user_context_path`) rather than reporting a
538    // malformed file as "not found".
539    let mut config = match TracevaultConfig::try_load(&root) {
540        Ok(Some(cfg)) => cfg,
541        Ok(None) => {
542            return Err("no .tracevault/config.toml found — run 'tracevault init' first".into())
543        }
544        Err(e) => return Err(format!("malformed .tracevault/config.toml: {e}").into()),
545    };
546
547    config.user_context = if disable {
548        UserContext::Toggle(false)
549    } else if let Some(p) = path {
550        UserContext::Path(p)
551    } else if default || enable {
552        UserContext::Toggle(true)
553    } else {
554        return Err("specify one of --enable, --disable, --path <file>, --default".into());
555    };
556
557    std::fs::write(TracevaultConfig::config_path(&root), config.to_toml())?;
558    println!("Updated user_context.");
559    Ok(())
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565    use std::collections::BTreeMap;
566    use std::fs;
567
568    #[test]
569    fn show_report_includes_user_section_and_repo_provenance() {
570        let user = Context {
571            flow_id: None,
572            labels: vec![],
573            params: BTreeMap::from([("owner".to_string(), Some("alice".to_string()))]),
574        };
575        let global = Context {
576            flow_id: None,
577            labels: vec![],
578            params: BTreeMap::from([("owner".to_string(), Some("bob".to_string()))]),
579        };
580        let eff = Context::merge_layers(&[&user, &global]);
581
582        let report = show_report(
583            Some(&user),
584            true,
585            Some(Path::new("/tmp/user.json")),
586            &global,
587            None,
588            false,
589            &eff,
590        );
591
592        assert!(
593            report.contains("=== User"),
594            "missing User section: {report}"
595        );
596        assert!(
597            report.contains("owner = bob   [from repo]"),
598            "missing repo provenance for overridden param: {report}"
599        );
600    }
601
602    /// Create a temp project with a `.tracevault/config.toml` for `run_source` tests.
603    fn temp_project() -> tempfile::TempDir {
604        let dir = tempfile::tempdir().unwrap();
605        let tv_dir = dir.path().join(".tracevault");
606        fs::create_dir_all(&tv_dir).unwrap();
607        fs::write(
608            tv_dir.join("config.toml"),
609            TracevaultConfig::default().to_toml(),
610        )
611        .unwrap();
612        dir
613    }
614
615    #[test]
616    fn source_enable_disable_and_path() {
617        let dir = temp_project();
618
619        run_source(dir.path(), true, false, None, false).unwrap();
620        let cfg = TracevaultConfig::load(dir.path()).unwrap();
621        assert!(cfg.user_context.resolve().is_some());
622
623        run_source(dir.path(), false, true, None, false).unwrap();
624        let cfg = TracevaultConfig::load(dir.path()).unwrap();
625        assert!(cfg.user_context.resolve().is_none());
626
627        run_source(dir.path(), false, false, Some("/p".to_string()), false).unwrap();
628        let cfg = TracevaultConfig::load(dir.path()).unwrap();
629        assert_eq!(
630            cfg.user_context.resolve(),
631            Some(std::path::PathBuf::from("/p"))
632        );
633    }
634
635    #[test]
636    fn source_default_flag_enables() {
637        let dir = temp_project();
638        run_source(dir.path(), false, false, None, true).unwrap();
639        let cfg = TracevaultConfig::load(dir.path()).unwrap();
640        assert!(cfg.user_context.resolve().is_some());
641    }
642
643    #[test]
644    fn source_no_flags_errors() {
645        let dir = temp_project();
646        let err = run_source(dir.path(), false, false, None, false).unwrap_err();
647        assert!(err.to_string().contains("--enable"));
648    }
649
650    #[test]
651    fn parse_param_valid() {
652        assert_eq!(
653            parse_param("key=value").unwrap(),
654            ("key".to_string(), "value".to_string())
655        );
656    }
657
658    #[test]
659    fn parse_param_value_contains_equals() {
660        // Only split on the FIRST =
661        assert_eq!(
662            parse_param("key=a=b").unwrap(),
663            ("key".to_string(), "a=b".to_string())
664        );
665    }
666
667    #[test]
668    fn parse_param_no_equals_errors() {
669        let err = parse_param("noequals").unwrap_err();
670        assert!(err.to_string().contains("expected key=value"));
671        assert!(err.to_string().contains("noequals"));
672    }
673
674    #[test]
675    fn split_labels_comma_separated() {
676        let result = split_labels(&["a,b,c".to_string(), "d".to_string()]);
677        assert_eq!(result, vec!["a", "b", "c", "d"]);
678    }
679
680    /// Create a temp project whose `config.toml` points `user_context` at an
681    /// explicit path outside the project (`uc_path`).
682    fn temp_project_with_user_context(uc_path: &Path) -> tempfile::TempDir {
683        let dir = tempfile::tempdir().unwrap();
684        let tv_dir = dir.path().join(".tracevault");
685        fs::create_dir_all(&tv_dir).unwrap();
686        let config = TracevaultConfig {
687            user_context: UserContext::Path(uc_path.display().to_string()),
688            ..TracevaultConfig::default()
689        };
690        fs::write(tv_dir.join("config.toml"), config.to_toml()).unwrap();
691        dir
692    }
693
694    #[test]
695    fn set_user_writes_resolved_user_context_file() {
696        let uc_dir = tempfile::tempdir().unwrap();
697        let uc_path = uc_dir.path().join("uc.json");
698        let project = temp_project_with_user_context(&uc_path);
699
700        run_set(
701            project.path(),
702            None,
703            vec!["team".to_string()],
704            vec!["env=prod".to_string()],
705            false,
706            true,
707        )
708        .unwrap();
709
710        let ctx = Context::load_from(&uc_path);
711        assert_eq!(ctx.labels, vec!["team".to_string()]);
712        assert_eq!(ctx.params.get("env"), Some(&Some("prod".to_string())));
713    }
714
715    #[test]
716    fn update_user_merges_into_resolved_user_context_file() {
717        let uc_dir = tempfile::tempdir().unwrap();
718        let uc_path = uc_dir.path().join("uc.json");
719        let project = temp_project_with_user_context(&uc_path);
720
721        run_set(
722            project.path(),
723            None,
724            vec!["team".to_string()],
725            vec!["env=prod".to_string()],
726            false,
727            true,
728        )
729        .unwrap();
730
731        run_update(
732            project.path(),
733            None,
734            vec!["extra".to_string()],
735            vec![],
736            vec![],
737            vec!["env".to_string()],
738            false,
739            true,
740        )
741        .unwrap();
742
743        let ctx = Context::load_from(&uc_path);
744        assert_eq!(ctx.labels, vec!["team".to_string(), "extra".to_string()]);
745        assert_eq!(ctx.params.get("env"), Some(&None));
746    }
747
748    #[test]
749    fn clear_user_resets_resolved_user_context_file() {
750        let uc_dir = tempfile::tempdir().unwrap();
751        let uc_path = uc_dir.path().join("uc.json");
752        let project = temp_project_with_user_context(&uc_path);
753
754        run_set(
755            project.path(),
756            None,
757            vec!["team".to_string()],
758            vec![],
759            false,
760            true,
761        )
762        .unwrap();
763
764        run_clear(project.path(), false, true).unwrap();
765
766        let ctx = Context::load_from(&uc_path);
767        assert_eq!(ctx, Context::default());
768    }
769}