Skip to main content

tracevault_cli/
context.rs

1use serde::{Deserialize, Serialize};
2use std::collections::BTreeMap;
3use std::io;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7// ---------------------------------------------------------------------------
8// Context struct
9// ---------------------------------------------------------------------------
10
11/// Active context written by `tracevault context set` and read by the CC hook.
12///
13/// Stored as pretty-printed JSON at `.tracevault/context.json`.
14/// BTreeMap is used for `params` so keys are always in sorted order on disk,
15/// giving stable, human-readable diffs.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
17pub struct Context {
18    pub flow_id: Option<String>,
19    /// Deduplicated, non-empty labels. Duplicates are removed on save (first
20    /// occurrence wins); blank/whitespace-only entries are dropped.
21    pub labels: Vec<String>,
22    /// Stored params. `Some(v)` sets a value; `None` is a delete tombstone that
23    /// removes an inherited key from a lower-precedence layer during the merge.
24    /// On disk, `Some("v")` serializes as `"v"` and `None` as `null`.
25    pub params: BTreeMap<String, Option<String>>,
26}
27
28/// Fully resolved context stamped onto every event. Unlike [`Context`] its
29/// params are string-only — tombstones have already been applied and dropped.
30#[derive(Debug, Clone, PartialEq, Serialize, Default)]
31pub struct EffectiveContext {
32    pub flow_id: Option<String>,
33    pub labels: Vec<String>,
34    pub params: BTreeMap<String, String>,
35}
36
37// ---------------------------------------------------------------------------
38// Worktree-aware resolution
39// ---------------------------------------------------------------------------
40
41/// Whether the current directory is the primary checkout or a linked worktree.
42#[derive(Debug, Clone, PartialEq)]
43pub enum WorktreeScope {
44    /// We are in the primary (main) worktree. The global context IS the only context.
45    Primary,
46    /// We are in a linked worktree. `key` is the basename of git-dir
47    /// (e.g. "foo" for `.git/worktrees/foo`).
48    Linked { key: String },
49}
50
51/// Resolved paths for context storage, rooted in the primary worktree's `.tracevault/`.
52#[derive(Debug, Clone)]
53pub struct ContextPaths {
54    /// `<primary_root>/.tracevault/`
55    pub tracevault_dir: PathBuf,
56    /// Primary or Linked.
57    pub scope: WorktreeScope,
58}
59
60impl ContextPaths {
61    /// `<tracevault_dir>/context.json` — the global (repo-wide) context file.
62    pub fn global_path(&self) -> PathBuf {
63        self.tracevault_dir.join("context.json")
64    }
65
66    /// `<tracevault_dir>/worktrees/<key>/context.json` when in a linked worktree;
67    /// `None` when in the primary worktree.
68    pub fn worktree_path(&self) -> Option<PathBuf> {
69        match &self.scope {
70            WorktreeScope::Primary => None,
71            WorktreeScope::Linked { key } => Some(
72                self.tracevault_dir
73                    .join("worktrees")
74                    .join(key)
75                    .join("context.json"),
76            ),
77        }
78    }
79}
80
81/// Run `git rev-parse --git-common-dir --git-dir` from `start_dir`.
82///
83/// Returns `(git_common_dir, git_dir)` both canonicalized to absolute paths
84/// (git may return relative paths; we resolve them against `start_dir`).
85///
86/// Returns `None` if git fails (not a git repo, git not installed, etc.).
87fn git_rev_parse(start_dir: &Path) -> Option<(PathBuf, PathBuf)> {
88    let output = Command::new("git")
89        .args([
90            "-C",
91            &start_dir.to_string_lossy(),
92            "rev-parse",
93            "--git-common-dir",
94            "--git-dir",
95        ])
96        .output()
97        .ok()?;
98
99    if !output.status.success() {
100        return None;
101    }
102
103    let stdout = std::str::from_utf8(&output.stdout).ok()?;
104    let mut lines = stdout.lines();
105    let raw_common = lines.next()?.trim();
106    let raw_dir = lines.next()?.trim();
107
108    // git may return relative paths; canonicalize against start_dir.
109    let canonicalize = |raw: &str| -> Option<PathBuf> {
110        let p = PathBuf::from(raw);
111        if p.is_absolute() {
112            // Already absolute — canonicalize to resolve symlinks.
113            p.canonicalize().ok()
114        } else {
115            // Relative to start_dir.
116            start_dir.join(&p).canonicalize().ok()
117        }
118    };
119
120    let git_common_dir = canonicalize(raw_common)?;
121    let git_dir = canonicalize(raw_dir)?;
122
123    Some((git_common_dir, git_dir))
124}
125
126/// Resolve worktree-aware context paths from `start_dir`.
127///
128/// Resolution order:
129/// 1. Run `git rev-parse --git-common-dir --git-dir` to locate the primary worktree.
130///    - `tracevault_dir = parent(git_common_dir)/.tracevault`
131///    - If `git_dir == git_common_dir` → Primary scope.
132///    - Else → Linked scope with `key = basename(git_dir)`.
133/// 2. Fallback (git not available or not a repo): delegate to
134///    [`crate::paths::resolve_project_root`] which walks up from `start_dir` to
135///    the nearest `.tracevault/` (or returns `start_dir` as last resort).
136///    Treat as Primary scope in both cases.
137pub fn resolve_context_paths(start_dir: &Path) -> ContextPaths {
138    // --- Git-aware path ---
139    if let Some((git_common_dir, git_dir)) = git_rev_parse(start_dir) {
140        // primary_root = parent of git_common_dir (e.g. parent of `.git` = repo root)
141        if let Some(primary_root) = git_common_dir.parent() {
142            let tracevault_dir = primary_root.join(".tracevault");
143
144            let scope = if git_dir == git_common_dir {
145                WorktreeScope::Primary
146            } else {
147                // Linked worktree: key = basename of git_dir (e.g. "foo" from .git/worktrees/foo)
148                let key = git_dir
149                    .file_name()
150                    .map(|n| n.to_string_lossy().into_owned())
151                    .unwrap_or_else(|| "default".to_string());
152                WorktreeScope::Linked { key }
153            };
154
155            return ContextPaths {
156                tracevault_dir,
157                scope,
158            };
159        }
160    }
161
162    // --- Fallback: delegate to the shared resolver (ancestor-walk or start_dir) ---
163    let fallback = crate::paths::resolve_project_root(start_dir);
164    ContextPaths {
165        tracevault_dir: fallback.root.join(".tracevault"),
166        scope: WorktreeScope::Primary,
167    }
168}
169
170// ---------------------------------------------------------------------------
171// Context I/O
172// ---------------------------------------------------------------------------
173
174impl Context {
175    /// Load the context from an explicit file path.
176    ///
177    /// - Missing file → `Context::default()` (silent).
178    /// - Malformed JSON → `Context::default()` + a warning printed to stderr.
179    ///
180    /// Use `ContextPaths::global_path()` or `ContextPaths::worktree_path()` to
181    /// obtain the correct path for the current worktree context.
182    pub fn load_from(path: &Path) -> Context {
183        let content = match std::fs::read_to_string(path) {
184            Ok(c) => c,
185            Err(e) if e.kind() == io::ErrorKind::NotFound => return Context::default(),
186            Err(e) => {
187                eprintln!(
188                    "tracevault: warning: could not read context file {}: {e}",
189                    path.display()
190                );
191                return Context::default();
192            }
193        };
194        match serde_json::from_str::<Context>(&content) {
195            Ok(ctx) => ctx,
196            Err(e) => {
197                eprintln!(
198                    "tracevault: warning: malformed context file {} (using empty context): {e}",
199                    path.display()
200                );
201                Context::default()
202            }
203        }
204    }
205
206    /// Save the context to an explicit file path.
207    ///
208    /// Normalises labels first:
209    /// 1. Trim whitespace from each label.
210    /// 2. Drop blank labels.
211    /// 3. Deduplicate: first occurrence wins.
212    ///
213    /// Creates the parent directory (including `worktrees/<key>/`) if it does not exist.
214    ///
215    /// Use `save_global` or `save_worktree` for scope-aware saves.
216    pub fn save_to(&self, path: &Path) -> io::Result<()> {
217        if let Some(parent) = path.parent() {
218            std::fs::create_dir_all(parent)?;
219        }
220
221        let normalised = Self {
222            flow_id: self.flow_id.clone(),
223            labels: dedup_labels(&self.labels),
224            params: self.params.clone(),
225        };
226
227        let json = serde_json::to_string_pretty(&normalised)
228            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
229
230        std::fs::write(path, json)
231    }
232
233    // ---------------------------------------------------------------------------
234    // Scope-aware load/save
235    // ---------------------------------------------------------------------------
236
237    /// Load the global context from the given resolved paths.
238    pub fn load_global(paths: &ContextPaths) -> Context {
239        Self::load_from(&paths.global_path())
240    }
241
242    /// Load the per-worktree context (if in a linked worktree and the file exists).
243    ///
244    /// Returns `None` when:
245    /// - In a primary checkout (no per-worktree path).
246    /// - In a linked worktree but the per-worktree file does not yet exist.
247    ///
248    /// Returns `Some(ctx)` only when the file exists and was successfully (or partially) loaded.
249    pub fn load_worktree(paths: &ContextPaths) -> Option<Context> {
250        let wt_path = paths.worktree_path()?;
251        if !wt_path.exists() {
252            return None;
253        }
254        Some(Self::load_from(&wt_path))
255    }
256
257    /// Save to the global context path.
258    pub fn save_global(&self, paths: &ContextPaths) -> io::Result<()> {
259        self.save_to(&paths.global_path())
260    }
261
262    /// Save to the per-worktree context path. Errors if called from a Primary scope.
263    pub fn save_worktree(&self, paths: &ContextPaths) -> io::Result<()> {
264        let wt_path = paths.worktree_path().ok_or_else(|| {
265            io::Error::other("cannot save per-worktree context from primary checkout")
266        })?;
267        self.save_to(&wt_path)
268    }
269
270    // ---------------------------------------------------------------------------
271    // Effective merge
272    // ---------------------------------------------------------------------------
273
274    /// Fold layers low→high into the effective context.
275    /// - flow_id: highest layer that sets a non-null value wins.
276    /// - labels: union across layers, deduped, low→high stable order.
277    /// - params: JSON merge-patch per layer — `Some(v)` sets/overrides,
278    ///   `None` deletes an inherited key. Effective params are string-only.
279    pub fn merge_layers(layers: &[&Context]) -> EffectiveContext {
280        let mut flow_id: Option<String> = None;
281        let mut all_labels: Vec<String> = Vec::new();
282        let mut params: BTreeMap<String, String> = BTreeMap::new();
283
284        for layer in layers {
285            if layer.flow_id.is_some() {
286                flow_id = layer.flow_id.clone();
287            }
288            all_labels.extend(layer.labels.iter().cloned());
289            for (k, v) in &layer.params {
290                match v {
291                    Some(val) => {
292                        params.insert(k.clone(), val.clone());
293                    }
294                    None => {
295                        params.remove(k);
296                    }
297                }
298            }
299        }
300
301        EffectiveContext {
302            flow_id,
303            labels: dedup_labels(&all_labels),
304            params,
305        }
306    }
307
308    /// Load user (if given) + global + per-worktree and return the merged
309    /// effective context that the hook stamps.
310    pub fn effective(start_dir: &Path, user_layer: Option<&Path>) -> EffectiveContext {
311        let (_, _, _, _, eff) = Self::effective_with_parts(start_dir, user_layer);
312        eff
313    }
314
315    /// Like `effective`, returning each layer separately (for `show`).
316    /// Tuple: (paths, user, global, worktree, effective).
317    #[allow(clippy::type_complexity)]
318    pub fn effective_with_parts(
319        start_dir: &Path,
320        user_layer: Option<&Path>,
321    ) -> (
322        ContextPaths,
323        Option<Context>,
324        Context,
325        Option<Context>,
326        EffectiveContext,
327    ) {
328        let paths = resolve_context_paths(start_dir);
329        let user = user_layer.map(Self::load_from);
330        let global = Self::load_global(&paths);
331        let worktree = Self::load_worktree(&paths);
332
333        let mut layers: Vec<&Context> = Vec::new();
334        if let Some(u) = &user {
335            layers.push(u);
336        }
337        layers.push(&global);
338        if let Some(w) = &worktree {
339            layers.push(w);
340        }
341        let effective = Self::merge_layers(&layers);
342        (paths, user, global, worktree, effective)
343    }
344}
345
346// ---------------------------------------------------------------------------
347// Helpers
348// ---------------------------------------------------------------------------
349
350/// Trim whitespace, drop blanks, remove duplicates (first occurrence wins).
351fn dedup_labels(labels: &[String]) -> Vec<String> {
352    let mut seen = std::collections::HashSet::new();
353    labels
354        .iter()
355        .map(|l| l.trim().to_string())
356        .filter(|l| !l.is_empty())
357        .filter(|l| seen.insert(l.clone()))
358        .collect()
359}
360
361// ---------------------------------------------------------------------------
362// Unit tests
363// ---------------------------------------------------------------------------
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use std::collections::BTreeMap;
369
370    #[test]
371    fn default_context_is_empty() {
372        let ctx = Context::default();
373        assert!(ctx.flow_id.is_none());
374        assert!(ctx.labels.is_empty());
375        assert!(ctx.params.is_empty());
376    }
377
378    #[test]
379    fn save_and_load_round_trip() {
380        let dir = tempfile::tempdir().unwrap();
381        let ctx_path = dir.path().join(".tracevault").join("context.json");
382        let mut params = BTreeMap::new();
383        params.insert("key1".to_string(), Some("value1".to_string()));
384        params.insert("key2".to_string(), Some("value2".to_string()));
385
386        let ctx = Context {
387            flow_id: Some("flow-abc-123".to_string()),
388            labels: vec!["backend".to_string(), "urgent".to_string()],
389            params,
390        };
391
392        ctx.save_to(&ctx_path).unwrap();
393        let loaded = Context::load_from(&ctx_path);
394        assert_eq!(ctx, loaded);
395    }
396
397    #[test]
398    fn load_missing_file_returns_default() {
399        let dir = tempfile::tempdir().unwrap();
400        let missing = dir.path().join(".tracevault").join("context.json");
401        let ctx = Context::load_from(&missing);
402        assert_eq!(ctx, Context::default());
403    }
404
405    #[test]
406    fn label_dedup_on_save() {
407        let dir = tempfile::tempdir().unwrap();
408        let ctx_path = dir.path().join(".tracevault").join("context.json");
409        let ctx = Context {
410            flow_id: None,
411            labels: vec![
412                "alpha".to_string(),
413                "beta".to_string(),
414                "alpha".to_string(), // duplicate — should be dropped
415                "  ".to_string(),    // whitespace-only — should be dropped
416                "gamma".to_string(),
417                "beta".to_string(), // duplicate — should be dropped
418            ],
419            params: BTreeMap::new(),
420        };
421
422        ctx.save_to(&ctx_path).unwrap();
423        let loaded = Context::load_from(&ctx_path);
424        assert_eq!(
425            loaded.labels,
426            vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]
427        );
428    }
429
430    #[test]
431    fn load_malformed_json_returns_default() {
432        let dir = tempfile::tempdir().unwrap();
433        let tv_dir = dir.path().join(".tracevault");
434        std::fs::create_dir_all(&tv_dir).unwrap();
435        let ctx_path = tv_dir.join("context.json");
436        std::fs::write(&ctx_path, b"not valid json {{{{").unwrap();
437
438        let ctx = Context::load_from(&ctx_path);
439        assert_eq!(ctx, Context::default());
440    }
441
442    #[test]
443    fn save_creates_tracevault_dir_if_missing() {
444        let dir = tempfile::tempdir().unwrap();
445        let ctx_path = dir.path().join(".tracevault").join("context.json");
446        // Ensure .tracevault does NOT exist yet
447        assert!(!dir.path().join(".tracevault").exists());
448
449        let ctx = Context::default();
450        ctx.save_to(&ctx_path).unwrap();
451
452        assert!(ctx_path.exists());
453    }
454
455    #[test]
456    fn params_tombstone_round_trips_as_null() {
457        let dir = tempfile::tempdir().unwrap();
458        let path = dir.path().join(".tracevault").join("context.json");
459        let mut params = BTreeMap::new();
460        params.insert("keep".to_string(), Some("v".to_string()));
461        params.insert("drop".to_string(), None); // tombstone
462        let ctx = Context {
463            flow_id: None,
464            labels: vec![],
465            params,
466        };
467        ctx.save_to(&path).unwrap();
468
469        let raw = std::fs::read_to_string(&path).unwrap();
470        assert!(
471            raw.contains("\"drop\": null"),
472            "tombstone must serialize as null"
473        );
474        assert!(raw.contains("\"keep\": \"v\""));
475        assert_eq!(Context::load_from(&path), ctx);
476    }
477
478    #[test]
479    fn legacy_string_params_load_as_some() {
480        let dir = tempfile::tempdir().unwrap();
481        let path = dir.path().join(".tracevault").join("context.json");
482        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
483        std::fs::write(&path, r#"{"flow_id":null,"labels":[],"params":{"k":"v"}}"#).unwrap();
484        let ctx = Context::load_from(&path);
485        assert_eq!(ctx.params.get("k"), Some(&Some("v".to_string())));
486    }
487
488    // ---------------------------------------------------------------------------
489    // merge_layers (ordered fold) unit tests
490    // ---------------------------------------------------------------------------
491
492    fn ctx(flow: Option<&str>, labels: &[&str], params: &[(&str, &str)]) -> Context {
493        Context {
494            flow_id: flow.map(str::to_string),
495            labels: labels.iter().map(|s| s.to_string()).collect(),
496            params: params
497                .iter()
498                .map(|(k, v)| (k.to_string(), Some(v.to_string())))
499                .collect(),
500        }
501    }
502
503    #[test]
504    fn fold_precedence_and_labels_union() {
505        let user = ctx(Some("u"), &["base"], &[("env", "prod"), ("owner", "u")]);
506        let repo = ctx(Some("r"), &["repo"], &[("owner", "team")]); // overrides owner
507        let wt = ctx(None, &["wt"], &[]);
508        let eff = Context::merge_layers(&[&user, &repo, &wt]);
509        assert_eq!(eff.flow_id, Some("r".to_string())); // highest non-null (wt is None)
510        assert_eq!(eff.labels, vec!["base", "repo", "wt"]); // union, low→high order
511        assert_eq!(eff.params["env"], "prod"); // only user set it
512        assert_eq!(eff.params["owner"], "team"); // repo overrides user
513    }
514
515    #[test]
516    fn fold_tombstone_removes_lower_layer_param() {
517        let user = ctx(Some("u"), &[], &[("secret", "x")]);
518        let mut repo = ctx(None, &[], &[]);
519        repo.params.insert("secret".to_string(), None); // tombstone
520        let eff = Context::merge_layers(&[&user, &repo]);
521        assert!(
522            !eff.params.contains_key("secret"),
523            "tombstone drops inherited key"
524        );
525    }
526
527    #[test]
528    fn fold_single_layer_matches_input() {
529        let only = ctx(Some("g"), &["a"], &[("k", "1")]);
530        let eff = Context::merge_layers(&[&only]);
531        assert_eq!(eff.flow_id, Some("g".to_string()));
532        assert_eq!(eff.labels, vec!["a"]);
533        assert_eq!(eff.params["k"], "1");
534    }
535}