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            // Marked: keep only if mine — the latest event ran here, or an
343            // anchored session lists this worktree as one it ran in (VIS-1257).
344            Ok(s) => s.trim() == worktree_top || crate::session_state::ran_in(dir, worktree_top),
345            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
346            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
347            // Marker present but unreadable (permissions/IO): we can't prove it's
348            // ours, so exclude it rather than risk cross-worktree interference.
349            // The safety rail below still prevents under-enforcement if this
350            // drops everything.
351            Err(_) => false,
352        }
353    };
354    let filtered: Vec<_> = session_dirs
355        .iter()
356        .filter(|d| belongs(d))
357        .cloned()
358        .collect();
359    if filtered.is_empty() && !session_dirs.is_empty() {
360        (session_dirs, true)
361    } else {
362        (filtered, false)
363    }
364}
365
366/// [`select_worktree_sessions`] over the local dirs, plus the `external` ones
367/// (already known to belong to this worktree). The fall-back to every local
368/// session applies only when neither matched: an external session is a match.
369fn select_with_external(
370    local: Vec<std::path::PathBuf>,
371    external: Vec<std::path::PathBuf>,
372    worktree_top: &str,
373) -> Vec<std::path::PathBuf> {
374    let (mut selected, fell_back) = select_worktree_sessions(local, worktree_top);
375    if fell_back {
376        if external.is_empty() {
377            eprintln!(
378                "Warning: no unpushed session matched this worktree by origin marker — \
379                 checking all unpushed sessions to avoid skipping policy enforcement."
380            );
381        } else {
382            selected.clear();
383        }
384    }
385    selected.extend(external);
386    selected
387}
388
389/// Add a session dir that lives outside `sessions_dir` to the sessions a
390/// push is checked against, unless it is gone, pushed, or already there.
391///
392/// A session keeps its dir in the `.tracevault/` it STARTED in (VIS-1257), so
393/// one started in an umbrella directory that then works in this checkout has
394/// no dir here. A dir inside `sessions_dir` was already considered by the
395/// worktree selection, and its verdict stands.
396fn add_external_session(
397    selected: &mut Vec<std::path::PathBuf>,
398    sessions_dir: &Path,
399    dir: std::path::PathBuf,
400) {
401    if dir.parent() == Some(sessions_dir) || !dir.is_dir() || dir.join(".pushed").exists() {
402        return;
403    }
404    if !selected.contains(&dir) {
405        selected.push(dir);
406    }
407}
408
409/// The server repo a push is checked under.
410#[derive(Debug, Clone, PartialEq, Eq)]
411struct PushedRepo {
412    id: uuid::Uuid,
413    /// The codebase it belongs to, when resolved through the origin remote.
414    remote_id: Option<uuid::Uuid>,
415}
416
417/// Resolve the repo being pushed — the policy authority for this push.
418///
419/// First through the checkout's origin remote, exactly as
420/// `tracevault repo switch <path>` binds a session (VIS-601): a session bound
421/// to this checkout then streams to the very repo it is checked under, so the
422/// server finds its verification window and tool stats. Then, for a checkout
423/// whose remote the server does not know (or that has none), by the primary
424/// checkout's directory name — the only resolution `check` had before.
425///
426/// Never the sessions' own bindings: a `repo switch` to another repo, or a
427/// machine-wide user default, must not decide which repo's policies a push
428/// to THIS checkout is held to.
429async fn resolve_pushed_repo(
430    client: &ApiClient,
431    project_root: &Path,
432) -> Result<PushedRepo, Box<dyn std::error::Error>> {
433    match crate::resolution::resolve_path_to_binding(project_root, client).await {
434        Ok(Some(b)) => {
435            if let Ok(id) = b.repo_id.parse() {
436                return Ok(PushedRepo {
437                    id,
438                    remote_id: b.remote_id,
439                });
440            }
441        }
442        Ok(None) => {}
443        Err(e) => return Err(connectivity_message(&e.to_string()).into()),
444    }
445    match resolve_repo_by_name(client, project_root).await {
446        Ok(r) => Ok(PushedRepo {
447            id: r.id,
448            remote_id: None,
449        }),
450        Err(ResolveRepoByNameError::ListFailed(e)) => {
451            Err(connectivity_message(&e.to_string()).into())
452        }
453        Err(ResolveRepoByNameError::NotFound { repo_name }) => Err(format!(
454            "Repo '{repo_name}' not found on server. Run `tracevault sync` first."
455        )
456        .into()),
457    }
458}
459
460/// A warning for a session whose events went to a different repo than the
461/// one this push is checked under, or `None` when they agree (or the session
462/// has no repo binding at all).
463///
464/// The session is still checked under the pushed repo — enforcement fails
465/// closed — but the server looks verification-phase data up by exact repo
466/// id, so that session's window and tool stats will not be found there.
467///
468/// Names the repos, not the session: the session id is not needed to act on
469/// it (the fix is a `repo switch` in whichever session is bound elsewhere),
470/// and CodeQL treats session ids as sensitive in log output.
471fn streamed_elsewhere_warning(
472    streamed_to: Option<&crate::session_state::RepoBinding>,
473    pushed: &PushedRepo,
474) -> Option<String> {
475    let b = streamed_to?;
476    if b.repo_id == pushed.id.to_string() {
477        return None;
478    }
479    let scope = match (b.remote_id, pushed.remote_id) {
480        (Some(a), Some(p)) if a == p => "another repo of this codebase",
481        (Some(_), Some(_)) => "a different codebase",
482        _ => "a different repo",
483    };
484    Some(format!(
485        "Warning: an unpushed session streamed its events to {scope} ({}), not to the repo \
486         this push is checked under ({}). Its verification-phase data will not be found; \
487         run `tracevault repo switch <this checkout>` in that session.",
488        b.repo_id, pushed.id
489    ))
490}
491
492/// Check unpushed sessions against server policies.
493///
494/// `project_root` — the git-resolved PRIMARY worktree root (from
495///   `paths::resolve_project_root`). Used to load config/credentials, locate
496///   `.tracevault/sessions/`, and resolve the server-registered repo (by its
497///   origin remote, else by the primary checkout's basename; a sibling
498///   worktree's own directory basename would not match the registered repo).
499/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
500///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
501///   pushed from the invoking worktree, not the primary's unrelated HEAD.
502pub async fn check_policies(
503    project_root: &Path,
504    cwd: &Path,
505) -> Result<(), Box<dyn std::error::Error>> {
506    let (server_url, credential) = resolve_credentials(project_root)?;
507
508    let server_url = server_url
509        .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
510
511    if credential.is_none() {
512        return Err(
513            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
514                .into(),
515        );
516    }
517
518    let client = ApiClient::with_credential(&server_url, credential);
519
520    // Resolve the pushed repo.
521    //
522    // Connectivity errors here (auth expired, server down, network
523    // unreachable) propagate so the pre-push hook exits non-zero — if a
524    // repo is opted into TraceVault, every push must be evaluated, full
525    // stop. Letting pushes slip when TV is unreachable would defeat the
526    // point of enforcement. We attach an actionable next step to each
527    // error so the user (or agent) knows the recovery command without
528    // guessing — see `connectivity_message` below.
529    let repo = resolve_pushed_repo(&client, project_root).await?;
530
531    // Collect unpushed session dirs from the shared primary .tracevault/.
532    let sessions_dir = project_root.join(".tracevault").join("sessions");
533    let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
534    if sessions_dir.exists() {
535        for entry in fs::read_dir(&sessions_dir)? {
536            let entry = entry?;
537            if !entry.file_type()?.is_dir() {
538                continue;
539            }
540            let session_dir = entry.path();
541            if session_dir.join(".pushed").exists() {
542                continue;
543            }
544            unpushed_dirs.push(session_dir);
545        }
546    }
547
548    // Filter to the worktree that is actually pushing, so a push is not
549    // evaluated against sessions belonging to other worktrees.
550    let worktree_top = crate::paths::worktree_toplevel(cwd);
551    //
552    // Sessions that keep their dir in the `.tracevault/` they started in (an
553    // umbrella dir, VIS-1257) and worked in this worktree, plus the session
554    // running this push, wherever its dir is, belong to it too — found
555    // first, so they count before falling back to every local session.
556    let invoking = crate::session_state::env_session_id()
557        .filter(|id| crate::session_state::is_safe_session_id(id))
558        .map(|id| crate::session_state::session_dir(project_root, &id));
559    let mut external = Vec::new();
560    for dir in crate::session_state::anchored_session_dirs(&sessions_dir, &worktree_top)
561        .into_iter()
562        .chain(invoking)
563    {
564        add_external_session(&mut external, &sessions_dir, dir);
565    }
566    let selected_dirs = select_with_external(unpushed_dirs, external, &worktree_top);
567
568    // Where each session's events actually went, resolved as the stream hook
569    // resolves it — only to warn when that is not the pushed repo. A
570    // malformed config.toml costs the bound tier here, nothing more: the
571    // check never needed the config before.
572    let bound = match crate::config::TracevaultConfig::try_load(project_root) {
573        Ok(cfg) => cfg
574            .as_ref()
575            .and_then(crate::resolution::binding_from_config),
576        Err(e) => {
577            eprintln!("Warning: ignoring malformed .tracevault/config.toml: {e}");
578            None
579        }
580    };
581    let user_default = crate::user_default::load();
582
583    let mut sessions = Vec::new();
584    for session_dir in &selected_dirs {
585        if let Some(data) = collect_session_data(session_dir) {
586            let state = crate::session_state::load(&data.session_id);
587            let streamed_to = crate::resolution::recorded_session_binding(
588                session_dir,
589                &worktree_top,
590                &state,
591                bound.clone(),
592                user_default.clone(),
593            );
594            if let Some(w) = streamed_elsewhere_warning(streamed_to.as_ref(), &repo) {
595                eprintln!("{w}");
596            }
597            sessions.push(data);
598        }
599    }
600
601    if sessions.is_empty() {
602        println!("No unpushed sessions to check.");
603        return Ok(());
604    }
605
606    println!("Checking {} session(s) against policies...", sessions.len());
607
608    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
609    // the commit being pushed lives on the current worktree's branch.
610    let commit_sha = git_head_sha(cwd);
611    let changed_paths = resolve_changed_paths(cwd);
612    let result = client
613        .check_policies(
614            &repo.id,
615            CheckPoliciesRequest {
616                sessions,
617                commit_sha,
618                changed_paths,
619            },
620        )
621        .await
622        .map_err(|e| connectivity_message(&e.to_string()))?;
623
624    // Print results
625    for r in &result.results {
626        let icon = match r.result.as_str() {
627            "pass" => "\x1b[32m✓\x1b[0m",                             // green
628            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
629            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
630            _ => " ",
631        };
632        println!(
633            "  {} [{}] {} — {}",
634            icon, r.severity, r.rule_name, r.details
635        );
636    }
637
638    if result.blocked {
639        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
640        std::process::exit(1);
641    } else if result.passed {
642        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
643    } else {
644        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
645    }
646
647    Ok(())
648}
649
650/// Wrap an opaque API-client error string with the most useful next step.
651/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
652/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
653/// the common shapes and surface a one-line action. A 404 gets its own
654/// version-mismatch hint rather than the generic fallback, since the calls
655/// that route through here have no legitimate domain reason to 404 — see
656/// the 404 branch below.
657fn connectivity_message(raw: &str) -> String {
658    let lower = raw.to_ascii_lowercase();
659
660    // 401 — token rejected. An expired session is the most common cause of
661    // a surprise blocked push, so point straight at the refresh command.
662    if lower.contains("401") || lower.contains("unauthorized") {
663        return with_action(
664            raw,
665            "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
666        );
667    }
668    // 403 — authenticated but not allowed. Re-login won't help; the token
669    // itself is not authorized for this repo's policies.
670    if lower.contains("403") || lower.contains("forbidden") {
671        return with_action(
672            raw,
673            "Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`.",
674        );
675    }
676    // 404 — the route itself wasn't found. Neither call that reaches this
677    // function (`list_repos`, `check_policies`) has a legitimate domain
678    // reason to 404 — a missing repo is already turned into its own message
679    // by `resolve_repo_by_name`'s `NotFound` variant before it gets here —
680    // so a 404 this far down most plausibly means this server build doesn't
681    // recognize the route at all: a CLI/server version mismatch (e.g. this
682    // CLI shipped ahead of a server still on the old routes).
683    if lower.contains("404") {
684        return with_action(
685            raw,
686            "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.",
687        );
688    }
689    // 5xx — server-side fault. Checked before the transport keywords below
690    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
691    if is_server_error(&lower) {
692        return with_action(
693            raw,
694            "TraceVault server returned an error. The team has likely been paged; retry shortly.",
695        );
696    }
697    // Transport-level failure with no HTTP status — DNS, refused, timeout.
698    // ("connect" also covers "connection refused"/"connection reset".)
699    if lower.contains("dns")
700        || lower.contains("connect")
701        || lower.contains("timed out")
702        || lower.contains("timeout")
703    {
704        return with_action(
705            raw,
706            "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
707        );
708    }
709    // Unrecognized — surface the raw error verbatim, no invented advice.
710    format!("Policy check could not run: {raw}.")
711}
712
713/// Format the standard "could not run" line with an actionable next step.
714fn with_action(raw: &str, action: &str) -> String {
715    format!("Policy check could not run: {raw}.\n  → {action}")
716}
717
718/// Heuristic for a 5xx server-side failure. Matches the textual status
719/// (`internal`, `server error`) and the concrete 5xx codes so a bare
720/// `503 Service Unavailable` — which carries neither phrase — is still
721/// recognized.
722fn is_server_error(lower: &str) -> bool {
723    lower.contains("internal")
724        || lower.contains("server error")
725        || ["500", "501", "502", "503", "504"]
726            .iter()
727            .any(|code| lower.contains(code))
728}
729
730#[cfg(test)]
731mod worktree_tests {
732    use super::{add_external_session, select_with_external, select_worktree_sessions};
733
734    #[test]
735    fn an_external_match_stops_the_fall_back_to_every_local_session() {
736        let tmp = tempfile::tempdir().unwrap();
737        let other = seed(tmp.path(), "other", Some("/wt/b"));
738        let ext = tmp.path().join("umbrella-session");
739        assert_eq!(
740            select_with_external(vec![other.clone()], vec![ext.clone()], "/wt/a"),
741            vec![ext.clone()]
742        );
743        assert_eq!(
744            select_with_external(vec![other.clone()], vec![], "/wt/a"),
745            vec![other.clone()],
746            "no match at all still checks everything"
747        );
748        let mine = seed(tmp.path(), "mine", Some("/wt/a"));
749        assert_eq!(
750            select_with_external(vec![mine.clone(), other], vec![ext.clone()], "/wt/a"),
751            vec![mine, ext]
752        );
753    }
754    use std::path::PathBuf;
755
756    /// A session kept here that ran here and moved to another repo: its
757    /// `origin` names the other repo, its worktree list names this one.
758    #[test]
759    fn keeps_a_session_that_ran_here_before_moving_on() {
760        let tmp = tempfile::tempdir().unwrap();
761        let moved = seed(tmp.path(), "moved", Some("/wt/b"));
762        crate::session_state::record_worktree(&moved, "/wt/a").unwrap();
763        crate::session_state::record_worktree(&moved, "/wt/b").unwrap();
764        let mine = seed(tmp.path(), "mine", Some("/wt/a"));
765        let other = seed(tmp.path(), "other", Some("/wt/b"));
766        let (mut kept, fell_back) =
767            select_worktree_sessions(vec![moved.clone(), mine.clone(), other], "/wt/a");
768        kept.sort();
769        assert_eq!(kept, vec![mine, moved]);
770        assert!(!fell_back);
771    }
772
773    #[test]
774    fn adds_an_external_session_only_when_it_lives_elsewhere() {
775        let tmp = tempfile::tempdir().unwrap();
776        let here = tmp.path().join("repo/.tracevault/sessions");
777        let local = seed(&here, "local", Some("/wt/b"));
778        let elsewhere = seed(
779            &tmp.path().join("umbrella/.tracevault/sessions"),
780            "s",
781            Some("/u"),
782        );
783        let pushed = seed(&tmp.path().join("umbrella/.tracevault/sessions"), "p", None);
784        std::fs::write(pushed.join(".pushed"), "").unwrap();
785
786        let mut selected = vec![];
787        add_external_session(&mut selected, &here, local);
788        assert!(
789            selected.is_empty(),
790            "a local dir is the worktree filter's call"
791        );
792
793        add_external_session(&mut selected, &here, elsewhere.clone());
794        add_external_session(&mut selected, &here, elsewhere.clone());
795        add_external_session(&mut selected, &here, tmp.path().join("missing"));
796        add_external_session(&mut selected, &here, pushed);
797        assert_eq!(selected, vec![elsewhere]);
798    }
799
800    fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
801        let d = tmp.join(id);
802        std::fs::create_dir_all(&d).unwrap();
803        if let Some(o) = origin {
804            std::fs::write(d.join("origin"), o).unwrap();
805        }
806        d
807    }
808
809    #[test]
810    fn keeps_current_worktree_and_unmarked_excludes_other() {
811        let tmp = tempfile::tempdir().unwrap();
812        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
813        let other = seed(tmp.path(), "other", Some("/wt/there"));
814        let legacy = seed(tmp.path(), "legacy", None);
815
816        let (kept, fell_back) = select_worktree_sessions(
817            vec![mine.clone(), other.clone(), legacy.clone()],
818            "/wt/here",
819        );
820
821        assert!(!fell_back);
822        assert!(kept.contains(&mine), "current worktree session kept");
823        assert!(
824            kept.contains(&legacy),
825            "unmarked legacy session kept (conservative)"
826        );
827        assert!(
828            !kept.contains(&other),
829            "other worktree's marked session excluded"
830        );
831    }
832
833    #[test]
834    fn excludes_session_with_unreadable_marker() {
835        let tmp = tempfile::tempdir().unwrap();
836        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
837        // A present-but-unreadable marker: make `origin` a directory so
838        // read_to_string fails with a non-NotFound error.
839        let bad = tmp.path().join("bad");
840        std::fs::create_dir_all(bad.join("origin")).unwrap();
841
842        let (kept, fell_back) =
843            select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
844
845        assert!(!fell_back);
846        assert!(kept.contains(&mine), "current worktree session kept");
847        assert!(
848            !kept.contains(&bad),
849            "session with a present-but-unreadable marker must be excluded, not kept as legacy"
850        );
851    }
852
853    #[test]
854    fn falls_back_to_all_when_nothing_matches() {
855        let tmp = tempfile::tempdir().unwrap();
856        let a = seed(tmp.path(), "a", Some("/wt/there"));
857        let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
858
859        let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
860
861        assert!(fell_back, "must flag fallback when filter matches nothing");
862        assert_eq!(
863            kept.len(),
864            2,
865            "never under-enforce: send all rather than zero"
866        );
867    }
868}
869
870#[cfg(test)]
871mod tests {
872    use super::{collect_session_data, connectivity_message};
873
874    /// The stream hook's `metadata.json` is what lets `check` see a streaming
875    /// session's tool calls; without it every session sent `tool_calls: None`
876    /// and a "must call X" policy could never pass.
877    #[test]
878    fn counts_tool_calls_from_the_transcript_the_stream_hook_recorded() {
879        let tmp = tempfile::tempdir().unwrap();
880        let transcript = tmp.path().join("t.jsonl");
881        std::fs::write(
882            &transcript,
883            concat!(
884                r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
885                "\n",
886                r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash"},{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
887                "\n",
888            ),
889        )
890        .unwrap();
891        let session_dir = tmp.path().join("sess-1");
892        std::fs::create_dir_all(&session_dir).unwrap();
893
894        let before = collect_session_data(&session_dir).unwrap();
895        assert!(
896            before.tool_calls.is_none(),
897            "no metadata.json, no tool calls"
898        );
899
900        crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
901            .unwrap();
902        let after = collect_session_data(&session_dir).unwrap();
903
904        assert_eq!(after.session_id, "sess-1");
905        assert_eq!(after.total_tool_calls, Some(3));
906        assert_eq!(
907            after.tool_calls,
908            Some(serde_json::json!({"mcp__cargo__cargo_check": 2, "Bash": 1}))
909        );
910    }
911
912    /// Write `lines` as a transcript, record it the way the stream hook does,
913    /// and return the tool calls `check` counts from it.
914    fn tool_calls_from_transcript(lines: &[&str]) -> Option<serde_json::Value> {
915        let tmp = tempfile::tempdir().unwrap();
916        let transcript = tmp.path().join("t.jsonl");
917        std::fs::write(&transcript, lines.join("\n")).unwrap();
918        let session_dir = tmp.path().join("sess");
919        std::fs::create_dir_all(&session_dir).unwrap();
920        crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
921            .unwrap();
922        collect_session_data(&session_dir).unwrap().tool_calls
923    }
924
925    #[test]
926    fn counts_tool_calls_from_a_codex_rollout() {
927        let calls = tool_calls_from_transcript(&[
928            r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix it"}]}}"#,
929            r#"{"type":"response_item","payload":{"type":"custom_tool_call","name":"apply_patch","input":"*** Begin Patch\n*** End Patch\n"}}"#,
930            r#"{"type":"response_item","payload":{"type":"function_call","name":"mcp__cargo__cargo_check","arguments":"{}"}}"#,
931            r#"{"type":"response_item","payload":{"type":"local_shell_call","command":"ls"}}"#,
932            r#"{"type":"event_msg","payload":{"type":"token_count"}}"#,
933        ]);
934        assert_eq!(
935            calls,
936            Some(serde_json::json!({"apply_patch": 1, "mcp__cargo__cargo_check": 1, "Bash": 1}))
937        );
938    }
939
940    #[test]
941    fn counts_tool_calls_from_a_gsd_session() {
942        let calls = tool_calls_from_transcript(&[
943            r#"{"type":"model_change","provider":"anthropic","modelId":"claude-opus-4-7"}"#,
944            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":{}}]}}"#,
945            r#"{"type":"message","message":{"role":"toolResult","toolName":"write","content":[]}}"#,
946        ]);
947        assert_eq!(calls, Some(serde_json::json!({"write": 1, "bash": 1})));
948    }
949
950    /// OpenCode sends no transcript path, only inline records; the stream hook
951    /// keeps their tool calls in a local log that `check` then counts.
952    #[test]
953    fn counts_tool_calls_from_opencode_inline_records() {
954        let tmp = tempfile::tempdir().unwrap();
955        let tool_event = [
956            serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"toolCall","name":"bash","arguments":{"command":"ls"}}]}}),
957            serde_json::json!({"type":"message","message":{"role":"toolResult","toolName":"bash","isError":false,"content":[{"type":"text","text":"a.rs"}]}}),
958        ];
959        let assistant_turn = [
960            serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"done"}]}}),
961        ];
962
963        crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
964        crate::commands::stream::record_inline_tool_calls(tmp.path(), &assistant_turn).unwrap();
965        assert!(collect_session_data(tmp.path())
966            .unwrap()
967            .tool_calls
968            .is_none());
969
970        crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
971        crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
972        let data = collect_session_data(tmp.path()).unwrap();
973        assert_eq!(data.tool_calls, Some(serde_json::json!({"bash": 2})));
974        assert_eq!(data.total_tool_calls, Some(2));
975    }
976
977    /// Amp's plugin sends Amp's own messages in an `amp_message` envelope;
978    /// policies name Amp's tools exactly (`shell_command`, `Task`, ...).
979    #[test]
980    fn counts_tool_calls_from_amp_inline_records() {
981        let tmp = tempfile::tempdir().unwrap();
982        let tool_event = [
983            serde_json::json!({"type":"amp_message","event":"tool.result","message":{"role":"assistant","content":[{"type":"tool_use","id":"TU-1","name":"shell_command","input":{"command":"ls"}}]}}),
984            serde_json::json!({"type":"amp_message","event":"tool.result","message":{"role":"user","content":[{"type":"tool_result","toolUseID":"TU-1","status":"done","output":{"output":"","exitCode":1}}]}}),
985        ];
986        let turn_end = [
987            serde_json::json!({"type":"amp_message","event":"agent.end","message":{"role":"assistant","content":[{"type":"text","text":"ok"},{"type":"tool_use","id":"TU-2","name":"Task","input":{}}],"usage":{"inputTokens":1}}}),
988        ];
989
990        crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
991        crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
992        crate::commands::stream::record_inline_tool_calls(tmp.path(), &turn_end).unwrap();
993        let data = collect_session_data(tmp.path()).unwrap();
994        assert_eq!(
995            data.tool_calls,
996            Some(serde_json::json!({"shell_command": 1, "Task": 1}))
997        );
998        assert_eq!(data.total_tool_calls, Some(2));
999    }
1000
1001    #[test]
1002    fn connectivity_message_suggests_login_on_401() {
1003        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
1004        assert!(
1005            m.contains("tracevault login"),
1006            "401 errors must surface the login hint; got: {m}"
1007        );
1008    }
1009
1010    #[test]
1011    fn connectivity_message_suggests_login_on_unauthorized_text() {
1012        let m = connectivity_message("Server returned: unauthorized request");
1013        assert!(m.contains("tracevault login"));
1014    }
1015
1016    #[test]
1017    fn connectivity_message_suggests_network_check_on_dns_error() {
1018        let m = connectivity_message("error sending request for url: dns error");
1019        assert!(
1020            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
1021            "DNS errors must surface a network hint; got: {m}"
1022        );
1023    }
1024
1025    #[test]
1026    fn connectivity_message_suggests_network_check_on_connection_refused() {
1027        let m = connectivity_message("connection refused");
1028        assert!(m.to_lowercase().contains("network"));
1029    }
1030
1031    #[test]
1032    fn connectivity_message_falls_back_when_unrecognized() {
1033        let m = connectivity_message("some weird new error shape we have not seen before");
1034        // No suggestion — but the raw error must still be in the message so
1035        // the user can debug.
1036        assert!(m.contains("some weird new error shape"));
1037        assert!(!m.contains("→")); // no action arrow
1038    }
1039
1040    #[test]
1041    fn connectivity_message_does_not_collide_on_403() {
1042        let m = connectivity_message("403 Forbidden");
1043        // 403 should point at token authorization, NOT a re-login.
1044        assert!(
1045            m.to_lowercase().contains("authorized"),
1046            "403 should mention authorization; got: {m}"
1047        );
1048    }
1049
1050    #[test]
1051    fn connectivity_message_flags_404_as_version_mismatch() {
1052        // Simulates an old-server-404 skew: a route the CLI expects to exist
1053        // (e.g. `Failed to list repos (404 Not Found)`) doesn't exist yet on
1054        // this server build. Must hint at a version mismatch, not just
1055        // report a bare 404 with no next step.
1056        let m = connectivity_message("Failed to list repos (404 Not Found): ");
1057        assert!(
1058            m.to_lowercase().contains("newer than the server")
1059                || m.to_lowercase().contains("version mismatch"),
1060            "404 should hint at a possible CLI/server version mismatch; got: {m}"
1061        );
1062    }
1063
1064    #[test]
1065    fn connectivity_message_flags_500_as_server_error() {
1066        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
1067        assert!(
1068            m.to_lowercase().contains("server returned an error"),
1069            "500 should surface the server-error hint; got: {m}"
1070        );
1071    }
1072
1073    #[test]
1074    fn connectivity_message_flags_503_without_internal_text() {
1075        // `503 Service Unavailable` carries neither "internal" nor
1076        // "server error" — the bare code must still be recognized.
1077        let m = connectivity_message("Server returned 503 Service Unavailable: ");
1078        assert!(
1079            m.to_lowercase().contains("server returned an error"),
1080            "503 should surface the server-error hint; got: {m}"
1081        );
1082    }
1083
1084    #[test]
1085    fn connectivity_message_treats_504_as_server_not_network() {
1086        // A gateway timeout is a server-side fault even though it contains
1087        // the word "timeout"; it must not be misreported as a local network
1088        // problem.
1089        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
1090        assert!(
1091            m.to_lowercase().contains("server returned an error"),
1092            "504 should be treated as a server error; got: {m}"
1093        );
1094    }
1095}
1096
1097#[cfg(test)]
1098mod push_ref_tests {
1099    use super::{is_zero_sha, parse_push_refs};
1100
1101    #[test]
1102    fn parses_a_single_ref_line() {
1103        let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456\n");
1104        assert_eq!(refs.len(), 1);
1105        assert_eq!(refs[0].local_sha, "abc123");
1106        assert_eq!(refs[0].remote_sha, "def456");
1107    }
1108
1109    #[test]
1110    fn parses_multiple_refs() {
1111        let refs = parse_push_refs(
1112            "refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444\n",
1113        );
1114        assert_eq!(refs.len(), 2);
1115    }
1116
1117    #[test]
1118    fn parses_a_single_ref_line_without_trailing_newline() {
1119        // This is the exact shape the generated pre-push hook produces: it
1120        // captures git's stdin with `$(cat)` (which strips trailing
1121        // newlines) and replays it with `printf '%s'` (which adds none
1122        // back), so the real input to `check` has no trailing newline on
1123        // its final line. Here that unterminated line is the *only* line.
1124        // Do not delete this as a duplicate of `parses_a_single_ref_line`;
1125        // it pins a different, easy-to-break input shape.
1126        let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456");
1127        assert_eq!(refs.len(), 1);
1128        assert_eq!(refs[0].local_sha, "abc123");
1129        assert_eq!(refs[0].remote_sha, "def456");
1130    }
1131
1132    #[test]
1133    fn parses_multiple_refs_when_last_line_has_no_trailing_newline() {
1134        // Same hook-stdin shape as above, but with two refs: only the final
1135        // line is unterminated, matching a real multi-ref push through
1136        // `$(cat)` + `printf '%s'`.
1137        let refs =
1138            parse_push_refs("refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444");
1139        assert_eq!(refs.len(), 2);
1140        assert_eq!(refs[0].local_sha, "111");
1141        assert_eq!(refs[1].local_sha, "333");
1142    }
1143
1144    #[test]
1145    fn skips_branch_deletions() {
1146        let zeros = "0".repeat(40);
1147        let line = format!("(delete) {zeros} refs/heads/gone abc123\n");
1148        assert!(parse_push_refs(&line).is_empty());
1149    }
1150
1151    #[test]
1152    fn keeps_new_branches_whose_remote_sha_is_zero() {
1153        let zeros = "0".repeat(40);
1154        let line = format!("refs/heads/new abc123 refs/heads/new {zeros}\n");
1155        let refs = parse_push_refs(&line);
1156        assert_eq!(refs.len(), 1);
1157        assert!(is_zero_sha(&refs[0].remote_sha));
1158    }
1159
1160    #[test]
1161    fn skips_malformed_lines_without_panicking() {
1162        assert!(parse_push_refs("garbage\n\nalso garbage here\n").is_empty());
1163    }
1164
1165    #[test]
1166    fn zero_sha_detection_handles_sha256_length() {
1167        assert!(is_zero_sha(&"0".repeat(64)));
1168        assert!(!is_zero_sha("0000000000000000000000000000000000000001"));
1169        assert!(!is_zero_sha(""));
1170    }
1171}
1172
1173/// Real-git coverage for the functions `resolve_changed_paths` composes:
1174/// `changed_files_for_refs` (the two-dot range and the empty-tree base for
1175/// new branches) and `git_empty_tree_sha`.
1176///
1177/// `resolve_changed_paths` itself is deliberately NOT driven directly here.
1178/// It reads `std::io::stdin()` when stdin is not a terminal, and `cargo
1179/// test` runs every test in one process sharing that real, global stdin —
1180/// there is no per-test way to inject or close it without invasive,
1181/// process-wide fd surgery, and a test that consumes it would make unrelated
1182/// tests in the same binary flaky. Testing the two git-backed branches it
1183/// falls back to (below) is the safe substitute; the stdin-parsing branch
1184/// itself is already covered without touching stdin by `push_ref_tests`
1185/// (`parse_push_refs`) plus `two_dot_range_returns_only_the_newer_commits_files`
1186/// and `new_branch_zero_remote_sha_resolves_via_empty_tree` below, which
1187/// together exercise every step `resolve_changed_paths` performs once it has
1188/// a parsed `Vec<PushRef>` in hand. The timeout mechanism that bounds the
1189/// stdin read (`read_with_timeout`) is factored generically over the reading
1190/// closure precisely so it can be tested without touching stdin at all —
1191/// see `read_with_timeout_tests` below.
1192#[cfg(test)]
1193mod git_diff_tests {
1194    use super::{changed_files_for_refs, git_empty_tree_sha, PushRef};
1195    use crate::test_helpers::init_git_repo;
1196    use std::path::Path;
1197    use std::process::Command;
1198
1199    /// Write `name` with `content` in `dir`, stage it, and commit it,
1200    /// returning the new commit's sha. Assumes `init_git_repo` already
1201    /// configured a local `user.name`/`user.email` in `dir`.
1202    fn commit_file(dir: &Path, name: &str, content: &str) -> String {
1203        std::fs::write(dir.join(name), content).unwrap();
1204        let ok = Command::new("git")
1205            .args(["-C", &dir.to_string_lossy(), "add", name])
1206            .status()
1207            .expect("git add failed")
1208            .success();
1209        assert!(ok, "git add must succeed");
1210        let ok = Command::new("git")
1211            .args([
1212                "-C",
1213                &dir.to_string_lossy(),
1214                "commit",
1215                "-m",
1216                &format!("add {name}"),
1217            ])
1218            .status()
1219            .expect("git commit failed")
1220            .success();
1221        assert!(ok, "git commit must succeed");
1222        head_sha(dir)
1223    }
1224
1225    fn head_sha(dir: &Path) -> String {
1226        let out = Command::new("git")
1227            .args(["-C", &dir.to_string_lossy(), "rev-parse", "HEAD"])
1228            .output()
1229            .expect("git rev-parse failed");
1230        assert!(out.status.success());
1231        String::from_utf8_lossy(&out.stdout).trim().to_string()
1232    }
1233
1234    #[test]
1235    fn two_dot_range_returns_only_the_newer_commits_files() {
1236        let tmp = tempfile::tempdir().unwrap();
1237        init_git_repo(tmp.path()); // empty "init" commit
1238
1239        let sha1 = commit_file(tmp.path(), "a.txt", "a");
1240        let sha2 = commit_file(tmp.path(), "b.txt", "b");
1241
1242        let refs = vec![PushRef {
1243            local_sha: sha2,
1244            remote_sha: sha1,
1245        }];
1246        let files = changed_files_for_refs(tmp.path(), &refs);
1247
1248        // Must be exactly the file the newer commit touched. A single-arg
1249        // `git diff --name-only <sha>` would instead diff against the
1250        // working tree and silently pull in every tracked file (here, also
1251        // "a.txt") — this is the mistake this test exists to catch.
1252        assert_eq!(files, vec!["b.txt".to_string()]);
1253    }
1254
1255    #[test]
1256    fn new_branch_zero_remote_sha_resolves_via_empty_tree() {
1257        let tmp = tempfile::tempdir().unwrap();
1258        init_git_repo(tmp.path());
1259
1260        commit_file(tmp.path(), "a.txt", "a");
1261        let sha2 = commit_file(tmp.path(), "b.txt", "b");
1262
1263        let refs = vec![PushRef {
1264            local_sha: sha2,
1265            remote_sha: "0".repeat(40),
1266        }];
1267        let mut files = changed_files_for_refs(tmp.path(), &refs);
1268        files.sort();
1269
1270        // A brand-new branch has no remote sha to diff from; the base must
1271        // resolve to the empty tree, so the full branch history shows up.
1272        assert_eq!(files, vec!["a.txt".to_string(), "b.txt".to_string()]);
1273    }
1274
1275    #[test]
1276    fn identical_shas_yield_an_empty_file_list() {
1277        let tmp = tempfile::tempdir().unwrap();
1278        init_git_repo(tmp.path());
1279        let sha = commit_file(tmp.path(), "a.txt", "a");
1280
1281        let refs = vec![PushRef {
1282            local_sha: sha.clone(),
1283            remote_sha: sha,
1284        }];
1285        let files = changed_files_for_refs(tmp.path(), &refs);
1286
1287        assert!(
1288            files.is_empty(),
1289            "a no-op push (same local and remote sha) must yield no files, got {files:?}"
1290        );
1291    }
1292
1293    #[test]
1294    fn non_ascii_path_is_returned_raw_not_octal_quoted() {
1295        let tmp = tempfile::tempdir().unwrap();
1296        init_git_repo(tmp.path());
1297        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1298
1299        let sha1 = commit_file(tmp.path(), "src/café.rs", "one");
1300        let sha2 = commit_file(tmp.path(), "src/café.rs", "two");
1301
1302        let refs = vec![PushRef {
1303            local_sha: sha2,
1304            remote_sha: sha1,
1305        }];
1306        let files = changed_files_for_refs(tmp.path(), &refs);
1307
1308        // Without `-z`, git's default `core.quotePath` behaviour renders this
1309        // as the 20-character literal string `"src/caf\303\251.rs"`
1310        // (surrounding quotes included) instead of the real path — see the
1311        // fix's doc comment. That string can never match the hook-recorded
1312        // path, so the file is silently pruned from `changed_paths`.
1313        assert_eq!(
1314            files,
1315            vec!["src/café.rs".to_string()],
1316            "must be the raw UTF-8 path, not git's octal-quoted rendering; got {files:?}"
1317        );
1318    }
1319
1320    #[test]
1321    fn path_containing_a_space_is_returned_intact() {
1322        let tmp = tempfile::tempdir().unwrap();
1323        init_git_repo(tmp.path());
1324        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1325
1326        let sha1 = commit_file(tmp.path(), "src/has space.rs", "one");
1327        let sha2 = commit_file(tmp.path(), "src/has space.rs", "two");
1328
1329        let refs = vec![PushRef {
1330            local_sha: sha2,
1331            remote_sha: sha1,
1332        }];
1333        let files = changed_files_for_refs(tmp.path(), &refs);
1334
1335        assert_eq!(files, vec!["src/has space.rs".to_string()]);
1336    }
1337
1338    #[test]
1339    fn rename_reports_both_source_and_destination() {
1340        let tmp = tempfile::tempdir().unwrap();
1341        init_git_repo(tmp.path());
1342        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1343        let sha1 = commit_file(tmp.path(), "src/plain.rs", "identical content");
1344
1345        let ok = Command::new("git")
1346            .args([
1347                "-C",
1348                &tmp.path().to_string_lossy(),
1349                "mv",
1350                "src/plain.rs",
1351                "src/renamed.rs",
1352            ])
1353            .status()
1354            .expect("git mv failed")
1355            .success();
1356        assert!(ok, "git mv must succeed");
1357        let ok = Command::new("git")
1358            .args([
1359                "-C",
1360                &tmp.path().to_string_lossy(),
1361                "commit",
1362                "-m",
1363                "rename plain.rs to renamed.rs",
1364            ])
1365            .status()
1366            .expect("git commit failed")
1367            .success();
1368        assert!(ok, "git commit must succeed");
1369        let sha2 = head_sha(tmp.path());
1370
1371        let refs = vec![PushRef {
1372            local_sha: sha2,
1373            remote_sha: sha1,
1374        }];
1375        let mut files = changed_files_for_refs(tmp.path(), &refs);
1376        files.sort();
1377
1378        // Git's rename detection is on by default, so a plain `git diff
1379        // --name-only` here would report only `src/renamed.rs`, hiding the
1380        // fact that `src/plain.rs` ever existed in this diff. If
1381        // `src/plain.rs` were a protected path, that silence is exactly what
1382        // lets an agent rename it away undetected.
1383        assert_eq!(
1384            files,
1385            vec!["src/plain.rs".to_string(), "src/renamed.rs".to_string()],
1386            "a rename must surface BOTH the source and destination path; got {files:?}"
1387        );
1388    }
1389
1390    #[test]
1391    fn git_empty_tree_sha_is_the_well_known_constant() {
1392        let tmp = tempfile::tempdir().unwrap();
1393        init_git_repo(tmp.path());
1394
1395        let empty_tree =
1396            git_empty_tree_sha(tmp.path()).expect("git hash-object must resolve the empty tree");
1397        // The well-known empty-tree object id for sha1 repositories (git's
1398        // default) — asserted against the literal, not just "non-empty", so
1399        // a regression that resolves some other tree can't slip through.
1400        assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1401    }
1402
1403    /// Not a call into `resolve_changed_paths` (see the module doc comment
1404    /// above for why) — this drives the exact git invocation its
1405    /// `@{{upstream}}` fallback branch makes, in a repo with no upstream
1406    /// configured, confirming that branch fails cleanly (non-zero exit) and
1407    /// so `resolve_changed_paths` would correctly return `None` rather than
1408    /// erroring or panicking.
1409    #[test]
1410    fn upstream_fallback_diff_fails_cleanly_with_no_upstream_configured() {
1411        let tmp = tempfile::tempdir().unwrap();
1412        init_git_repo(tmp.path());
1413        commit_file(tmp.path(), "a.txt", "a");
1414
1415        let out = Command::new("git")
1416            .args([
1417                "diff",
1418                "--name-only",
1419                "-z",
1420                "--no-renames",
1421                "@{upstream}..HEAD",
1422            ])
1423            .current_dir(tmp.path())
1424            .output()
1425            .expect("git diff must run");
1426
1427        assert!(
1428            !out.status.success(),
1429            "no upstream is configured, so this must fail rather than \
1430             silently resolve to something else"
1431        );
1432    }
1433
1434    /// Companion to the test above: with an upstream configured but no diff
1435    /// between it and `HEAD`, the same invocation must succeed with empty
1436    /// output — the shape `resolve_changed_paths` treats as `None`.
1437    #[test]
1438    fn upstream_fallback_diff_is_empty_when_upstream_matches_head() {
1439        let tmp = tempfile::tempdir().unwrap();
1440        init_git_repo(tmp.path());
1441        commit_file(tmp.path(), "a.txt", "a");
1442
1443        let branch_out = Command::new("git")
1444            .args(["symbolic-ref", "--short", "HEAD"])
1445            .current_dir(tmp.path())
1446            .output()
1447            .expect("git symbolic-ref must run");
1448        assert!(branch_out.status.success());
1449        let branch = String::from_utf8_lossy(&branch_out.stdout)
1450            .trim()
1451            .to_string();
1452
1453        // Track a same-commit local branch as upstream, so `@{upstream}`
1454        // resolves but the diff against it is empty — without needing an
1455        // actual remote.
1456        for args in [
1457            vec!["branch", "tracking", &branch],
1458            vec!["branch", "--set-upstream-to=tracking", &branch],
1459        ] {
1460            let ok = Command::new("git")
1461                .args(&args)
1462                .current_dir(tmp.path())
1463                .status()
1464                .expect("git command must run")
1465                .success();
1466            assert!(ok, "git {args:?} must succeed");
1467        }
1468
1469        let out = Command::new("git")
1470            .args([
1471                "diff",
1472                "--name-only",
1473                "-z",
1474                "--no-renames",
1475                "@{upstream}..HEAD",
1476            ])
1477            .current_dir(tmp.path())
1478            .output()
1479            .expect("git diff must run");
1480
1481        assert!(out.status.success());
1482        assert!(
1483            out.stdout.is_empty(),
1484            "identical upstream/HEAD must diff to no files"
1485        );
1486    }
1487}
1488
1489/// Coverage for the generic timeout mechanism behind `read_stdin_with_timeout`.
1490///
1491/// These drive `read_with_timeout` directly with an injected closure instead
1492/// of the real `stdin()` — see the doc comment on `git_diff_tests` above for
1493/// why touching the process's real, global stdin from a test is unsafe here.
1494/// `read_stdin_with_timeout` itself is left thin and untested; once the
1495/// generic helper is proven to time out and to pass through a prompt result,
1496/// there is nothing stdin-specific left to verify.
1497#[cfg(test)]
1498mod read_with_timeout_tests {
1499    use super::read_with_timeout;
1500    use std::time::Duration;
1501
1502    #[test]
1503    fn returns_the_value_when_it_arrives_before_the_deadline() {
1504        let got = read_with_timeout(|| Some("hi".to_string()), Duration::from_secs(1));
1505        assert_eq!(got, Some("hi".to_string()));
1506    }
1507
1508    #[test]
1509    fn returns_none_when_the_closure_itself_returns_none() {
1510        let got = read_with_timeout(|| None, Duration::from_secs(1));
1511        assert_eq!(got, None);
1512    }
1513
1514    #[test]
1515    fn times_out_instead_of_hanging_on_a_closure_that_never_returns() {
1516        // The stalled-pipe case in miniature: the closure blocks well past
1517        // the deadline (in the real bug, forever). Margins are kept wide so
1518        // this cannot flake on a loaded CI machine — a 50ms timeout that
1519        // must return within 1s, against a closure that sleeps for 10s.
1520        let start = std::time::Instant::now();
1521        let got = read_with_timeout(
1522            || {
1523                std::thread::sleep(Duration::from_secs(10));
1524                Some("too late".to_string())
1525            },
1526            Duration::from_millis(50),
1527        );
1528        assert_eq!(got, None, "must give up rather than wait for the closure");
1529        assert!(
1530            start.elapsed() < Duration::from_secs(1),
1531            "must return promptly on timeout, not block on the stalled closure; took {:?}",
1532            start.elapsed()
1533        );
1534    }
1535}
1536
1537#[cfg(test)]
1538mod pushed_repo_tests {
1539    use super::{streamed_elsewhere_warning, PushedRepo};
1540    use crate::session_state::RepoBinding;
1541
1542    /// The repo the checkout's origin remote resolves to.
1543    const PUSHED: uuid::Uuid = uuid::uuid!("44000761-0000-4000-8000-000000000001");
1544    /// The repo registered under the checkout's directory name.
1545    const BY_NAME: uuid::Uuid = uuid::uuid!("7995d35d-0000-4000-8000-000000000002");
1546    /// Some other repo a session could be bound to.
1547    const OTHER: uuid::Uuid = uuid::uuid!("aaaaaaaa-0000-4000-8000-000000000003");
1548    const CODEBASE: uuid::Uuid = uuid::uuid!("cccccccc-0000-4000-8000-000000000004");
1549    const OTHER_CODEBASE: uuid::Uuid = uuid::uuid!("dddddddd-0000-4000-8000-000000000005");
1550    const PASS: &str = r#"{"passed":true,"results":[],"blocked":false}"#;
1551
1552    fn binding(repo: uuid::Uuid, remote: Option<uuid::Uuid>) -> RepoBinding {
1553        RepoBinding {
1554            repo_id: repo.to_string(),
1555            git_url: None,
1556            remote_id: remote,
1557            codebase_name: None,
1558            updated_at: "t".into(),
1559        }
1560    }
1561
1562    // ── streamed_elsewhere_warning ───────────────────────────────────────────
1563
1564    #[test]
1565    fn no_warning_when_the_session_streamed_to_the_pushed_repo_or_is_unbound() {
1566        let pushed = PushedRepo {
1567            id: PUSHED,
1568            remote_id: Some(CODEBASE),
1569        };
1570        assert_eq!(
1571            streamed_elsewhere_warning(Some(&binding(PUSHED, None)), &pushed),
1572            None
1573        );
1574        assert_eq!(streamed_elsewhere_warning(None, &pushed), None);
1575    }
1576
1577    #[test]
1578    fn warning_names_both_repos_and_how_far_apart_they_are() {
1579        let pushed = PushedRepo {
1580            id: PUSHED,
1581            remote_id: Some(CODEBASE),
1582        };
1583        let same =
1584            streamed_elsewhere_warning(Some(&binding(OTHER, Some(CODEBASE))), &pushed).unwrap();
1585        assert!(same.contains("another repo of this codebase"), "{same}");
1586        assert!(same.contains(&OTHER.to_string()) && same.contains(&PUSHED.to_string()));
1587        let far = streamed_elsewhere_warning(Some(&binding(OTHER, Some(OTHER_CODEBASE))), &pushed)
1588            .unwrap();
1589        assert!(far.contains("a different codebase"), "{far}");
1590        let unknown = streamed_elsewhere_warning(Some(&binding(OTHER, None)), &pushed).unwrap();
1591        assert!(unknown.contains("a different repo"), "{unknown}");
1592    }
1593
1594    // ── check_policies end to end against a one-shot server ──────────────────
1595
1596    /// Isolated config/state homes and a saved login for a server answering
1597    /// `responses` in order; a primary checkout named `tracing` (with an
1598    /// origin remote when `remote` is set) holding the given sessions, all
1599    /// marked as this worktree's.
1600    struct Fixture {
1601        _guard: crate::test_helpers::EnvVarGuard,
1602        _home: tempfile::TempDir,
1603        _tmp: tempfile::TempDir,
1604        repo: std::path::PathBuf,
1605        rx: std::sync::mpsc::Receiver<String>,
1606    }
1607
1608    fn fixture(remote: bool, sessions: &[&str], responses: Vec<String>) -> Fixture {
1609        let home = tempfile::tempdir().unwrap();
1610        let mut guard = crate::test_helpers::EnvVarGuard::new();
1611        guard.set("XDG_CONFIG_HOME", home.path());
1612        guard.set("XDG_STATE_HOME", home.path());
1613        guard.remove("TRACEVAULT_API_KEY");
1614        guard.remove("TRACEVAULT_SERVER_URL");
1615        let (server, rx) = crate::test_helpers::spawn_seq(responses);
1616        let creds_dir = home.path().join("tracevault");
1617        std::fs::create_dir_all(&creds_dir).unwrap();
1618        std::fs::write(
1619            creds_dir.join("credentials.json"),
1620            format!(
1621                r#"{{"server_url":"{server}","email":"a@b.com","auth":{{
1622                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
1623                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
1624            ),
1625        )
1626        .unwrap();
1627
1628        let tmp = tempfile::tempdir().unwrap();
1629        let repo = tmp.path().join("tracing");
1630        std::fs::create_dir_all(&repo).unwrap();
1631        crate::test_helpers::init_git_repo(&repo);
1632        if remote {
1633            let ok = std::process::Command::new("git")
1634                .args([
1635                    "remote",
1636                    "add",
1637                    "origin",
1638                    "https://github.com/example/visdom-tracing.git",
1639                ])
1640                .current_dir(&repo)
1641                .status()
1642                .unwrap()
1643                .success();
1644            assert!(ok, "git remote add failed");
1645        }
1646        let top = crate::paths::worktree_toplevel(&repo);
1647        for id in sessions {
1648            let dir = repo.join(".tracevault").join("sessions").join(id);
1649            std::fs::create_dir_all(&dir).unwrap();
1650            std::fs::write(dir.join("origin"), &top).unwrap();
1651        }
1652        Fixture {
1653            _guard: guard,
1654            _home: home,
1655            _tmp: tmp,
1656            repo,
1657            rx,
1658        }
1659    }
1660
1661    fn bind_with_repo_switch(session_id: &str, repo_id: uuid::Uuid) {
1662        let state = crate::session_state::SessionState {
1663            active: Some(binding(repo_id, None)),
1664            ..Default::default()
1665        };
1666        crate::session_state::save(session_id, &state).unwrap();
1667    }
1668
1669    /// The origin remote resolves to codebase `CODEBASE`, whose only repo is
1670    /// `PUSHED` — what `repo switch <checkout>` binds a session to.
1671    fn remote_resolves_to_pushed() -> Vec<String> {
1672        vec![
1673            crate::test_helpers::http_json(
1674                "200 OK",
1675                &format!(
1676                    r#"{{"remote_id":"{CODEBASE}","name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready"}}"#
1677                ),
1678            ),
1679            crate::test_helpers::http_json(
1680                "200 OK",
1681                &format!(
1682                    r#"{{"name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready","repos":[{{"id":"{PUSHED}","name":"visdom-tracing"}}]}}"#
1683                ),
1684            ),
1685        ]
1686    }
1687
1688    fn repos_listing() -> String {
1689        crate::test_helpers::http_json(
1690            "200 OK",
1691            &format!(r#"[{{"id":"{BY_NAME}","name":"tracing"}}]"#),
1692        )
1693    }
1694
1695    fn pass() -> String {
1696        crate::test_helpers::http_json("200 OK", PASS)
1697    }
1698
1699    fn recv(f: &Fixture) -> String {
1700        f.rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT)
1701            .expect("expected another request")
1702    }
1703
1704    fn assert_checked_under(request: &str, repo: uuid::Uuid) {
1705        assert!(
1706            request.starts_with(&format!("POST /api/v1/repos/{repo}/policies/check")),
1707            "expected the check under {repo}: {request}"
1708        );
1709    }
1710
1711    /// VIS-601 (first hit on VIS-536's PR): a session bound with
1712    /// `repo switch <checkout>` streamed to the repo the checkout's remote
1713    /// resolves to, but was checked under the repo found by directory name.
1714    /// The push is now checked under the remote-resolved repo, where that
1715    /// session's data lives.
1716    #[tokio::test]
1717    async fn a_push_is_checked_under_the_repo_its_remote_resolves_to() {
1718        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1719        let mut responses = remote_resolves_to_pushed();
1720        responses.push(pass());
1721        let f = fixture(true, &["sess-bound"], responses);
1722        bind_with_repo_switch("sess-bound", PUSHED);
1723
1724        super::check_policies(&f.repo, &f.repo).await.unwrap();
1725
1726        assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
1727        assert!(recv(&f).starts_with(&format!("GET /api/v1/remotes/{CODEBASE} ")));
1728        let check = recv(&f);
1729        assert_checked_under(&check, PUSHED);
1730        assert!(check.contains("sess-bound"), "{check}");
1731    }
1732
1733    /// The pushed repo is the policy authority: a session bound elsewhere —
1734    /// by `repo switch` or by a machine-wide user default — must not move the
1735    /// push to that repo's (possibly laxer) policies.
1736    #[tokio::test]
1737    async fn a_session_bound_elsewhere_does_not_change_which_repo_the_push_is_checked_under() {
1738        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1739        let mut responses = remote_resolves_to_pushed();
1740        responses.push(pass());
1741        let f = fixture(true, &["sess-switched", "sess-default"], responses);
1742        bind_with_repo_switch("sess-switched", OTHER);
1743        crate::user_default::save(&binding(OTHER, None)).unwrap();
1744        assert_eq!(
1745            crate::user_default::load().map(|b| b.repo_id),
1746            Some(OTHER.to_string()),
1747            "fixture must actually set a user default"
1748        );
1749
1750        super::check_policies(&f.repo, &f.repo).await.unwrap();
1751
1752        recv(&f);
1753        recv(&f);
1754        let check = recv(&f);
1755        assert_checked_under(&check, PUSHED);
1756        assert!(
1757            check.contains("sess-switched") && check.contains("sess-default"),
1758            "every session is still evaluated (fail closed): {check}"
1759        );
1760    }
1761
1762    /// No origin remote: the directory-name lookup, exactly as before VIS-601.
1763    #[tokio::test]
1764    async fn without_a_remote_the_push_is_checked_under_the_name_resolved_repo() {
1765        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1766        let f = fixture(false, &["sess-free"], vec![repos_listing(), pass()]);
1767
1768        super::check_policies(&f.repo, &f.repo).await.unwrap();
1769
1770        assert!(recv(&f).starts_with("GET /api/v1/repos "));
1771        let check = recv(&f);
1772        assert_checked_under(&check, BY_NAME);
1773        assert!(check.contains("sess-free"), "{check}");
1774    }
1775
1776    /// A remote the server does not know falls back to the name lookup too.
1777    #[tokio::test]
1778    async fn an_unknown_remote_falls_back_to_the_name_resolved_repo() {
1779        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1780        let f = fixture(
1781            true,
1782            &["sess-free"],
1783            vec![
1784                crate::test_helpers::http_json("404 Not Found", r#"{"error":"remote not found"}"#),
1785                repos_listing(),
1786                pass(),
1787            ],
1788        );
1789
1790        super::check_policies(&f.repo, &f.repo).await.unwrap();
1791
1792        assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
1793        assert!(recv(&f).starts_with("GET /api/v1/repos "));
1794        assert_checked_under(&recv(&f), BY_NAME);
1795    }
1796
1797    /// An unregistered repo still fails the push, even with nothing to check.
1798    #[tokio::test]
1799    async fn an_unregistered_repo_fails_the_push_even_without_sessions() {
1800        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1801        let f = fixture(
1802            false,
1803            &[],
1804            vec![crate::test_helpers::http_json("200 OK", "[]")],
1805        );
1806
1807        let err = super::check_policies(&f.repo, &f.repo)
1808            .await
1809            .expect_err("an unregistered repo must fail the push");
1810        assert!(err.to_string().contains("'tracing' not found"), "{err}");
1811    }
1812}