1use crate::api_client::{ApiClient, GetMeError};
8use crate::config::TracevaultConfig;
9use crate::credentials::{Credential, Credentials};
10use crate::resolution::{
11 effective_project, git_remote_url, resolve_effective_project, ProjectResolveInputs,
12 ProjectSource,
13};
14use std::fs;
15use std::path::{Path, PathBuf};
16
17const ANSI_GREEN: &str = "\x1b[32m";
18const ANSI_RED: &str = "\x1b[31m";
19const ANSI_YELLOW: &str = "\x1b[33m";
20const ANSI_DIM: &str = "\x1b[2m";
21const ANSI_RESET: &str = "\x1b[0m";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26enum Level {
27 Ok,
28 Warn,
29 Error,
30 Skip,
33}
34
35#[derive(Debug)]
36struct Check {
37 label: String,
38 level: Level,
39 detail: String,
40}
41
42impl Check {
43 fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
44 Self {
45 label: label.into(),
46 level: Level::Ok,
47 detail: detail.into(),
48 }
49 }
50 fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
51 Self {
52 label: label.into(),
53 level: Level::Warn,
54 detail: detail.into(),
55 }
56 }
57 fn err(label: impl Into<String>, detail: impl Into<String>) -> Self {
58 Self {
59 label: label.into(),
60 level: Level::Error,
61 detail: detail.into(),
62 }
63 }
64 fn skip(label: impl Into<String>, detail: impl Into<String>) -> Self {
65 Self {
66 label: label.into(),
67 level: Level::Skip,
68 detail: detail.into(),
69 }
70 }
71}
72
73fn marker(l: Level) -> &'static str {
74 match l {
75 Level::Ok => "\x1b[32m✓\x1b[0m",
76 Level::Warn => "\x1b[33m!\x1b[0m",
77 Level::Error => "\x1b[31m✗\x1b[0m",
78 Level::Skip => "\x1b[2m·\x1b[0m",
79 }
80}
81
82fn print_section(title: &str, checks: &[Check]) {
83 println!("{ANSI_DIM}──{ANSI_RESET} {title}");
84 for c in checks {
85 if c.detail.is_empty() {
86 println!(" {} {}", marker(c.level), c.label);
87 } else {
88 println!(
89 " {} {:<32} {ANSI_DIM}{}{ANSI_RESET}",
90 marker(c.level),
91 c.label,
92 c.detail
93 );
94 }
95 }
96 println!();
97}
98
99struct AuthContext {
102 server_url: Option<String>,
103 credential: Option<Credential>,
106 source: &'static str, email_from_creds: Option<String>,
108 url_override_mismatch: Option<(String, String)>,
116}
117
118fn resolve_auth(config_server_url: Option<&str>, config_api_key: Option<&str>) -> AuthContext {
124 let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
128 let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();
129
130 if let Some(token) = env_key {
131 return AuthContext {
132 server_url: env_url.or_else(|| config_server_url.map(str::to_string)),
136 credential: Some(Credential::ApiKey(token)),
137 source: "env (TRACEVAULT_API_KEY)",
138 email_from_creds: None,
139 url_override_mismatch: None,
141 };
142 }
143
144 let creds = Credentials::load();
145 if let Some(c) = creds {
146 let source = match &c.auth {
147 Some(_) => "credentials file (Keycloak session)",
148 None => "credentials file (API key)",
149 };
150 let url_override_mismatch = env_url.filter(|env| {
154 c.credential().is_some() && !crate::credentials::same_server(&c.server_url, env)
155 });
156 return AuthContext {
157 server_url: Some(c.server_url.clone()),
158 credential: c.credential(),
159 source,
160 email_from_creds: Some(c.email).filter(|e| !e.is_empty()),
164 url_override_mismatch: url_override_mismatch.map(|env| (c.server_url, env)),
165 };
166 }
167
168 AuthContext {
172 server_url: env_url.or_else(|| config_server_url.map(str::to_string)),
173 credential: config_api_key.map(|k| Credential::ApiKey(k.to_string())),
174 source: if config_api_key.is_some() {
175 "project config (.tracevault/config.toml)"
176 } else {
177 "none"
178 },
179 email_from_creds: None,
180 url_override_mismatch: None,
181 }
182}
183
184async fn auth_checks(auth: &AuthContext, config_server_url: Option<&str>) -> Vec<Check> {
185 let mut out = Vec::new();
186
187 match (auth.credential.as_ref(), auth.server_url.as_ref()) {
188 (None, _) => {
189 out.push(Check::err(
190 "Logged in",
191 "no credentials found. Run `tracevault login --server-url <URL>`.",
192 ));
193 out.push(Check::skip("Token valid", "no token to check"));
194 return out;
195 }
196 (Some(_), None) => {
197 out.push(Check::err(
198 "Logged in",
199 "token found but no server URL (set TRACEVAULT_SERVER_URL)",
200 ));
201 out.push(Check::skip("Token valid", "no server URL to call"));
202 return out;
203 }
204 (Some(_), Some(url)) => {
205 out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
206 }
207 }
208
209 if let Some((file_url, env_url)) = &auth.url_override_mismatch {
213 out.push(Check::err(
214 "Server URL",
215 format!(
216 "TRACEVAULT_SERVER_URL is '{env_url}' but the saved login is for '{file_url}'. \
217 Commands will refuse to run rather than send that session's token to another \
218 instance. Unset TRACEVAULT_SERVER_URL, or run `tracevault login --server-url \
219 {env_url}`."
220 ),
221 ));
222 }
223
224 if let Some((file_url, config_url)) = crate::credentials::config_url_conflict(
232 config_server_url,
233 auth.server_url.as_deref(),
234 std::env::var("TRACEVAULT_SERVER_URL").is_ok(),
235 ) {
236 out.push(Check::warn(
237 "Server URL",
238 format!(
239 ".tracevault/config.toml pins '{config_url}' but the saved login is for \
240 '{file_url}'. The config URL is ignored — commands use '{file_url}'. Run \
241 `tracevault login --server-url {config_url}` to use the repo's instance, or \
242 remove `server_url` from .tracevault/config.toml."
243 ),
244 ));
245 }
246
247 let server_url = auth.server_url.as_ref().unwrap();
248 let client = ApiClient::with_credential(server_url, auth.credential.clone());
249 match client.get_me().await {
250 Ok(me) => {
251 let who = me.name.unwrap_or_else(|| me.email.clone());
252 let detail = match &me.role {
253 Some(role) => format!("{who} <{}> (role: {role})", me.email),
254 None => format!("{who} <{}>", me.email),
255 };
256 out.push(Check::ok("Token valid", detail));
257
258 if let Some(cached) = &auth.email_from_creds {
259 if cached != &me.email {
260 out.push(Check::warn(
261 "Credentials cache",
262 format!(
263 "cached email '{cached}' differs from server '{}' — re-run login",
264 me.email
265 ),
266 ));
267 }
268 }
269 }
270 Err(GetMeError::Unauthorized) => {
271 out.push(Check::err(
272 "Token valid",
273 "rejected by server (expired or revoked). Run `tracevault login` again.",
274 ));
275 }
276 Err(GetMeError::Forbidden(_)) => {
279 out.push(Check::err(
280 "Account authorized",
281 "the token is valid but this account has no `tracevault` grant in Control Plane — \
282 ask an administrator to grant it (or the `ai-tracing-admin` realm role).",
283 ));
284 }
285 Err(GetMeError::Network(msg)) => {
286 out.push(Check::warn(
287 "Server reachable",
288 format!("{msg} — cannot confirm token validity"),
289 ));
290 }
291 Err(GetMeError::Server(msg)) => {
292 out.push(Check::warn("Token valid", format!("server error: {msg}")));
293 }
294 }
295 out
296}
297
298fn project_checks(
303 project_root: &Path,
304 global_settings: Option<&Path>,
305 has_global: bool,
306 has_binding: bool,
307) -> (Vec<Check>, Option<TracevaultConfig>) {
308 let mut out = Vec::new();
309
310 let is_git = project_root.join(".git").exists();
311 if is_git {
312 out.push(Check::ok(
313 "Git repository",
314 project_root.display().to_string(),
315 ));
316 } else if has_global || has_binding {
317 out.push(Check::skip(
318 "Git repository",
319 "not a git repo (global/workspace mode)",
320 ));
321 } else {
322 out.push(Check::err(
323 "Git repository",
324 "current directory is not a git repo",
325 ));
326 }
327
328 let tv_present = project_root.join(".tracevault").exists();
329 out.push(tracevault_init_check(tv_present, has_global, has_binding));
330
331 let config = match TracevaultConfig::try_load(project_root) {
336 Ok(Some(c)) => {
337 let url = c.server_url.as_deref().unwrap_or("<unset>");
338 out.push(Check::ok("Project config", format!("server={url}")));
339 Some(c)
340 }
341 Ok(None) => {
342 if tv_present {
343 out.push(Check::warn(
344 "Project config",
345 "No .tracevault/config.toml — run `tracevault init`, or use workspace mode (`tracevault repo status`).",
346 ));
347 }
348 None
349 }
350 Err(e) => {
351 out.push(Check::err(
352 "Project config",
353 format!(".tracevault/config.toml malformed: {e}"),
354 ));
355 None
356 }
357 };
358
359 if tv_present {
360 out.push(git_hook_check(
362 project_root,
363 "pre-push",
364 "# tracevault:enforce",
365 ));
366 out.push(git_hook_check(
367 project_root,
368 "post-commit",
369 "# tracevault:post-commit",
370 ));
371 } else if has_global || has_binding {
372 out.push(Check::skip(
373 "Git hooks",
374 "not used in global/workspace mode",
375 ));
376 } else {
377 out.push(Check::skip(
378 "Git hooks",
379 "not installed (no .tracevault/ — run `tracevault init`)",
380 ));
381 }
382
383 out.push(claude_hook_check_in(
384 &project_root.join(".claude"),
385 global_settings,
386 ));
387
388 (out, config)
389}
390
391fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
392 let path = project_root.join(".git/hooks").join(name);
393 let label = format!("Git hook: {name}");
394 if !path.exists() {
395 return Check::warn(
396 label,
397 format!(".git/hooks/{name} missing — rerun `tracevault init`"),
398 );
399 }
400 match fs::read_to_string(&path) {
401 Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
402 Ok(_) => Check::warn(
403 label,
404 format!("{name} exists but no tracevault block — rerun `tracevault init`"),
405 ),
406 Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
407 }
408}
409
410fn settings_has_tracevault_hooks(contents: &str) -> bool {
412 contents.contains("tracevault stream")
413 || contents.contains("tracevault session-start")
414 || contents.contains("tracevault user-prompt")
415}
416
417enum SettingsHooks {
421 Present,
422 NoHooks,
423 Missing,
424 Unreadable(String),
425}
426
427fn read_settings_hooks(path: &Path) -> SettingsHooks {
428 match fs::read_to_string(path) {
429 Ok(s) if settings_has_tracevault_hooks(&s) => SettingsHooks::Present,
430 Ok(_) => SettingsHooks::NoHooks,
431 Err(e) if e.kind() == std::io::ErrorKind::NotFound => SettingsHooks::Missing,
432 Err(e) => SettingsHooks::Unreadable(e.to_string()),
433 }
434}
435
436fn global_hook_check_in(settings_path: &Path) -> Check {
440 match read_settings_hooks(settings_path) {
441 SettingsHooks::Present => Check::ok(
442 "Global install",
443 "hooks installed in ~/.claude/settings.json",
444 ),
445 SettingsHooks::NoHooks => Check::skip(
446 "Global install",
447 "~/.claude/settings.json has no tracevault hooks",
448 ),
449 SettingsHooks::Missing => Check::skip("Global install", "no ~/.claude/settings.json"),
450 SettingsHooks::Unreadable(e) => Check::warn(
451 "Global install",
452 format!("cannot read ~/.claude/settings.json: {e}"),
453 ),
454 }
455}
456
457fn claude_telemetry_check_in(
463 settings_path: &Path,
464 server_url: Option<&str>,
465 env: &crate::commands::claude_telemetry::Environment,
466) -> Check {
467 use crate::commands::claude_telemetry::{inspect, logs_endpoint, TelemetryState};
468 const LABEL: &str = "Claude Code telemetry";
469 let settings = match fs::read_to_string(settings_path) {
470 Ok(s) => match serde_json::from_str::<serde_json::Value>(&s) {
471 Ok(v) => v,
472 Err(e) => {
473 return Check::warn(LABEL, format!("cannot parse ~/.claude/settings.json: {e}"))
474 }
475 },
476 Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),
477 Err(e) => return Check::warn(LABEL, format!("cannot read ~/.claude/settings.json: {e}")),
478 };
479 let expected = server_url.map(logs_endpoint);
480 match inspect(&settings, env, expected.as_deref()) {
481 TelemetryState::Off => Check::skip(LABEL, "off (enable with `tracevault telemetry on`)"),
482 TelemetryState::Foreign { reasons, ours_too } => {
483 let detail = format!("exported elsewhere: {}", reasons.join("; "));
484 if ours_too {
485 Check::warn(
486 LABEL,
487 format!(
488 "{detail} — these exporters also receive TraceVault's otel-headers \
489 token; remove them or TraceVault's otelHeadersHelper"
490 ),
491 )
492 } else {
493 Check::skip(LABEL, format!("{detail} (see README: collector route)"))
494 }
495 }
496 TelemetryState::Ours { missing, .. } if !missing.is_empty() => Check::warn(
497 LABEL,
498 format!(
499 "incomplete ({} missing or changed): re-run `tracevault init --claude-telemetry`",
500 missing.join(", ")
501 ),
502 ),
503 TelemetryState::Ours { endpoint, .. } => {
504 let endpoint = endpoint.unwrap_or_default();
505 match expected {
506 Some(expected) if expected != endpoint => Check::warn(
507 LABEL,
508 format!(
509 "exports to {endpoint}, but you are logged in to {}: re-run \
510 `tracevault init --claude-telemetry`",
511 server_url.unwrap_or_default()
512 ),
513 ),
514 _ => Check::ok(LABEL, format!("exports cost to {endpoint}")),
515 }
516 }
517 }
518}
519
520fn with_telemetry_choice(mut check: Check, state: &crate::install_state::InstallState) -> Check {
524 match check.level {
525 Level::Skip if state.claude_telemetry_opt_out && check.detail.starts_with("off") => {
526 check.detail =
527 "off — you opted out, upgrades keep it off (`tracevault telemetry on` to enable)"
528 .to_string();
529 }
530 Level::Ok => {
531 if let Some(version) = &state.telemetry_auto_enabled {
532 check.detail.push_str(&format!(
533 " — turned on automatically by the upgrade to {version} \
534 (`tracevault telemetry off` to disable)"
535 ));
536 }
537 }
538 _ => {}
539 }
540 check
541}
542
543pub fn telemetry_status_line(server_url: Option<&str>) -> String {
546 let Some(settings) = dirs::home_dir().map(|h| h.join(".claude").join("settings.json")) else {
547 return "Claude Code telemetry: cannot determine home directory".to_string();
548 };
549 let check = with_telemetry_choice(
550 claude_telemetry_check_in(
551 &settings,
552 server_url,
553 &crate::commands::claude_telemetry::Environment::current(
554 settings.parent().unwrap_or(&settings),
555 ),
556 ),
557 &crate::install_state::load_in(&crate::config::tv_config_root()),
558 );
559 format!("{}: {}", check.label, check.detail)
560}
561
562const REPO_CLAUDE_SETTINGS: [&str; 2] = ["settings.json", "settings.local.json"];
565
566fn claude_hook_check_in(repo_claude_dir: &Path, global_settings: Option<&Path>) -> Check {
572 let repo: Vec<(&str, SettingsHooks)> = REPO_CLAUDE_SETTINGS
573 .iter()
574 .map(|name| (*name, read_settings_hooks(&repo_claude_dir.join(name))))
575 .collect();
576 if let Some((name, _)) = repo
577 .iter()
578 .find(|(_, h)| matches!(h, SettingsHooks::Present))
579 {
580 return Check::ok("Claude Code hooks", format!("registered in .claude/{name}"));
581 }
582 let global = global_settings.map(read_settings_hooks);
583 if matches!(global, Some(SettingsHooks::Present)) {
584 return Check::ok("Claude Code hooks", "via global install (see Installation)");
585 }
586 for (name, hooks) in &repo {
587 if let SettingsHooks::Unreadable(e) = hooks {
588 return Check::warn(
589 "Claude Code hooks",
590 format!("cannot read <repo>/.claude/{name}: {e}"),
591 );
592 }
593 }
594 if let Some(SettingsHooks::Unreadable(e)) = &global {
595 return Check::warn(
596 "Claude Code hooks",
597 format!("cannot read ~/.claude/settings.json: {e}"),
598 );
599 }
600 Check::warn(
601 "Claude Code hooks",
602 "not registered in <repo>/.claude/settings.json, <repo>/.claude/settings.local.json or ~/.claude/settings.json (capture will miss some events)",
603 )
604}
605
606fn tracevault_init_check(tv_dir_present: bool, has_global: bool, has_binding: bool) -> Check {
611 if tv_dir_present {
612 Check::ok("TraceVault initialized", ".tracevault/ present")
613 } else if has_global || has_binding {
614 Check::skip(
615 "TraceVault initialized",
616 "no per-repo .tracevault/ — global/workspace mode",
617 )
618 } else {
619 Check::err(
620 "TraceVault initialized",
621 "not set up: run `tracevault init` (per-repo) or `tracevault init --global`",
622 )
623 }
624}
625
626fn latest_active_binding_in(
632 sessions_dir: &Path,
633) -> Option<(String, crate::session_state::RepoBinding)> {
634 let mut sessions: Vec<(std::time::SystemTime, String)> = Vec::new();
635 for entry in fs::read_dir(sessions_dir).ok()?.flatten() {
636 let name = entry.file_name();
637 let name = name.to_str().unwrap_or("");
638 let Some(id) = name.strip_suffix(".toml") else {
639 continue;
640 };
641 if id.is_empty() {
642 continue;
643 }
644 let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
645 continue;
646 };
647 sessions.push((mtime, id.to_string()));
648 }
649 sessions.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); for (_, id) in sessions {
651 if let Some(b) = crate::session_state::load_from(sessions_dir, &id).active {
652 return Some((id, b));
653 }
654 }
655 None
656}
657
658fn workspace_repo_binding_check(
669 b: &crate::session_state::RepoBinding,
670 detail_suffix: &str,
671) -> Check {
672 let base = format!("repo {} via repo switch{detail_suffix}", b.repo_id);
673 if crate::commands::stream::binding_repo_id_is_valid(&b.repo_id) {
674 Check::ok("Workspace repo", base)
675 } else {
676 Check::warn(
677 "Workspace repo",
678 format!(
679 "{base} — this repo_id is not a valid id and will be dropped at capture time; run `tracevault repo switch <path>` to rewrite it"
680 ),
681 )
682 }
683}
684
685fn workspace_binding_check_in(
703 sessions_dir: &Path,
704 explicit_session_id: Option<&str>,
705) -> (Check, Option<crate::session_state::RepoBinding>) {
706 match explicit_session_id {
707 Some(id) => {
708 let state = crate::session_state::load_from(sessions_dir, id);
709 match state.active {
710 Some(b) => {
711 let check = workspace_repo_binding_check(&b, &format!(" (session {id})"));
712 (check, Some(b))
713 }
714 None => (
715 Check::skip(
716 "Workspace repo",
717 format!("session {id} has no active binding"),
718 ),
719 None,
720 ),
721 }
722 }
723 None => match latest_active_binding_in(sessions_dir) {
724 Some((id, b)) => {
725 let suffix = format!(
726 " — most recent session with a binding: {id} (may be another repo; pass --session-id to target one)"
727 );
728 let check = workspace_repo_binding_check(&b, &suffix);
729 (check, Some(b))
730 }
731 None => (
732 Check::skip("Workspace repo", "no active workspace binding found"),
733 None,
734 ),
735 },
736 }
737}
738
739type ProjectOutcome = Result<
750 Option<(crate::session_state::ProjectBinding, ProjectSource)>,
751 Box<dyn std::error::Error>,
752>;
753
754fn project_label(binding: &crate::session_state::ProjectBinding) -> &str {
763 if binding.project_name.is_empty() {
764 &binding.project_id
765 } else {
766 &binding.project_name
767 }
768}
769
770fn project_binding_check(outcome: &ProjectOutcome) -> Check {
828 match outcome {
829 Err(e) => Check::warn("Project", e.to_string()),
830 Ok(None) => Check::skip(
831 "Project",
832 "not bound — run `tracevault project switch --user \"<name>\"`, or `tracevault repo switch <path>` inside a checkout",
833 ),
834 Ok(Some((binding, source))) => {
835 let honored_tier = matches!(
843 source,
844 ProjectSource::ProjectFlag
845 | ProjectSource::Subagent
846 | ProjectSource::Env
847 | ProjectSource::SessionActive
848 | ProjectSource::UserDefault
849 );
850 let env_name_form = *source == ProjectSource::Env
856 && crate::commands::stream::env_project_binding().is_none();
857 let label = project_label(binding);
858 if env_name_form {
859 Check::warn(
860 "Project",
861 format!(
862 "{label} — {source}, resolved for display only: the capture path honours only the UUID form of TRACEVAULT_PROJECT, so a NAME is ignored there and attribution falls through to the next tier — export TRACEVAULT_PROJECT={} instead, or bind it with `tracevault project switch <name>`",
863 binding.project_id
864 ),
865 )
866 } else if !honored_tier {
867 Check::warn(
868 "Project",
869 format!(
870 "{label} — {source}, not used for attribution at capture time; set one explicitly with `tracevault project switch <name>` or --project"
871 ),
872 )
873 } else if binding.project_id.parse::<uuid::Uuid>().is_err() {
874 Check::warn(
875 "Project",
876 format!(
877 "{label} — {source}, but the saved project_id is not a valid id and will be dropped at capture time; run `tracevault project switch <name>` to rewrite it"
878 ),
879 )
880 } else {
881 Check::ok("Project", format!("{label} — {source}"))
882 }
883 }
884 }
885}
886
887fn unresolved_config_default_check(name: &str) -> Check {
900 Check::warn(
901 "Project default",
902 format!(
903 "configured default_project '{name}' could not be resolved (network error, or no matching project); even if it resolved, this tier is not used for attribution at capture time — set one with `tracevault project switch <name>` or --project instead"
904 ),
905 )
906}
907
908fn recording_check(
928 session_id: Option<&str>,
929 attribution: Option<&crate::commands::stream::Attribution>,
930) -> Option<Check> {
931 let id = session_id?;
932 if attribution.is_some() {
933 return None;
934 }
935 Some(Check::err(
936 "Recording",
937 format!(
938 "nothing will be recorded — session {id} is bound on neither the repo nor the \
939 project axis; run `tracevault project switch --user \"<name>\"` on a repo-less \
940 machine, or `tracevault repo switch <path>` inside a checkout"
941 ),
942 ))
943}
944
945fn checkout_recording_check(
965 attribution: Option<&crate::commands::stream::Attribution>,
966 config: Option<&TracevaultConfig>,
967) -> Check {
968 use crate::commands::stream::Attribution;
969 const LABEL: &str = "Recording";
970 let repo_id_problem = config.and_then(|c| match c.repo_id.as_deref() {
971 None => Some(".tracevault/config.toml has no repo_id".to_string()),
972 Some(id) if !crate::commands::stream::binding_repo_id_is_valid(id) => Some(format!(
973 ".tracevault/config.toml repo_id '{id}' is not a valid id"
974 )),
975 Some(_) => None,
976 });
977 match (attribution, repo_id_problem) {
978 (Some(Attribution::Repo { repo_id, .. }), _) => Check::ok(
979 LABEL,
980 format!("new sessions in this checkout record to repo {repo_id}"),
981 ),
982 (Some(Attribution::ProjectOnly { project_id }), Some(problem)) => Check::warn(
983 LABEL,
984 format!(
985 "{problem}: new sessions here record to project {project_id} only, not to this repo — run `tracevault sync` while logged in"
986 ),
987 ),
988 (Some(Attribution::ProjectOnly { project_id }), None) => Check::ok(
989 LABEL,
990 format!("new sessions in this checkout record to project {project_id}"),
991 ),
992 (None, Some(problem)) => Check::err(
993 LABEL,
994 format!(
995 "nothing will be recorded — {problem} and nothing else binds this checkout; run `tracevault sync` while logged in"
996 ),
997 ),
998 (None, None) => Check::warn(
999 LABEL,
1000 "no session named and nothing binds this checkout locally — a new session here is bound by its hooks to the repo of this checkout's origin remote if the server has it registered (otherwise run `tracevault sync` while logged in), or by `tracevault repo switch <path>`",
1001 ),
1002 }
1003}
1004
1005fn recording_attribution(
1025 sessions_dir: Option<&Path>,
1026 session_id: Option<&str>,
1027 cwd: &Path,
1028 config: Option<&TracevaultConfig>,
1029) -> (Option<crate::commands::stream::Attribution>, String) {
1030 let session = match (sessions_dir, session_id) {
1031 (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
1032 _ => crate::session_state::SessionState::default(),
1033 };
1034 let worktree = crate::paths::worktree_toplevel(cwd);
1035 let bound = config.and_then(crate::resolution::binding_from_config);
1036 let user_default_repo = crate::user_default::load();
1037 let stream_binding = crate::commands::stream::resolve_stream_binding(
1038 &session,
1039 &worktree,
1040 bound,
1041 user_default_repo,
1042 );
1043 let capture_pid = crate::commands::stream::capture_project(&session, Some(&worktree));
1044 let attribution =
1045 crate::commands::stream::attribution_for(stream_binding.as_ref(), capture_pid);
1046 (attribution, worktree)
1047}
1048
1049async fn resolve_name_via_client(
1073 client: &ApiClient,
1074 name: &str,
1075) -> Option<crate::session_state::ProjectBinding> {
1076 client.list_projects().await.ok().and_then(|items| {
1077 items
1078 .into_iter()
1079 .find(|p| p.name == name)
1080 .map(|p| crate::session_state::ProjectBinding {
1081 project_id: p.id.to_string(),
1082 project_name: p.name,
1083 updated_at: chrono::Utc::now().to_rfc3339(),
1084 forced_until: None,
1085 })
1086 })
1087}
1088
1089async fn online_project_outcome(
1090 client: &ApiClient,
1091 config_default_name: Option<&str>,
1092 project_session: &crate::session_state::SessionState,
1093 worktree: &str,
1094 user_default_project: Option<crate::session_state::ProjectBinding>,
1095 project_git_url: Option<&str>,
1096) -> (ProjectOutcome, Option<String>) {
1097 let mut config_default_unresolved = None;
1100 let config_default = match config_default_name {
1101 Some(name) => {
1102 let resolved = resolve_name_via_client(client, name).await;
1103 if resolved.is_none() {
1104 config_default_unresolved = Some(name.to_string());
1105 }
1106 resolved
1107 }
1108 None => None,
1109 };
1110 let env_project = match crate::commands::stream::env_project_binding() {
1119 Some(binding) => Some(binding),
1120 None => match std::env::var("TRACEVAULT_PROJECT").ok() {
1121 Some(raw) if !raw.trim().is_empty() => {
1122 resolve_name_via_client(client, raw.trim()).await
1123 }
1124 _ => None,
1125 },
1126 };
1127 let inputs = ProjectResolveInputs {
1128 project_flag: None,
1129 env_project,
1130 session: project_session,
1131 worktree_path: Some(worktree),
1132 config_default,
1133 };
1134 let outcome =
1135 resolve_effective_project(&inputs, user_default_project, project_git_url, client).await;
1136 (outcome, config_default_unresolved)
1137}
1138
1139fn offline_project_outcome(
1150 inputs: &ProjectResolveInputs,
1151 user_default_project: Option<crate::session_state::ProjectBinding>,
1152) -> ProjectOutcome {
1153 Ok(effective_project(inputs)
1154 .or_else(|| user_default_project.map(|b| (b, ProjectSource::UserDefault))))
1155}
1156
1157#[derive(Debug, Clone, PartialEq)]
1164enum RepoLookup {
1165 Workspace(String),
1168 Bound(String),
1170 MissingRepoId,
1174}
1175
1176fn server_repo_lookup(
1183 config: Option<&TracevaultConfig>,
1184 binding: Option<&crate::session_state::RepoBinding>,
1185) -> Option<RepoLookup> {
1186 if let Some(b) = binding {
1187 return Some(RepoLookup::Workspace(b.repo_id.clone()));
1188 }
1189 let config = config?;
1190 Some(match &config.repo_id {
1191 Some(id) => RepoLookup::Bound(id.clone()),
1192 None => RepoLookup::MissingRepoId,
1193 })
1194}
1195
1196fn session_repo_binding(
1202 session: &crate::session_state::SessionState,
1203 worktree: &str,
1204) -> Option<crate::session_state::RepoBinding> {
1205 crate::commands::stream::resolve_stream_binding(session, worktree, None, None)
1206}
1207
1208fn find_repo_by_id<'a>(
1212 repos: &'a [crate::api_client::RepoListItem],
1213 id: &str,
1214) -> Option<&'a crate::api_client::RepoListItem> {
1215 let id: uuid::Uuid = id.trim().parse().ok()?;
1216 repos.iter().find(|r| r.id == id)
1217}
1218
1219async fn server_repo_checks(
1220 project_root: &Path,
1221 auth: &AuthContext,
1222 config: Option<&TracevaultConfig>,
1223 binding: Option<&crate::session_state::RepoBinding>,
1224) -> Vec<Check> {
1225 let mut out = Vec::new();
1226
1227 let (id, source, bound_mode) = match server_repo_lookup(config, binding) {
1232 None => {
1233 out.push(Check::skip(
1234 "Repo registered on server",
1235 "not bound (need a project config.toml or a --session-id workspace binding)",
1236 ));
1237 return out;
1238 }
1239 Some(RepoLookup::MissingRepoId) => {
1240 out.push(Check::err(
1241 "Repo registered on server",
1242 ".tracevault/config.toml has no repo_id, so sessions here are not attributed to this repo — run `tracevault sync` while logged in to register the repo and write it",
1243 ));
1244 return out;
1245 }
1246 Some(RepoLookup::Workspace(id)) => (id, "session binding", false),
1247 Some(RepoLookup::Bound(id)) => (id, ".tracevault/config.toml", true),
1248 };
1249
1250 let (Some(credential), Some(server_url)) = (auth.credential.clone(), auth.server_url.as_ref())
1251 else {
1252 out.push(Check::skip(
1253 "Repo registered on server",
1254 format!("not authenticated (would look up repo id {id} from {source})"),
1255 ));
1256 return out;
1257 };
1258
1259 let client = ApiClient::with_credential(server_url, Some(credential));
1260 let repos = match client.list_repos().await {
1261 Ok(r) => r,
1262 Err(e) => {
1263 out.push(Check::warn(
1264 "Repo registered on server",
1265 format!("failed to list repos: {e}"),
1266 ));
1267 return out;
1268 }
1269 };
1270
1271 match find_repo_by_id(&repos, &id) {
1272 None => {
1273 out.push(Check::err(
1274 "Repo registered on server",
1275 format!("repo id {id} (from {source}) not found on the server. Run `tracevault sync` while logged in."),
1276 ));
1277 return out;
1278 }
1279 Some(r) => {
1280 out.push(Check::ok(
1281 "Repo registered on server",
1282 format!("id={} (from {source})", r.id),
1283 ));
1284 match r.clone_status.as_deref() {
1285 Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
1286 Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
1287 "Server-side clone",
1288 format!("{other} — analytics and code browser unavailable until it finishes"),
1289 )),
1290 Some("error") => out.push(Check::err(
1291 "Server-side clone",
1292 "error — check the repo settings page on the dashboard",
1293 )),
1294 Some(other) => out.push(Check::warn(
1295 "Server-side clone",
1296 format!("unknown status '{other}'"),
1297 )),
1298 None => out.push(Check::skip(
1299 "Server-side clone",
1300 "server did not report clone status",
1301 )),
1302 }
1303
1304 if bound_mode {
1305 let local_remote = git_remote_url(project_root);
1306 match (local_remote.as_deref(), r.github_url.as_deref()) {
1307 (Some(local), Some(remote))
1308 if normalize_remote(local) == normalize_remote(remote) =>
1309 {
1310 out.push(Check::ok("Remote URL matches", remote.to_string()));
1311 }
1312 (Some(local), Some(remote)) => out.push(Check::warn(
1313 "Remote URL matches",
1314 format!("local={local} vs server={remote} — run `tracevault sync`"),
1315 )),
1316 (Some(local), None) => out.push(Check::warn(
1317 "Remote URL matches",
1318 format!("server has no github_url; local={local}"),
1319 )),
1320 (None, _) => out.push(Check::warn(
1321 "Remote URL matches",
1322 "no local `origin` remote configured",
1323 )),
1324 }
1325 } else {
1326 out.push(Check::skip(
1327 "Remote URL matches",
1328 "n/a in workspace mode (bound by id)",
1329 ));
1330 }
1331 }
1332 }
1333
1334 out
1335}
1336
1337fn is_pending_queue_filename(name: &str) -> bool {
1346 crate::commands::flush::repo_id_from_pending_filename(name).is_some()
1347}
1348
1349fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
1359 let Ok(read) = fs::read_dir(session_dir) else {
1360 return 0;
1361 };
1362
1363 read.flatten()
1364 .filter(|entry| {
1365 entry
1366 .file_name()
1367 .to_str()
1368 .map(|name| {
1369 is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
1370 })
1371 .unwrap_or(false)
1372 })
1373 .map(|entry| {
1374 fs::read_to_string(entry.path())
1375 .unwrap_or_default()
1376 .lines()
1377 .filter(|l| !l.trim().is_empty())
1378 .count()
1379 })
1380 .sum()
1381}
1382
1383fn session_checks(project_root: &Path) -> Vec<Check> {
1384 let sessions_dir = project_root.join(".tracevault/sessions");
1385 if !sessions_dir.exists() {
1386 return vec![Check::skip(
1387 "Pending events",
1388 "no .tracevault/sessions/ here (project-local check; a detached worker's queue may live under its own working dir)",
1389 )];
1390 }
1391
1392 let include_legacy = TracevaultConfig::load(project_root)
1396 .and_then(|c| c.repo_id)
1397 .is_some();
1398
1399 let mut total_sessions = 0usize;
1400 let mut sessions_with_pending = 0usize;
1401 let mut pending_event_count = 0usize;
1402
1403 if let Ok(read) = fs::read_dir(&sessions_dir) {
1404 for entry in read.flatten() {
1405 if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
1406 continue;
1407 }
1408 total_sessions += 1;
1409 let count = count_pending_events(&entry.path(), include_legacy);
1410 if count > 0 {
1411 sessions_with_pending += 1;
1412 pending_event_count += count;
1413 }
1414 }
1415 }
1416
1417 vec![if sessions_with_pending == 0 {
1418 Check::ok(
1419 "Pending events",
1420 format!("{total_sessions} session(s), all synced (project-local)"),
1421 )
1422 } else {
1423 Check::warn(
1424 "Pending events",
1425 format!(
1426 "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
1427 ),
1428 )
1429 }]
1430}
1431
1432fn normalize_remote(url: &str) -> String {
1437 let trimmed = url
1438 .trim()
1439 .trim_end_matches('/')
1440 .trim_end_matches(".git")
1441 .to_string();
1442
1443 if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
1445 return format!("github.com/{rest}");
1446 }
1447 for p in ["https://", "http://"] {
1449 if let Some(rest) = trimmed.strip_prefix(p) {
1450 return rest.to_string();
1451 }
1452 }
1453 trimmed
1454}
1455
1456pub fn effective_session_id(arg: Option<String>, env: Option<String>) -> Option<String> {
1461 arg.filter(|s| !s.is_empty())
1462 .or_else(|| env.filter(|s| !s.is_empty()))
1463}
1464
1465pub async fn run_status(project_root: &Path, cwd: &Path, session_id: Option<&str>) -> i32 {
1466 let auth_config = TracevaultConfig::try_load(project_root).ok().flatten();
1472 let config_server_url = auth_config.as_ref().and_then(|c| c.server_url.as_deref());
1473 let auth = resolve_auth(
1474 config_server_url,
1475 auth_config.as_ref().and_then(|c| c.api_key.as_deref()),
1476 );
1477
1478 let global_settings: Option<PathBuf> =
1482 dirs::home_dir().map(|h| h.join(".claude").join("settings.json"));
1483 let sessions_dir = crate::session_state::sessions_dir();
1484
1485 let global_check = match global_settings.as_deref() {
1486 Some(p) => global_hook_check_in(p),
1487 None => Check::skip("Global install", "cannot determine home directory"),
1488 };
1489 let has_global = global_check.level == Level::Ok;
1490
1491 let (binding_check, binding) = match sessions_dir.as_deref() {
1494 Some(dir) => workspace_binding_check_in(dir, session_id),
1495 None => (
1496 Check::skip("Workspace repo", "cannot determine session state dir"),
1497 None,
1498 ),
1499 };
1500 let explicit_session = session_id.is_some();
1506 let has_binding = binding.is_some() && explicit_session;
1507
1508 let auth_checks_v = auth_checks(&auth, config_server_url).await;
1509 let telemetry_check = match global_settings.as_deref() {
1510 Some(p) => with_telemetry_choice(
1511 claude_telemetry_check_in(
1512 p,
1513 auth.server_url.as_deref(),
1514 &crate::commands::claude_telemetry::Environment::current(p.parent().unwrap_or(p)),
1515 ),
1516 &crate::install_state::load_in(&crate::config::tv_config_root()),
1517 ),
1518 None => Check::skip("Claude Code telemetry", "cannot determine home directory"),
1519 };
1520 let install_v = vec![global_check, telemetry_check];
1521 let (proj_checks_v, config) = project_checks(
1522 project_root,
1523 global_settings.as_deref(),
1524 has_global,
1525 has_binding,
1526 );
1527
1528 let (attribution, worktree) =
1534 recording_attribution(sessions_dir.as_deref(), session_id, cwd, config.as_ref());
1535
1536 let project_session = match (sessions_dir.as_deref(), session_id) {
1543 (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
1544 _ => crate::session_state::SessionState::default(),
1545 };
1546
1547 let config_default_name = config.as_ref().and_then(|c| c.default_project.clone());
1557 let user_default_project = crate::user_project_default::load();
1558 let project_git_url = git_remote_url(cwd);
1559 let (project_outcome, config_default_unresolved): (ProjectOutcome, Option<String>) =
1566 match (auth.credential.clone(), auth.server_url.as_ref()) {
1567 (Some(credential), Some(server_url)) => {
1568 let client = ApiClient::with_credential(server_url, Some(credential));
1569 online_project_outcome(
1570 &client,
1571 config_default_name.as_deref(),
1572 &project_session,
1573 &worktree,
1574 user_default_project,
1575 project_git_url.as_deref(),
1576 )
1577 .await
1578 }
1579 _ => {
1580 let inputs = ProjectResolveInputs {
1590 project_flag: None,
1591 env_project: crate::commands::stream::env_project_binding(),
1592 session: &project_session,
1593 worktree_path: Some(&worktree),
1594 config_default: None,
1595 };
1596 (offline_project_outcome(&inputs, user_default_project), None)
1597 }
1598 };
1599
1600 let mut attribution_v = Vec::new();
1601 match session_id {
1602 Some(_) => attribution_v.extend(recording_check(session_id, attribution.as_ref())),
1603 None => attribution_v.push(checkout_recording_check(
1606 attribution.as_ref(),
1607 config.as_ref(),
1608 )),
1609 }
1610 attribution_v.push(binding_check);
1611 attribution_v.push(project_binding_check(&project_outcome));
1612 if let Some(name) = config_default_unresolved {
1613 attribution_v.push(unresolved_config_default_check(&name));
1614 }
1615
1616 let server_binding = if explicit_session {
1620 session_repo_binding(&project_session, &worktree)
1621 } else {
1622 None
1623 };
1624 let server_checks_v = server_repo_checks(
1625 project_root,
1626 &auth,
1627 config.as_ref(),
1628 server_binding.as_ref(),
1629 )
1630 .await;
1631 let session_checks_v = session_checks(project_root);
1632
1633 let sections: Vec<(&str, Vec<Check>)> = vec![
1634 ("Authentication", auth_checks_v),
1635 ("Installation", install_v),
1636 ("Project", proj_checks_v),
1637 ("Attribution", attribution_v),
1638 ("Server repo", server_checks_v),
1639 ("Sessions", session_checks_v),
1640 ];
1641 for (title, checks) in §ions {
1642 print_section(title, checks);
1643 }
1644 let all: Vec<&Check> = sections.iter().flat_map(|(_, v)| v.iter()).collect();
1645
1646 let errors = all.iter().filter(|c| c.level == Level::Error).count();
1647 let warns = all.iter().filter(|c| c.level == Level::Warn).count();
1648
1649 match (errors, warns) {
1650 (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
1651 (0, w) => println!(
1652 "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
1653 if w == 1 { "" } else { "s" }
1654 ),
1655 (e, 0) => println!(
1656 "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
1657 if e == 1 { "" } else { "s" }
1658 ),
1659 (e, w) => println!(
1660 "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
1661 if e == 1 { "" } else { "s" },
1662 if w == 1 { "" } else { "s" }
1663 ),
1664 }
1665
1666 exit_code_for(&all)
1667}
1668
1669fn exit_code_for(checks: &[&Check]) -> i32 {
1674 if checks.iter().any(|c| c.level == Level::Error) {
1675 1
1676 } else {
1677 0
1678 }
1679}
1680
1681#[cfg(test)]
1682mod tests {
1683 use super::*;
1684
1685 #[test]
1686 fn normalize_remote_ssh_https_equal() {
1687 assert_eq!(
1688 normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
1689 normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
1690 );
1691 assert_eq!(
1692 normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
1693 "github.com/VirtusLab/visdom-ai-tracing"
1694 );
1695 }
1696
1697 #[test]
1698 fn normalize_remote_preserves_non_github() {
1699 assert_eq!(
1700 normalize_remote("git@gitlab.com:foo/bar.git"),
1701 "git@gitlab.com:foo/bar"
1702 );
1703 }
1704
1705 #[test]
1706 fn git_hook_check_missing_file_is_warning() {
1707 let dir = tempfile::tempdir().unwrap();
1708 let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1709 assert_eq!(check.level, Level::Warn);
1710 }
1711
1712 #[test]
1713 fn git_hook_check_with_marker_is_ok() {
1714 let dir = tempfile::tempdir().unwrap();
1715 let hooks = dir.path().join(".git/hooks");
1716 std::fs::create_dir_all(&hooks).unwrap();
1717 std::fs::write(
1718 hooks.join("pre-push"),
1719 "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
1720 )
1721 .unwrap();
1722 let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1723 assert_eq!(check.level, Level::Ok);
1724 }
1725
1726 #[test]
1727 fn git_hook_check_without_marker_is_warning() {
1728 let dir = tempfile::tempdir().unwrap();
1729 let hooks = dir.path().join(".git/hooks");
1730 std::fs::create_dir_all(&hooks).unwrap();
1731 std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
1732 let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1733 assert_eq!(check.level, Level::Warn);
1734 }
1735
1736 #[test]
1737 fn project_checks_errors_without_tracevault_dir_and_no_global_or_binding() {
1738 let dir = tempfile::tempdir().unwrap();
1739 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1740 let missing_global = dir.path().join("no-global.json");
1741 let (checks, cfg) =
1742 project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1743 assert!(cfg.is_none());
1744 assert!(checks
1745 .iter()
1746 .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
1747 let git_hooks = checks
1750 .iter()
1751 .find(|c| c.label == "Git hooks")
1752 .expect("Git hooks check present");
1753 assert_eq!(git_hooks.level, Level::Skip);
1754 assert!(
1755 !git_hooks.detail.contains("global/workspace mode"),
1756 "unconfigured git-hooks detail must not claim global/workspace mode: {}",
1757 git_hooks.detail
1758 );
1759 }
1760
1761 #[test]
1762 fn project_checks_no_tracevault_dir_is_not_error_in_global_mode() {
1763 let dir = tempfile::tempdir().unwrap();
1764 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1765 let missing_global = dir.path().join("no-global.json");
1766 let (checks, _) = project_checks(dir.path(), Some(missing_global.as_path()), true, false);
1767 let refs: Vec<&Check> = checks.iter().collect();
1768 assert_eq!(
1769 exit_code_for(&refs),
1770 0,
1771 "global mode must not force exit 1 on missing .tracevault/"
1772 );
1773 assert!(checks
1774 .iter()
1775 .any(|c| c.label == "TraceVault initialized" && c.level == Level::Skip));
1776 }
1777
1778 #[test]
1779 fn project_checks_warns_when_config_toml_missing() {
1780 let dir = tempfile::tempdir().unwrap();
1785 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1786 std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1787 let missing_global = dir.path().join("no-global.json");
1788 let (checks, cfg) =
1789 project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1790 assert!(cfg.is_none());
1791 let project_config_check = checks
1792 .iter()
1793 .find(|c| c.label == "Project config")
1794 .expect("Project config check present");
1795 assert_eq!(project_config_check.level, Level::Warn);
1796
1797 let refs: Vec<&Check> = checks.iter().collect();
1798 assert_eq!(
1799 exit_code_for(&refs),
1800 0,
1801 "a missing config.toml alone must not force a non-zero exit code"
1802 );
1803 }
1804
1805 #[test]
1806 fn project_checks_errors_on_malformed_config_toml() {
1807 let dir = tempfile::tempdir().unwrap();
1811 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1812 std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1813 std::fs::write(
1814 dir.path().join(".tracevault/config.toml"),
1815 "not valid toml {{{",
1816 )
1817 .unwrap();
1818 let missing_global = dir.path().join("no-global.json");
1819 let (checks, cfg) =
1820 project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1821 assert!(cfg.is_none());
1822 let project_config_check = checks
1823 .iter()
1824 .find(|c| c.label == "Project config")
1825 .expect("Project config check present");
1826 assert_eq!(project_config_check.level, Level::Error);
1827
1828 let refs: Vec<&Check> = checks.iter().collect();
1829 assert_eq!(exit_code_for(&refs), 1);
1830 }
1831
1832 #[test]
1833 fn exit_code_for_warn_only_is_zero() {
1834 let checks = [
1835 Check::warn("a", ""),
1836 Check::ok("b", ""),
1837 Check::skip("c", ""),
1838 ];
1839 let refs: Vec<&Check> = checks.iter().collect();
1840 assert_eq!(exit_code_for(&refs), 0);
1841 }
1842
1843 #[test]
1844 fn exit_code_for_any_error_is_one() {
1845 let checks = [
1846 Check::ok("a", ""),
1847 Check::err("b", ""),
1848 Check::warn("c", ""),
1849 ];
1850 let refs: Vec<&Check> = checks.iter().collect();
1851 assert_eq!(exit_code_for(&refs), 1);
1852 }
1853
1854 #[test]
1855 fn count_pending_events_sums_across_per_repo_queues() {
1856 let dir = tempfile::tempdir().unwrap();
1857 std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1858 std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
1859 std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
1860 assert_eq!(count_pending_events(dir.path(), false), 3);
1861 assert_eq!(count_pending_events(dir.path(), true), 3);
1862 }
1863
1864 #[test]
1865 fn count_pending_events_ignores_unrelated_files() {
1866 let dir = tempfile::tempdir().unwrap();
1867 std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
1868 std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
1869 assert_eq!(count_pending_events(dir.path(), false), 1);
1870 }
1871
1872 #[test]
1873 fn count_pending_events_zero_for_empty_dir() {
1874 let dir = tempfile::tempdir().unwrap();
1875 assert_eq!(count_pending_events(dir.path(), false), 0);
1876 assert_eq!(count_pending_events(dir.path(), true), 0);
1877 }
1878
1879 #[test]
1880 fn is_pending_queue_filename_matches_per_repo_only() {
1881 assert!(!is_pending_queue_filename("pending.jsonl"));
1882 assert!(is_pending_queue_filename(
1889 "pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"
1890 ));
1891 assert!(is_pending_queue_filename("pending-a.jsonl"));
1892 }
1893
1894 #[test]
1895 fn is_pending_queue_filename_rejects_lookalikes() {
1896 assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
1897 assert!(!is_pending_queue_filename("pending-.jsonl"));
1898 }
1899
1900 #[test]
1901 fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
1902 let dir = tempfile::tempdir().unwrap();
1903 std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
1904 assert_eq!(
1905 count_pending_events(dir.path(), false),
1906 0,
1907 "legacy pending.jsonl must not be counted when there's no bound repo_id"
1908 );
1909 assert_eq!(
1910 count_pending_events(dir.path(), true),
1911 2,
1912 "legacy pending.jsonl counts once a repo_id is bound"
1913 );
1914 }
1915
1916 #[test]
1917 fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
1918 let dir = tempfile::tempdir().unwrap();
1919 std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
1920 std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1921 assert_eq!(count_pending_events(dir.path(), false), 2);
1922 assert_eq!(count_pending_events(dir.path(), true), 3);
1923 }
1924
1925 #[test]
1926 fn count_pending_events_ignores_lookalike_filenames() {
1927 let dir = tempfile::tempdir().unwrap();
1928 std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
1929 std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
1930 assert_eq!(count_pending_events(dir.path(), false), 0);
1931 assert_eq!(count_pending_events(dir.path(), true), 0);
1932 }
1933
1934 #[test]
1935 fn settings_has_tracevault_hooks_detects_commands() {
1936 assert!(settings_has_tracevault_hooks(
1937 r#"{"hooks":{"PreToolUse":[{"hooks":[{"command":"tracevault stream --event pre"}]}]}}"#
1938 ));
1939 assert!(settings_has_tracevault_hooks(
1940 r#"{"command":"tracevault session-start"}"#
1941 ));
1942 assert!(settings_has_tracevault_hooks(
1943 r#"{"command":"tracevault user-prompt"}"#
1944 ));
1945 assert!(!settings_has_tracevault_hooks(
1946 r#"{"hooks":{"PreToolUse":[]}}"#
1947 ));
1948 assert!(!settings_has_tracevault_hooks("{}"));
1949 }
1950
1951 #[test]
1952 fn claude_telemetry_check_levels() {
1953 let dir = tempfile::tempdir().unwrap();
1954 let p = dir.path().join("settings.json");
1955 let server = Some("https://tv.example.com");
1956
1957 let c = claude_telemetry_check_in(
1959 &p,
1960 server,
1961 &crate::commands::claude_telemetry::Environment::default(),
1962 );
1963 assert_eq!(c.level, Level::Skip, "{c:?}");
1964
1965 crate::commands::claude_telemetry::install(
1966 dir.path(),
1967 "https://tv.example.com",
1968 &crate::commands::claude_telemetry::Environment::default(),
1969 )
1970 .unwrap();
1971 let c = claude_telemetry_check_in(
1972 &p,
1973 server,
1974 &crate::commands::claude_telemetry::Environment::default(),
1975 );
1976 assert_eq!(c.level, Level::Ok, "{c:?}");
1977 assert!(
1978 c.detail.contains("https://tv.example.com/otlp/v1/logs"),
1979 "{c:?}"
1980 );
1981
1982 let c = claude_telemetry_check_in(
1984 &p,
1985 Some("https://other.example.com"),
1986 &crate::commands::claude_telemetry::Environment::default(),
1987 );
1988 assert_eq!(c.level, Level::Warn, "{c:?}");
1989
1990 let env = crate::commands::claude_telemetry::tests::shell("OTEL_METRICS_EXPORTER", "otlp");
1992 let c = claude_telemetry_check_in(&p, server, &env);
1993 assert_eq!(c.level, Level::Warn, "{c:?}");
1994
1995 std::fs::write(&p, r#"{"env":{"OTEL_LOGS_EXPORTER":"console"}}"#).unwrap();
1997 let c = claude_telemetry_check_in(
1998 &p,
1999 server,
2000 &crate::commands::claude_telemetry::Environment::default(),
2001 );
2002 assert_eq!(c.level, Level::Skip, "{c:?}");
2003 assert!(c.detail.contains("exported elsewhere"), "{c:?}");
2004
2005 std::fs::write(&p, "{not json").unwrap();
2006 assert_eq!(
2007 claude_telemetry_check_in(
2008 &p,
2009 server,
2010 &crate::commands::claude_telemetry::Environment::default()
2011 )
2012 .level,
2013 Level::Warn
2014 );
2015 }
2016
2017 #[test]
2018 fn global_hook_check_ok_when_present() {
2019 let dir = tempfile::tempdir().unwrap();
2020 let p = dir.path().join("settings.json");
2021 std::fs::write(
2022 &p,
2023 r#"{"hooks":{"SessionStart":[{"hooks":[{"command":"tracevault session-start"}]}]}}"#,
2024 )
2025 .unwrap();
2026 assert_eq!(global_hook_check_in(&p).level, Level::Ok);
2027 }
2028
2029 #[test]
2030 fn global_hook_check_skip_when_absent_or_no_hooks() {
2031 let dir = tempfile::tempdir().unwrap();
2032 let missing = dir.path().join("settings.json");
2033 assert_eq!(global_hook_check_in(&missing).level, Level::Skip);
2034 let empty = dir.path().join("empty.json");
2035 std::fs::write(&empty, "{}").unwrap();
2036 assert_eq!(global_hook_check_in(&empty).level, Level::Skip);
2037 }
2038
2039 #[test]
2040 fn global_hook_check_warns_when_unreadable() {
2041 let dir = tempfile::tempdir().unwrap();
2044 let as_dir = dir.path().join("settings.json");
2045 std::fs::create_dir(&as_dir).unwrap();
2046 let check = global_hook_check_in(&as_dir);
2047 assert_eq!(check.level, Level::Warn);
2048 assert!(
2049 check.detail.contains("cannot read"),
2050 "detail: {}",
2051 check.detail
2052 );
2053 }
2054
2055 #[test]
2056 fn claude_hook_check_ok_from_global_only() {
2057 let dir = tempfile::tempdir().unwrap();
2058 let repo = dir.path().join(".claude"); let global = dir.path().join("global-settings.json");
2060 std::fs::write(&global, r#"{"command":"tracevault stream"}"#).unwrap();
2061 let c = claude_hook_check_in(&repo, Some(global.as_path()));
2062 assert_eq!(c.level, Level::Ok);
2063 assert!(
2064 c.detail.to_lowercase().contains("global") || c.detail.contains("~/.claude"),
2065 "detail: {}",
2066 c.detail
2067 );
2068 }
2069
2070 #[test]
2071 fn claude_hook_check_ok_from_repo() {
2072 let dir = tempfile::tempdir().unwrap();
2073 let repo = dir.path().join(".claude");
2074 std::fs::create_dir(&repo).unwrap();
2075 std::fs::write(
2076 repo.join("settings.json"),
2077 r#"{"command":"tracevault stream"}"#,
2078 )
2079 .unwrap();
2080 let global = dir.path().join("global-settings.json"); let c = claude_hook_check_in(&repo, Some(global.as_path()));
2082 assert_eq!(c.level, Level::Ok);
2083 assert!(
2084 c.detail.contains(".claude/settings.json"),
2085 "detail: {}",
2086 c.detail
2087 );
2088 }
2089
2090 #[test]
2091 fn claude_hook_check_ok_from_repo_local_settings() {
2092 let dir = tempfile::tempdir().unwrap();
2095 let repo = dir.path().join(".claude");
2096 std::fs::create_dir(&repo).unwrap();
2097 std::fs::write(
2098 repo.join("settings.local.json"),
2099 r#"{"command":"tracevault stream"}"#,
2100 )
2101 .unwrap();
2102 let global = dir.path().join("global-settings.json"); let c = claude_hook_check_in(&repo, Some(global.as_path()));
2104 assert_eq!(c.level, Level::Ok);
2105 assert!(
2106 c.detail.contains(".claude/settings.local.json"),
2107 "detail: {}",
2108 c.detail
2109 );
2110 }
2111
2112 #[test]
2113 fn claude_hook_check_local_settings_win_over_hookless_shared() {
2114 let dir = tempfile::tempdir().unwrap();
2117 let repo = dir.path().join(".claude");
2118 std::fs::create_dir(&repo).unwrap();
2119 std::fs::write(repo.join("settings.json"), r#"{"permissions":{}}"#).unwrap();
2120 std::fs::write(
2121 repo.join("settings.local.json"),
2122 r#"{"command":"tracevault session-start"}"#,
2123 )
2124 .unwrap();
2125 assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
2126 }
2127
2128 #[test]
2129 fn claude_hook_check_no_global_path_uses_repo_only() {
2130 let dir = tempfile::tempdir().unwrap();
2133 let repo = dir.path().join(".claude");
2134 std::fs::create_dir(&repo).unwrap();
2135 std::fs::write(
2136 repo.join("settings.json"),
2137 r#"{"command":"tracevault stream"}"#,
2138 )
2139 .unwrap();
2140 assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
2141
2142 let missing = dir.path().join("nope");
2143 assert_eq!(claude_hook_check_in(&missing, None).level, Level::Warn);
2144 }
2145
2146 #[test]
2147 fn claude_hook_check_warn_when_neither() {
2148 let dir = tempfile::tempdir().unwrap();
2149 let c = claude_hook_check_in(
2150 &dir.path().join(".claude"),
2151 Some(dir.path().join("b.json").as_path()),
2152 );
2153 assert_eq!(c.level, Level::Warn);
2154 assert!(
2155 c.detail.contains("settings.local.json"),
2156 "detail: {}",
2157 c.detail
2158 );
2159 }
2160
2161 #[test]
2162 fn claude_hook_check_warns_when_repo_settings_unreadable() {
2163 let dir = tempfile::tempdir().unwrap();
2164 let repo = dir.path().join(".claude");
2165 std::fs::create_dir_all(repo.join("settings.local.json")).unwrap();
2167 let global = dir.path().join("global.json"); let c = claude_hook_check_in(&repo, Some(global.as_path()));
2169 assert_eq!(c.level, Level::Warn);
2170 assert!(c.detail.contains("cannot read"), "detail: {}", c.detail);
2171 assert!(
2172 c.detail.contains("settings.local.json"),
2173 "detail: {}",
2174 c.detail
2175 );
2176 }
2177
2178 #[test]
2179 fn tracevault_init_check_severity_matrix() {
2180 assert_eq!(tracevault_init_check(true, false, false).level, Level::Ok); assert_eq!(tracevault_init_check(false, true, false).level, Level::Skip); assert_eq!(tracevault_init_check(false, false, true).level, Level::Skip); assert_eq!(tracevault_init_check(false, true, true).level, Level::Skip);
2184 assert_eq!(
2185 tracevault_init_check(false, false, false).level,
2186 Level::Error
2187 ); }
2189
2190 #[test]
2191 fn workspace_binding_explicit_id_with_binding_is_ok() {
2192 let dir = tempfile::tempdir().unwrap();
2193 let st = crate::session_state::SessionState {
2194 active: Some(crate::session_state::RepoBinding {
2195 repo_id: "11111111-1111-4111-8111-111111111111".into(),
2196 git_url: None,
2197 remote_id: None,
2198 codebase_name: None,
2199 updated_at: "t".into(),
2200 }),
2201 ..Default::default()
2202 };
2203 std::fs::write(
2204 dir.path().join("sess-9.toml"),
2205 toml::to_string(&st).unwrap(),
2206 )
2207 .unwrap();
2208 let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-9"));
2209 assert_eq!(check.level, Level::Ok);
2210 assert!(
2211 check
2212 .detail
2213 .contains("11111111-1111-4111-8111-111111111111"),
2214 "detail: {}",
2215 check.detail
2216 );
2217 assert_eq!(
2218 binding.unwrap().repo_id,
2219 "11111111-1111-4111-8111-111111111111"
2220 );
2221 }
2222
2223 #[test]
2224 fn workspace_binding_explicit_id_without_binding_is_skip() {
2225 let dir = tempfile::tempdir().unwrap();
2229 std::fs::write(
2230 dir.path().join("sess-empty.toml"),
2231 toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
2232 )
2233 .unwrap();
2234 let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-empty"));
2235 assert_eq!(check.level, Level::Skip);
2236 assert!(binding.is_none());
2237 }
2238
2239 #[test]
2240 fn workspace_binding_no_id_empty_dir_is_skip() {
2241 let dir = tempfile::tempdir().unwrap();
2242 let (check, binding) = workspace_binding_check_in(dir.path(), None);
2243 assert_eq!(check.level, Level::Skip);
2244 assert!(binding.is_none());
2245 }
2246
2247 #[test]
2248 fn workspace_binding_no_id_scans_latest() {
2249 let dir = tempfile::tempdir().unwrap();
2250 let older = crate::session_state::SessionState {
2252 active: Some(crate::session_state::RepoBinding {
2253 repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
2254 git_url: None,
2255 remote_id: None,
2256 codebase_name: None,
2257 updated_at: "t".into(),
2258 }),
2259 ..Default::default()
2260 };
2261 std::fs::write(
2262 dir.path().join("old.toml"),
2263 toml::to_string(&older).unwrap(),
2264 )
2265 .unwrap();
2266 std::thread::sleep(std::time::Duration::from_millis(20));
2268 let newer = crate::session_state::SessionState {
2269 active: Some(crate::session_state::RepoBinding {
2270 repo_id: "bbbbbbbb-2222-4222-8222-222222222222".into(),
2271 git_url: None,
2272 remote_id: None,
2273 codebase_name: None,
2274 updated_at: "t".into(),
2275 }),
2276 ..Default::default()
2277 };
2278 std::fs::write(
2279 dir.path().join("new.toml"),
2280 toml::to_string(&newer).unwrap(),
2281 )
2282 .unwrap();
2283 let (check, binding) = workspace_binding_check_in(dir.path(), None);
2284 assert_eq!(check.level, Level::Ok);
2285 assert_eq!(
2286 binding.unwrap().repo_id,
2287 "bbbbbbbb-2222-4222-8222-222222222222",
2288 "must pick the most-recently-modified session"
2289 );
2290 }
2291
2292 #[test]
2293 fn workspace_binding_scan_skips_newest_without_binding() {
2294 let dir = tempfile::tempdir().unwrap();
2297 let with_binding = crate::session_state::SessionState {
2298 active: Some(crate::session_state::RepoBinding {
2299 repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
2300 git_url: None,
2301 remote_id: None,
2302 codebase_name: None,
2303 updated_at: "t".into(),
2304 }),
2305 ..Default::default()
2306 };
2307 std::fs::write(
2308 dir.path().join("older.toml"),
2309 toml::to_string(&with_binding).unwrap(),
2310 )
2311 .unwrap();
2312 std::thread::sleep(std::time::Duration::from_millis(20));
2313 std::fs::write(
2315 dir.path().join("newest.toml"),
2316 toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
2317 )
2318 .unwrap();
2319 let (check, binding) = workspace_binding_check_in(dir.path(), None);
2320 assert_eq!(check.level, Level::Ok);
2321 assert_eq!(
2322 binding.unwrap().repo_id,
2323 "aaaaaaaa-1111-4111-8111-111111111111"
2324 );
2325 }
2326
2327 #[test]
2328 fn workspace_binding_scan_no_active_binding_is_skip_not_warn() {
2329 let dir = tempfile::tempdir().unwrap();
2332 std::fs::write(
2333 dir.path().join("stray.toml"),
2334 toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
2335 )
2336 .unwrap();
2337 let (check, binding) = workspace_binding_check_in(dir.path(), None);
2338 assert_eq!(check.level, Level::Skip);
2339 assert!(binding.is_none());
2340 }
2341
2342 #[test]
2343 fn workspace_binding_explicit_id_malformed_repo_id_is_warn_not_ok() {
2344 let dir = tempfile::tempdir().unwrap();
2349 let st = crate::session_state::SessionState {
2350 active: Some(crate::session_state::RepoBinding {
2351 repo_id: "not-a-uuid".into(),
2352 git_url: None,
2353 remote_id: None,
2354 codebase_name: None,
2355 updated_at: "t".into(),
2356 }),
2357 ..Default::default()
2358 };
2359 std::fs::write(
2360 dir.path().join("sess-bad.toml"),
2361 toml::to_string(&st).unwrap(),
2362 )
2363 .unwrap();
2364 let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-bad"));
2365 assert_eq!(check.level, Level::Warn);
2366 assert!(
2367 check.detail.contains("not a valid id"),
2368 "detail: {}",
2369 check.detail
2370 );
2371 assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
2374 }
2375
2376 #[test]
2377 fn workspace_binding_scan_malformed_repo_id_is_warn_not_ok() {
2378 let dir = tempfile::tempdir().unwrap();
2381 let st = crate::session_state::SessionState {
2382 active: Some(crate::session_state::RepoBinding {
2383 repo_id: "not-a-uuid".into(),
2384 git_url: None,
2385 remote_id: None,
2386 codebase_name: None,
2387 updated_at: "t".into(),
2388 }),
2389 ..Default::default()
2390 };
2391 std::fs::write(
2392 dir.path().join("sess-bad.toml"),
2393 toml::to_string(&st).unwrap(),
2394 )
2395 .unwrap();
2396 let (check, binding) = workspace_binding_check_in(dir.path(), None);
2397 assert_eq!(check.level, Level::Warn);
2398 assert!(
2399 check.detail.contains("not a valid id"),
2400 "detail: {}",
2401 check.detail
2402 );
2403 assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
2404 }
2405
2406 fn repo_item(id: &str, name: &str) -> crate::api_client::RepoListItem {
2407 crate::api_client::RepoListItem {
2408 id: id.parse().unwrap(),
2409 name: name.to_string(),
2410 github_url: None,
2411 clone_status: None,
2412 }
2413 }
2414
2415 fn workspace_binding(id: &str) -> crate::session_state::RepoBinding {
2416 crate::session_state::RepoBinding {
2417 repo_id: id.into(),
2418 git_url: None,
2419 remote_id: None,
2420 codebase_name: None,
2421 updated_at: "t".into(),
2422 }
2423 }
2424
2425 #[test]
2426 fn find_repo_by_id_hits_by_id_not_name() {
2427 let id = "11111111-1111-4111-8111-111111111111";
2428 let repos = vec![repo_item(id, "myrepo")];
2429 assert_eq!(find_repo_by_id(&repos, id).unwrap().name, "myrepo");
2430 assert!(find_repo_by_id(&repos, &id.to_uppercase()).is_some());
2432 }
2433
2434 #[test]
2435 fn find_repo_by_id_ignores_same_named_repo() {
2436 let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
2439 assert!(find_repo_by_id(&repos, "22222222-2222-4222-8222-222222222222").is_none());
2440 assert!(find_repo_by_id(&repos, "myrepo").is_none());
2441 }
2442
2443 #[test]
2444 fn server_repo_lookup_uses_config_repo_id() {
2445 let config = TracevaultConfig {
2446 repo_id: Some("rid-config".into()),
2447 ..Default::default()
2448 };
2449 assert_eq!(
2450 server_repo_lookup(Some(&config), None),
2451 Some(RepoLookup::Bound("rid-config".into()))
2452 );
2453 }
2454
2455 #[test]
2456 fn server_repo_lookup_config_without_repo_id_is_missing() {
2457 let config = TracevaultConfig::default();
2460 assert_eq!(
2461 server_repo_lookup(Some(&config), None),
2462 Some(RepoLookup::MissingRepoId)
2463 );
2464 }
2465
2466 #[test]
2467 fn server_repo_lookup_session_binding_wins_over_config() {
2468 let config = TracevaultConfig::default();
2471 let b = workspace_binding("rid-session");
2472 assert_eq!(
2473 server_repo_lookup(Some(&config), Some(&b)),
2474 Some(RepoLookup::Workspace("rid-session".into()))
2475 );
2476 assert_eq!(
2477 server_repo_lookup(None, Some(&b)),
2478 Some(RepoLookup::Workspace("rid-session".into()))
2479 );
2480 }
2481
2482 #[test]
2483 fn server_repo_lookup_none_when_neither() {
2484 assert!(server_repo_lookup(None, None).is_none());
2485 }
2486
2487 fn unauthenticated() -> AuthContext {
2488 AuthContext {
2489 server_url: None,
2490 credential: None,
2491 source: "none",
2492 email_from_creds: None,
2493 url_override_mismatch: None,
2494 }
2495 }
2496
2497 #[tokio::test]
2498 async fn server_repo_checks_missing_repo_id_is_error_before_login() {
2499 let dir = tempfile::tempdir().unwrap();
2502 let config = TracevaultConfig::default();
2503 let checks = server_repo_checks(dir.path(), &unauthenticated(), Some(&config), None).await;
2504 assert_eq!(checks.len(), 1);
2505 assert_eq!(checks[0].level, Level::Error);
2506 assert!(
2507 checks[0].detail.contains("no repo_id"),
2508 "detail: {}",
2509 checks[0].detail
2510 );
2511 }
2512
2513 #[tokio::test]
2514 async fn server_repo_checks_with_repo_id_but_no_login_is_skip() {
2515 let dir = tempfile::tempdir().unwrap();
2516 let config = TracevaultConfig {
2517 repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
2518 ..Default::default()
2519 };
2520 let checks = server_repo_checks(dir.path(), &unauthenticated(), Some(&config), None).await;
2521 assert_eq!(checks.len(), 1);
2522 assert_eq!(checks[0].level, Level::Skip);
2523 assert!(
2524 checks[0]
2525 .detail
2526 .contains("22222222-2222-4222-8222-222222222222"),
2527 "detail: {}",
2528 checks[0].detail
2529 );
2530 }
2531
2532 #[test]
2533 fn session_repo_binding_prefers_subagent_override_like_the_hook() {
2534 let mut session = crate::session_state::SessionState {
2537 active: Some(workspace_binding("11111111-1111-4111-8111-111111111111")),
2538 ..Default::default()
2539 };
2540 session.subagents.insert(
2541 "/wt/sub".into(),
2542 workspace_binding("33333333-3333-4333-8333-333333333333"),
2543 );
2544 assert_eq!(
2545 session_repo_binding(&session, "/wt/sub").unwrap().repo_id,
2546 "33333333-3333-4333-8333-333333333333"
2547 );
2548 assert_eq!(
2549 session_repo_binding(&session, "/wt/other").unwrap().repo_id,
2550 "11111111-1111-4111-8111-111111111111"
2551 );
2552 assert!(session_repo_binding(&Default::default(), "/wt/sub").is_none());
2553 }
2554
2555 fn checkout_verdict(config: Option<&TracevaultConfig>) -> Check {
2559 let cwd = tempfile::tempdir().unwrap();
2560 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), config);
2561 checkout_recording_check(attribution.as_ref(), config)
2562 }
2563
2564 #[test]
2565 fn checkout_recording_config_without_repo_id_is_error() {
2566 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2569 let cfg_tmp = tempfile::tempdir().unwrap();
2570 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2571 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2572 _guard.set("HOME", cfg_tmp.path());
2573 _guard.remove("TRACEVAULT_PROJECT");
2574
2575 let check = checkout_verdict(Some(&TracevaultConfig::default()));
2576 assert_eq!(check.level, Level::Error);
2577 assert!(
2578 check.detail.contains("no repo_id"),
2579 "detail: {}",
2580 check.detail
2581 );
2582 assert!(
2583 check.detail.contains("tracevault sync"),
2584 "detail: {}",
2585 check.detail
2586 );
2587 }
2588
2589 #[test]
2590 fn checkout_recording_config_with_invalid_repo_id_is_error() {
2591 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2592 let cfg_tmp = tempfile::tempdir().unwrap();
2593 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2594 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2595 _guard.set("HOME", cfg_tmp.path());
2596 _guard.remove("TRACEVAULT_PROJECT");
2597
2598 let config = TracevaultConfig {
2599 repo_id: Some("not-a-uuid".into()),
2600 ..Default::default()
2601 };
2602 let check = checkout_verdict(Some(&config));
2603 assert_eq!(check.level, Level::Error);
2604 assert!(
2605 check.detail.contains("not a valid id"),
2606 "detail: {}",
2607 check.detail
2608 );
2609 }
2610
2611 #[test]
2612 fn checkout_recording_config_with_repo_id_is_ok() {
2613 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2614 let cfg_tmp = tempfile::tempdir().unwrap();
2615 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2616 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2617 _guard.set("HOME", cfg_tmp.path());
2618 _guard.remove("TRACEVAULT_PROJECT");
2619
2620 let config = TracevaultConfig {
2621 repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
2622 ..Default::default()
2623 };
2624 let check = checkout_verdict(Some(&config));
2625 assert_eq!(check.level, Level::Ok);
2626 assert!(
2627 check
2628 .detail
2629 .contains("22222222-2222-4222-8222-222222222222"),
2630 "detail: {}",
2631 check.detail
2632 );
2633 }
2634
2635 #[test]
2636 fn checkout_recording_config_without_repo_id_but_user_project_is_warn() {
2637 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2640 let cfg_tmp = tempfile::tempdir().unwrap();
2641 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2642 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2643 _guard.set("HOME", cfg_tmp.path());
2644 _guard.remove("TRACEVAULT_PROJECT");
2645 crate::user_project_default::save(&project_binding(
2646 &uuid::Uuid::from_u128(7).to_string(),
2647 "p",
2648 ))
2649 .unwrap();
2650
2651 let check = checkout_verdict(Some(&TracevaultConfig::default()));
2652 assert_eq!(check.level, Level::Warn);
2653 assert!(check.detail.contains("project"), "detail: {}", check.detail);
2654 }
2655
2656 #[test]
2657 fn checkout_recording_user_default_repo_without_config_is_ok() {
2658 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2659 let cfg_tmp = tempfile::tempdir().unwrap();
2660 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2661 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2662 _guard.set("HOME", cfg_tmp.path());
2663 _guard.remove("TRACEVAULT_PROJECT");
2664 crate::user_default::save(&workspace_binding("11111111-1111-4111-8111-111111111111"))
2665 .unwrap();
2666
2667 assert_eq!(checkout_verdict(None).level, Level::Ok);
2668 }
2669
2670 #[test]
2671 fn checkout_recording_nothing_bound_without_config_is_warn() {
2672 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2675 let cfg_tmp = tempfile::tempdir().unwrap();
2676 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2677 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2678 _guard.set("HOME", cfg_tmp.path());
2679 _guard.remove("TRACEVAULT_PROJECT");
2680
2681 let check = checkout_verdict(None);
2682 assert_eq!(check.level, Level::Warn);
2683 assert!(
2685 check.detail.contains("origin remote") && check.detail.contains("tracevault sync"),
2686 "detail: {}",
2687 check.detail
2688 );
2689 }
2690
2691 #[test]
2692 fn effective_session_id_arg_wins_and_filters_empty() {
2693 assert_eq!(
2694 effective_session_id(Some("a".into()), Some("b".into())),
2695 Some("a".into())
2696 );
2697 assert_eq!(
2698 effective_session_id(Some("".into()), Some("b".into())),
2699 Some("b".into())
2700 );
2701 assert_eq!(
2702 effective_session_id(Some(" ".into()), None).as_deref(),
2703 Some(" ")
2704 ); assert_eq!(effective_session_id(None, Some("".into())), None);
2706 assert_eq!(effective_session_id(None, None), None);
2707 }
2708
2709 fn project_binding(id: &str, name: &str) -> crate::session_state::ProjectBinding {
2710 crate::session_state::ProjectBinding {
2711 project_id: id.into(),
2712 project_name: name.into(),
2713 updated_at: "t".into(),
2714 forced_until: None,
2715 }
2716 }
2717
2718 fn repo_binding_for_attribution(id: &str) -> crate::session_state::RepoBinding {
2722 crate::session_state::RepoBinding {
2723 repo_id: id.into(),
2724 git_url: None,
2725 remote_id: None,
2726 codebase_name: None,
2727 updated_at: "t".into(),
2728 }
2729 }
2730
2731 #[test]
2732 fn recording_check_truth_table() {
2733 let repo_attr = crate::commands::stream::Attribution::Repo {
2738 repo_id: "11111111-1111-4111-8111-111111111111".into(),
2739 project: None,
2740 };
2741 let project_attr = crate::commands::stream::Attribution::ProjectOnly {
2742 project_id: uuid::Uuid::from_u128(1),
2743 };
2744
2745 assert!(recording_check(None, None).is_none());
2748 assert!(recording_check(None, Some(&repo_attr)).is_none());
2749 assert!(recording_check(None, Some(&project_attr)).is_none());
2750
2751 assert!(recording_check(Some("s"), Some(&repo_attr)).is_none());
2753 assert!(recording_check(Some("s"), Some(&project_attr)).is_none());
2754
2755 assert_eq!(
2757 recording_check(Some("s"), None).map(|c| c.level),
2758 Some(Level::Error)
2759 );
2760 }
2761
2762 #[test]
2763 fn recording_check_error_names_project_switch_and_session() {
2764 let check = recording_check(Some("3f27a336-abcd"), None).expect("expected an Error check");
2769 assert_eq!(check.level, Level::Error);
2770 assert!(
2771 check.detail.contains("project switch"),
2772 "detail: {}",
2773 check.detail
2774 );
2775 assert!(
2776 check.detail.contains("3f27a336-abcd"),
2777 "detail: {}",
2778 check.detail
2779 );
2780 }
2781
2782 #[test]
2783 fn project_binding_check_tiers_capture_project_honors_are_ok() {
2784 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2800 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2801 _guard.set("TRACEVAULT_PROJECT", "33333333-3333-4333-8333-333333333333");
2802
2803 use crate::resolution::ProjectSource::*;
2804 for source in [ProjectFlag, Subagent, Env, SessionActive, UserDefault] {
2805 let outcome: ProjectOutcome = Ok(Some((
2806 project_binding("33333333-3333-4333-8333-333333333333", "My Project"),
2807 source,
2808 )));
2809 let check = project_binding_check(&outcome);
2810 assert_eq!(check.level, Level::Ok, "source={source} should read Ok");
2811 assert!(
2812 check.detail.contains("My Project"),
2813 "source={source} detail: {}",
2814 check.detail
2815 );
2816 }
2817 }
2818
2819 #[test]
2833 fn project_binding_check_env_name_form_is_warn_not_ok() {
2834 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2835 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2836 _guard.set("TRACEVAULT_PROJECT", "payments");
2837
2838 let outcome: ProjectOutcome = Ok(Some((
2842 project_binding("33333333-3333-4333-8333-333333333333", "payments"),
2843 crate::resolution::ProjectSource::Env,
2844 )));
2845 let check = project_binding_check(&outcome);
2846 assert_eq!(
2847 check.level,
2848 Level::Warn,
2849 "a NAME in TRACEVAULT_PROJECT is ignored by the capture path, so it must never read Ok: {}",
2850 check.detail
2851 );
2852 assert!(
2853 check.detail.contains("UUID form"),
2854 "the warning must say WHICH form is honoured: {}",
2855 check.detail
2856 );
2857 assert!(
2858 check.detail.contains("display only"),
2859 "worded like unresolved_config_default_check's precedent: {}",
2860 check.detail
2861 );
2862
2863 _guard.set("TRACEVAULT_PROJECT", "33333333-3333-4333-8333-333333333333");
2866 let outcome: ProjectOutcome = Ok(Some((
2867 project_binding("33333333-3333-4333-8333-333333333333", "payments"),
2868 crate::resolution::ProjectSource::Env,
2869 )));
2870 assert_eq!(project_binding_check(&outcome).level, Level::Ok);
2871 }
2872
2873 #[test]
2874 fn project_binding_check_config_default_is_warn_not_ok() {
2875 let outcome: ProjectOutcome = Ok(Some((
2879 project_binding("pid-3", "My Project"),
2880 crate::resolution::ProjectSource::ConfigDefault,
2881 )));
2882 let check = project_binding_check(&outcome);
2883 assert_eq!(check.level, Level::Warn);
2884 assert!(
2885 check
2886 .detail
2887 .contains("not used for attribution at capture time"),
2888 "detail: {}",
2889 check.detail
2890 );
2891 }
2892
2893 #[test]
2894 fn project_binding_check_deduced_is_warn() {
2895 let outcome: ProjectOutcome = Ok(Some((
2898 project_binding("pid-2", ""),
2899 crate::resolution::ProjectSource::Deduced,
2900 )));
2901 let check = project_binding_check(&outcome);
2902 assert_eq!(check.level, Level::Warn);
2903 assert!(
2904 check
2905 .detail
2906 .contains("not used for attribution at capture time"),
2907 "detail: {}",
2908 check.detail
2909 );
2910 }
2911
2912 #[test]
2913 fn project_binding_check_malformed_project_id_is_warn_not_ok() {
2914 use crate::resolution::ProjectSource::{SessionActive, UserDefault};
2921 for source in [SessionActive, UserDefault] {
2922 let outcome: ProjectOutcome =
2923 Ok(Some((project_binding("not-a-uuid", "My Project"), source)));
2924 let check = project_binding_check(&outcome);
2925 assert_eq!(check.level, Level::Warn, "source={source}");
2926 assert!(
2927 check.detail.contains("not a valid id"),
2928 "source={source} detail: {}",
2929 check.detail
2930 );
2931 }
2932 }
2933
2934 #[test]
2935 fn project_binding_check_ambiguous_err_is_warn_not_error() {
2936 let outcome: ProjectOutcome =
2942 Err("this repo belongs to multiple projects; select one with `tracevault project switch <name>`".into());
2943 let check = project_binding_check(&outcome);
2944 assert_eq!(check.level, Level::Warn);
2945 assert!(
2946 check.detail.contains("multiple projects"),
2947 "detail: {}",
2948 check.detail
2949 );
2950 }
2951
2952 #[test]
2953 fn project_binding_check_none_is_skip() {
2954 let outcome: ProjectOutcome = Ok(None);
2955 let check = project_binding_check(&outcome);
2956 assert_eq!(check.level, Level::Skip);
2957 }
2958
2959 fn auth_fixture() -> (
2996 tempfile::TempDir,
2997 tokio::sync::MutexGuard<'static, ()>,
2998 crate::test_helpers::EnvVarGuard,
2999 ) {
3000 let env_lock = crate::test_helpers::lock_env_mutation_sync();
3001 let dir = tempfile::tempdir().unwrap();
3002 let mut guard = crate::test_helpers::EnvVarGuard::new();
3003 guard.set("XDG_CONFIG_HOME", dir.path());
3004 guard.set("HOME", dir.path());
3005 guard.remove("TRACEVAULT_API_KEY");
3006 guard.remove("TRACEVAULT_SERVER_URL");
3007 (dir, env_lock, guard)
3008 }
3009
3010 #[test]
3014 fn a_config_only_setup_reads_as_logged_in() {
3015 let (_dir, _lock, _guard) = auth_fixture();
3016
3017 let auth = resolve_auth(Some("http://localhost:8080"), Some("tvk_from_config"));
3018
3019 assert_eq!(auth.server_url.as_deref(), Some("http://localhost:8080"));
3020 assert!(
3021 matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_config"),
3022 "the config's key is the credential every command resolves"
3023 );
3024 assert_eq!(auth.source, "project config (.tracevault/config.toml)");
3025 }
3026
3027 #[test]
3031 fn an_env_key_takes_its_url_from_the_config_when_the_env_has_none() {
3032 let (_dir, _lock, mut guard) = auth_fixture();
3033 guard.set("TRACEVAULT_API_KEY", "tvk_from_env");
3034
3035 let auth = resolve_auth(Some("http://localhost:8080"), None);
3036
3037 assert_eq!(auth.server_url.as_deref(), Some("http://localhost:8080"));
3038 assert!(matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_env"));
3039 assert_eq!(auth.source, "env (TRACEVAULT_API_KEY)");
3040 }
3041
3042 #[test]
3045 fn the_credentials_file_still_outranks_the_config() {
3046 let (dir, _lock, _guard) = auth_fixture();
3047 let creds_dir = dir.path().join("tracevault");
3048 std::fs::create_dir_all(&creds_dir).unwrap();
3049 std::fs::write(
3050 creds_dir.join("credentials.json"),
3051 r#"{"server_url":"https://dev.example.com","token":"tvk_from_file","email":"a@b.com"}"#,
3052 )
3053 .unwrap();
3054
3055 let auth = resolve_auth(Some("http://localhost:8080"), Some("tvk_from_config"));
3056
3057 assert_eq!(auth.server_url.as_deref(), Some("https://dev.example.com"));
3058 assert!(matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_file"));
3059 assert_eq!(auth.source, "credentials file (API key)");
3060 }
3061
3062 #[test]
3065 fn a_config_without_a_key_is_still_not_logged_in() {
3066 let (_dir, _lock, _guard) = auth_fixture();
3067
3068 let auth = resolve_auth(Some("http://localhost:8080"), None);
3069
3070 assert!(auth.credential.is_none());
3071 assert_eq!(auth.source, "none");
3072 assert_eq!(
3073 auth.server_url.as_deref(),
3074 Some("http://localhost:8080"),
3075 "the pin is still worth reporting"
3076 );
3077 }
3078
3079 #[test]
3080 fn verdict_repo_user_default_alone_is_not_an_error() {
3081 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3083 let cfg_tmp = tempfile::tempdir().unwrap();
3084 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3085 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3086 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); crate::user_default::save(&repo_binding_for_attribution(
3090 "11111111-1111-4111-8111-111111111111",
3091 ))
3092 .unwrap();
3093
3094 let cwd = tempfile::tempdir().unwrap();
3095 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3096 assert_eq!(
3097 attribution,
3098 Some(crate::commands::stream::Attribution::Repo {
3099 repo_id: "11111111-1111-4111-8111-111111111111".into(),
3100 project: None,
3101 })
3102 );
3103 assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
3104 }
3105
3106 #[test]
3107 fn verdict_project_user_default_alone_is_not_an_error() {
3108 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3112 let cfg_tmp = tempfile::tempdir().unwrap();
3113 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3114 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3115 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let pb = crate::session_state::ProjectBinding {
3119 project_id: uuid::Uuid::from_u128(7).to_string(),
3120 project_name: "p".into(),
3121 updated_at: "".into(),
3122 forced_until: None,
3123 };
3124 crate::user_project_default::save(&pb).unwrap();
3125
3126 let cwd = tempfile::tempdir().unwrap();
3127 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3128 assert_eq!(
3129 attribution,
3130 Some(crate::commands::stream::Attribution::ProjectOnly {
3131 project_id: uuid::Uuid::from_u128(7)
3132 })
3133 );
3134 assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
3135 }
3136
3137 #[test]
3138 fn verdict_config_without_repo_id_and_nothing_else_is_error() {
3139 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3142 let cfg_tmp = tempfile::tempdir().unwrap();
3143 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3144 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3145 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let config = crate::config::TracevaultConfig::default();
3149 assert!(
3150 crate::resolution::binding_from_config(&config).is_none(),
3151 "a repo_id-less config must not bind"
3152 );
3153
3154 let cwd = tempfile::tempdir().unwrap();
3155 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
3156 assert_eq!(
3157 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3158 Some(Level::Error)
3159 );
3160 }
3161
3162 #[test]
3163 fn verdict_nothing_anywhere_is_error() {
3164 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3165 let cfg_tmp = tempfile::tempdir().unwrap();
3166 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3167 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3168 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let cwd = tempfile::tempdir().unwrap();
3172 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3173 assert_eq!(
3174 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3175 Some(Level::Error)
3176 );
3177 }
3178
3179 #[test]
3180 fn verdict_deduced_project_display_does_not_suppress_recording_error() {
3181 let outcome: ProjectOutcome = Ok(Some((
3184 project_binding("pid", ""),
3185 crate::resolution::ProjectSource::Deduced,
3186 )));
3187 assert_eq!(project_binding_check(&outcome).level, Level::Warn);
3188
3189 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3190 let cfg_tmp = tempfile::tempdir().unwrap();
3191 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3192 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3193 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let cwd = tempfile::tempdir().unwrap();
3197 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3198 assert_eq!(
3199 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3200 Some(Level::Error),
3201 "a Deduced display value must not suppress the Recording error"
3202 );
3203 }
3204
3205 #[test]
3206 fn verdict_deduction_failure_is_warn_and_does_not_affect_recording() {
3207 let outcome: ProjectOutcome = Err("this repo belongs to multiple projects".into());
3212 assert_eq!(project_binding_check(&outcome).level, Level::Warn);
3213
3214 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3215 let cfg_tmp = tempfile::tempdir().unwrap();
3216 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3217 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3218 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let config = crate::config::TracevaultConfig {
3222 repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
3223 ..Default::default()
3224 };
3225 let cwd = tempfile::tempdir().unwrap();
3226 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
3227 assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
3230 }
3231
3232 #[test]
3233 fn offline_project_outcome_falls_back_to_saved_user_default() {
3234 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3238 let cfg_tmp = tempfile::tempdir().unwrap();
3239 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3240 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3241 _guard.set("HOME", cfg_tmp.path()); let pb = crate::session_state::ProjectBinding {
3244 project_id: uuid::Uuid::from_u128(9).to_string(),
3245 project_name: "My Project".into(),
3246 updated_at: "".into(),
3247 forced_until: None,
3248 };
3249 crate::user_project_default::save(&pb).unwrap();
3250
3251 let session = crate::session_state::SessionState::default();
3252 let inputs = ProjectResolveInputs {
3253 project_flag: None,
3254 env_project: None,
3255 session: &session,
3256 worktree_path: None,
3257 config_default: None,
3258 };
3259 let user_default_project = crate::user_project_default::load();
3261 let outcome = offline_project_outcome(&inputs, user_default_project);
3262 let check = project_binding_check(&outcome);
3263 assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
3264 assert!(
3265 check.detail.contains("My Project"),
3266 "detail: {}",
3267 check.detail
3268 );
3269 }
3270
3271 #[tokio::test]
3278 async fn online_project_outcome_resolves_env_uuid_and_reads_ok() {
3279 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3280 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3281 let uuid = "55555555-5555-4555-8555-555555555555";
3282 _guard.set("TRACEVAULT_PROJECT", uuid);
3283
3284 let client = ApiClient::new("http://127.0.0.1:0", Some("tok"));
3286 let session = crate::session_state::SessionState::default();
3287 let (outcome, unresolved) =
3288 online_project_outcome(&client, None, &session, "/wt", None, None).await;
3289 assert!(unresolved.is_none());
3290 let (b, source) = outcome
3291 .unwrap()
3292 .expect("TRACEVAULT_PROJECT must resolve to a binding");
3293 assert_eq!(source, ProjectSource::Env);
3294 assert_eq!(b.project_id, uuid);
3295
3296 let check = project_binding_check(&Ok(Some((b, source))));
3297 assert_eq!(
3298 check.level,
3299 Level::Ok,
3300 "an Env-sourced binding is honoured by capture_project and must read Ok: {}",
3301 check.detail
3302 );
3303 }
3304
3305 #[tokio::test]
3309 async fn online_project_outcome_resolves_env_name_via_the_client() {
3310 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3311 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3312 _guard.set("TRACEVAULT_PROJECT", "payments");
3313
3314 let list =
3315 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
3316 let (base, _rx) =
3317 crate::test_helpers::spawn_seq(vec![crate::test_helpers::http_json("200 OK", &list)]);
3318 let client = ApiClient::new(&base, Some("tok"));
3319 let session = crate::session_state::SessionState::default();
3320 let (outcome, _unresolved) =
3321 online_project_outcome(&client, None, &session, "/wt", None, None).await;
3322 let (b, source) = outcome
3323 .unwrap()
3324 .expect("a name should resolve via list_projects");
3325 assert_eq!(source, ProjectSource::Env);
3326 assert_eq!(b.project_name, "payments");
3327 assert_eq!(b.project_id, "11111111-1111-4111-8111-111111111111");
3328 }
3329
3330 #[test]
3331 fn recording_attribution_finds_subagent_override_via_linked_worktree_cwd() {
3332 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3336 let cfg_tmp = tempfile::tempdir().unwrap();
3337 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3338 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3339 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let base = tempfile::tempdir().unwrap();
3343 let repo_dir = base.path().join("repo");
3344 let wt_dir = base.path().join("wt");
3345 std::fs::create_dir_all(&repo_dir).unwrap();
3346 crate::test_helpers::init_git_repo(&repo_dir);
3347 crate::test_helpers::add_worktree(&repo_dir, &wt_dir);
3348
3349 let wt_key = crate::paths::worktree_toplevel(&wt_dir);
3350 let project_id = uuid::Uuid::from_u128(42);
3351 let mut subagent_projects = std::collections::HashMap::new();
3352 subagent_projects.insert(
3353 wt_key,
3354 crate::session_state::ProjectBinding {
3355 project_id: project_id.to_string(),
3356 project_name: "linked".into(),
3357 updated_at: "t".into(),
3358 forced_until: None,
3359 },
3360 );
3361 let state = crate::session_state::SessionState {
3362 subagent_projects,
3363 ..Default::default()
3364 };
3365 let sessions_dir = tempfile::tempdir().unwrap();
3366 std::fs::write(
3367 sessions_dir.path().join("sess-linked.toml"),
3368 toml::to_string(&state).unwrap(),
3369 )
3370 .unwrap();
3371
3372 let (found, _worktree) = recording_attribution(
3374 Some(sessions_dir.path()),
3375 Some("sess-linked"),
3376 &wt_dir,
3377 None,
3378 );
3379 assert_eq!(
3380 found,
3381 Some(crate::commands::stream::Attribution::ProjectOnly { project_id })
3382 );
3383
3384 let (missed, _worktree) = recording_attribution(
3387 Some(sessions_dir.path()),
3388 Some("sess-linked"),
3389 &repo_dir,
3390 None,
3391 );
3392 assert_eq!(missed, None);
3393 }
3394
3395 #[test]
3396 fn verdict_malformed_project_id_leaves_project_axis_unbound() {
3397 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3401 let cfg_tmp = tempfile::tempdir().unwrap();
3402 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3403 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3404 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let state = crate::session_state::SessionState {
3408 active_project: Some(project_binding("not-a-uuid", "My Project")),
3409 ..Default::default()
3410 };
3411 let sessions_dir = tempfile::tempdir().unwrap();
3412 std::fs::write(
3413 sessions_dir.path().join("sess-bad-project.toml"),
3414 toml::to_string(&state).unwrap(),
3415 )
3416 .unwrap();
3417
3418 let cwd = tempfile::tempdir().unwrap();
3419 let (attribution, _worktree) = recording_attribution(
3420 Some(sessions_dir.path()),
3421 Some("sess-bad-project"),
3422 cwd.path(),
3423 None,
3424 );
3425 assert_eq!(
3426 attribution, None,
3427 "a malformed project_id must not resolve an attribution"
3428 );
3429 assert_eq!(
3430 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3431 Some(Level::Error)
3432 );
3433 }
3434
3435 #[test]
3436 fn verdict_malformed_repo_id_with_nothing_else_bound_is_error() {
3437 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3441 let cfg_tmp = tempfile::tempdir().unwrap();
3442 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3443 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3444 _guard.set("HOME", cfg_tmp.path()); _guard.remove("TRACEVAULT_PROJECT"); let state = crate::session_state::SessionState {
3448 active: Some(crate::session_state::RepoBinding {
3449 repo_id: "not-a-uuid".into(),
3450 git_url: None,
3451 remote_id: None,
3452 codebase_name: None,
3453 updated_at: "t".into(),
3454 }),
3455 ..Default::default()
3456 };
3457 let sessions_dir = tempfile::tempdir().unwrap();
3458 std::fs::write(
3459 sessions_dir.path().join("sess-bad-repo.toml"),
3460 toml::to_string(&state).unwrap(),
3461 )
3462 .unwrap();
3463
3464 let cwd = tempfile::tempdir().unwrap();
3465 let (attribution, _worktree) = recording_attribution(
3466 Some(sessions_dir.path()),
3467 Some("sess-bad-repo"),
3468 cwd.path(),
3469 None,
3470 );
3471 assert_eq!(
3472 attribution, None,
3473 "a malformed repo_id must not resolve an attribution"
3474 );
3475 assert_eq!(
3476 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3477 Some(Level::Error)
3478 );
3479 }
3480
3481 #[test]
3482 fn unresolved_config_default_check_names_it_and_is_warn() {
3483 let check = unresolved_config_default_check("payments-platform");
3484 assert_eq!(check.level, Level::Warn);
3485 assert!(
3486 check.detail.contains("payments-platform"),
3487 "detail: {}",
3488 check.detail
3489 );
3490 assert!(
3491 check
3492 .detail
3493 .contains("not used for attribution at capture time"),
3494 "detail should not imply resolving it would make capture-time \
3495 attribution work: {}",
3496 check.detail
3497 );
3498 }
3499}