Skip to main content

agentmux_srv_core/backend/work_facts/
git.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The git half of an agent's work facts: repository, branch and
5//! uncommitted files in its working folder.
6//!
7//! git never runs on a request: a background loop probes each agent's folder
8//! and the request reads the cache. An entry is re-probed once it is
9//! [`REFRESH_AFTER_MS`] old or the agent's folder changed. Distinct folders
10//! are probed concurrently ([`MAX_CONCURRENT_PROBES`] at a time) and a probe
11//! is abandoned after [`PROBE_TIMEOUT`], so with a handful of folders an
12//! entry is under ~30 s old; many slow repositories can make it older, which
13//! is why every answer carries `git_checked_ms`. Every git run goes through
14//! `fs_ops::git`'s safe runner (the repository's own fsmonitor and filters
15//! are off, nothing prompts, the index isn't written, a slow run is killed
16//! after a few seconds). For a folder a container agent can write, that
17//! runner runs git inside the agent's container and never on the host, so a
18//! container agent's facts are its own git's.
19
20use std::collections::{HashMap, HashSet};
21use std::future::Future;
22use std::sync::Arc;
23use std::time::Duration;
24
25use futures_util::StreamExt;
26
27use serde::{Deserialize, Serialize};
28
29use crate::backend::fs_ops::git::{parse_porcelain_v2, safe_git_line, safe_status_porcelain, safe_toplevel};
30use crate::backend::rpc_types::FsGitState;
31use crate::backend::storage::store::Store;
32
33use super::paths::{normalize_path, normalize_repo};
34
35/// How often the loop looks for entries to refresh.
36const TICK: Duration = Duration::from_secs(5);
37
38/// An entry this old is probed again on the next tick.
39pub const REFRESH_AFTER_MS: u64 = 20_000;
40
41/// Most probes running at once: each is a few git processes.
42const MAX_CONCURRENT_PROBES: usize = 4;
43
44/// A probe (several git runs, each with its own 4 s limit) is abandoned
45/// after this and the folder reads as having no git facts until the next.
46const PROBE_TIMEOUT: Duration = Duration::from_secs(8);
47
48/// Most uncommitted paths kept per agent; [`GitFacts::dirty_count`] is the
49/// real total.
50const MAX_DIRTY_FILES: usize = 500;
51
52/// What git says about one working folder.
53#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
54pub struct GitFacts {
55    /// The repository's top folder, normalized.
56    pub root: String,
57    /// `owner/repo` from the `origin` remote; `None` without one.
58    pub repo: Option<String>,
59    /// `None` when detached or unknown.
60    pub branch: Option<String>,
61    /// Repository-relative paths with uncommitted changes (staged, unstaged,
62    /// untracked; an untracked folder is reported whole, ending in `/`).
63    pub dirty_files: Vec<String>,
64    pub dirty_count: usize,
65    /// Why the status part is missing, when it is.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub error: Option<String>,
68    pub checked_ms: u64,
69}
70
71/// Probe `dir`: `None` when it isn't inside a git repository (or git is
72/// missing or too slow).
73pub async fn probe(dir: &str, now_ms: u64) -> Option<GitFacts> {
74    let root = normalize_path(&safe_toplevel(dir).await?);
75    let repo = safe_git_line(&root, &["remote", "get-url", "origin"])
76        .await
77        .and_then(|url| normalize_repo(&url));
78    let mut facts = GitFacts { root, repo, checked_ms: now_ms, ..Default::default() };
79    match safe_status_porcelain(&facts.root, &[]).await {
80        Ok(out) => {
81            let p = parse_porcelain_v2(&out);
82            facts.branch = p.branch;
83            let dirty: Vec<String> =
84                p.records.into_iter().filter(|r| r.state != FsGitState::Ignored).map(|r| r.path).collect();
85            facts.dirty_count = dirty.len();
86            facts.dirty_files = dirty.into_iter().take(MAX_DIRTY_FILES).collect();
87        }
88        Err(e) => {
89            facts.branch = safe_git_line(&facts.root, &["branch", "--show-current"]).await;
90            facts.error = Some(match e {
91                crate::backend::fs_ops::git::StatusError::Settings(what) => what.to_string(),
92                crate::backend::fs_ops::git::StatusError::Git(m) => m,
93            });
94        }
95    }
96    Some(facts)
97}
98
99#[derive(Debug, Clone)]
100struct Entry {
101    dir: String,
102    facts: Option<GitFacts>,
103    checked_ms: u64,
104}
105
106/// Probe results per block id, with the folder each was taken in.
107#[derive(Debug, Default)]
108pub struct GitCache {
109    entries: HashMap<String, Entry>,
110}
111
112impl GitCache {
113    /// Whether `block`'s folder `dir` should be probed now.
114    pub fn needs_probe(&self, block: &str, dir: &str, now_ms: u64) -> bool {
115        match self.entries.get(block) {
116            None => true,
117            Some(e) => e.dir != dir || now_ms.saturating_sub(e.checked_ms) >= REFRESH_AFTER_MS,
118        }
119    }
120
121    pub fn put(&mut self, block: &str, dir: &str, facts: Option<GitFacts>, now_ms: u64) {
122        self.entries.insert(block.to_string(), Entry { dir: dir.to_string(), facts, checked_ms: now_ms });
123    }
124
125    /// The facts for `block`, only if they were taken in `dir`: after a `cd`
126    /// the old repository is no longer what the agent is working in.
127    pub fn get(&self, block: &str, dir: &str) -> Option<GitFacts> {
128        self.entries.get(block).filter(|e| e.dir == dir).and_then(|e| e.facts.clone())
129    }
130
131    pub fn retain(&mut self, live: &HashSet<String>) {
132        self.entries.retain(|b, _| live.contains(b));
133    }
134}
135
136fn cache() -> &'static parking_lot::RwLock<GitCache> {
137    static CACHE: std::sync::LazyLock<parking_lot::RwLock<GitCache>> = std::sync::LazyLock::new(Default::default);
138    &CACHE
139}
140
141/// The cached facts for `block` in `dir` (see [`GitCache::get`]).
142pub fn cached(block: &str, dir: &str) -> Option<GitFacts> {
143    cache().read().get(block, dir)
144}
145
146/// One refresh pass: probe each due `(block, folder)` in `folders`, every
147/// distinct folder once and at most [`MAX_CONCURRENT_PROBES`] at a time,
148/// each abandoned after `timeout`, and store the results stamped `now_ms`.
149pub async fn refresh_once<F, Fut>(
150    cache: &parking_lot::RwLock<GitCache>,
151    folders: Vec<(String, String)>,
152    now_ms: u64,
153    timeout: Duration,
154    probe: F,
155) where
156    F: Fn(String) -> Fut,
157    Fut: Future<Output = Option<GitFacts>>,
158{
159    let due: Vec<(String, String)> = {
160        let c = cache.read();
161        folders.into_iter().filter(|(b, d)| c.needs_probe(b, d, now_ms)).collect()
162    };
163    let mut dirs: Vec<String> = due.iter().map(|(_, d)| d.clone()).collect();
164    dirs.sort();
165    dirs.dedup();
166    let results: HashMap<String, Option<GitFacts>> = futures_util::stream::iter(dirs)
167        .map(|dir| {
168            let fut = probe(dir.clone());
169            async move { (dir, tokio::time::timeout(timeout, fut).await.ok().flatten()) }
170        })
171        .buffer_unordered(MAX_CONCURRENT_PROBES)
172        .collect()
173        .await;
174    let mut c = cache.write();
175    for (block, dir) in due {
176        c.put(&block, &dir, results.get(&dir).cloned().flatten(), now_ms);
177    }
178}
179
180/// Keep every registered agent's git facts fresh. Never returns.
181pub async fn run_git_refresh_loop(mstore: Arc<Store>) {
182    crate::backend::fs_ops::container_folders::install(&mstore);
183    let mut ticker = tokio::time::interval(TICK);
184    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
185    loop {
186        ticker.tick().await;
187        let agents = crate::backend::reactive::get_global_handler().list_agents();
188        let live: HashSet<String> = agents.iter().map(|a| a.block_id.clone()).collect();
189        cache().write().retain(&live);
190
191        // Block meta lives in the store: read it off the async workers.
192        let store = mstore.clone();
193        let Ok(folders) = tokio::task::spawn_blocking(move || {
194            let home = dirs::home_dir();
195            agents
196                .iter()
197                .filter_map(|a| super::folder_of(&store, home.as_deref(), a).map(|d| (a.block_id.clone(), d)))
198                .collect::<Vec<_>>()
199        })
200        .await
201        else {
202            continue;
203        };
204
205        let now = agentmux_common::time::now_ms_u64();
206        refresh_once(cache(), folders, now, PROBE_TIMEOUT, |dir| async move { probe(&dir, now).await }).await;
207    }
208}
209
210/// A branch name taken from a command, safe to hand git: no option, range or
211/// whitespace.
212fn plain_branch(name: &str) -> bool {
213    !name.is_empty() && !name.starts_with('-') && !name.contains("..") && !name.contains(char::is_whitespace)
214}
215
216/// The first of `candidates` that names a commit in `root`.
217async fn first_ref(root: &str, candidates: &[String]) -> Option<String> {
218    for c in candidates {
219        if safe_git_line(root, &["rev-parse", "--verify", "--quiet", &format!("{c}^{{commit}}")]).await.is_some() {
220            return Some(c.clone());
221        }
222    }
223    None
224}
225
226/// The branch's `gh-merge-base` setting (gh's base for a PR from it), if set.
227pub async fn merge_base_setting(root: &str, branch: &str) -> Option<String> {
228    if !plain_branch(branch) {
229        return None;
230    }
231    safe_git_line(root, &["config", "--get", &format!("branch.{branch}.gh-merge-base")]).await.filter(|b| plain_branch(b))
232}
233
234/// The files a PR from `head` into `base` changes in `root`: `git diff
235/// --name-only base...head`, the base being `origin/<base>` (or a local
236/// `<base>`), else the default branch (`origin/HEAD`, `origin/main`,
237/// `origin/master`), and the head a local branch, else `origin/<head>`. Empty
238/// when either can't be found, on the base itself, or when git can't say in
239/// [`PROBE_TIMEOUT`]. A diff of two commits: no working-tree filter runs.
240pub async fn branch_files(root: &str, base: Option<&str>, head: &str) -> Vec<String> {
241    branch_diff_names(root, base, head, None).await
242}
243
244/// The files that PR deletes (the `--diff-filter=D` part of
245/// [`branch_files`]). A release PR deletes every changeset it consumes.
246pub async fn branch_deleted_files(root: &str, base: Option<&str>, head: &str) -> Vec<String> {
247    branch_diff_names(root, base, head, Some("--diff-filter=D")).await
248}
249
250/// The refs a PR's base can be, in the order tried.
251fn base_candidates(base: Option<&str>) -> Vec<String> {
252    match base {
253        Some(b) => vec![format!("origin/{b}"), b.to_string()],
254        None => ["origin/HEAD", "origin/main", "origin/master"].iter().map(|s| s.to_string()).collect(),
255    }
256}
257
258async fn branch_diff_names(root: &str, base: Option<&str>, head: &str, filter: Option<&str>) -> Vec<String> {
259    if !plain_branch(head) || base.is_some_and(|b| !plain_branch(b)) {
260        return Vec::new();
261    }
262    let files = async {
263        let base = first_ref(root, &base_candidates(base)).await?;
264        let head = first_ref(root, &[format!("refs/heads/{head}"), format!("origin/{head}")]).await?;
265        let range = format!("{base}...{head}");
266        let mut args = vec!["diff", "--name-only"];
267        args.extend(filter);
268        args.push(&range);
269        let out = safe_git_line(root, &args).await?;
270        Some(out.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect::<Vec<_>>())
271    };
272    tokio::time::timeout(PROBE_TIMEOUT, files).await.ok().flatten().unwrap_or_default()
273}
274
275/// Whether every commit of `branch` is already in the default branch of
276/// `root` (`origin/HEAD`, `origin/main`, `origin/master`): a merged or
277/// fast-forwarded branch. False when either can't be found. A squash merge
278/// leaves the tip outside the default branch: [`landed_files`] sees those.
279pub async fn branch_contained_in_default(root: &str, branch: &str) -> bool {
280    if !plain_branch(branch) {
281        return false;
282    }
283    let check = async {
284        let base = first_ref(root, &base_candidates(None)).await?;
285        let head = first_ref(root, &[format!("refs/heads/{branch}"), format!("origin/{branch}")]).await?;
286        let n = safe_git_line(root, &["rev-list", "--count", &format!("{base}..{head}")]).await?;
287        Some(n.trim() == "0")
288    };
289    tokio::time::timeout(PROBE_TIMEOUT, check).await.ok().flatten().unwrap_or(false)
290}
291
292/// Of `files` (which `their_branch` changes in `their_root`), the ones whose
293/// content on that branch is exactly what the PR's base has in `my_root`:
294/// the change already landed there (a squash merge leaves the branch tip
295/// outside the base, but the blobs are the same), so it is no overlap. Blob
296/// ids are content hashes, comparable across clones. A file either side can't
297/// be read is kept.
298pub async fn landed_files(
299    my_root: &str,
300    base: Option<&str>,
301    their_root: &str,
302    their_branch: &str,
303    files: &[String],
304) -> Vec<String> {
305    if files.is_empty() || !plain_branch(their_branch) || base.is_some_and(|b| !plain_branch(b)) {
306        return Vec::new();
307    }
308    let check = async {
309        let my_base = first_ref(my_root, &base_candidates(base)).await?;
310        let their_head = first_ref(their_root, &[format!("refs/heads/{their_branch}"), format!("origin/{their_branch}")]).await?;
311        let mut landed = Vec::new();
312        for f in files {
313            if f.starts_with('-') || f.contains(['\n', ':']) {
314                continue;
315            }
316            let (mine, theirs) = (
317                safe_git_line(my_root, &["rev-parse", "--verify", "--quiet", &format!("{my_base}:{f}")]).await,
318                safe_git_line(their_root, &["rev-parse", "--verify", "--quiet", &format!("{their_head}:{f}")]).await,
319            );
320            if mine.is_some() && mine == theirs {
321                landed.push(f.clone());
322            }
323        }
324        Some(landed)
325    };
326    tokio::time::timeout(PROBE_TIMEOUT, check).await.ok().flatten().unwrap_or_default()
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    fn git(dir: &std::path::Path, args: &[&str]) {
334        use agentmux_common::win32::NoWindow;
335        let ok = std::process::Command::new("git")
336            .args(args)
337            .current_dir(dir)
338            .env("GIT_AUTHOR_NAME", "t")
339            .env("GIT_AUTHOR_EMAIL", "t@t")
340            .env("GIT_COMMITTER_NAME", "t")
341            .env("GIT_COMMITTER_EMAIL", "t@t")
342            .no_window()
343            .output()
344            .map(|o| o.status.success())
345            .unwrap_or(false);
346        assert!(ok, "git {args:?} failed");
347    }
348
349    /// A temp repository gives its repository, branch and uncommitted files.
350    #[tokio::test]
351    async fn a_temp_repo_gives_repo_branch_and_dirty_files() {
352        let tmp = tempfile::tempdir().unwrap();
353        let dir = tmp.path();
354        git(dir, &["init", "-q", "-b", "feat/x"]);
355        git(dir, &["remote", "add", "origin", "https://github.com/AgentMuxAI/Example.git"]);
356        std::fs::create_dir_all(dir.join("src")).unwrap();
357        std::fs::write(dir.join("src/a.rs"), "a").unwrap();
358        git(dir, &["add", "."]);
359        git(dir, &["-c", "commit.gpgsign=false", "commit", "-q", "-m", "init"]);
360        std::fs::write(dir.join("src/a.rs"), "changed").unwrap();
361        std::fs::create_dir_all(dir.join("new")).unwrap();
362        std::fs::write(dir.join("new/b.rs"), "b").unwrap();
363
364        let sub = dir.join("src");
365        let facts = probe(&sub.to_string_lossy(), 42).await.expect("inside a repository");
366        assert_eq!(facts.repo.as_deref(), Some("agentmuxai/example"));
367        assert_eq!(facts.branch.as_deref(), Some("feat/x"));
368        let mut dirty = facts.dirty_files.clone();
369        dirty.sort();
370        assert_eq!(dirty, vec!["new/".to_string(), "src/a.rs".to_string()]);
371        assert_eq!(facts.dirty_count, 2);
372        assert_eq!(facts.checked_ms, 42);
373        let name = dir.file_name().unwrap().to_string_lossy().into_owned();
374        assert!(facts.root.ends_with(&name), "root {} is the temp repository, not its src folder", facts.root);
375    }
376
377    /// A container agent's facts are what git says inside its container, and the helpers that compare
378    /// branches run there too: for its folder no git is started on the host.
379    #[tokio::test]
380    async fn a_container_agents_git_facts_are_read_inside_its_container() {
381        use crate::backend::fs_ops::git::test_support;
382        let tmp = tempfile::tempdir().unwrap();
383        let sub = tmp.path().join("sub");
384        std::fs::create_dir_all(&sub).unwrap();
385        let name = tmp.path().file_name().unwrap().to_string_lossy().into_owned();
386        let container = format!("agentmux-{name}");
387        crate::backend::fs_ops::container_folders::add_for_test(tmp.path(), &container, "/workspace");
388        let seen = test_support::container_git(&container);
389
390        let facts = probe(&sub.to_string_lossy(), 42).await.expect("the container's git has facts");
391        assert_eq!(facts.repo.as_deref(), Some("agentmuxai/inside"));
392        assert_eq!(facts.branch.as_deref(), Some("inside"));
393        assert_eq!(facts.dirty_files, vec!["in-container.txt".to_string(), "sub/new-inside.txt".to_string()]);
394        assert_eq!(facts.error, None);
395        assert!(facts.root.ends_with(&name), "the host folder the repository is bound from: {}", facts.root);
396
397        // The overlap and PR helpers, in the root the facts gave.
398        assert!(branch_files(&facts.root, None, "inside").await.is_empty());
399        assert!(!branch_contained_in_default(&facts.root, "inside").await);
400        assert_eq!(merge_base_setting(&facts.root, "inside").await, None);
401        assert!(landed_files(&facts.root, None, &facts.root, "inside", &["a.rs".to_string()]).await.is_empty());
402
403        let seen = seen.lock().clone();
404        assert!(seen.iter().any(|(argv, _)| argv.iter().any(|a| a == "--verify")), "the helpers asked the container: {seen:?}");
405        assert!(seen.iter().all(|(argv, _)| argv[2] == "/workspace" || argv[2] == "/workspace/sub"), "{seen:?}");
406        assert_eq!(test_support::host_runs_for(&name), 0, "git was started on the host for a container agent's folder");
407    }
408
409    #[tokio::test]
410    async fn a_folder_outside_any_repository_has_no_git_facts() {
411        let tmp = tempfile::tempdir().unwrap();
412        // A temp folder might sit inside a repository on a dev machine; only
413        // assert when git agrees it doesn't.
414        if let Some(f) = probe(&tmp.path().to_string_lossy(), 1).await {
415            assert!(!f.root.is_empty());
416        }
417    }
418
419    /// The 30 s cache: an entry is reused until it is REFRESH_AFTER_MS old,
420    /// and dropped at once when the agent changes folder.
421    #[test]
422    fn the_cache_is_reused_until_stale_or_the_folder_changes() {
423        let mut c = GitCache::default();
424        assert!(c.needs_probe("b1", "/r", 0), "never probed");
425        let facts = GitFacts { root: "/r".into(), checked_ms: 1_000, ..Default::default() };
426        c.put("b1", "/r", Some(facts.clone()), 1_000);
427        assert!(!c.needs_probe("b1", "/r", 1_000 + REFRESH_AFTER_MS - 1));
428        assert!(c.needs_probe("b1", "/r", 1_000 + REFRESH_AFTER_MS));
429        assert!(c.needs_probe("b1", "/other", 1_001), "a cd re-probes at once");
430        assert_eq!(c.get("b1", "/r"), Some(facts));
431        assert_eq!(c.get("b1", "/other"), None, "facts from the old folder aren't shown");
432
433        c.put("b2", "/n", None, 1_000);
434        assert!(!c.needs_probe("b2", "/n", 2_000), "a folder outside git is cached too");
435        c.retain(&HashSet::from(["b2".to_string()]));
436        assert_eq!(c.get("b1", "/r"), None, "a gone agent's entry is dropped");
437    }
438
439    fn facts_for(dir: &str) -> GitFacts {
440        GitFacts { root: dir.to_string(), ..Default::default() }
441    }
442
443    /// The loop's real pass: distinct folders are probed concurrently (at
444    /// most MAX_CONCURRENT_PROBES), a shared folder once, a fresh entry not
445    /// at all, and a hung probe is abandoned rather than holding up the rest.
446    #[tokio::test(start_paused = true)]
447    async fn a_pass_probes_due_folders_concurrently_and_abandons_a_hung_one() {
448        use std::sync::atomic::{AtomicUsize, Ordering};
449        let cache = parking_lot::RwLock::new(GitCache::default());
450        cache.write().put("fresh", "/fresh", Some(facts_for("/fresh")), 1_000);
451
452        let mut folders: Vec<(String, String)> = (0..8).map(|i| (format!("b{i}"), format!("/r{i}"))).collect();
453        folders.push(("shares-r0".into(), "/r0".into()));
454        folders.push(("fresh".into(), "/fresh".into()));
455        folders.push(("hung".into(), "/hung".into()));
456
457        let (running, peak, calls) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
458        let start = tokio::time::Instant::now();
459        refresh_once(&cache, folders, 2_000, Duration::from_secs(8), |dir| {
460            let (running, peak, calls) = (&running, &peak, &calls);
461            async move {
462                calls.fetch_add(1, Ordering::SeqCst);
463                let now = running.fetch_add(1, Ordering::SeqCst) + 1;
464                peak.fetch_max(now, Ordering::SeqCst);
465                let wait = if dir == "/hung" { 600 } else { 2 };
466                tokio::time::sleep(Duration::from_secs(wait)).await;
467                running.fetch_sub(1, Ordering::SeqCst);
468                Some(facts_for(&dir))
469            }
470        })
471        .await;
472
473        assert_eq!(calls.load(Ordering::SeqCst), 9, "8 folders + the hung one; shared and fresh ones skipped");
474        assert_eq!(peak.load(Ordering::SeqCst), MAX_CONCURRENT_PROBES);
475        // Eight 2 s probes four at a time beside one 8 s timeout finish in
476        // about 8 s; one at a time would take 24 s.
477        assert!(start.elapsed() <= Duration::from_secs(9), "took {:?}", start.elapsed());
478        let c = cache.read();
479        assert_eq!(c.get("b3", "/r3"), Some(facts_for("/r3")));
480        assert_eq!(c.get("shares-r0", "/r0"), Some(facts_for("/r0")));
481        assert_eq!(c.get("hung", "/hung"), None, "abandoned");
482        assert!(!c.needs_probe("hung", "/hung", 2_001), "and not retried until it is due again");
483        assert_eq!(c.get("fresh", "/fresh"), Some(facts_for("/fresh")));
484    }
485
486    #[tokio::test]
487    async fn a_branch_lists_the_files_it_changes_since_the_default_branch() {
488        let tmp = std::env::temp_dir().join(format!("wf-branch-files-{}-{}", std::process::id(), agentmux_common::time::now_ms()));
489        std::fs::create_dir_all(&tmp).unwrap();
490        git(&tmp, &["init", "-q", "-b", "main"]);
491        git(&tmp, &["config", "user.email", "t@t"]);
492        git(&tmp, &["config", "user.name", "t"]);
493        std::fs::write(tmp.join("base.rs"), "a").unwrap();
494        git(&tmp, &["add", "."]);
495        git(&tmp, &["commit", "-q", "-m", "base"]);
496        git(&tmp, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
497        let root = tmp.to_string_lossy().to_string();
498        assert!(branch_files(&root, None, "main").await.is_empty(), "the default branch itself: nothing");
499        git(&tmp, &["checkout", "-q", "-b", "agent/x"]);
500        std::fs::create_dir_all(tmp.join("src")).unwrap();
501        std::fs::write(tmp.join("src/new.rs"), "b").unwrap();
502        std::fs::write(tmp.join("base.rs"), "changed").unwrap();
503        git(&tmp, &["add", "."]);
504        git(&tmp, &["commit", "-q", "-m", "work"]);
505        let both = vec!["base.rs".to_string(), "src/new.rs".to_string()];
506        assert_eq!(branch_files(&root, None, "agent/x").await, both);
507        // A PR for another head, from wherever HEAD is.
508        git(&tmp, &["checkout", "-q", "main"]);
509        assert_eq!(branch_files(&root, None, "agent/x").await, both, "--head, not the checked-out branch");
510        // A stacked PR: based on agent/x, it changes only its own commit.
511        git(&tmp, &["checkout", "-q", "-b", "agent/y", "agent/x"]);
512        std::fs::write(tmp.join("y.rs"), "y").unwrap();
513        git(&tmp, &["add", "."]);
514        git(&tmp, &["commit", "-q", "-m", "stacked"]);
515        assert_eq!(branch_files(&root, Some("agent/x"), "agent/y").await, vec!["y.rs".to_string()]);
516        git(&tmp, &["config", "branch.agent/y.gh-merge-base", "agent/x"]);
517        assert_eq!(merge_base_setting(&root, "agent/y").await.as_deref(), Some("agent/x"));
518        assert!(branch_files(&root, None, "no/such/branch").await.is_empty(), "a head that can't be found");
519        assert!(branch_files(&root, None, "--output=x").await.is_empty(), "never a flag");
520        let _ = std::fs::remove_dir_all(&tmp);
521    }
522
523    /// A merged branch, a squash-merged branch and a release's deleted
524    /// changesets are told apart from work still in flight.
525    #[tokio::test]
526    async fn merged_squashed_and_deleted_files_are_told_from_work_in_flight() {
527        let tmp = std::env::temp_dir().join(format!("wf-landed-{}-{}", std::process::id(), agentmux_common::time::now_ms()));
528        std::fs::create_dir_all(tmp.join(".changesets")).unwrap();
529        git(&tmp, &["init", "-q", "-b", "main"]);
530        git(&tmp, &["config", "user.email", "t@t"]);
531        git(&tmp, &["config", "user.name", "t"]);
532        std::fs::write(tmp.join("base.rs"), "a").unwrap();
533        git(&tmp, &["add", "."]);
534        git(&tmp, &["commit", "-q", "-m", "base"]);
535        git(&tmp, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
536        let root = tmp.to_string_lossy().to_string();
537
538        git(&tmp, &["checkout", "-q", "-b", "agent/x"]);
539        std::fs::write(tmp.join("base.rs"), "x").unwrap();
540        std::fs::write(tmp.join("other.rs"), "o").unwrap();
541        std::fs::write(tmp.join(".changesets/1.md"), "c").unwrap();
542        git(&tmp, &["add", "."]);
543        git(&tmp, &["commit", "-q", "-m", "work"]);
544        assert!(!branch_contained_in_default(&root, "agent/x").await, "not merged yet");
545        assert!(!branch_contained_in_default(&root, "no/such").await, "unknown branch");
546        assert!(!branch_contained_in_default(&root, "--output=x").await, "never a flag");
547        let files = vec!["base.rs".to_string(), "other.rs".to_string(), ".changesets/1.md".to_string()];
548        assert!(landed_files(&root, None, &root, "agent/x", &files).await.is_empty(), "nothing on main yet");
549
550        // Squash merge: main gets the same content in a new commit, the
551        // branch tip stays outside it; other.rs is not part of it.
552        git(&tmp, &["checkout", "-q", "main"]);
553        std::fs::create_dir_all(tmp.join(".changesets")).unwrap();
554        std::fs::write(tmp.join("base.rs"), "x").unwrap();
555        std::fs::write(tmp.join(".changesets/1.md"), "c").unwrap();
556        git(&tmp, &["add", "."]);
557        git(&tmp, &["commit", "-q", "-m", "squash"]);
558        git(&tmp, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
559        assert!(!branch_contained_in_default(&root, "agent/x").await, "a squash leaves the tip outside");
560        assert_eq!(
561            landed_files(&root, None, &root, "agent/x", &files).await,
562            vec!["base.rs".to_string(), ".changesets/1.md".to_string()],
563            "same content on main: landed; other.rs is not"
564        );
565
566        // A release PR deletes the consumed changeset.
567        git(&tmp, &["checkout", "-q", "-b", "agent/release"]);
568        git(&tmp, &["rm", "-q", ".changesets/1.md"]);
569        git(&tmp, &["commit", "-q", "-m", "release"]);
570        assert_eq!(branch_deleted_files(&root, None, "agent/release").await, vec![".changesets/1.md".to_string()]);
571        assert_eq!(branch_files(&root, None, "agent/release").await, vec![".changesets/1.md".to_string()]);
572        assert!(branch_deleted_files(&root, None, "agent/x").await.is_empty(), "a branch that deletes nothing");
573
574        // A fast-forward merge: the branch is inside main.
575        git(&tmp, &["update-ref", "refs/remotes/origin/main", "agent/x"]);
576        assert!(branch_contained_in_default(&root, "agent/x").await);
577        let _ = std::fs::remove_dir_all(&tmp);
578    }
579}