1use crate::config::{TracevaultConfig, UserContext};
2use crate::context::{resolve_context_paths, Context, WorktreeScope};
3use std::io;
4use std::path::{Path, PathBuf};
5
6pub 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
26fn 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
37fn 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
47fn 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
55fn 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, };
72 if let Some(uc) = repo_uc {
73 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
97pub 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 ¶ms {
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 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#[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 ¶ms,
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 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 ¶ms,
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
223fn 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 if let Some(f) = flow {
236 ctx.flow_id = Some(f);
237 }
238
239 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 for raw in params {
249 let (k, v) = parse_param(raw)?;
250 ctx.params.insert(k, Some(v));
251 }
252
253 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 for k in remove_params {
261 ctx.params.insert(k.clone(), None);
262 }
263
264 Ok(())
265}
266
267pub fn run_show(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
279 run_show_in(cwd, &crate::config::tv_config_root())
280}
281
282pub fn run_show_in(cwd: &Path, config_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
287 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 !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
326const LAYER_USER: &str = "user";
328const LAYER_REPO: &str = "repo";
329const LAYER_WORKTREE: &str = "worktree";
330
331fn 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
358fn 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
383fn 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#[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
506pub 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 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 Context::default()
544 .save_global(&paths)
545 .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
546 } else {
547 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 => {} Err(e) => return Err(format!("failed to clear context: {e}").into()),
555 }
556 }
557 }
558
559 println!("Context cleared.");
560 Ok(())
561}
562
563pub 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 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 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 #[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 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 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(); 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 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(); 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 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 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}