Skip to main content

tracevault_cli/
context.rs

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// ---------------------------------------------------------------------------
9// Context struct
10// ---------------------------------------------------------------------------
11
12/// Active context written by `tracevault context set` and read by the CC hook.
13///
14/// Stored as pretty-printed JSON at `.visdom/context.json`.
15/// BTreeMap is used for `params` so keys are always in sorted order on disk,
16/// giving stable, human-readable diffs.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
18pub struct Context {
19    pub flow_id: Option<String>,
20    /// Deduplicated, non-empty labels. Duplicates are removed on save (first
21    /// occurrence wins); blank/whitespace-only entries are dropped.
22    pub labels: Vec<String>,
23    /// Stored params. `Some(v)` sets a value; `None` is a delete tombstone that
24    /// removes an inherited key from a lower-precedence layer during the merge.
25    /// On disk, `Some("v")` serializes as `"v"` and `None` as `null`.
26    pub params: BTreeMap<String, Option<String>>,
27}
28
29/// Fully resolved context stamped onto every event. Unlike [`Context`] its
30/// params are string-only — tombstones have already been applied and dropped.
31#[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// ---------------------------------------------------------------------------
39// Worktree-aware resolution
40// ---------------------------------------------------------------------------
41
42/// Whether the current directory is the primary checkout or a linked worktree.
43#[derive(Debug, Clone, PartialEq)]
44pub enum WorktreeScope {
45    /// We are in the primary (main) worktree. The global context IS the only context.
46    Primary,
47    /// We are in a linked worktree. `key` is the basename of git-dir
48    /// (e.g. "foo" for `.git/worktrees/foo`).
49    Linked { key: String },
50}
51
52/// Resolved paths for context storage, rooted in the primary worktree's `.visdom/`.
53#[derive(Debug, Clone)]
54pub struct ContextPaths {
55    /// `<primary_root>/.visdom/`
56    pub state_dir: PathBuf,
57    /// Primary or Linked.
58    pub scope: WorktreeScope,
59}
60
61impl ContextPaths {
62    /// Create the directory context is saved into, with the `.gitignore`
63    /// that keeps it out of commits: a checkout an earlier release set up
64    /// has no `.visdom/` yet, and its root `.gitignore` only names
65    /// `.tracevault/`.
66    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    /// Whether the checkout has been set up: its `.visdom/` exists, or the
72    /// `.tracevault/` of an earlier release does.
73    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    /// `<state_dir>/context.json` — the global (repo-wide) context file.
79    pub fn global_path(&self) -> PathBuf {
80        self.state_dir.join("context.json")
81    }
82
83    /// `<state_dir>/worktrees/<key>/context.json` when in a linked worktree;
84    /// `None` when in the primary worktree.
85    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
98/// Run `git rev-parse --git-common-dir --git-dir` from `start_dir`.
99///
100/// Returns `(git_common_dir, git_dir)` both canonicalized to absolute paths
101/// (git may return relative paths; we resolve them against `start_dir`).
102///
103/// Returns `None` if git fails (not a git repo, git not installed, etc.).
104fn 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    // git may return relative paths; canonicalize against start_dir.
126    let canonicalize = |raw: &str| -> Option<PathBuf> {
127        let p = PathBuf::from(raw);
128        if p.is_absolute() {
129            // Already absolute — canonicalize to resolve symlinks.
130            p.canonicalize().ok()
131        } else {
132            // Relative to start_dir.
133            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
143/// The directory `root`'s context files are written to. A file an earlier
144/// release left in `.tracevault/` is still read — each file on its own, see
145/// [`Context::load_from`] — until something is saved in its place.
146fn context_dir(root: &Path) -> PathBuf {
147    crate::layout::repo_dir(root)
148}
149
150/// Resolve worktree-aware context paths from `start_dir`.
151///
152/// Resolution order:
153/// 1. Run `git rev-parse --git-common-dir --git-dir` to locate the primary worktree.
154///    - `state_dir = parent(git_common_dir)/.visdom`
155///    - If `git_dir == git_common_dir` → Primary scope.
156///    - Else → Linked scope with `key = basename(git_dir)`.
157/// 2. Fallback (git not available or not a repo): delegate to
158///    [`crate::paths::resolve_project_root`] which walks up from `start_dir` to
159///    the nearest `.visdom/` (or returns `start_dir` as last resort).
160///    Treat as Primary scope in both cases.
161pub fn resolve_context_paths(start_dir: &Path) -> ContextPaths {
162    // --- Git-aware path ---
163    if let Some((git_common_dir, git_dir)) = git_rev_parse(start_dir) {
164        // primary_root = parent of git_common_dir (e.g. parent of `.git` = repo root)
165        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                // Linked worktree: key = basename of git_dir (e.g. "foo" from .git/worktrees/foo)
172                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    // --- Fallback: delegate to the shared resolver (ancestor-walk or start_dir) ---
184    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
191// ---------------------------------------------------------------------------
192// Context I/O
193// ---------------------------------------------------------------------------
194
195impl Context {
196    /// Load the context from an explicit file path.
197    ///
198    /// - Missing file → `Context::default()` (silent).
199    /// - Malformed JSON → `Context::default()` + a warning printed to stderr.
200    ///
201    /// Use `ContextPaths::global_path()` or `ContextPaths::worktree_path()` to
202    /// obtain the correct path for the current worktree context.
203    pub fn load_from(path: &Path) -> Context {
204        // A file an earlier release wrote under the `tracevault` names is
205        // read until one is saved under the new name.
206        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    /// Save the context to an explicit file path.
231    ///
232    /// Normalises labels first:
233    /// 1. Trim whitespace from each label.
234    /// 2. Drop blank labels.
235    /// 3. Deduplicate: first occurrence wins.
236    ///
237    /// Creates the parent directory (including `worktrees/<key>/`) if it does not exist.
238    ///
239    /// Use `save_global` or `save_worktree` for scope-aware saves.
240    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    // ---------------------------------------------------------------------------
258    // Scope-aware load/save
259    // ---------------------------------------------------------------------------
260
261    /// Load the global context from the given resolved paths.
262    pub fn load_global(paths: &ContextPaths) -> Context {
263        Self::load_from(&paths.global_path())
264    }
265
266    /// Load the per-worktree context (if in a linked worktree and the file exists).
267    ///
268    /// Returns `None` when:
269    /// - In a primary checkout (no per-worktree path).
270    /// - In a linked worktree but the per-worktree file does not yet exist.
271    ///
272    /// Returns `Some(ctx)` only when the file exists and was successfully (or partially) loaded.
273    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    /// Save to the global context path.
282    pub fn save_global(&self, paths: &ContextPaths) -> io::Result<()> {
283        paths.prepare_state_dir()?;
284        self.save_to(&paths.global_path())
285    }
286
287    /// Save to the per-worktree context path. Errors if called from a Primary scope.
288    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    // ---------------------------------------------------------------------------
297    // Effective merge
298    // ---------------------------------------------------------------------------
299
300    /// Fold layers low→high into the effective context.
301    /// - flow_id: highest layer that sets a non-null value wins.
302    /// - labels: union across layers, deduped, low→high stable order.
303    /// - params: JSON merge-patch per layer — `Some(v)` sets/overrides,
304    ///   `None` deletes an inherited key. Effective params are string-only.
305    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    /// Load user (if given) + global + per-worktree and return the merged
335    /// effective context that the hook stamps.
336    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    /// Like `effective`, returning each layer separately (for `show`).
342    /// Tuple: (paths, user, global, worktree, effective).
343    #[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
372// ---------------------------------------------------------------------------
373// Helpers
374// ---------------------------------------------------------------------------
375
376/// Trim whitespace, drop blanks, remove duplicates (first occurrence wins).
377fn 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// ---------------------------------------------------------------------------
388// Unit tests
389// ---------------------------------------------------------------------------
390
391#[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(), // duplicate — should be dropped
441                "  ".to_string(),    // whitespace-only — should be dropped
442                "gamma".to_string(),
443                "beta".to_string(), // duplicate — should be dropped
444            ],
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        // Ensure .visdom does NOT exist yet
473        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); // tombstone
488        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    // ---------------------------------------------------------------------------
515    // merge_layers (ordered fold) unit tests
516    // ---------------------------------------------------------------------------
517
518    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")]); // overrides owner
533        let wt = ctx(None, &["wt"], &[]);
534        let eff = Context::merge_layers(&[&user, &repo, &wt]);
535        assert_eq!(eff.flow_id, Some("r".to_string())); // highest non-null (wt is None)
536        assert_eq!(eff.labels, vec!["base", "repo", "wt"]); // union, low→high order
537        assert_eq!(eff.params["env"], "prod"); // only user set it
538        assert_eq!(eff.params["owner"], "team"); // repo overrides user
539    }
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); // tombstone
546        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        // The global file is already under the new name; the worktree's one
573        // is still where an earlier release wrote it.
574        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        // Saving goes to the new place and leaves the old file as it was.
597        worktree.save_worktree(&paths).unwrap();
598        assert!(root.join(".visdom/worktrees/feature/context.json").exists());
599        // And the new directory keeps itself out of commits.
600        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}