Skip to main content

tracevault_cli/commands/
check.rs

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/// One ref being pushed, as described by git's pre-push stdin protocol.
27#[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
37/// Parse git's pre-push stdin. Malformed lines are skipped rather than
38/// failing the push: this is an enrichment, and a parse error must never be
39/// the reason a developer cannot push. Branch deletions (all-zero LOCAL sha)
40/// are dropped — no content is being pushed for them.
41pub(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
61/// Files changed by the refs being pushed, repo-relative as git emits them.
62/// Over-inclusion is the safe direction: a larger set only means less pruning
63/// of AI-touched paths, never a missed violation.
64fn 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        // A new branch has no remote sha to diff from. `git diff --name-only
69        // <sha>` (one argument) diffs the working tree against that commit,
70        // which is wrong here, so name the empty tree explicitly.
71        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`: NUL-delimit output and disable git's default path
84                // quoting (`core.quotePath`), which otherwise renders any
85                // path outside plain ASCII — accents, CJK, a literal space
86                // in some locales — as an octal-escaped, double-quoted
87                // string that can never match the hook-recorded path.
88                "-z",
89                // Rename detection is on by default and reports only the
90                // destination path, hiding the source. A larger
91                // `changed_paths` only ever means less pruning, never a
92                // missed violation, so always disable it here.
93                "--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
111/// Split `git diff -z` output into paths.
112///
113/// `-z` NUL-*terminates* each path rather than NUL-*separating* them, so a
114/// naive split always yields one trailing empty element — filtered out here,
115/// along with any other empty segment. Paths are NOT trimmed: a NUL-split
116/// path needs no trimming, and trimming could corrupt a path with legal
117/// leading/trailing whitespace. `String::from_utf8_lossy` is used rather than
118/// a strict UTF-8 parse so a non-UTF-8 path degrades gracefully instead of
119/// dropping the whole diff.
120fn 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
128/// The well-known empty tree object, resolved via git so it is correct for
129/// both sha1 and sha256 repositories rather than hardcoded.
130fn 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
147/// How long to wait for git's pre-push stdin to close before falling back to
148/// `@{upstream}..HEAD`. A pre-push hook writes its ref lines and closes the
149/// pipe immediately, so this bound is never hit in normal operation — it
150/// exists only to protect against a stalled non-TTY pipe (see
151/// `resolve_changed_paths` and `read_stdin_with_timeout`).
152const STDIN_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
153
154/// Run `f` on a detached background thread and wait up to `timeout` for it
155/// to produce a value, returning `None` on timeout.
156///
157/// `f` is not cancelled on timeout: a blocked read has no way to be aborted
158/// from the outside, so the thread is deliberately leaked and we let the
159/// process exit around it rather than wait for it to unblock.
160///
161/// Generic over the read so the timeout mechanism can be exercised in tests
162/// without touching the process's real, global stdin — see
163/// `read_stdin_with_timeout`, which is the thin, untested wrapper that calls
164/// this with `std::io::stdin().read_to_string(..)`.
165fn 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
176/// Read all of stdin, giving up after `timeout`.
177///
178/// `read_to_string` blocks until EOF, and a non-TTY pipe whose writer never
179/// closes never sends one. A git pre-push hook always closes the pipe, so
180/// this bound is not hit in normal operation — but `tracevault check` sits in
181/// the push path, and hanging there with no output is far worse than losing
182/// the push-diff optimisation.
183fn 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
194/// Files in the push being attempted, or `None` if it cannot be determined.
195///
196/// Order: git's pre-push stdin (authoritative — correct for new branches,
197/// force pushes, and multi-ref pushes), then `@{upstream}..HEAD`, then give
198/// up. `None` is safe: the server falls back to evaluating the raw AI-touched
199/// set, which over-blocks rather than under-blocks. Once stdin has yielded
200/// usable refs, its diff is final — even if empty — and the function returns
201/// without trying `@{upstream}..HEAD`; that fallback is only for when stdin
202/// gave no usable refs at all, never a second opinion on an authoritative
203/// empty diff (see the comment inline below).
204fn resolve_changed_paths(project_root: &Path) -> Option<Vec<String>> {
205    use std::io::IsTerminal;
206
207    // `tracevault check` is also run by hand. Reading stdin unconditionally
208    // would block waiting for EOF, hanging the terminal. That guard alone is
209    // incomplete, though: a non-TTY pipe whose writer never closes (e.g. a
210    // stalled hook, a misbehaving wrapper script) also never sends EOF, so
211    // the read is additionally bounded in time.
212    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                // Authoritative: stdin gave us real push refs, so whatever
217                // `changed_files_for_refs` returns for them — including
218                // nothing — IS the answer for this push. Do not fall through
219                // to the `@{upstream}..HEAD` fallback below: that is a
220                // DIFFERENT range that can contain files not in this push at
221                // all, and sending paths from the wrong range corrupts the
222                // server's intersection against AI-touched paths. An
223                // authoritative empty diff must resolve to `None`, not to
224                // whatever the fallback range happens to contain.
225                let files = changed_files_for_refs(project_root, &refs);
226                return if files.is_empty() { None } else { Some(files) };
227            }
228        }
229    }
230
231    // Only reached when stdin gave us no usable refs at all (no stdin, a
232    // terminal, a timeout, or every line malformed) — never as a fallback
233    // from an authoritative-but-empty diff above.
234    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    // Read events.jsonl for files_modified
260    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    // Read transcript for tool_calls
285    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
326/// Select the session directories that belong to the current worktree.
327/// Keeps sessions whose `origin` marker == `worktree_top` OR that have no
328/// marker (legacy/unmarked — kept conservatively). Marked sessions from other
329/// worktrees are excluded.
330///
331/// Safety rail: if filtering would drop EVERY session while sessions exist,
332/// return all of them with `fell_back = true` — never under-enforce by sending
333/// zero sessions for a push that has unpushed work.
334///
335/// `pub` so the integration test in Task 7 can drive it.
336pub 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, // marked: keep only if mine
343            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
344            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
345            // Marker present but unreadable (permissions/IO): we can't prove it's
346            // ours, so exclude it rather than risk cross-worktree interference.
347            // The safety rail below still prevents under-enforcement if this
348            // drops everything.
349            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/// The server repo a push is checked under.
365#[derive(Debug, Clone, PartialEq, Eq)]
366struct PushedRepo {
367    id: uuid::Uuid,
368    /// The codebase it belongs to, when resolved through the origin remote.
369    remote_id: Option<uuid::Uuid>,
370}
371
372/// Resolve the repo being pushed — the policy authority for this push.
373///
374/// First through the checkout's origin remote, exactly as
375/// `tracevault repo switch <path>` binds a session (VIS-601): a session bound
376/// to this checkout then streams to the very repo it is checked under, so the
377/// server finds its verification window and tool stats. Then, for a checkout
378/// whose remote the server does not know (or that has none), by the primary
379/// checkout's directory name — the only resolution `check` had before.
380///
381/// Never the sessions' own bindings: a `repo switch` to another repo, or a
382/// machine-wide user default, must not decide which repo's policies a push
383/// to THIS checkout is held to.
384async 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
415/// A warning for a session whose events went to a different repo than the
416/// one this push is checked under, or `None` when they agree (or the session
417/// has no repo binding at all).
418///
419/// The session is still checked under the pushed repo — enforcement fails
420/// closed — but the server looks verification-phase data up by exact repo
421/// id, so that session's window and tool stats will not be found there.
422///
423/// Names the repos, not the session: the session id is not needed to act on
424/// it (the fix is a `repo switch` in whichever session is bound elsewhere),
425/// and CodeQL treats session ids as sensitive in log output.
426fn 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
447/// Check unpushed sessions against server policies.
448///
449/// `project_root` — the git-resolved PRIMARY worktree root (from
450///   `paths::resolve_project_root`). Used to load config/credentials, locate
451///   `.tracevault/sessions/`, and resolve the server-registered repo (by its
452///   origin remote, else by the primary checkout's basename; a sibling
453///   worktree's own directory basename would not match the registered repo).
454/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
455///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
456///   pushed from the invoking worktree, not the primary's unrelated HEAD.
457pub 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    // Resolve the pushed repo.
476    //
477    // Connectivity errors here (auth expired, server down, network
478    // unreachable) propagate so the pre-push hook exits non-zero — if a
479    // repo is opted into TraceVault, every push must be evaluated, full
480    // stop. Letting pushes slip when TV is unreachable would defeat the
481    // point of enforcement. We attach an actionable next step to each
482    // error so the user (or agent) knows the recovery command without
483    // guessing — see `connectivity_message` below.
484    let repo = resolve_pushed_repo(&client, project_root).await?;
485
486    // Collect unpushed session dirs from the shared primary .tracevault/.
487    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    // Filter to the worktree that is actually pushing, so a push is not
504    // evaluated against sessions belonging to other worktrees.
505    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    // Where each session's events actually went, resolved as the stream hook
515    // resolves it — only to warn when that is not the pushed repo. A
516    // malformed config.toml costs the bound tier here, nothing more: the
517    // check never needed the config before.
518    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    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
554    // the commit being pushed lives on the current worktree's branch.
555    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    // Print results
570    for r in &result.results {
571        let icon = match r.result.as_str() {
572            "pass" => "\x1b[32m✓\x1b[0m",                             // green
573            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
574            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
575            _ => " ",
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
595/// Wrap an opaque API-client error string with the most useful next step.
596/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
597/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
598/// the common shapes and surface a one-line action. A 404 gets its own
599/// version-mismatch hint rather than the generic fallback, since the calls
600/// that route through here have no legitimate domain reason to 404 — see
601/// the 404 branch below.
602fn connectivity_message(raw: &str) -> String {
603    let lower = raw.to_ascii_lowercase();
604
605    // 401 — token rejected. An expired session is the most common cause of
606    // a surprise blocked push, so point straight at the refresh command.
607    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    // 403 — authenticated but not allowed. Re-login won't help; the token
614    // itself is not authorized for this repo's policies.
615    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    // 404 — the route itself wasn't found. Neither call that reaches this
622    // function (`list_repos`, `check_policies`) has a legitimate domain
623    // reason to 404 — a missing repo is already turned into its own message
624    // by `resolve_repo_by_name`'s `NotFound` variant before it gets here —
625    // so a 404 this far down most plausibly means this server build doesn't
626    // recognize the route at all: a CLI/server version mismatch (e.g. this
627    // CLI shipped ahead of a server still on the old routes).
628    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    // 5xx — server-side fault. Checked before the transport keywords below
635    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
636    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    // Transport-level failure with no HTTP status — DNS, refused, timeout.
643    // ("connect" also covers "connection refused"/"connection reset".)
644    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    // Unrecognized — surface the raw error verbatim, no invented advice.
655    format!("Policy check could not run: {raw}.")
656}
657
658/// Format the standard "could not run" line with an actionable next step.
659fn with_action(raw: &str, action: &str) -> String {
660    format!("Policy check could not run: {raw}.\n  → {action}")
661}
662
663/// Heuristic for a 5xx server-side failure. Matches the textual status
664/// (`internal`, `server error`) and the concrete 5xx codes so a bare
665/// `503 Service Unavailable` — which carries neither phrase — is still
666/// recognized.
667fn 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        // A present-but-unreadable marker: make `origin` a directory so
718        // read_to_string fails with a non-NotFound error.
719        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    /// The stream hook's `metadata.json` is what lets `check` see a streaming
755    /// session's tool calls; without it every session sent `tool_calls: None`
756    /// and a "must call X" policy could never pass.
757    #[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    /// Write `lines` as a transcript, record it the way the stream hook does,
793    /// and return the tool calls `check` counts from it.
794    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    /// OpenCode sends no transcript path, only inline records; the stream hook
831    /// keeps their tool calls in a local log that `check` then counts.
832    #[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        // No suggestion — but the raw error must still be in the message so
891        // the user can debug.
892        assert!(m.contains("some weird new error shape"));
893        assert!(!m.contains("→")); // no action arrow
894    }
895
896    #[test]
897    fn connectivity_message_does_not_collide_on_403() {
898        let m = connectivity_message("403 Forbidden");
899        // 403 should point at token authorization, NOT a re-login.
900        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        // Simulates an old-server-404 skew: a route the CLI expects to exist
909        // (e.g. `Failed to list repos (404 Not Found)`) doesn't exist yet on
910        // this server build. Must hint at a version mismatch, not just
911        // report a bare 404 with no next step.
912        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        // `503 Service Unavailable` carries neither "internal" nor
932        // "server error" — the bare code must still be recognized.
933        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        // A gateway timeout is a server-side fault even though it contains
943        // the word "timeout"; it must not be misreported as a local network
944        // problem.
945        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        // This is the exact shape the generated pre-push hook produces: it
976        // captures git's stdin with `$(cat)` (which strips trailing
977        // newlines) and replays it with `printf '%s'` (which adds none
978        // back), so the real input to `check` has no trailing newline on
979        // its final line. Here that unterminated line is the *only* line.
980        // Do not delete this as a duplicate of `parses_a_single_ref_line`;
981        // it pins a different, easy-to-break input shape.
982        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        // Same hook-stdin shape as above, but with two refs: only the final
991        // line is unterminated, matching a real multi-ref push through
992        // `$(cat)` + `printf '%s'`.
993        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/// Real-git coverage for the functions `resolve_changed_paths` composes:
1030/// `changed_files_for_refs` (the two-dot range and the empty-tree base for
1031/// new branches) and `git_empty_tree_sha`.
1032///
1033/// `resolve_changed_paths` itself is deliberately NOT driven directly here.
1034/// It reads `std::io::stdin()` when stdin is not a terminal, and `cargo
1035/// test` runs every test in one process sharing that real, global stdin —
1036/// there is no per-test way to inject or close it without invasive,
1037/// process-wide fd surgery, and a test that consumes it would make unrelated
1038/// tests in the same binary flaky. Testing the two git-backed branches it
1039/// falls back to (below) is the safe substitute; the stdin-parsing branch
1040/// itself is already covered without touching stdin by `push_ref_tests`
1041/// (`parse_push_refs`) plus `two_dot_range_returns_only_the_newer_commits_files`
1042/// and `new_branch_zero_remote_sha_resolves_via_empty_tree` below, which
1043/// together exercise every step `resolve_changed_paths` performs once it has
1044/// a parsed `Vec<PushRef>` in hand. The timeout mechanism that bounds the
1045/// stdin read (`read_with_timeout`) is factored generically over the reading
1046/// closure precisely so it can be tested without touching stdin at all —
1047/// see `read_with_timeout_tests` below.
1048#[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    /// Write `name` with `content` in `dir`, stage it, and commit it,
1056    /// returning the new commit's sha. Assumes `init_git_repo` already
1057    /// configured a local `user.name`/`user.email` in `dir`.
1058    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()); // empty "init" commit
1094
1095        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        // Must be exactly the file the newer commit touched. A single-arg
1105        // `git diff --name-only <sha>` would instead diff against the
1106        // working tree and silently pull in every tracked file (here, also
1107        // "a.txt") — this is the mistake this test exists to catch.
1108        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        // A brand-new branch has no remote sha to diff from; the base must
1127        // resolve to the empty tree, so the full branch history shows up.
1128        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        // Without `-z`, git's default `core.quotePath` behaviour renders this
1165        // as the 20-character literal string `"src/caf\303\251.rs"`
1166        // (surrounding quotes included) instead of the real path — see the
1167        // fix's doc comment. That string can never match the hook-recorded
1168        // path, so the file is silently pruned from `changed_paths`.
1169        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        // Git's rename detection is on by default, so a plain `git diff
1235        // --name-only` here would report only `src/renamed.rs`, hiding the
1236        // fact that `src/plain.rs` ever existed in this diff. If
1237        // `src/plain.rs` were a protected path, that silence is exactly what
1238        // lets an agent rename it away undetected.
1239        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        // The well-known empty-tree object id for sha1 repositories (git's
1254        // default) — asserted against the literal, not just "non-empty", so
1255        // a regression that resolves some other tree can't slip through.
1256        assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1257    }
1258
1259    /// Not a call into `resolve_changed_paths` (see the module doc comment
1260    /// above for why) — this drives the exact git invocation its
1261    /// `@{{upstream}}` fallback branch makes, in a repo with no upstream
1262    /// configured, confirming that branch fails cleanly (non-zero exit) and
1263    /// so `resolve_changed_paths` would correctly return `None` rather than
1264    /// erroring or panicking.
1265    #[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    /// Companion to the test above: with an upstream configured but no diff
1291    /// between it and `HEAD`, the same invocation must succeed with empty
1292    /// output — the shape `resolve_changed_paths` treats as `None`.
1293    #[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        // Track a same-commit local branch as upstream, so `@{upstream}`
1310        // resolves but the diff against it is empty — without needing an
1311        // actual remote.
1312        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/// Coverage for the generic timeout mechanism behind `read_stdin_with_timeout`.
1346///
1347/// These drive `read_with_timeout` directly with an injected closure instead
1348/// of the real `stdin()` — see the doc comment on `git_diff_tests` above for
1349/// why touching the process's real, global stdin from a test is unsafe here.
1350/// `read_stdin_with_timeout` itself is left thin and untested; once the
1351/// generic helper is proven to time out and to pass through a prompt result,
1352/// there is nothing stdin-specific left to verify.
1353#[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        // The stalled-pipe case in miniature: the closure blocks well past
1373        // the deadline (in the real bug, forever). Margins are kept wide so
1374        // this cannot flake on a loaded CI machine — a 50ms timeout that
1375        // must return within 1s, against a closure that sleeps for 10s.
1376        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    /// The repo the checkout's origin remote resolves to.
1399    const PUSHED: uuid::Uuid = uuid::uuid!("44000761-0000-4000-8000-000000000001");
1400    /// The repo registered under the checkout's directory name.
1401    const BY_NAME: uuid::Uuid = uuid::uuid!("7995d35d-0000-4000-8000-000000000002");
1402    /// Some other repo a session could be bound to.
1403    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    // ── streamed_elsewhere_warning ───────────────────────────────────────────
1419
1420    #[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    // ── check_policies end to end against a one-shot server ──────────────────
1451
1452    /// Isolated config/state homes and a saved login for a server answering
1453    /// `responses` in order; a primary checkout named `tracing` (with an
1454    /// origin remote when `remote` is set) holding the given sessions, all
1455    /// marked as this worktree's.
1456    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    /// The origin remote resolves to codebase `CODEBASE`, whose only repo is
1526    /// `PUSHED` — what `repo switch <checkout>` binds a session to.
1527    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    /// VIS-601 (first hit on VIS-536's PR): a session bound with
1568    /// `repo switch <checkout>` streamed to the repo the checkout's remote
1569    /// resolves to, but was checked under the repo found by directory name.
1570    /// The push is now checked under the remote-resolved repo, where that
1571    /// session's data lives.
1572    #[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    /// The pushed repo is the policy authority: a session bound elsewhere —
1590    /// by `repo switch` or by a machine-wide user default — must not move the
1591    /// push to that repo's (possibly laxer) policies.
1592    #[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    /// No origin remote: the directory-name lookup, exactly as before VIS-601.
1619    #[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    /// A remote the server does not know falls back to the name lookup too.
1633    #[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    /// An unregistered repo still fails the push, even with nothing to check.
1654    #[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}