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
7pub 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
27fn 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
38fn 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
48fn 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
56fn 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, };
73 if let Some(uc) = repo_uc {
74 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
98pub 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 ¶ms {
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 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#[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 ¶ms,
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 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 ¶ms,
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
224fn 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 if let Some(f) = flow {
237 ctx.flow_id = Some(f);
238 }
239
240 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 for raw in params {
250 let (k, v) = parse_param(raw)?;
251 ctx.params.insert(k, Some(v));
252 }
253
254 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 for k in remove_params {
262 ctx.params.insert(k.clone(), None);
263 }
264
265 Ok(())
266}
267
268pub fn run_show(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
280 run_show_in(cwd, &crate::config::tv_config_root())
281}
282
283pub fn run_show_in(cwd: &Path, config_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
288 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 !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
327const LAYER_USER: &str = "user";
329const LAYER_REPO: &str = "repo";
330const LAYER_WORKTREE: &str = "worktree";
331
332fn 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
359fn 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
384fn 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#[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
507pub 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 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 Context::default()
545 .save_global(&paths)
546 .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
547 } else {
548 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 => {} Err(e) => return Err(format!("failed to clear context: {e}").into()),
559 }
560 }
561 }
562
563 println!("Context cleared.");
564 Ok(())
565}
566
567pub 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 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 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 #[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 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 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(); 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 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(); 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 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 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}