1use crate::api_client::{ApiClient, CheckPoliciesRequest, SessionCheckData};
2use crate::credentials::resolve_credentials;
3use crate::resolution::{resolve_repo_by_name, ResolveRepoByNameError};
4use std::collections::HashSet;
5use std::fs;
6use std::path::Path;
7use std::process::Command;
8
9fn git_head_sha(project_root: &Path) -> Option<String> {
10 let out = Command::new("git")
11 .args(["rev-parse", "HEAD"])
12 .current_dir(project_root)
13 .output()
14 .ok()?;
15 if !out.status.success() {
16 return None;
17 }
18 let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
19 if sha.is_empty() {
20 None
21 } else {
22 Some(sha)
23 }
24}
25
26#[derive(Debug, PartialEq)]
28pub(crate) struct PushRef {
29 pub local_sha: String,
30 pub remote_sha: String,
31}
32
33fn is_zero_sha(sha: &str) -> bool {
34 !sha.is_empty() && sha.chars().all(|c| c == '0')
35}
36
37pub(crate) fn parse_push_refs(stdin: &str) -> Vec<PushRef> {
42 stdin
43 .lines()
44 .filter_map(|line| {
45 let mut parts = line.split_whitespace();
46 let _local_ref = parts.next()?;
47 let local_sha = parts.next()?;
48 let _remote_ref = parts.next()?;
49 let remote_sha = parts.next()?;
50 if is_zero_sha(local_sha) {
51 return None;
52 }
53 Some(PushRef {
54 local_sha: local_sha.to_string(),
55 remote_sha: remote_sha.to_string(),
56 })
57 })
58 .collect()
59}
60
61fn changed_files_for_refs(project_root: &Path, refs: &[PushRef]) -> Vec<String> {
65 let mut seen = HashSet::new();
66 let mut out = Vec::new();
67 for r in refs {
68 let base = if is_zero_sha(&r.remote_sha) {
72 match git_empty_tree_sha(project_root) {
73 Some(t) => t,
74 None => continue,
75 }
76 } else {
77 r.remote_sha.clone()
78 };
79 let out_bytes = Command::new("git")
80 .args([
81 "diff",
82 "--name-only",
83 "-z",
89 "--no-renames",
94 &format!("{base}..{}", r.local_sha),
95 ])
96 .current_dir(project_root)
97 .output();
98 let Ok(o) = out_bytes else { continue };
99 if !o.status.success() {
100 continue;
101 }
102 for p in split_nul_delimited_paths(&o.stdout) {
103 if seen.insert(p.clone()) {
104 out.push(p);
105 }
106 }
107 }
108 out
109}
110
111fn split_nul_delimited_paths(bytes: &[u8]) -> Vec<String> {
121 String::from_utf8_lossy(bytes)
122 .split('\0')
123 .filter(|p| !p.is_empty())
124 .map(|p| p.to_string())
125 .collect()
126}
127
128fn git_empty_tree_sha(project_root: &Path) -> Option<String> {
131 let out = Command::new("git")
132 .args(["hash-object", "-t", "tree", "/dev/null"])
133 .current_dir(project_root)
134 .output()
135 .ok()?;
136 if !out.status.success() {
137 return None;
138 }
139 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
140 if s.is_empty() {
141 None
142 } else {
143 Some(s)
144 }
145}
146
147const STDIN_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
153
154fn read_with_timeout<F>(f: F, timeout: std::time::Duration) -> Option<String>
166where
167 F: FnOnce() -> Option<String> + Send + 'static,
168{
169 let (tx, rx) = std::sync::mpsc::channel();
170 std::thread::spawn(move || {
171 let _ = tx.send(f());
172 });
173 rx.recv_timeout(timeout).ok().flatten()
174}
175
176fn read_stdin_with_timeout(timeout: std::time::Duration) -> Option<String> {
184 use std::io::Read;
185 read_with_timeout(
186 || {
187 let mut buf = String::new();
188 std::io::stdin().read_to_string(&mut buf).ok().map(|_| buf)
189 },
190 timeout,
191 )
192}
193
194fn resolve_changed_paths(project_root: &Path) -> Option<Vec<String>> {
205 use std::io::IsTerminal;
206
207 if !std::io::stdin().is_terminal() {
213 if let Some(buf) = read_stdin_with_timeout(STDIN_READ_TIMEOUT) {
214 let refs = parse_push_refs(&buf);
215 if !refs.is_empty() {
216 let files = changed_files_for_refs(project_root, &refs);
226 return if files.is_empty() { None } else { Some(files) };
227 }
228 }
229 }
230
231 let out = Command::new("git")
235 .args([
236 "diff",
237 "--name-only",
238 "-z",
239 "--no-renames",
240 "@{upstream}..HEAD",
241 ])
242 .current_dir(project_root)
243 .output()
244 .ok()?;
245 if !out.status.success() {
246 return None;
247 }
248 let files = split_nul_delimited_paths(&out.stdout);
249 if files.is_empty() {
250 None
251 } else {
252 Some(files)
253 }
254}
255
256fn collect_session_data(session_dir: &Path) -> Option<SessionCheckData> {
257 let session_id = session_dir.file_name()?.to_string_lossy().to_string();
258
259 let events_path = session_dir.join("events.jsonl");
261 let mut files_modified = Vec::new();
262 let mut files_seen = HashSet::new();
263
264 if events_path.exists() {
265 if let Ok(content) = fs::read_to_string(&events_path) {
266 for line in content.lines() {
267 let event: serde_json::Value = match serde_json::from_str(line) {
268 Ok(v) => v,
269 Err(_) => continue,
270 };
271 if let Some(path) = event
272 .get("tool_input")
273 .and_then(|v| v.get("file_path"))
274 .and_then(|v| v.as_str())
275 {
276 if files_seen.insert(path.to_string()) {
277 files_modified.push(path.to_string());
278 }
279 }
280 }
281 }
282 }
283
284 let meta_path = session_dir.join("metadata.json");
286 let metadata: Option<serde_json::Value> = meta_path
287 .exists()
288 .then(|| fs::read_to_string(&meta_path).ok())
289 .flatten()
290 .and_then(|c| serde_json::from_str(&c).ok());
291
292 let transcript_path = metadata
293 .as_ref()
294 .and_then(|m| m.get("transcript_path"))
295 .and_then(|v| v.as_str())
296 .map(|s| s.to_string());
297
298 let tool_calls_map = transcript_path
299 .as_deref()
300 .map(|p| crate::transcript::count_tool_calls(Path::new(p)))
301 .unwrap_or_default();
302 let total_tool_calls: i32 = tool_calls_map.values().sum();
303
304 let tool_calls = if tool_calls_map.is_empty() {
305 None
306 } else {
307 serde_json::to_value(&tool_calls_map).ok()
308 };
309
310 Some(SessionCheckData {
311 session_id,
312 tool_calls,
313 files_modified: if files_modified.is_empty() {
314 None
315 } else {
316 Some(files_modified)
317 },
318 total_tool_calls: if total_tool_calls > 0 {
319 Some(total_tool_calls)
320 } else {
321 None
322 },
323 })
324}
325
326pub fn select_worktree_sessions(
337 session_dirs: Vec<std::path::PathBuf>,
338 worktree_top: &str,
339) -> (Vec<std::path::PathBuf>, bool) {
340 let belongs = |dir: &std::path::Path| -> bool {
341 match fs::read_to_string(dir.join("origin")) {
342 Ok(s) => s.trim() == worktree_top, Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
345 Err(_) => false,
350 }
351 };
352 let filtered: Vec<_> = session_dirs
353 .iter()
354 .filter(|d| belongs(d))
355 .cloned()
356 .collect();
357 if filtered.is_empty() && !session_dirs.is_empty() {
358 (session_dirs, true)
359 } else {
360 (filtered, false)
361 }
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
366struct PushedRepo {
367 id: uuid::Uuid,
368 remote_id: Option<uuid::Uuid>,
370}
371
372async fn resolve_pushed_repo(
385 client: &ApiClient,
386 project_root: &Path,
387) -> Result<PushedRepo, Box<dyn std::error::Error>> {
388 match crate::resolution::resolve_path_to_binding(project_root, client).await {
389 Ok(Some(b)) => {
390 if let Ok(id) = b.repo_id.parse() {
391 return Ok(PushedRepo {
392 id,
393 remote_id: b.remote_id,
394 });
395 }
396 }
397 Ok(None) => {}
398 Err(e) => return Err(connectivity_message(&e.to_string()).into()),
399 }
400 match resolve_repo_by_name(client, project_root).await {
401 Ok(r) => Ok(PushedRepo {
402 id: r.id,
403 remote_id: None,
404 }),
405 Err(ResolveRepoByNameError::ListFailed(e)) => {
406 Err(connectivity_message(&e.to_string()).into())
407 }
408 Err(ResolveRepoByNameError::NotFound { repo_name }) => Err(format!(
409 "Repo '{repo_name}' not found on server. Run `tracevault sync` first."
410 )
411 .into()),
412 }
413}
414
415fn streamed_elsewhere_warning(
427 streamed_to: Option<&crate::session_state::RepoBinding>,
428 pushed: &PushedRepo,
429) -> Option<String> {
430 let b = streamed_to?;
431 if b.repo_id == pushed.id.to_string() {
432 return None;
433 }
434 let scope = match (b.remote_id, pushed.remote_id) {
435 (Some(a), Some(p)) if a == p => "another repo of this codebase",
436 (Some(_), Some(_)) => "a different codebase",
437 _ => "a different repo",
438 };
439 Some(format!(
440 "Warning: an unpushed session streamed its events to {scope} ({}), not to the repo \
441 this push is checked under ({}). Its verification-phase data will not be found; \
442 run `tracevault repo switch <this checkout>` in that session.",
443 b.repo_id, pushed.id
444 ))
445}
446
447pub async fn check_policies(
458 project_root: &Path,
459 cwd: &Path,
460) -> Result<(), Box<dyn std::error::Error>> {
461 let (server_url, credential) = resolve_credentials(project_root)?;
462
463 let server_url = server_url
464 .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
465
466 if credential.is_none() {
467 return Err(
468 "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
469 .into(),
470 );
471 }
472
473 let client = ApiClient::with_credential(&server_url, credential);
474
475 let repo = resolve_pushed_repo(&client, project_root).await?;
485
486 let sessions_dir = project_root.join(".tracevault").join("sessions");
488 let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
489 if sessions_dir.exists() {
490 for entry in fs::read_dir(&sessions_dir)? {
491 let entry = entry?;
492 if !entry.file_type()?.is_dir() {
493 continue;
494 }
495 let session_dir = entry.path();
496 if session_dir.join(".pushed").exists() {
497 continue;
498 }
499 unpushed_dirs.push(session_dir);
500 }
501 }
502
503 let worktree_top = crate::paths::worktree_toplevel(cwd);
506 let (selected_dirs, fell_back) = select_worktree_sessions(unpushed_dirs, &worktree_top);
507 if fell_back {
508 eprintln!(
509 "Warning: no unpushed session matched this worktree by origin marker — \
510 checking all unpushed sessions to avoid skipping policy enforcement."
511 );
512 }
513
514 let bound = match crate::config::TracevaultConfig::try_load(project_root) {
519 Ok(cfg) => cfg
520 .as_ref()
521 .and_then(crate::resolution::binding_from_config),
522 Err(e) => {
523 eprintln!("Warning: ignoring malformed .tracevault/config.toml: {e}");
524 None
525 }
526 };
527 let user_default = crate::user_default::load();
528
529 let mut sessions = Vec::new();
530 for session_dir in &selected_dirs {
531 if let Some(data) = collect_session_data(session_dir) {
532 let state = crate::session_state::load(&data.session_id);
533 let streamed_to = crate::resolution::recorded_session_binding(
534 session_dir,
535 &state,
536 bound.clone(),
537 user_default.clone(),
538 );
539 if let Some(w) = streamed_elsewhere_warning(streamed_to.as_ref(), &repo) {
540 eprintln!("{w}");
541 }
542 sessions.push(data);
543 }
544 }
545
546 if sessions.is_empty() {
547 println!("No unpushed sessions to check.");
548 return Ok(());
549 }
550
551 println!("Checking {} session(s) against policies...", sessions.len());
552
553 let commit_sha = git_head_sha(cwd);
556 let changed_paths = resolve_changed_paths(cwd);
557 let result = client
558 .check_policies(
559 &repo.id,
560 CheckPoliciesRequest {
561 sessions,
562 commit_sha,
563 changed_paths,
564 },
565 )
566 .await
567 .map_err(|e| connectivity_message(&e.to_string()))?;
568
569 for r in &result.results {
571 let icon = match r.result.as_str() {
572 "pass" => "\x1b[32m✓\x1b[0m", "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", "fail" => "\x1b[33m!\x1b[0m", _ => " ",
576 };
577 println!(
578 " {} [{}] {} — {}",
579 icon, r.severity, r.rule_name, r.details
580 );
581 }
582
583 if result.blocked {
584 eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
585 std::process::exit(1);
586 } else if result.passed {
587 println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
588 } else {
589 println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
590 }
591
592 Ok(())
593}
594
595fn connectivity_message(raw: &str) -> String {
603 let lower = raw.to_ascii_lowercase();
604
605 if lower.contains("401") || lower.contains("unauthorized") {
608 return with_action(
609 raw,
610 "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
611 );
612 }
613 if lower.contains("403") || lower.contains("forbidden") {
616 return with_action(
617 raw,
618 "Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`.",
619 );
620 }
621 if lower.contains("404") {
629 return with_action(
630 raw,
631 "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.",
632 );
633 }
634 if is_server_error(&lower) {
637 return with_action(
638 raw,
639 "TraceVault server returned an error. The team has likely been paged; retry shortly.",
640 );
641 }
642 if lower.contains("dns")
645 || lower.contains("connect")
646 || lower.contains("timed out")
647 || lower.contains("timeout")
648 {
649 return with_action(
650 raw,
651 "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
652 );
653 }
654 format!("Policy check could not run: {raw}.")
656}
657
658fn with_action(raw: &str, action: &str) -> String {
660 format!("Policy check could not run: {raw}.\n → {action}")
661}
662
663fn is_server_error(lower: &str) -> bool {
668 lower.contains("internal")
669 || lower.contains("server error")
670 || ["500", "501", "502", "503", "504"]
671 .iter()
672 .any(|code| lower.contains(code))
673}
674
675#[cfg(test)]
676mod worktree_tests {
677 use super::select_worktree_sessions;
678 use std::path::PathBuf;
679
680 fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
681 let d = tmp.join(id);
682 std::fs::create_dir_all(&d).unwrap();
683 if let Some(o) = origin {
684 std::fs::write(d.join("origin"), o).unwrap();
685 }
686 d
687 }
688
689 #[test]
690 fn keeps_current_worktree_and_unmarked_excludes_other() {
691 let tmp = tempfile::tempdir().unwrap();
692 let mine = seed(tmp.path(), "mine", Some("/wt/here"));
693 let other = seed(tmp.path(), "other", Some("/wt/there"));
694 let legacy = seed(tmp.path(), "legacy", None);
695
696 let (kept, fell_back) = select_worktree_sessions(
697 vec![mine.clone(), other.clone(), legacy.clone()],
698 "/wt/here",
699 );
700
701 assert!(!fell_back);
702 assert!(kept.contains(&mine), "current worktree session kept");
703 assert!(
704 kept.contains(&legacy),
705 "unmarked legacy session kept (conservative)"
706 );
707 assert!(
708 !kept.contains(&other),
709 "other worktree's marked session excluded"
710 );
711 }
712
713 #[test]
714 fn excludes_session_with_unreadable_marker() {
715 let tmp = tempfile::tempdir().unwrap();
716 let mine = seed(tmp.path(), "mine", Some("/wt/here"));
717 let bad = tmp.path().join("bad");
720 std::fs::create_dir_all(bad.join("origin")).unwrap();
721
722 let (kept, fell_back) =
723 select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
724
725 assert!(!fell_back);
726 assert!(kept.contains(&mine), "current worktree session kept");
727 assert!(
728 !kept.contains(&bad),
729 "session with a present-but-unreadable marker must be excluded, not kept as legacy"
730 );
731 }
732
733 #[test]
734 fn falls_back_to_all_when_nothing_matches() {
735 let tmp = tempfile::tempdir().unwrap();
736 let a = seed(tmp.path(), "a", Some("/wt/there"));
737 let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
738
739 let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
740
741 assert!(fell_back, "must flag fallback when filter matches nothing");
742 assert_eq!(
743 kept.len(),
744 2,
745 "never under-enforce: send all rather than zero"
746 );
747 }
748}
749
750#[cfg(test)]
751mod tests {
752 use super::{collect_session_data, connectivity_message};
753
754 #[test]
758 fn counts_tool_calls_from_the_transcript_the_stream_hook_recorded() {
759 let tmp = tempfile::tempdir().unwrap();
760 let transcript = tmp.path().join("t.jsonl");
761 std::fs::write(
762 &transcript,
763 concat!(
764 r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
765 "\n",
766 r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash"},{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
767 "\n",
768 ),
769 )
770 .unwrap();
771 let session_dir = tmp.path().join("sess-1");
772 std::fs::create_dir_all(&session_dir).unwrap();
773
774 let before = collect_session_data(&session_dir).unwrap();
775 assert!(
776 before.tool_calls.is_none(),
777 "no metadata.json, no tool calls"
778 );
779
780 crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
781 .unwrap();
782 let after = collect_session_data(&session_dir).unwrap();
783
784 assert_eq!(after.session_id, "sess-1");
785 assert_eq!(after.total_tool_calls, Some(3));
786 assert_eq!(
787 after.tool_calls,
788 Some(serde_json::json!({"mcp__cargo__cargo_check": 2, "Bash": 1}))
789 );
790 }
791
792 fn tool_calls_from_transcript(lines: &[&str]) -> Option<serde_json::Value> {
795 let tmp = tempfile::tempdir().unwrap();
796 let transcript = tmp.path().join("t.jsonl");
797 std::fs::write(&transcript, lines.join("\n")).unwrap();
798 let session_dir = tmp.path().join("sess");
799 std::fs::create_dir_all(&session_dir).unwrap();
800 crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
801 .unwrap();
802 collect_session_data(&session_dir).unwrap().tool_calls
803 }
804
805 #[test]
806 fn counts_tool_calls_from_a_codex_rollout() {
807 let calls = tool_calls_from_transcript(&[
808 r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix it"}]}}"#,
809 r#"{"type":"response_item","payload":{"type":"custom_tool_call","name":"apply_patch","input":"*** Begin Patch\n*** End Patch\n"}}"#,
810 r#"{"type":"response_item","payload":{"type":"function_call","name":"mcp__cargo__cargo_check","arguments":"{}"}}"#,
811 r#"{"type":"response_item","payload":{"type":"local_shell_call","command":"ls"}}"#,
812 r#"{"type":"event_msg","payload":{"type":"token_count"}}"#,
813 ]);
814 assert_eq!(
815 calls,
816 Some(serde_json::json!({"apply_patch": 1, "mcp__cargo__cargo_check": 1, "Bash": 1}))
817 );
818 }
819
820 #[test]
821 fn counts_tool_calls_from_a_gsd_session() {
822 let calls = tool_calls_from_transcript(&[
823 r#"{"type":"model_change","provider":"anthropic","modelId":"claude-opus-4-7"}"#,
824 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":{}}]}}"#,
825 r#"{"type":"message","message":{"role":"toolResult","toolName":"write","content":[]}}"#,
826 ]);
827 assert_eq!(calls, Some(serde_json::json!({"write": 1, "bash": 1})));
828 }
829
830 #[test]
833 fn counts_tool_calls_from_opencode_inline_records() {
834 let tmp = tempfile::tempdir().unwrap();
835 let tool_event = [
836 serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"toolCall","name":"bash","arguments":{"command":"ls"}}]}}),
837 serde_json::json!({"type":"message","message":{"role":"toolResult","toolName":"bash","isError":false,"content":[{"type":"text","text":"a.rs"}]}}),
838 ];
839 let assistant_turn = [
840 serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"done"}]}}),
841 ];
842
843 crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
844 crate::commands::stream::record_inline_tool_calls(tmp.path(), &assistant_turn).unwrap();
845 assert!(collect_session_data(tmp.path())
846 .unwrap()
847 .tool_calls
848 .is_none());
849
850 crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
851 crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
852 let data = collect_session_data(tmp.path()).unwrap();
853 assert_eq!(data.tool_calls, Some(serde_json::json!({"bash": 2})));
854 assert_eq!(data.total_tool_calls, Some(2));
855 }
856
857 #[test]
858 fn connectivity_message_suggests_login_on_401() {
859 let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
860 assert!(
861 m.contains("tracevault login"),
862 "401 errors must surface the login hint; got: {m}"
863 );
864 }
865
866 #[test]
867 fn connectivity_message_suggests_login_on_unauthorized_text() {
868 let m = connectivity_message("Server returned: unauthorized request");
869 assert!(m.contains("tracevault login"));
870 }
871
872 #[test]
873 fn connectivity_message_suggests_network_check_on_dns_error() {
874 let m = connectivity_message("error sending request for url: dns error");
875 assert!(
876 m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
877 "DNS errors must surface a network hint; got: {m}"
878 );
879 }
880
881 #[test]
882 fn connectivity_message_suggests_network_check_on_connection_refused() {
883 let m = connectivity_message("connection refused");
884 assert!(m.to_lowercase().contains("network"));
885 }
886
887 #[test]
888 fn connectivity_message_falls_back_when_unrecognized() {
889 let m = connectivity_message("some weird new error shape we have not seen before");
890 assert!(m.contains("some weird new error shape"));
893 assert!(!m.contains("→")); }
895
896 #[test]
897 fn connectivity_message_does_not_collide_on_403() {
898 let m = connectivity_message("403 Forbidden");
899 assert!(
901 m.to_lowercase().contains("authorized"),
902 "403 should mention authorization; got: {m}"
903 );
904 }
905
906 #[test]
907 fn connectivity_message_flags_404_as_version_mismatch() {
908 let m = connectivity_message("Failed to list repos (404 Not Found): ");
913 assert!(
914 m.to_lowercase().contains("newer than the server")
915 || m.to_lowercase().contains("version mismatch"),
916 "404 should hint at a possible CLI/server version mismatch; got: {m}"
917 );
918 }
919
920 #[test]
921 fn connectivity_message_flags_500_as_server_error() {
922 let m = connectivity_message("Server returned 500 Internal Server Error: oops");
923 assert!(
924 m.to_lowercase().contains("server returned an error"),
925 "500 should surface the server-error hint; got: {m}"
926 );
927 }
928
929 #[test]
930 fn connectivity_message_flags_503_without_internal_text() {
931 let m = connectivity_message("Server returned 503 Service Unavailable: ");
934 assert!(
935 m.to_lowercase().contains("server returned an error"),
936 "503 should surface the server-error hint; got: {m}"
937 );
938 }
939
940 #[test]
941 fn connectivity_message_treats_504_as_server_not_network() {
942 let m = connectivity_message("Server returned 504 Gateway Timeout: ");
946 assert!(
947 m.to_lowercase().contains("server returned an error"),
948 "504 should be treated as a server error; got: {m}"
949 );
950 }
951}
952
953#[cfg(test)]
954mod push_ref_tests {
955 use super::{is_zero_sha, parse_push_refs};
956
957 #[test]
958 fn parses_a_single_ref_line() {
959 let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456\n");
960 assert_eq!(refs.len(), 1);
961 assert_eq!(refs[0].local_sha, "abc123");
962 assert_eq!(refs[0].remote_sha, "def456");
963 }
964
965 #[test]
966 fn parses_multiple_refs() {
967 let refs = parse_push_refs(
968 "refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444\n",
969 );
970 assert_eq!(refs.len(), 2);
971 }
972
973 #[test]
974 fn parses_a_single_ref_line_without_trailing_newline() {
975 let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456");
983 assert_eq!(refs.len(), 1);
984 assert_eq!(refs[0].local_sha, "abc123");
985 assert_eq!(refs[0].remote_sha, "def456");
986 }
987
988 #[test]
989 fn parses_multiple_refs_when_last_line_has_no_trailing_newline() {
990 let refs =
994 parse_push_refs("refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444");
995 assert_eq!(refs.len(), 2);
996 assert_eq!(refs[0].local_sha, "111");
997 assert_eq!(refs[1].local_sha, "333");
998 }
999
1000 #[test]
1001 fn skips_branch_deletions() {
1002 let zeros = "0".repeat(40);
1003 let line = format!("(delete) {zeros} refs/heads/gone abc123\n");
1004 assert!(parse_push_refs(&line).is_empty());
1005 }
1006
1007 #[test]
1008 fn keeps_new_branches_whose_remote_sha_is_zero() {
1009 let zeros = "0".repeat(40);
1010 let line = format!("refs/heads/new abc123 refs/heads/new {zeros}\n");
1011 let refs = parse_push_refs(&line);
1012 assert_eq!(refs.len(), 1);
1013 assert!(is_zero_sha(&refs[0].remote_sha));
1014 }
1015
1016 #[test]
1017 fn skips_malformed_lines_without_panicking() {
1018 assert!(parse_push_refs("garbage\n\nalso garbage here\n").is_empty());
1019 }
1020
1021 #[test]
1022 fn zero_sha_detection_handles_sha256_length() {
1023 assert!(is_zero_sha(&"0".repeat(64)));
1024 assert!(!is_zero_sha("0000000000000000000000000000000000000001"));
1025 assert!(!is_zero_sha(""));
1026 }
1027}
1028
1029#[cfg(test)]
1049mod git_diff_tests {
1050 use super::{changed_files_for_refs, git_empty_tree_sha, PushRef};
1051 use crate::test_helpers::init_git_repo;
1052 use std::path::Path;
1053 use std::process::Command;
1054
1055 fn commit_file(dir: &Path, name: &str, content: &str) -> String {
1059 std::fs::write(dir.join(name), content).unwrap();
1060 let ok = Command::new("git")
1061 .args(["-C", &dir.to_string_lossy(), "add", name])
1062 .status()
1063 .expect("git add failed")
1064 .success();
1065 assert!(ok, "git add must succeed");
1066 let ok = Command::new("git")
1067 .args([
1068 "-C",
1069 &dir.to_string_lossy(),
1070 "commit",
1071 "-m",
1072 &format!("add {name}"),
1073 ])
1074 .status()
1075 .expect("git commit failed")
1076 .success();
1077 assert!(ok, "git commit must succeed");
1078 head_sha(dir)
1079 }
1080
1081 fn head_sha(dir: &Path) -> String {
1082 let out = Command::new("git")
1083 .args(["-C", &dir.to_string_lossy(), "rev-parse", "HEAD"])
1084 .output()
1085 .expect("git rev-parse failed");
1086 assert!(out.status.success());
1087 String::from_utf8_lossy(&out.stdout).trim().to_string()
1088 }
1089
1090 #[test]
1091 fn two_dot_range_returns_only_the_newer_commits_files() {
1092 let tmp = tempfile::tempdir().unwrap();
1093 init_git_repo(tmp.path()); let sha1 = commit_file(tmp.path(), "a.txt", "a");
1096 let sha2 = commit_file(tmp.path(), "b.txt", "b");
1097
1098 let refs = vec![PushRef {
1099 local_sha: sha2,
1100 remote_sha: sha1,
1101 }];
1102 let files = changed_files_for_refs(tmp.path(), &refs);
1103
1104 assert_eq!(files, vec!["b.txt".to_string()]);
1109 }
1110
1111 #[test]
1112 fn new_branch_zero_remote_sha_resolves_via_empty_tree() {
1113 let tmp = tempfile::tempdir().unwrap();
1114 init_git_repo(tmp.path());
1115
1116 commit_file(tmp.path(), "a.txt", "a");
1117 let sha2 = commit_file(tmp.path(), "b.txt", "b");
1118
1119 let refs = vec![PushRef {
1120 local_sha: sha2,
1121 remote_sha: "0".repeat(40),
1122 }];
1123 let mut files = changed_files_for_refs(tmp.path(), &refs);
1124 files.sort();
1125
1126 assert_eq!(files, vec!["a.txt".to_string(), "b.txt".to_string()]);
1129 }
1130
1131 #[test]
1132 fn identical_shas_yield_an_empty_file_list() {
1133 let tmp = tempfile::tempdir().unwrap();
1134 init_git_repo(tmp.path());
1135 let sha = commit_file(tmp.path(), "a.txt", "a");
1136
1137 let refs = vec![PushRef {
1138 local_sha: sha.clone(),
1139 remote_sha: sha,
1140 }];
1141 let files = changed_files_for_refs(tmp.path(), &refs);
1142
1143 assert!(
1144 files.is_empty(),
1145 "a no-op push (same local and remote sha) must yield no files, got {files:?}"
1146 );
1147 }
1148
1149 #[test]
1150 fn non_ascii_path_is_returned_raw_not_octal_quoted() {
1151 let tmp = tempfile::tempdir().unwrap();
1152 init_git_repo(tmp.path());
1153 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1154
1155 let sha1 = commit_file(tmp.path(), "src/café.rs", "one");
1156 let sha2 = commit_file(tmp.path(), "src/café.rs", "two");
1157
1158 let refs = vec![PushRef {
1159 local_sha: sha2,
1160 remote_sha: sha1,
1161 }];
1162 let files = changed_files_for_refs(tmp.path(), &refs);
1163
1164 assert_eq!(
1170 files,
1171 vec!["src/café.rs".to_string()],
1172 "must be the raw UTF-8 path, not git's octal-quoted rendering; got {files:?}"
1173 );
1174 }
1175
1176 #[test]
1177 fn path_containing_a_space_is_returned_intact() {
1178 let tmp = tempfile::tempdir().unwrap();
1179 init_git_repo(tmp.path());
1180 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1181
1182 let sha1 = commit_file(tmp.path(), "src/has space.rs", "one");
1183 let sha2 = commit_file(tmp.path(), "src/has space.rs", "two");
1184
1185 let refs = vec![PushRef {
1186 local_sha: sha2,
1187 remote_sha: sha1,
1188 }];
1189 let files = changed_files_for_refs(tmp.path(), &refs);
1190
1191 assert_eq!(files, vec!["src/has space.rs".to_string()]);
1192 }
1193
1194 #[test]
1195 fn rename_reports_both_source_and_destination() {
1196 let tmp = tempfile::tempdir().unwrap();
1197 init_git_repo(tmp.path());
1198 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1199 let sha1 = commit_file(tmp.path(), "src/plain.rs", "identical content");
1200
1201 let ok = Command::new("git")
1202 .args([
1203 "-C",
1204 &tmp.path().to_string_lossy(),
1205 "mv",
1206 "src/plain.rs",
1207 "src/renamed.rs",
1208 ])
1209 .status()
1210 .expect("git mv failed")
1211 .success();
1212 assert!(ok, "git mv must succeed");
1213 let ok = Command::new("git")
1214 .args([
1215 "-C",
1216 &tmp.path().to_string_lossy(),
1217 "commit",
1218 "-m",
1219 "rename plain.rs to renamed.rs",
1220 ])
1221 .status()
1222 .expect("git commit failed")
1223 .success();
1224 assert!(ok, "git commit must succeed");
1225 let sha2 = head_sha(tmp.path());
1226
1227 let refs = vec![PushRef {
1228 local_sha: sha2,
1229 remote_sha: sha1,
1230 }];
1231 let mut files = changed_files_for_refs(tmp.path(), &refs);
1232 files.sort();
1233
1234 assert_eq!(
1240 files,
1241 vec!["src/plain.rs".to_string(), "src/renamed.rs".to_string()],
1242 "a rename must surface BOTH the source and destination path; got {files:?}"
1243 );
1244 }
1245
1246 #[test]
1247 fn git_empty_tree_sha_is_the_well_known_constant() {
1248 let tmp = tempfile::tempdir().unwrap();
1249 init_git_repo(tmp.path());
1250
1251 let empty_tree =
1252 git_empty_tree_sha(tmp.path()).expect("git hash-object must resolve the empty tree");
1253 assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1257 }
1258
1259 #[test]
1266 fn upstream_fallback_diff_fails_cleanly_with_no_upstream_configured() {
1267 let tmp = tempfile::tempdir().unwrap();
1268 init_git_repo(tmp.path());
1269 commit_file(tmp.path(), "a.txt", "a");
1270
1271 let out = Command::new("git")
1272 .args([
1273 "diff",
1274 "--name-only",
1275 "-z",
1276 "--no-renames",
1277 "@{upstream}..HEAD",
1278 ])
1279 .current_dir(tmp.path())
1280 .output()
1281 .expect("git diff must run");
1282
1283 assert!(
1284 !out.status.success(),
1285 "no upstream is configured, so this must fail rather than \
1286 silently resolve to something else"
1287 );
1288 }
1289
1290 #[test]
1294 fn upstream_fallback_diff_is_empty_when_upstream_matches_head() {
1295 let tmp = tempfile::tempdir().unwrap();
1296 init_git_repo(tmp.path());
1297 commit_file(tmp.path(), "a.txt", "a");
1298
1299 let branch_out = Command::new("git")
1300 .args(["symbolic-ref", "--short", "HEAD"])
1301 .current_dir(tmp.path())
1302 .output()
1303 .expect("git symbolic-ref must run");
1304 assert!(branch_out.status.success());
1305 let branch = String::from_utf8_lossy(&branch_out.stdout)
1306 .trim()
1307 .to_string();
1308
1309 for args in [
1313 vec!["branch", "tracking", &branch],
1314 vec!["branch", "--set-upstream-to=tracking", &branch],
1315 ] {
1316 let ok = Command::new("git")
1317 .args(&args)
1318 .current_dir(tmp.path())
1319 .status()
1320 .expect("git command must run")
1321 .success();
1322 assert!(ok, "git {args:?} must succeed");
1323 }
1324
1325 let out = Command::new("git")
1326 .args([
1327 "diff",
1328 "--name-only",
1329 "-z",
1330 "--no-renames",
1331 "@{upstream}..HEAD",
1332 ])
1333 .current_dir(tmp.path())
1334 .output()
1335 .expect("git diff must run");
1336
1337 assert!(out.status.success());
1338 assert!(
1339 out.stdout.is_empty(),
1340 "identical upstream/HEAD must diff to no files"
1341 );
1342 }
1343}
1344
1345#[cfg(test)]
1354mod read_with_timeout_tests {
1355 use super::read_with_timeout;
1356 use std::time::Duration;
1357
1358 #[test]
1359 fn returns_the_value_when_it_arrives_before_the_deadline() {
1360 let got = read_with_timeout(|| Some("hi".to_string()), Duration::from_secs(1));
1361 assert_eq!(got, Some("hi".to_string()));
1362 }
1363
1364 #[test]
1365 fn returns_none_when_the_closure_itself_returns_none() {
1366 let got = read_with_timeout(|| None, Duration::from_secs(1));
1367 assert_eq!(got, None);
1368 }
1369
1370 #[test]
1371 fn times_out_instead_of_hanging_on_a_closure_that_never_returns() {
1372 let start = std::time::Instant::now();
1377 let got = read_with_timeout(
1378 || {
1379 std::thread::sleep(Duration::from_secs(10));
1380 Some("too late".to_string())
1381 },
1382 Duration::from_millis(50),
1383 );
1384 assert_eq!(got, None, "must give up rather than wait for the closure");
1385 assert!(
1386 start.elapsed() < Duration::from_secs(1),
1387 "must return promptly on timeout, not block on the stalled closure; took {:?}",
1388 start.elapsed()
1389 );
1390 }
1391}
1392
1393#[cfg(test)]
1394mod pushed_repo_tests {
1395 use super::{streamed_elsewhere_warning, PushedRepo};
1396 use crate::session_state::RepoBinding;
1397
1398 const PUSHED: uuid::Uuid = uuid::uuid!("44000761-0000-4000-8000-000000000001");
1400 const BY_NAME: uuid::Uuid = uuid::uuid!("7995d35d-0000-4000-8000-000000000002");
1402 const OTHER: uuid::Uuid = uuid::uuid!("aaaaaaaa-0000-4000-8000-000000000003");
1404 const CODEBASE: uuid::Uuid = uuid::uuid!("cccccccc-0000-4000-8000-000000000004");
1405 const OTHER_CODEBASE: uuid::Uuid = uuid::uuid!("dddddddd-0000-4000-8000-000000000005");
1406 const PASS: &str = r#"{"passed":true,"results":[],"blocked":false}"#;
1407
1408 fn binding(repo: uuid::Uuid, remote: Option<uuid::Uuid>) -> RepoBinding {
1409 RepoBinding {
1410 repo_id: repo.to_string(),
1411 git_url: None,
1412 remote_id: remote,
1413 codebase_name: None,
1414 updated_at: "t".into(),
1415 }
1416 }
1417
1418 #[test]
1421 fn no_warning_when_the_session_streamed_to_the_pushed_repo_or_is_unbound() {
1422 let pushed = PushedRepo {
1423 id: PUSHED,
1424 remote_id: Some(CODEBASE),
1425 };
1426 assert_eq!(
1427 streamed_elsewhere_warning(Some(&binding(PUSHED, None)), &pushed),
1428 None
1429 );
1430 assert_eq!(streamed_elsewhere_warning(None, &pushed), None);
1431 }
1432
1433 #[test]
1434 fn warning_names_both_repos_and_how_far_apart_they_are() {
1435 let pushed = PushedRepo {
1436 id: PUSHED,
1437 remote_id: Some(CODEBASE),
1438 };
1439 let same =
1440 streamed_elsewhere_warning(Some(&binding(OTHER, Some(CODEBASE))), &pushed).unwrap();
1441 assert!(same.contains("another repo of this codebase"), "{same}");
1442 assert!(same.contains(&OTHER.to_string()) && same.contains(&PUSHED.to_string()));
1443 let far = streamed_elsewhere_warning(Some(&binding(OTHER, Some(OTHER_CODEBASE))), &pushed)
1444 .unwrap();
1445 assert!(far.contains("a different codebase"), "{far}");
1446 let unknown = streamed_elsewhere_warning(Some(&binding(OTHER, None)), &pushed).unwrap();
1447 assert!(unknown.contains("a different repo"), "{unknown}");
1448 }
1449
1450 struct Fixture {
1457 _guard: crate::test_helpers::EnvVarGuard,
1458 _home: tempfile::TempDir,
1459 _tmp: tempfile::TempDir,
1460 repo: std::path::PathBuf,
1461 rx: std::sync::mpsc::Receiver<String>,
1462 }
1463
1464 fn fixture(remote: bool, sessions: &[&str], responses: Vec<String>) -> Fixture {
1465 let home = tempfile::tempdir().unwrap();
1466 let mut guard = crate::test_helpers::EnvVarGuard::new();
1467 guard.set("XDG_CONFIG_HOME", home.path());
1468 guard.set("XDG_STATE_HOME", home.path());
1469 guard.remove("TRACEVAULT_API_KEY");
1470 guard.remove("TRACEVAULT_SERVER_URL");
1471 let (server, rx) = crate::test_helpers::spawn_seq(responses);
1472 let creds_dir = home.path().join("tracevault");
1473 std::fs::create_dir_all(&creds_dir).unwrap();
1474 std::fs::write(
1475 creds_dir.join("credentials.json"),
1476 format!(
1477 r#"{{"server_url":"{server}","email":"a@b.com","auth":{{
1478 "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
1479 "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
1480 ),
1481 )
1482 .unwrap();
1483
1484 let tmp = tempfile::tempdir().unwrap();
1485 let repo = tmp.path().join("tracing");
1486 std::fs::create_dir_all(&repo).unwrap();
1487 crate::test_helpers::init_git_repo(&repo);
1488 if remote {
1489 let ok = std::process::Command::new("git")
1490 .args([
1491 "remote",
1492 "add",
1493 "origin",
1494 "https://github.com/example/visdom-tracing.git",
1495 ])
1496 .current_dir(&repo)
1497 .status()
1498 .unwrap()
1499 .success();
1500 assert!(ok, "git remote add failed");
1501 }
1502 let top = crate::paths::worktree_toplevel(&repo);
1503 for id in sessions {
1504 let dir = repo.join(".tracevault").join("sessions").join(id);
1505 std::fs::create_dir_all(&dir).unwrap();
1506 std::fs::write(dir.join("origin"), &top).unwrap();
1507 }
1508 Fixture {
1509 _guard: guard,
1510 _home: home,
1511 _tmp: tmp,
1512 repo,
1513 rx,
1514 }
1515 }
1516
1517 fn bind_with_repo_switch(session_id: &str, repo_id: uuid::Uuid) {
1518 let state = crate::session_state::SessionState {
1519 active: Some(binding(repo_id, None)),
1520 ..Default::default()
1521 };
1522 crate::session_state::save(session_id, &state).unwrap();
1523 }
1524
1525 fn remote_resolves_to_pushed() -> Vec<String> {
1528 vec![
1529 crate::test_helpers::http_json(
1530 "200 OK",
1531 &format!(
1532 r#"{{"remote_id":"{CODEBASE}","name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready"}}"#
1533 ),
1534 ),
1535 crate::test_helpers::http_json(
1536 "200 OK",
1537 &format!(
1538 r#"{{"name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready","repos":[{{"id":"{PUSHED}","name":"visdom-tracing"}}]}}"#
1539 ),
1540 ),
1541 ]
1542 }
1543
1544 fn repos_listing() -> String {
1545 crate::test_helpers::http_json(
1546 "200 OK",
1547 &format!(r#"[{{"id":"{BY_NAME}","name":"tracing"}}]"#),
1548 )
1549 }
1550
1551 fn pass() -> String {
1552 crate::test_helpers::http_json("200 OK", PASS)
1553 }
1554
1555 fn recv(f: &Fixture) -> String {
1556 f.rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT)
1557 .expect("expected another request")
1558 }
1559
1560 fn assert_checked_under(request: &str, repo: uuid::Uuid) {
1561 assert!(
1562 request.starts_with(&format!("POST /api/v1/repos/{repo}/policies/check")),
1563 "expected the check under {repo}: {request}"
1564 );
1565 }
1566
1567 #[tokio::test]
1573 async fn a_push_is_checked_under_the_repo_its_remote_resolves_to() {
1574 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1575 let mut responses = remote_resolves_to_pushed();
1576 responses.push(pass());
1577 let f = fixture(true, &["sess-bound"], responses);
1578 bind_with_repo_switch("sess-bound", PUSHED);
1579
1580 super::check_policies(&f.repo, &f.repo).await.unwrap();
1581
1582 assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
1583 assert!(recv(&f).starts_with(&format!("GET /api/v1/remotes/{CODEBASE} ")));
1584 let check = recv(&f);
1585 assert_checked_under(&check, PUSHED);
1586 assert!(check.contains("sess-bound"), "{check}");
1587 }
1588
1589 #[tokio::test]
1593 async fn a_session_bound_elsewhere_does_not_change_which_repo_the_push_is_checked_under() {
1594 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1595 let mut responses = remote_resolves_to_pushed();
1596 responses.push(pass());
1597 let f = fixture(true, &["sess-switched", "sess-default"], responses);
1598 bind_with_repo_switch("sess-switched", OTHER);
1599 crate::user_default::save(&binding(OTHER, None)).unwrap();
1600 assert_eq!(
1601 crate::user_default::load().map(|b| b.repo_id),
1602 Some(OTHER.to_string()),
1603 "fixture must actually set a user default"
1604 );
1605
1606 super::check_policies(&f.repo, &f.repo).await.unwrap();
1607
1608 recv(&f);
1609 recv(&f);
1610 let check = recv(&f);
1611 assert_checked_under(&check, PUSHED);
1612 assert!(
1613 check.contains("sess-switched") && check.contains("sess-default"),
1614 "every session is still evaluated (fail closed): {check}"
1615 );
1616 }
1617
1618 #[tokio::test]
1620 async fn without_a_remote_the_push_is_checked_under_the_name_resolved_repo() {
1621 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1622 let f = fixture(false, &["sess-free"], vec![repos_listing(), pass()]);
1623
1624 super::check_policies(&f.repo, &f.repo).await.unwrap();
1625
1626 assert!(recv(&f).starts_with("GET /api/v1/repos "));
1627 let check = recv(&f);
1628 assert_checked_under(&check, BY_NAME);
1629 assert!(check.contains("sess-free"), "{check}");
1630 }
1631
1632 #[tokio::test]
1634 async fn an_unknown_remote_falls_back_to_the_name_resolved_repo() {
1635 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1636 let f = fixture(
1637 true,
1638 &["sess-free"],
1639 vec![
1640 crate::test_helpers::http_json("404 Not Found", r#"{"error":"remote not found"}"#),
1641 repos_listing(),
1642 pass(),
1643 ],
1644 );
1645
1646 super::check_policies(&f.repo, &f.repo).await.unwrap();
1647
1648 assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
1649 assert!(recv(&f).starts_with("GET /api/v1/repos "));
1650 assert_checked_under(&recv(&f), BY_NAME);
1651 }
1652
1653 #[tokio::test]
1655 async fn an_unregistered_repo_fails_the_push_even_without_sessions() {
1656 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1657 let f = fixture(
1658 false,
1659 &[],
1660 vec![crate::test_helpers::http_json("200 OK", "[]")],
1661 );
1662
1663 let err = super::check_policies(&f.repo, &f.repo)
1664 .await
1665 .expect_err("an unregistered repo must fail the push");
1666 assert!(err.to_string().contains("'tracing' not found"), "{err}");
1667 }
1668}