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