1use crate::program::TOP;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use std::io;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
18pub struct Context {
19 pub flow_id: Option<String>,
20 pub labels: Vec<String>,
23 pub params: BTreeMap<String, Option<String>>,
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize, Default)]
32pub struct EffectiveContext {
33 pub flow_id: Option<String>,
34 pub labels: Vec<String>,
35 pub params: BTreeMap<String, String>,
36}
37
38#[derive(Debug, Clone, PartialEq)]
44pub enum WorktreeScope {
45 Primary,
47 Linked { key: String },
50}
51
52#[derive(Debug, Clone)]
54pub struct ContextPaths {
55 pub state_dir: PathBuf,
57 pub scope: WorktreeScope,
59}
60
61impl ContextPaths {
62 fn prepare_state_dir(&self) -> io::Result<()> {
67 std::fs::create_dir_all(&self.state_dir)?;
68 crate::config::TracevaultConfig::ensure_gitignore(&self.state_dir)
69 }
70
71 pub fn is_set_up(&self) -> bool {
74 self.state_dir.exists()
75 || crate::layout::legacy_twin(&self.state_dir).is_some_and(|dir| dir.exists())
76 }
77
78 pub fn global_path(&self) -> PathBuf {
80 self.state_dir.join("context.json")
81 }
82
83 pub fn worktree_path(&self) -> Option<PathBuf> {
86 match &self.scope {
87 WorktreeScope::Primary => None,
88 WorktreeScope::Linked { key } => Some(
89 self.state_dir
90 .join("worktrees")
91 .join(key)
92 .join("context.json"),
93 ),
94 }
95 }
96}
97
98fn git_rev_parse(start_dir: &Path) -> Option<(PathBuf, PathBuf)> {
105 let output = Command::new("git")
106 .args([
107 "-C",
108 &start_dir.to_string_lossy(),
109 "rev-parse",
110 "--git-common-dir",
111 "--git-dir",
112 ])
113 .output()
114 .ok()?;
115
116 if !output.status.success() {
117 return None;
118 }
119
120 let stdout = std::str::from_utf8(&output.stdout).ok()?;
121 let mut lines = stdout.lines();
122 let raw_common = lines.next()?.trim();
123 let raw_dir = lines.next()?.trim();
124
125 let canonicalize = |raw: &str| -> Option<PathBuf> {
127 let p = PathBuf::from(raw);
128 if p.is_absolute() {
129 p.canonicalize().ok()
131 } else {
132 start_dir.join(&p).canonicalize().ok()
134 }
135 };
136
137 let git_common_dir = canonicalize(raw_common)?;
138 let git_dir = canonicalize(raw_dir)?;
139
140 Some((git_common_dir, git_dir))
141}
142
143fn context_dir(root: &Path) -> PathBuf {
147 crate::layout::repo_dir(root)
148}
149
150pub fn resolve_context_paths(start_dir: &Path) -> ContextPaths {
162 if let Some((git_common_dir, git_dir)) = git_rev_parse(start_dir) {
164 if let Some(primary_root) = git_common_dir.parent() {
166 let state_dir = context_dir(primary_root);
167
168 let scope = if git_dir == git_common_dir {
169 WorktreeScope::Primary
170 } else {
171 let key = git_dir
173 .file_name()
174 .map(|n| n.to_string_lossy().into_owned())
175 .unwrap_or_else(|| "default".to_string());
176 WorktreeScope::Linked { key }
177 };
178
179 return ContextPaths { state_dir, scope };
180 }
181 }
182
183 let fallback = crate::paths::resolve_project_root(start_dir);
185 ContextPaths {
186 state_dir: context_dir(&fallback.root),
187 scope: WorktreeScope::Primary,
188 }
189}
190
191impl Context {
196 pub fn load_from(path: &Path) -> Context {
204 let path = &crate::layout::existing_or_twin(path);
207 let content = match std::fs::read_to_string(path) {
208 Ok(c) => c,
209 Err(e) if e.kind() == io::ErrorKind::NotFound => return Context::default(),
210 Err(e) => {
211 eprintln!(
212 "{TOP}: warning: could not read context file {}: {e}",
213 path.display()
214 );
215 return Context::default();
216 }
217 };
218 match serde_json::from_str::<Context>(&content) {
219 Ok(ctx) => ctx,
220 Err(e) => {
221 eprintln!(
222 "{TOP}: warning: malformed context file {} (using empty context): {e}",
223 path.display()
224 );
225 Context::default()
226 }
227 }
228 }
229
230 pub fn save_to(&self, path: &Path) -> io::Result<()> {
241 if let Some(parent) = path.parent() {
242 std::fs::create_dir_all(parent)?;
243 }
244
245 let normalised = Self {
246 flow_id: self.flow_id.clone(),
247 labels: dedup_labels(&self.labels),
248 params: self.params.clone(),
249 };
250
251 let json = serde_json::to_string_pretty(&normalised)
252 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
253
254 std::fs::write(path, json)
255 }
256
257 pub fn load_global(paths: &ContextPaths) -> Context {
263 Self::load_from(&paths.global_path())
264 }
265
266 pub fn load_worktree(paths: &ContextPaths) -> Option<Context> {
274 let wt_path = paths.worktree_path()?;
275 if !crate::layout::existing_or_twin(&wt_path).exists() {
276 return None;
277 }
278 Some(Self::load_from(&wt_path))
279 }
280
281 pub fn save_global(&self, paths: &ContextPaths) -> io::Result<()> {
283 paths.prepare_state_dir()?;
284 self.save_to(&paths.global_path())
285 }
286
287 pub fn save_worktree(&self, paths: &ContextPaths) -> io::Result<()> {
289 let wt_path = paths.worktree_path().ok_or_else(|| {
290 io::Error::other("cannot save per-worktree context from primary checkout")
291 })?;
292 paths.prepare_state_dir()?;
293 self.save_to(&wt_path)
294 }
295
296 pub fn merge_layers(layers: &[&Context]) -> EffectiveContext {
306 let mut flow_id: Option<String> = None;
307 let mut all_labels: Vec<String> = Vec::new();
308 let mut params: BTreeMap<String, String> = BTreeMap::new();
309
310 for layer in layers {
311 if layer.flow_id.is_some() {
312 flow_id = layer.flow_id.clone();
313 }
314 all_labels.extend(layer.labels.iter().cloned());
315 for (k, v) in &layer.params {
316 match v {
317 Some(val) => {
318 params.insert(k.clone(), val.clone());
319 }
320 None => {
321 params.remove(k);
322 }
323 }
324 }
325 }
326
327 EffectiveContext {
328 flow_id,
329 labels: dedup_labels(&all_labels),
330 params,
331 }
332 }
333
334 pub fn effective(start_dir: &Path, user_layer: Option<&Path>) -> EffectiveContext {
337 let (_, _, _, _, eff) = Self::effective_with_parts(start_dir, user_layer);
338 eff
339 }
340
341 #[allow(clippy::type_complexity)]
344 pub fn effective_with_parts(
345 start_dir: &Path,
346 user_layer: Option<&Path>,
347 ) -> (
348 ContextPaths,
349 Option<Context>,
350 Context,
351 Option<Context>,
352 EffectiveContext,
353 ) {
354 let paths = resolve_context_paths(start_dir);
355 let user = user_layer.map(Self::load_from);
356 let global = Self::load_global(&paths);
357 let worktree = Self::load_worktree(&paths);
358
359 let mut layers: Vec<&Context> = Vec::new();
360 if let Some(u) = &user {
361 layers.push(u);
362 }
363 layers.push(&global);
364 if let Some(w) = &worktree {
365 layers.push(w);
366 }
367 let effective = Self::merge_layers(&layers);
368 (paths, user, global, worktree, effective)
369 }
370}
371
372fn dedup_labels(labels: &[String]) -> Vec<String> {
378 let mut seen = std::collections::HashSet::new();
379 labels
380 .iter()
381 .map(|l| l.trim().to_string())
382 .filter(|l| !l.is_empty())
383 .filter(|l| seen.insert(l.clone()))
384 .collect()
385}
386
387#[cfg(test)]
392mod tests {
393 use super::*;
394 use std::collections::BTreeMap;
395
396 #[test]
397 fn default_context_is_empty() {
398 let ctx = Context::default();
399 assert!(ctx.flow_id.is_none());
400 assert!(ctx.labels.is_empty());
401 assert!(ctx.params.is_empty());
402 }
403
404 #[test]
405 fn save_and_load_round_trip() {
406 let dir = tempfile::tempdir().unwrap();
407 let ctx_path = dir.path().join(".visdom").join("context.json");
408 let mut params = BTreeMap::new();
409 params.insert("key1".to_string(), Some("value1".to_string()));
410 params.insert("key2".to_string(), Some("value2".to_string()));
411
412 let ctx = Context {
413 flow_id: Some("flow-abc-123".to_string()),
414 labels: vec!["backend".to_string(), "urgent".to_string()],
415 params,
416 };
417
418 ctx.save_to(&ctx_path).unwrap();
419 let loaded = Context::load_from(&ctx_path);
420 assert_eq!(ctx, loaded);
421 }
422
423 #[test]
424 fn load_missing_file_returns_default() {
425 let dir = tempfile::tempdir().unwrap();
426 let missing = dir.path().join(".visdom").join("context.json");
427 let ctx = Context::load_from(&missing);
428 assert_eq!(ctx, Context::default());
429 }
430
431 #[test]
432 fn label_dedup_on_save() {
433 let dir = tempfile::tempdir().unwrap();
434 let ctx_path = dir.path().join(".visdom").join("context.json");
435 let ctx = Context {
436 flow_id: None,
437 labels: vec![
438 "alpha".to_string(),
439 "beta".to_string(),
440 "alpha".to_string(), " ".to_string(), "gamma".to_string(),
443 "beta".to_string(), ],
445 params: BTreeMap::new(),
446 };
447
448 ctx.save_to(&ctx_path).unwrap();
449 let loaded = Context::load_from(&ctx_path);
450 assert_eq!(
451 loaded.labels,
452 vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]
453 );
454 }
455
456 #[test]
457 fn load_malformed_json_returns_default() {
458 let dir = tempfile::tempdir().unwrap();
459 let tv_dir = dir.path().join(".visdom");
460 std::fs::create_dir_all(&tv_dir).unwrap();
461 let ctx_path = tv_dir.join("context.json");
462 std::fs::write(&ctx_path, b"not valid json {{{{").unwrap();
463
464 let ctx = Context::load_from(&ctx_path);
465 assert_eq!(ctx, Context::default());
466 }
467
468 #[test]
469 fn save_creates_tracevault_dir_if_missing() {
470 let dir = tempfile::tempdir().unwrap();
471 let ctx_path = dir.path().join(".visdom").join("context.json");
472 assert!(!dir.path().join(".visdom").exists());
474
475 let ctx = Context::default();
476 ctx.save_to(&ctx_path).unwrap();
477
478 assert!(ctx_path.exists());
479 }
480
481 #[test]
482 fn params_tombstone_round_trips_as_null() {
483 let dir = tempfile::tempdir().unwrap();
484 let path = dir.path().join(".visdom").join("context.json");
485 let mut params = BTreeMap::new();
486 params.insert("keep".to_string(), Some("v".to_string()));
487 params.insert("drop".to_string(), None); let ctx = Context {
489 flow_id: None,
490 labels: vec![],
491 params,
492 };
493 ctx.save_to(&path).unwrap();
494
495 let raw = std::fs::read_to_string(&path).unwrap();
496 assert!(
497 raw.contains("\"drop\": null"),
498 "tombstone must serialize as null"
499 );
500 assert!(raw.contains("\"keep\": \"v\""));
501 assert_eq!(Context::load_from(&path), ctx);
502 }
503
504 #[test]
505 fn legacy_string_params_load_as_some() {
506 let dir = tempfile::tempdir().unwrap();
507 let path = dir.path().join(".visdom").join("context.json");
508 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
509 std::fs::write(&path, r#"{"flow_id":null,"labels":[],"params":{"k":"v"}}"#).unwrap();
510 let ctx = Context::load_from(&path);
511 assert_eq!(ctx.params.get("k"), Some(&Some("v".to_string())));
512 }
513
514 fn ctx(flow: Option<&str>, labels: &[&str], params: &[(&str, &str)]) -> Context {
519 Context {
520 flow_id: flow.map(str::to_string),
521 labels: labels.iter().map(|s| s.to_string()).collect(),
522 params: params
523 .iter()
524 .map(|(k, v)| (k.to_string(), Some(v.to_string())))
525 .collect(),
526 }
527 }
528
529 #[test]
530 fn fold_precedence_and_labels_union() {
531 let user = ctx(Some("u"), &["base"], &[("env", "prod"), ("owner", "u")]);
532 let repo = ctx(Some("r"), &["repo"], &[("owner", "team")]); let wt = ctx(None, &["wt"], &[]);
534 let eff = Context::merge_layers(&[&user, &repo, &wt]);
535 assert_eq!(eff.flow_id, Some("r".to_string())); assert_eq!(eff.labels, vec!["base", "repo", "wt"]); assert_eq!(eff.params["env"], "prod"); assert_eq!(eff.params["owner"], "team"); }
540
541 #[test]
542 fn fold_tombstone_removes_lower_layer_param() {
543 let user = ctx(Some("u"), &[], &[("secret", "x")]);
544 let mut repo = ctx(None, &[], &[]);
545 repo.params.insert("secret".to_string(), None); let eff = Context::merge_layers(&[&user, &repo]);
547 assert!(
548 !eff.params.contains_key("secret"),
549 "tombstone drops inherited key"
550 );
551 }
552
553 #[test]
554 fn fold_single_layer_matches_input() {
555 let only = ctx(Some("g"), &["a"], &[("k", "1")]);
556 let eff = Context::merge_layers(&[&only]);
557 assert_eq!(eff.flow_id, Some("g".to_string()));
558 assert_eq!(eff.labels, vec!["a"]);
559 assert_eq!(eff.params["k"], "1");
560 }
561
562 #[test]
563 fn legacy_context_is_read_file_by_file_and_never_written() {
564 let dir = tempfile::tempdir().unwrap();
565 let root = dir.path();
566 let json = |notes: &str| format!(r#"{{"labels":["{notes}"],"params":{{}}}}"#);
567 let write = |rel: &str, notes: &str| {
568 let path = root.join(rel);
569 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
570 std::fs::write(path, json(notes)).unwrap();
571 };
572 write(".visdom/context.json", "new global");
575 write(".tracevault/context.json", "old global");
576 write(".tracevault/worktrees/feature/context.json", "old worktree");
577 let paths = ContextPaths {
578 state_dir: root.join(".visdom"),
579 scope: WorktreeScope::Linked {
580 key: "feature".into(),
581 },
582 };
583
584 let global = Context::load_global(&paths);
585 let mut worktree = Context::load_worktree(&paths).expect("the legacy worktree file");
586 assert_eq!(
587 serde_json::to_value(&global).unwrap(),
588 serde_json::to_value(Context::load_from(&root.join(".visdom/context.json"))).unwrap()
589 );
590 assert_ne!(
591 serde_json::to_value(&worktree).unwrap(),
592 serde_json::to_value(Context::default()).unwrap(),
593 "the worktree context an earlier release wrote must still be read"
594 );
595
596 worktree.save_worktree(&paths).unwrap();
598 assert!(root.join(".visdom/worktrees/feature/context.json").exists());
599 assert!(root.join(".visdom/.gitignore").exists());
601 assert_eq!(
602 std::fs::read_to_string(root.join(".tracevault/worktrees/feature/context.json"))
603 .unwrap(),
604 json("old worktree")
605 );
606 worktree = Context::default();
607 worktree.save_global(&paths).unwrap();
608 assert_eq!(
609 std::fs::read_to_string(root.join(".tracevault/context.json")).unwrap(),
610 json("old global")
611 );
612 }
613
614 #[test]
615 fn a_checkout_set_up_by_an_earlier_release_counts_as_set_up() {
616 let dir = tempfile::tempdir().unwrap();
617 let paths = ContextPaths {
618 state_dir: dir.path().join(".visdom"),
619 scope: WorktreeScope::Primary,
620 };
621 assert!(!paths.is_set_up());
622 std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
623 assert!(paths.is_set_up());
624 }
625}