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 mut tool_calls_map: std::collections::HashMap<String, i32> =
299        std::collections::HashMap::new();
300    let mut total_tool_calls: i32 = 0;
301
302    if let Some(path) = &transcript_path {
303        if let Ok(content) = fs::read_to_string(path) {
304            for line in content.lines() {
305                let entry: serde_json::Value = match serde_json::from_str(line) {
306                    Ok(v) => v,
307                    Err(_) => continue,
308                };
309
310                if entry.get("type").and_then(|v| v.as_str()) == Some("assistant") {
311                    if let Some(content_arr) = entry
312                        .get("message")
313                        .and_then(|m| m.get("content"))
314                        .and_then(|c| c.as_array())
315                    {
316                        for block in content_arr {
317                            if block.get("type").and_then(|v| v.as_str()) == Some("tool_use") {
318                                if let Some(name) = block.get("name").and_then(|v| v.as_str()) {
319                                    *tool_calls_map.entry(name.to_string()).or_insert(0) += 1;
320                                    total_tool_calls += 1;
321                                }
322                            }
323                        }
324                    }
325                }
326            }
327        }
328    }
329
330    let tool_calls = if tool_calls_map.is_empty() {
331        None
332    } else {
333        serde_json::to_value(&tool_calls_map).ok()
334    };
335
336    Some(SessionCheckData {
337        session_id,
338        tool_calls,
339        files_modified: if files_modified.is_empty() {
340            None
341        } else {
342            Some(files_modified)
343        },
344        total_tool_calls: if total_tool_calls > 0 {
345            Some(total_tool_calls)
346        } else {
347            None
348        },
349    })
350}
351
352/// Select the session directories that belong to the current worktree.
353/// Keeps sessions whose `origin` marker == `worktree_top` OR that have no
354/// marker (legacy/unmarked — kept conservatively). Marked sessions from other
355/// worktrees are excluded.
356///
357/// Safety rail: if filtering would drop EVERY session while sessions exist,
358/// return all of them with `fell_back = true` — never under-enforce by sending
359/// zero sessions for a push that has unpushed work.
360///
361/// `pub` so the integration test in Task 7 can drive it.
362pub fn select_worktree_sessions(
363    session_dirs: Vec<std::path::PathBuf>,
364    worktree_top: &str,
365) -> (Vec<std::path::PathBuf>, bool) {
366    let belongs = |dir: &std::path::Path| -> bool {
367        match fs::read_to_string(dir.join("origin")) {
368            Ok(s) => s.trim() == worktree_top, // marked: keep only if mine
369            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
370            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
371            // Marker present but unreadable (permissions/IO): we can't prove it's
372            // ours, so exclude it rather than risk cross-worktree interference.
373            // The safety rail below still prevents under-enforcement if this
374            // drops everything.
375            Err(_) => false,
376        }
377    };
378    let filtered: Vec<_> = session_dirs
379        .iter()
380        .filter(|d| belongs(d))
381        .cloned()
382        .collect();
383    if filtered.is_empty() && !session_dirs.is_empty() {
384        (session_dirs, true)
385    } else {
386        (filtered, false)
387    }
388}
389
390/// Check unpushed sessions against server policies.
391///
392/// `project_root` — the git-resolved PRIMARY worktree root (from
393///   `paths::resolve_project_root`). Used to load config/credentials, locate
394///   `.tracevault/sessions/`, and resolve the server-registered repo name
395///   (the primary checkout's basename; a sibling worktree's own directory
396///   basename would not match the registered repo).
397/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
398///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
399///   pushed from the invoking worktree, not the primary's unrelated HEAD.
400pub async fn check_policies(
401    project_root: &Path,
402    cwd: &Path,
403) -> Result<(), Box<dyn std::error::Error>> {
404    let (server_url, credential) = resolve_credentials(project_root)?;
405
406    let server_url = server_url
407        .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
408
409    if credential.is_none() {
410        return Err(
411            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
412                .into(),
413        );
414    }
415
416    let client = ApiClient::with_credential(&server_url, credential);
417
418    // Resolve repo_id by name.
419    //
420    // Connectivity errors here (auth expired, server down, network
421    // unreachable) propagate so the pre-push hook exits non-zero — if a
422    // repo is opted into TraceVault, every push must be evaluated, full
423    // stop. Letting pushes slip when TV is unreachable would defeat the
424    // point of enforcement. We attach an actionable next step to each
425    // error so the user (or agent) knows the recovery command without
426    // guessing — see `connectivity_message` below.
427    let repo = match resolve_repo_by_name(&client, project_root).await {
428        Ok(r) => r,
429        Err(ResolveRepoByNameError::ListFailed(e)) => {
430            return Err(connectivity_message(&e.to_string()).into());
431        }
432        Err(ResolveRepoByNameError::NotFound { repo_name }) => {
433            return Err(format!(
434                "Repo '{repo_name}' not found on server. Run `tracevault sync` first."
435            )
436            .into());
437        }
438    };
439
440    // Collect unpushed session dirs from the shared primary .tracevault/.
441    let sessions_dir = project_root.join(".tracevault").join("sessions");
442    let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
443    if sessions_dir.exists() {
444        for entry in fs::read_dir(&sessions_dir)? {
445            let entry = entry?;
446            if !entry.file_type()?.is_dir() {
447                continue;
448            }
449            let session_dir = entry.path();
450            if session_dir.join(".pushed").exists() {
451                continue;
452            }
453            unpushed_dirs.push(session_dir);
454        }
455    }
456
457    // Filter to the worktree that is actually pushing, so a push is not
458    // evaluated against sessions belonging to other worktrees.
459    let worktree_top = crate::paths::worktree_toplevel(cwd);
460    let (selected_dirs, fell_back) = select_worktree_sessions(unpushed_dirs, &worktree_top);
461    if fell_back {
462        eprintln!(
463            "Warning: no unpushed session matched this worktree by origin marker — \
464             checking all unpushed sessions to avoid skipping policy enforcement."
465        );
466    }
467
468    let mut sessions = Vec::new();
469    for session_dir in &selected_dirs {
470        if let Some(data) = collect_session_data(session_dir) {
471            sessions.push(data);
472        }
473    }
474
475    if sessions.is_empty() {
476        println!("No unpushed sessions to check.");
477        return Ok(());
478    }
479
480    println!("Checking {} session(s) against policies...", sessions.len());
481
482    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
483    // the commit being pushed lives on the current worktree's branch.
484    let commit_sha = git_head_sha(cwd);
485    let changed_paths = resolve_changed_paths(cwd);
486    let result = client
487        .check_policies(
488            &repo.id,
489            CheckPoliciesRequest {
490                sessions,
491                commit_sha,
492                changed_paths,
493            },
494        )
495        .await
496        .map_err(|e| connectivity_message(&e.to_string()))?;
497
498    // Print results
499    for r in &result.results {
500        let icon = match r.result.as_str() {
501            "pass" => "\x1b[32m✓\x1b[0m",                             // green
502            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
503            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
504            _ => " ",
505        };
506        println!(
507            "  {} [{}] {} — {}",
508            icon, r.severity, r.rule_name, r.details
509        );
510    }
511
512    if result.blocked {
513        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
514        std::process::exit(1);
515    } else if result.passed {
516        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
517    } else {
518        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
519    }
520
521    Ok(())
522}
523
524/// Wrap an opaque API-client error string with the most useful next step.
525/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
526/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
527/// the common shapes and surface a one-line action. A 404 gets its own
528/// version-mismatch hint rather than the generic fallback, since the calls
529/// that route through here have no legitimate domain reason to 404 — see
530/// the 404 branch below.
531fn connectivity_message(raw: &str) -> String {
532    let lower = raw.to_ascii_lowercase();
533
534    // 401 — token rejected. An expired session is the most common cause of
535    // a surprise blocked push, so point straight at the refresh command.
536    if lower.contains("401") || lower.contains("unauthorized") {
537        return with_action(
538            raw,
539            "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
540        );
541    }
542    // 403 — authenticated but not allowed. Re-login won't help; the token
543    // itself is not authorized for this repo's policies.
544    if lower.contains("403") || lower.contains("forbidden") {
545        return with_action(
546            raw,
547            "Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`.",
548        );
549    }
550    // 404 — the route itself wasn't found. Neither call that reaches this
551    // function (`list_repos`, `check_policies`) has a legitimate domain
552    // reason to 404 — a missing repo is already turned into its own message
553    // by `resolve_repo_by_name`'s `NotFound` variant before it gets here —
554    // so a 404 this far down most plausibly means this server build doesn't
555    // recognize the route at all: a CLI/server version mismatch (e.g. this
556    // CLI shipped ahead of a server still on the old routes).
557    if lower.contains("404") {
558        return with_action(
559            raw,
560            "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.",
561        );
562    }
563    // 5xx — server-side fault. Checked before the transport keywords below
564    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
565    if is_server_error(&lower) {
566        return with_action(
567            raw,
568            "TraceVault server returned an error. The team has likely been paged; retry shortly.",
569        );
570    }
571    // Transport-level failure with no HTTP status — DNS, refused, timeout.
572    // ("connect" also covers "connection refused"/"connection reset".)
573    if lower.contains("dns")
574        || lower.contains("connect")
575        || lower.contains("timed out")
576        || lower.contains("timeout")
577    {
578        return with_action(
579            raw,
580            "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
581        );
582    }
583    // Unrecognized — surface the raw error verbatim, no invented advice.
584    format!("Policy check could not run: {raw}.")
585}
586
587/// Format the standard "could not run" line with an actionable next step.
588fn with_action(raw: &str, action: &str) -> String {
589    format!("Policy check could not run: {raw}.\n  → {action}")
590}
591
592/// Heuristic for a 5xx server-side failure. Matches the textual status
593/// (`internal`, `server error`) and the concrete 5xx codes so a bare
594/// `503 Service Unavailable` — which carries neither phrase — is still
595/// recognized.
596fn is_server_error(lower: &str) -> bool {
597    lower.contains("internal")
598        || lower.contains("server error")
599        || ["500", "501", "502", "503", "504"]
600            .iter()
601            .any(|code| lower.contains(code))
602}
603
604#[cfg(test)]
605mod worktree_tests {
606    use super::select_worktree_sessions;
607    use std::path::PathBuf;
608
609    fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
610        let d = tmp.join(id);
611        std::fs::create_dir_all(&d).unwrap();
612        if let Some(o) = origin {
613            std::fs::write(d.join("origin"), o).unwrap();
614        }
615        d
616    }
617
618    #[test]
619    fn keeps_current_worktree_and_unmarked_excludes_other() {
620        let tmp = tempfile::tempdir().unwrap();
621        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
622        let other = seed(tmp.path(), "other", Some("/wt/there"));
623        let legacy = seed(tmp.path(), "legacy", None);
624
625        let (kept, fell_back) = select_worktree_sessions(
626            vec![mine.clone(), other.clone(), legacy.clone()],
627            "/wt/here",
628        );
629
630        assert!(!fell_back);
631        assert!(kept.contains(&mine), "current worktree session kept");
632        assert!(
633            kept.contains(&legacy),
634            "unmarked legacy session kept (conservative)"
635        );
636        assert!(
637            !kept.contains(&other),
638            "other worktree's marked session excluded"
639        );
640    }
641
642    #[test]
643    fn excludes_session_with_unreadable_marker() {
644        let tmp = tempfile::tempdir().unwrap();
645        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
646        // A present-but-unreadable marker: make `origin` a directory so
647        // read_to_string fails with a non-NotFound error.
648        let bad = tmp.path().join("bad");
649        std::fs::create_dir_all(bad.join("origin")).unwrap();
650
651        let (kept, fell_back) =
652            select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
653
654        assert!(!fell_back);
655        assert!(kept.contains(&mine), "current worktree session kept");
656        assert!(
657            !kept.contains(&bad),
658            "session with a present-but-unreadable marker must be excluded, not kept as legacy"
659        );
660    }
661
662    #[test]
663    fn falls_back_to_all_when_nothing_matches() {
664        let tmp = tempfile::tempdir().unwrap();
665        let a = seed(tmp.path(), "a", Some("/wt/there"));
666        let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
667
668        let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
669
670        assert!(fell_back, "must flag fallback when filter matches nothing");
671        assert_eq!(
672            kept.len(),
673            2,
674            "never under-enforce: send all rather than zero"
675        );
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    use super::connectivity_message;
682
683    #[test]
684    fn connectivity_message_suggests_login_on_401() {
685        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
686        assert!(
687            m.contains("tracevault login"),
688            "401 errors must surface the login hint; got: {m}"
689        );
690    }
691
692    #[test]
693    fn connectivity_message_suggests_login_on_unauthorized_text() {
694        let m = connectivity_message("Server returned: unauthorized request");
695        assert!(m.contains("tracevault login"));
696    }
697
698    #[test]
699    fn connectivity_message_suggests_network_check_on_dns_error() {
700        let m = connectivity_message("error sending request for url: dns error");
701        assert!(
702            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
703            "DNS errors must surface a network hint; got: {m}"
704        );
705    }
706
707    #[test]
708    fn connectivity_message_suggests_network_check_on_connection_refused() {
709        let m = connectivity_message("connection refused");
710        assert!(m.to_lowercase().contains("network"));
711    }
712
713    #[test]
714    fn connectivity_message_falls_back_when_unrecognized() {
715        let m = connectivity_message("some weird new error shape we have not seen before");
716        // No suggestion — but the raw error must still be in the message so
717        // the user can debug.
718        assert!(m.contains("some weird new error shape"));
719        assert!(!m.contains("→")); // no action arrow
720    }
721
722    #[test]
723    fn connectivity_message_does_not_collide_on_403() {
724        let m = connectivity_message("403 Forbidden");
725        // 403 should point at token authorization, NOT a re-login.
726        assert!(
727            m.to_lowercase().contains("authorized"),
728            "403 should mention authorization; got: {m}"
729        );
730    }
731
732    #[test]
733    fn connectivity_message_flags_404_as_version_mismatch() {
734        // Simulates an old-server-404 skew: a route the CLI expects to exist
735        // (e.g. `Failed to list repos (404 Not Found)`) doesn't exist yet on
736        // this server build. Must hint at a version mismatch, not just
737        // report a bare 404 with no next step.
738        let m = connectivity_message("Failed to list repos (404 Not Found): ");
739        assert!(
740            m.to_lowercase().contains("newer than the server")
741                || m.to_lowercase().contains("version mismatch"),
742            "404 should hint at a possible CLI/server version mismatch; got: {m}"
743        );
744    }
745
746    #[test]
747    fn connectivity_message_flags_500_as_server_error() {
748        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
749        assert!(
750            m.to_lowercase().contains("server returned an error"),
751            "500 should surface the server-error hint; got: {m}"
752        );
753    }
754
755    #[test]
756    fn connectivity_message_flags_503_without_internal_text() {
757        // `503 Service Unavailable` carries neither "internal" nor
758        // "server error" — the bare code must still be recognized.
759        let m = connectivity_message("Server returned 503 Service Unavailable: ");
760        assert!(
761            m.to_lowercase().contains("server returned an error"),
762            "503 should surface the server-error hint; got: {m}"
763        );
764    }
765
766    #[test]
767    fn connectivity_message_treats_504_as_server_not_network() {
768        // A gateway timeout is a server-side fault even though it contains
769        // the word "timeout"; it must not be misreported as a local network
770        // problem.
771        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
772        assert!(
773            m.to_lowercase().contains("server returned an error"),
774            "504 should be treated as a server error; got: {m}"
775        );
776    }
777}
778
779#[cfg(test)]
780mod push_ref_tests {
781    use super::{is_zero_sha, parse_push_refs};
782
783    #[test]
784    fn parses_a_single_ref_line() {
785        let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456\n");
786        assert_eq!(refs.len(), 1);
787        assert_eq!(refs[0].local_sha, "abc123");
788        assert_eq!(refs[0].remote_sha, "def456");
789    }
790
791    #[test]
792    fn parses_multiple_refs() {
793        let refs = parse_push_refs(
794            "refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444\n",
795        );
796        assert_eq!(refs.len(), 2);
797    }
798
799    #[test]
800    fn parses_a_single_ref_line_without_trailing_newline() {
801        // This is the exact shape the generated pre-push hook produces: it
802        // captures git's stdin with `$(cat)` (which strips trailing
803        // newlines) and replays it with `printf '%s'` (which adds none
804        // back), so the real input to `check` has no trailing newline on
805        // its final line. Here that unterminated line is the *only* line.
806        // Do not delete this as a duplicate of `parses_a_single_ref_line`;
807        // it pins a different, easy-to-break input shape.
808        let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456");
809        assert_eq!(refs.len(), 1);
810        assert_eq!(refs[0].local_sha, "abc123");
811        assert_eq!(refs[0].remote_sha, "def456");
812    }
813
814    #[test]
815    fn parses_multiple_refs_when_last_line_has_no_trailing_newline() {
816        // Same hook-stdin shape as above, but with two refs: only the final
817        // line is unterminated, matching a real multi-ref push through
818        // `$(cat)` + `printf '%s'`.
819        let refs =
820            parse_push_refs("refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444");
821        assert_eq!(refs.len(), 2);
822        assert_eq!(refs[0].local_sha, "111");
823        assert_eq!(refs[1].local_sha, "333");
824    }
825
826    #[test]
827    fn skips_branch_deletions() {
828        let zeros = "0".repeat(40);
829        let line = format!("(delete) {zeros} refs/heads/gone abc123\n");
830        assert!(parse_push_refs(&line).is_empty());
831    }
832
833    #[test]
834    fn keeps_new_branches_whose_remote_sha_is_zero() {
835        let zeros = "0".repeat(40);
836        let line = format!("refs/heads/new abc123 refs/heads/new {zeros}\n");
837        let refs = parse_push_refs(&line);
838        assert_eq!(refs.len(), 1);
839        assert!(is_zero_sha(&refs[0].remote_sha));
840    }
841
842    #[test]
843    fn skips_malformed_lines_without_panicking() {
844        assert!(parse_push_refs("garbage\n\nalso garbage here\n").is_empty());
845    }
846
847    #[test]
848    fn zero_sha_detection_handles_sha256_length() {
849        assert!(is_zero_sha(&"0".repeat(64)));
850        assert!(!is_zero_sha("0000000000000000000000000000000000000001"));
851        assert!(!is_zero_sha(""));
852    }
853}
854
855/// Real-git coverage for the functions `resolve_changed_paths` composes:
856/// `changed_files_for_refs` (the two-dot range and the empty-tree base for
857/// new branches) and `git_empty_tree_sha`.
858///
859/// `resolve_changed_paths` itself is deliberately NOT driven directly here.
860/// It reads `std::io::stdin()` when stdin is not a terminal, and `cargo
861/// test` runs every test in one process sharing that real, global stdin —
862/// there is no per-test way to inject or close it without invasive,
863/// process-wide fd surgery, and a test that consumes it would make unrelated
864/// tests in the same binary flaky. Testing the two git-backed branches it
865/// falls back to (below) is the safe substitute; the stdin-parsing branch
866/// itself is already covered without touching stdin by `push_ref_tests`
867/// (`parse_push_refs`) plus `two_dot_range_returns_only_the_newer_commits_files`
868/// and `new_branch_zero_remote_sha_resolves_via_empty_tree` below, which
869/// together exercise every step `resolve_changed_paths` performs once it has
870/// a parsed `Vec<PushRef>` in hand. The timeout mechanism that bounds the
871/// stdin read (`read_with_timeout`) is factored generically over the reading
872/// closure precisely so it can be tested without touching stdin at all —
873/// see `read_with_timeout_tests` below.
874#[cfg(test)]
875mod git_diff_tests {
876    use super::{changed_files_for_refs, git_empty_tree_sha, PushRef};
877    use crate::test_helpers::init_git_repo;
878    use std::path::Path;
879    use std::process::Command;
880
881    /// Write `name` with `content` in `dir`, stage it, and commit it,
882    /// returning the new commit's sha. Assumes `init_git_repo` already
883    /// configured a local `user.name`/`user.email` in `dir`.
884    fn commit_file(dir: &Path, name: &str, content: &str) -> String {
885        std::fs::write(dir.join(name), content).unwrap();
886        let ok = Command::new("git")
887            .args(["-C", &dir.to_string_lossy(), "add", name])
888            .status()
889            .expect("git add failed")
890            .success();
891        assert!(ok, "git add must succeed");
892        let ok = Command::new("git")
893            .args([
894                "-C",
895                &dir.to_string_lossy(),
896                "commit",
897                "-m",
898                &format!("add {name}"),
899            ])
900            .status()
901            .expect("git commit failed")
902            .success();
903        assert!(ok, "git commit must succeed");
904        head_sha(dir)
905    }
906
907    fn head_sha(dir: &Path) -> String {
908        let out = Command::new("git")
909            .args(["-C", &dir.to_string_lossy(), "rev-parse", "HEAD"])
910            .output()
911            .expect("git rev-parse failed");
912        assert!(out.status.success());
913        String::from_utf8_lossy(&out.stdout).trim().to_string()
914    }
915
916    #[test]
917    fn two_dot_range_returns_only_the_newer_commits_files() {
918        let tmp = tempfile::tempdir().unwrap();
919        init_git_repo(tmp.path()); // empty "init" commit
920
921        let sha1 = commit_file(tmp.path(), "a.txt", "a");
922        let sha2 = commit_file(tmp.path(), "b.txt", "b");
923
924        let refs = vec![PushRef {
925            local_sha: sha2,
926            remote_sha: sha1,
927        }];
928        let files = changed_files_for_refs(tmp.path(), &refs);
929
930        // Must be exactly the file the newer commit touched. A single-arg
931        // `git diff --name-only <sha>` would instead diff against the
932        // working tree and silently pull in every tracked file (here, also
933        // "a.txt") — this is the mistake this test exists to catch.
934        assert_eq!(files, vec!["b.txt".to_string()]);
935    }
936
937    #[test]
938    fn new_branch_zero_remote_sha_resolves_via_empty_tree() {
939        let tmp = tempfile::tempdir().unwrap();
940        init_git_repo(tmp.path());
941
942        commit_file(tmp.path(), "a.txt", "a");
943        let sha2 = commit_file(tmp.path(), "b.txt", "b");
944
945        let refs = vec![PushRef {
946            local_sha: sha2,
947            remote_sha: "0".repeat(40),
948        }];
949        let mut files = changed_files_for_refs(tmp.path(), &refs);
950        files.sort();
951
952        // A brand-new branch has no remote sha to diff from; the base must
953        // resolve to the empty tree, so the full branch history shows up.
954        assert_eq!(files, vec!["a.txt".to_string(), "b.txt".to_string()]);
955    }
956
957    #[test]
958    fn identical_shas_yield_an_empty_file_list() {
959        let tmp = tempfile::tempdir().unwrap();
960        init_git_repo(tmp.path());
961        let sha = commit_file(tmp.path(), "a.txt", "a");
962
963        let refs = vec![PushRef {
964            local_sha: sha.clone(),
965            remote_sha: sha,
966        }];
967        let files = changed_files_for_refs(tmp.path(), &refs);
968
969        assert!(
970            files.is_empty(),
971            "a no-op push (same local and remote sha) must yield no files, got {files:?}"
972        );
973    }
974
975    #[test]
976    fn non_ascii_path_is_returned_raw_not_octal_quoted() {
977        let tmp = tempfile::tempdir().unwrap();
978        init_git_repo(tmp.path());
979        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
980
981        let sha1 = commit_file(tmp.path(), "src/café.rs", "one");
982        let sha2 = commit_file(tmp.path(), "src/café.rs", "two");
983
984        let refs = vec![PushRef {
985            local_sha: sha2,
986            remote_sha: sha1,
987        }];
988        let files = changed_files_for_refs(tmp.path(), &refs);
989
990        // Without `-z`, git's default `core.quotePath` behaviour renders this
991        // as the 20-character literal string `"src/caf\303\251.rs"`
992        // (surrounding quotes included) instead of the real path — see the
993        // fix's doc comment. That string can never match the hook-recorded
994        // path, so the file is silently pruned from `changed_paths`.
995        assert_eq!(
996            files,
997            vec!["src/café.rs".to_string()],
998            "must be the raw UTF-8 path, not git's octal-quoted rendering; got {files:?}"
999        );
1000    }
1001
1002    #[test]
1003    fn path_containing_a_space_is_returned_intact() {
1004        let tmp = tempfile::tempdir().unwrap();
1005        init_git_repo(tmp.path());
1006        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1007
1008        let sha1 = commit_file(tmp.path(), "src/has space.rs", "one");
1009        let sha2 = commit_file(tmp.path(), "src/has space.rs", "two");
1010
1011        let refs = vec![PushRef {
1012            local_sha: sha2,
1013            remote_sha: sha1,
1014        }];
1015        let files = changed_files_for_refs(tmp.path(), &refs);
1016
1017        assert_eq!(files, vec!["src/has space.rs".to_string()]);
1018    }
1019
1020    #[test]
1021    fn rename_reports_both_source_and_destination() {
1022        let tmp = tempfile::tempdir().unwrap();
1023        init_git_repo(tmp.path());
1024        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1025        let sha1 = commit_file(tmp.path(), "src/plain.rs", "identical content");
1026
1027        let ok = Command::new("git")
1028            .args([
1029                "-C",
1030                &tmp.path().to_string_lossy(),
1031                "mv",
1032                "src/plain.rs",
1033                "src/renamed.rs",
1034            ])
1035            .status()
1036            .expect("git mv failed")
1037            .success();
1038        assert!(ok, "git mv must succeed");
1039        let ok = Command::new("git")
1040            .args([
1041                "-C",
1042                &tmp.path().to_string_lossy(),
1043                "commit",
1044                "-m",
1045                "rename plain.rs to renamed.rs",
1046            ])
1047            .status()
1048            .expect("git commit failed")
1049            .success();
1050        assert!(ok, "git commit must succeed");
1051        let sha2 = head_sha(tmp.path());
1052
1053        let refs = vec![PushRef {
1054            local_sha: sha2,
1055            remote_sha: sha1,
1056        }];
1057        let mut files = changed_files_for_refs(tmp.path(), &refs);
1058        files.sort();
1059
1060        // Git's rename detection is on by default, so a plain `git diff
1061        // --name-only` here would report only `src/renamed.rs`, hiding the
1062        // fact that `src/plain.rs` ever existed in this diff. If
1063        // `src/plain.rs` were a protected path, that silence is exactly what
1064        // lets an agent rename it away undetected.
1065        assert_eq!(
1066            files,
1067            vec!["src/plain.rs".to_string(), "src/renamed.rs".to_string()],
1068            "a rename must surface BOTH the source and destination path; got {files:?}"
1069        );
1070    }
1071
1072    #[test]
1073    fn git_empty_tree_sha_is_the_well_known_constant() {
1074        let tmp = tempfile::tempdir().unwrap();
1075        init_git_repo(tmp.path());
1076
1077        let empty_tree =
1078            git_empty_tree_sha(tmp.path()).expect("git hash-object must resolve the empty tree");
1079        // The well-known empty-tree object id for sha1 repositories (git's
1080        // default) — asserted against the literal, not just "non-empty", so
1081        // a regression that resolves some other tree can't slip through.
1082        assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1083    }
1084
1085    /// Not a call into `resolve_changed_paths` (see the module doc comment
1086    /// above for why) — this drives the exact git invocation its
1087    /// `@{{upstream}}` fallback branch makes, in a repo with no upstream
1088    /// configured, confirming that branch fails cleanly (non-zero exit) and
1089    /// so `resolve_changed_paths` would correctly return `None` rather than
1090    /// erroring or panicking.
1091    #[test]
1092    fn upstream_fallback_diff_fails_cleanly_with_no_upstream_configured() {
1093        let tmp = tempfile::tempdir().unwrap();
1094        init_git_repo(tmp.path());
1095        commit_file(tmp.path(), "a.txt", "a");
1096
1097        let out = Command::new("git")
1098            .args([
1099                "diff",
1100                "--name-only",
1101                "-z",
1102                "--no-renames",
1103                "@{upstream}..HEAD",
1104            ])
1105            .current_dir(tmp.path())
1106            .output()
1107            .expect("git diff must run");
1108
1109        assert!(
1110            !out.status.success(),
1111            "no upstream is configured, so this must fail rather than \
1112             silently resolve to something else"
1113        );
1114    }
1115
1116    /// Companion to the test above: with an upstream configured but no diff
1117    /// between it and `HEAD`, the same invocation must succeed with empty
1118    /// output — the shape `resolve_changed_paths` treats as `None`.
1119    #[test]
1120    fn upstream_fallback_diff_is_empty_when_upstream_matches_head() {
1121        let tmp = tempfile::tempdir().unwrap();
1122        init_git_repo(tmp.path());
1123        commit_file(tmp.path(), "a.txt", "a");
1124
1125        let branch_out = Command::new("git")
1126            .args(["symbolic-ref", "--short", "HEAD"])
1127            .current_dir(tmp.path())
1128            .output()
1129            .expect("git symbolic-ref must run");
1130        assert!(branch_out.status.success());
1131        let branch = String::from_utf8_lossy(&branch_out.stdout)
1132            .trim()
1133            .to_string();
1134
1135        // Track a same-commit local branch as upstream, so `@{upstream}`
1136        // resolves but the diff against it is empty — without needing an
1137        // actual remote.
1138        for args in [
1139            vec!["branch", "tracking", &branch],
1140            vec!["branch", "--set-upstream-to=tracking", &branch],
1141        ] {
1142            let ok = Command::new("git")
1143                .args(&args)
1144                .current_dir(tmp.path())
1145                .status()
1146                .expect("git command must run")
1147                .success();
1148            assert!(ok, "git {args:?} must succeed");
1149        }
1150
1151        let out = Command::new("git")
1152            .args([
1153                "diff",
1154                "--name-only",
1155                "-z",
1156                "--no-renames",
1157                "@{upstream}..HEAD",
1158            ])
1159            .current_dir(tmp.path())
1160            .output()
1161            .expect("git diff must run");
1162
1163        assert!(out.status.success());
1164        assert!(
1165            out.stdout.is_empty(),
1166            "identical upstream/HEAD must diff to no files"
1167        );
1168    }
1169}
1170
1171/// Coverage for the generic timeout mechanism behind `read_stdin_with_timeout`.
1172///
1173/// These drive `read_with_timeout` directly with an injected closure instead
1174/// of the real `stdin()` — see the doc comment on `git_diff_tests` above for
1175/// why touching the process's real, global stdin from a test is unsafe here.
1176/// `read_stdin_with_timeout` itself is left thin and untested; once the
1177/// generic helper is proven to time out and to pass through a prompt result,
1178/// there is nothing stdin-specific left to verify.
1179#[cfg(test)]
1180mod read_with_timeout_tests {
1181    use super::read_with_timeout;
1182    use std::time::Duration;
1183
1184    #[test]
1185    fn returns_the_value_when_it_arrives_before_the_deadline() {
1186        let got = read_with_timeout(|| Some("hi".to_string()), Duration::from_secs(1));
1187        assert_eq!(got, Some("hi".to_string()));
1188    }
1189
1190    #[test]
1191    fn returns_none_when_the_closure_itself_returns_none() {
1192        let got = read_with_timeout(|| None, Duration::from_secs(1));
1193        assert_eq!(got, None);
1194    }
1195
1196    #[test]
1197    fn times_out_instead_of_hanging_on_a_closure_that_never_returns() {
1198        // The stalled-pipe case in miniature: the closure blocks well past
1199        // the deadline (in the real bug, forever). Margins are kept wide so
1200        // this cannot flake on a loaded CI machine — a 50ms timeout that
1201        // must return within 1s, against a closure that sleeps for 10s.
1202        let start = std::time::Instant::now();
1203        let got = read_with_timeout(
1204            || {
1205                std::thread::sleep(Duration::from_secs(10));
1206                Some("too late".to_string())
1207            },
1208            Duration::from_millis(50),
1209        );
1210        assert_eq!(got, None, "must give up rather than wait for the closure");
1211        assert!(
1212            start.elapsed() < Duration::from_secs(1),
1213            "must return promptly on timeout, not block on the stalled closure; took {:?}",
1214            start.elapsed()
1215        );
1216    }
1217}