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 pub fn try_load(project_root: &Path) -> Result<Option<Self>, String> {
256 let path = Self::config_path(project_root);
257 let content = match std::fs::read_to_string(&path) {
258 Ok(c) => c,
259 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
260 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
261 };
262 toml::from_str(&content)
263 .map(Some)
264 .map_err(|e| e.to_string())
265 }
266
267 pub fn load(project_root: &Path) -> Option<Self> {
272 match Self::try_load(project_root) {
273 Ok(cfg) => cfg,
274 Err(e) => {
275 eprintln!("tracevault: warning: malformed config.toml: {e}");
276 None
277 }
278 }
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use std::fs;
286
287 #[test]
288 fn to_toml_all_fields() {
289 let cfg = TracevaultConfig {
290 agent: "claude-code".into(),
291 server_url: Some("https://example.com".into()),
292 api_key: None, repo_id: Some("repo-1".into()),
294 user_context: None,
295 remote_id: None,
296 codebase_name: None,
297 default_project: None,
298 };
299 let toml = cfg.to_toml();
300 assert!(toml.contains("agent = \"claude-code\""));
301 assert!(toml.contains("server_url = \"https://example.com\""));
302 assert!(toml.contains("repo_id = \"repo-1\""));
303 assert!(
304 !toml.contains("user_context"),
305 "None user_context must be omitted"
306 );
307 }
308
309 #[test]
310 fn to_toml_minimal() {
311 let cfg = TracevaultConfig::default();
312 let toml = cfg.to_toml();
313 assert!(toml.contains("agent = \"claude-code\""));
314 assert!(!toml.contains("server_url"));
315 }
316
317 #[test]
318 fn load_valid_config() {
319 let dir = tempfile::tempdir().unwrap();
320 let tv_dir = dir.path().join(".tracevault");
321 fs::create_dir_all(&tv_dir).unwrap();
322 fs::write(
323 tv_dir.join("config.toml"),
324 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\n",
325 )
326 .unwrap();
327 let cfg = TracevaultConfig::load(dir.path()).unwrap();
328 assert_eq!(cfg.agent, "claude-code");
329 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
330 }
331
332 #[test]
333 fn load_old_config_with_org_slug_still_parses() {
334 let dir = tempfile::tempdir().unwrap();
338 let tv_dir = dir.path().join(".tracevault");
339 fs::create_dir_all(&tv_dir).unwrap();
340 fs::write(
341 tv_dir.join("config.toml"),
342 "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"x\"\n",
343 )
344 .unwrap();
345 let cfg = TracevaultConfig::load(dir.path()).unwrap();
346 assert_eq!(cfg.agent, "claude-code");
347 assert_eq!(cfg.server_url.unwrap(), "https://example.com");
348 }
349
350 #[test]
351 fn load_missing_file_returns_none() {
352 let dir = tempfile::tempdir().unwrap();
353 assert!(TracevaultConfig::load(dir.path()).is_none());
354 }
355
356 #[test]
357 fn try_load_distinguishes_missing_valid_and_malformed() {
358 let missing = tempfile::tempdir().unwrap();
360 assert!(matches!(
361 TracevaultConfig::try_load(missing.path()),
362 Ok(None)
363 ));
364
365 let valid = tempfile::tempdir().unwrap();
367 let tv_dir = valid.path().join(".tracevault");
368 fs::create_dir_all(&tv_dir).unwrap();
369 fs::write(tv_dir.join("config.toml"), "agent = \"claude-code\"\n").unwrap();
370 assert!(matches!(
371 TracevaultConfig::try_load(valid.path()),
372 Ok(Some(_))
373 ));
374
375 let bad = tempfile::tempdir().unwrap();
377 let bad_dir = bad.path().join(".tracevault");
378 fs::create_dir_all(&bad_dir).unwrap();
379 fs::write(bad_dir.join("config.toml"), "this = = not valid toml").unwrap();
380 assert!(TracevaultConfig::try_load(bad.path()).is_err());
381
382 let io = tempfile::tempdir().unwrap();
385 fs::create_dir_all(io.path().join(".tracevault").join("config.toml")).unwrap();
386 assert!(TracevaultConfig::try_load(io.path()).is_err());
387 }
388
389 #[test]
390 fn ensure_gitignore_creates_runtime_ignore_file() {
391 let dir = tempfile::tempdir().unwrap();
392 let config_dir = dir.path().join(".tracevault");
393 fs::create_dir_all(&config_dir).unwrap();
394
395 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
396
397 let gitignore = config_dir.join(".gitignore");
398 assert!(gitignore.exists(), ".gitignore must be created");
399 let content = fs::read_to_string(&gitignore).unwrap();
400 assert!(content.contains("sessions/"), "must ignore sessions/");
401 assert!(content.contains("cache/"), "must ignore cache/");
402 assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
403 }
404
405 #[test]
406 fn toml_round_trip_omits_api_key_and_none_fields() {
407 let cfg = TracevaultConfig {
408 agent: "claude-code".into(),
409 server_url: Some("https://example.com".into()),
410 api_key: Some("secret".into()),
411 repo_id: None,
412 user_context: None,
413 remote_id: None,
414 codebase_name: None,
415 default_project: None,
416 };
417 let toml = cfg.to_toml();
418 assert!(toml.contains("agent = \"claude-code\""));
419 assert!(toml.contains("server_url = \"https://example.com\""));
420 assert!(!toml.contains("api_key"), "api_key must never be written");
421 assert!(!toml.contains("repo_id"), "None fields must be omitted");
422
423 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
425 assert_eq!(parsed.agent, "claude-code");
426 assert_eq!(parsed.server_url.as_deref(), Some("https://example.com"));
427 assert_eq!(parsed.api_key, None);
428 }
429
430 #[test]
431 fn user_context_forms_resolve_correctly() {
432 let none_cfg: TracevaultConfig = toml::from_str("agent = \"claude-code\"").unwrap();
434 assert!(none_cfg.user_context.is_none());
435
436 let f: TracevaultConfig =
438 toml::from_str("agent=\"claude-code\"\nuser_context = false").unwrap();
439 assert!(matches!(f.user_context, Some(UserContext::Toggle(false))));
440 assert!(f.user_context.unwrap().resolve().is_none());
441
442 let t: TracevaultConfig =
444 toml::from_str("agent=\"claude-code\"\nuser_context = true").unwrap();
445 assert_eq!(
446 t.user_context.unwrap().resolve(),
447 Some(default_user_context_path())
448 );
449
450 let p: TracevaultConfig =
452 toml::from_str("agent=\"claude-code\"\nuser_context = \"/tmp/ctx.json\"").unwrap();
453 assert_eq!(
454 p.user_context.unwrap().resolve(),
455 Some(PathBuf::from("/tmp/ctx.json"))
456 );
457
458 let obj: TracevaultConfig = toml::from_str(
460 "agent=\"claude-code\"\n[user_context]\nenable = false\npath = \"/tmp/x.json\"",
461 )
462 .unwrap();
463 let obj_ctx = obj.user_context.unwrap();
464 assert!(obj_ctx.resolve().is_none());
465 assert_eq!(obj_ctx.path(), PathBuf::from("/tmp/x.json"));
466 }
467
468 #[test]
469 fn explicit_disable_is_persisted_not_skipped() {
470 let cfg = TracevaultConfig {
471 user_context: Some(UserContext::Toggle(false)),
472 ..Default::default()
473 };
474 let toml = cfg.to_toml();
475 assert!(
476 toml.contains("user_context"),
477 "explicit off must serialize, got:\n{toml}"
478 );
479 let back: TracevaultConfig = toml::from_str(&toml).unwrap();
480 assert!(matches!(
481 back.user_context,
482 Some(UserContext::Toggle(false))
483 ));
484 }
485
486 #[test]
487 fn user_config_paths_are_under_config_root() {
488 let root = std::path::Path::new("/x/tracevault");
489 assert_eq!(
490 user_config_path_in(root),
491 std::path::Path::new("/x/tracevault/config.toml")
492 );
493 assert_eq!(
494 default_user_context_path_in(root),
495 std::path::Path::new("/x/tracevault/context.json")
496 );
497 }
498
499 #[test]
500 fn try_load_user_config_missing_is_ok_none() {
501 let dir = tempfile::tempdir().unwrap();
502 assert!(matches!(try_load_user_config_in(dir.path()), Ok(None)));
503 }
504
505 #[test]
506 fn try_load_user_config_reads_user_context() {
507 let dir = tempfile::tempdir().unwrap();
508 std::fs::write(
509 user_config_path_in(dir.path()),
510 "agent=\"claude-code\"\nuser_context = true\n",
511 )
512 .unwrap();
513 let cfg = try_load_user_config_in(dir.path()).unwrap().unwrap();
514 assert_eq!(
518 cfg.user_context.unwrap().resolve_in(dir.path()),
519 Some(default_user_context_path_in(dir.path()))
520 );
521 }
522
523 #[test]
524 fn try_load_user_config_malformed_is_err() {
525 let dir = tempfile::tempdir().unwrap();
526 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
527 assert!(try_load_user_config_in(dir.path()).is_err());
528 }
529
530 #[test]
531 fn load_user_config_lenient_defaults_on_missing() {
532 let dir = tempfile::tempdir().unwrap();
533 assert!(load_user_config_in(dir.path()).user_context.is_none());
534 }
535
536 #[test]
537 fn load_user_config_lenient_defaults_on_malformed() {
538 let dir = tempfile::tempdir().unwrap();
541 std::fs::write(user_config_path_in(dir.path()), "this is = = not toml").unwrap();
542 assert!(load_user_config_in(dir.path()).user_context.is_none());
543 }
544
545 #[test]
546 fn resolve_user_context_prefers_repo_over_global() {
547 let dir = tempfile::tempdir().unwrap();
548 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
549 let uc = resolve_user_context_in(Some(UserContext::Toggle(false)), dir.path());
551 assert!(
552 uc.resolve().is_none(),
553 "explicit repo-off must hard-disable"
554 );
555 }
556
557 #[test]
558 fn resolve_user_context_falls_back_to_global_when_repo_unset() {
559 let dir = tempfile::tempdir().unwrap();
560 std::fs::write(user_config_path_in(dir.path()), "user_context = true\n").unwrap();
561 let uc = resolve_user_context_in(None, dir.path());
562 assert_eq!(
564 uc.resolve_in(dir.path()),
565 Some(default_user_context_path_in(dir.path()))
566 );
567 }
568
569 #[test]
570 fn resolve_user_context_off_when_neither_configured() {
571 let dir = tempfile::tempdir().unwrap();
572 assert!(resolve_user_context_in(None, dir.path())
573 .resolve()
574 .is_none());
575 }
576
577 #[test]
578 fn from_init_flags_maps_variants() {
579 assert!(matches!(
580 UserContext::from_init_flags(true, None),
581 Ok(Some(UserContext::Toggle(false)))
582 ));
583 assert!(matches!(
584 UserContext::from_init_flags(false, None),
585 Ok(None)
586 ));
587 assert!(matches!(
588 UserContext::from_init_flags(false, Some("/p".into())),
589 Ok(Some(UserContext::Path(_)))
590 ));
591 assert!(UserContext::from_init_flags(false, Some(" ".into())).is_err());
592 }
593
594 #[test]
595 fn ensure_gitignore_preserves_existing_file() {
596 let dir = tempfile::tempdir().unwrap();
597 let config_dir = dir.path().join(".tracevault");
598 fs::create_dir_all(&config_dir).unwrap();
599 let gitignore = config_dir.join(".gitignore");
600 fs::write(&gitignore, "custom-user-content\n").unwrap();
601
602 TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
603
604 assert_eq!(
606 fs::read_to_string(&gitignore).unwrap(),
607 "custom-user-content\n"
608 );
609 }
610
611 #[test]
612 fn default_project_roundtrips_through_toml() {
613 let cfg = TracevaultConfig {
614 default_project: Some("payments-platform".into()),
615 ..Default::default()
616 };
617 let toml = cfg.to_toml();
618 assert!(toml.contains("default_project = \"payments-platform\""));
619 let parsed: TracevaultConfig = toml::from_str(&toml).unwrap();
620 assert_eq!(parsed.default_project.as_deref(), Some("payments-platform"));
621 }
622
623 #[test]
624 fn default_project_absent_is_omitted_from_toml() {
625 let toml = TracevaultConfig::default().to_toml();
626 assert!(!toml.contains("default_project"));
627 }
628}