1use crate::api_client::{ApiClient, CheckPoliciesRequest, SessionCheckData};
2use crate::credentials::resolve_credentials;
3use crate::program::CLI;
4use crate::resolution::{resolve_repo_by_name, ResolveRepoByNameError};
5use std::collections::HashSet;
6use std::fs;
7use std::path::Path;
8use std::process::Command;
9
10fn git_head_sha(project_root: &Path) -> Option<String> {
11 let out = Command::new("git")
12 .args(["rev-parse", "HEAD"])
13 .current_dir(project_root)
14 .output()
15 .ok()?;
16 if !out.status.success() {
17 return None;
18 }
19 let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
20 if sha.is_empty() {
21 None
22 } else {
23 Some(sha)
24 }
25}
26
27#[derive(Debug, PartialEq)]
29pub(crate) struct PushRef {
30 pub local_sha: String,
31 pub remote_sha: String,
32}
33
34fn is_zero_sha(sha: &str) -> bool {
35 !sha.is_empty() && sha.chars().all(|c| c == '0')
36}
37
38pub(crate) fn parse_push_refs(stdin: &str) -> Vec<PushRef> {
43 stdin
44 .lines()
45 .filter_map(|line| {
46 let mut parts = line.split_whitespace();
47 let _local_ref = parts.next()?;
48 let local_sha = parts.next()?;
49 let _remote_ref = parts.next()?;
50 let remote_sha = parts.next()?;
51 if is_zero_sha(local_sha) {
52 return None;
53 }
54 Some(PushRef {
55 local_sha: local_sha.to_string(),
56 remote_sha: remote_sha.to_string(),
57 })
58 })
59 .collect()
60}
61
62fn changed_files_for_refs(project_root: &Path, refs: &[PushRef]) -> Vec<String> {
66 let mut seen = HashSet::new();
67 let mut out = Vec::new();
68 for r in refs {
69 let base = if is_zero_sha(&r.remote_sha) {
73 match git_empty_tree_sha(project_root) {
74 Some(t) => t,
75 None => continue,
76 }
77 } else {
78 r.remote_sha.clone()
79 };
80 let out_bytes = Command::new("git")
81 .args([
82 "diff",
83 "--name-only",
84 "-z",
90 "--no-renames",
95 &format!("{base}..{}", r.local_sha),
96 ])
97 .current_dir(project_root)
98 .output();
99 let Ok(o) = out_bytes else { continue };
100 if !o.status.success() {
101 continue;
102 }
103 for p in split_nul_delimited_paths(&o.stdout) {
104 if seen.insert(p.clone()) {
105 out.push(p);
106 }
107 }
108 }
109 out
110}
111
112fn split_nul_delimited_paths(bytes: &[u8]) -> Vec<String> {
122 String::from_utf8_lossy(bytes)
123 .split('\0')
124 .filter(|p| !p.is_empty())
125 .map(|p| p.to_string())
126 .collect()
127}
128
129fn git_empty_tree_sha(project_root: &Path) -> Option<String> {
132 let out = Command::new("git")
133 .args(["hash-object", "-t", "tree", "/dev/null"])
134 .current_dir(project_root)
135 .output()
136 .ok()?;
137 if !out.status.success() {
138 return None;
139 }
140 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
141 if s.is_empty() {
142 None
143 } else {
144 Some(s)
145 }
146}
147
148const STDIN_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
154
155fn read_with_timeout<F>(f: F, timeout: std::time::Duration) -> Option<String>
167where
168 F: FnOnce() -> Option<String> + Send + 'static,
169{
170 let (tx, rx) = std::sync::mpsc::channel();
171 std::thread::spawn(move || {
172 let _ = tx.send(f());
173 });
174 rx.recv_timeout(timeout).ok().flatten()
175}
176
177fn read_stdin_with_timeout(timeout: std::time::Duration) -> Option<String> {
185 use std::io::Read;
186 read_with_timeout(
187 || {
188 let mut buf = String::new();
189 std::io::stdin().read_to_string(&mut buf).ok().map(|_| buf)
190 },
191 timeout,
192 )
193}
194
195fn resolve_changed_paths(project_root: &Path) -> Option<Vec<String>> {
206 use std::io::IsTerminal;
207
208 if !std::io::stdin().is_terminal() {
214 if let Some(buf) = read_stdin_with_timeout(STDIN_READ_TIMEOUT) {
215 let refs = parse_push_refs(&buf);
216 if !refs.is_empty() {
217 let files = changed_files_for_refs(project_root, &refs);
227 return if files.is_empty() { None } else { Some(files) };
228 }
229 }
230 }
231
232 let out = Command::new("git")
236 .args([
237 "diff",
238 "--name-only",
239 "-z",
240 "--no-renames",
241 "@{upstream}..HEAD",
242 ])
243 .current_dir(project_root)
244 .output()
245 .ok()?;
246 if !out.status.success() {
247 return None;
248 }
249 let files = split_nul_delimited_paths(&out.stdout);
250 if files.is_empty() {
251 None
252 } else {
253 Some(files)
254 }
255}
256
257fn collect_session_data(session_dir: &Path) -> Option<SessionCheckData> {
258 let session_id = session_dir.file_name()?.to_string_lossy().to_string();
259
260 let events_path = session_dir.join("events.jsonl");
262 let mut files_modified = Vec::new();
263 let mut files_seen = HashSet::new();
264
265 if events_path.exists() {
266 if let Ok(content) = fs::read_to_string(&events_path) {
267 for line in content.lines() {
268 let event: serde_json::Value = match serde_json::from_str(line) {
269 Ok(v) => v,
270 Err(_) => continue,
271 };
272 if let Some(path) = event
273 .get("tool_input")
274 .and_then(|v| v.get("file_path"))
275 .and_then(|v| v.as_str())
276 {
277 if files_seen.insert(path.to_string()) {
278 files_modified.push(path.to_string());
279 }
280 }
281 }
282 }
283 }
284
285 let meta_path = session_dir.join("metadata.json");
287 let metadata: Option<serde_json::Value> = meta_path
288 .exists()
289 .then(|| fs::read_to_string(&meta_path).ok())
290 .flatten()
291 .and_then(|c| serde_json::from_str(&c).ok());
292
293 let transcript_path = metadata
294 .as_ref()
295 .and_then(|m| m.get("transcript_path"))
296 .and_then(|v| v.as_str())
297 .map(|s| s.to_string());
298
299 let tool_calls_map = transcript_path
300 .as_deref()
301 .map(|p| crate::transcript::count_tool_calls(Path::new(p)))
302 .unwrap_or_default();
303 let total_tool_calls: i32 = tool_calls_map.values().sum();
304
305 let tool_calls = if tool_calls_map.is_empty() {
306 None
307 } else {
308 serde_json::to_value(&tool_calls_map).ok()
309 };
310
311 Some(SessionCheckData {
312 session_id,
313 tool_calls,
314 files_modified: if files_modified.is_empty() {
315 None
316 } else {
317 Some(files_modified)
318 },
319 total_tool_calls: if total_tool_calls > 0 {
320 Some(total_tool_calls)
321 } else {
322 None
323 },
324 })
325}
326
327pub fn select_worktree_sessions(
338 session_dirs: Vec<std::path::PathBuf>,
339 worktree_top: &str,
340) -> (Vec<std::path::PathBuf>, bool) {
341 let belongs = |dir: &std::path::Path| -> bool {
342 match fs::read_to_string(dir.join("origin")) {
343 Ok(s) => s.trim() == worktree_top || crate::session_state::ran_in(dir, worktree_top),
346 Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
348 Err(_) => false,
353 }
354 };
355 let filtered: Vec<_> = session_dirs
356 .iter()
357 .filter(|d| belongs(d))
358 .cloned()
359 .collect();
360 if filtered.is_empty() && !session_dirs.is_empty() {
361 (session_dirs, true)
362 } else {
363 (filtered, false)
364 }
365}
366
367fn select_with_external(
371 local: Vec<std::path::PathBuf>,
372 external: Vec<std::path::PathBuf>,
373 worktree_top: &str,
374) -> Vec<std::path::PathBuf> {
375 let (mut selected, fell_back) = select_worktree_sessions(local, worktree_top);
376 if fell_back {
377 if external.is_empty() {
378 eprintln!(
379 "Warning: no unpushed session matched this worktree by origin marker — \
380 checking all unpushed sessions to avoid skipping policy enforcement."
381 );
382 } else {
383 selected.clear();
384 }
385 }
386 selected.extend(external);
387 selected
388}
389
390fn add_external_session(
398 selected: &mut Vec<std::path::PathBuf>,
399 sessions_dir: &Path,
400 dir: std::path::PathBuf,
401) {
402 let local = dir
403 .parent()
404 .is_some_and(|parent| crate::session_state::is_local_sessions_dir(parent, sessions_dir));
405 if local || !dir.is_dir() || dir.join(".pushed").exists() {
406 return;
407 }
408 if !selected.contains(&dir) {
409 selected.push(dir);
410 }
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
415struct PushedRepo {
416 id: uuid::Uuid,
417 remote_id: Option<uuid::Uuid>,
419}
420
421async fn resolve_pushed_repo(
434 client: &ApiClient,
435 project_root: &Path,
436) -> Result<PushedRepo, Box<dyn std::error::Error>> {
437 match crate::resolution::resolve_path_to_binding(project_root, client).await {
438 Ok(Some(b)) => {
439 if let Ok(id) = b.repo_id.parse() {
440 return Ok(PushedRepo {
441 id,
442 remote_id: b.remote_id,
443 });
444 }
445 }
446 Ok(None) => {}
447 Err(e) => return Err(connectivity_message(&e.to_string()).into()),
448 }
449 match resolve_repo_by_name(client, project_root).await {
450 Ok(r) => Ok(PushedRepo {
451 id: r.id,
452 remote_id: None,
453 }),
454 Err(ResolveRepoByNameError::ListFailed(e)) => {
455 Err(connectivity_message(&e.to_string()).into())
456 }
457 Err(ResolveRepoByNameError::NotFound { repo_name }) => {
458 Err(format!("Repo '{repo_name}' not found on server. Run `{CLI} sync` first.").into())
459 }
460 }
461}
462
463fn streamed_elsewhere_warning(
475 streamed_to: Option<&crate::session_state::RepoBinding>,
476 pushed: &PushedRepo,
477) -> Option<String> {
478 let b = streamed_to?;
479 if b.repo_id == pushed.id.to_string() {
480 return None;
481 }
482 let scope = match (b.remote_id, pushed.remote_id) {
483 (Some(a), Some(p)) if a == p => "another repo of this codebase",
484 (Some(_), Some(_)) => "a different codebase",
485 _ => "a different repo",
486 };
487 Some(format!(
488 "Warning: an unpushed session streamed its events to {scope} ({}), not to the repo \
489 this push is checked under ({}). Its verification-phase data will not be found; \
490 run `{CLI} repo switch <this checkout>` in that session.",
491 b.repo_id, pushed.id
492 ))
493}
494
495pub async fn check_policies(
506 project_root: &Path,
507 cwd: &Path,
508) -> Result<(), Box<dyn std::error::Error>> {
509 let (server_url, credential) = resolve_credentials(project_root)?;
510
511 let server_url = server_url.ok_or(crate::program::say(
512 "No server URL configured. Run `tracevault login --server-url=<url>` to set one.",
513 ))?;
514
515 if credential.is_none() {
516 return Err(crate::program::say(
517 "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate.",
518 )
519 .into());
520 }
521
522 let client = ApiClient::with_credential(&server_url, credential);
523
524 let repo = resolve_pushed_repo(&client, project_root).await?;
534
535 let sessions_dir = crate::layout::sessions_dir(project_root);
537 let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
538 for dir in crate::layout::existing_sessions_dirs(project_root) {
539 for entry in fs::read_dir(&dir)? {
540 let entry = entry?;
541 if !entry.file_type()?.is_dir() {
542 continue;
543 }
544 let session_dir = entry.path();
545 if session_dir.join(".pushed").exists() {
546 continue;
547 }
548 unpushed_dirs.push(session_dir);
549 }
550 }
551
552 let worktree_top = crate::paths::worktree_toplevel(cwd);
555 let invoking = crate::session_state::env_session_id()
561 .filter(|id| crate::session_state::is_safe_session_id(id))
562 .map(|id| crate::session_state::session_dir(project_root, &id));
563 let mut external = Vec::new();
564 for dir in crate::session_state::anchored_session_dirs(&sessions_dir, &worktree_top)
565 .into_iter()
566 .chain(invoking)
567 {
568 add_external_session(&mut external, &sessions_dir, dir);
569 }
570 let selected_dirs = select_with_external(unpushed_dirs, external, &worktree_top);
571
572 let bound = match crate::config::TracevaultConfig::try_load(project_root) {
577 Ok(cfg) => cfg
578 .as_ref()
579 .and_then(crate::resolution::binding_from_config),
580 Err(e) => {
581 eprintln!("Warning: ignoring malformed .visdom/tracing.toml: {e}");
582 None
583 }
584 };
585 let user_default = crate::user_default::load();
586
587 let mut sessions = Vec::new();
588 for session_dir in &selected_dirs {
589 if let Some(data) = collect_session_data(session_dir) {
590 let state = crate::session_state::load(&data.session_id);
591 let streamed_to = crate::resolution::recorded_session_binding(
592 session_dir,
593 &worktree_top,
594 &state,
595 bound.clone(),
596 user_default.clone(),
597 );
598 if let Some(w) = streamed_elsewhere_warning(streamed_to.as_ref(), &repo) {
599 eprintln!("{w}");
600 }
601 sessions.push(data);
602 }
603 }
604
605 if sessions.is_empty() {
606 println!("No unpushed sessions to check.");
607 return Ok(());
608 }
609
610 println!("Checking {} session(s) against policies...", sessions.len());
611
612 let commit_sha = git_head_sha(cwd);
615 let changed_paths = resolve_changed_paths(cwd);
616 let result = client
617 .check_policies(
618 &repo.id,
619 CheckPoliciesRequest {
620 sessions,
621 commit_sha,
622 changed_paths,
623 },
624 )
625 .await
626 .map_err(|e| connectivity_message(&e.to_string()))?;
627
628 for r in &result.results {
630 let icon = match r.result.as_str() {
631 "pass" => "\x1b[32m✓\x1b[0m", "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", "fail" => "\x1b[33m!\x1b[0m", _ => " ",
635 };
636 println!(
637 " {} [{}] {} — {}",
638 icon, r.severity, r.rule_name, r.details
639 );
640 }
641
642 if result.blocked {
643 eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
644 std::process::exit(1);
645 } else if result.passed {
646 println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
647 } else {
648 println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
649 }
650
651 Ok(())
652}
653
654fn connectivity_message(raw: &str) -> String {
662 let lower = raw.to_ascii_lowercase();
663
664 if lower.contains("401") || lower.contains("unauthorized") {
667 return with_action(
668 raw,
669 &crate::program::say("Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh."),
670 );
671 }
672 if lower.contains("403") || lower.contains("forbidden") {
675 return with_action(
676 raw,
677 &crate::program::say("Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`."),
678 );
679 }
680 if lower.contains("404") {
688 return with_action(
689 raw,
690 "This server may not recognize this endpoint yet — this can happen when the CLI is newer than the server. Confirm the server has been upgraded, or downgrade the CLI to match it.",
691 );
692 }
693 if is_server_error(&lower) {
696 return with_action(
697 raw,
698 "Visdom server returned an error. The team has likely been paged; retry shortly.",
699 );
700 }
701 if lower.contains("dns")
704 || lower.contains("connect")
705 || lower.contains("timed out")
706 || lower.contains("timeout")
707 {
708 return with_action(
709 raw,
710 "Could not reach the Visdom server. Check network and `server_url` in .visdom/tracing.toml.",
711 );
712 }
713 format!("Policy check could not run: {raw}.")
715}
716
717fn with_action(raw: &str, action: &str) -> String {
719 format!("Policy check could not run: {raw}.\n → {action}")
720}
721
722fn is_server_error(lower: &str) -> bool {
727 lower.contains("internal")
728 || lower.contains("server error")
729 || ["500", "501", "502", "503", "504"]
730 .iter()
731 .any(|code| lower.contains(code))
732}
733
734#[cfg(test)]
735mod worktree_tests {
736 use super::{add_external_session, select_with_external, select_worktree_sessions};
737
738 #[test]
739 fn an_external_match_stops_the_fall_back_to_every_local_session() {
740 let tmp = tempfile::tempdir().unwrap();
741 let other = seed(tmp.path(), "other", Some("/wt/b"));
742 let ext = tmp.path().join("umbrella-session");
743 assert_eq!(
744 select_with_external(vec![other.clone()], vec![ext.clone()], "/wt/a"),
745 vec![ext.clone()]
746 );
747 assert_eq!(
748 select_with_external(vec![other.clone()], vec![], "/wt/a"),
749 vec![other.clone()],
750 "no match at all still checks everything"
751 );
752 let mine = seed(tmp.path(), "mine", Some("/wt/a"));
753 assert_eq!(
754 select_with_external(vec![mine.clone(), other], vec![ext.clone()], "/wt/a"),
755 vec![mine, ext]
756 );
757 }
758 use std::path::PathBuf;
759
760 #[test]
763 fn keeps_a_session_that_ran_here_before_moving_on() {
764 let tmp = tempfile::tempdir().unwrap();
765 let moved = seed(tmp.path(), "moved", Some("/wt/b"));
766 crate::session_state::record_worktree(&moved, "/wt/a").unwrap();
767 crate::session_state::record_worktree(&moved, "/wt/b").unwrap();
768 let mine = seed(tmp.path(), "mine", Some("/wt/a"));
769 let other = seed(tmp.path(), "other", Some("/wt/b"));
770 let (mut kept, fell_back) =
771 select_worktree_sessions(vec![moved.clone(), mine.clone(), other], "/wt/a");
772 kept.sort();
773 assert_eq!(kept, vec![mine, moved]);
774 assert!(!fell_back);
775 }
776
777 #[test]
778 fn adds_an_external_session_only_when_it_lives_elsewhere() {
779 let tmp = tempfile::tempdir().unwrap();
780 let here = tmp.path().join("repo/.visdom/sessions");
781 let local = seed(&here, "local", Some("/wt/b"));
782 let elsewhere = seed(
783 &tmp.path().join("umbrella/.visdom/sessions"),
784 "s",
785 Some("/u"),
786 );
787 let pushed = seed(&tmp.path().join("umbrella/.visdom/sessions"), "p", None);
788 std::fs::write(pushed.join(".pushed"), "").unwrap();
789
790 let mut selected = vec![];
791 add_external_session(&mut selected, &here, local);
792 assert!(
793 selected.is_empty(),
794 "a local dir is the worktree filter's call"
795 );
796
797 add_external_session(&mut selected, &here, elsewhere.clone());
798 add_external_session(&mut selected, &here, elsewhere.clone());
799 add_external_session(&mut selected, &here, tmp.path().join("missing"));
800 add_external_session(&mut selected, &here, pushed);
801 assert_eq!(selected, vec![elsewhere]);
802 }
803
804 fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
805 let d = tmp.join(id);
806 std::fs::create_dir_all(&d).unwrap();
807 if let Some(o) = origin {
808 std::fs::write(d.join("origin"), o).unwrap();
809 }
810 d
811 }
812
813 #[test]
814 fn keeps_current_worktree_and_unmarked_excludes_other() {
815 let tmp = tempfile::tempdir().unwrap();
816 let mine = seed(tmp.path(), "mine", Some("/wt/here"));
817 let other = seed(tmp.path(), "other", Some("/wt/there"));
818 let legacy = seed(tmp.path(), "legacy", None);
819
820 let (kept, fell_back) = select_worktree_sessions(
821 vec![mine.clone(), other.clone(), legacy.clone()],
822 "/wt/here",
823 );
824
825 assert!(!fell_back);
826 assert!(kept.contains(&mine), "current worktree session kept");
827 assert!(
828 kept.contains(&legacy),
829 "unmarked legacy session kept (conservative)"
830 );
831 assert!(
832 !kept.contains(&other),
833 "other worktree's marked session excluded"
834 );
835 }
836
837 #[test]
838 fn excludes_session_with_unreadable_marker() {
839 let tmp = tempfile::tempdir().unwrap();
840 let mine = seed(tmp.path(), "mine", Some("/wt/here"));
841 let bad = tmp.path().join("bad");
844 std::fs::create_dir_all(bad.join("origin")).unwrap();
845
846 let (kept, fell_back) =
847 select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
848
849 assert!(!fell_back);
850 assert!(kept.contains(&mine), "current worktree session kept");
851 assert!(
852 !kept.contains(&bad),
853 "session with a present-but-unreadable marker must be excluded, not kept as legacy"
854 );
855 }
856
857 #[test]
858 fn falls_back_to_all_when_nothing_matches() {
859 let tmp = tempfile::tempdir().unwrap();
860 let a = seed(tmp.path(), "a", Some("/wt/there"));
861 let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
862
863 let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
864
865 assert!(fell_back, "must flag fallback when filter matches nothing");
866 assert_eq!(
867 kept.len(),
868 2,
869 "never under-enforce: send all rather than zero"
870 );
871 }
872}
873
874#[cfg(test)]
875mod tests {
876 use super::{collect_session_data, connectivity_message};
877
878 #[test]
882 fn counts_tool_calls_from_the_transcript_the_stream_hook_recorded() {
883 let tmp = tempfile::tempdir().unwrap();
884 let transcript = tmp.path().join("t.jsonl");
885 std::fs::write(
886 &transcript,
887 concat!(
888 r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
889 "\n",
890 r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash"},{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
891 "\n",
892 ),
893 )
894 .unwrap();
895 let session_dir = tmp.path().join("sess-1");
896 std::fs::create_dir_all(&session_dir).unwrap();
897
898 let before = collect_session_data(&session_dir).unwrap();
899 assert!(
900 before.tool_calls.is_none(),
901 "no metadata.json, no tool calls"
902 );
903
904 crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
905 .unwrap();
906 let after = collect_session_data(&session_dir).unwrap();
907
908 assert_eq!(after.session_id, "sess-1");
909 assert_eq!(after.total_tool_calls, Some(3));
910 assert_eq!(
911 after.tool_calls,
912 Some(serde_json::json!({"mcp__cargo__cargo_check": 2, "Bash": 1}))
913 );
914 }
915
916 fn tool_calls_from_transcript(lines: &[&str]) -> Option<serde_json::Value> {
919 let tmp = tempfile::tempdir().unwrap();
920 let transcript = tmp.path().join("t.jsonl");
921 std::fs::write(&transcript, lines.join("\n")).unwrap();
922 let session_dir = tmp.path().join("sess");
923 std::fs::create_dir_all(&session_dir).unwrap();
924 crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
925 .unwrap();
926 collect_session_data(&session_dir).unwrap().tool_calls
927 }
928
929 #[test]
930 fn counts_tool_calls_from_a_codex_rollout() {
931 let calls = tool_calls_from_transcript(&[
932 r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix it"}]}}"#,
933 r#"{"type":"response_item","payload":{"type":"custom_tool_call","name":"apply_patch","input":"*** Begin Patch\n*** End Patch\n"}}"#,
934 r#"{"type":"response_item","payload":{"type":"function_call","name":"mcp__cargo__cargo_check","arguments":"{}"}}"#,
935 r#"{"type":"response_item","payload":{"type":"local_shell_call","command":"ls"}}"#,
936 r#"{"type":"event_msg","payload":{"type":"token_count"}}"#,
937 ]);
938 assert_eq!(
939 calls,
940 Some(serde_json::json!({"apply_patch": 1, "mcp__cargo__cargo_check": 1, "Bash": 1}))
941 );
942 }
943
944 #[test]
945 fn counts_tool_calls_from_a_gsd_session() {
946 let calls = tool_calls_from_transcript(&[
947 r#"{"type":"model_change","provider":"anthropic","modelId":"claude-opus-4-7"}"#,
948 r#"{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"ok"},{"type":"toolCall","id":"t1","name":"write","arguments":{}},{"type":"toolCall","id":"t2","name":"bash","arguments":{}}]}}"#,
949 r#"{"type":"message","message":{"role":"toolResult","toolName":"write","content":[]}}"#,
950 ]);
951 assert_eq!(calls, Some(serde_json::json!({"write": 1, "bash": 1})));
952 }
953
954 #[test]
957 fn counts_tool_calls_from_opencode_inline_records() {
958 let tmp = tempfile::tempdir().unwrap();
959 let tool_event = [
960 serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"toolCall","name":"bash","arguments":{"command":"ls"}}]}}),
961 serde_json::json!({"type":"message","message":{"role":"toolResult","toolName":"bash","isError":false,"content":[{"type":"text","text":"a.rs"}]}}),
962 ];
963 let assistant_turn = [
964 serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"done"}]}}),
965 ];
966
967 crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
968 crate::commands::stream::record_inline_tool_calls(tmp.path(), &assistant_turn).unwrap();
969 assert!(collect_session_data(tmp.path())
970 .unwrap()
971 .tool_calls
972 .is_none());
973
974 crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
975 crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
976 let data = collect_session_data(tmp.path()).unwrap();
977 assert_eq!(data.tool_calls, Some(serde_json::json!({"bash": 2})));
978 assert_eq!(data.total_tool_calls, Some(2));
979 }
980
981 #[test]
984 fn counts_tool_calls_from_amp_inline_records() {
985 let tmp = tempfile::tempdir().unwrap();
986 let tool_event = [
987 serde_json::json!({"type":"amp_message","event":"tool.result","message":{"role":"assistant","content":[{"type":"tool_use","id":"TU-1","name":"shell_command","input":{"command":"ls"}}]}}),
988 serde_json::json!({"type":"amp_message","event":"tool.result","message":{"role":"user","content":[{"type":"tool_result","toolUseID":"TU-1","status":"done","output":{"output":"","exitCode":1}}]}}),
989 ];
990 let turn_end = [
991 serde_json::json!({"type":"amp_message","event":"agent.end","message":{"role":"assistant","content":[{"type":"text","text":"ok"},{"type":"tool_use","id":"TU-2","name":"Task","input":{}}],"usage":{"inputTokens":1}}}),
992 ];
993
994 crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
995 crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
996 crate::commands::stream::record_inline_tool_calls(tmp.path(), &turn_end).unwrap();
997 let data = collect_session_data(tmp.path()).unwrap();
998 assert_eq!(
999 data.tool_calls,
1000 Some(serde_json::json!({"shell_command": 1, "Task": 1}))
1001 );
1002 assert_eq!(data.total_tool_calls, Some(2));
1003 }
1004
1005 #[test]
1006 fn connectivity_message_suggests_login_on_401() {
1007 let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
1008 assert!(
1009 m.contains("tracevault login"),
1010 "401 errors must surface the login hint; got: {m}"
1011 );
1012 }
1013
1014 #[test]
1015 fn connectivity_message_suggests_login_on_unauthorized_text() {
1016 let m = connectivity_message("Server returned: unauthorized request");
1017 assert!(m.contains("tracevault login"));
1018 }
1019
1020 #[test]
1021 fn connectivity_message_suggests_network_check_on_dns_error() {
1022 let m = connectivity_message("error sending request for url: dns error");
1023 assert!(
1024 m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
1025 "DNS errors must surface a network hint; got: {m}"
1026 );
1027 }
1028
1029 #[test]
1030 fn connectivity_message_suggests_network_check_on_connection_refused() {
1031 let m = connectivity_message("connection refused");
1032 assert!(m.to_lowercase().contains("network"));
1033 }
1034
1035 #[test]
1036 fn connectivity_message_falls_back_when_unrecognized() {
1037 let m = connectivity_message("some weird new error shape we have not seen before");
1038 assert!(m.contains("some weird new error shape"));
1041 assert!(!m.contains("→")); }
1043
1044 #[test]
1045 fn connectivity_message_does_not_collide_on_403() {
1046 let m = connectivity_message("403 Forbidden");
1047 assert!(
1049 m.to_lowercase().contains("authorized"),
1050 "403 should mention authorization; got: {m}"
1051 );
1052 }
1053
1054 #[test]
1055 fn connectivity_message_flags_404_as_version_mismatch() {
1056 let m = connectivity_message("Failed to list repos (404 Not Found): ");
1061 assert!(
1062 m.to_lowercase().contains("newer than the server")
1063 || m.to_lowercase().contains("version mismatch"),
1064 "404 should hint at a possible CLI/server version mismatch; got: {m}"
1065 );
1066 }
1067
1068 #[test]
1069 fn connectivity_message_flags_500_as_server_error() {
1070 let m = connectivity_message("Server returned 500 Internal Server Error: oops");
1071 assert!(
1072 m.to_lowercase().contains("server returned an error"),
1073 "500 should surface the server-error hint; got: {m}"
1074 );
1075 }
1076
1077 #[test]
1078 fn connectivity_message_flags_503_without_internal_text() {
1079 let m = connectivity_message("Server returned 503 Service Unavailable: ");
1082 assert!(
1083 m.to_lowercase().contains("server returned an error"),
1084 "503 should surface the server-error hint; got: {m}"
1085 );
1086 }
1087
1088 #[test]
1089 fn connectivity_message_treats_504_as_server_not_network() {
1090 let m = connectivity_message("Server returned 504 Gateway Timeout: ");
1094 assert!(
1095 m.to_lowercase().contains("server returned an error"),
1096 "504 should be treated as a server error; got: {m}"
1097 );
1098 }
1099}
1100
1101#[cfg(test)]
1102mod push_ref_tests {
1103 use super::{is_zero_sha, parse_push_refs};
1104
1105 #[test]
1106 fn parses_a_single_ref_line() {
1107 let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456\n");
1108 assert_eq!(refs.len(), 1);
1109 assert_eq!(refs[0].local_sha, "abc123");
1110 assert_eq!(refs[0].remote_sha, "def456");
1111 }
1112
1113 #[test]
1114 fn parses_multiple_refs() {
1115 let refs = parse_push_refs(
1116 "refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444\n",
1117 );
1118 assert_eq!(refs.len(), 2);
1119 }
1120
1121 #[test]
1122 fn parses_a_single_ref_line_without_trailing_newline() {
1123 let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456");
1131 assert_eq!(refs.len(), 1);
1132 assert_eq!(refs[0].local_sha, "abc123");
1133 assert_eq!(refs[0].remote_sha, "def456");
1134 }
1135
1136 #[test]
1137 fn parses_multiple_refs_when_last_line_has_no_trailing_newline() {
1138 let refs =
1142 parse_push_refs("refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444");
1143 assert_eq!(refs.len(), 2);
1144 assert_eq!(refs[0].local_sha, "111");
1145 assert_eq!(refs[1].local_sha, "333");
1146 }
1147
1148 #[test]
1149 fn skips_branch_deletions() {
1150 let zeros = "0".repeat(40);
1151 let line = format!("(delete) {zeros} refs/heads/gone abc123\n");
1152 assert!(parse_push_refs(&line).is_empty());
1153 }
1154
1155 #[test]
1156 fn keeps_new_branches_whose_remote_sha_is_zero() {
1157 let zeros = "0".repeat(40);
1158 let line = format!("refs/heads/new abc123 refs/heads/new {zeros}\n");
1159 let refs = parse_push_refs(&line);
1160 assert_eq!(refs.len(), 1);
1161 assert!(is_zero_sha(&refs[0].remote_sha));
1162 }
1163
1164 #[test]
1165 fn skips_malformed_lines_without_panicking() {
1166 assert!(parse_push_refs("garbage\n\nalso garbage here\n").is_empty());
1167 }
1168
1169 #[test]
1170 fn zero_sha_detection_handles_sha256_length() {
1171 assert!(is_zero_sha(&"0".repeat(64)));
1172 assert!(!is_zero_sha("0000000000000000000000000000000000000001"));
1173 assert!(!is_zero_sha(""));
1174 }
1175}
1176
1177#[cfg(test)]
1197mod git_diff_tests {
1198 use super::{changed_files_for_refs, git_empty_tree_sha, PushRef};
1199 use crate::test_helpers::init_git_repo;
1200 use std::path::Path;
1201 use std::process::Command;
1202
1203 fn commit_file(dir: &Path, name: &str, content: &str) -> String {
1207 std::fs::write(dir.join(name), content).unwrap();
1208 let ok = Command::new("git")
1209 .args(["-C", &dir.to_string_lossy(), "add", name])
1210 .status()
1211 .expect("git add failed")
1212 .success();
1213 assert!(ok, "git add must succeed");
1214 let ok = Command::new("git")
1215 .args([
1216 "-C",
1217 &dir.to_string_lossy(),
1218 "commit",
1219 "-m",
1220 &format!("add {name}"),
1221 ])
1222 .status()
1223 .expect("git commit failed")
1224 .success();
1225 assert!(ok, "git commit must succeed");
1226 head_sha(dir)
1227 }
1228
1229 fn head_sha(dir: &Path) -> String {
1230 let out = Command::new("git")
1231 .args(["-C", &dir.to_string_lossy(), "rev-parse", "HEAD"])
1232 .output()
1233 .expect("git rev-parse failed");
1234 assert!(out.status.success());
1235 String::from_utf8_lossy(&out.stdout).trim().to_string()
1236 }
1237
1238 #[test]
1239 fn two_dot_range_returns_only_the_newer_commits_files() {
1240 let tmp = tempfile::tempdir().unwrap();
1241 init_git_repo(tmp.path()); let sha1 = commit_file(tmp.path(), "a.txt", "a");
1244 let sha2 = commit_file(tmp.path(), "b.txt", "b");
1245
1246 let refs = vec![PushRef {
1247 local_sha: sha2,
1248 remote_sha: sha1,
1249 }];
1250 let files = changed_files_for_refs(tmp.path(), &refs);
1251
1252 assert_eq!(files, vec!["b.txt".to_string()]);
1257 }
1258
1259 #[test]
1260 fn new_branch_zero_remote_sha_resolves_via_empty_tree() {
1261 let tmp = tempfile::tempdir().unwrap();
1262 init_git_repo(tmp.path());
1263
1264 commit_file(tmp.path(), "a.txt", "a");
1265 let sha2 = commit_file(tmp.path(), "b.txt", "b");
1266
1267 let refs = vec![PushRef {
1268 local_sha: sha2,
1269 remote_sha: "0".repeat(40),
1270 }];
1271 let mut files = changed_files_for_refs(tmp.path(), &refs);
1272 files.sort();
1273
1274 assert_eq!(files, vec!["a.txt".to_string(), "b.txt".to_string()]);
1277 }
1278
1279 #[test]
1280 fn identical_shas_yield_an_empty_file_list() {
1281 let tmp = tempfile::tempdir().unwrap();
1282 init_git_repo(tmp.path());
1283 let sha = commit_file(tmp.path(), "a.txt", "a");
1284
1285 let refs = vec![PushRef {
1286 local_sha: sha.clone(),
1287 remote_sha: sha,
1288 }];
1289 let files = changed_files_for_refs(tmp.path(), &refs);
1290
1291 assert!(
1292 files.is_empty(),
1293 "a no-op push (same local and remote sha) must yield no files, got {files:?}"
1294 );
1295 }
1296
1297 #[test]
1298 fn non_ascii_path_is_returned_raw_not_octal_quoted() {
1299 let tmp = tempfile::tempdir().unwrap();
1300 init_git_repo(tmp.path());
1301 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1302
1303 let sha1 = commit_file(tmp.path(), "src/café.rs", "one");
1304 let sha2 = commit_file(tmp.path(), "src/café.rs", "two");
1305
1306 let refs = vec![PushRef {
1307 local_sha: sha2,
1308 remote_sha: sha1,
1309 }];
1310 let files = changed_files_for_refs(tmp.path(), &refs);
1311
1312 assert_eq!(
1318 files,
1319 vec!["src/café.rs".to_string()],
1320 "must be the raw UTF-8 path, not git's octal-quoted rendering; got {files:?}"
1321 );
1322 }
1323
1324 #[test]
1325 fn path_containing_a_space_is_returned_intact() {
1326 let tmp = tempfile::tempdir().unwrap();
1327 init_git_repo(tmp.path());
1328 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1329
1330 let sha1 = commit_file(tmp.path(), "src/has space.rs", "one");
1331 let sha2 = commit_file(tmp.path(), "src/has space.rs", "two");
1332
1333 let refs = vec![PushRef {
1334 local_sha: sha2,
1335 remote_sha: sha1,
1336 }];
1337 let files = changed_files_for_refs(tmp.path(), &refs);
1338
1339 assert_eq!(files, vec!["src/has space.rs".to_string()]);
1340 }
1341
1342 #[test]
1343 fn rename_reports_both_source_and_destination() {
1344 let tmp = tempfile::tempdir().unwrap();
1345 init_git_repo(tmp.path());
1346 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1347 let sha1 = commit_file(tmp.path(), "src/plain.rs", "identical content");
1348
1349 let ok = Command::new("git")
1350 .args([
1351 "-C",
1352 &tmp.path().to_string_lossy(),
1353 "mv",
1354 "src/plain.rs",
1355 "src/renamed.rs",
1356 ])
1357 .status()
1358 .expect("git mv failed")
1359 .success();
1360 assert!(ok, "git mv must succeed");
1361 let ok = Command::new("git")
1362 .args([
1363 "-C",
1364 &tmp.path().to_string_lossy(),
1365 "commit",
1366 "-m",
1367 "rename plain.rs to renamed.rs",
1368 ])
1369 .status()
1370 .expect("git commit failed")
1371 .success();
1372 assert!(ok, "git commit must succeed");
1373 let sha2 = head_sha(tmp.path());
1374
1375 let refs = vec![PushRef {
1376 local_sha: sha2,
1377 remote_sha: sha1,
1378 }];
1379 let mut files = changed_files_for_refs(tmp.path(), &refs);
1380 files.sort();
1381
1382 assert_eq!(
1388 files,
1389 vec!["src/plain.rs".to_string(), "src/renamed.rs".to_string()],
1390 "a rename must surface BOTH the source and destination path; got {files:?}"
1391 );
1392 }
1393
1394 #[test]
1395 fn git_empty_tree_sha_is_the_well_known_constant() {
1396 let tmp = tempfile::tempdir().unwrap();
1397 init_git_repo(tmp.path());
1398
1399 let empty_tree =
1400 git_empty_tree_sha(tmp.path()).expect("git hash-object must resolve the empty tree");
1401 assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1405 }
1406
1407 #[test]
1414 fn upstream_fallback_diff_fails_cleanly_with_no_upstream_configured() {
1415 let tmp = tempfile::tempdir().unwrap();
1416 init_git_repo(tmp.path());
1417 commit_file(tmp.path(), "a.txt", "a");
1418
1419 let out = Command::new("git")
1420 .args([
1421 "diff",
1422 "--name-only",
1423 "-z",
1424 "--no-renames",
1425 "@{upstream}..HEAD",
1426 ])
1427 .current_dir(tmp.path())
1428 .output()
1429 .expect("git diff must run");
1430
1431 assert!(
1432 !out.status.success(),
1433 "no upstream is configured, so this must fail rather than \
1434 silently resolve to something else"
1435 );
1436 }
1437
1438 #[test]
1442 fn upstream_fallback_diff_is_empty_when_upstream_matches_head() {
1443 let tmp = tempfile::tempdir().unwrap();
1444 init_git_repo(tmp.path());
1445 commit_file(tmp.path(), "a.txt", "a");
1446
1447 let branch_out = Command::new("git")
1448 .args(["symbolic-ref", "--short", "HEAD"])
1449 .current_dir(tmp.path())
1450 .output()
1451 .expect("git symbolic-ref must run");
1452 assert!(branch_out.status.success());
1453 let branch = String::from_utf8_lossy(&branch_out.stdout)
1454 .trim()
1455 .to_string();
1456
1457 for args in [
1461 vec!["branch", "tracking", &branch],
1462 vec!["branch", "--set-upstream-to=tracking", &branch],
1463 ] {
1464 let ok = Command::new("git")
1465 .args(&args)
1466 .current_dir(tmp.path())
1467 .status()
1468 .expect("git command must run")
1469 .success();
1470 assert!(ok, "git {args:?} must succeed");
1471 }
1472
1473 let out = Command::new("git")
1474 .args([
1475 "diff",
1476 "--name-only",
1477 "-z",
1478 "--no-renames",
1479 "@{upstream}..HEAD",
1480 ])
1481 .current_dir(tmp.path())
1482 .output()
1483 .expect("git diff must run");
1484
1485 assert!(out.status.success());
1486 assert!(
1487 out.stdout.is_empty(),
1488 "identical upstream/HEAD must diff to no files"
1489 );
1490 }
1491}
1492
1493#[cfg(test)]
1502mod read_with_timeout_tests {
1503 use super::read_with_timeout;
1504 use std::time::Duration;
1505
1506 #[test]
1507 fn returns_the_value_when_it_arrives_before_the_deadline() {
1508 let got = read_with_timeout(|| Some("hi".to_string()), Duration::from_secs(1));
1509 assert_eq!(got, Some("hi".to_string()));
1510 }
1511
1512 #[test]
1513 fn returns_none_when_the_closure_itself_returns_none() {
1514 let got = read_with_timeout(|| None, Duration::from_secs(1));
1515 assert_eq!(got, None);
1516 }
1517
1518 #[test]
1519 fn times_out_instead_of_hanging_on_a_closure_that_never_returns() {
1520 let start = std::time::Instant::now();
1525 let got = read_with_timeout(
1526 || {
1527 std::thread::sleep(Duration::from_secs(10));
1528 Some("too late".to_string())
1529 },
1530 Duration::from_millis(50),
1531 );
1532 assert_eq!(got, None, "must give up rather than wait for the closure");
1533 assert!(
1534 start.elapsed() < Duration::from_secs(1),
1535 "must return promptly on timeout, not block on the stalled closure; took {:?}",
1536 start.elapsed()
1537 );
1538 }
1539}
1540
1541#[cfg(test)]
1542mod pushed_repo_tests {
1543 use super::{streamed_elsewhere_warning, PushedRepo};
1544 use crate::session_state::RepoBinding;
1545
1546 const PUSHED: uuid::Uuid = uuid::uuid!("44000761-0000-4000-8000-000000000001");
1548 const BY_NAME: uuid::Uuid = uuid::uuid!("7995d35d-0000-4000-8000-000000000002");
1550 const OTHER: uuid::Uuid = uuid::uuid!("aaaaaaaa-0000-4000-8000-000000000003");
1552 const CODEBASE: uuid::Uuid = uuid::uuid!("cccccccc-0000-4000-8000-000000000004");
1553 const OTHER_CODEBASE: uuid::Uuid = uuid::uuid!("dddddddd-0000-4000-8000-000000000005");
1554 const PASS: &str = r#"{"passed":true,"results":[],"blocked":false}"#;
1555
1556 fn binding(repo: uuid::Uuid, remote: Option<uuid::Uuid>) -> RepoBinding {
1557 RepoBinding {
1558 repo_id: repo.to_string(),
1559 git_url: None,
1560 remote_id: remote,
1561 codebase_name: None,
1562 updated_at: "t".into(),
1563 }
1564 }
1565
1566 #[test]
1569 fn no_warning_when_the_session_streamed_to_the_pushed_repo_or_is_unbound() {
1570 let pushed = PushedRepo {
1571 id: PUSHED,
1572 remote_id: Some(CODEBASE),
1573 };
1574 assert_eq!(
1575 streamed_elsewhere_warning(Some(&binding(PUSHED, None)), &pushed),
1576 None
1577 );
1578 assert_eq!(streamed_elsewhere_warning(None, &pushed), None);
1579 }
1580
1581 #[test]
1582 fn warning_names_both_repos_and_how_far_apart_they_are() {
1583 let pushed = PushedRepo {
1584 id: PUSHED,
1585 remote_id: Some(CODEBASE),
1586 };
1587 let same =
1588 streamed_elsewhere_warning(Some(&binding(OTHER, Some(CODEBASE))), &pushed).unwrap();
1589 assert!(same.contains("another repo of this codebase"), "{same}");
1590 assert!(same.contains(&OTHER.to_string()) && same.contains(&PUSHED.to_string()));
1591 let far = streamed_elsewhere_warning(Some(&binding(OTHER, Some(OTHER_CODEBASE))), &pushed)
1592 .unwrap();
1593 assert!(far.contains("a different codebase"), "{far}");
1594 let unknown = streamed_elsewhere_warning(Some(&binding(OTHER, None)), &pushed).unwrap();
1595 assert!(unknown.contains("a different repo"), "{unknown}");
1596 }
1597
1598 struct Fixture {
1605 _guard: crate::test_helpers::EnvVarGuard,
1606 _home: tempfile::TempDir,
1607 _tmp: tempfile::TempDir,
1608 repo: std::path::PathBuf,
1609 rx: std::sync::mpsc::Receiver<String>,
1610 }
1611
1612 fn fixture(remote: bool, sessions: &[&str], responses: Vec<String>) -> Fixture {
1613 let home = tempfile::tempdir().unwrap();
1614 let mut guard = crate::test_helpers::EnvVarGuard::new();
1615 guard.set("XDG_CONFIG_HOME", home.path());
1616 guard.set("XDG_STATE_HOME", home.path());
1617 guard.remove("TRACEVAULT_API_KEY");
1618 guard.remove("TRACEVAULT_SERVER_URL");
1619 let (server, rx) = crate::test_helpers::spawn_seq(responses);
1620 let creds_dir = home.path().join("visdom");
1621 std::fs::create_dir_all(&creds_dir).unwrap();
1622 std::fs::write(
1623 creds_dir.join("credentials.json"),
1624 format!(
1625 r#"{{"server_url":"{server}","email":"a@b.com","auth":{{
1626 "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
1627 "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
1628 ),
1629 )
1630 .unwrap();
1631
1632 let tmp = tempfile::tempdir().unwrap();
1633 let repo = tmp.path().join("tracing");
1634 std::fs::create_dir_all(&repo).unwrap();
1635 crate::test_helpers::init_git_repo(&repo);
1636 if remote {
1637 let ok = std::process::Command::new("git")
1638 .args([
1639 "remote",
1640 "add",
1641 "origin",
1642 "https://github.com/example/visdom-tracing.git",
1643 ])
1644 .current_dir(&repo)
1645 .status()
1646 .unwrap()
1647 .success();
1648 assert!(ok, "git remote add failed");
1649 }
1650 let top = crate::paths::worktree_toplevel(&repo);
1651 for id in sessions {
1652 let dir = repo.join(".visdom").join("sessions").join(id);
1653 std::fs::create_dir_all(&dir).unwrap();
1654 std::fs::write(dir.join("origin"), &top).unwrap();
1655 }
1656 Fixture {
1657 _guard: guard,
1658 _home: home,
1659 _tmp: tmp,
1660 repo,
1661 rx,
1662 }
1663 }
1664
1665 fn bind_with_repo_switch(session_id: &str, repo_id: uuid::Uuid) {
1666 let state = crate::session_state::SessionState {
1667 active: Some(binding(repo_id, None)),
1668 ..Default::default()
1669 };
1670 crate::session_state::save(session_id, &state).unwrap();
1671 }
1672
1673 fn remote_resolves_to_pushed() -> Vec<String> {
1676 vec![
1677 crate::test_helpers::http_json(
1678 "200 OK",
1679 &format!(
1680 r#"{{"remote_id":"{CODEBASE}","name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready"}}"#
1681 ),
1682 ),
1683 crate::test_helpers::http_json(
1684 "200 OK",
1685 &format!(
1686 r#"{{"name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready","repos":[{{"id":"{PUSHED}","name":"visdom-tracing"}}]}}"#
1687 ),
1688 ),
1689 ]
1690 }
1691
1692 fn repos_listing() -> String {
1693 crate::test_helpers::http_json(
1694 "200 OK",
1695 &format!(r#"[{{"id":"{BY_NAME}","name":"tracing"}}]"#),
1696 )
1697 }
1698
1699 fn pass() -> String {
1700 crate::test_helpers::http_json("200 OK", PASS)
1701 }
1702
1703 fn recv(f: &Fixture) -> String {
1704 f.rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT)
1705 .expect("expected another request")
1706 }
1707
1708 fn assert_checked_under(request: &str, repo: uuid::Uuid) {
1709 assert!(
1710 request.starts_with(&format!("POST /api/v1/repos/{repo}/policies/check")),
1711 "expected the check under {repo}: {request}"
1712 );
1713 }
1714
1715 #[tokio::test]
1721 async fn a_push_is_checked_under_the_repo_its_remote_resolves_to() {
1722 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1723 let mut responses = remote_resolves_to_pushed();
1724 responses.push(pass());
1725 let f = fixture(true, &["sess-bound"], responses);
1726 bind_with_repo_switch("sess-bound", PUSHED);
1727
1728 super::check_policies(&f.repo, &f.repo).await.unwrap();
1729
1730 assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
1731 assert!(recv(&f).starts_with(&format!("GET /api/v1/remotes/{CODEBASE} ")));
1732 let check = recv(&f);
1733 assert_checked_under(&check, PUSHED);
1734 assert!(check.contains("sess-bound"), "{check}");
1735 }
1736
1737 #[tokio::test]
1741 async fn a_session_bound_elsewhere_does_not_change_which_repo_the_push_is_checked_under() {
1742 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1743 let mut responses = remote_resolves_to_pushed();
1744 responses.push(pass());
1745 let f = fixture(true, &["sess-switched", "sess-default"], responses);
1746 bind_with_repo_switch("sess-switched", OTHER);
1747 crate::user_default::save(&binding(OTHER, None)).unwrap();
1748 assert_eq!(
1749 crate::user_default::load().map(|b| b.repo_id),
1750 Some(OTHER.to_string()),
1751 "fixture must actually set a user default"
1752 );
1753
1754 super::check_policies(&f.repo, &f.repo).await.unwrap();
1755
1756 recv(&f);
1757 recv(&f);
1758 let check = recv(&f);
1759 assert_checked_under(&check, PUSHED);
1760 assert!(
1761 check.contains("sess-switched") && check.contains("sess-default"),
1762 "every session is still evaluated (fail closed): {check}"
1763 );
1764 }
1765
1766 #[tokio::test]
1768 async fn without_a_remote_the_push_is_checked_under_the_name_resolved_repo() {
1769 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1770 let f = fixture(false, &["sess-free"], vec![repos_listing(), pass()]);
1771
1772 super::check_policies(&f.repo, &f.repo).await.unwrap();
1773
1774 assert!(recv(&f).starts_with("GET /api/v1/repos "));
1775 let check = recv(&f);
1776 assert_checked_under(&check, BY_NAME);
1777 assert!(check.contains("sess-free"), "{check}");
1778 }
1779
1780 #[tokio::test]
1782 async fn an_unknown_remote_falls_back_to_the_name_resolved_repo() {
1783 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1784 let f = fixture(
1785 true,
1786 &["sess-free"],
1787 vec![
1788 crate::test_helpers::http_json("404 Not Found", r#"{"error":"remote not found"}"#),
1789 repos_listing(),
1790 pass(),
1791 ],
1792 );
1793
1794 super::check_policies(&f.repo, &f.repo).await.unwrap();
1795
1796 assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
1797 assert!(recv(&f).starts_with("GET /api/v1/repos "));
1798 assert_checked_under(&recv(&f), BY_NAME);
1799 }
1800
1801 #[tokio::test]
1803 async fn an_unregistered_repo_fails_the_push_even_without_sessions() {
1804 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1805 let f = fixture(
1806 false,
1807 &[],
1808 vec![crate::test_helpers::http_json("200 OK", "[]")],
1809 );
1810
1811 let err = super::check_policies(&f.repo, &f.repo)
1812 .await
1813 .expect_err("an unregistered repo must fail the push");
1814 assert!(err.to_string().contains("'tracing' not found"), "{err}");
1815 }
1816}