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)]
15 #[allow(dead_code)]
16 pub api_key: Option<String>,
17 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub org_slug: Option<String>,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub repo_id: Option<String>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub user_context: Option<UserContext>,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub remote_id: Option<String>,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub codebase_name: Option<String>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub default_project: Option<String>,
37}
38
39fn default_agent() -> String {
40 "claude-code".to_string()
41}
42
43impl Default for TracevaultConfig {
44 fn default() -> Self {
45 Self {
46 agent: "claude-code".to_string(),
47 server_url: None,
48 api_key: None,
49 org_slug: None,
50 repo_id: None,
51 user_context: None,
52 remote_id: None,
53 codebase_name: None,
54 default_project: None,
55 }
56 }
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(untagged)]
63pub enum UserContext {
64 Toggle(bool),
65 Path(String),
66 Full {
67 #[serde(default = "crate::config::enable_default")]
68 enable: bool,
69 #[serde(default)]
70 path: Option<String>,
71 },
72}
73
74impl Default for UserContext {
75 fn default() -> Self {
76 UserContext::Toggle(false)
77 }
78}
79
80pub(crate) fn enable_default() -> bool {
81 true
82}
83
84pub fn tv_config_root() -> PathBuf {
87 dirs::config_dir()
88 .unwrap_or_else(|| PathBuf::from("."))
89 .join("tracevault")
90}
91
92pub fn user_config_path_in(config_root: &Path) -> PathBuf {
93 config_root.join("config.toml")
94}
95pub fn user_config_path() -> PathBuf {
96 user_config_path_in(&tv_config_root())
97}
98pub fn default_user_context_path_in(config_root: &Path) -> PathBuf {
99 config_root.join("context.json")
100}
101
102#[allow(dead_code)]
107pub fn default_user_context_path() -> PathBuf {
108 default_user_context_path_in(&tv_config_root())
109}
110
111pub fn try_load_user_config_in(config_root: &Path) -> Result<Option<TracevaultConfig>, String> {
116 let path = user_config_path_in(config_root);
117 let content = match std::fs::read_to_string(&path) {
118 Ok(c) => c,
119 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
120 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
121 };
122 toml::from_str(&content)
123 .map(Some)
124 .map_err(|e| e.to_string())
125}
126
127pub fn load_user_config_in(config_root: &Path) -> TracevaultConfig {
129 match try_load_user_config_in(config_root) {
130 Ok(Some(cfg)) => cfg,
131 Ok(None) => TracevaultConfig::default(),
132 Err(e) => {
133 eprintln!("tracevault: warning: malformed user config.toml: {e}");
134 TracevaultConfig::default()
135 }
136 }
137}
138
139pub fn resolve_user_context_in(
144 repo_configured: Option<UserContext>,
145 config_root: &Path,
146) -> UserContext {
147 repo_configured.unwrap_or_else(|| {
148 load_user_config_in(config_root)
149 .user_context
150 .unwrap_or_default()
151 })
152}
153
154pub fn resolve_user_context(repo_configured: Option<UserContext>) -> UserContext {
156 resolve_user_context_in(repo_configured, &tv_config_root())
157}
158
159impl UserContext {
160 pub fn path(&self) -> PathBuf {
163 self.path_in(&tv_config_root())
164 }
165
166 pub fn path_in(&self, config_root: &Path) -> PathBuf {
173 match self {
174 UserContext::Path(p) => PathBuf::from(p),
175 UserContext::Full { path: Some(p), .. } => PathBuf::from(p),
176 _ => default_user_context_path_in(config_root),
177 }
178 }
179
180 pub fn resolve(&self) -> Option<PathBuf> {
182 self.resolve_in(&tv_config_root())
183 }
184
185 pub fn resolve_in(&self, config_root: &Path) -> Option<PathBuf> {
191 let enabled = match self {
192 UserContext::Toggle(b) => *b,
193 UserContext::Path(_) => true,
194 UserContext::Full { enable, .. } => *enable,
195 };
196 enabled.then(|| self.path_in(config_root))
197 }
198
199 pub fn from_init_flags(
204 no_user_context: bool,
205 user_context: Option<String>,
206 ) -> Result<Option<UserContext>, String> {
207 match (no_user_context, user_context) {
208 (true, _) => Ok(Some(UserContext::Toggle(false))),
209 (false, Some(p)) if p.trim().is_empty() => {
210 Err("--user-context path must not be empty".to_string())
211 }
212 (false, Some(p)) => Ok(Some(UserContext::Path(p))),
213 (false, None) => Ok(None),
214 }
215 }
216}
217
218impl TracevaultConfig {
219 pub fn config_dir(project_root: &Path) -> PathBuf {
220 project_root.join(".tracevault")
221 }
222
223 pub fn config_path(project_root: &Path) -> PathBuf {
224 Self::config_dir(project_root).join("config.toml")
225 }
226
227 const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";
230
231 pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
238 let path = config_dir.join(".gitignore");
239 if path.exists() {
240 return Ok(());
241 }
242 std::fs::write(path, Self::GITIGNORE_CONTENTS)
243 }
244
245 pub fn to_toml(&self) -> String {
246 let body = toml::to_string(self).unwrap_or_default();
247 format!("# TraceVault configuration\n{body}")
248 }
249
250 pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
259 let path = Self::config_path(project_root);
260 let content = match std::fs::read_to_string(&path) {
261 Ok(c) => c,
262 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
263 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
264 };
265 toml::from_str(&content)
266 .map(Some)
267 .map_err(|e| e.to_string())
268 }
269
270 pub fn load(project_root: &Path) -> Option<Self> {
275 match Self::try_load(project_root) {
276 Ok(cfg) => cfg,
277 Err(e) => {
278 eprintln!("tracevault: warning: malformed config.toml: {e}");
279 None
280 }
281 }
282 }
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288 use std::fs;
289
290 #[test]
291 fn to_toml_all_fields() {
292 let cfg = TracevaultConfig {
293 agent: "claude-code".into(),
294 server_url: Some("https://example.com".into()),
295 api_key: None, org_slug: Some("my-org".into()),
297 repo_id: Some("repo-1".into()),
298 user_context: None,
299 remote_id: None,
300 codebase_name: None,
301 default_project: None,
302 };
303 let toml = cfg.to_toml();
304 assert!(toml.contains("agent = \"claude-code\""));
305 assert!(toml.contains("server_url = \"https://example.com\""));
306 assert!(toml.contains("org_slug = \"my-org\""));
307 assert!(toml.contains("repo_id = \"repo-1\""));
308 assert!(
309 !toml.contains("user_context"),
310 "None user_context must be omitted"
311 );
312 }
313
314 #[test]
315 fn to_toml_minimal() {
316 let cfg = TracevaultConfig::default();
317 let toml = cfg.to_toml();
318 assert!(toml.contains("agent = \"claude-code\""));
319 assert!(!toml.contains("server_url"));
320 }
321
322 #[test]
323 fn load_valid_config() {
324 let dir = tempfile::tempdir().unwrap();
325 let tv_dir = dir.path().join(".tracevault");
326 fs::create_dir_all(&tv_dir).unwrap();
327 fs::write(
328 tv_dir.join("config.toml"),
329 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"myorg\"\n",
330 )
331 .unwrap();
332 let cfg = TracevaultConfig::load(dir.path()).unwrap();
333 assert_eq!(cfg.agent, "claude-code");
334 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
335 assert_eq!(cfg.org_slug.unwrap(), "myorg");
336 }
337
338 #[test]
339 fn load_missing_file_returns_none() {
340 let dir = tempfile::tempdir().unwrap();
341 assert!(TracevaultConfig::load(dir.path()).is_none());
342 }
343
344 #[test]
345 fn try_load_distinguishes_missing_valid_and_malformed() {
346 let missing = tempfile::tempdir().unwrap();
348 assert!(matches!(
349 TracevaultConfig::try_load(missing.path()),
350 Ok(None)
351 ));
352
353 let valid = tempfile::tempdir().unwrap();
355 let tv_dir = valid.path().join(".tracevault");
356 fs::create_dir_all(&tv_dir).unwrap();
357 fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
358 assert!(matches!(
359 TracevaultConfig::try_load(valid.path()),
360 Ok(Some(_))
361 ));
362
363 let bad = tempfile::tempdir().unwrap();
365 let bad_dir = bad.path().join(".tracevault");
366 fs::create_dir_all(&bad_dir).unwrap();
367 fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
368 assert!(TracevaultConfig::try_load(bad.path()).is_err());
369
370 let io = tempfile::tempdir().unwrap();
373 fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
374 assert!(TracevaultConfig::try_load(io.path()).is_err());
375 }
376
377 #[test]
378 fn ensure_gitignore_creates_runtime_ignore_file() {
379 let dir = tempfile::tempdir().unwrap();
380 let config_dir = dir.path().join(".tracevault");
381 fs::create_dir_all(&config_dir).unwrap();
382
383 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
384
385 let gitignore = config_dir.join(".gitignore");
386 assert!(gitignore.exists(), ".gitignore must be created");
387 let content = fs::read_to_string(&gitignore).unwrap();
388 assert!(content.contains("sessions/"), "must ignore sessions/");
389 assert!(content.contains("cache/"), "must ignore cache/");
390 assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
391 }
392
393 #[test]
394 fn toml_round_trip_omits_api_key_and_none_fields() {
395 let cfg = TracevaultConfig {
396 agent: "claude-code".into(),
397 server_url: Some("https://example.com".into()),
398 api_key: Some("secret".into()),
399 org_slug: Some("my-org".into()),
400 repo_id: None,
401 user_context: None,
402 remote_id: None,
403 codebase_name: None,
404 default_project: None,
405 };
406 let toml = cfg.to_toml();
407 assert!(toml.contains("agent = \"claude-code\""));
408 assert!(toml.contains("server_url = \"https://example.com\""));
409 assert!(toml.contains("org_slug = \"my-org\""));
410 assert!(!toml.contains("api_key"), "api_key must never be written");
411 assert!(!toml.contains("repo_id"), "None fields must be omitted");
412
413 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
415 assert_eq!(parsed.agent, "claude-code");
416 assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
417 assert_eq!(parsed.org_slug.as_deref(), Some("my-org"));
418 assert_eq!(parsed.api_key, None);
419 }
420
421 #[test]
422 fn user_context_forms_resolve_correctly() {
423 let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
425 assert!(none_cfg.user_context.is_none());
426
427 let f: TracevaultConfig =
429 toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
430 assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
431 assert!(f.user_context.unwrap().resolve().is_none());
432
433 let t: TracevaultConfig =
435 toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
436 assert_eq!(
437 t.user_context.unwrap().resolve(),
438 Some(default_user_context_path())
439 );
440
441 let p: TracevaultConfig =
443 toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
444 assert_eq!(
445 p.user_context.unwrap().resolve(),
446 Some(PathBuf::from("/tmp/ctx.json"))
447 );
448
449 let obj: TracevaultConfig = toml::from_str(
451 "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
452 )
453 .unwrap();
454 let obj_ctx = obj.user_context.unwrap();
455 assert!(obj_ctx.resolve().is_none());
456 assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
457 }
458
459 #[test]
460 fn explicit_disable_is_persisted_not_skipped() {
461 let cfg = TracevaultConfig {
462 user_context: Some(UserContext::Toggle(false)),
463 ..Default::default()
464 };
465 let toml = cfg.to_toml();
466 assert!(
467 toml.contains("user_context"),
468 "explicit off must serialize, got:\n{toml}"
469 );
470 let back: TracevaultConfig = toml::from_str(&toml).unwrap();
471 assert!(matches!(
472 back.user_context,
473 Some(UserContext::Toggle(false))
474 ));
475 }
476
477 #[test]
478 fn user_config_paths_are_under_config_root() {
479 let root = std::path::Path::new("/x/tracevault");
480 assert_eq!(
481 user_config_path_in(root),
482 std::path::Path::new("/x/tracevault/config.toml")
483 );
484 assert_eq!(
485 default_user_context_path_in(root),
486 std::path::Path::new("/x/tracevault/context.json")
487 );
488 }
489
490 #[test]
491 fn try_load_user_config_missing_is_ok_none() {
492 let dir = tempfile::tempdir().unwrap();
493 assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
494 }
495
496 #[test]
497 fn try_load_user_config_reads_user_context() {
498 let dir = tempfile::tempdir().unwrap();
499 std::fs::write(
500 user_config_path_in(dir.path()),
501 "agent=\"claude-code\"\nuser_context = true\n",
502 )
503 .unwrap();
504 let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
505 assert_eq!(
509 cfg.user_context.unwrap().resolve_in(dir.path()),
510 Some(default_user_context_path_in(dir.path()))
511 );
512 }
513
514 #[test]
515 fn try_load_user_config_malformed_is_err() {
516 let dir = tempfile::tempdir().unwrap();
517 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
518 assert!(try_load_user_config_in(dir.path()).is_err());
519 }
520
521 #[test]
522 fn load_user_config_lenient_defaults_on_missing() {
523 let dir = tempfile::tempdir().unwrap();
524 assert!(load_user_config_in(dir.path()).user_context.is_none());
525 }
526
527 #[test]
528 fn load_user_config_lenient_defaults_on_malformed() {
529 let dir = tempfile::tempdir().unwrap();
532 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
533 assert!(load_user_config_in(dir.path()).user_context.is_none());
534 }
535
536 #[test]
537 fn resolve_user_context_prefers_repo_over_global() {
538 let dir = tempfile::tempdir().unwrap();
539 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
540 let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
542 assert!(
543 uc.resolve().is_none(),
544 "explicit repo-off must hard-disable"
545 );
546 }
547
548 #[test]
549 fn resolve_user_context_falls_back_to_global_when_repo_unset() {
550 let dir = tempfile::tempdir().unwrap();
551 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
552 let uc = resolve_user_context_in(None, dir.path());
553 assert_eq!(
555 uc.resolve_in(dir.path()),
556 Some(default_user_context_path_in(dir.path()))
557 );
558 }
559
560 #[test]
561 fn resolve_user_context_off_when_neither_configured() {
562 let dir = tempfile::tempdir().unwrap();
563 assert!(resolve_user_context_in(None, dir.path())
564 .resolve()
565 .is_none());
566 }
567
568 #[test]
569 fn from_init_flags_maps_variants() {
570 assert!(matches!(
571 UserContext::from_init_flags(true, None),
572 Ok(Some(UserContext::Toggle(false)))
573 ));
574 assert!(matches!(
575 UserContext::from_init_flags(false, None),
576 Ok(None)
577 ));
578 assert!(matches!(
579 UserContext::from_init_flags(false, Some("/p".into())),
580 Ok(Some(UserContext::Path(_)))
581 ));
582 assert!(UserContext::from_init_flags(false, Some(" ".into())).is_err());
583 }
584
585 #[test]
586 fn ensure_gitignore_preserves_existing_file() {
587 let dir = tempfile::tempdir().unwrap();
588 let config_dir = dir.path().join(".tracevault");
589 fs::create_dir_all(&config_dir).unwrap();
590 let gitignore = config_dir.join(".gitignore");
591 fs::write(&gitignore, "custom-user-content\n").unwrap();
592
593 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
594
595 assert_eq!(
597 fs::read_to_string(&gitignore).unwrap(),
598 "custom-user-content\n"
599 );
600 }
601
602 #[test]
603 fn default_project_roundtrips_through_toml() {
604 let cfg = TracevaultConfig {
605 default_project: Some("payments-platform".into()),
606 ..Default::default()
607 };
608 let toml = cfg.to_toml();
609 assert!(toml.contains("default_project = \"payments-platform\""));
610 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
611 assert_eq!(parsed.default_project.as_deref(), Some("payments-platform"));
612 }
613
614 #[test]
615 fn default_project_absent_is_omitted_from_toml() {
616 let toml = TracevaultConfig::default().to_toml();
617 assert!(!toml.contains("default_project"));
618 }
619}