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, Option<String>>,
26}
27
28#[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#[derive(Debug, Clone, PartialEq)]
43pub enum WorktreeScope {
44 Primary,
46 Linked { key: String },
49}
50
51#[derive(Debug, Clone)]
53pub struct ContextPaths {
54 pub tracevault_dir: PathBuf,
56 pub scope: WorktreeScope,
58}
59
60impl ContextPaths {
61 pub fn global_path(&self) -> PathBuf {
63 self.tracevault_dir.join("context.json")
64 }
65
66 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
81fn 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 let canonicalize = |raw: &str| -> Option<PathBuf> {
110 let p = PathBuf::from(raw);
111 if p.is_absolute() {
112 p.canonicalize().ok()
114 } else {
115 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
126pub fn resolve_context_paths(start_dir: &Path) -> ContextPaths {
138 if let Some((git_common_dir, git_dir)) = git_rev_parse(start_dir) {
140 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 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 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
170impl Context {
175 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 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 pub fn load_global(paths: &ContextPaths) -> Context {
239 Self::load_from(&paths.global_path())
240 }
241
242 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 pub fn save_global(&self, paths: &ContextPaths) -> io::Result<()> {
259 self.save_to(&paths.global_path())
260 }
261
262 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 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 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 #[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
346fn 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#[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(), " ".to_string(), "gamma".to_string(),
417 "beta".to_string(), ],
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 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); 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 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")]); let wt = ctx(None, &["wt"], &[]);
508 let eff = Context::merge_layers(&[&user, &repo, &wt]);
509 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"); }
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); 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}