Skip to main content

tracevault_cli/commands/
check.rs

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/// One ref being pushed, as described by git's pre-push stdin protocol.
28#[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
38/// Parse git's pre-push stdin. Malformed lines are skipped rather than
39/// failing the push: this is an enrichment, and a parse error must never be
40/// the reason a developer cannot push. Branch deletions (all-zero LOCAL sha)
41/// are dropped — no content is being pushed for them.
42pub(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
62/// Files changed by the refs being pushed, repo-relative as git emits them.
63/// Over-inclusion is the safe direction: a larger set only means less pruning
64/// of AI-touched paths, never a missed violation.
65fn 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        // A new branch has no remote sha to diff from. `git diff --name-only
70        // <sha>` (one argument) diffs the working tree against that commit,
71        // which is wrong here, so name the empty tree explicitly.
72        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`: NUL-delimit output and disable git's default path
85                // quoting (`core.quotePath`), which otherwise renders any
86                // path outside plain ASCII — accents, CJK, a literal space
87                // in some locales — as an octal-escaped, double-quoted
88                // string that can never match the hook-recorded path.
89                "-z",
90                // Rename detection is on by default and reports only the
91                // destination path, hiding the source. A larger
92                // `changed_paths` only ever means less pruning, never a
93                // missed violation, so always disable it here.
94                "--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
112/// Split `git diff -z` output into paths.
113///
114/// `-z` NUL-*terminates* each path rather than NUL-*separating* them, so a
115/// naive split always yields one trailing empty element — filtered out here,
116/// along with any other empty segment. Paths are NOT trimmed: a NUL-split
117/// path needs no trimming, and trimming could corrupt a path with legal
118/// leading/trailing whitespace. `String::from_utf8_lossy` is used rather than
119/// a strict UTF-8 parse so a non-UTF-8 path degrades gracefully instead of
120/// dropping the whole diff.
121fn 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
129/// The well-known empty tree object, resolved via git so it is correct for
130/// both sha1 and sha256 repositories rather than hardcoded.
131fn 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
148/// How long to wait for git's pre-push stdin to close before falling back to
149/// `@{upstream}..HEAD`. A pre-push hook writes its ref lines and closes the
150/// pipe immediately, so this bound is never hit in normal operation — it
151/// exists only to protect against a stalled non-TTY pipe (see
152/// `resolve_changed_paths` and `read_stdin_with_timeout`).
153const STDIN_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
154
155/// Run `f` on a detached background thread and wait up to `timeout` for it
156/// to produce a value, returning `None` on timeout.
157///
158/// `f` is not cancelled on timeout: a blocked read has no way to be aborted
159/// from the outside, so the thread is deliberately leaked and we let the
160/// process exit around it rather than wait for it to unblock.
161///
162/// Generic over the read so the timeout mechanism can be exercised in tests
163/// without touching the process's real, global stdin — see
164/// `read_stdin_with_timeout`, which is the thin, untested wrapper that calls
165/// this with `std::io::stdin().read_to_string(..)`.
166fn 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
177/// Read all of stdin, giving up after `timeout`.
178///
179/// `read_to_string` blocks until EOF, and a non-TTY pipe whose writer never
180/// closes never sends one. A git pre-push hook always closes the pipe, so
181/// this bound is not hit in normal operation — but `tracevault check` sits in
182/// the push path, and hanging there with no output is far worse than losing
183/// the push-diff optimisation.
184fn 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
195/// Files in the push being attempted, or `None` if it cannot be determined.
196///
197/// Order: git's pre-push stdin (authoritative — correct for new branches,
198/// force pushes, and multi-ref pushes), then `@{upstream}..HEAD`, then give
199/// up. `None` is safe: the server falls back to evaluating the raw AI-touched
200/// set, which over-blocks rather than under-blocks. Once stdin has yielded
201/// usable refs, its diff is final — even if empty — and the function returns
202/// without trying `@{upstream}..HEAD`; that fallback is only for when stdin
203/// gave no usable refs at all, never a second opinion on an authoritative
204/// empty diff (see the comment inline below).
205fn resolve_changed_paths(project_root: &Path) -> Option<Vec<String>> {
206    use std::io::IsTerminal;
207
208    // `tracevault check` is also run by hand. Reading stdin unconditionally
209    // would block waiting for EOF, hanging the terminal. That guard alone is
210    // incomplete, though: a non-TTY pipe whose writer never closes (e.g. a
211    // stalled hook, a misbehaving wrapper script) also never sends EOF, so
212    // the read is additionally bounded in time.
213    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                // Authoritative: stdin gave us real push refs, so whatever
218                // `changed_files_for_refs` returns for them — including
219                // nothing — IS the answer for this push. Do not fall through
220                // to the `@{upstream}..HEAD` fallback below: that is a
221                // DIFFERENT range that can contain files not in this push at
222                // all, and sending paths from the wrong range corrupts the
223                // server's intersection against AI-touched paths. An
224                // authoritative empty diff must resolve to `None`, not to
225                // whatever the fallback range happens to contain.
226                let files = changed_files_for_refs(project_root, &refs);
227                return if files.is_empty() { None } else { Some(files) };
228            }
229        }
230    }
231
232    // Only reached when stdin gave us no usable refs at all (no stdin, a
233    // terminal, a timeout, or every line malformed) — never as a fallback
234    // from an authoritative-but-empty diff above.
235    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    // Read events.jsonl for files_modified
261    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    // Read transcript for tool_calls
286    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
327/// Select the session directories that belong to the current worktree.
328/// Keeps sessions whose `origin` marker == `worktree_top` OR that have no
329/// marker (legacy/unmarked — kept conservatively). Marked sessions from other
330/// worktrees are excluded.
331///
332/// Safety rail: if filtering would drop EVERY session while sessions exist,
333/// return all of them with `fell_back = true` — never under-enforce by sending
334/// zero sessions for a push that has unpushed work.
335///
336/// `pub` so the integration test in Task 7 can drive it.
337pub 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            // Marked: keep only if mine — the latest event ran here, or an
344            // anchored session lists this worktree as one it ran in (VIS-1257).
345            Ok(s) => s.trim() == worktree_top || crate::session_state::ran_in(dir, worktree_top),
346            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
347            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
348            // Marker present but unreadable (permissions/IO): we can't prove it's
349            // ours, so exclude it rather than risk cross-worktree interference.
350            // The safety rail below still prevents under-enforcement if this
351            // drops everything.
352            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
367/// [`select_worktree_sessions`] over the local dirs, plus the `external` ones
368/// (already known to belong to this worktree). The fall-back to every local
369/// session applies only when neither matched: an external session is a match.
370fn 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
390/// Add a session dir that lives outside `sessions_dir` to the sessions a
391/// push is checked against, unless it is gone, pushed, or already there.
392///
393/// A session keeps its dir in the `.visdom/` it STARTED in (VIS-1257), so
394/// one started in an umbrella directory that then works in this checkout has
395/// no dir here. A dir inside `sessions_dir` was already considered by the
396/// worktree selection, and its verdict stands.
397fn 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/// The server repo a push is checked under.
414#[derive(Debug, Clone, PartialEq, Eq)]
415struct PushedRepo {
416    id: uuid::Uuid,
417    /// The codebase it belongs to, when resolved through the origin remote.
418    remote_id: Option<uuid::Uuid>,
419}
420
421/// Resolve the repo being pushed — the policy authority for this push.
422///
423/// First through the checkout's origin remote, exactly as
424/// `tracevault repo switch <path>` binds a session (VIS-601): a session bound
425/// to this checkout then streams to the very repo it is checked under, so the
426/// server finds its verification window and tool stats. Then, for a checkout
427/// whose remote the server does not know (or that has none), by the primary
428/// checkout's directory name — the only resolution `check` had before.
429///
430/// Never the sessions' own bindings: a `repo switch` to another repo, or a
431/// machine-wide user default, must not decide which repo's policies a push
432/// to THIS checkout is held to.
433async 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
463/// A warning for a session whose events went to a different repo than the
464/// one this push is checked under, or `None` when they agree (or the session
465/// has no repo binding at all).
466///
467/// The session is still checked under the pushed repo — enforcement fails
468/// closed — but the server looks verification-phase data up by exact repo
469/// id, so that session's window and tool stats will not be found there.
470///
471/// Names the repos, not the session: the session id is not needed to act on
472/// it (the fix is a `repo switch` in whichever session is bound elsewhere),
473/// and CodeQL treats session ids as sensitive in log output.
474fn 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
495/// Check unpushed sessions against server policies.
496///
497/// `project_root` — the git-resolved PRIMARY worktree root (from
498///   `paths::resolve_project_root`). Used to load config/credentials, locate
499///   `.visdom/sessions/`, and resolve the server-registered repo (by its
500///   origin remote, else by the primary checkout's basename; a sibling
501///   worktree's own directory basename would not match the registered repo).
502/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
503///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
504///   pushed from the invoking worktree, not the primary's unrelated HEAD.
505pub 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    // Resolve the pushed repo.
525    //
526    // Connectivity errors here (auth expired, server down, network
527    // unreachable) propagate so the pre-push hook exits non-zero — if a
528    // repo is opted into Visdom, every push must be evaluated, full
529    // stop. Letting pushes slip when TV is unreachable would defeat the
530    // point of enforcement. We attach an actionable next step to each
531    // error so the user (or agent) knows the recovery command without
532    // guessing — see `connectivity_message` below.
533    let repo = resolve_pushed_repo(&client, project_root).await?;
534
535    // Collect unpushed session dirs from the shared primary .visdom/.
536    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    // Filter to the worktree that is actually pushing, so a push is not
553    // evaluated against sessions belonging to other worktrees.
554    let worktree_top = crate::paths::worktree_toplevel(cwd);
555    //
556    // Sessions that keep their dir in the `.visdom/` they started in (an
557    // umbrella dir, VIS-1257) and worked in this worktree, plus the session
558    // running this push, wherever its dir is, belong to it too — found
559    // first, so they count before falling back to every local session.
560    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    // Where each session's events actually went, resolved as the stream hook
573    // resolves it — only to warn when that is not the pushed repo. A
574    // malformed config.toml costs the bound tier here, nothing more: the
575    // check never needed the config before.
576    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    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
613    // the commit being pushed lives on the current worktree's branch.
614    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    // Print results
629    for r in &result.results {
630        let icon = match r.result.as_str() {
631            "pass" => "\x1b[32m✓\x1b[0m",                             // green
632            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
633            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
634            _ => " ",
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
654/// Wrap an opaque API-client error string with the most useful next step.
655/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
656/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
657/// the common shapes and surface a one-line action. A 404 gets its own
658/// version-mismatch hint rather than the generic fallback, since the calls
659/// that route through here have no legitimate domain reason to 404 — see
660/// the 404 branch below.
661fn connectivity_message(raw: &str) -> String {
662    let lower = raw.to_ascii_lowercase();
663
664    // 401 — token rejected. An expired session is the most common cause of
665    // a surprise blocked push, so point straight at the refresh command.
666    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    // 403 — authenticated but not allowed. Re-login won't help; the token
673    // itself is not authorized for this repo's policies.
674    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    // 404 — the route itself wasn't found. Neither call that reaches this
681    // function (`list_repos`, `check_policies`) has a legitimate domain
682    // reason to 404 — a missing repo is already turned into its own message
683    // by `resolve_repo_by_name`'s `NotFound` variant before it gets here —
684    // so a 404 this far down most plausibly means this server build doesn't
685    // recognize the route at all: a CLI/server version mismatch (e.g. this
686    // CLI shipped ahead of a server still on the old routes).
687    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    // 5xx — server-side fault. Checked before the transport keywords below
694    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
695    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    // Transport-level failure with no HTTP status — DNS, refused, timeout.
702    // ("connect" also covers "connection refused"/"connection reset".)
703    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    // Unrecognized — surface the raw error verbatim, no invented advice.
714    format!("Policy check could not run: {raw}.")
715}
716
717/// Format the standard "could not run" line with an actionable next step.
718fn with_action(raw: &str, action: &str) -> String {
719    format!("Policy check could not run: {raw}.\n  → {action}")
720}
721
722/// Heuristic for a 5xx server-side failure. Matches the textual status
723/// (`internal`, `server error`) and the concrete 5xx codes so a bare
724/// `503 Service Unavailable` — which carries neither phrase — is still
725/// recognized.
726fn 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    /// A session kept here that ran here and moved to another repo: its
761    /// `origin` names the other repo, its worktree list names this one.
762    #[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        // A present-but-unreadable marker: make `origin` a directory so
842        // read_to_string fails with a non-NotFound error.
843        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    /// The stream hook's `metadata.json` is what lets `check` see a streaming
879    /// session's tool calls; without it every session sent `tool_calls: None`
880    /// and a "must call X" policy could never pass.
881    #[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    /// Write `lines` as a transcript, record it the way the stream hook does,
917    /// and return the tool calls `check` counts from it.
918    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    /// OpenCode sends no transcript path, only inline records; the stream hook
955    /// keeps their tool calls in a local log that `check` then counts.
956    #[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    /// Amp's plugin sends Amp's own messages in an `amp_message` envelope;
982    /// policies name Amp's tools exactly (`shell_command`, `Task`, ...).
983    #[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        // No suggestion — but the raw error must still be in the message so
1039        // the user can debug.
1040        assert!(m.contains("some weird new error shape"));
1041        assert!(!m.contains("→")); // no action arrow
1042    }
1043
1044    #[test]
1045    fn connectivity_message_does_not_collide_on_403() {
1046        let m = connectivity_message("403 Forbidden");
1047        // 403 should point at token authorization, NOT a re-login.
1048        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        // Simulates an old-server-404 skew: a route the CLI expects to exist
1057        // (e.g. `Failed to list repos (404 Not Found)`) doesn't exist yet on
1058        // this server build. Must hint at a version mismatch, not just
1059        // report a bare 404 with no next step.
1060        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        // `503 Service Unavailable` carries neither "internal" nor
1080        // "server error" — the bare code must still be recognized.
1081        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        // A gateway timeout is a server-side fault even though it contains
1091        // the word "timeout"; it must not be misreported as a local network
1092        // problem.
1093        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        // This is the exact shape the generated pre-push hook produces: it
1124        // captures git's stdin with `$(cat)` (which strips trailing
1125        // newlines) and replays it with `printf '%s'` (which adds none
1126        // back), so the real input to `check` has no trailing newline on
1127        // its final line. Here that unterminated line is the *only* line.
1128        // Do not delete this as a duplicate of `parses_a_single_ref_line`;
1129        // it pins a different, easy-to-break input shape.
1130        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        // Same hook-stdin shape as above, but with two refs: only the final
1139        // line is unterminated, matching a real multi-ref push through
1140        // `$(cat)` + `printf '%s'`.
1141        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/// Real-git coverage for the functions `resolve_changed_paths` composes:
1178/// `changed_files_for_refs` (the two-dot range and the empty-tree base for
1179/// new branches) and `git_empty_tree_sha`.
1180///
1181/// `resolve_changed_paths` itself is deliberately NOT driven directly here.
1182/// It reads `std::io::stdin()` when stdin is not a terminal, and `cargo
1183/// test` runs every test in one process sharing that real, global stdin —
1184/// there is no per-test way to inject or close it without invasive,
1185/// process-wide fd surgery, and a test that consumes it would make unrelated
1186/// tests in the same binary flaky. Testing the two git-backed branches it
1187/// falls back to (below) is the safe substitute; the stdin-parsing branch
1188/// itself is already covered without touching stdin by `push_ref_tests`
1189/// (`parse_push_refs`) plus `two_dot_range_returns_only_the_newer_commits_files`
1190/// and `new_branch_zero_remote_sha_resolves_via_empty_tree` below, which
1191/// together exercise every step `resolve_changed_paths` performs once it has
1192/// a parsed `Vec<PushRef>` in hand. The timeout mechanism that bounds the
1193/// stdin read (`read_with_timeout`) is factored generically over the reading
1194/// closure precisely so it can be tested without touching stdin at all —
1195/// see `read_with_timeout_tests` below.
1196#[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    /// Write `name` with `content` in `dir`, stage it, and commit it,
1204    /// returning the new commit's sha. Assumes `init_git_repo` already
1205    /// configured a local `user.name`/`user.email` in `dir`.
1206    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()); // empty "init" commit
1242
1243        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        // Must be exactly the file the newer commit touched. A single-arg
1253        // `git diff --name-only <sha>` would instead diff against the
1254        // working tree and silently pull in every tracked file (here, also
1255        // "a.txt") — this is the mistake this test exists to catch.
1256        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        // A brand-new branch has no remote sha to diff from; the base must
1275        // resolve to the empty tree, so the full branch history shows up.
1276        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        // Without `-z`, git's default `core.quotePath` behaviour renders this
1313        // as the 20-character literal string `"src/caf\303\251.rs"`
1314        // (surrounding quotes included) instead of the real path — see the
1315        // fix's doc comment. That string can never match the hook-recorded
1316        // path, so the file is silently pruned from `changed_paths`.
1317        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        // Git's rename detection is on by default, so a plain `git diff
1383        // --name-only` here would report only `src/renamed.rs`, hiding the
1384        // fact that `src/plain.rs` ever existed in this diff. If
1385        // `src/plain.rs` were a protected path, that silence is exactly what
1386        // lets an agent rename it away undetected.
1387        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        // The well-known empty-tree object id for sha1 repositories (git's
1402        // default) — asserted against the literal, not just "non-empty", so
1403        // a regression that resolves some other tree can't slip through.
1404        assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1405    }
1406
1407    /// Not a call into `resolve_changed_paths` (see the module doc comment
1408    /// above for why) — this drives the exact git invocation its
1409    /// `@{{upstream}}` fallback branch makes, in a repo with no upstream
1410    /// configured, confirming that branch fails cleanly (non-zero exit) and
1411    /// so `resolve_changed_paths` would correctly return `None` rather than
1412    /// erroring or panicking.
1413    #[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    /// Companion to the test above: with an upstream configured but no diff
1439    /// between it and `HEAD`, the same invocation must succeed with empty
1440    /// output — the shape `resolve_changed_paths` treats as `None`.
1441    #[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        // Track a same-commit local branch as upstream, so `@{upstream}`
1458        // resolves but the diff against it is empty — without needing an
1459        // actual remote.
1460        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/// Coverage for the generic timeout mechanism behind `read_stdin_with_timeout`.
1494///
1495/// These drive `read_with_timeout` directly with an injected closure instead
1496/// of the real `stdin()` — see the doc comment on `git_diff_tests` above for
1497/// why touching the process's real, global stdin from a test is unsafe here.
1498/// `read_stdin_with_timeout` itself is left thin and untested; once the
1499/// generic helper is proven to time out and to pass through a prompt result,
1500/// there is nothing stdin-specific left to verify.
1501#[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        // The stalled-pipe case in miniature: the closure blocks well past
1521        // the deadline (in the real bug, forever). Margins are kept wide so
1522        // this cannot flake on a loaded CI machine — a 50ms timeout that
1523        // must return within 1s, against a closure that sleeps for 10s.
1524        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    /// The repo the checkout's origin remote resolves to.
1547    const PUSHED: uuid::Uuid = uuid::uuid!("44000761-0000-4000-8000-000000000001");
1548    /// The repo registered under the checkout's directory name.
1549    const BY_NAME: uuid::Uuid = uuid::uuid!("7995d35d-0000-4000-8000-000000000002");
1550    /// Some other repo a session could be bound to.
1551    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    // ── streamed_elsewhere_warning ───────────────────────────────────────────
1567
1568    #[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    // ── check_policies end to end against a one-shot server ──────────────────
1599
1600    /// Isolated config/state homes and a saved login for a server answering
1601    /// `responses` in order; a primary checkout named `tracing` (with an
1602    /// origin remote when `remote` is set) holding the given sessions, all
1603    /// marked as this worktree's.
1604    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    /// The origin remote resolves to codebase `CODEBASE`, whose only repo is
1674    /// `PUSHED` — what `repo switch <checkout>` binds a session to.
1675    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    /// VIS-601 (first hit on VIS-536's PR): a session bound with
1716    /// `repo switch <checkout>` streamed to the repo the checkout's remote
1717    /// resolves to, but was checked under the repo found by directory name.
1718    /// The push is now checked under the remote-resolved repo, where that
1719    /// session's data lives.
1720    #[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    /// The pushed repo is the policy authority: a session bound elsewhere —
1738    /// by `repo switch` or by a machine-wide user default — must not move the
1739    /// push to that repo's (possibly laxer) policies.
1740    #[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    /// No origin remote: the directory-name lookup, exactly as before VIS-601.
1767    #[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    /// A remote the server does not know falls back to the name lookup too.
1781    #[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    /// An unregistered repo still fails the push, even with nothing to check.
1802    #[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}