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 std::fs::write(TracevaultConfig::config_path(&root), config.to_toml())?;
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]
688 fn source_no_flags_errors() {
689 let dir = temp_project();
690 let err = run_source(dir.path(), false, false, None, false).unwrap_err();
691 assert!(err.to_string().contains("--enable"));
692 }
693
694 #[test]
695 fn parse_param_valid() {
696 assert_eq!(
697 parse_param("key=value").unwrap(),
698 ("key".to_string(), "value".to_string())
699 );
700 }
701
702 #[test]
703 fn parse_param_value_contains_equals() {
704 assert_eq!(
706 parse_param("key=a=b").unwrap(),
707 ("key".to_string(), "a=b".to_string())
708 );
709 }
710
711 #[test]
712 fn parse_param_no_equals_errors() {
713 let err = parse_param("noequals").unwrap_err();
714 assert!(err.to_string().contains("expected key=value"));
715 assert!(err.to_string().contains("noequals"));
716 }
717
718 #[test]
719 fn split_labels_comma_separated() {
720 let result = split_labels(&["a,b,c".to_string(), "d".to_string()]);
721 assert_eq!(result, vec!["a", "b", "c", "d"]);
722 }
723
724 fn temp_project_with_user_context(uc_path: &Path) -> tempfile::TempDir {
727 let dir = tempfile::tempdir().unwrap();
728 let tv_dir = dir.path().join(".tracevault");
729 fs::create_dir_all(&tv_dir).unwrap();
730 let config = TracevaultConfig {
731 user_context: Some(UserContext::Path(uc_path.display().to_string())),
732 ..TracevaultConfig::default()
733 };
734 fs::write(tv_dir.join("config.toml"), config.to_toml()).unwrap();
735 dir
736 }
737
738 #[test]
739 fn set_user_writes_resolved_user_context_file() {
740 let uc_dir = tempfile::tempdir().unwrap();
741 let uc_path = uc_dir.path().join("uc.json");
742 let project = temp_project_with_user_context(&uc_path);
743
744 run_set(
745 project.path(),
746 None,
747 vec!["team".to_string()],
748 vec!["env=prod".to_string()],
749 false,
750 true,
751 )
752 .unwrap();
753
754 let ctx = Context::load_from(&uc_path);
755 assert_eq!(ctx.labels, vec!["team".to_string()]);
756 assert_eq!(ctx.params.get("env"), Some(&Some("prod".to_string())));
757 }
758
759 #[test]
760 fn update_user_merges_into_resolved_user_context_file() {
761 let uc_dir = tempfile::tempdir().unwrap();
762 let uc_path = uc_dir.path().join("uc.json");
763 let project = temp_project_with_user_context(&uc_path);
764
765 run_set(
766 project.path(),
767 None,
768 vec!["team".to_string()],
769 vec!["env=prod".to_string()],
770 false,
771 true,
772 )
773 .unwrap();
774
775 run_update(
776 project.path(),
777 None,
778 vec!["extra".to_string()],
779 vec![],
780 vec![],
781 vec!["env".to_string()],
782 false,
783 true,
784 )
785 .unwrap();
786
787 let ctx = Context::load_from(&uc_path);
788 assert_eq!(ctx.labels, vec!["team".to_string(), "extra".to_string()]);
789 assert_eq!(ctx.params.get("env"), Some(&None));
790 }
791
792 #[test]
793 fn user_context_path_no_checkout_uses_global_config() {
794 let cfg_root = tempfile::tempdir().unwrap();
795 std::fs::write(
796 crate::config::user_config_path_in(cfg_root.path()),
797 "user_context = true\n",
798 )
799 .unwrap();
800 let cwd = tempfile::tempdir().unwrap(); let p = user_context_path_in(cwd.path(), cfg_root.path()).unwrap();
802 assert_eq!(
803 p,
804 crate::config::default_user_context_path_in(cfg_root.path())
805 );
806 }
807
808 #[test]
809 fn user_context_path_no_checkout_defaults_when_global_absent() {
810 let cfg_root = tempfile::tempdir().unwrap();
811 let cwd = tempfile::tempdir().unwrap();
812 let p = user_context_path_in(cwd.path(), cfg_root.path()).unwrap();
813 assert_eq!(
814 p,
815 crate::config::default_user_context_path_in(cfg_root.path())
816 );
817 }
818
819 #[test]
820 fn run_show_in_detached_uses_user_level_config_without_error() {
821 let cfg_root = tempfile::tempdir().unwrap();
822 std::fs::write(
823 crate::config::user_config_path_in(cfg_root.path()),
824 "user_context = true\n",
825 )
826 .unwrap();
827 let ctx = crate::config::default_user_context_path_in(cfg_root.path());
829 crate::context::Context::default().save_to(&ctx).unwrap();
830 let cwd = tempfile::tempdir().unwrap(); assert!(run_show_in(cwd.path(), cfg_root.path()).is_ok());
833 }
834
835 #[test]
836 fn user_context_path_explicit_off_repo_falls_through_to_user_level() {
837 let repo = tempfile::tempdir().unwrap();
839 let tv = repo.path().join(".tracevault");
840 std::fs::create_dir_all(&tv).unwrap();
841 std::fs::write(
842 tv.join("config.toml"),
843 "agent = \"claude-code\"\nuser_context = false\n",
844 )
845 .unwrap();
846 let cfg_root = tempfile::tempdir().unwrap();
848 let custom = cfg_root.path().join("mine.json");
849 std::fs::write(
850 crate::config::user_config_path_in(cfg_root.path()),
851 format!("user_context = \"{}\"\n", custom.display()),
852 )
853 .unwrap();
854 let p = user_context_path_in(repo.path(), cfg_root.path()).unwrap();
855 assert_eq!(
856 p, custom,
857 "explicit-off repo must not hijack the --user edit to the default file"
858 );
859 }
860
861 #[test]
862 fn clear_user_resets_resolved_user_context_file() {
863 let uc_dir = tempfile::tempdir().unwrap();
864 let uc_path = uc_dir.path().join("uc.json");
865 let project = temp_project_with_user_context(&uc_path);
866
867 run_set(
868 project.path(),
869 None,
870 vec!["team".to_string()],
871 vec![],
872 false,
873 true,
874 )
875 .unwrap();
876
877 run_clear(project.path(), false, true).unwrap();
878
879 let ctx = Context::load_from(&uc_path);
880 assert_eq!(ctx, Context::default());
881 }
882}