Skip to main content

agentmux_srv_core/backend/fs_ops/
git.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `fs.git_status`: what git says about the entries of a listed folder, for
5//! the Files pane's markers (modified, untracked, ignored...) and its status
6//! line (branch, ahead/behind).
7//!
8//! Running git inside a folder the user merely browsed must not run code the
9//! folder chose. A repository's own config can name programs that `git
10//! status` executes: `core.fsmonitor`, and a `filter.<name>.clean` (or
11//! `.process`) applied through its `.gitattributes` whenever a file's stat
12//! data differs from the index. Command-line `-c` settings win over every
13//! config file, so the fsmonitor is turned off and every filter the
14//! repository itself defines is blanked; the user's own system and global
15//! filters (Git LFS) are left alone. Submodules, which have configs of their
16//! own, are not entered. The status never writes the index
17//! (`--no-optional-locks`), prompts for nothing, and is killed after a few
18//! seconds on a huge repository.
19//!
20//! Every run here reads what is already on the disk: none fetches a missing
21//! object, and none may start a transport ([`NO_NETWORK_ENV`]). Those two are
22//! set in the environment, where no config file can change them.
23//!
24//! Git facts of a container agent are read inside its container: for a folder
25//! a container agent can write, or anything inside it, no git is started on
26//! the host. The same command runs in the agent's container, as the agent, at
27//! the same folder there ([`super::container_folders`]), and says nothing
28//! while that container is not running.
29//!
30//! Spec: docs/specs/SPEC_FILE_BROWSER_PANE_2026_10_01.md §12 (Phase 2, git
31//! decorations).
32
33use std::collections::HashMap;
34use std::time::Duration;
35
36use agentmux_common::win32::NoWindow;
37
38use crate::backend::container::mounts::read_exec;
39use crate::backend::rpc_types::{FsGitEntry, FsGitState, FsGitStatus};
40
41use super::container_folders::{self, Inside, Place};
42use super::platform::display_path;
43
44/// A status that takes longer than this is abandoned: the pane shows no
45/// markers rather than waiting.
46const GIT_TIMEOUT: Duration = Duration::from_secs(4);
47
48/// Settings forced on every git run here, ahead of any config file.
49const SAFE_CONFIG: &[&str] = &[
50    // A repository's config could name a program to run (see module docs).
51    "-c",
52    "core.fsmonitor=false",
53    // Don't write the untracked cache into the repository.
54    "-c",
55    "core.untrackedCache=false",
56];
57
58/// Set on every git run here: a read of the folder as it is. git does not
59/// fetch an object the repository lacks, and no transport is allowed (an
60/// empty list of allowed protocols), whatever the repository's config says.
61pub const NO_NETWORK_ENV: &[(&str, &str)] = &[("GIT_NO_LAZY_FETCH", "1"), ("GIT_ALLOW_PROTOCOL", "")];
62
63/// Set on every git run here, with [`NO_NETWORK_ENV`]: nothing prompts and no
64/// lock is taken.
65const QUIET_ENV: &[(&str, &str)] = &[("GIT_OPTIONAL_LOCKS", "0"), ("GIT_TERMINAL_PROMPT", "0")];
66
67/// What a git run answers, without starting git, while it can't be told whose
68/// the folder is.
69pub const NOT_READ_ON_THE_HOST: &str = "Git facts of a container agent's folder are not read on the host.";
70
71/// The most a git run inside a container may print.
72const MAX_INSIDE_OUTPUT: usize = 16 * 1024 * 1024;
73
74/// `fs.git_status` for `raw` (a folder the pane listed).
75pub async fn git_status(raw: &str) -> FsGitStatus {
76    let dir = match super::resolve_request_path(raw).and_then(|p| p.canonicalize().map_err(|e| e.to_string())) {
77        Ok(d) if d.is_dir() => d,
78        _ => return FsGitStatus::default(),
79    };
80    let dir_arg = display_path(&dir);
81
82    // Where the folder sits in its repository ("" at the top). Failing here
83    // is the ordinary "not a repository", or no git at all: no markers.
84    let prefix = match run_git(&dir_arg, &["rev-parse", "--show-prefix"]).await {
85        Ok(out) => String::from_utf8_lossy(&out).trim_end_matches(['\r', '\n']).to_string(),
86        Err(_) => return FsGitStatus::default(),
87    };
88    let status = ["--ignored=matching", "--", "."];
89    let out = match safe_status_porcelain(&dir_arg, &status).await {
90        Ok(out) => out,
91        Err(StatusError::Settings(what)) => {
92            return FsGitStatus {
93                in_repo: true,
94                error: Some(format!("{what}, so git markers are off here.")),
95                ..Default::default()
96            };
97        }
98        Err(StatusError::Git(e)) => return FsGitStatus { in_repo: true, error: Some(e), ..Default::default() },
99    };
100    summarize(&parse_porcelain_v2(&out), &prefix)
101}
102
103/// Why [`safe_status_porcelain`] gave no status.
104#[derive(Debug)]
105pub(crate) enum StatusError {
106    /// The repository's settings couldn't be read safely: git status was
107    /// not run at all. The text completes "…, so …".
108    Settings(&'static str),
109    /// git itself failed or timed out, in a sentence.
110    Git(String),
111}
112
113/// `git status --porcelain=v2 -z --branch --untracked-files=normal
114/// --ignore-submodules=all <extra>` in `dir`, with the repository's own
115/// filters blanked (see module docs). Shared by the Files pane and the
116/// agents' work facts (`backend::work_facts`).
117pub(crate) async fn safe_status_porcelain(dir: &str, extra: &[&str]) -> Result<Vec<u8>, StatusError> {
118    // The repository's own filters, blanked for this run (see module docs).
119    // Fails closed: if the config can't be read, git status doesn't run
120    // (#4223): unblanked filters would run.
121    let Ok(filters) = repo_filters(dir).await else {
122        return Err(StatusError::Settings("Couldn't read this repository's settings"));
123    };
124    // `-c` splits at the first `=`, so a filter named `x=y` can't be
125    // blanked that way (#4223). Such a name is never needed: don't run git
126    // there at all.
127    if filters.iter().any(|n| n.contains('=')) {
128        return Err(StatusError::Settings("This repository's settings can't be read safely"));
129    }
130    let mut args: Vec<String> = Vec::new();
131    for name in filters {
132        for key in ["clean", "smudge", "process"] {
133            args.push("-c".into());
134            args.push(format!("filter.{name}.{key}="));
135        }
136        args.push("-c".into());
137        args.push(format!("filter.{name}.required=false"));
138    }
139    args.extend(
140        ["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal", "--ignore-submodules=all"]
141            .map(String::from),
142    );
143    args.extend(extra.iter().map(|s| s.to_string()));
144    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
145    run_git(dir, &arg_refs).await.map_err(|e| StatusError::Git(e.message()))
146}
147
148/// The top folder of the repository `dir` is in, as a host path. `None`
149/// outside a repository, and for a container agent's folder whose repository
150/// is not inside the folder bound into its container.
151pub(crate) async fn safe_toplevel(dir: &str) -> Option<String> {
152    let (out, inside) = run_git_where(dir, &["rev-parse", "--show-toplevel"]).await.ok()?;
153    let line = String::from_utf8_lossy(&out).trim_end_matches(['\r', '\n']).to_string();
154    if line.is_empty() {
155        return None;
156    }
157    match inside {
158        None => Some(line),
159        Some(inside) => inside.host_path(&line),
160    }
161}
162
163/// Run a read-only git command (`rev-parse`, `remote get-url`) in `dir` with
164/// the same safe settings and timeout as the status above: its trimmed
165/// stdout, or `None` on any failure.
166pub(crate) async fn safe_git_line(dir: &str, args: &[&str]) -> Option<String> {
167    let out = run_git(dir, args).await.ok()?;
168    let line = String::from_utf8_lossy(&out).trim_end_matches(['\r', '\n']).to_string();
169    (!line.is_empty()).then_some(line)
170}
171
172/// The names of the filters a repository's own config defines (its
173/// `.git/config`, worktree config, and what they include): every
174/// `filter.<name>.*` key whose scope isn't the user's system or global
175/// config. An older git without `--show-scope` gets every filter blanked.
176/// `Err` when the config couldn't be read: the caller must not run git
177/// status then. Only `--get-regexp`'s exit 1 ("no match") means none.
178async fn repo_filters(dir: &str) -> Result<Vec<String>, ()> {
179    let scoped = run_git(dir, &["config", "--show-scope", "--name-only", "--get-regexp", r"^filter\."]).await;
180    let (out, scoped) = match scoped {
181        Ok(out) => (out, true),
182        Err(GitError::Exit(1)) => return Ok(Vec::new()),
183        // An older git without `--show-scope`: every filter, unscoped.
184        Err(_) => match run_git(dir, &["config", "--name-only", "--get-regexp", r"^filter\."]).await {
185            Ok(out) => (out, false),
186            Err(GitError::Exit(1)) => return Ok(Vec::new()),
187            Err(_) => return Err(()),
188        },
189    };
190    Ok(filter_names(&String::from_utf8_lossy(&out), scoped))
191}
192
193/// Filter names from `git config [--show-scope] --name-only --get-regexp
194/// ^filter\.` output; with scopes, only those outside system and global.
195pub fn filter_names(out: &str, scoped: bool) -> Vec<String> {
196    let mut names: Vec<String> = Vec::new();
197    for line in out.lines() {
198        let (scope, key) = if scoped {
199            match line.split_once(|c: char| c.is_whitespace()) {
200                Some((s, k)) => (s, k.trim()),
201                None => continue,
202            }
203        } else {
204            ("", line.trim())
205        };
206        if scoped && (scope == "system" || scope == "global") {
207            continue;
208        }
209        // filter.<name>.<key>; a name may itself contain dots.
210        let Some(rest) = key.strip_prefix("filter.") else { continue };
211        let Some((name, _)) = rest.rsplit_once('.') else { continue };
212        if !name.is_empty() && !names.iter().any(|n| n == name) {
213            names.push(name.to_string());
214        }
215    }
216    names
217}
218
219/// Run git for `dir` with the safe settings, where that folder's git runs: on
220/// the host, or inside the container of the agent that can write it. Its
221/// stdout, or a sentence.
222async fn run_git(dir: &str, args: &[&str]) -> Result<Vec<u8>, GitError> {
223    run_git_where(dir, args).await.map(|(out, _)| out)
224}
225
226/// [`run_git`], with the place it ran in when that was inside a container.
227async fn run_git_where(dir: &str, args: &[&str]) -> Result<(Vec<u8>, Option<Inside>), GitError> {
228    // Decided before any command is built; a check that can't finish counts as not known.
229    let asked = dir.to_string();
230    let place = tokio::task::spawn_blocking(move || container_folders::place(&asked)).await.unwrap_or(Place::Unknown);
231    match place {
232        Place::Host => run_on_host(dir, args).await.map(|out| (out, None)),
233        Place::Inside(inside) => run_inside(&inside, args).await.map(|out| (out, Some(inside))),
234        Place::Unknown => Err(GitError::Failed(NOT_READ_ON_THE_HOST.to_string())),
235    }
236}
237
238/// The command in the container of the agent that can write the folder, as
239/// that agent, with the settings and the environment of a host run. git's
240/// exit and error text are read as on the host.
241async fn run_inside(inside: &Inside, args: &[&str]) -> Result<Vec<u8>, GitError> {
242    let mut argv = vec!["git".to_string()];
243    argv.extend(git_args(&inside.dir, args));
244    let env: Vec<(String, String)> = QUIET_ENV.iter().chain(NO_NETWORK_ENV).map(|(k, v)| (k.to_string(), v.to_string())).collect();
245    let out = read_exec::read(&inside.container, &argv, &env, GIT_TIMEOUT, MAX_INSIDE_OUTPUT).await.map_err(GitError::Failed)?;
246    match out.exit {
247        Some(0) => Ok(out.stdout),
248        Some(read_exec::TIMED_OUT_EXIT) => Err(GitError::Failed("git took too long to answer.".to_string())),
249        Some(code) if out.stderr.is_empty() => Err(GitError::Exit(i32::try_from(code).unwrap_or(-1))),
250        None if out.stderr.is_empty() => Err(GitError::Failed("git didn't say how it ended.".to_string())),
251        _ => Err(GitError::Failed(String::from_utf8_lossy(&out.stderr).trim().to_string())),
252    }
253}
254
255/// The command on the host.
256async fn run_on_host(dir: &str, args: &[&str]) -> Result<Vec<u8>, GitError> {
257    #[cfg(test)]
258    test_support::note_host_run(dir);
259    let mut cmd = git_command(dir, args);
260    let child = cmd.spawn().map_err(|e| GitError::Failed(format!("Couldn't run git: {e}")))?;
261    match tokio::time::timeout(GIT_TIMEOUT, child.wait_with_output()).await {
262        Err(_) => Err(GitError::Failed("git took too long to answer.".to_string())),
263        Ok(Err(e)) => Err(GitError::Failed(format!("git failed: {e}"))),
264        Ok(Ok(out)) if out.status.success() => Ok(out.stdout),
265        Ok(Ok(out)) => match out.status.code() {
266            Some(code) if out.stderr.is_empty() => Err(GitError::Exit(code)),
267            _ => Err(GitError::Failed(String::from_utf8_lossy(&out.stderr).trim().to_string())),
268        },
269    }
270}
271
272/// What follows `git` in every run here: the folder, the safe settings, no
273/// optional lock, then the command.
274fn git_args(dir: &str, args: &[&str]) -> Vec<String> {
275    let mut all = vec!["-C".to_string(), dir.to_string()];
276    all.extend(SAFE_CONFIG.iter().map(|s| s.to_string()));
277    all.push("--no-optional-locks".to_string());
278    all.extend(args.iter().map(|s| s.to_string()));
279    all
280}
281
282/// The one git command this module runs on the host: the safe settings, no
283/// prompt, no optional lock, no fetch and no transport, and nothing of this
284/// instance's identity.
285fn git_command(dir: &str, args: &[&str]) -> tokio::process::Command {
286    let mut cmd = tokio::process::Command::new("git");
287    cmd.args(git_args(dir, args));
288    cmd.envs(QUIET_ENV.iter().copied());
289    cmd.stdin(std::process::Stdio::null())
290        .stdout(std::process::Stdio::piped())
291        .stderr(std::process::Stdio::piped())
292        .kill_on_drop(true)
293        .no_window();
294    // git needs nothing of this instance's identity.
295    crate::backend::pane_env::sanitize_external_command(&mut cmd);
296    // Last, so nothing above can take them off.
297    cmd.envs(NO_NETWORK_ENV.iter().copied());
298    cmd
299}
300
301#[derive(Debug)]
302enum GitError {
303    /// git exited with this code and said nothing.
304    Exit(i32),
305    Failed(String),
306}
307
308impl GitError {
309    fn message(self) -> String {
310        match self {
311            GitError::Exit(code) => format!("git exited with status {code}."),
312            GitError::Failed(m) => m,
313        }
314    }
315}
316
317/// One path git reported, relative to the repository's top.
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct GitRecord {
320    pub path: String,
321    pub state: FsGitState,
322}
323
324/// What `git status --porcelain=v2 -z --branch` printed.
325#[derive(Debug, Default, PartialEq, Eq)]
326pub struct Porcelain {
327    pub branch: Option<String>,
328    pub ahead: Option<u64>,
329    pub behind: Option<u64>,
330    pub records: Vec<GitRecord>,
331}
332
333/// The state an ordinary (`1`) or rename/copy (`2`) record's XY code means:
334/// the most pressing of the staged (X) and unstaged (Y) changes.
335fn state_of_xy(xy: &str) -> FsGitState {
336    let mut state = FsGitState::Added;
337    let mut seen = false;
338    for c in xy.chars() {
339        let s = match c {
340            'M' | 'T' => FsGitState::Modified,
341            'D' => FsGitState::Deleted,
342            'R' | 'C' => FsGitState::Renamed,
343            'A' => FsGitState::Added,
344            _ => continue,
345        };
346        state = if seen { state.max(s) } else { s };
347        seen = true;
348    }
349    state
350}
351
352/// Parse porcelain v2 output (`-z`: NUL-terminated records; a rename's
353/// original path follows it as its own NUL-terminated field).
354pub fn parse_porcelain_v2(out: &[u8]) -> Porcelain {
355    let mut p = Porcelain::default();
356    let mut fields = out.split(|b| *b == 0).map(|f| String::from_utf8_lossy(f).into_owned());
357    while let Some(line) = fields.next() {
358        if line.is_empty() {
359            continue;
360        }
361        let kind = line.as_bytes()[0];
362        match kind {
363            b'#' => {
364                if let Some(head) = line.strip_prefix("# branch.head ") {
365                    if head != "(detached)" {
366                        p.branch = Some(head.to_string());
367                    }
368                } else if let Some(ab) = line.strip_prefix("# branch.ab ") {
369                    let mut it = ab.split(' ');
370                    p.ahead = it.next().and_then(|a| a.trim_start_matches('+').parse().ok());
371                    p.behind = it.next().and_then(|b| b.trim_start_matches('-').parse().ok());
372                }
373            }
374            b'1' => {
375                // 1 XY sub mH mI mW hH hI path
376                let parts: Vec<&str> = line.splitn(9, ' ').collect();
377                if parts.len() == 9 {
378                    p.records.push(GitRecord { path: parts[8].to_string(), state: state_of_xy(parts[1]) });
379                }
380            }
381            b'2' => {
382                // 2 XY sub mH mI mW hH hI Xscore path, then the original path.
383                let parts: Vec<&str> = line.splitn(10, ' ').collect();
384                let _orig = fields.next();
385                if parts.len() == 10 {
386                    p.records.push(GitRecord { path: parts[9].to_string(), state: state_of_xy(parts[1]).max(FsGitState::Renamed) });
387                }
388            }
389            b'u' => {
390                // u XY sub m1 m2 m3 mW h1 h2 h3 path
391                let parts: Vec<&str> = line.splitn(11, ' ').collect();
392                if parts.len() == 11 {
393                    p.records.push(GitRecord { path: parts[10].to_string(), state: FsGitState::Conflicted });
394                }
395            }
396            b'?' | b'!' => {
397                if let Some(path) = line.get(2..) {
398                    let state = if kind == b'?' { FsGitState::Untracked } else { FsGitState::Ignored };
399                    p.records.push(GitRecord { path: path.to_string(), state });
400                }
401            }
402            _ => {}
403        }
404    }
405    p
406}
407
408/// Fold the records under `prefix` (the listed folder, relative to the
409/// repository's top, `/`-separated with a trailing `/`, or empty) into one
410/// state per direct child. A folder takes the most pressing state of what's
411/// inside it, except that a folder is only "ignored" when git ignores the
412/// folder itself.
413pub fn summarize(p: &Porcelain, prefix: &str) -> FsGitStatus {
414    let mut by_child: HashMap<String, FsGitState> = HashMap::new();
415    let mut changes = 0u64;
416    for r in &p.records {
417        let Some(rel) = r.path.strip_prefix(prefix) else { continue };
418        let rel = rel.trim_end_matches('/');
419        if rel.is_empty() {
420            continue;
421        }
422        if r.state != FsGitState::Ignored {
423            changes += 1;
424        }
425        let (child, nested) = match rel.split_once('/') {
426            Some((c, _)) => (c, true),
427            None => (rel, false),
428        };
429        // Something ignored deep inside doesn't make its folder look ignored.
430        if nested && r.state == FsGitState::Ignored {
431            continue;
432        }
433        by_child.entry(child.to_string()).and_modify(|s| *s = (*s).max(r.state)).or_insert(r.state);
434    }
435    let mut entries: Vec<FsGitEntry> = by_child.into_iter().map(|(name, state)| FsGitEntry { name, state }).collect();
436    entries.sort_by(|a, b| a.name.cmp(&b.name));
437    FsGitStatus {
438        in_repo: true,
439        branch: p.branch.clone(),
440        ahead: p.ahead,
441        behind: p.behind,
442        entries,
443        changes,
444        error: None,
445    }
446}
447
448/// For the tests of this crate: a container whose git answers, and which
449/// folders git was started for on the host.
450#[cfg(test)]
451pub(crate) mod test_support {
452    use std::sync::Arc;
453
454    use crate::backend::container::mounts::read_exec::{self, ReadOutput};
455
456    fn host_runs() -> &'static parking_lot::Mutex<Vec<String>> {
457        static RUNS: std::sync::LazyLock<parking_lot::Mutex<Vec<String>>> = std::sync::LazyLock::new(Default::default);
458        &RUNS
459    }
460
461    pub(super) fn note_host_run(dir: &str) {
462        host_runs().lock().push(dir.replace('\\', "/"));
463    }
464
465    /// How many times git was started on the host for a folder whose path has `part` in it.
466    pub(crate) fn host_runs_for(part: &str) -> usize {
467        host_runs().lock().iter().filter(|dir| dir.contains(part)).count()
468    }
469
470    /// Each run a container's git was asked for: its words and its environment.
471    pub(crate) type Seen = Arc<parking_lot::Mutex<Vec<(Vec<String>, Vec<(String, String)>)>>>;
472
473    /// Stands in for the git of `container`: a repository at `/workspace` on the branch `inside`, from
474    /// `agentmuxai/inside`, with `in-container.txt` changed and `sub/new-inside.txt` new. Answers what it was
475    /// asked with.
476    pub(crate) fn container_git(container: &str) -> Seen {
477        let seen = Seen::default();
478        let log = seen.clone();
479        read_exec::stand_in_for_test(container, move |argv, env| {
480            log.lock().push((argv.to_vec(), env.to_vec()));
481            let has = |word: &str| argv.iter().any(|a| a == word);
482            let says = |out: &[u8]| Ok(ReadOutput { exit: Some(0), stdout: out.to_vec(), stderr: Vec::new() });
483            let dir = argv.get(2).map(String::as_str).unwrap_or_default();
484            if !(dir == "/workspace" || dir.starts_with("/workspace/")) {
485                return Ok(ReadOutput { exit: Some(128), stdout: Vec::new(), stderr: b"fatal: not a git repository".to_vec() });
486            }
487            if has("--show-toplevel") {
488                says(b"/workspace\n")
489            } else if has("--show-prefix") {
490                let below = dir.trim_start_matches("/workspace").trim_start_matches('/');
491                says(if below.is_empty() { String::new() } else { format!("{below}/\n") }.as_bytes())
492            } else if has("get-url") {
493                says(b"https://github.com/AgentMuxAI/Inside.git\n")
494            } else if has("status") {
495                says(b"# branch.head inside\x001 .M N... 100644 100644 100644 abc abc in-container.txt\x00? sub/new-inside.txt\x00")
496            } else {
497                // No filter is set, no such ref: git's quiet exit 1.
498                Ok(ReadOutput { exit: Some(1), ..Default::default() })
499            }
500        });
501        seen
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    fn z(records: &[&str]) -> Vec<u8> {
510        let mut out = Vec::new();
511        for r in records {
512            out.extend_from_slice(r.as_bytes());
513            out.push(0);
514        }
515        out
516    }
517
518    #[test]
519    fn parses_branch_ahead_and_behind() {
520        let p = parse_porcelain_v2(&z(&["# branch.oid abc", "# branch.head main", "# branch.upstream origin/main", "# branch.ab +2 -5"]));
521        assert_eq!(p.branch.as_deref(), Some("main"));
522        assert_eq!((p.ahead, p.behind), (Some(2), Some(5)));
523        let detached = parse_porcelain_v2(&z(&["# branch.head (detached)"]));
524        assert_eq!(detached.branch, None);
525    }
526
527    #[test]
528    fn parses_every_record_kind_including_spaces_and_renames() {
529        let out = z(&[
530            "1 .M N... 100644 100644 100644 aaa bbb src/a file.ts",
531            "1 A. N... 000000 100644 100644 000 ccc new.ts",
532            "1 D. N... 100644 000000 000000 ddd 000 gone.ts",
533            "2 R. N... 100644 100644 100644 eee eee R100 docs/new name.md",
534            "docs/old name.md",
535            "u UU N... 100644 100644 100644 100644 a b c conflict.rs",
536            "? notes.txt",
537            "! target/",
538        ]);
539        let p = parse_porcelain_v2(&out);
540        let got: Vec<(&str, FsGitState)> = p.records.iter().map(|r| (r.path.as_str(), r.state)).collect();
541        assert_eq!(
542            got,
543            vec![
544                ("src/a file.ts", FsGitState::Modified),
545                ("new.ts", FsGitState::Added),
546                ("gone.ts", FsGitState::Deleted),
547                ("docs/new name.md", FsGitState::Renamed),
548                ("conflict.rs", FsGitState::Conflicted),
549                ("notes.txt", FsGitState::Untracked),
550                ("target/", FsGitState::Ignored),
551            ]
552        );
553    }
554
555    #[test]
556    fn a_staged_add_with_later_edits_reads_as_modified() {
557        assert_eq!(state_of_xy("AM"), FsGitState::Modified);
558        assert_eq!(state_of_xy("MD"), FsGitState::Modified);
559        assert_eq!(state_of_xy("R."), FsGitState::Renamed);
560    }
561
562    #[test]
563    fn folds_records_into_the_listed_folders_children() {
564        let p = parse_porcelain_v2(&z(&[
565            "# branch.head main",
566            "1 .M N... 1 1 1 a b app/src/x.ts",
567            "? app/src/new/",
568            "1 .M N... 1 1 1 a b app/README.md",
569            "! app/node_modules/",
570            "! app/src/cache/",
571            "? app/notes.txt",
572            "1 .M N... 1 1 1 a b other/y.ts",
573        ]));
574        let s = summarize(&p, "app/");
575        let got: Vec<(&str, FsGitState)> = s.entries.iter().map(|e| (e.name.as_str(), e.state)).collect();
576        assert_eq!(
577            got,
578            vec![
579                ("README.md", FsGitState::Modified),
580                ("node_modules", FsGitState::Ignored),
581                ("notes.txt", FsGitState::Untracked),
582                // Modified beats untracked; the ignored cache inside doesn't count.
583                ("src", FsGitState::Modified),
584            ]
585        );
586        assert_eq!(s.changes, 4);
587        assert_eq!(s.branch.as_deref(), Some("main"));
588    }
589
590    #[test]
591    fn at_the_top_the_prefix_is_empty() {
592        let p = parse_porcelain_v2(&z(&["? a.txt", "1 .M N... 1 1 1 a b dir/b.txt"]));
593        let s = summarize(&p, "");
594        assert_eq!(s.entries.len(), 2);
595    }
596
597    /// The real thing, when git is installed: a repo whose config asks for an
598    /// fsmonitor program gets none run, and the markers come back.
599    #[tokio::test]
600    async fn runs_git_without_the_repositorys_fsmonitor() {
601        let dir = tempfile::tempdir().unwrap();
602        let git = |args: &[&str]| {
603            std::process::Command::new("git")
604                .args(["-c", "user.email=a@b", "-c", "user.name=a"])
605                .args(args)
606                .current_dir(dir.path())
607                .no_window()
608                .output()
609        };
610        if git(&["init", "-q"]).map(|o| !o.status.success()).unwrap_or(true) {
611            return; // No git on this machine.
612        }
613        std::fs::write(dir.path().join("tracked.txt"), "a").unwrap();
614        let _ = git(&["add", "."]);
615        let _ = git(&["commit", "-qm", "x"]);
616        std::fs::write(dir.path().join("tracked.txt"), "b").unwrap();
617        std::fs::write(dir.path().join("new.txt"), "n").unwrap();
618        // A program git would run for core.fsmonitor: it would leave a mark.
619        let mark = dir.path().join("fsmonitor-ran");
620        let _ = git(&["config", "core.fsmonitor", &format!("touch '{}'", mark.display())]);
621
622        let s = git_status(&dir.path().to_string_lossy()).await;
623        assert!(s.in_repo, "{s:?}");
624        let get = |n: &str| s.entries.iter().find(|e| e.name == n).map(|e| e.state);
625        assert_eq!(get("tracked.txt"), Some(FsGitState::Modified));
626        assert_eq!(get("new.txt"), Some(FsGitState::Untracked));
627        assert!(!mark.exists(), "the repository's fsmonitor program ran");
628    }
629
630    #[test]
631    fn blanks_the_repositorys_filters_and_keeps_the_users() {
632        let out = "system\tfilter.lfs.clean\nglobal\tfilter.lfs.process\nlocal\tfilter.evil.clean\nlocal\tfilter.evil.process\nworktree\tfilter.a.b.smudge\n";
633        assert_eq!(filter_names(out, true), vec!["evil".to_string(), "a.b".to_string()]);
634        // Without scopes (an older git), every filter.
635        assert_eq!(filter_names("filter.lfs.clean\nfilter.x.process\n", false), vec!["lfs".to_string(), "x".to_string()]);
636    }
637
638    /// The other route git status has to a repository's code: a clean filter
639    /// named in `.git/config` and applied by `.gitattributes`, run when a
640    /// file's stat data differs from the index. ReAgent on #4223.
641    #[tokio::test]
642    async fn runs_git_without_the_repositorys_clean_filter() {
643        let dir = tempfile::tempdir().unwrap();
644        let git = |args: &[&str]| {
645            std::process::Command::new("git")
646                .args(["-c", "user.email=a@b", "-c", "user.name=a"])
647                .args(args)
648                .current_dir(dir.path())
649                .no_window()
650                .output()
651        };
652        if git(&["init", "-q"]).map(|o| !o.status.success()).unwrap_or(true) {
653            return; // No git on this machine.
654        }
655        std::fs::write(dir.path().join(".gitattributes"), "*.txt filter=evil\n").unwrap();
656        std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
657        let _ = git(&["add", "."]);
658        let _ = git(&["commit", "-qm", "x"]);
659        let mark = dir.path().join("filter-ran");
660        let mark_arg = mark.display().to_string().replace('\\', "/");
661        let _ = git(&["config", "filter.evil.clean", &format!("sh -c 'touch \"{mark_arg}\"; cat'")]);
662        // New stat data, same content: git must look at the content, through
663        // the filter if it were allowed to.
664        std::thread::sleep(std::time::Duration::from_millis(1100));
665        std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
666
667        let s = git_status(&dir.path().to_string_lossy()).await;
668        assert!(s.in_repo && s.error.is_none(), "{s:?}");
669        assert!(!mark.exists(), "the repository's clean filter ran");
670    }
671
672    /// `-c filter.x=y.clean=` would set `filter.x`, not blank `x=y`'s clean
673    /// command: a repository with such a filter gets no git run at all.
674    #[tokio::test]
675    async fn refuses_a_filter_name_that_c_cannot_blank() {
676        let dir = tempfile::tempdir().unwrap();
677        let git = |args: &[&str]| {
678            std::process::Command::new("git")
679                .args(["-c", "user.email=a@b", "-c", "user.name=a"])
680                .args(args)
681                .current_dir(dir.path())
682                .no_window()
683                .output()
684        };
685        if git(&["init", "-q"]).map(|o| !o.status.success()).unwrap_or(true) {
686            return; // No git on this machine.
687        }
688        std::fs::write(dir.path().join(".gitattributes"), "*.txt filter=x=y\n").unwrap();
689        std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
690        let _ = git(&["add", "."]);
691        let _ = git(&["commit", "-qm", "x"]);
692        let mark = dir.path().join("filter-ran");
693        let mark_arg = mark.display().to_string().replace('\\', "/");
694        let _ = git(&["config", "filter.x=y.clean", &format!("sh -c 'touch \"{mark_arg}\"; cat'")]);
695        std::thread::sleep(std::time::Duration::from_millis(1100));
696        std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
697
698        let s = git_status(&dir.path().to_string_lossy()).await;
699        assert!(s.entries.is_empty() && s.error.is_some(), "{s:?}");
700        assert!(!mark.exists(), "the repository's clean filter ran");
701    }
702
703    /// A config git can't parse makes the filter lookup fail: then git
704    /// status must not run (it would run with nothing blanked).
705    #[tokio::test]
706    async fn an_unreadable_config_turns_markers_off() {
707        let dir = tempfile::tempdir().unwrap();
708        let ok = std::process::Command::new("git").args(["init", "-q"]).current_dir(dir.path()).no_window().output();
709        if ok.map(|o| !o.status.success()).unwrap_or(true) {
710            return; // No git on this machine.
711        }
712        let config = dir.path().join(".git").join("config");
713        let mut text = std::fs::read_to_string(&config).unwrap();
714        text.push_str("\n[filter \"evil\"\n\tclean = broken\n");
715        std::fs::write(&config, text).unwrap();
716        // git refuses the repository at the first step, or the filter lookup
717        // fails: either way no status runs and there are no markers.
718        let s = git_status(&dir.path().to_string_lossy()).await;
719        assert!(s.entries.is_empty(), "{s:?}");
720        assert!(!s.in_repo || s.error.is_some(), "{s:?}");
721    }
722
723    fn test_git(dir: &std::path::Path, args: &[&str]) -> Option<String> {
724        let out = std::process::Command::new("git")
725            .args(["-c", "user.email=a@b", "-c", "user.name=a"])
726            .args(args)
727            .current_dir(dir)
728            .no_window()
729            .output()
730            .ok()?;
731        out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
732    }
733
734    /// A repository whose own settings say where a missing object comes from
735    /// and allow every transport, with one object of its HEAD missing. The
736    /// program it names for that would leave `mark`. The missing object's id,
737    /// or `None` without git (or when the object isn't a loose file).
738    fn repository_missing_an_object(dir: &std::path::Path, mark: &std::path::Path) -> Option<String> {
739        test_git(dir, &["init", "-q"])?;
740        std::fs::write(dir.join("a.txt"), "a\n").unwrap();
741        test_git(dir, &["add", "."])?;
742        test_git(dir, &["commit", "-qm", "x"])?;
743        let tree = test_git(dir, &["rev-parse", "HEAD^{tree}"])?;
744        let source = dir.join("source");
745        std::fs::create_dir_all(&source).unwrap();
746        let slashes = |p: &std::path::Path| p.display().to_string().replace('\\', "/");
747        for (key, value) in [
748            ("core.repositoryformatversion", "1".to_string()),
749            ("extensions.partialClone", "origin".to_string()),
750            ("remote.origin.url", slashes(&source)),
751            ("remote.origin.promisor", "true".to_string()),
752            ("remote.origin.uploadpack", format!("echo ran > '{}' ; true", slashes(mark))),
753            ("protocol.allow", "always".to_string()),
754            ("protocol.file.allow", "always".to_string()),
755        ] {
756            test_git(dir, &["config", key, &value])?;
757        }
758        let object = dir.join(".git").join("objects").join(&tree[..2]).join(&tree[2..]);
759        std::fs::remove_file(object).ok()?;
760        Some(tree)
761    }
762
763    #[test]
764    fn every_git_run_is_set_to_fetch_nothing_and_allow_no_transport() {
765        let cmd = git_command(".", &["status"]);
766        let env: std::collections::HashMap<String, Option<String>> = cmd
767            .as_std()
768            .get_envs()
769            .map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned())))
770            .collect();
771        assert_eq!(env.get("GIT_NO_LAZY_FETCH"), Some(&Some("1".to_string())));
772        assert_eq!(env.get("GIT_ALLOW_PROTOCOL"), Some(&Some(String::new())), "set, and empty: no protocol is allowed");
773    }
774
775    /// The status read fetches nothing and starts no transport, whatever the
776    /// repository's own config allows.
777    #[tokio::test]
778    async fn a_status_read_never_fetches_and_allows_no_transport() {
779        let dir = tempfile::tempdir().unwrap();
780        let mark = dir.path().join("fetch-ran");
781        if repository_missing_an_object(dir.path(), &mark).is_none() {
782            return; // No git on this machine.
783        }
784        let s = git_status(&dir.path().to_string_lossy()).await;
785        assert!(s.in_repo && s.entries.is_empty(), "{s:?}");
786        assert!(!mark.exists(), "the status read went to fetch the missing object");
787    }
788
789    /// The same for the one-line reads (the checks of a ref the work facts make).
790    #[tokio::test]
791    async fn a_ref_check_never_fetches_and_allows_no_transport() {
792        let dir = tempfile::tempdir().unwrap();
793        let mark = dir.path().join("fetch-ran");
794        let Some(tree) = repository_missing_an_object(dir.path(), &mark) else {
795            return; // No git on this machine.
796        };
797        let found = safe_git_line(&dir.path().to_string_lossy(), &["rev-parse", "--verify", "--quiet", &format!("{tree}^{{tree}}")]).await;
798        assert_eq!(found, None, "the object is not there");
799        assert!(!mark.exists(), "the ref check went to fetch the missing object");
800    }
801
802    /// A repository with a commit, a changed file and a new one: every read here has something to say about it.
803    fn repository_with_changes(dir: &std::path::Path) -> Option<()> {
804        test_git(dir, &["init", "-q"])?;
805        std::fs::write(dir.join("tracked.txt"), "a").unwrap();
806        test_git(dir, &["add", "."])?;
807        test_git(dir, &["commit", "-qm", "x"])?;
808        std::fs::write(dir.join("tracked.txt"), "b").unwrap();
809        std::fs::write(dir.join("new.txt"), "n").unwrap();
810        Some(())
811    }
812
813    /// A temp folder that is a repository with changes on the host, its `sub` folder, and a name no other
814    /// test's folder has.
815    fn host_repository() -> (tempfile::TempDir, String, String, String) {
816        let dir = tempfile::tempdir().unwrap();
817        let _ = repository_with_changes(dir.path());
818        let inner = dir.path().join("sub");
819        std::fs::create_dir_all(&inner).unwrap();
820        let (top, sub) = (dir.path().to_string_lossy().into_owned(), inner.to_string_lossy().into_owned());
821        let name = dir.path().file_name().unwrap().to_string_lossy().into_owned();
822        (dir, top, sub, name)
823    }
824
825    /// For a folder a container agent can write, and a folder inside it, every read is git run inside the
826    /// agent's container at the same folder there, with the settings and the environment of a host run, and
827    /// no git is started on the host: the Files pane's markers, the status and the one-line reads say what
828    /// the container's git says, not what the host's would.
829    #[tokio::test]
830    async fn git_facts_of_a_container_agent_are_read_inside_its_container() {
831        let (dir, top, sub, name) = host_repository();
832        // As any other folder, the host's git reads it (where there is one).
833        let on_host = git_status(&top).await;
834        let host_runs = test_support::host_runs_for(&name);
835
836        let container = format!("agentmux-{name}");
837        container_folders::add_for_test(dir.path(), &container, "/workspace");
838        let seen = test_support::container_git(&container);
839
840        let s = git_status(&top).await;
841        assert!(s.in_repo && s.error.is_none(), "{s:?}");
842        assert_eq!(s.branch.as_deref(), Some("inside"));
843        let names: Vec<&str> = s.entries.iter().map(|e| e.name.as_str()).collect();
844        assert_eq!(names, vec!["in-container.txt", "sub"], "the container's changes, not the host's: {on_host:?}");
845        let below = git_status(&sub).await;
846        assert_eq!(below.entries.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), vec!["new-inside.txt"]);
847        assert_eq!(safe_git_line(&sub, &["remote", "get-url", "origin"]).await.as_deref(), Some("https://github.com/AgentMuxAI/Inside.git"));
848        assert!(safe_status_porcelain(&top, &[]).await.is_ok());
849
850        // The repository's top folder comes back as the host folder it is bound from.
851        let root = safe_toplevel(&sub).await.expect("inside a repository");
852        assert!(root.ends_with(&name), "{root}");
853        assert!(matches!(container_folders::place(&root), Place::Inside(at) if at.dir == "/workspace"));
854
855        let seen = seen.lock().clone();
856        assert!(seen.len() >= 8, "{seen:?}");
857        for (argv, env) in &seen {
858            assert_eq!(&argv[..2], ["git", "-C"]);
859            assert!(argv[2] == "/workspace" || argv[2] == "/workspace/sub", "the same folder, as the container names it: {argv:?}");
860            assert_eq!(&argv[3..8], ["-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "--no-optional-locks"]);
861            for pair in [("GIT_NO_LAZY_FETCH", "1"), ("GIT_ALLOW_PROTOCOL", ""), ("GIT_TERMINAL_PROMPT", "0"), ("GIT_OPTIONAL_LOCKS", "0")] {
862                assert!(env.contains(&(pair.0.to_string(), pair.1.to_string())), "{pair:?} is set inside too: {env:?}");
863            }
864        }
865        assert_eq!(test_support::host_runs_for(&name), host_runs, "git was started on the host for a container agent's folder");
866    }
867
868    /// While the agent's container is not running there are no facts, and still no git on the host.
869    #[tokio::test]
870    async fn a_container_agents_folder_has_no_git_facts_while_its_container_is_not_running() {
871        let (dir, top, sub, name) = host_repository();
872        container_folders::add_for_test(dir.path(), &format!("agentmux-stopped-{name}"), "/workspace");
873        for folder in [&top, &sub] {
874            let s = git_status(folder).await;
875            assert!(!s.in_repo && s.entries.is_empty() && s.error.is_none(), "{s:?}");
876            assert_eq!(safe_git_line(folder, &["rev-parse", "--show-prefix"]).await, None);
877            assert_eq!(safe_toplevel(folder).await, None);
878            assert!(matches!(safe_status_porcelain(folder, &[]).await, Err(StatusError::Settings(_))), "no status run");
879        }
880        assert_eq!(test_support::host_runs_for(&name), 0, "git was started on the host for a container agent's folder");
881    }
882
883    #[tokio::test]
884    async fn a_folder_outside_any_repository_has_no_markers() {
885        let dir = tempfile::tempdir().unwrap();
886        let s = git_status(&dir.path().to_string_lossy()).await;
887        // A temp dir can sit inside a repository on some machines; then it has
888        // markers, which is also right. What must hold: no error either way.
889        assert!(s.error.is_none(), "{s:?}");
890    }
891}