1use std::path::{Path, PathBuf};
4
5use tracevault_cli::agent::Agent;
6use tracevault_cli::commands::init::{
7 has_marker, has_tracevault_hooks, POST_COMMIT_MARKER, PRE_PUSH_MARKER,
8};
9use tracevault_cli::config::TracevaultConfig;
10
11use super::{CheckContext, CredentialState};
12use crate::finding::{Finding, Fix, FixAction, Severity};
13
14const COMPONENT: &str = "tracing";
15
16pub fn check(ctx: &CheckContext) -> Vec<Finding> {
21 let mut findings = vec![auth(ctx)];
22 let (Some(project_dir), Some(root)) = (&ctx.workdir.checkout, &ctx.workdir.primary) else {
23 findings.push(Finding::new(
24 COMPONENT,
25 "tracing.repo",
26 Severity::Info,
27 "not in a repository: only sessions captured by a global install are traced here",
28 ));
29 return findings;
30 };
31
32 let global = global_hook_file(ctx);
33 let global_installed = matches!(has_tracevault_hooks(&global), Ok(true));
34 let init = || Fix {
35 description: format!(
36 "run `visdom trace init --agent {}` in {} (writes .visdom/, the {} hooks and \
37 the git hooks)",
38 ctx.agent.tool_name(),
39 root.display(),
40 ctx.agent.label()
41 ),
42 action: FixAction::TracingInit {
43 agent: ctx.agent,
44 dir: root.clone(),
45 },
46 };
47
48 let config = TracevaultConfig::try_load(root);
49 let own_setup = !matches!(config, Ok(None));
50 findings.push(if let Err(e) = &config {
51 Finding::new(
54 COMPONENT,
55 "tracing.repo",
56 Severity::Unknown,
57 format!(
58 "cannot use {} — {e}; fix or remove it",
59 TracevaultConfig::existing_config_path(root).display()
60 ),
61 )
62 } else if own_setup {
63 Finding::new(
64 COMPONENT,
65 "tracing.repo",
66 Severity::Ok,
67 format!("tracing is set up in {}", root.display()),
68 )
69 } else if global_installed {
70 Finding::new(
71 COMPONENT,
72 "tracing.repo",
73 Severity::Ok,
74 "no .visdom/ here: sessions are captured by the global install and bound to \
75 the repository by its origin remote",
76 )
77 } else {
78 Finding::new(
79 COMPONENT,
80 "tracing.repo",
81 Severity::Error,
82 format!("tracing is not set up in {}", root.display()),
83 )
84 .with_fix(init())
85 });
86
87 let hooks = agent_hooks(ctx, project_dir, root, &global);
88 findings.push(if hooks.severity == Severity::Error {
89 hooks.with_fix(init())
90 } else {
91 hooks
92 });
93
94 let git_hooks = missing_git_hooks(root);
95 if let Err(unreadable) = &git_hooks {
96 findings.push(Finding::new(
97 COMPONENT,
98 "tracing.git_hooks",
99 Severity::Unknown,
100 format!("could not tell whether the git hooks are installed — {unreadable}"),
101 ));
102 } else if let Ok(Some(missing)) = &git_hooks {
103 let message = format!(
104 "git {missing} hook{} not installed in {}: commits are not linked to sessions and \
105 policies are not checked before a push",
106 if missing.contains(" and ") { "s" } else { "" },
107 root.join(".git/hooks").display()
108 );
109 findings.push(if global_installed && !own_setup {
110 Finding::new(
114 COMPONENT,
115 "tracing.git_hooks",
116 Severity::Info,
117 format!(
118 "{message} (`visdom trace init` in {} adds them)",
119 root.display()
120 ),
121 )
122 } else {
123 Finding::new(COMPONENT, "tracing.git_hooks", Severity::Warn, message).with_fix(init())
124 });
125 } else {
126 findings.push(Finding::new(
127 COMPONENT,
128 "tracing.git_hooks",
129 Severity::Ok,
130 "git hooks installed (pre-push, post-commit)",
131 ));
132 }
133 findings
134}
135
136pub fn working(ctx: &CheckContext) -> bool {
141 if ctx.server_url.is_none() || ctx.credential != CredentialState::Present {
142 return false;
143 }
144 let global = global_hook_file(ctx);
145 match (&ctx.workdir.checkout, &ctx.workdir.primary) {
146 (Some(project_dir), Some(root)) => {
147 agent_hooks(ctx, project_dir, root, &global).severity == Severity::Ok
148 }
149 _ => matches!(has_tracevault_hooks(&global), Ok(true)),
150 }
151}
152
153fn auth(ctx: &CheckContext) -> Finding {
154 const ID: &str = "tracing.auth";
155 match (&ctx.credential, &ctx.server_url) {
156 (CredentialState::Present, Some(url)) => {
157 Finding::new(COMPONENT, ID, Severity::Ok, format!("logged in to {url}"))
158 }
159 (CredentialState::Present, None) => {
160 Finding::new(COMPONENT, ID, Severity::Ok, "credential found")
161 }
162 (CredentialState::Unreadable(path), _) => Finding::new(
163 COMPONENT,
164 ID,
165 Severity::Unknown,
166 format!("could not tell whether you are logged in — {path} cannot be read or parsed"),
167 ),
168 (CredentialState::Unusable(reason), _) => {
169 Finding::new(COMPONENT, ID, Severity::Error, reason.clone())
170 }
171 (CredentialState::Missing, Some(url)) => Finding::new(
172 COMPONENT,
173 ID,
174 Severity::Error,
175 format!("not logged in to {url}"),
176 )
177 .with_fix(Fix {
178 description: format!(
179 "run `visdom login --server-url {url}` (signs you in through the browser)"
180 ),
181 action: FixAction::Login {
182 server_url: url.clone(),
183 },
184 }),
185 (CredentialState::Missing, None) => Finding::new(
186 COMPONENT,
187 ID,
188 Severity::Error,
189 "not logged in — run `visdom login --server-url <url>`",
190 ),
191 }
192}
193
194fn global_hook_file(ctx: &CheckContext) -> PathBuf {
196 match ctx.agent {
197 Agent::Codex => ctx.codex_home.join("hooks.json"),
198 _ => ctx.home.join(".claude").join("settings.json"),
199 }
200}
201
202fn agent_hooks(ctx: &CheckContext, project_dir: &Path, root: &Path, global: &Path) -> Finding {
205 const ID: &str = "tracing.agent_hooks";
206 let names: &[&str] = match ctx.agent {
207 Agent::Codex => &[".codex/hooks.json"],
208 _ => &[".claude/settings.json", ".claude/settings.local.json"],
209 };
210 let mut files: Vec<PathBuf> = Vec::new();
213 for dir in [project_dir, root] {
214 for name in names {
215 let file = dir.join(name);
216 if !files.contains(&file) {
217 files.push(file);
218 }
219 }
220 }
221 files.push(global.to_path_buf());
222
223 let mut unreadable = Vec::new();
224 for file in &files {
225 match has_tracevault_hooks(file) {
226 Ok(true) => {
227 return Finding::new(
228 COMPONENT,
229 ID,
230 Severity::Ok,
231 format!("{} hooks installed ({})", ctx.agent.label(), file.display()),
232 )
233 }
234 Ok(false) => {}
235 Err(e) => unreadable.push(format!("{}: {e}", file.display())),
236 }
237 }
238 if !unreadable.is_empty() {
239 return Finding::new(
240 COMPONENT,
241 ID,
242 Severity::Unknown,
243 format!(
244 "could not tell whether the {} hooks are installed — {}",
245 ctx.agent.label(),
246 unreadable.join("; ")
247 ),
248 );
249 }
250 Finding::new(
251 COMPONENT,
252 ID,
253 Severity::Error,
254 format!(
255 "{} hooks are not installed: sessions in this project are not traced",
256 ctx.agent.label()
257 ),
258 )
259}
260
261fn missing_git_hooks(root: &Path) -> Result<Option<String>, String> {
265 let hooks = root.join(".git").join("hooks");
266 let mut missing: Vec<&str> = Vec::new();
267 for (name, marker) in [
268 ("pre-push", PRE_PUSH_MARKER),
269 ("post-commit", POST_COMMIT_MARKER),
270 ] {
271 let path = hooks.join(name);
272 match std::fs::read(&path) {
273 Ok(bytes) if has_marker(&String::from_utf8_lossy(&bytes), marker) => {}
274 Ok(_) => missing.push(name),
275 Err(e) if e.kind() == std::io::ErrorKind::NotFound => missing.push(name),
276 Err(e) => return Err(format!("{}: {e}", path.display())),
277 }
278 }
279 Ok((!missing.is_empty()).then(|| missing.join(" and ")))
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use crate::agents::Workdir;
286 use std::fs;
287 use tempfile::TempDir;
288
289 struct Fixture {
290 repo: TempDir,
291 home: TempDir,
292 }
293
294 impl Fixture {
295 fn new() -> Self {
296 let repo = TempDir::new().unwrap();
297 let status = std::process::Command::new("git")
298 .args(["init", "-q"])
299 .current_dir(repo.path())
300 .status()
301 .unwrap();
302 assert!(status.success());
303 Fixture {
304 repo,
305 home: TempDir::new().unwrap(),
306 }
307 }
308
309 fn ctx(&self, agent: Agent) -> CheckContext {
310 CheckContext {
311 workdir: Workdir::checkout(self.repo.path()),
312 home: self.home.path().to_path_buf(),
313 codex_home: self.home.path().join(".codex"),
314 agent,
315 mode: crate::mode::TracingMode::Hooks,
316 server_url: Some("https://tv.example.com".to_string()),
317 credential: CredentialState::Present,
318 }
319 }
320
321 fn write(&self, rel: &str, content: &str) {
322 let path = self.repo.path().join(rel);
323 fs::create_dir_all(path.parent().unwrap()).unwrap();
324 fs::write(path, content).unwrap();
325 }
326
327 fn wire_config(&self) {
328 self.write(".visdom/tracing.toml", "server_url = \"https://tv\"\n");
329 }
330
331 fn wire_git_hooks(&self) {
332 self.write(
333 ".git/hooks/pre-push",
334 &format!("#!/bin/sh\n{PRE_PUSH_MARKER}\n"),
335 );
336 self.write(
337 ".git/hooks/post-commit",
338 &format!("#!/bin/sh\n{POST_COMMIT_MARKER}\n"),
339 );
340 }
341 }
342
343 const CLAUDE_HOOKS: &str = r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"tracevault stream --event stop"}]}]}}"#;
344 const CODEX_HOOKS: &str = r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"tracevault stream --event stop --agent codex"}]}]}}"#;
345
346 fn by_id<'a>(findings: &'a [Finding], id: &str) -> &'a Finding {
347 findings
348 .iter()
349 .find(|f| f.id == id)
350 .unwrap_or_else(|| panic!("no finding {id} in {findings:?}"))
351 }
352
353 fn is_init(finding: &Finding, agent: Agent, dir: &Path) -> bool {
354 matches!(&finding.fix, Some(Fix { action: FixAction::TracingInit { agent: a, dir: d }, .. })
355 if *a == agent && d == dir)
356 }
357
358 #[test]
359 fn fully_wired_repo_is_all_ok() {
360 let fx = Fixture::new();
361 fx.wire_config();
362 fx.wire_git_hooks();
363 fx.write(".claude/settings.local.json", CLAUDE_HOOKS);
364 let findings = check(&fx.ctx(Agent::ClaudeCode));
365 assert_eq!(findings.len(), 4, "{findings:?}");
366 for finding in &findings {
367 assert_eq!(finding.severity, Severity::Ok, "{finding:?}");
368 assert!(finding.fix.is_none());
369 }
370 }
371
372 #[test]
373 fn outside_repo_is_info_without_fix() {
374 let fx = Fixture::new();
375 let mut ctx = fx.ctx(Agent::ClaudeCode);
376 ctx.workdir = Workdir::plain(fx.home.path());
377 let findings = check(&ctx);
378 let ids: Vec<&str> = findings.iter().map(|f| f.id).collect();
379 assert_eq!(ids, ["tracing.auth", "tracing.repo"]);
380 let repo = by_id(&findings, "tracing.repo");
381 assert_eq!(repo.severity, Severity::Info);
382 assert!(repo.message.contains("not in a repository"));
383 assert!(findings.iter().all(|f| f.fix.is_none()));
384 }
385
386 #[test]
387 fn missing_agent_hooks_offers_init() {
388 let fx = Fixture::new();
389 fx.wire_config();
390 fx.wire_git_hooks();
391 let findings = check(&fx.ctx(Agent::ClaudeCode));
392 let hooks = by_id(&findings, "tracing.agent_hooks");
393 assert_eq!(hooks.severity, Severity::Error);
394 assert!(
395 is_init(hooks, Agent::ClaudeCode, fx.repo.path()),
396 "{hooks:?}"
397 );
398 assert!(hooks
399 .fix
400 .as_ref()
401 .unwrap()
402 .description
403 .contains("visdom trace init --agent claude-code"));
404 assert_eq!(by_id(&findings, "tracing.repo").severity, Severity::Ok);
405 }
406
407 #[test]
408 fn nothing_wired_offers_one_shared_init() {
409 let fx = Fixture::new();
410 let findings = check(&fx.ctx(Agent::ClaudeCode));
411 let fixes: Vec<&FixAction> = findings
412 .iter()
413 .filter_map(|f| f.fix.as_ref().map(|fix| &fix.action))
414 .collect();
415 assert_eq!(fixes.len(), 3, "repo, agent hooks, git hooks: {findings:?}");
416 assert!(fixes.iter().all(|a| *a == fixes[0]), "one init fixes all");
417 }
418
419 #[test]
420 fn global_claude_hooks_satisfy_agent_hooks() {
421 let fx = Fixture::new();
422 fs::create_dir_all(fx.home.path().join(".claude")).unwrap();
423 fs::write(fx.home.path().join(".claude/settings.json"), CLAUDE_HOOKS).unwrap();
424 let findings = check(&fx.ctx(Agent::ClaudeCode));
425 assert_eq!(
426 by_id(&findings, "tracing.agent_hooks").severity,
427 Severity::Ok
428 );
429 let repo = by_id(&findings, "tracing.repo");
431 assert_eq!(repo.severity, Severity::Ok);
432 assert!(repo.message.contains("global install"), "{repo:?}");
433 let git = by_id(&findings, "tracing.git_hooks");
435 assert_eq!(git.severity, Severity::Info);
436 assert!(git.fix.is_none());
437 assert!(findings.iter().all(|f| f.fix.is_none()), "{findings:?}");
438 }
439
440 #[test]
441 fn codex_checks_codex_files_not_claude() {
442 let fx = Fixture::new();
443 fx.wire_config();
444 fx.write(".claude/settings.json", CLAUDE_HOOKS);
445 let findings = check(&fx.ctx(Agent::Codex));
446 let hooks = by_id(&findings, "tracing.agent_hooks");
447 assert_eq!(hooks.severity, Severity::Error);
448 assert!(is_init(hooks, Agent::Codex, fx.repo.path()));
449
450 fx.write(".codex/hooks.json", CODEX_HOOKS);
451 let findings = check(&fx.ctx(Agent::Codex));
452 assert_eq!(
453 by_id(&findings, "tracing.agent_hooks").severity,
454 Severity::Ok
455 );
456
457 let other = Fixture::new();
459 other.write(".codex/hooks.json", CODEX_HOOKS);
460 let findings = check(&other.ctx(Agent::ClaudeCode));
461 assert_eq!(
462 by_id(&findings, "tracing.agent_hooks").severity,
463 Severity::Error
464 );
465 }
466
467 #[test]
468 fn global_codex_hooks_are_read_from_codex_home() {
469 let fx = Fixture::new();
470 fs::create_dir_all(fx.home.path().join(".codex")).unwrap();
471 fs::write(fx.home.path().join(".codex/hooks.json"), CODEX_HOOKS).unwrap();
472 let findings = check(&fx.ctx(Agent::Codex));
473 assert_eq!(
474 by_id(&findings, "tracing.agent_hooks").severity,
475 Severity::Ok
476 );
477 }
478
479 #[test]
480 fn unreadable_hook_file_is_unknown_without_fix() {
481 let fx = Fixture::new();
482 fx.wire_config();
483 fx.write(".claude/settings.json", "{ not json");
484 let findings = check(&fx.ctx(Agent::ClaudeCode));
485 let hooks = by_id(&findings, "tracing.agent_hooks");
486 assert_eq!(hooks.severity, Severity::Unknown);
487 assert!(hooks.fix.is_none());
488 assert!(hooks.message.contains("settings.json"), "{hooks:?}");
489 }
490
491 #[test]
492 fn missing_git_hooks_is_warn() {
493 let fx = Fixture::new();
494 fx.wire_config();
495 fx.write(".claude/settings.json", CLAUDE_HOOKS);
496 let findings = check(&fx.ctx(Agent::ClaudeCode));
497 let git = by_id(&findings, "tracing.git_hooks");
498 assert_eq!(git.severity, Severity::Warn);
499 assert!(
500 git.message.contains("pre-push and post-commit hooks"),
501 "{git:?}"
502 );
503 assert!(is_init(git, Agent::ClaudeCode, fx.repo.path()));
504
505 fx.write(".git/hooks/pre-push", "#!/bin/sh\nexit 0\n");
507 fx.write(
508 ".git/hooks/post-commit",
509 &format!("#!/bin/sh\n{POST_COMMIT_MARKER}\n"),
510 );
511 let findings = check(&fx.ctx(Agent::ClaudeCode));
512 let git = by_id(&findings, "tracing.git_hooks");
513 assert!(git.message.contains("git pre-push hook not"), "{git:?}");
514 }
515
516 #[test]
517 fn malformed_tracing_config_is_unknown_without_fix() {
518 let fx = Fixture::new();
519 fx.wire_git_hooks();
520 fx.write(".claude/settings.json", CLAUDE_HOOKS);
521 fx.write(".visdom/tracing.toml", "server_url = [truncated");
522 let findings = check(&fx.ctx(Agent::ClaudeCode));
523 let repo = by_id(&findings, "tracing.repo");
524 assert_eq!(repo.severity, Severity::Unknown, "{repo:?}");
525 assert!(repo.fix.is_none());
526 assert!(repo.message.contains("tracing.toml"), "{repo:?}");
527 }
528
529 #[test]
530 fn unreadable_git_hook_is_unknown_without_fix() {
531 let fx = Fixture::new();
532 fx.wire_config();
533 fx.wire_git_hooks();
534 fx.write(".claude/settings.json", CLAUDE_HOOKS);
535 fs::remove_file(fx.repo.path().join(".git/hooks/pre-push")).unwrap();
538 fs::create_dir(fx.repo.path().join(".git/hooks/pre-push")).unwrap();
539 let findings = check(&fx.ctx(Agent::ClaudeCode));
540 let git = by_id(&findings, "tracing.git_hooks");
541 assert_eq!(git.severity, Severity::Unknown, "{git:?}");
542 assert!(git.fix.is_none());
543 assert!(git.message.contains("pre-push"), "{git:?}");
544
545 fs::remove_dir(fx.repo.path().join(".git/hooks/pre-push")).unwrap();
547 let mut bytes = vec![0xff, 0xfe, b'\n'];
548 bytes.extend_from_slice(PRE_PUSH_MARKER.as_bytes());
549 fs::write(fx.repo.path().join(".git/hooks/pre-push"), bytes).unwrap();
550 let findings = check(&fx.ctx(Agent::ClaudeCode));
551 assert_eq!(by_id(&findings, "tracing.git_hooks").severity, Severity::Ok);
552 }
553
554 #[test]
557 fn linked_worktree_checks_the_primary_checkout() {
558 let fx = Fixture::new();
559 let worktree = TempDir::new().unwrap();
560 let mut ctx = fx.ctx(Agent::ClaudeCode);
561 ctx.workdir = Workdir {
562 start_dir: worktree.path().to_path_buf(),
563 checkout: Some(worktree.path().to_path_buf()),
564 primary: Some(fx.repo.path().to_path_buf()),
565 };
566
567 let findings = check(&ctx);
568 let hooks = by_id(&findings, "tracing.agent_hooks");
569 assert!(
570 is_init(hooks, Agent::ClaudeCode, fx.repo.path()),
571 "{hooks:?}"
572 );
573
574 fx.wire_config();
575 fx.wire_git_hooks();
576 fx.write(".claude/settings.local.json", CLAUDE_HOOKS);
577 let findings = check(&ctx);
578 assert!(
579 findings.iter().all(|f| f.severity == Severity::Ok),
580 "{findings:?}"
581 );
582 }
583
584 #[test]
585 fn no_credentials_is_error_with_login_fix() {
586 let fx = Fixture::new();
587 let mut ctx = fx.ctx(Agent::ClaudeCode);
588 ctx.credential = CredentialState::Missing;
589 let findings = check(&ctx);
590 let auth = by_id(&findings, "tracing.auth");
591 assert_eq!(auth.severity, Severity::Error);
592 assert_eq!(
593 auth.fix.as_ref().map(|f| &f.action),
594 Some(&FixAction::Login {
595 server_url: "https://tv.example.com".to_string()
596 })
597 );
598
599 ctx.server_url = None;
601 let findings = check(&ctx);
602 let auth = by_id(&findings, "tracing.auth");
603 assert_eq!(auth.severity, Severity::Error);
604 assert!(auth.fix.is_none());
605 assert!(auth.message.contains("visdom login --server-url <url>"));
606 }
607
608 #[test]
609 fn unreadable_credential_file_is_unknown_without_login_fix() {
610 let fx = Fixture::new();
611 let mut ctx = fx.ctx(Agent::ClaudeCode);
612 ctx.credential = CredentialState::Unreadable("/cfg/visdom/credentials.json".into());
613 let findings = check(&ctx);
614 let auth = by_id(&findings, "tracing.auth");
615 assert_eq!(auth.severity, Severity::Unknown);
616 assert!(auth.fix.is_none());
617 assert!(auth.message.contains("credentials.json"), "{auth:?}");
618 }
619
620 #[test]
621 fn unusable_credential_is_error_with_its_reason() {
622 let fx = Fixture::new();
623 let mut ctx = fx.ctx(Agent::ClaudeCode);
624 ctx.credential = CredentialState::Unusable("logged in to another server".to_string());
625 let findings = check(&ctx);
626 let auth = by_id(&findings, "tracing.auth");
627 assert_eq!(auth.severity, Severity::Error);
628 assert_eq!(auth.message, "logged in to another server");
629 assert!(auth.fix.is_none());
630 }
631
632 #[test]
635 fn api_key_env_counts_as_credential() {
636 let fx = Fixture::new();
637 let mut ctx = fx.ctx(Agent::ClaudeCode);
638 ctx.credential = CredentialState::Present;
639 ctx.server_url = None;
640 let findings = check(&ctx);
641 let auth = by_id(&findings, "tracing.auth");
642 assert_eq!(auth.severity, Severity::Ok);
643 assert!(auth.fix.is_none());
644 }
645
646 #[test]
647 fn the_setup_is_checked_the_same_in_gateway_mode() {
648 let fx = Fixture::new();
649 let hooks = check(&fx.ctx(Agent::ClaudeCode));
650 let mut ctx = fx.ctx(Agent::ClaudeCode);
651 ctx.mode = crate::mode::TracingMode::Gateway;
652 let gateway = check(&ctx);
653 let ids = |findings: &[Finding]| -> Vec<(&'static str, Severity)> {
654 findings.iter().map(|f| (f.id, f.severity)).collect()
655 };
656 assert_eq!(ids(&gateway), ids(&hooks));
657 assert!(!gateway.is_empty());
658 }
659}