1use serde::{Deserialize, Serialize};
2use std::collections::BTreeMap;
3use std::io;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
17pub struct Context {
18 pub flow_id: Option<String>,
19 pub labels: Vec<String>,
22 pub params: BTreeMap<String, String>,
23}
24
25#[derive(Debug, Clone, PartialEq)]
31pub enum WorktreeScope {
32 Primary,
34 Linked { key: String },
37}
38
39#[derive(Debug, Clone)]
41pub struct ContextPaths {
42 pub tracevault_dir: PathBuf,
44 pub scope: WorktreeScope,
46}
47
48impl ContextPaths {
49 pub fn global_path(&self) -> PathBuf {
51 self.tracevault_dir.join("context.json")
52 }
53
54 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
69fn 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 let canonicalize = |raw: &str| -> Option<PathBuf> {
98 let p = PathBuf::from(raw);
99 if p.is_absolute() {
100 p.canonicalize().ok()
102 } else {
103 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
114pub fn resolve_context_paths(start_dir: &Path) -> ContextPaths {
126 if let Some((git_common_dir, git_dir)) = git_rev_parse(start_dir) {
128 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 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 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
158impl Context {
163 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 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 pub fn load_global(paths: &ContextPaths) -> Context {
227 Self::load_from(&paths.global_path())
228 }
229
230 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 pub fn save_global(&self, paths: &ContextPaths) -> io::Result<()> {
247 self.save_to(&paths.global_path())
248 }
249
250 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 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 let flow_id = wt.flow_id.clone().or_else(|| global.flow_id.clone());
275
276 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 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 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 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
321fn 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#[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(), " ".to_string(), "gamma".to_string(),
392 "beta".to_string(), ],
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 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 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 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}