1use crate::program::TOP;
2use serde::{Deserialize, Serialize};
3use std::path::{Path, PathBuf};
4
5#[derive(Debug, Serialize, Deserialize)]
6pub struct TracevaultConfig {
7 #[serde(default = "default_agent")]
8 pub agent: String,
9 #[serde(default, skip_serializing_if = "Option::is_none")]
10 pub server_url: Option<String>,
11 #[serde(default, skip_serializing)]
17 pub api_key: Option<String>,
18 #[serde(default, skip_serializing_if = "Option::is_none")]
19 pub repo_id: Option<String>,
20 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub user_context: Option<UserContext>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub remote_id: Option<String>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub codebase_name: Option<String>,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub default_project: Option<String>,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub project_id: Option<String>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub project_name: Option<String>,
52}
53
54fn default_agent() -> String {
55 "claude-code".to_string()
56}
57
58impl Default for TracevaultConfig {
59 fn default() -> Self {
60 Self {
61 agent: "claude-code".to_string(),
62 server_url: None,
63 api_key: None,
64 repo_id: None,
65 user_context: None,
66 remote_id: None,
67 codebase_name: None,
68 default_project: None,
69 project_id: None,
70 project_name: None,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(untagged)]
79pub enum UserContext {
80 Toggle(bool),
81 Path(String),
82 Full {
83 #[serde(default = "crate::config::enable_default")]
84 enable: bool,
85 #[serde(default)]
86 path: Option<String>,
87 },
88}
89
90impl Default for UserContext {
91 fn default() -> Self {
92 UserContext::Toggle(false)
93 }
94}
95
96pub(crate) fn enable_default() -> bool {
97 true
98}
99
100pub fn tv_config_root() -> PathBuf {
105 crate::layout::user_dir_in(&dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")))
106}
107
108pub fn user_config_path_in(config_root: &Path) -> PathBuf {
111 config_root.join(crate::layout::TRACING_CONFIG)
112}
113
114pub fn existing_user_config_path_in(config_root: &Path) -> PathBuf {
117 crate::layout::existing_user_tracing_config(config_root)
118}
119pub fn user_config_path() -> PathBuf {
120 user_config_path_in(&tv_config_root())
121}
122pub fn default_user_context_path_in(config_root: &Path) -> PathBuf {
126 config_root.join("context.json")
127}
128
129#[allow(dead_code)]
134pub fn default_user_context_path() -> PathBuf {
135 default_user_context_path_in(&tv_config_root())
136}
137
138pub fn try_load_user_config_in(config_root: &Path) -> Result<Option<TracevaultConfig>, String> {
143 let path = existing_user_config_path_in(config_root);
144 let content = match std::fs::read_to_string(&path) {
145 Ok(c) => c,
146 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
147 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
148 };
149 toml::from_str(&content)
150 .map(Some)
151 .map_err(|e| e.to_string())
152}
153
154pub fn load_user_config_in(config_root: &Path) -> TracevaultConfig {
156 match try_load_user_config_in(config_root) {
157 Ok(Some(cfg)) => cfg,
158 Ok(None) => TracevaultConfig::default(),
159 Err(e) => {
160 eprintln!("{TOP}: warning: malformed user tracing config: {e}");
161 TracevaultConfig::default()
162 }
163 }
164}
165
166pub fn resolve_user_context_in(
171 repo_configured: Option<UserContext>,
172 config_root: &Path,
173) -> UserContext {
174 repo_configured.unwrap_or_else(|| {
175 load_user_config_in(config_root)
176 .user_context
177 .unwrap_or_default()
178 })
179}
180
181pub fn resolve_user_context(repo_configured: Option<UserContext>) -> UserContext {
183 resolve_user_context_in(repo_configured, &tv_config_root())
184}
185
186impl UserContext {
187 pub fn path(&self) -> PathBuf {
190 self.path_in(&tv_config_root())
191 }
192
193 pub fn path_in(&self, config_root: &Path) -> PathBuf {
200 match self {
201 UserContext::Path(p) => PathBuf::from(p),
202 UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
203 _ => default_user_context_path_in(config_root),
204 }
205 }
206
207 pub fn resolve(&self) -> Option<PathBuf> {
209 self.resolve_in(&tv_config_root())
210 }
211
212 pub fn resolve_in(&self, config_root: &Path) -> Option<PathBuf> {
218 let enabled = match self {
219 UserContext::Toggle(b) => *b,
220 UserContext::Path(_) => true,
221 UserContext::Full { enable, .. } => *enable,
222 };
223 enabled.then(|| self.path_in(config_root))
224 }
225
226 pub fn from_init_flags(
231 no_user_context: bool,
232 user_context: Option<String>,
233 ) -> Result<Option<UserContext>, String> {
234 match (no_user_context, user_context) {
235 (true, _) => Ok(Some(UserContext::Toggle(false))),
236 (false, Some(p)) if p.trim().is_empty() => {
237 Err("--user-context path must not be empty".to_string())
238 }
239 (false, Some(p)) => Ok(Some(UserContext::Path(p))),
240 (false, None) => Ok(None),
241 }
242 }
243}
244
245impl TracevaultConfig {
246 pub fn config_dir(project_root: &Path) -> PathBuf {
248 crate::layout::repo_dir(project_root)
249 }
250
251 pub fn config_path(project_root: &Path) -> PathBuf {
253 crate::layout::tracing_config(project_root)
254 }
255
256 pub fn existing_config_path(project_root: &Path) -> PathBuf {
259 crate::layout::existing_tracing_config(project_root)
260 }
261
262 const GITIGNORE_CONTENTS: &'static str = "*\n!.gitignore\n!config.toml\n";
266
267 pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
274 let path = config_dir.join(".gitignore");
275 if path.exists() {
276 return Ok(());
277 }
278 std::fs::write(path, Self::GITIGNORE_CONTENTS)
279 }
280
281 pub fn to_toml(&self) -> String {
282 let body = toml::to_string(self).unwrap_or_default();
283 format!("{}{body}", Self::HEADER)
284 }
285
286 const HEADER: &'static str = "# Visdom tracing configuration (this checkout's own)\n";
287
288 const FIELDS: &'static [&'static str] = &[
291 "agent",
292 "server_url",
293 "api_key",
294 "repo_id",
295 "user_context",
296 "remote_id",
297 "codebase_name",
298 "default_project",
299 "project_id",
300 "project_name",
301 ];
302
303 pub fn save(&self, project_root: &Path) -> std::io::Result<()> {
312 let path = Self::config_path(project_root);
313 let mut table: toml::Table =
314 std::fs::read_to_string(Self::existing_config_path(project_root))
315 .ok()
316 .and_then(|content| content.parse().ok())
317 .unwrap_or_default();
318 let ours = toml::Table::try_from(self).map_err(std::io::Error::other)?;
319 let as_loaded = table
322 .clone()
323 .try_into::<Self>()
324 .ok()
325 .and_then(|cfg| toml::Table::try_from(&cfg).ok())
326 .unwrap_or_default();
327 table.retain(|key, _| {
329 key == "api_key" || !Self::FIELDS.contains(&key) || ours.contains_key(key)
330 });
331 for (key, value) in ours {
332 if !table.contains_key(&key) || as_loaded.get(&key) != Some(&value) {
335 table.insert(key, value);
336 }
337 }
338 match &self.api_key {
339 Some(key) => {
340 table.insert("api_key".into(), key.clone().into());
341 }
342 None => {
343 table.remove("api_key");
344 }
345 }
346 let body = toml::to_string(&table).map_err(std::io::Error::other)?;
347 let dir = Self::config_dir(project_root);
348 std::fs::create_dir_all(&dir)?;
349 Self::ensure_gitignore(&dir)?;
350 std::fs::write(path, format!("{}{body}", Self::HEADER))
351 }
352
353 pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
362 let path = Self::existing_config_path(project_root);
363 let content = match std::fs::read_to_string(&path) {
364 Ok(c) => c,
365 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
366 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
367 };
368 toml::from_str(&content)
369 .map(Some)
370 .map_err(|e| e.to_string())
371 }
372
373 pub fn load(project_root: &Path) -> Option<Self> {
378 match Self::try_load(project_root) {
379 Ok(cfg) => cfg,
380 Err(e) => {
381 eprintln!("{TOP}: warning: malformed tracing config: {e}");
382 None
383 }
384 }
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391 use std::fs;
392
393 #[test]
394 fn to_toml_all_fields() {
395 let cfg = TracevaultConfig {
396 agent: "claude-code".into(),
397 server_url: Some("https://example.com".into()),
398 api_key: None, repo_id: Some("repo-1".into()),
400 user_context: None,
401 remote_id: None,
402 codebase_name: None,
403 default_project: None,
404 project_id: None,
405 project_name: None,
406 };
407 let toml = cfg.to_toml();
408 assert!(toml.contains("agent = \"claude-code\""));
409 assert!(toml.contains("server_url = \"https://example.com\""));
410 assert!(toml.contains("repo_id = \"repo-1\""));
411 assert!(
412 !toml.contains("user_context"),
413 "None user_context must be omitted"
414 );
415 }
416
417 #[test]
418 fn to_toml_minimal() {
419 let cfg = TracevaultConfig::default();
420 let toml = cfg.to_toml();
421 assert!(toml.contains("agent = \"claude-code\""));
422 assert!(!toml.contains("server_url"));
423 }
424
425 #[test]
426 fn load_valid_config() {
427 let dir = tempfile::tempdir().unwrap();
428 let tv_dir = dir.path().join(".visdom");
429 fs::create_dir_all(&tv_dir).unwrap();
430 fs::write(
431 tv_dir.join("tracing.toml"),
432 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\n",
433 )
434 .unwrap();
435 let cfg = TracevaultConfig::load(dir.path()).unwrap();
436 assert_eq!(cfg.agent, "claude-code");
437 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
438 }
439
440 #[test]
441 fn load_old_config_with_org_slug_still_parses() {
442 let dir = tempfile::tempdir().unwrap();
446 let tv_dir = dir.path().join(".visdom");
447 fs::create_dir_all(&tv_dir).unwrap();
448 fs::write(
449 tv_dir.join("tracing.toml"),
450 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"x\"\n",
451 )
452 .unwrap();
453 let cfg = TracevaultConfig::load(dir.path()).unwrap();
454 assert_eq!(cfg.agent, "claude-code");
455 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
456 }
457
458 #[test]
459 fn load_missing_file_returns_none() {
460 let dir = tempfile::tempdir().unwrap();
461 assert!(TracevaultConfig::load(dir.path()).is_none());
462 }
463
464 #[test]
465 fn try_load_distinguishes_missing_valid_and_malformed() {
466 let missing = tempfile::tempdir().unwrap();
468 assert!(matches!(
469 TracevaultConfig::try_load(missing.path()),
470 Ok(None)
471 ));
472
473 let valid = tempfile::tempdir().unwrap();
475 let tv_dir = valid.path().join(".visdom");
476 fs::create_dir_all(&tv_dir).unwrap();
477 fs::write(tv_dir.join("tracing.toml"), "agent = \"claude-code\"\n").unwrap();
478 assert!(matches!(
479 TracevaultConfig::try_load(valid.path()),
480 Ok(Some(_))
481 ));
482
483 let bad = tempfile::tempdir().unwrap();
485 let bad_dir = bad.path().join(".visdom");
486 fs::create_dir_all(&bad_dir).unwrap();
487 fs::write(bad_dir.join("tracing.toml"), "this = = not valid toml").unwrap();
488 assert!(TracevaultConfig::try_load(bad.path()).is_err());
489
490 let io = tempfile::tempdir().unwrap();
493 fs::create_dir_all(io.path().join(".visdom").join("tracing.toml")).unwrap();
494 assert!(TracevaultConfig::try_load(io.path()).is_err());
495 }
496
497 #[test]
498 fn ensure_gitignore_creates_runtime_ignore_file() {
499 let dir = tempfile::tempdir().unwrap();
500 let config_dir = dir.path().join(".visdom");
501 fs::create_dir_all(&config_dir).unwrap();
502
503 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
504
505 let gitignore = config_dir.join(".gitignore");
506 assert!(gitignore.exists(), ".gitignore must be created");
507 let content = fs::read_to_string(&gitignore).unwrap();
508 assert_eq!(content, "*\n!.gitignore\n!config.toml\n");
510 }
511
512 #[test]
513 fn toml_round_trip_omits_api_key_and_none_fields() {
514 let cfg = TracevaultConfig {
515 agent: "claude-code".into(),
516 server_url: Some("https://example.com".into()),
517 api_key: Some("secret".into()),
518 repo_id: None,
519 user_context: None,
520 remote_id: None,
521 codebase_name: None,
522 default_project: None,
523 project_id: None,
524 project_name: None,
525 };
526 let toml = cfg.to_toml();
527 assert!(toml.contains("agent = \"claude-code\""));
528 assert!(toml.contains("server_url = \"https://example.com\""));
529 assert!(!toml.contains("api_key"), "api_key must never be written");
530 assert!(!toml.contains("repo_id"), "None fields must be omitted");
531
532 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
534 assert_eq!(parsed.agent, "claude-code");
535 assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
536 assert_eq!(parsed.api_key, None);
537 }
538
539 #[test]
540 fn user_context_forms_resolve_correctly() {
541 let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
543 assert!(none_cfg.user_context.is_none());
544
545 let f: TracevaultConfig =
547 toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
548 assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
549 assert!(f.user_context.unwrap().resolve().is_none());
550
551 let t: TracevaultConfig =
553 toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
554 assert_eq!(
555 t.user_context.unwrap().resolve(),
556 Some(default_user_context_path())
557 );
558
559 let p: TracevaultConfig =
561 toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
562 assert_eq!(
563 p.user_context.unwrap().resolve(),
564 Some(PathBuf::from("/tmp/ctx.json"))
565 );
566
567 let obj: TracevaultConfig = toml::from_str(
569 "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
570 )
571 .unwrap();
572 let obj_ctx = obj.user_context.unwrap();
573 assert!(obj_ctx.resolve().is_none());
574 assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
575 }
576
577 #[test]
578 fn explicit_disable_is_persisted_not_skipped() {
579 let cfg = TracevaultConfig {
580 user_context: Some(UserContext::Toggle(false)),
581 ..Default::default()
582 };
583 let toml = cfg.to_toml();
584 assert!(
585 toml.contains("user_context"),
586 "explicit off must serialize, got:\n{toml}"
587 );
588 let back: TracevaultConfig = toml::from_str(&toml).unwrap();
589 assert!(matches!(
590 back.user_context,
591 Some(UserContext::Toggle(false))
592 ));
593 }
594
595 #[test]
596 fn user_config_paths_are_under_config_root() {
597 let root = std::path::Path::new("/x/visdom");
598 assert_eq!(
599 user_config_path_in(root),
600 std::path::Path::new("/x/visdom/tracing.toml")
601 );
602 assert_eq!(
603 default_user_context_path_in(root),
604 std::path::Path::new("/x/visdom/context.json")
605 );
606 }
607
608 #[test]
609 fn try_load_user_config_missing_is_ok_none() {
610 let dir = tempfile::tempdir().unwrap();
611 assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
612 }
613
614 #[test]
615 fn try_load_user_config_reads_user_context() {
616 let dir = tempfile::tempdir().unwrap();
617 std::fs::write(
618 user_config_path_in(dir.path()),
619 "agent=\"claude-code\"\nuser_context = true\n",
620 )
621 .unwrap();
622 let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
623 assert_eq!(
627 cfg.user_context.unwrap().resolve_in(dir.path()),
628 Some(default_user_context_path_in(dir.path()))
629 );
630 }
631
632 #[test]
633 fn try_load_user_config_malformed_is_err() {
634 let dir = tempfile::tempdir().unwrap();
635 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
636 assert!(try_load_user_config_in(dir.path()).is_err());
637 }
638
639 #[test]
640 fn load_user_config_lenient_defaults_on_missing() {
641 let dir = tempfile::tempdir().unwrap();
642 assert!(load_user_config_in(dir.path()).user_context.is_none());
643 }
644
645 #[test]
646 fn load_user_config_lenient_defaults_on_malformed() {
647 let dir = tempfile::tempdir().unwrap();
650 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
651 assert!(load_user_config_in(dir.path()).user_context.is_none());
652 }
653
654 #[test]
655 fn resolve_user_context_prefers_repo_over_global() {
656 let dir = tempfile::tempdir().unwrap();
657 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
658 let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
660 assert!(
661 uc.resolve().is_none(),
662 "explicit repo-off must hard-disable"
663 );
664 }
665
666 #[test]
667 fn resolve_user_context_falls_back_to_global_when_repo_unset() {
668 let dir = tempfile::tempdir().unwrap();
669 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
670 let uc = resolve_user_context_in(None, dir.path());
671 assert_eq!(
673 uc.resolve_in(dir.path()),
674 Some(default_user_context_path_in(dir.path()))
675 );
676 }
677
678 #[test]
679 fn resolve_user_context_off_when_neither_configured() {
680 let dir = tempfile::tempdir().unwrap();
681 assert!(resolve_user_context_in(None, dir.path())
682 .resolve()
683 .is_none());
684 }
685
686 #[test]
687 fn from_init_flags_maps_variants() {
688 assert!(matches!(
689 UserContext::from_init_flags(true, None),
690 Ok(Some(UserContext::Toggle(false)))
691 ));
692 assert!(matches!(
693 UserContext::from_init_flags(false, None),
694 Ok(None)
695 ));
696 assert!(matches!(
697 UserContext::from_init_flags(false, Some("/p".into())),
698 Ok(Some(UserContext::Path(_)))
699 ));
700 assert!(UserContext::from_init_flags(false, Some(" ".into())).is_err());
701 }
702
703 #[test]
704 fn ensure_gitignore_preserves_existing_file() {
705 let dir = tempfile::tempdir().unwrap();
706 let config_dir = dir.path().join(".visdom");
707 fs::create_dir_all(&config_dir).unwrap();
708 let gitignore = config_dir.join(".gitignore");
709 fs::write(&gitignore, "custom-user-content\n").unwrap();
710
711 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
712
713 assert_eq!(
715 fs::read_to_string(&gitignore).unwrap(),
716 "custom-user-content\n"
717 );
718 }
719
720 #[test]
721 fn default_project_roundtrips_through_toml() {
722 let cfg = TracevaultConfig {
723 default_project: Some("payments-platform".into()),
724 ..Default::default()
725 };
726 let toml = cfg.to_toml();
727 assert!(toml.contains("default_project = \"payments-platform\""));
728 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
729 assert_eq!(parsed.default_project.as_deref(), Some("payments-platform"));
730 }
731
732 #[test]
733 fn default_project_absent_is_omitted_from_toml() {
734 let toml = TracevaultConfig::default().to_toml();
735 assert!(!toml.contains("default_project"));
736 }
737
738 #[test]
739 fn fields_lists_every_serialized_key() {
740 let cfg = TracevaultConfig {
741 agent: "claude-code".into(),
742 server_url: Some("https://example.com".into()),
743 api_key: Some("tvk_x".into()),
744 repo_id: Some("r".into()),
745 user_context: Some(UserContext::Toggle(true)),
746 remote_id: Some("rm".into()),
747 codebase_name: Some("cb".into()),
748 default_project: Some("p".into()),
749 project_id: Some("00000000-0000-4000-8000-000000000001".into()),
750 project_name: Some("p".into()),
751 };
752 let mut keys: Vec<String> = toml::Table::try_from(&cfg)
753 .unwrap()
754 .keys()
755 .cloned()
756 .collect();
757 keys.push("api_key".into()); keys.sort();
759 let mut fields: Vec<&str> = TracevaultConfig::FIELDS.to_vec();
760 fields.sort();
761 assert_eq!(keys, fields);
762 }
763
764 fn write_config(root: &Path, content: &str) {
765 fs::create_dir_all(root.join(".visdom")).unwrap();
766 fs::write(root.join(".visdom/tracing.toml"), content).unwrap();
767 }
768
769 #[test]
770 fn save_keeps_api_key_unknown_keys_and_key_order() {
771 let dir = tempfile::tempdir().unwrap();
772 write_config(
773 dir.path(),
774 "repo_id = \"r1\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n",
775 );
776
777 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
778 cfg.repo_id = Some("r2".into());
779 cfg.save(dir.path()).unwrap();
780
781 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
782 assert_eq!(
783 content,
784 "# Visdom tracing configuration (this checkout's own)\nrepo_id = \"r2\"\napi_key = \"tvk_abc==\"\nfuture_key = 7\nagent = \"claude-code\"\n"
785 );
786 }
787
788 #[test]
789 fn save_removes_a_known_key_set_to_none() {
790 let dir = tempfile::tempdir().unwrap();
791 write_config(dir.path(), "codebase_name = \"old\"\nrepo_id = \"r1\"\n");
792
793 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
794 cfg.codebase_name = None;
795 cfg.save(dir.path()).unwrap();
796
797 let reloaded = TracevaultConfig::load(dir.path()).unwrap();
798 assert_eq!(reloaded.codebase_name, None);
799 assert_eq!(reloaded.repo_id.as_deref(), Some("r1"));
800 }
801
802 #[test]
803 fn save_puts_scalars_before_a_table_valued_user_context() {
804 let dir = tempfile::tempdir().unwrap();
805 write_config(
806 dir.path(),
807 "[user_context]\nenable = false\npath = \"/x.json\"\n",
808 );
809
810 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
811 cfg.api_key = Some("tvk_y".into());
812 cfg.repo_id = Some("r".into());
813 cfg.save(dir.path()).unwrap();
814
815 let reloaded = TracevaultConfig::load(dir.path()).unwrap();
816 assert_eq!(reloaded.api_key.as_deref(), Some("tvk_y"));
817 assert_eq!(reloaded.repo_id.as_deref(), Some("r"));
818 assert!(matches!(
819 reloaded.user_context,
820 Some(UserContext::Full { enable: false, path: Some(ref p) }) if p == "/x.json"
821 ));
822 }
823
824 #[test]
825 fn save_keeps_an_unchanged_user_context_table_verbatim() {
826 let dir = tempfile::tempdir().unwrap();
827 let original = "repo_id = \"r1\"\nagent = \"claude-code\"\n\n[user_context]\npath = \"/x.json\"\nfuture_setting = 1\nenable = true\n";
828 write_config(dir.path(), original);
829
830 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
831 cfg.repo_id = Some("r2".into());
832 cfg.save(dir.path()).unwrap();
833
834 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
835 assert_eq!(
836 content,
837 format!(
838 "# Visdom tracing configuration (this checkout's own)\n{}",
839 original.replace("r1", "r2")
840 )
841 );
842 }
843
844 #[test]
845 fn save_replaces_a_changed_user_context() {
846 let dir = tempfile::tempdir().unwrap();
847 write_config(
848 dir.path(),
849 "[user_context]\npath = \"/x.json\"\nfuture_setting = 1\n",
850 );
851
852 let mut cfg = TracevaultConfig::load(dir.path()).unwrap();
853 cfg.user_context = Some(UserContext::Toggle(false));
854 cfg.save(dir.path()).unwrap();
855
856 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
857 assert_eq!(
858 content,
859 "# Visdom tracing configuration (this checkout's own)\nuser_context = false\nagent = \"claude-code\"\n"
860 );
861 }
862
863 #[test]
864 fn save_writes_the_default_agent_into_a_file_without_one() {
865 let dir = tempfile::tempdir().unwrap();
866 write_config(dir.path(), "repo_id = \"r1\"\n");
867
868 TracevaultConfig::load(dir.path())
869 .unwrap()
870 .save(dir.path())
871 .unwrap();
872
873 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
874 assert!(content.contains("agent = \"claude-code\""), "{content}");
875 }
876
877 #[test]
878 fn save_creates_a_missing_config() {
879 let dir = tempfile::tempdir().unwrap();
880 fs::create_dir_all(dir.path().join(".visdom")).unwrap();
881 TracevaultConfig::default().save(dir.path()).unwrap();
882 let content = fs::read_to_string(TracevaultConfig::config_path(dir.path())).unwrap();
883 assert_eq!(content, TracevaultConfig::default().to_toml());
884 }
885
886 #[test]
887 fn a_legacy_config_is_read_and_saved_into_the_new_place() {
888 let dir = tempfile::tempdir().unwrap();
889 let root = dir.path();
890 fs::create_dir_all(root.join(".tracevault")).unwrap();
891 fs::write(
892 root.join(".tracevault/config.toml"),
893 "repo_id = \"r1\"\napi_key = \"tvk_x\"\nfuture_setting = 1\n",
894 )
895 .unwrap();
896 fs::create_dir_all(root.join(".visdom")).unwrap();
898 fs::write(root.join(".visdom/config.toml"), "agent = \"codex\"\n").unwrap();
899
900 let mut cfg = TracevaultConfig::try_load(root).unwrap().unwrap();
901 assert_eq!(cfg.repo_id.as_deref(), Some("r1"));
902 assert_eq!(cfg.agent, "claude-code");
903
904 cfg.repo_id = Some("r2".into());
905 cfg.save(root).unwrap();
906
907 assert_eq!(
909 fs::read_to_string(root.join(".visdom/tracing.toml")).unwrap(),
910 "# Visdom tracing configuration (this checkout's own)\nrepo_id = \"r2\"\n\
911 api_key = \"tvk_x\"\nfuture_setting = 1\nagent = \"claude-code\"\n"
912 );
913 assert_eq!(
914 fs::read_to_string(root.join(".visdom/config.toml")).unwrap(),
915 "agent = \"codex\"\n"
916 );
917 assert!(root.join(".visdom/.gitignore").exists());
918 assert!(fs::read_to_string(root.join(".tracevault/config.toml"))
920 .unwrap()
921 .contains("r1"));
922 assert_eq!(
923 TracevaultConfig::load(root).unwrap().repo_id.as_deref(),
924 Some("r2")
925 );
926 }
927
928 #[test]
929 fn a_legacy_user_config_is_read() {
930 let dir = tempfile::tempdir().unwrap();
931 fs::create_dir_all(dir.path().join("tracevault")).unwrap();
932 fs::write(
933 dir.path().join("tracevault/config.toml"),
934 "user_context = \"/ctx.json\"\n",
935 )
936 .unwrap();
937 fs::write(dir.path().join("tracevault/context.json"), "{}").unwrap();
938 let user = dir.path().join("visdom");
939
940 let cfg = try_load_user_config_in(&user).unwrap().unwrap();
941 assert!(matches!(cfg.user_context, Some(UserContext::Path(p)) if p == "/ctx.json"));
942 assert_eq!(
945 default_user_context_path_in(&user),
946 user.join("context.json")
947 );
948 assert_eq!(
949 crate::layout::existing_or_twin(&default_user_context_path_in(&user)),
950 dir.path().join("tracevault/context.json")
951 );
952 assert_eq!(user_config_path_in(&user), user.join("tracing.toml"));
953 }
954}