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