1use crate::api_client::{ApiClient, GetMeError};
8use crate::config::TracevaultConfig;
9use crate::credentials::{Credential, Credentials};
10use crate::resolution::{
11 effective_project, git_remote_url, git_repo_name, resolve_effective_project,
12 ProjectResolveInputs, 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() -> AuthContext {
119 let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
123 let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();
124
125 if let Some(token) = env_key {
126 return AuthContext {
127 server_url: env_url,
128 credential: Some(Credential::ApiKey(token)),
129 source: "env (TRACEVAULT_API_KEY)",
130 email_from_creds: None,
131 url_override_mismatch: None,
133 };
134 }
135
136 let creds = Credentials::load();
137 if let Some(c) = creds {
138 let source = match &c.auth {
139 Some(_) => "credentials file (Keycloak session)",
140 None => "credentials file (API key)",
141 };
142 let url_override_mismatch = env_url.filter(|env| {
146 c.credential().is_some() && !crate::credentials::same_server(&c.server_url, env)
147 });
148 return AuthContext {
149 server_url: Some(c.server_url.clone()),
150 credential: c.credential(),
151 source,
152 email_from_creds: Some(c.email).filter(|e| !e.is_empty()),
156 url_override_mismatch: url_override_mismatch.map(|env| (c.server_url, env)),
157 };
158 }
159
160 AuthContext {
161 server_url: env_url,
162 credential: None,
163 source: "none",
164 email_from_creds: None,
165 url_override_mismatch: None,
166 }
167}
168
169async fn auth_checks(auth: &AuthContext) -> Vec<Check> {
170 let mut out = Vec::new();
171
172 match (auth.credential.as_ref(), auth.server_url.as_ref()) {
173 (None, _) => {
174 out.push(Check::err(
175 "Logged in",
176 "no credentials found. Run `tracevault login --server-url <URL>`.",
177 ));
178 out.push(Check::skip("Token valid", "no token to check"));
179 return out;
180 }
181 (Some(_), None) => {
182 out.push(Check::err(
183 "Logged in",
184 "token found but no server URL (set TRACEVAULT_SERVER_URL)",
185 ));
186 out.push(Check::skip("Token valid", "no server URL to call"));
187 return out;
188 }
189 (Some(_), Some(url)) => {
190 out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
191 }
192 }
193
194 if let Some((file_url, env_url)) = &auth.url_override_mismatch {
198 out.push(Check::err(
199 "Server URL",
200 format!(
201 "TRACEVAULT_SERVER_URL is '{env_url}' but the saved login is for '{file_url}'. \
202 Commands will refuse to run rather than send that session's token to another \
203 instance. Unset TRACEVAULT_SERVER_URL, or run `tracevault login --server-url \
204 {env_url}`."
205 ),
206 ));
207 }
208
209 let server_url = auth.server_url.as_ref().unwrap();
210 let client = ApiClient::with_credential(server_url, auth.credential.clone());
211 match client.get_me().await {
212 Ok(me) => {
213 let who = me.name.unwrap_or_else(|| me.email.clone());
214 let detail = match &me.role {
215 Some(role) => format!("{who} <{}> (role: {role})", me.email),
216 None => format!("{who} <{}>", me.email),
217 };
218 out.push(Check::ok("Token valid", detail));
219
220 if let Some(cached) = &auth.email_from_creds {
221 if cached != &me.email {
222 out.push(Check::warn(
223 "Credentials cache",
224 format!(
225 "cached email '{cached}' differs from server '{}' — re-run login",
226 me.email
227 ),
228 ));
229 }
230 }
231 }
232 Err(GetMeError::Unauthorized) => {
233 out.push(Check::err(
234 "Token valid",
235 "rejected by server (expired or revoked). Run `tracevault login` again.",
236 ));
237 }
238 Err(GetMeError::Forbidden(_)) => {
241 out.push(Check::err(
242 "Account authorized",
243 "the token is valid but this account lacks the `tracing` Keycloak realm role — \
244 ask an administrator to grant `tracing` (or `tracing-admin`).",
245 ));
246 }
247 Err(GetMeError::Network(msg)) => {
248 out.push(Check::warn(
249 "Server reachable",
250 format!("{msg} — cannot confirm token validity"),
251 ));
252 }
253 Err(GetMeError::Server(msg)) => {
254 out.push(Check::warn("Token valid", format!("server error: {msg}")));
255 }
256 }
257 out
258}
259
260fn project_checks(
265 project_root: &Path,
266 global_settings: Option<&Path>,
267 has_global: bool,
268 has_binding: bool,
269) -> (Vec<Check>, Option<TracevaultConfig>) {
270 let mut out = Vec::new();
271
272 let is_git = project_root.join(".git").exists();
273 if is_git {
274 out.push(Check::ok(
275 "Git repository",
276 project_root.display().to_string(),
277 ));
278 } else if has_global || has_binding {
279 out.push(Check::skip(
280 "Git repository",
281 "not a git repo (global/workspace mode)",
282 ));
283 } else {
284 out.push(Check::err(
285 "Git repository",
286 "current directory is not a git repo",
287 ));
288 }
289
290 let tv_present = project_root.join(".tracevault").exists();
291 out.push(tracevault_init_check(tv_present, has_global, has_binding));
292
293 let config = match TracevaultConfig::try_load(project_root) {
298 Ok(Some(c)) => {
299 let url = c.server_url.as_deref().unwrap_or("<unset>");
300 out.push(Check::ok("Project config", format!("server={url}")));
301 Some(c)
302 }
303 Ok(None) => {
304 if tv_present {
305 out.push(Check::warn(
306 "Project config",
307 "No .tracevault/config.toml — run `tracevault init`, or use workspace mode (`tracevault repo status`).",
308 ));
309 }
310 None
311 }
312 Err(e) => {
313 out.push(Check::err(
314 "Project config",
315 format!(".tracevault/config.toml malformed: {e}"),
316 ));
317 None
318 }
319 };
320
321 if tv_present {
322 out.push(git_hook_check(
324 project_root,
325 "pre-push",
326 "# tracevault:enforce",
327 ));
328 out.push(git_hook_check(
329 project_root,
330 "post-commit",
331 "# tracevault:post-commit",
332 ));
333 } else if has_global || has_binding {
334 out.push(Check::skip(
335 "Git hooks",
336 "not used in global/workspace mode",
337 ));
338 } else {
339 out.push(Check::skip(
340 "Git hooks",
341 "not installed (no .tracevault/ — run `tracevault init`)",
342 ));
343 }
344
345 out.push(claude_hook_check_in(
346 &project_root.join(".claude/settings.json"),
347 global_settings,
348 ));
349
350 (out, config)
351}
352
353fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
354 let path = project_root.join(".git/hooks").join(name);
355 let label = format!("Git hook: {name}");
356 if !path.exists() {
357 return Check::warn(
358 label,
359 format!(".git/hooks/{name} missing — rerun `tracevault init`"),
360 );
361 }
362 match fs::read_to_string(&path) {
363 Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
364 Ok(_) => Check::warn(
365 label,
366 format!("{name} exists but no tracevault block — rerun `tracevault init`"),
367 ),
368 Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
369 }
370}
371
372fn settings_has_tracevault_hooks(contents: &str) -> bool {
374 contents.contains("tracevault stream")
375 || contents.contains("tracevault session-start")
376 || contents.contains("tracevault user-prompt")
377}
378
379enum SettingsHooks {
383 Present,
384 NoHooks,
385 Missing,
386 Unreadable(String),
387}
388
389fn read_settings_hooks(path: &Path) -> SettingsHooks {
390 match fs::read_to_string(path) {
391 Ok(s) if settings_has_tracevault_hooks(&s) => SettingsHooks::Present,
392 Ok(_) => SettingsHooks::NoHooks,
393 Err(e) if e.kind() == std::io::ErrorKind::NotFound => SettingsHooks::Missing,
394 Err(e) => SettingsHooks::Unreadable(e.to_string()),
395 }
396}
397
398fn global_hook_check_in(settings_path: &Path) -> Check {
402 match read_settings_hooks(settings_path) {
403 SettingsHooks::Present => Check::ok(
404 "Global install",
405 "hooks installed in ~/.claude/settings.json",
406 ),
407 SettingsHooks::NoHooks => Check::skip(
408 "Global install",
409 "~/.claude/settings.json has no tracevault hooks",
410 ),
411 SettingsHooks::Missing => Check::skip("Global install", "no ~/.claude/settings.json"),
412 SettingsHooks::Unreadable(e) => Check::warn(
413 "Global install",
414 format!("cannot read ~/.claude/settings.json: {e}"),
415 ),
416 }
417}
418
419fn claude_hook_check_in(repo_settings: &Path, global_settings: Option<&Path>) -> Check {
424 let repo = read_settings_hooks(repo_settings);
425 if matches!(repo, SettingsHooks::Present) {
426 return Check::ok("Claude Code hooks", "registered in .claude/settings.json");
427 }
428 let global = global_settings.map(read_settings_hooks);
429 if matches!(global, Some(SettingsHooks::Present)) {
430 return Check::ok("Claude Code hooks", "via global install (see Installation)");
431 }
432 if let SettingsHooks::Unreadable(e) = &repo {
433 return Check::warn(
434 "Claude Code hooks",
435 format!("cannot read <repo>/.claude/settings.json: {e}"),
436 );
437 }
438 if let Some(SettingsHooks::Unreadable(e)) = &global {
439 return Check::warn(
440 "Claude Code hooks",
441 format!("cannot read ~/.claude/settings.json: {e}"),
442 );
443 }
444 Check::warn(
445 "Claude Code hooks",
446 "not registered in <repo>/.claude/settings.json or ~/.claude/settings.json (capture will miss some events)",
447 )
448}
449
450fn tracevault_init_check(tv_dir_present: bool, has_global: bool, has_binding: bool) -> Check {
455 if tv_dir_present {
456 Check::ok("TraceVault initialized", ".tracevault/ present")
457 } else if has_global || has_binding {
458 Check::skip(
459 "TraceVault initialized",
460 "no per-repo .tracevault/ — global/workspace mode",
461 )
462 } else {
463 Check::err(
464 "TraceVault initialized",
465 "not set up: run `tracevault init` (per-repo) or `tracevault init --global`",
466 )
467 }
468}
469
470fn latest_active_binding_in(
476 sessions_dir: &Path,
477) -> Option<(String, crate::session_state::RepoBinding)> {
478 let mut sessions: Vec<(std::time::SystemTime, String)> = Vec::new();
479 for entry in fs::read_dir(sessions_dir).ok()?.flatten() {
480 let name = entry.file_name();
481 let name = name.to_str().unwrap_or("");
482 let Some(id) = name.strip_suffix(".toml") else {
483 continue;
484 };
485 if id.is_empty() {
486 continue;
487 }
488 let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
489 continue;
490 };
491 sessions.push((mtime, id.to_string()));
492 }
493 sessions.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); for (_, id) in sessions {
495 if let Some(b) = crate::session_state::load_from(sessions_dir, &id).active {
496 return Some((id, b));
497 }
498 }
499 None
500}
501
502fn workspace_repo_binding_check(
513 b: &crate::session_state::RepoBinding,
514 detail_suffix: &str,
515) -> Check {
516 let base = format!("repo {} via repo switch{detail_suffix}", b.repo_id);
517 if crate::commands::stream::binding_repo_id_is_valid(&b.repo_id) {
518 Check::ok("Workspace repo", base)
519 } else {
520 Check::warn(
521 "Workspace repo",
522 format!(
523 "{base} — this repo_id is not a valid id and will be dropped at capture time; run `tracevault repo switch <path>` to rewrite it"
524 ),
525 )
526 }
527}
528
529fn workspace_binding_check_in(
547 sessions_dir: &Path,
548 explicit_session_id: Option<&str>,
549) -> (Check, Option<crate::session_state::RepoBinding>) {
550 match explicit_session_id {
551 Some(id) => {
552 let state = crate::session_state::load_from(sessions_dir, id);
553 match state.active {
554 Some(b) => {
555 let check = workspace_repo_binding_check(&b, &format!(" (session {id})"));
556 (check, Some(b))
557 }
558 None => (
559 Check::skip(
560 "Workspace repo",
561 format!("session {id} has no active binding"),
562 ),
563 None,
564 ),
565 }
566 }
567 None => match latest_active_binding_in(sessions_dir) {
568 Some((id, b)) => {
569 let suffix = format!(
570 " — most recent session with a binding: {id} (may be another repo; pass --session-id to target one)"
571 );
572 let check = workspace_repo_binding_check(&b, &suffix);
573 (check, Some(b))
574 }
575 None => (
576 Check::skip("Workspace repo", "no active workspace binding found"),
577 None,
578 ),
579 },
580 }
581}
582
583type ProjectOutcome = Result<
594 Option<(crate::session_state::ProjectBinding, ProjectSource)>,
595 Box<dyn std::error::Error>,
596>;
597
598fn project_label(binding: &crate::session_state::ProjectBinding) -> &str {
607 if binding.project_name.is_empty() {
608 &binding.project_id
609 } else {
610 &binding.project_name
611 }
612}
613
614fn project_binding_check(outcome: &ProjectOutcome) -> Check {
641 match outcome {
642 Err(e) => Check::warn("Project", e.to_string()),
643 Ok(None) => Check::skip(
644 "Project",
645 "not bound — run `tracevault project switch --user \"<name>\"`, or `tracevault repo switch <path>` inside a checkout",
646 ),
647 Ok(Some((binding, source))) => {
648 let honored_tier = matches!(
649 source,
650 ProjectSource::ProjectFlag
651 | ProjectSource::Subagent
652 | ProjectSource::SessionActive
653 | ProjectSource::UserDefault
654 );
655 let label = project_label(binding);
656 if !honored_tier {
657 Check::warn(
658 "Project",
659 format!(
660 "{label} — {source}, not used for attribution at capture time; set one explicitly with `tracevault project switch <name>` or --project"
661 ),
662 )
663 } else if binding.project_id.parse::<uuid::Uuid>().is_err() {
664 Check::warn(
665 "Project",
666 format!(
667 "{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"
668 ),
669 )
670 } else {
671 Check::ok("Project", format!("{label} — {source}"))
672 }
673 }
674 }
675}
676
677fn unresolved_config_default_check(name: &str) -> Check {
690 Check::warn(
691 "Project default",
692 format!(
693 "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"
694 ),
695 )
696}
697
698fn recording_check(
717 session_id: Option<&str>,
718 attribution: Option<&crate::commands::stream::Attribution>,
719) -> Option<Check> {
720 let id = session_id?;
721 if attribution.is_some() {
722 return None;
723 }
724 Some(Check::err(
725 "Recording",
726 format!(
727 "nothing will be recorded — session {id} is bound on neither the repo nor the \
728 project axis; run `tracevault project switch --user \"<name>\"` on a repo-less \
729 machine, or `tracevault repo switch <path>` inside a checkout"
730 ),
731 ))
732}
733
734fn recording_attribution(
754 sessions_dir: Option<&Path>,
755 session_id: Option<&str>,
756 cwd: &Path,
757 config: Option<&TracevaultConfig>,
758) -> (Option<crate::commands::stream::Attribution>, String) {
759 let session = match (sessions_dir, session_id) {
760 (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
761 _ => crate::session_state::SessionState::default(),
762 };
763 let worktree = crate::paths::worktree_toplevel(cwd);
764 let bound = config.and_then(crate::resolution::binding_from_config);
765 let user_default_repo = crate::user_default::load();
766 let stream_binding = crate::commands::stream::resolve_stream_binding(
767 &session,
768 &worktree,
769 bound,
770 user_default_repo,
771 );
772 let capture_pid = crate::commands::stream::capture_project(&session, Some(&worktree));
773 let attribution =
774 crate::commands::stream::attribution_for(stream_binding.as_ref(), capture_pid);
775 (attribution, worktree)
776}
777
778fn offline_project_outcome(
789 inputs: &ProjectResolveInputs,
790 user_default_project: Option<crate::session_state::ProjectBinding>,
791) -> ProjectOutcome {
792 Ok(effective_project(inputs)
793 .or_else(|| user_default_project.map(|b| (b, ProjectSource::UserDefault))))
794}
795
796#[derive(Debug, Clone, PartialEq)]
800enum RepoMatch {
801 ByName(String),
802 ById(String),
803}
804
805fn server_repo_lookup(
810 config_present: bool,
811 repo_name: &str,
812 binding: Option<&crate::session_state::RepoBinding>,
813) -> Option<RepoMatch> {
814 if config_present {
815 return Some(RepoMatch::ByName(repo_name.to_string()));
816 }
817 if let Some(b) = binding {
818 return Some(RepoMatch::ById(b.repo_id.clone()));
819 }
820 None
821}
822
823fn find_repo_with_fallback<'a>(
836 repos: &'a [crate::api_client::RepoListItem],
837 want: &RepoMatch,
838 binding: Option<&crate::session_state::RepoBinding>,
839) -> Option<(&'a crate::api_client::RepoListItem, RepoMatch)> {
840 if let Some(r) = repos.iter().find(|r| match want {
841 RepoMatch::ByName(name) => &r.name == name,
842 RepoMatch::ById(id) => &r.id.to_string() == id,
843 }) {
844 return Some((r, want.clone()));
845 }
846 if let RepoMatch::ByName(_) = want {
847 let b = binding?;
848 let r = repos.iter().find(|r| r.id.to_string() == b.repo_id)?;
849 return Some((r, RepoMatch::ById(b.repo_id.clone())));
850 }
851 None
852}
853
854async fn server_repo_checks(
855 project_root: &Path,
856 auth: &AuthContext,
857 config: Option<&TracevaultConfig>,
858 binding: Option<&crate::session_state::RepoBinding>,
859) -> Vec<Check> {
860 let mut out = Vec::new();
861
862 let (Some(credential), Some(server_url)) = (auth.credential.clone(), auth.server_url.as_ref())
863 else {
864 out.push(Check::skip(
865 "Repo registered on server",
866 "not authenticated",
867 ));
868 return out;
869 };
870
871 let repo_name = git_repo_name(project_root);
872 let Some(want) = server_repo_lookup(config.is_some(), &repo_name, binding) else {
873 out.push(Check::skip(
874 "Repo registered on server",
875 "not bound (need a project config.toml or a --session-id workspace binding)",
876 ));
877 return out;
878 };
879
880 let client = ApiClient::with_credential(server_url, Some(credential));
881 let repos = match client.list_repos().await {
882 Ok(r) => r,
883 Err(e) => {
884 out.push(Check::warn(
885 "Repo registered on server",
886 format!("failed to list repos: {e}"),
887 ));
888 return out;
889 }
890 };
891
892 let found = find_repo_with_fallback(&repos, &want, binding);
893
894 match found {
895 None => {
896 let what = match &want {
897 RepoMatch::ByName(n) => format!("'{n}'"),
898 RepoMatch::ById(id) => format!("repo id {id}"),
899 };
900 out.push(Check::err(
901 "Repo registered on server",
902 format!("{what} not found on the server. Run `tracevault init` while logged in, or `tracevault sync`."),
903 ));
904 return out;
905 }
906 Some((r, matched_via)) => {
907 out.push(Check::ok(
908 "Repo registered on server",
909 format!("id={}", r.id),
910 ));
911 match r.clone_status.as_deref() {
912 Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
913 Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
914 "Server-side clone",
915 format!("{other} — analytics and code browser unavailable until it finishes"),
916 )),
917 Some("error") => out.push(Check::err(
918 "Server-side clone",
919 "error — check the repo settings page on the dashboard",
920 )),
921 Some(other) => out.push(Check::warn(
922 "Server-side clone",
923 format!("unknown status '{other}'"),
924 )),
925 None => out.push(Check::skip(
926 "Server-side clone",
927 "server did not report clone status",
928 )),
929 }
930
931 match &matched_via {
932 RepoMatch::ByName(_) => {
933 let local_remote = git_remote_url(project_root);
934 match (local_remote.as_deref(), r.github_url.as_deref()) {
935 (Some(local), Some(remote))
936 if normalize_remote(local) == normalize_remote(remote) =>
937 {
938 out.push(Check::ok("Remote URL matches", remote.to_string()));
939 }
940 (Some(local), Some(remote)) => out.push(Check::warn(
941 "Remote URL matches",
942 format!("local={local} vs server={remote} — run `tracevault sync`"),
943 )),
944 (Some(local), None) => out.push(Check::warn(
945 "Remote URL matches",
946 format!("server has no github_url; local={local}"),
947 )),
948 (None, _) => out.push(Check::warn(
949 "Remote URL matches",
950 "no local `origin` remote configured",
951 )),
952 }
953 }
954 RepoMatch::ById(_) => {
955 out.push(Check::skip(
956 "Remote URL matches",
957 "n/a in workspace mode (bound by name/id)",
958 ));
959 }
960 }
961 }
962 }
963
964 out
965}
966
967fn is_pending_queue_filename(name: &str) -> bool {
976 crate::commands::flush::repo_id_from_pending_filename(name).is_some()
977}
978
979fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
989 let Ok(read) = fs::read_dir(session_dir) else {
990 return 0;
991 };
992
993 read.flatten()
994 .filter(|entry| {
995 entry
996 .file_name()
997 .to_str()
998 .map(|name| {
999 is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
1000 })
1001 .unwrap_or(false)
1002 })
1003 .map(|entry| {
1004 fs::read_to_string(entry.path())
1005 .unwrap_or_default()
1006 .lines()
1007 .filter(|l| !l.trim().is_empty())
1008 .count()
1009 })
1010 .sum()
1011}
1012
1013fn session_checks(project_root: &Path) -> Vec<Check> {
1014 let sessions_dir = project_root.join(".tracevault/sessions");
1015 if !sessions_dir.exists() {
1016 return vec![Check::skip(
1017 "Pending events",
1018 "no .tracevault/sessions/ here (project-local check; a detached worker's queue may live under its own working dir)",
1019 )];
1020 }
1021
1022 let include_legacy = TracevaultConfig::load(project_root)
1026 .and_then(|c| c.repo_id)
1027 .is_some();
1028
1029 let mut total_sessions = 0usize;
1030 let mut sessions_with_pending = 0usize;
1031 let mut pending_event_count = 0usize;
1032
1033 if let Ok(read) = fs::read_dir(&sessions_dir) {
1034 for entry in read.flatten() {
1035 if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
1036 continue;
1037 }
1038 total_sessions += 1;
1039 let count = count_pending_events(&entry.path(), include_legacy);
1040 if count > 0 {
1041 sessions_with_pending += 1;
1042 pending_event_count += count;
1043 }
1044 }
1045 }
1046
1047 vec![if sessions_with_pending == 0 {
1048 Check::ok(
1049 "Pending events",
1050 format!("{total_sessions} session(s), all synced (project-local)"),
1051 )
1052 } else {
1053 Check::warn(
1054 "Pending events",
1055 format!(
1056 "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
1057 ),
1058 )
1059 }]
1060}
1061
1062fn normalize_remote(url: &str) -> String {
1067 let trimmed = url
1068 .trim()
1069 .trim_end_matches('/')
1070 .trim_end_matches(".git")
1071 .to_string();
1072
1073 if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
1075 return format!("github.com/{rest}");
1076 }
1077 for p in ["https://", "http://"] {
1079 if let Some(rest) = trimmed.strip_prefix(p) {
1080 return rest.to_string();
1081 }
1082 }
1083 trimmed
1084}
1085
1086pub fn effective_session_id(arg: Option<String>, env: Option<String>) -> Option<String> {
1091 arg.filter(|s| !s.is_empty())
1092 .or_else(|| env.filter(|s| !s.is_empty()))
1093}
1094
1095pub async fn run_status(project_root: &Path, cwd: &Path, session_id: Option<&str>) -> i32 {
1096 let auth = resolve_auth();
1097
1098 let global_settings: Option<PathBuf> =
1102 dirs::home_dir().map(|h| h.join(".claude").join("settings.json"));
1103 let sessions_dir = crate::session_state::sessions_dir();
1104
1105 let global_check = match global_settings.as_deref() {
1106 Some(p) => global_hook_check_in(p),
1107 None => Check::skip("Global install", "cannot determine home directory"),
1108 };
1109 let has_global = global_check.level == Level::Ok;
1110
1111 let (binding_check, binding) = match sessions_dir.as_deref() {
1114 Some(dir) => workspace_binding_check_in(dir, session_id),
1115 None => (
1116 Check::skip("Workspace repo", "cannot determine session state dir"),
1117 None,
1118 ),
1119 };
1120 let explicit_session = session_id.is_some();
1126 let has_binding = binding.is_some() && explicit_session;
1127 let authoritative_binding = if explicit_session {
1128 binding.as_ref()
1129 } else {
1130 None
1131 };
1132
1133 let auth_checks_v = auth_checks(&auth).await;
1134 let install_v = vec![global_check];
1135 let (proj_checks_v, config) = project_checks(
1136 project_root,
1137 global_settings.as_deref(),
1138 has_global,
1139 has_binding,
1140 );
1141
1142 let (attribution, worktree) =
1148 recording_attribution(sessions_dir.as_deref(), session_id, cwd, config.as_ref());
1149
1150 let project_session = match (sessions_dir.as_deref(), session_id) {
1157 (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
1158 _ => crate::session_state::SessionState::default(),
1159 };
1160
1161 let config_default_name = config.as_ref().and_then(|c| c.default_project.clone());
1171 let user_default_project = crate::user_project_default::load();
1172 let project_git_url = git_remote_url(cwd);
1173 let mut config_default_unresolved: Option<String> = None;
1181
1182 let project_outcome: ProjectOutcome = match (auth.credential.clone(), auth.server_url.as_ref())
1183 {
1184 (Some(credential), Some(server_url)) => {
1185 let client = ApiClient::with_credential(server_url, Some(credential));
1186 let config_default = match config_default_name.as_deref() {
1189 Some(name) => {
1190 let resolved = client.list_projects().await.ok().and_then(|items| {
1191 items.into_iter().find(|p| p.name == name).map(|p| {
1192 crate::session_state::ProjectBinding {
1193 project_id: p.id.to_string(),
1194 project_name: p.name,
1195 updated_at: chrono::Utc::now().to_rfc3339(),
1196 }
1197 })
1198 });
1199 if resolved.is_none() {
1200 config_default_unresolved = Some(name.to_string());
1201 }
1202 resolved
1203 }
1204 None => None,
1205 };
1206 let inputs = ProjectResolveInputs {
1207 project_flag: None,
1208 session: &project_session,
1209 worktree_path: Some(&worktree),
1210 config_default,
1211 };
1212 resolve_effective_project(
1213 &inputs,
1214 user_default_project,
1215 project_git_url.as_deref(),
1216 &client,
1217 )
1218 .await
1219 }
1220 _ => {
1221 let inputs = ProjectResolveInputs {
1222 project_flag: None,
1223 session: &project_session,
1224 worktree_path: Some(&worktree),
1225 config_default: None,
1226 };
1227 offline_project_outcome(&inputs, user_default_project)
1228 }
1229 };
1230
1231 let mut attribution_v = Vec::new();
1232 if let Some(c) = recording_check(session_id, attribution.as_ref()) {
1233 attribution_v.push(c);
1234 }
1235 attribution_v.push(binding_check);
1236 attribution_v.push(project_binding_check(&project_outcome));
1237 if let Some(name) = config_default_unresolved {
1238 attribution_v.push(unresolved_config_default_check(&name));
1239 }
1240
1241 let server_checks_v =
1242 server_repo_checks(project_root, &auth, config.as_ref(), authoritative_binding).await;
1243 let session_checks_v = session_checks(project_root);
1244
1245 let sections: Vec<(&str, Vec<Check>)> = vec![
1246 ("Authentication", auth_checks_v),
1247 ("Installation", install_v),
1248 ("Project", proj_checks_v),
1249 ("Attribution", attribution_v),
1250 ("Server repo", server_checks_v),
1251 ("Sessions", session_checks_v),
1252 ];
1253 for (title, checks) in §ions {
1254 print_section(title, checks);
1255 }
1256 let all: Vec<&Check> = sections.iter().flat_map(|(_, v)| v.iter()).collect();
1257
1258 let errors = all.iter().filter(|c| c.level == Level::Error).count();
1259 let warns = all.iter().filter(|c| c.level == Level::Warn).count();
1260
1261 match (errors, warns) {
1262 (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
1263 (0, w) => println!(
1264 "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
1265 if w == 1 { "" } else { "s" }
1266 ),
1267 (e, 0) => println!(
1268 "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
1269 if e == 1 { "" } else { "s" }
1270 ),
1271 (e, w) => println!(
1272 "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
1273 if e == 1 { "" } else { "s" },
1274 if w == 1 { "" } else { "s" }
1275 ),
1276 }
1277
1278 exit_code_for(&all)
1279}
1280
1281fn exit_code_for(checks: &[&Check]) -> i32 {
1286 if checks.iter().any(|c| c.level == Level::Error) {
1287 1
1288 } else {
1289 0
1290 }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295 use super::*;
1296
1297 #[test]
1298 fn normalize_remote_ssh_https_equal() {
1299 assert_eq!(
1300 normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
1301 normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
1302 );
1303 assert_eq!(
1304 normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
1305 "github.com/VirtusLab/visdom-ai-tracing"
1306 );
1307 }
1308
1309 #[test]
1310 fn normalize_remote_preserves_non_github() {
1311 assert_eq!(
1312 normalize_remote("git@gitlab.com:foo/bar.git"),
1313 "git@gitlab.com:foo/bar"
1314 );
1315 }
1316
1317 #[test]
1318 fn git_hook_check_missing_file_is_warning() {
1319 let dir = tempfile::tempdir().unwrap();
1320 let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1321 assert_eq!(check.level, Level::Warn);
1322 }
1323
1324 #[test]
1325 fn git_hook_check_with_marker_is_ok() {
1326 let dir = tempfile::tempdir().unwrap();
1327 let hooks = dir.path().join(".git/hooks");
1328 std::fs::create_dir_all(&hooks).unwrap();
1329 std::fs::write(
1330 hooks.join("pre-push"),
1331 "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
1332 )
1333 .unwrap();
1334 let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1335 assert_eq!(check.level, Level::Ok);
1336 }
1337
1338 #[test]
1339 fn git_hook_check_without_marker_is_warning() {
1340 let dir = tempfile::tempdir().unwrap();
1341 let hooks = dir.path().join(".git/hooks");
1342 std::fs::create_dir_all(&hooks).unwrap();
1343 std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
1344 let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1345 assert_eq!(check.level, Level::Warn);
1346 }
1347
1348 #[test]
1349 fn project_checks_errors_without_tracevault_dir_and_no_global_or_binding() {
1350 let dir = tempfile::tempdir().unwrap();
1351 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1352 let missing_global = dir.path().join("no-global.json");
1353 let (checks, cfg) =
1354 project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1355 assert!(cfg.is_none());
1356 assert!(checks
1357 .iter()
1358 .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
1359 let git_hooks = checks
1362 .iter()
1363 .find(|c| c.label == "Git hooks")
1364 .expect("Git hooks check present");
1365 assert_eq!(git_hooks.level, Level::Skip);
1366 assert!(
1367 !git_hooks.detail.contains("global/workspace mode"),
1368 "unconfigured git-hooks detail must not claim global/workspace mode: {}",
1369 git_hooks.detail
1370 );
1371 }
1372
1373 #[test]
1374 fn project_checks_no_tracevault_dir_is_not_error_in_global_mode() {
1375 let dir = tempfile::tempdir().unwrap();
1376 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1377 let missing_global = dir.path().join("no-global.json");
1378 let (checks, _) = project_checks(dir.path(), Some(missing_global.as_path()), true, false);
1379 let refs: Vec<&Check> = checks.iter().collect();
1380 assert_eq!(
1381 exit_code_for(&refs),
1382 0,
1383 "global mode must not force exit 1 on missing .tracevault/"
1384 );
1385 assert!(checks
1386 .iter()
1387 .any(|c| c.label == "TraceVault initialized" && c.level == Level::Skip));
1388 }
1389
1390 #[test]
1391 fn project_checks_warns_when_config_toml_missing() {
1392 let dir = tempfile::tempdir().unwrap();
1397 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1398 std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1399 let missing_global = dir.path().join("no-global.json");
1400 let (checks, cfg) =
1401 project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1402 assert!(cfg.is_none());
1403 let project_config_check = checks
1404 .iter()
1405 .find(|c| c.label == "Project config")
1406 .expect("Project config check present");
1407 assert_eq!(project_config_check.level, Level::Warn);
1408
1409 let refs: Vec<&Check> = checks.iter().collect();
1410 assert_eq!(
1411 exit_code_for(&refs),
1412 0,
1413 "a missing config.toml alone must not force a non-zero exit code"
1414 );
1415 }
1416
1417 #[test]
1418 fn project_checks_errors_on_malformed_config_toml() {
1419 let dir = tempfile::tempdir().unwrap();
1423 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1424 std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1425 std::fs::write(
1426 dir.path().join(".tracevault/config.toml"),
1427 "not valid toml {{{",
1428 )
1429 .unwrap();
1430 let missing_global = dir.path().join("no-global.json");
1431 let (checks, cfg) =
1432 project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1433 assert!(cfg.is_none());
1434 let project_config_check = checks
1435 .iter()
1436 .find(|c| c.label == "Project config")
1437 .expect("Project config check present");
1438 assert_eq!(project_config_check.level, Level::Error);
1439
1440 let refs: Vec<&Check> = checks.iter().collect();
1441 assert_eq!(exit_code_for(&refs), 1);
1442 }
1443
1444 #[test]
1445 fn exit_code_for_warn_only_is_zero() {
1446 let checks = [
1447 Check::warn("a", ""),
1448 Check::ok("b", ""),
1449 Check::skip("c", ""),
1450 ];
1451 let refs: Vec<&Check> = checks.iter().collect();
1452 assert_eq!(exit_code_for(&refs), 0);
1453 }
1454
1455 #[test]
1456 fn exit_code_for_any_error_is_one() {
1457 let checks = [
1458 Check::ok("a", ""),
1459 Check::err("b", ""),
1460 Check::warn("c", ""),
1461 ];
1462 let refs: Vec<&Check> = checks.iter().collect();
1463 assert_eq!(exit_code_for(&refs), 1);
1464 }
1465
1466 #[test]
1467 fn count_pending_events_sums_across_per_repo_queues() {
1468 let dir = tempfile::tempdir().unwrap();
1469 std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1470 std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
1471 std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
1472 assert_eq!(count_pending_events(dir.path(), false), 3);
1473 assert_eq!(count_pending_events(dir.path(), true), 3);
1474 }
1475
1476 #[test]
1477 fn count_pending_events_ignores_unrelated_files() {
1478 let dir = tempfile::tempdir().unwrap();
1479 std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
1480 std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
1481 assert_eq!(count_pending_events(dir.path(), false), 1);
1482 }
1483
1484 #[test]
1485 fn count_pending_events_zero_for_empty_dir() {
1486 let dir = tempfile::tempdir().unwrap();
1487 assert_eq!(count_pending_events(dir.path(), false), 0);
1488 assert_eq!(count_pending_events(dir.path(), true), 0);
1489 }
1490
1491 #[test]
1492 fn is_pending_queue_filename_matches_per_repo_only() {
1493 assert!(!is_pending_queue_filename("pending.jsonl"));
1494 assert!(is_pending_queue_filename(
1501 "pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"
1502 ));
1503 assert!(is_pending_queue_filename("pending-a.jsonl"));
1504 }
1505
1506 #[test]
1507 fn is_pending_queue_filename_rejects_lookalikes() {
1508 assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
1509 assert!(!is_pending_queue_filename("pending-.jsonl"));
1510 }
1511
1512 #[test]
1513 fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
1514 let dir = tempfile::tempdir().unwrap();
1515 std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
1516 assert_eq!(
1517 count_pending_events(dir.path(), false),
1518 0,
1519 "legacy pending.jsonl must not be counted when there's no bound repo_id"
1520 );
1521 assert_eq!(
1522 count_pending_events(dir.path(), true),
1523 2,
1524 "legacy pending.jsonl counts once a repo_id is bound"
1525 );
1526 }
1527
1528 #[test]
1529 fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
1530 let dir = tempfile::tempdir().unwrap();
1531 std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
1532 std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1533 assert_eq!(count_pending_events(dir.path(), false), 2);
1534 assert_eq!(count_pending_events(dir.path(), true), 3);
1535 }
1536
1537 #[test]
1538 fn count_pending_events_ignores_lookalike_filenames() {
1539 let dir = tempfile::tempdir().unwrap();
1540 std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
1541 std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
1542 assert_eq!(count_pending_events(dir.path(), false), 0);
1543 assert_eq!(count_pending_events(dir.path(), true), 0);
1544 }
1545
1546 #[test]
1547 fn settings_has_tracevault_hooks_detects_commands() {
1548 assert!(settings_has_tracevault_hooks(
1549 r#"{"hooks":{"PreToolUse":[{"hooks":[{"command":"tracevault stream --event pre"}]}]}}"#
1550 ));
1551 assert!(settings_has_tracevault_hooks(
1552 r#"{"command":"tracevault session-start"}"#
1553 ));
1554 assert!(settings_has_tracevault_hooks(
1555 r#"{"command":"tracevault user-prompt"}"#
1556 ));
1557 assert!(!settings_has_tracevault_hooks(
1558 r#"{"hooks":{"PreToolUse":[]}}"#
1559 ));
1560 assert!(!settings_has_tracevault_hooks("{}"));
1561 }
1562
1563 #[test]
1564 fn global_hook_check_ok_when_present() {
1565 let dir = tempfile::tempdir().unwrap();
1566 let p = dir.path().join("settings.json");
1567 std::fs::write(
1568 &p,
1569 r#"{"hooks":{"SessionStart":[{"hooks":[{"command":"tracevault session-start"}]}]}}"#,
1570 )
1571 .unwrap();
1572 assert_eq!(global_hook_check_in(&p).level, Level::Ok);
1573 }
1574
1575 #[test]
1576 fn global_hook_check_skip_when_absent_or_no_hooks() {
1577 let dir = tempfile::tempdir().unwrap();
1578 let missing = dir.path().join("settings.json");
1579 assert_eq!(global_hook_check_in(&missing).level, Level::Skip);
1580 let empty = dir.path().join("empty.json");
1581 std::fs::write(&empty, "{}").unwrap();
1582 assert_eq!(global_hook_check_in(&empty).level, Level::Skip);
1583 }
1584
1585 #[test]
1586 fn global_hook_check_warns_when_unreadable() {
1587 let dir = tempfile::tempdir().unwrap();
1590 let as_dir = dir.path().join("settings.json");
1591 std::fs::create_dir(&as_dir).unwrap();
1592 let check = global_hook_check_in(&as_dir);
1593 assert_eq!(check.level, Level::Warn);
1594 assert!(
1595 check.detail.contains("cannot read"),
1596 "detail: {}",
1597 check.detail
1598 );
1599 }
1600
1601 #[test]
1602 fn claude_hook_check_ok_from_global_only() {
1603 let dir = tempfile::tempdir().unwrap();
1604 let repo = dir.path().join("repo-settings.json"); let global = dir.path().join("global-settings.json");
1606 std::fs::write(&global, r#"{"command":"tracevault stream"}"#).unwrap();
1607 let c = claude_hook_check_in(&repo, Some(global.as_path()));
1608 assert_eq!(c.level, Level::Ok);
1609 assert!(
1610 c.detail.to_lowercase().contains("global") || c.detail.contains("~/.claude"),
1611 "detail: {}",
1612 c.detail
1613 );
1614 }
1615
1616 #[test]
1617 fn claude_hook_check_ok_from_repo() {
1618 let dir = tempfile::tempdir().unwrap();
1619 let repo = dir.path().join("repo-settings.json");
1620 std::fs::write(&repo, r#"{"command":"tracevault stream"}"#).unwrap();
1621 let global = dir.path().join("global-settings.json"); assert_eq!(
1623 claude_hook_check_in(&repo, Some(global.as_path())).level,
1624 Level::Ok
1625 );
1626 }
1627
1628 #[test]
1629 fn claude_hook_check_no_global_path_uses_repo_only() {
1630 let dir = tempfile::tempdir().unwrap();
1633 let repo = dir.path().join("repo-settings.json");
1634 std::fs::write(&repo, r#"{"command":"tracevault stream"}"#).unwrap();
1635 assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
1636
1637 let missing = dir.path().join("nope.json");
1638 assert_eq!(claude_hook_check_in(&missing, None).level, Level::Warn);
1639 }
1640
1641 #[test]
1642 fn claude_hook_check_warn_when_neither() {
1643 let dir = tempfile::tempdir().unwrap();
1644 let c = claude_hook_check_in(
1645 &dir.path().join("a.json"),
1646 Some(dir.path().join("b.json").as_path()),
1647 );
1648 assert_eq!(c.level, Level::Warn);
1649 }
1650
1651 #[test]
1652 fn claude_hook_check_warns_when_repo_settings_unreadable() {
1653 let dir = tempfile::tempdir().unwrap();
1654 let repo = dir.path().join("repo-settings.json");
1655 std::fs::create_dir(&repo).unwrap(); let global = dir.path().join("global.json"); let c = claude_hook_check_in(&repo, Some(global.as_path()));
1658 assert_eq!(c.level, Level::Warn);
1659 assert!(c.detail.contains("cannot read"), "detail: {}", c.detail);
1660 }
1661
1662 #[test]
1663 fn tracevault_init_check_severity_matrix() {
1664 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);
1668 assert_eq!(
1669 tracevault_init_check(false, false, false).level,
1670 Level::Error
1671 ); }
1673
1674 #[test]
1675 fn workspace_binding_explicit_id_with_binding_is_ok() {
1676 let dir = tempfile::tempdir().unwrap();
1677 let st = crate::session_state::SessionState {
1678 active: Some(crate::session_state::RepoBinding {
1679 repo_id: "11111111-1111-4111-8111-111111111111".into(),
1680 git_url: None,
1681 remote_id: None,
1682 codebase_name: None,
1683 updated_at: "t".into(),
1684 }),
1685 ..Default::default()
1686 };
1687 std::fs::write(
1688 dir.path().join("sess-9.toml"),
1689 toml::to_string(&st).unwrap(),
1690 )
1691 .unwrap();
1692 let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-9"));
1693 assert_eq!(check.level, Level::Ok);
1694 assert!(
1695 check
1696 .detail
1697 .contains("11111111-1111-4111-8111-111111111111"),
1698 "detail: {}",
1699 check.detail
1700 );
1701 assert_eq!(
1702 binding.unwrap().repo_id,
1703 "11111111-1111-4111-8111-111111111111"
1704 );
1705 }
1706
1707 #[test]
1708 fn workspace_binding_explicit_id_without_binding_is_skip() {
1709 let dir = tempfile::tempdir().unwrap();
1713 std::fs::write(
1714 dir.path().join("sess-empty.toml"),
1715 toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1716 )
1717 .unwrap();
1718 let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-empty"));
1719 assert_eq!(check.level, Level::Skip);
1720 assert!(binding.is_none());
1721 }
1722
1723 #[test]
1724 fn workspace_binding_no_id_empty_dir_is_skip() {
1725 let dir = tempfile::tempdir().unwrap();
1726 let (check, binding) = workspace_binding_check_in(dir.path(), None);
1727 assert_eq!(check.level, Level::Skip);
1728 assert!(binding.is_none());
1729 }
1730
1731 #[test]
1732 fn workspace_binding_no_id_scans_latest() {
1733 let dir = tempfile::tempdir().unwrap();
1734 let older = crate::session_state::SessionState {
1736 active: Some(crate::session_state::RepoBinding {
1737 repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
1738 git_url: None,
1739 remote_id: None,
1740 codebase_name: None,
1741 updated_at: "t".into(),
1742 }),
1743 ..Default::default()
1744 };
1745 std::fs::write(
1746 dir.path().join("old.toml"),
1747 toml::to_string(&older).unwrap(),
1748 )
1749 .unwrap();
1750 std::thread::sleep(std::time::Duration::from_millis(20));
1752 let newer = crate::session_state::SessionState {
1753 active: Some(crate::session_state::RepoBinding {
1754 repo_id: "bbbbbbbb-2222-4222-8222-222222222222".into(),
1755 git_url: None,
1756 remote_id: None,
1757 codebase_name: None,
1758 updated_at: "t".into(),
1759 }),
1760 ..Default::default()
1761 };
1762 std::fs::write(
1763 dir.path().join("new.toml"),
1764 toml::to_string(&newer).unwrap(),
1765 )
1766 .unwrap();
1767 let (check, binding) = workspace_binding_check_in(dir.path(), None);
1768 assert_eq!(check.level, Level::Ok);
1769 assert_eq!(
1770 binding.unwrap().repo_id,
1771 "bbbbbbbb-2222-4222-8222-222222222222",
1772 "must pick the most-recently-modified session"
1773 );
1774 }
1775
1776 #[test]
1777 fn workspace_binding_scan_skips_newest_without_binding() {
1778 let dir = tempfile::tempdir().unwrap();
1781 let with_binding = crate::session_state::SessionState {
1782 active: Some(crate::session_state::RepoBinding {
1783 repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
1784 git_url: None,
1785 remote_id: None,
1786 codebase_name: None,
1787 updated_at: "t".into(),
1788 }),
1789 ..Default::default()
1790 };
1791 std::fs::write(
1792 dir.path().join("older.toml"),
1793 toml::to_string(&with_binding).unwrap(),
1794 )
1795 .unwrap();
1796 std::thread::sleep(std::time::Duration::from_millis(20));
1797 std::fs::write(
1799 dir.path().join("newest.toml"),
1800 toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1801 )
1802 .unwrap();
1803 let (check, binding) = workspace_binding_check_in(dir.path(), None);
1804 assert_eq!(check.level, Level::Ok);
1805 assert_eq!(
1806 binding.unwrap().repo_id,
1807 "aaaaaaaa-1111-4111-8111-111111111111"
1808 );
1809 }
1810
1811 #[test]
1812 fn workspace_binding_scan_no_active_binding_is_skip_not_warn() {
1813 let dir = tempfile::tempdir().unwrap();
1816 std::fs::write(
1817 dir.path().join("stray.toml"),
1818 toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1819 )
1820 .unwrap();
1821 let (check, binding) = workspace_binding_check_in(dir.path(), None);
1822 assert_eq!(check.level, Level::Skip);
1823 assert!(binding.is_none());
1824 }
1825
1826 #[test]
1827 fn workspace_binding_explicit_id_malformed_repo_id_is_warn_not_ok() {
1828 let dir = tempfile::tempdir().unwrap();
1833 let st = crate::session_state::SessionState {
1834 active: Some(crate::session_state::RepoBinding {
1835 repo_id: "not-a-uuid".into(),
1836 git_url: None,
1837 remote_id: None,
1838 codebase_name: None,
1839 updated_at: "t".into(),
1840 }),
1841 ..Default::default()
1842 };
1843 std::fs::write(
1844 dir.path().join("sess-bad.toml"),
1845 toml::to_string(&st).unwrap(),
1846 )
1847 .unwrap();
1848 let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-bad"));
1849 assert_eq!(check.level, Level::Warn);
1850 assert!(
1851 check.detail.contains("not a valid id"),
1852 "detail: {}",
1853 check.detail
1854 );
1855 assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
1858 }
1859
1860 #[test]
1861 fn workspace_binding_scan_malformed_repo_id_is_warn_not_ok() {
1862 let dir = tempfile::tempdir().unwrap();
1865 let st = crate::session_state::SessionState {
1866 active: Some(crate::session_state::RepoBinding {
1867 repo_id: "not-a-uuid".into(),
1868 git_url: None,
1869 remote_id: None,
1870 codebase_name: None,
1871 updated_at: "t".into(),
1872 }),
1873 ..Default::default()
1874 };
1875 std::fs::write(
1876 dir.path().join("sess-bad.toml"),
1877 toml::to_string(&st).unwrap(),
1878 )
1879 .unwrap();
1880 let (check, binding) = workspace_binding_check_in(dir.path(), None);
1881 assert_eq!(check.level, Level::Warn);
1882 assert!(
1883 check.detail.contains("not a valid id"),
1884 "detail: {}",
1885 check.detail
1886 );
1887 assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
1888 }
1889
1890 fn repo_item(id: &str, name: &str) -> crate::api_client::RepoListItem {
1891 crate::api_client::RepoListItem {
1892 id: id.parse().unwrap(),
1893 name: name.to_string(),
1894 github_url: None,
1895 clone_status: None,
1896 }
1897 }
1898
1899 #[test]
1900 fn find_repo_with_fallback_direct_name_hit_no_fallback_needed() {
1901 let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1902 let want = RepoMatch::ByName("myrepo".to_string());
1903 let (r, matched_via) = find_repo_with_fallback(&repos, &want, None).unwrap();
1904 assert_eq!(r.name, "myrepo");
1905 assert_eq!(matched_via, want);
1906 }
1907
1908 #[test]
1909 fn find_repo_with_fallback_falls_back_to_binding_id_on_name_miss() {
1910 let id = "11111111-1111-4111-8111-111111111111";
1915 let repos = vec![repo_item(id, "myrepo")];
1916 let binding = crate::session_state::RepoBinding {
1917 repo_id: id.to_string(),
1918 git_url: None,
1919 remote_id: None,
1920 codebase_name: None,
1921 updated_at: "t".into(),
1922 };
1923 let want = RepoMatch::ByName("renamed".to_string());
1924 let (r, matched_via) = find_repo_with_fallback(&repos, &want, Some(&binding))
1925 .expect("fallback by binding id must find the repo");
1926 assert_eq!(r.name, "myrepo");
1927 assert_eq!(matched_via, RepoMatch::ById(id.to_string()));
1928 }
1929
1930 #[test]
1931 fn find_repo_with_fallback_none_when_name_misses_and_no_binding() {
1932 let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1933 let want = RepoMatch::ByName("renamed".to_string());
1934 assert!(find_repo_with_fallback(&repos, &want, None).is_none());
1935 }
1936
1937 #[test]
1938 fn find_repo_with_fallback_none_when_name_and_binding_both_miss() {
1939 let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1940 let binding = crate::session_state::RepoBinding {
1941 repo_id: "22222222-2222-4222-8222-222222222222".to_string(),
1942 git_url: None,
1943 remote_id: None,
1944 codebase_name: None,
1945 updated_at: "t".into(),
1946 };
1947 let want = RepoMatch::ByName("renamed".to_string());
1948 assert!(find_repo_with_fallback(&repos, &want, Some(&binding)).is_none());
1949 }
1950
1951 #[test]
1952 fn find_repo_with_fallback_by_id_miss_is_never_retried() {
1953 let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1957 let binding = crate::session_state::RepoBinding {
1958 repo_id: "99999999-9999-4999-8999-999999999999".to_string(),
1959 git_url: None,
1960 remote_id: None,
1961 codebase_name: None,
1962 updated_at: "t".into(),
1963 };
1964 let want = RepoMatch::ById("99999999-9999-4999-8999-999999999999".to_string());
1965 assert!(find_repo_with_fallback(&repos, &want, Some(&binding)).is_none());
1966 }
1967
1968 #[test]
1969 fn server_repo_lookup_prefers_config_by_name() {
1970 let m = server_repo_lookup(true, "myrepo", None).unwrap();
1971 assert_eq!(m, RepoMatch::ByName("myrepo".to_string()));
1972 }
1973
1974 #[test]
1975 fn server_repo_lookup_falls_back_to_binding_by_id() {
1976 let b = crate::session_state::RepoBinding {
1977 repo_id: "rid-1".into(),
1978 git_url: None,
1979 remote_id: None,
1980 codebase_name: None,
1981 updated_at: "t".into(),
1982 };
1983 let m = server_repo_lookup(false, "ignored", Some(&b)).unwrap();
1984 assert_eq!(m, RepoMatch::ById("rid-1".to_string()));
1985 }
1986
1987 #[test]
1988 fn server_repo_lookup_none_when_neither() {
1989 assert!(server_repo_lookup(false, "x", None).is_none());
1990 }
1991
1992 #[test]
1993 fn effective_session_id_arg_wins_and_filters_empty() {
1994 assert_eq!(
1995 effective_session_id(Some("a".into()), Some("b".into())),
1996 Some("a".into())
1997 );
1998 assert_eq!(
1999 effective_session_id(Some("".into()), Some("b".into())),
2000 Some("b".into())
2001 );
2002 assert_eq!(
2003 effective_session_id(Some(" ".into()), None).as_deref(),
2004 Some(" ")
2005 ); assert_eq!(effective_session_id(None, Some("".into())), None);
2007 assert_eq!(effective_session_id(None, None), None);
2008 }
2009
2010 fn project_binding(id: &str, name: &str) -> crate::session_state::ProjectBinding {
2011 crate::session_state::ProjectBinding {
2012 project_id: id.into(),
2013 project_name: name.into(),
2014 updated_at: "t".into(),
2015 }
2016 }
2017
2018 fn repo_binding_for_attribution(id: &str) -> crate::session_state::RepoBinding {
2022 crate::session_state::RepoBinding {
2023 repo_id: id.into(),
2024 git_url: None,
2025 remote_id: None,
2026 codebase_name: None,
2027 updated_at: "t".into(),
2028 }
2029 }
2030
2031 #[test]
2032 fn recording_check_truth_table() {
2033 let repo_attr = crate::commands::stream::Attribution::Repo {
2038 repo_id: "11111111-1111-4111-8111-111111111111".into(),
2039 project: None,
2040 };
2041 let project_attr = crate::commands::stream::Attribution::ProjectOnly {
2042 project_id: uuid::Uuid::from_u128(1),
2043 };
2044
2045 assert!(recording_check(None, None).is_none());
2048 assert!(recording_check(None, Some(&repo_attr)).is_none());
2049 assert!(recording_check(None, Some(&project_attr)).is_none());
2050
2051 assert!(recording_check(Some("s"), Some(&repo_attr)).is_none());
2053 assert!(recording_check(Some("s"), Some(&project_attr)).is_none());
2054
2055 assert_eq!(
2057 recording_check(Some("s"), None).map(|c| c.level),
2058 Some(Level::Error)
2059 );
2060 }
2061
2062 #[test]
2063 fn recording_check_error_names_project_switch_and_session() {
2064 let check = recording_check(Some("3f27a336-abcd"), None).expect("expected an Error check");
2069 assert_eq!(check.level, Level::Error);
2070 assert!(
2071 check.detail.contains("project switch"),
2072 "detail: {}",
2073 check.detail
2074 );
2075 assert!(
2076 check.detail.contains("3f27a336-abcd"),
2077 "detail: {}",
2078 check.detail
2079 );
2080 }
2081
2082 #[test]
2083 fn project_binding_check_tiers_capture_project_honors_are_ok() {
2084 use crate::resolution::ProjectSource::*;
2091 for source in [ProjectFlag, Subagent, SessionActive, UserDefault] {
2092 let outcome: ProjectOutcome = Ok(Some((
2093 project_binding("33333333-3333-4333-8333-333333333333", "My Project"),
2094 source,
2095 )));
2096 let check = project_binding_check(&outcome);
2097 assert_eq!(check.level, Level::Ok, "source={source} should read Ok");
2098 assert!(
2099 check.detail.contains("My Project"),
2100 "source={source} detail: {}",
2101 check.detail
2102 );
2103 }
2104 }
2105
2106 #[test]
2107 fn project_binding_check_config_default_is_warn_not_ok() {
2108 let outcome: ProjectOutcome = Ok(Some((
2112 project_binding("pid-3", "My Project"),
2113 crate::resolution::ProjectSource::ConfigDefault,
2114 )));
2115 let check = project_binding_check(&outcome);
2116 assert_eq!(check.level, Level::Warn);
2117 assert!(
2118 check
2119 .detail
2120 .contains("not used for attribution at capture time"),
2121 "detail: {}",
2122 check.detail
2123 );
2124 }
2125
2126 #[test]
2127 fn project_binding_check_deduced_is_warn() {
2128 let outcome: ProjectOutcome = Ok(Some((
2131 project_binding("pid-2", ""),
2132 crate::resolution::ProjectSource::Deduced,
2133 )));
2134 let check = project_binding_check(&outcome);
2135 assert_eq!(check.level, Level::Warn);
2136 assert!(
2137 check
2138 .detail
2139 .contains("not used for attribution at capture time"),
2140 "detail: {}",
2141 check.detail
2142 );
2143 }
2144
2145 #[test]
2146 fn project_binding_check_malformed_project_id_is_warn_not_ok() {
2147 use crate::resolution::ProjectSource::{SessionActive, UserDefault};
2154 for source in [SessionActive, UserDefault] {
2155 let outcome: ProjectOutcome =
2156 Ok(Some((project_binding("not-a-uuid", "My Project"), source)));
2157 let check = project_binding_check(&outcome);
2158 assert_eq!(check.level, Level::Warn, "source={source}");
2159 assert!(
2160 check.detail.contains("not a valid id"),
2161 "source={source} detail: {}",
2162 check.detail
2163 );
2164 }
2165 }
2166
2167 #[test]
2168 fn project_binding_check_ambiguous_err_is_warn_not_error() {
2169 let outcome: ProjectOutcome =
2175 Err("this repo belongs to multiple projects; select one with `tracevault project switch <name>`".into());
2176 let check = project_binding_check(&outcome);
2177 assert_eq!(check.level, Level::Warn);
2178 assert!(
2179 check.detail.contains("multiple projects"),
2180 "detail: {}",
2181 check.detail
2182 );
2183 }
2184
2185 #[test]
2186 fn project_binding_check_none_is_skip() {
2187 let outcome: ProjectOutcome = Ok(None);
2188 let check = project_binding_check(&outcome);
2189 assert_eq!(check.level, Level::Skip);
2190 }
2191
2192 #[test]
2216 fn verdict_repo_user_default_alone_is_not_an_error() {
2217 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2219 let cfg_tmp = tempfile::tempdir().unwrap();
2220 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2221 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2222 _guard.set("HOME", cfg_tmp.path()); crate::user_default::save(&repo_binding_for_attribution(
2225 "11111111-1111-4111-8111-111111111111",
2226 ))
2227 .unwrap();
2228
2229 let cwd = tempfile::tempdir().unwrap();
2230 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2231 assert_eq!(
2232 attribution,
2233 Some(crate::commands::stream::Attribution::Repo {
2234 repo_id: "11111111-1111-4111-8111-111111111111".into(),
2235 project: None,
2236 })
2237 );
2238 assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
2239 }
2240
2241 #[test]
2242 fn verdict_project_user_default_alone_is_not_an_error() {
2243 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2247 let cfg_tmp = tempfile::tempdir().unwrap();
2248 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2249 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2250 _guard.set("HOME", cfg_tmp.path()); let pb = crate::session_state::ProjectBinding {
2253 project_id: uuid::Uuid::from_u128(7).to_string(),
2254 project_name: "p".into(),
2255 updated_at: "".into(),
2256 };
2257 crate::user_project_default::save(&pb).unwrap();
2258
2259 let cwd = tempfile::tempdir().unwrap();
2260 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2261 assert_eq!(
2262 attribution,
2263 Some(crate::commands::stream::Attribution::ProjectOnly {
2264 project_id: uuid::Uuid::from_u128(7)
2265 })
2266 );
2267 assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
2268 }
2269
2270 #[test]
2271 fn verdict_config_without_repo_id_and_nothing_else_is_error() {
2272 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2275 let cfg_tmp = tempfile::tempdir().unwrap();
2276 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2277 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2278 _guard.set("HOME", cfg_tmp.path()); let config = crate::config::TracevaultConfig::default();
2281 assert!(
2282 crate::resolution::binding_from_config(&config).is_none(),
2283 "a repo_id-less config must not bind"
2284 );
2285
2286 let cwd = tempfile::tempdir().unwrap();
2287 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
2288 assert_eq!(
2289 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2290 Some(Level::Error)
2291 );
2292 }
2293
2294 #[test]
2295 fn verdict_nothing_anywhere_is_error() {
2296 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2297 let cfg_tmp = tempfile::tempdir().unwrap();
2298 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2299 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2300 _guard.set("HOME", cfg_tmp.path()); let cwd = tempfile::tempdir().unwrap();
2303 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2304 assert_eq!(
2305 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2306 Some(Level::Error)
2307 );
2308 }
2309
2310 #[test]
2311 fn verdict_deduced_project_display_does_not_suppress_recording_error() {
2312 let outcome: ProjectOutcome = Ok(Some((
2315 project_binding("pid", ""),
2316 crate::resolution::ProjectSource::Deduced,
2317 )));
2318 assert_eq!(project_binding_check(&outcome).level, Level::Warn);
2319
2320 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2321 let cfg_tmp = tempfile::tempdir().unwrap();
2322 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2323 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2324 _guard.set("HOME", cfg_tmp.path()); let cwd = tempfile::tempdir().unwrap();
2327 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2328 assert_eq!(
2329 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2330 Some(Level::Error),
2331 "a Deduced display value must not suppress the Recording error"
2332 );
2333 }
2334
2335 #[test]
2336 fn verdict_deduction_failure_is_warn_and_does_not_affect_recording() {
2337 let outcome: ProjectOutcome = Err("this repo belongs to multiple projects".into());
2342 assert_eq!(project_binding_check(&outcome).level, Level::Warn);
2343
2344 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2345 let cfg_tmp = tempfile::tempdir().unwrap();
2346 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2347 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2348 _guard.set("HOME", cfg_tmp.path()); let config = crate::config::TracevaultConfig {
2351 repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
2352 ..Default::default()
2353 };
2354 let cwd = tempfile::tempdir().unwrap();
2355 let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
2356 assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
2359 }
2360
2361 #[test]
2362 fn offline_project_outcome_falls_back_to_saved_user_default() {
2363 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2367 let cfg_tmp = tempfile::tempdir().unwrap();
2368 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2369 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2370 _guard.set("HOME", cfg_tmp.path()); let pb = crate::session_state::ProjectBinding {
2373 project_id: uuid::Uuid::from_u128(9).to_string(),
2374 project_name: "My Project".into(),
2375 updated_at: "".into(),
2376 };
2377 crate::user_project_default::save(&pb).unwrap();
2378
2379 let session = crate::session_state::SessionState::default();
2380 let inputs = ProjectResolveInputs {
2381 project_flag: None,
2382 session: &session,
2383 worktree_path: None,
2384 config_default: None,
2385 };
2386 let user_default_project = crate::user_project_default::load();
2388 let outcome = offline_project_outcome(&inputs, user_default_project);
2389 let check = project_binding_check(&outcome);
2390 assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
2391 assert!(
2392 check.detail.contains("My Project"),
2393 "detail: {}",
2394 check.detail
2395 );
2396 }
2397
2398 #[test]
2399 fn recording_attribution_finds_subagent_override_via_linked_worktree_cwd() {
2400 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2404 let cfg_tmp = tempfile::tempdir().unwrap();
2405 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2406 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2407 _guard.set("HOME", cfg_tmp.path()); let base = tempfile::tempdir().unwrap();
2410 let repo_dir = base.path().join("repo");
2411 let wt_dir = base.path().join("wt");
2412 std::fs::create_dir_all(&repo_dir).unwrap();
2413 crate::test_helpers::init_git_repo(&repo_dir);
2414 crate::test_helpers::add_worktree(&repo_dir, &wt_dir);
2415
2416 let wt_key = crate::paths::worktree_toplevel(&wt_dir);
2417 let project_id = uuid::Uuid::from_u128(42);
2418 let mut subagent_projects = std::collections::HashMap::new();
2419 subagent_projects.insert(
2420 wt_key,
2421 crate::session_state::ProjectBinding {
2422 project_id: project_id.to_string(),
2423 project_name: "linked".into(),
2424 updated_at: "t".into(),
2425 },
2426 );
2427 let state = crate::session_state::SessionState {
2428 subagent_projects,
2429 ..Default::default()
2430 };
2431 let sessions_dir = tempfile::tempdir().unwrap();
2432 std::fs::write(
2433 sessions_dir.path().join("sess-linked.toml"),
2434 toml::to_string(&state).unwrap(),
2435 )
2436 .unwrap();
2437
2438 let (found, _worktree) = recording_attribution(
2440 Some(sessions_dir.path()),
2441 Some("sess-linked"),
2442 &wt_dir,
2443 None,
2444 );
2445 assert_eq!(
2446 found,
2447 Some(crate::commands::stream::Attribution::ProjectOnly { project_id })
2448 );
2449
2450 let (missed, _worktree) = recording_attribution(
2453 Some(sessions_dir.path()),
2454 Some("sess-linked"),
2455 &repo_dir,
2456 None,
2457 );
2458 assert_eq!(missed, None);
2459 }
2460
2461 #[test]
2462 fn verdict_malformed_project_id_leaves_project_axis_unbound() {
2463 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2467 let cfg_tmp = tempfile::tempdir().unwrap();
2468 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2469 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2470 _guard.set("HOME", cfg_tmp.path()); let state = crate::session_state::SessionState {
2473 active_project: Some(project_binding("not-a-uuid", "My Project")),
2474 ..Default::default()
2475 };
2476 let sessions_dir = tempfile::tempdir().unwrap();
2477 std::fs::write(
2478 sessions_dir.path().join("sess-bad-project.toml"),
2479 toml::to_string(&state).unwrap(),
2480 )
2481 .unwrap();
2482
2483 let cwd = tempfile::tempdir().unwrap();
2484 let (attribution, _worktree) = recording_attribution(
2485 Some(sessions_dir.path()),
2486 Some("sess-bad-project"),
2487 cwd.path(),
2488 None,
2489 );
2490 assert_eq!(
2491 attribution, None,
2492 "a malformed project_id must not resolve an attribution"
2493 );
2494 assert_eq!(
2495 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2496 Some(Level::Error)
2497 );
2498 }
2499
2500 #[test]
2501 fn verdict_malformed_repo_id_with_nothing_else_bound_is_error() {
2502 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2506 let cfg_tmp = tempfile::tempdir().unwrap();
2507 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2508 _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2509 _guard.set("HOME", cfg_tmp.path()); let state = crate::session_state::SessionState {
2512 active: Some(crate::session_state::RepoBinding {
2513 repo_id: "not-a-uuid".into(),
2514 git_url: None,
2515 remote_id: None,
2516 codebase_name: None,
2517 updated_at: "t".into(),
2518 }),
2519 ..Default::default()
2520 };
2521 let sessions_dir = tempfile::tempdir().unwrap();
2522 std::fs::write(
2523 sessions_dir.path().join("sess-bad-repo.toml"),
2524 toml::to_string(&state).unwrap(),
2525 )
2526 .unwrap();
2527
2528 let cwd = tempfile::tempdir().unwrap();
2529 let (attribution, _worktree) = recording_attribution(
2530 Some(sessions_dir.path()),
2531 Some("sess-bad-repo"),
2532 cwd.path(),
2533 None,
2534 );
2535 assert_eq!(
2536 attribution, None,
2537 "a malformed repo_id must not resolve an attribution"
2538 );
2539 assert_eq!(
2540 recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2541 Some(Level::Error)
2542 );
2543 }
2544
2545 #[test]
2546 fn unresolved_config_default_check_names_it_and_is_warn() {
2547 let check = unresolved_config_default_check("payments-platform");
2548 assert_eq!(check.level, Level::Warn);
2549 assert!(
2550 check.detail.contains("payments-platform"),
2551 "detail: {}",
2552 check.detail
2553 );
2554 assert!(
2555 check
2556 .detail
2557 .contains("not used for attribution at capture time"),
2558 "detail should not imply resolving it would make capture-time \
2559 attribution work: {}",
2560 check.detail
2561 );
2562 }
2563}