1use serde::{Deserialize, Serialize};
2use std::path::{Path, PathBuf};
3
4#[derive(Debug, Serialize, Deserialize)]
5pub struct TracevaultConfig {
6 #[serde(default = "default_agent")]
7 pub agent: String,
8 #[serde(default, skip_serializing_if = "Option::is_none")]
9 pub server_url: Option<String>,
10 #[serde(default, skip_serializing)]
16 pub api_key: Option<String>,
17 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub repo_id: Option<String>,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub user_context: Option<UserContext>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
25 pub remote_id: Option<String>,
26 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub codebase_name: Option<String>,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub default_project: Option<String>,
35}
36
37fn default_agent() -> String {
38 "claude-code".to_string()
39}
40
41impl Default for TracevaultConfig {
42 fn default() -> Self {
43 Self {
44 agent: "claude-code".to_string(),
45 server_url: None,
46 api_key: None,
47 repo_id: None,
48 user_context: None,
49 remote_id: None,
50 codebase_name: None,
51 default_project: None,
52 }
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
59#[serde(untagged)]
60pub enum UserContext {
61 Toggle(bool),
62 Path(String),
63 Full {
64 #[serde(default = "crate::config::enable_default")]
65 enable: bool,
66 #[serde(default)]
67 path: Option<String>,
68 },
69}
70
71impl Default for UserContext {
72 fn default() -> Self {
73 UserContext::Toggle(false)
74 }
75}
76
77pub(crate) fn enable_default() -> bool {
78 true
79}
80
81pub fn tv_config_root() -> PathBuf {
84 dirs::config_dir()
85 .unwrap_or_else(|| PathBuf::from("."))
86 .join("tracevault")
87}
88
89pub fn user_config_path_in(config_root: &Path) -> PathBuf {
90 config_root.join("config.toml")
91}
92pub fn user_config_path() -> PathBuf {
93 user_config_path_in(&tv_config_root())
94}
95pub fn default_user_context_path_in(config_root: &Path) -> PathBuf {
96 config_root.join("context.json")
97}
98
99#[allow(dead_code)]
104pub fn default_user_context_path() -> PathBuf {
105 default_user_context_path_in(&tv_config_root())
106}
107
108pub fn try_load_user_config_in(config_root: &Path) -> Result<Option<TracevaultConfig>, String> {
113 let path = user_config_path_in(config_root);
114 let content = match std::fs::read_to_string(&path) {
115 Ok(c) => c,
116 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
117 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
118 };
119 toml::from_str(&content)
120 .map(Some)
121 .map_err(|e| e.to_string())
122}
123
124pub fn load_user_config_in(config_root: &Path) -> TracevaultConfig {
126 match try_load_user_config_in(config_root) {
127 Ok(Some(cfg)) => cfg,
128 Ok(None) => TracevaultConfig::default(),
129 Err(e) => {
130 eprintln!("tracevault: warning: malformed user config.toml: {e}");
131 TracevaultConfig::default()
132 }
133 }
134}
135
136pub fn resolve_user_context_in(
141 repo_configured: Option<UserContext>,
142 config_root: &Path,
143) -> UserContext {
144 repo_configured.unwrap_or_else(|| {
145 load_user_config_in(config_root)
146 .user_context
147 .unwrap_or_default()
148 })
149}
150
151pub fn resolve_user_context(repo_configured: Option<UserContext>) -> UserContext {
153 resolve_user_context_in(repo_configured, &tv_config_root())
154}
155
156impl UserContext {
157 pub fn path(&self) -> PathBuf {
160 self.path_in(&tv_config_root())
161 }
162
163 pub fn path_in(&self, config_root: &Path) -> PathBuf {
170 match self {
171 UserContext::Path(p) => PathBuf::from(p),
172 UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
173 _ => default_user_context_path_in(config_root),
174 }
175 }
176
177 pub fn resolve(&self) -> Option<PathBuf> {
179 self.resolve_in(&tv_config_root())
180 }
181
182 pub fn resolve_in(&self, config_root: &Path) -> Option<PathBuf> {
188 let enabled = match self {
189 UserContext::Toggle(b) => *b,
190 UserContext::Path(_) => true,
191 UserContext::Full { enable, .. } => *enable,
192 };
193 enabled.then(|| self.path_in(config_root))
194 }
195
196 pub fn from_init_flags(
201 no_user_context: bool,
202 user_context: Option<String>,
203 ) -> Result<Option<UserContext>, String> {
204 match (no_user_context, user_context) {
205 (true, _) => Ok(Some(UserContext::Toggle(false))),
206 (false, Some(p)) if p.trim().is_empty() => {
207 Err("--user-context path must not be empty".to_string())
208 }
209 (false, Some(p)) => Ok(Some(UserContext::Path(p))),
210 (false, None) => Ok(None),
211 }
212 }
213}
214
215impl TracevaultConfig {
216 pub fn config_dir(project_root: &Path) -> PathBuf {
217 project_root.join(".tracevault")
218 }
219
220 pub fn config_path(project_root: &Path) -> PathBuf {
221 Self::config_dir(project_root).join("config.toml")
222 }
223
224 const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";
227
228 pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
235 let path = config_dir.join(".gitignore");
236 if path.exists() {
237 return Ok(());
238 }
239 std::fs::write(path, Self::GITIGNORE_CONTENTS)
240 }
241
242 pub fn to_toml(&self) -> String {
243 let body = toml::to_string(self).unwrap_or_default();
244 format!("# TraceVault configuration\n{body}")
245 }
246
247 const FIELDS: &'static [&'static str] = &[
250 "agent",
251 "server_url",
252 "api_key",
253 "repo_id",
254 "user_context",
255 "remote_id",
256 "codebase_name",
257 "default_project",
258 ];
259
260 pub fn save(&self, project_root: &Path) -> std::io::Result<()> {
269 let path = Self::config_path(project_root);
270 let mut table: toml::Table = std::fs::read_to_string(&path)
271 .ok()
272 .and_then(|content| content.parse().ok())
273 .unwrap_or_default();
274 let ours = toml::Table::try_from(self).map_err(std::io::Error::other)?;
275 let as_loaded = table
278 .clone()
279 .try_into::<Self>()
280 .ok()
281 .and_then(|cfg| toml::Table::try_from(&cfg).ok())
282 .unwrap_or_default();
283 table.retain(|key, _| {
285 key == "api_key" || !Self::FIELDS.contains(&key) || ours.contains_key(key)
286 });
287 for (key, value) in ours {
288 if !table.contains_key(&key) || as_loaded.get(&key) != Some(&value) {
291 table.insert(key, value);
292 }
293 }
294 match &self.api_key {
295 Some(key) => {
296 table.insert("api_key".into(), key.clone().into());
297 }
298 None => {
299 table.remove("api_key");
300 }
301 }
302 let body = toml::to_string(&table).map_err(std::io::Error::other)?;
303 std::fs::write(path, format!("# TraceVault configuration\n{body}"))
304 }
305
306 pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
315 let path = Self::config_path(project_root);
316 let content = match std::fs::read_to_string(&path) {
317 Ok(c) => c,
318 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
319 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
320 };
321 toml::from_str(&content)
322 .map(Some)
323 .map_err(|e| e.to_string())
324 }
325
326 pub fn load(project_root: &Path) -> Option<Self> {
331 match Self::try_load(project_root) {
332 Ok(cfg) => cfg,
333 Err(e) => {
334 eprintln!("tracevault: warning: malformed config.toml: {e}");
335 None
336 }
337 }
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344 use std::fs;
345
346 #[test]
347 fn to_toml_all_fields() {
348 let cfg = TracevaultConfig {
349 agent: "claude-code".into(),
350 server_url: Some("https://example.com".into()),
351 api_key: None, repo_id: Some("repo-1".into()),
353 user_context: None,
354 remote_id: None,
355 codebase_name: None,
356 default_project: None,
357 };
358 let toml = cfg.to_toml();
359 assert!(toml.contains("agent = \"claude-code\""));
360 assert!(toml.contains("server_url = \"https://example.com\""));
361 assert!(toml.contains("repo_id = \"repo-1\""));
362 assert!(
363 !toml.contains("user_context"),
364 "None user_context must be omitted"
365 );
366 }
367
368 #[test]
369 fn to_toml_minimal() {
370 let cfg = TracevaultConfig::default();
371 let toml = cfg.to_toml();
372 assert!(toml.contains("agent = \"claude-code\""));
373 assert!(!toml.contains("server_url"));
374 }
375
376 #[test]
377 fn load_valid_config() {
378 let dir = tempfile::tempdir().unwrap();
379 let tv_dir = dir.path().join(".tracevault");
380 fs::create_dir_all(&tv_dir).unwrap();
381 fs::write(
382 tv_dir.join("config.toml"),
383 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\n",
384 )
385 .unwrap();
386 let cfg = TracevaultConfig::load(dir.path()).unwrap();
387 assert_eq!(cfg.agent, "claude-code");
388 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
389 }
390
391 #[test]
392 fn load_old_config_with_org_slug_still_parses() {
393 let dir = tempfile::tempdir().unwrap();
397 let tv_dir = dir.path().join(".tracevault");
398 fs::create_dir_all(&tv_dir).unwrap();
399 fs::write(
400 tv_dir.join("config.toml"),
401 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"x\"\n",
402 )
403 .unwrap();
404 let cfg = TracevaultConfig::load(dir.path()).unwrap();
405 assert_eq!(cfg.agent, "claude-code");
406 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
407 }
408
409 #[test]
410 fn load_missing_file_returns_none() {
411 let dir = tempfile::tempdir().unwrap();
412 assert!(TracevaultConfig::load(dir.path()).is_none());
413 }
414
415 #[test]
416 fn try_load_distinguishes_missing_valid_and_malformed() {
417 let missing = tempfile::tempdir().unwrap();
419 assert!(matches!(
420 TracevaultConfig::try_load(missing.path()),
421 Ok(None)
422 ));
423
424 let valid = tempfile::tempdir().unwrap();
426 let tv_dir = valid.path().join(".tracevault");
427 fs::create_dir_all(&tv_dir).unwrap();
428 fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
429 assert!(matches!(
430 TracevaultConfig::try_load(valid.path()),
431 Ok(Some(_))
432 ));
433
434 let bad = tempfile::tempdir().unwrap();
436 let bad_dir = bad.path().join(".tracevault");
437 fs::create_dir_all(&bad_dir).unwrap();
438 fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
439 assert!(TracevaultConfig::try_load(bad.path()).is_err());
440
441 let io = tempfile::tempdir().unwrap();
444 fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
445 assert!(TracevaultConfig::try_load(io.path()).is_err());
446 }
447
448 #[test]
449 fn ensure_gitignore_creates_runtime_ignore_file() {
450 let dir = tempfile::tempdir().unwrap();
451 let config_dir = dir.path().join(".tracevault");
452 fs::create_dir_all(&config_dir).unwrap();
453
454 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
455
456 let gitignore = config_dir.join(".gitignore");
457 assert!(gitignore.exists(), ".gitignore must be created");
458 let content = fs::read_to_string(&gitignore).unwrap();
459 assert!(content.contains("sessions/"), "must ignore sessions/");
460 assert!(content.contains("cache/"), "must ignore cache/");
461 assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
462 }
463
464 #[test]
465 fn toml_round_trip_omits_api_key_and_none_fields() {
466 let cfg = TracevaultConfig {
467 agent: "claude-code".into(),
468 server_url: Some("https://example.com".into()),
469 api_key: Some("secret".into()),
470 repo_id: None,
471 user_context: None,
472 remote_id: None,
473 codebase_name: None,
474 default_project: None,
475 };
476 let toml = cfg.to_toml();
477 assert!(toml.contains("agent = \"claude-code\""));
478 assert!(toml.contains("server_url = \"https://example.com\""));
479 assert!(!toml.contains("api_key"), "api_key must never be written");
480 assert!(!toml.contains("repo_id"), "None fields must be omitted");
481
482 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
484 assert_eq!(parsed.agent, "claude-code");
485 assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
486 assert_eq!(parsed.api_key, None);
487 }
488
489 #[test]
490 fn user_context_forms_resolve_correctly() {
491 let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
493 assert!(none_cfg.user_context.is_none());
494
495 let f: TracevaultConfig =
497 toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
498 assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
499 assert!(f.user_context.unwrap().resolve().is_none());
500
501 let t: TracevaultConfig =
503 toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
504 assert_eq!(
505 t.user_context.unwrap().resolve(),
506 Some(default_user_context_path())
507 );
508
509 let p: TracevaultConfig =
511 toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
512 assert_eq!(
513 p.user_context.unwrap().resolve(),
514 Some(PathBuf::from("/tmp/ctx.json"))
515 );
516
517 let obj: TracevaultConfig = toml::from_str(
519 "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
520 )
521 .unwrap();
522 let obj_ctx = obj.user_context.unwrap();
523 assert!(obj_ctx.resolve().is_none());
524 assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
525 }
526
527 #[test]
528 fn explicit_disable_is_persisted_not_skipped() {
529 let cfg = TracevaultConfig {
530 user_context: Some(UserContext::Toggle(false)),
531 ..Default::default()
532 };
533 let toml = cfg.to_toml();
534 assert!(
535 toml.contains("user_context"),
536 "explicit off must serialize, got:\n{toml}"
537 );
538 let back: TracevaultConfig = toml::from_str(&toml).unwrap();
539 assert!(matches!(
540 back.user_context,
541 Some(UserContext::Toggle(false))
542 ));
543 }
544
545 #[test]
546 fn user_config_paths_are_under_config_root() {
547 let root = std::path::Path::new("/x/tracevault");
548 assert_eq!(
549 user_config_path_in(root),
550 std::path::Path::new("/x/tracevault/config.toml")
551 );
552 assert_eq!(
553 default_user_context_path_in(root),
554 std::path::Path::new("/x/tracevault/context.json")
555 );
556 }
557
558 #[test]
559 fn try_load_user_config_missing_is_ok_none() {
560 let dir = tempfile::tempdir().unwrap();
561 assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
562 }
563
564 #[test]
565 fn try_load_user_config_reads_user_context() {
566 let dir = tempfile::tempdir().unwrap();
567 std::fs::write(
568 user_config_path_in(dir.path()),
569 "agent=\"claude-code\"\nuser_context = true\n",
570 )
571 .unwrap();
572 let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
573 assert_eq!(
577 cfg.user_context.unwrap().resolve_in(dir.path()),
578 Some(default_user_context_path_in(dir.path()))
579 );
580 }
581
582 #[test]
583 fn try_load_user_config_malformed_is_err() {
584 let dir = tempfile::tempdir().unwrap();
585 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
586 assert!(try_load_user_config_in(dir.path()).is_err());
587 }
588
589 #[test]
590 fn load_user_config_lenient_defaults_on_missing() {
591 let dir = tempfile::tempdir().unwrap();
592 assert!(load_user_config_in(dir.path()).user_context.is_none());
593 }
594
595 #[test]
596 fn load_user_config_lenient_defaults_on_malformed() {
597 let dir = tempfile::tempdir().unwrap();
600 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
601 assert!(load_user_config_in(dir.path()).user_context.is_none());
602 }
603
604 #[test]
605 fn resolve_user_context_prefers_repo_over_global() {
606 let dir = tempfile::tempdir().unwrap();
607 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
608 let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
610 assert!(
611 uc.resolve().is_none(),
612 "explicit repo-off must hard-disable"
613 );
614 }
615
616 #[test]
617 fn resolve_user_context_falls_back_to_global_when_repo_unset() {
618 let dir = tempfile::tempdir().unwrap();
619 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
620 let uc = resolve_user_context_in(None, dir.path());
621 assert_eq!(
623 uc.resolve_in(dir.path()),
624 Some(default_user_context_path_in(dir.path()))
625 );
626 }
627
628 #[test]
629 fn resolve_user_context_off_when_neither_configured() {
630 let dir = tempfile::tempdir().unwrap();
631 assert!(resolve_user_context_in(None, dir.path())
632 .resolve()
633 .is_none());
634 }
635
636 #[test]
637 fn from_init_flags_maps_variants() {
638 assert!(matches!(
639 UserContext::from_init_flags(true, None),
640 Ok(Some(UserContext::Toggle(false)))
641 ));
642 assert!(matches!(
643 UserContext::from_init_flags(false, None),
644 Ok(None)
645 ));
646 assert!(matches!(
647 UserContext::from_init_flags(false, Some("/p".into())),
648 Ok(Some(UserContext::Path(_)))
649 ));
650 assert!(UserContext::from_init_flags(false, Some(" ".into())).is_err());
651 }
652
653 #[test]
654 fn ensure_gitignore_preserves_existing_file() {
655 let dir = tempfile::tempdir().unwrap();
656 let config_dir = dir.path().join(".tracevault");
657 fs::create_dir_all(&config_dir).unwrap();
658 let gitignore = config_dir.join(".gitignore");
659 fs::write(&gitignore, "custom-user-content\n").unwrap();
660
661 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
662
663 assert_eq!(
665 fs::read_to_string(&gitignore).unwrap(),
666 "custom-user-content\n"
667 );
668 }
669
670 #[test]
671 fn default_project_roundtrips_through_toml() {
672 let cfg = TracevaultConfig {
673 default_project: Some("payments-platform".into()),
674 ..Default::default()
675 };
676 let toml = cfg.to_toml();
677 assert!(toml.contains("default_project = \"payments-platform\""));
678 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
679 assert_eq!(parsed.default_project.as_deref(), Some("payments-platform"));
680 }
681
682 #[test]
683 fn default_project_absent_is_omitted_from_toml() {
684 let toml = TracevaultConfig::default().to_toml();
685 assert!(!toml.contains("default_project"));
686 }
687
688 #[test]
689 fn fields_lists_every_serialized_key() {
690 let cfg = TracevaultConfig {
691 agent: "claude-code".into(),
692 server_url: Some("https://example.com".into()),
693 api_key: Some("tvk_x".into()),
694 repo_id: Some("r".into()),
695 user_context: Some(UserContext::Toggle(true)),
696 remote_id: Some("rm".into()),
697 codebase_name: Some("cb".into()),
698 default_project: Some("p".into()),
699 };
700 let mut keys: Vec<String> = toml::Table::try_from(&cfg)
701 .unwrap()
702 .keys()
703 .cloned()
704 .collect();
705 keys.push("api_key".into()); keys.sort();
707 let mut fields: Vec<&str> = TracevaultConfig::FIELDS.to_vec();
708 fields.sort();
709 assert_eq!(keys, fields);
710 }
711
712 fn write_config(root: &Path, content: &str) {
713 fs::create_dir_all(root.join(".tracevault")).unwrap();
714 fs::write(root.join(".tracevault/config.toml"), content).unwrap();
715 }
716
717 #[test]
718 fn save_keeps_api_key_unknown_keys_and_key_order() {
719 let dir = tempfile::tempdir().unwrap();
720 write_config(
721 dir.path(),
722 "repo_id = \"r1\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n",
723 );
724
725 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
726 cfg.repo_id = Some("r2".into());
727 cfg.save(dir.path()).unwrap();
728
729 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
730 assert_eq!(
731 content,
732 "# TraceVault configuration\nrepo_id = \"r2\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n"
733 );
734 }
735
736 #[test]
737 fn save_removes_a_known_key_set_to_none() {
738 let dir = tempfile::tempdir().unwrap();
739 write_config(dir.path(), "codebase_name = \"old\"\nrepo_id = \"r1\"\n");
740
741 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
742 cfg.codebase_name = None;
743 cfg.save(dir.path()).unwrap();
744
745 let reloaded = TracevaultConfig::load(dir.path()).unwrap();
746 assert_eq!(reloaded.codebase_name, None);
747 assert_eq!(reloaded.repo_id.as_deref(), Some("r1"));
748 }
749
750 #[test]
751 fn save_puts_scalars_before_a_table_valued_user_context() {
752 let dir = tempfile::tempdir().unwrap();
753 write_config(
754 dir.path(),
755 "[user_context]\nenable = false\npath = \"/x.json\"\n",
756 );
757
758 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
759 cfg.api_key = Some("tvk_y".into());
760 cfg.repo_id = Some("r".into());
761 cfg.save(dir.path()).unwrap();
762
763 let reloaded = TracevaultConfig::load(dir.path()).unwrap();
764 assert_eq!(reloaded.api_key.as_deref(), Some("tvk_y"));
765 assert_eq!(reloaded.repo_id.as_deref(), Some("r"));
766 assert!(matches!(
767 reloaded.user_context,
768 Some(UserContext::Full { enable: false, path: Some(ref p) }) if p == "/x.json"
769 ));
770 }
771
772 #[test]
773 fn save_keeps_an_unchanged_user_context_table_verbatim() {
774 let dir = tempfile::tempdir().unwrap();
775 let original = "repo_id = \"r1\"\nagent = \"claude-code\"\n\n[user_context]\npath = \"/x.json\"\nfuture_setting = 1\nenable = true\n";
776 write_config(dir.path(), original);
777
778 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
779 cfg.repo_id = Some("r2".into());
780 cfg.save(dir.path()).unwrap();
781
782 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
783 assert_eq!(
784 content,
785 format!(
786 "# TraceVault configuration\n{}",
787 original.replace("r1", "r2")
788 )
789 );
790 }
791
792 #[test]
793 fn save_replaces_a_changed_user_context() {
794 let dir = tempfile::tempdir().unwrap();
795 write_config(
796 dir.path(),
797 "[user_context]\npath = \"/x.json\"\nfuture_setting = 1\n",
798 );
799
800 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
801 cfg.user_context = Some(UserContext::Toggle(false));
802 cfg.save(dir.path()).unwrap();
803
804 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
805 assert_eq!(
806 content,
807 "# TraceVault configuration\nuser_context = false\nagent = \"claude-code\"\n"
808 );
809 }
810
811 #[test]
812 fn save_writes_the_default_agent_into_a_file_without_one() {
813 let dir = tempfile::tempdir().unwrap();
814 write_config(dir.path(), "repo_id = \"r1\"\n");
815
816 TracevaultConfig::load(dir.path())
817 .unwrap()
818 .save(dir.path())
819 .unwrap();
820
821 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
822 assert!(content.contains("agent = \"claude-code\""), "{content}");
823 }
824
825 #[test]
826 fn save_creates_a_missing_config() {
827 let dir = tempfile::tempdir().unwrap();
828 fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
829 TracevaultConfig::default().save(dir.path()).unwrap();
830 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
831 assert_eq!(content, TracevaultConfig::default().to_toml());
832 }
833}