Skip to main content

magi/
git.rs

1//! Git plumbing.
2//!
3//! magi drives the `git` CLI rather than linking a library: every operation it
4//! needs is a one-liner, and shelling out keeps the behaviour identical to what
5//! the operator sees when they inspect a run by hand.
6use std::path::{Path, PathBuf};
7use std::process::Stdio;
8
9use crate::proc::Quiet as _;
10use anyhow::{Context as _, Result, bail, ensure};
11use tokio::process::Command;
12
13/// Output of a completed `git` invocation.
14#[derive(Debug)]
15pub struct GitOut {
16    /// Exit status code, if the process was not killed by a signal.
17    pub code: Option<i32>,
18    /// Captured stdout, trailing newline trimmed.
19    pub stdout: String,
20    /// Captured stderr, trailing newline trimmed.
21    pub stderr: String,
22}
23
24impl GitOut {
25    /// Did the command succeed?
26    pub fn ok(&self) -> bool {
27        self.code == Some(0)
28    }
29}
30
31/// Run `git` in `cwd` with `args`, returning the captured output regardless of
32/// exit status.
33pub async fn git_raw(cwd: &Path, args: &[&str]) -> Result<GitOut> {
34    #[cfg(test)]
35    crate::web::request_cost::git();
36    let out = Command::new("git")
37        .args(args)
38        .current_dir(cwd)
39        .quiet()
40        // A hook that opens an editor or a credential prompt would hang a
41        // headless run forever.
42        .env("GIT_TERMINAL_PROMPT", "0")
43        .env("GIT_EDITOR", "true")
44        .stdin(Stdio::null())
45        .output()
46        .await
47        .with_context(|| format!("spawn git {}", args.join(" ")))?;
48    Ok(GitOut {
49        code: out.status.code(),
50        stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
51        stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
52    })
53}
54
55/// Native filesystem paths stay canonical internally; Git for Windows needs
56/// conventional drive/UNC spelling for path arguments instead of `\\?\`.
57pub(crate) fn path_arg(path: &Path) -> String {
58    #[cfg(windows)]
59    let unicode = path.to_str().is_some();
60    let path = path.to_string_lossy();
61    #[cfg(windows)]
62    {
63        if unicode {
64            windows_cli_path(&path)
65        } else {
66            path.into_owned()
67        }
68    }
69    #[cfg(not(windows))]
70    {
71        path.into_owned()
72    }
73}
74
75#[cfg(any(windows, test))]
76fn windows_cli_path(path: &str) -> String {
77    let path = path.replace('\\', "/");
78    if path.starts_with("//?/")
79        && path[4..].split('/').any(|part| {
80            let name = part.split('.').next().unwrap_or("").to_ascii_uppercase();
81            part.ends_with(['.', ' '])
82                || matches!(
83                    name.as_str(),
84                    "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
85                )
86                || (name.len() == 4
87                    && (name.starts_with("COM") || name.starts_with("LPT"))
88                    && matches!(name.as_bytes()[3], b'1'..=b'9'))
89        })
90    {
91        // These names need the native namespace; stripping it can select a
92        // different file. Leave them unsupported by Git rather than alias them.
93        return path;
94    }
95    if let Some(unc) = path.strip_prefix("//?/UNC/") {
96        return format!("//{unc}");
97    }
98    if let Some(drive) = path.strip_prefix("//?/")
99        && drive.as_bytes().get(1) == Some(&b':')
100        && drive.as_bytes().get(2) == Some(&b'/')
101        && drive.as_bytes()[0].is_ascii_alphabetic()
102    {
103        return drive.to_owned();
104    }
105    path
106}
107
108/// Accept Git's platform spelling only when it names a canonical filesystem
109/// path. Symlink aliases and redirects still fail this comparison.
110pub(crate) fn canonical_output_path(value: &str) -> Result<PathBuf> {
111    let path = PathBuf::from(value);
112    let canonical = path.canonicalize()?;
113    #[cfg(windows)]
114    let same_path = windows_cli_path(path.to_str().context("non UTF-8 Git path")?)
115        == windows_cli_path(canonical.to_str().context("non UTF-8 canonical Git path")?);
116    #[cfg(not(windows))]
117    let same_path = path == canonical;
118    ensure!(same_path, "noncanonical Git path: {}", path.display());
119    Ok(canonical)
120}
121
122/// Fetch `origin`'s branches into `refs/remotes/origin/*` in `cwd`, bounded by
123/// `timeout`.
124///
125/// The destination is fixed on the command line and the remote is addressed by
126/// its URL rather than its name. A plain `git fetch origin` follows the
127/// configured `remote.origin.fetch`, which can map onto local branches
128/// (`+refs/heads/main:refs/heads/main`) or a single branch, and even a fetch
129/// with an explicit refspec updates remote-tracking refs from that config
130/// when the remote is named. By URL, nothing but the refspec given here is
131/// written: no local branch, HEAD, index or working tree. A child still
132/// running at the deadline is killed on drop.
133pub async fn fetch_origin(cwd: &Path, timeout: std::time::Duration) -> Result<()> {
134    let url = git(cwd, &["remote", "get-url", "origin"]).await?;
135    #[cfg(test)]
136    crate::web::request_cost::git();
137    let fut = Command::new("git")
138        .args([
139            "fetch",
140            "--quiet",
141            "--no-tags",
142            "--no-recurse-submodules",
143            "--no-write-fetch-head",
144            "--",
145            url.as_str(),
146            "+refs/heads/*:refs/remotes/origin/*",
147        ])
148        .current_dir(cwd)
149        .quiet()
150        .env("GIT_TERMINAL_PROMPT", "0")
151        .stdin(Stdio::null())
152        .kill_on_drop(true)
153        .output();
154    let out = tokio::time::timeout(timeout, fut)
155        .await
156        .map_err(|_| anyhow::anyhow!("git fetch timed out after {}s", timeout.as_secs()))?
157        .context("spawn git fetch")?;
158    if !out.status.success() {
159        bail!(
160            "git fetch failed ({}): {}",
161            crate::notices::exit_status(out.status.code()),
162            String::from_utf8_lossy(&out.stderr).trim_end()
163        );
164    }
165    Ok(())
166}
167
168/// Run `git`, failing on a non-zero exit status.
169pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
170    let out = git_raw(cwd, args).await?;
171    if !out.ok() {
172        bail!(
173            "git {} failed in {} ({}): {}",
174            args.join(" "),
175            cwd.display(),
176            crate::notices::exit_status(out.code),
177            if out.stderr.is_empty() {
178                out.stdout.as_str()
179            } else {
180                out.stderr.as_str()
181            }
182        );
183    }
184    Ok(out.stdout)
185}
186
187/// Absolute path to the top level of the working tree containing `path`.
188pub async fn toplevel(path: &Path) -> Result<PathBuf> {
189    let out = git(path, &["rev-parse", "--show-toplevel"]).await?;
190    Ok(PathBuf::from(out))
191}
192
193/// Resolve a revision to a full object id.
194pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
195    git(repo, &["rev-parse", rev]).await
196}
197
198/// Currently checked-out branch, or `None` when detached.
199pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
200    let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
201    Ok(if out.ok() && !out.stdout.is_empty() {
202        Some(out.stdout)
203    } else {
204        None
205    })
206}
207
208/// The branch a `refs/remotes/<remote>/HEAD` symref names, e.g.
209/// `refs/remotes/origin/main` -> `main`. Pure, and shared with
210/// `Config::discover` so the branch magi reads its config from and the branch
211/// a run starts from can never come from two different readings.
212pub fn remote_head_branch(remote: &str, symref: &str) -> Option<String> {
213    symref
214        .trim()
215        .strip_prefix(&format!("refs/remotes/{remote}/"))
216        .filter(|b| !b.is_empty() && *b != "HEAD")
217        .map(str::to_owned)
218}
219
220/// Record `refs/remotes/<remote>/HEAD` -> `<remote>/<base>` when it is absent,
221/// so a later read of the remote's default (`Config::discover`) agrees with
222/// the branch just resolved even when git did not create the symref on fetch
223/// (`followRemoteHEAD=never`, old git). Moves only `refs/remotes`; an existing
224/// symref is left alone. Best effort.
225pub async fn ensure_remote_head(repo: &Path, remote: &str, base: &str) {
226    let head = format!("refs/remotes/{remote}/HEAD");
227    if git_raw(repo, &["symbolic-ref", "--quiet", &head])
228        .await
229        .is_ok_and(|o| o.ok())
230    {
231        return;
232    }
233    let target = format!("refs/remotes/{remote}/{base}");
234    let _ = git_raw(repo, &["symbolic-ref", &head, &target]).await;
235}
236
237/// The branch in `git ls-remote --symref <remote> HEAD` output
238/// (`ref: refs/heads/main\tHEAD`).
239fn symref_branch(out: &str) -> Option<String> {
240    out.lines()
241        .find_map(|l| l.strip_prefix("ref: refs/heads/"))
242        .and_then(|l| l.split_whitespace().next())
243        .map(str::to_owned)
244}
245
246/// Which branch of `remote` is the base: `explicit` (`[merge] base`) wins,
247/// else the remote's default branch as recorded in `refs/remotes/<remote>/HEAD`.
248/// When that ref is missing (a checkout that was never cloned from it), ask the
249/// remote once with `git remote set-head <remote> -a`, which moves only
250/// `refs/remotes`. Never the checked-out branch: a detached or stale primary
251/// checkout must not decide what a run branches off.
252pub async fn merge_base_branch(
253    repo: &Path,
254    remote: &str,
255    explicit: Option<&str>,
256) -> Result<String> {
257    if let Some(b) = explicit.map(str::trim).filter(|b| !b.is_empty()) {
258        return Ok(b.to_owned());
259    }
260    let head = format!("refs/remotes/{remote}/HEAD");
261    let read = || async {
262        let out = git_raw(repo, &["symbolic-ref", "--quiet", &head])
263            .await
264            .ok()?;
265        if out.ok() {
266            remote_head_branch(remote, &out.stdout)
267        } else {
268            None
269        }
270    };
271    if let Some(b) = read().await {
272        return Ok(b);
273    }
274    let set = git_raw(repo, &["remote", "set-head", remote, "-a"]).await;
275    if let Some(b) = read().await {
276        return Ok(b);
277    }
278    // `set-head -a` insists the tracking ref already exists, which it does not
279    // for a remote that was never fetched (or a single-branch clone of another
280    // branch). Ask the remote for its HEAD symref instead: that only names the
281    // branch, and the fetch that follows (`resolve_base`) creates the ref.
282    if let Ok(o) = git_raw(repo, &["ls-remote", "--symref", remote, "HEAD"]).await
283        && o.ok()
284        && let Some(b) = symref_branch(&o.stdout)
285    {
286        return Ok(b);
287    }
288    let why = match set {
289        Ok(o) if !o.ok() => o.stderr.lines().next().unwrap_or("").trim().to_owned(),
290        Ok(_) => "the remote reported no default branch".to_owned(),
291        Err(e) => e.to_string(),
292    };
293    bail!(
294        "cannot tell which branch of `{remote}` is the base ({why}): set [merge] base \
295         (and remote) in magi.toml, or run `git remote set-head {remote} -a`. magi does \
296         not fall back to the checked-out branch, which may be detached or stale"
297    )
298}
299
300/// Is the working tree free of tracked modifications and untracked files?
301pub async fn is_clean(repo: &Path) -> Result<bool> {
302    Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
303}
304
305/// `git status --porcelain`, for reporting what is dirty.
306pub async fn status_porcelain(repo: &Path) -> Result<String> {
307    git(repo, &["status", "--porcelain"]).await
308}
309
310/// Create a worktree at `path` with a fresh branch `branch` starting at `base`.
311pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
312    if let Some(parent) = path.parent() {
313        tokio::fs::create_dir_all(parent).await.ok();
314    }
315    let path_s = path.to_string_lossy().to_string();
316    git(repo, &["worktree", "add", "-b", branch, &path_s, base])
317        .await
318        .map(|_| ())
319}
320
321/// Create a worktree at `path` with a detached HEAD at `rev`.
322pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
323    if let Some(parent) = path.parent() {
324        tokio::fs::create_dir_all(parent).await.ok();
325    }
326    let path_s = path_arg(path);
327    git(repo, &["worktree", "add", "--detach", &path_s, rev])
328        .await
329        .map(|_| ())
330}
331
332/// Move an existing detached worktree to `rev`, discarding local state.
333pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
334    git(worktree, &["checkout", "--detach", rev]).await?;
335    git(worktree, &["reset", "--hard", rev]).await?;
336    git(worktree, &["clean", "-fdx"]).await?;
337    Ok(())
338}
339
340/// Where `branch` is checked out, if some worktree holds it.
341///
342/// Read from `git worktree list --porcelain` rather than out of an error
343/// message, which varies with git's version and locale.
344pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
345    let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
346    Ok(parse_worktree_holder(&listing, branch))
347}
348
349fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
350    let want = format!("refs/heads/{branch}");
351    let mut path: Option<PathBuf> = None;
352    for line in listing.lines() {
353        if let Some(p) = line.strip_prefix("worktree ") {
354            path = Some(PathBuf::from(p));
355        } else if line.strip_prefix("branch ") == Some(want.as_str()) {
356            return path;
357        }
358    }
359    None
360}
361
362/// Force removal of a disposable worktree, including build output or conflicts.
363/// Candidate work must use [`worktree_remove_clean`] instead.
364/// Returns `Ok(false)` on refusal; callers must retain their ownership record.
365pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
366    let path_s = path.to_string_lossy().to_string();
367    let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
368    if out.ok() {
369        return Ok(true);
370    }
371    // Do not prune metadata for an existing tree after any refusal.
372    if !path.exists() {
373        git_raw(repo, &["worktree", "prune"]).await?;
374    }
375    Ok(false)
376}
377
378/// Remove a worktree only if git finds it clean: no `--force`, so a change
379/// made after the caller last looked is refused rather than thrown away.
380/// Ignored files (`target/`) do not count as changes and go with it.
381pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
382    let path_s = path_arg(path);
383    Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
384}
385
386/// Unregister a linked worktree whose directory is about to be deleted by
387/// hand, so the path can be `worktree add`-ed again.
388///
389/// A linked worktree's `.git` is a file whose `gitdir:` line names the
390/// bookkeeping entry inside its repository's admin directory; pruning from
391/// there removes the registration without touching the directory. No-op when
392/// `dir` is not a registered worktree (`.git` missing or not a `gitdir:`
393/// link): nothing was registered, nothing survives removal.
394pub async fn remove_worktree_from_linked(dir: &Path) {
395    let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
396        return;
397    };
398    let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
399        return;
400    };
401    // `<repo>/.git/worktrees/<name>`, so the repository's git dir is two
402    // levels up from here.
403    let admin = Path::new(admin);
404    let Some(common) = admin.parent().and_then(Path::parent) else {
405        return;
406    };
407    let common_s = common.to_string_lossy();
408    let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
409}
410
411/// Drop registrations for worktrees whose directory is already gone.
412///
413/// `git worktree remove` already does this for the path it just removed, but
414/// a directory deleted by hand - [`crate::clean::fold_orphaned_worktrees`], or
415/// an operator's own `rm -rf` - leaves the registration behind, and a
416/// registered path refuses a fresh `worktree add` until something prunes it.
417/// The operator's own machine had 31 such registrations sitting in one
418/// repository, all of them for directories that no longer existed.
419pub async fn worktree_prune(repo: &Path) -> Result<()> {
420    git(repo, &["worktree", "prune"]).await.map(|_| ())
421}
422
423/// Delete a branch, ignoring "not found".
424pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
425    Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
426}
427
428/// Does `branch` exist?
429pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
430    let refname = format!("refs/heads/{branch}");
431    Ok(
432        git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
433            .await?
434            .ok(),
435    )
436}
437
438/// Does `remote` have `branch`? `Err` when that cannot be told (unreachable
439/// remote), which callers must not read as "no".
440pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
441    let refname = format!("refs/heads/{branch}");
442    let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
443    match out.code {
444        Some(0) => Ok(true),
445        Some(2) => Ok(false),
446        code => bail!(
447            "git ls-remote {remote} failed ({}): {}",
448            crate::notices::exit_status(code),
449            out.stderr
450        ),
451    }
452}
453
454/// Patch of `head` against the merge base with `base`.
455pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
456    let range = format!("{base}...{head}");
457    git(
458        worktree,
459        &["diff", "--no-color", "--no-ext-diff", "-M", &range],
460    )
461    .await
462}
463
464/// `--stat` summary of `base...head`.
465pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
466    let range = format!("{base}...{head}");
467    git(worktree, &["diff", "--no-color", "--stat", &range]).await
468}
469
470/// Total changed lines (added + removed) between two revisions, from
471/// `--numstat`. `None` when git could not say, or a binary file changed
472/// (numstat prints `-` for it). This measurement does not determine acceptance.
473pub async fn changed_lines(worktree: &Path, base: &str, head: &str) -> Option<usize> {
474    let out = git_raw(worktree, &["diff", "--numstat", base, head])
475        .await
476        .ok()?;
477    if !out.ok() {
478        return None;
479    }
480    let mut total = 0usize;
481    for line in out.stdout.lines().filter(|l| !l.trim().is_empty()) {
482        let mut cols = line.split('\t');
483        let added: usize = cols.next()?.parse().ok()?;
484        let removed: usize = cols.next()?.parse().ok()?;
485        total = total.saturating_add(added).saturating_add(removed);
486    }
487    Some(total)
488}
489
490/// Put the worktree back on `rev`: tracked files reset, untracked files
491/// removed. Ignored paths (a `[worktree] setup`'s products are hidden through
492/// the per-worktree excludes) are left alone.
493pub async fn restore_to(worktree: &Path, rev: &str) -> Result<()> {
494    git(worktree, &["reset", "--hard", "-q", rev]).await?;
495    // `-ff`: a single `-f` skips untracked nested git repositories, which is
496    // what a submodule or clone added by a rejected change leaves behind.
497    git(worktree, &["clean", "-ffdq"]).await?;
498    // The parent's reset leaves an initialised submodule's own tree alone
499    // (`submodule.recurse` defaults to false): put each back on the commit the
500    // parent records (`--checkout` overrides a configured
501    // `submodule.<name>.update` such as `none`), and drop what is untracked inside. No-ops without
502    // submodules; an error is an unconfirmed restore.
503    git(
504        worktree,
505        &[
506            "submodule",
507            "--quiet",
508            "update",
509            "--recursive",
510            "--force",
511            "--checkout",
512        ],
513    )
514    .await?;
515    git(
516        worktree,
517        &[
518            "submodule",
519            "--quiet",
520            "foreach",
521            "--recursive",
522            "git clean -ffdq",
523        ],
524    )
525    .await?;
526    Ok(())
527}
528
529/// Number of files touched by `base...head`.
530pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
531    let range = format!("{base}...{head}");
532    let out = git(worktree, &["diff", "--name-only", &range]).await?;
533    Ok(out.lines().map(str::to_owned).collect())
534}
535
536/// Subject and body of every commit in `base..head`, oldest first. Fields are
537/// split on control characters git never prints in a message, so an empty
538/// subject or a body full of separators cannot shift a record.
539pub async fn commit_log(worktree: &Path, base: &str, head: &str) -> Result<Vec<(String, String)>> {
540    let range = format!("{base}..{head}");
541    let out = git(
542        worktree,
543        &[
544            "log",
545            "--reverse",
546            "--no-color",
547            "--format=%s%x1f%b%x00",
548            &range,
549        ],
550    )
551    .await?;
552    Ok(out
553        .split('\0')
554        .filter_map(|rec| {
555            let rec = rec.trim_start_matches('\n');
556            if rec.trim().is_empty() {
557                return None;
558            }
559            let (subject, body) = rec.split_once('\x1f').unwrap_or((rec, ""));
560            Some((subject.trim().to_owned(), body.trim().to_owned()))
561        })
562        .collect())
563}
564
565/// One-line log of `base..head`, oldest first.
566pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
567    let range = format!("{base}..{head}");
568    git(
569        worktree,
570        &["log", "--reverse", "--format=%s%n%b%n--", &range],
571    )
572    .await
573}
574
575/// Subjects of the commits in `base..head`, oldest first. NUL-terminated so an
576/// empty subject keeps its place instead of shifting the later ones forward.
577pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
578    let range = format!("{base}..{head}");
579    let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
580    let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
581    // Whatever follows the last terminator is just the trailing newline.
582    parts.pop();
583    Ok(parts)
584}
585
586/// How many commits `head` is ahead of `base`.
587pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
588    let range = format!("{base}..{head}");
589    let out = git(worktree, &["rev-list", "--count", &range]).await?;
590    Ok(out.trim().parse().unwrap_or(0))
591}
592
593/// Stage everything and commit under a neutral identity.
594///
595/// Used to rescue an agent that edited files but never committed: without this
596/// its candidate would silently be empty. The neutral identity is part of the
597/// blindness contract — a real `user.name` in a candidate's history would name
598/// the operator, and an agent-configured one would name the vendor.
599pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
600    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
601        return Ok(false);
602    }
603    git(worktree, &["add", "-A"]).await?;
604    // What `[worktree] setup` produced is not the agent's work.
605    if !crate::worktree_setup::withheld_paths(worktree)
606        .await
607        .is_empty()
608    {
609        crate::worktree_setup::unstage_products(worktree).await?;
610        if git_raw(worktree, &["diff", "--cached", "--quiet"])
611            .await?
612            .ok()
613        {
614            return Ok(false);
615        }
616    }
617    let out = git_raw(
618        worktree,
619        &[
620            "-c",
621            "user.name=magi candidate",
622            "-c",
623            "user.email=magi@localhost",
624            "commit",
625            "--no-verify",
626            "-m",
627            message,
628        ],
629    )
630    .await?;
631    if !out.ok() {
632        bail!("rescue commit failed: {}", out.stderr);
633    }
634    Ok(true)
635}
636
637/// A freshly created lockfile that belongs to a package manager the directory
638/// does not use, and was therefore left out of a rescue commit.
639#[derive(Debug, Clone, PartialEq, Eq)]
640pub struct Stray {
641    /// Repo-relative path, forward slashes.
642    pub path: String,
643    /// The package manager the file belongs to (`pnpm`, `cargo`, ...).
644    pub manager: String,
645    /// What made it foreign: the tracked lockfile (or `Cargo.toml`'s absence)
646    /// that says which manager the directory really uses.
647    pub kept_by: String,
648}
649
650/// What [`rescue_commit`] did.
651#[derive(Debug, Default)]
652pub struct Rescue {
653    /// Whether a commit was made.
654    pub committed: bool,
655    /// Files left untracked in the worktree instead of being committed.
656    pub withheld: Vec<Stray>,
657}
658
659/// `(ecosystem, manager)` for a lockfile's file name.
660fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
661    Some(match name {
662        "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
663        "yarn.lock" => ("node", "yarn"),
664        "pnpm-lock.yaml" => ("node", "pnpm"),
665        "bun.lock" | "bun.lockb" => ("node", "bun"),
666        "poetry.lock" => ("python", "poetry"),
667        "uv.lock" => ("python", "uv"),
668        "Pipfile.lock" => ("python", "pipenv"),
669        "pdm.lock" => ("python", "pdm"),
670        "Cargo.lock" => ("rust", "cargo"),
671        _ => return None,
672    })
673}
674
675fn split_dir(path: &str) -> (&str, &str) {
676    path.rsplit_once('/').unwrap_or(("", path))
677}
678
679/// Which of the newly created `untracked` files are lockfiles of a manager the
680/// repo does not use in that directory.
681///
682/// Foreign means: a lockfile of the same ecosystem but another manager is
683/// already tracked *in the same directory* (no recursion — a workspace root and
684/// a sub-package may legitimately differ), or, for `Cargo.lock`, there is no
685/// `Cargo.toml` beside it. A first lockfile in a directory with none is normal.
686pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
687    let mut out = Vec::new();
688    for path in untracked {
689        let (dir, name) = split_dir(path);
690        let Some((eco, manager)) = lock_kind(name) else {
691            continue;
692        };
693        let beside = |other: &String| split_dir(other).0 == dir;
694        let kept_by = if manager == "cargo" {
695            let has_manifest = tracked
696                .iter()
697                .chain(untracked)
698                .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
699            if has_manifest {
700                continue;
701            }
702            "no Cargo.toml in the directory".to_owned()
703        } else {
704            let Some(other) = tracked.iter().find(|p| {
705                beside(p)
706                    && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
707            }) else {
708                continue;
709            };
710            other.clone()
711        };
712        out.push(Stray {
713            path: path.clone(),
714            manager: manager.to_owned(),
715            kept_by,
716        });
717    }
718    out
719}
720
721async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
722    let out = git(worktree, args).await?;
723    Ok(out
724        .split('\0')
725        .filter(|s| !s.is_empty())
726        .map(str::to_owned)
727        .collect())
728}
729
730/// Index-independent recovery evidence. Never treats a snapshot as a commit.
731/// Preserve staged and working tree changes separately, plus untracked bytes.
732/// Failure leaves the original tree untouched and is reported by the caller.
733pub async fn snapshot_uncommitted(worktree: &Path, destination: &Path) -> Result<()> {
734    if destination.exists() {
735        if destination.join("complete").exists() {
736            return Ok(());
737        }
738        bail!("earlier recovery snapshot is incomplete; retain original worktree");
739    }
740    std::fs::create_dir_all(destination)?;
741    for (name, args) in [
742        ("status.txt", vec!["status", "--porcelain=v1"]),
743        ("staged.patch", vec!["diff", "--binary", "--cached"]),
744        ("unstaged.patch", vec!["diff", "--binary"]),
745    ] {
746        // GitOut trims stdout for display. Recovery patches need exact bytes,
747        // including trailing whitespace and no-final-newline markers.
748        let out = Command::new("git")
749            .args(&args)
750            .current_dir(worktree)
751            .quiet()
752            .stdin(Stdio::null())
753            .output()
754            .await?;
755        if !out.status.success() {
756            bail!(
757                "recovery snapshot failed: {}",
758                String::from_utf8_lossy(&out.stderr)
759            );
760        }
761        std::fs::write(destination.join(name), out.stdout)?;
762    }
763    let paths = nul_list(
764        worktree,
765        &["ls-files", "-z", "--others", "--exclude-standard"],
766    )
767    .await?;
768    for name in paths {
769        let relative = Path::new(&name);
770        if relative
771            .components()
772            .any(|c| !matches!(c, std::path::Component::Normal(_)))
773        {
774            bail!("unsafe recovery path");
775        }
776        let source = worktree.join(relative);
777        let target = destination.join("untracked").join(relative);
778        std::fs::create_dir_all(target.parent().context("untracked recovery parent")?)?;
779        if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
780            // Do not follow a link outside the checkout or silently flatten it.
781            bail!("untracked symlink requires manual recovery: {name}");
782        }
783        std::fs::copy(source, target)?;
784    }
785    std::fs::write(destination.join("complete"), "snapshot captured\n")?;
786    Ok(())
787}
788
789/// [`commit_all`] for an agent's leftover work, minus stray foreign lockfiles.
790///
791/// The withheld files stay untracked in the worktree (nothing is deleted) and
792/// are returned so the caller can record them: silently dropping them could
793/// lose a file the task really asked for.
794pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
795    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
796        return Ok(Rescue::default());
797    }
798    let untracked = nul_list(
799        worktree,
800        &["ls-files", "-z", "--others", "--exclude-standard"],
801    )
802    .await?;
803    let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
804    let withheld = stray_lockfiles(&untracked, &tracked);
805
806    git(worktree, &["add", "-A"]).await?;
807    if !withheld.is_empty() {
808        let mut args = vec!["reset", "-q", "--"];
809        args.extend(withheld.iter().map(|s| s.path.as_str()));
810        git(worktree, &args).await?;
811    }
812    crate::worktree_setup::unstage_products(worktree).await?;
813    if git_raw(worktree, &["diff", "--cached", "--quiet"])
814        .await?
815        .ok()
816    {
817        return Ok(Rescue {
818            committed: false,
819            withheld,
820        });
821    }
822    let out = git_raw(
823        worktree,
824        &[
825            "-c",
826            "user.name=magi candidate",
827            "-c",
828            "user.email=magi@localhost",
829            "commit",
830            "--no-verify",
831            "-m",
832            message,
833        ],
834    )
835    .await?;
836    if !out.ok() {
837        bail!("rescue commit failed: {}", out.stderr);
838    }
839    Ok(Rescue {
840        committed: true,
841        withheld,
842    })
843}
844
845/// Enable `extensions.worktreeConfig` if it is not already on.
846///
847/// Returns `true` when magi turned it on, so the caller can turn it back off
848/// during cleanup and leave the repo exactly as it found it.
849pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
850    let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
851    if out.ok() && out.stdout.trim() == "true" {
852        return Ok(false);
853    }
854    git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
855    Ok(true)
856}
857
858/// Undo [`enable_worktree_config`].
859pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
860    git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
861    Ok(())
862}
863
864/// How many runs currently want `extensions.worktreeConfig` on for one
865/// repository, and whether magi is the one that turned it on.
866struct WorktreeConfigRef {
867    /// Runs holding a reference, via [`acquire_worktree_config`].
868    count: usize,
869    /// Did *this process* flip the setting from off to on? If not - it was
870    /// already `true` when the first run in this process asked - nothing
871    /// here ever turns it off either; that is what [`enable_worktree_config`]
872    /// already decided for the single-run case, and the ref-counted version
873    /// must not second-guess it.
874    we_enabled: bool,
875}
876
877/// One entry per repository, each guarded by its own `tokio::sync::Mutex` so
878/// that two repositories' acquisitions never wait on each other - only two
879/// runs in the *same* repository do, which is the point.
880///
881/// A `std::sync::Mutex` guards the map itself, held only long enough to find
882/// or insert an entry and clone its `Arc`, never across an `.await`.
883static WORKTREE_CONFIG: std::sync::LazyLock<
884    std::sync::Mutex<
885        std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
886    >,
887> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
888
889/// The per-repository slot, creating it if this is the first run to ask.
890fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
891    let mut map = WORKTREE_CONFIG
892        .lock()
893        .unwrap_or_else(std::sync::PoisonError::into_inner);
894    map.entry(repo.to_path_buf())
895        .or_insert_with(|| {
896            std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
897                count: 0,
898                we_enabled: false,
899            }))
900        })
901        .clone()
902}
903
904/// Take a reference on `extensions.worktreeConfig` being on for `repo`.
905///
906/// [`enable_worktree_config`] alone is only safe for one run in a repository
907/// at a time: it is a plain get-then-set, so a second run's "already true?"
908/// check can see the first run's write and conclude it owns nothing to turn
909/// back off, while the first run's own cleanup turns the setting off under
910/// the second run's feet the moment *it* finishes - the exact race that let a
911/// finished run's fold disable the hook a still-running sibling in the same
912/// repository depended on. This ref-counts instead: the setting is turned on
913/// once, by whichever caller is first, and turned off only once every caller
914/// has released it via [`release_worktree_config`].
915///
916/// The per-repository lock is held across the `git config` call for the
917/// first acquire, so a second, concurrent acquire for the same repository
918/// waits for it rather than racing it - without that, both could observe
919/// "not yet counted" and both try to flip the setting on.
920pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
921    let slot = worktree_config_slot(repo);
922    let mut entry = slot.lock().await;
923    entry.count += 1;
924    if entry.count == 1 {
925        entry.we_enabled = enable_worktree_config(repo).await?;
926    }
927    Ok(())
928}
929
930/// Release a reference taken by [`acquire_worktree_config`].
931///
932/// Only the last release for a repository actually calls
933/// [`disable_worktree_config`], and only when this process was the one that
934/// turned the setting on in the first place.
935pub async fn release_worktree_config(repo: &Path) -> Result<()> {
936    let slot = worktree_config_slot(repo);
937    let mut entry = slot.lock().await;
938    entry.count = entry.count.saturating_sub(1);
939    if entry.count == 0 && entry.we_enabled {
940        disable_worktree_config(repo).await?;
941        entry.we_enabled = false;
942    }
943    Ok(())
944}
945
946/// Point a single worktree at its own hooks directory.
947///
948/// `core.hooksPath` is normally repo-wide; scoping it with `--worktree` keeps
949/// the operator's own hooks untouched in the primary worktree, and the setting
950/// disappears together with the worktree.
951pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
952    let dir = hooks_dir.to_string_lossy().replace('\\', "/");
953    git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
954        .await
955        .map(|_| ())
956}
957
958/// Exclude a path from a worktree's status without touching `.gitignore`.
959pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
960    let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
961    let path = worktree.join(git_dir);
962    if let Some(parent) = path.parent() {
963        tokio::fs::create_dir_all(parent).await.ok();
964    }
965    let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
966    if body.lines().any(|l| l.trim() == pattern) {
967        return Ok(());
968    }
969    if !body.is_empty() && !body.ends_with('\n') {
970        body.push('\n');
971    }
972    body.push_str(pattern);
973    body.push('\n');
974    tokio::fs::write(&path, body)
975        .await
976        .with_context(|| format!("write {}", path.display()))?;
977    Ok(())
978}
979
980/// `git merge --no-ff` of `branch` into the currently checked-out branch.
981///
982/// One of three ways to land a branch driven by [`crate::config::MergeStyle`]
983/// — see [`merge_squash`] and [`merge_ff_only`] for the other two, and that
984/// enum's own doc for why the choice between them lives in configuration.
985pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
986    git_raw(
987        repo,
988        &["merge", "--no-ff", "--no-edit", "-m", message, branch],
989    )
990    .await
991}
992
993/// `git merge --squash` of `branch`, followed by a commit under `message`.
994///
995/// Two `git` calls because `--squash` only stages the result — unlike
996/// [`merge_no_ff`] there is no merge commit for `--no-edit` to write, and
997/// skipping the second call is exactly the trap `land`'s module doc warns
998/// about: a squash that inherits `branch`'s own single-commit subject
999/// (`magi: candidate A (uncommitted work)`) instead of `message`. Returns the
1000/// `--squash` step's own output, unrun `commit` included, when staging itself
1001/// fails (a conflict), so a caller sees what actually went wrong rather than
1002/// a `git commit` complaint about nothing being staged.
1003pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1004    let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
1005    if !staged.ok() {
1006        return Ok(staged);
1007    }
1008    git_raw(repo, &["commit", "-m", message]).await
1009}
1010
1011/// Fast-forward `branch` into the currently checked-out branch, refusing to
1012/// create a merge commit.
1013///
1014/// Only ever fast-forwards because the winner was already rebased onto the
1015/// tracked base tip before this runs (`Runner::sync_to_base`); at that point
1016/// `--ff-only` is indistinguishable from GitHub's "rebase and merge" button.
1017/// If the base moved again in the meantime this fails rather than falling
1018/// back to a real rebase, the same way `merge_no_ff` fails rather than
1019/// resolving a conflict — landing is not the place to improvise.
1020pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
1021    git_raw(repo, &["merge", "--ff-only", branch]).await
1022}
1023
1024/// Push a branch to `remote`.
1025pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1026    git_raw(repo, &["push", "-u", remote, branch]).await
1027}
1028
1029/// Push a local branch to a separate public head with an explicit lease.
1030/// An empty expected SHA requires the remote branch to be absent.
1031pub async fn push_as(
1032    repo: &Path,
1033    remote: &str,
1034    local: &str,
1035    head: &str,
1036    expected: &str,
1037) -> Result<GitOut> {
1038    let lease = format!("--force-with-lease=refs/heads/{head}:{expected}");
1039    let refspec = format!("refs/heads/{local}:refs/heads/{head}");
1040    git_raw(repo, &["push", &lease, remote, &refspec]).await
1041}
1042
1043/// Read a remote head without moving a tracking ref. Unreadable is an error.
1044pub async fn remote_head(repo: &Path, remote: &str, branch: &str) -> Result<Option<String>> {
1045    let reference = format!("refs/heads/{branch}");
1046    let out = git(repo, &["ls-remote", "--refs", remote, &reference]).await?;
1047    Ok(out.split_whitespace().next().map(str::to_owned))
1048}
1049
1050/// Force-push a branch that has been rewritten, refusing to clobber work
1051/// pushed since this side last looked.
1052///
1053/// `--force-with-lease` rather than `--force`: a rebase replaces the branch's
1054/// commits, so a plain push is rejected, but a blind force would also throw
1055/// away anything a person pushed to the same branch meanwhile. The lease
1056/// turns that case into a failure instead of a loss.
1057pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1058    git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
1059}
1060
1061/// Force-push `branch` only if `remote` still has it at `expected`.
1062///
1063/// The lease is pinned to a sha the caller read itself, not to whatever the
1064/// remote-tracking ref says at push time: a `fetch` in between moves the
1065/// tracking ref, and a bare lease would then be measured against the very
1066/// commit it was meant to protect a person's push from. A remote that has
1067/// moved on refuses the push, so a concurrent push fails the step instead of
1068/// being lost.
1069pub async fn push_pinned(
1070    repo: &Path,
1071    remote: &str,
1072    branch: &str,
1073    expected: &str,
1074) -> Result<GitOut> {
1075    let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
1076    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1077    git_raw(repo, &["push", &lease, remote, &refspec]).await
1078}
1079
1080/// `git cherry <upstream> <head>`, split into the commits of `head` that have
1081/// no patch-id twin in `upstream` (`+`) and those that do (`-`).
1082pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
1083    let out = git(repo, &["cherry", upstream, head]).await?;
1084    let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
1085    for line in out.lines() {
1086        if let Some(sha) = line.strip_prefix("+ ") {
1087            unmatched.push(sha.trim().to_owned());
1088        } else if let Some(sha) = line.strip_prefix("- ") {
1089            matched.push(sha.trim().to_owned());
1090        }
1091    }
1092    Ok((unmatched, matched))
1093}
1094
1095/// Git's pick order and the HEAD observed by the exec following each pick.
1096#[derive(Debug)]
1097pub struct RebaseRecord {
1098    /// Full original commit ids in Git's replay order.
1099    pub picks: Vec<String>,
1100    /// Full HEAD ids observed immediately after those picks.
1101    pub heads: Vec<String>,
1102}
1103
1104const REBASE_EXEC: &str = "git rev-parse HEAD >> \"$(git rev-parse --git-path magi-rebase-heads)\"";
1105
1106async fn rebase_file(scratch: &Path, name: &str) -> Result<PathBuf> {
1107    let path = git(scratch, &["rev-parse", "--git-path", name]).await?;
1108    let path = Path::new(path.trim());
1109    Ok(if path.is_absolute() {
1110        path.to_path_buf()
1111    } else {
1112        scratch.join(path)
1113    })
1114}
1115
1116async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1117    anyhow::ensure!(
1118        !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1119        "invalid rebase commit id: {sha}"
1120    );
1121    rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1122}
1123
1124/// Save Git's exact picks before a fixer can change its todo list. Resolve
1125/// abbreviations while the sequencer still exists; ambiguity is an error.
1126async fn save_rebase_picks(scratch: &Path) -> Result<()> {
1127    let mut picks = Vec::new();
1128    for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1129        let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1130        for line in text.lines().map(str::trim) {
1131            if line.is_empty() || line.starts_with('#') {
1132                continue;
1133            }
1134            let mut words = line.split_whitespace();
1135            match words.next() {
1136                Some("pick" | "p") => {
1137                    picks.push(
1138                        full_commit(scratch, words.next().context("pick without commit")?).await?,
1139                    );
1140                }
1141                Some("exec" | "x")
1142                    if line
1143                        .split_once(' ')
1144                        .is_some_and(|(_, cmd)| cmd == REBASE_EXEC) => {}
1145                _ => bail!("unexpected rebase instruction: {line}"),
1146            }
1147        }
1148    }
1149    let path = rebase_file(scratch, "magi-rebase-picks").await?;
1150    let tmp = path.with_extension("tmp");
1151    std::fs::write(&tmp, picks.join("\n") + "\n")?;
1152    std::fs::rename(tmp, path)?;
1153    Ok(())
1154}
1155
1156/// Read a completed rebase's durable record, rejecting missing or corrupt data.
1157pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1158    let mut lists = Vec::new();
1159    for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1160        let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1161            .with_context(|| format!("read {name}"))?;
1162        let mut commits = Vec::new();
1163        for sha in text.lines() {
1164            let full = full_commit(scratch, sha).await?;
1165            anyhow::ensure!(full == sha, "non-full commit id in {name}");
1166            commits.push(full);
1167        }
1168        lists.push(commits);
1169    }
1170    let heads = lists.pop().unwrap();
1171    let picks = lists.pop().unwrap();
1172    anyhow::ensure!(
1173        !picks.is_empty() && picks.len() == heads.len(),
1174        "rebase pick/HEAD count mismatch"
1175    );
1176    Ok(RebaseRecord { picks, heads })
1177}
1178
1179/// Strip only the diagnostics emitted by our recording exec.
1180pub fn rebase_said(text: &str) -> String {
1181    text.trim()
1182        .split(['\r', '\n'])
1183        .filter(|line| !line.trim_start().starts_with("Executing:"))
1184        .collect::<Vec<_>>()
1185        .join("\n")
1186}
1187
1188/// How [`rebase_start`] ended.
1189#[derive(Debug, Clone, PartialEq, Eq)]
1190pub enum RebaseStart {
1191    /// It applied; the branch points at the rebased commits and the throwaway
1192    /// worktree is gone.
1193    Applied,
1194    /// It stopped on a conflict and the throwaway worktree was **kept**
1195    /// mid-rebase, for someone to resolve. Carries what git said.
1196    Conflicted(String),
1197    /// It failed without leaving a rebase in progress; the worktree is gone
1198    /// and the branch is untouched. Carries what git said.
1199    Failed(String),
1200}
1201
1202/// Start rebasing `branch` onto `onto` inside a throwaway worktree, and leave
1203/// a conflict standing.
1204///
1205/// A worktree of its own for two reasons. The repository magi runs in may be
1206/// jj-colocated, where git `HEAD` is detached and a rebase in the primary
1207/// tree would move it under the operator; and a rebase that hits a conflict
1208/// leaves state behind, which is far easier to discard with the whole
1209/// directory than to unpick in a tree somebody is using.
1210///
1211/// Unlike [`rebase_branch_in_temp`] this does not abort on a conflict: the
1212/// caller decides whether to hand the conflicted tree to a fixer or to call
1213/// [`rebase_abort`]. Any leftover at `scratch` from an earlier attempt is
1214/// removed first, so callers re-entering a rebase already in progress must
1215/// check [`rebase_in_progress`] before calling this.
1216pub async fn rebase_start(
1217    repo: &Path,
1218    scratch: &Path,
1219    branch: &str,
1220    onto: &str,
1221) -> Result<RebaseStart> {
1222    // Removed first so a leftover from an interrupted attempt cannot make
1223    // `worktree add` fail on a path that already exists.
1224    worktree_remove(repo, scratch).await.ok();
1225    git_raw(
1226        repo,
1227        &[
1228            "worktree",
1229            "add",
1230            "--force",
1231            &scratch.to_string_lossy(),
1232            branch,
1233        ],
1234    )
1235    .await?;
1236
1237    std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1238    let out = git_raw(
1239        scratch,
1240        &["rebase", "--empty=drop", "--exec", REBASE_EXEC, onto],
1241    )
1242    .await?;
1243    if out.ok() {
1244        worktree_remove(repo, scratch).await.ok();
1245        return Ok(RebaseStart::Applied);
1246    }
1247    let why = rebase_said(&if out.stderr.trim().is_empty() {
1248        out.stdout.trim().to_owned()
1249    } else {
1250        out.stderr.trim().to_owned()
1251    });
1252    if rebase_in_progress(scratch).await {
1253        if let Err(error) = save_rebase_picks(scratch).await {
1254            rebase_abort(repo, scratch).await;
1255            return Ok(RebaseStart::Failed(format!(
1256                "cannot record rebase picks: {error:#}"
1257            )));
1258        }
1259        return Ok(RebaseStart::Conflicted(why));
1260    }
1261    worktree_remove(repo, scratch).await.ok();
1262    Ok(RebaseStart::Failed(why))
1263}
1264
1265/// Is a rebase (merge or apply backend) in progress in `worktree`?
1266pub async fn rebase_in_progress(worktree: &Path) -> bool {
1267    for name in ["rebase-merge", "rebase-apply"] {
1268        let Ok(p) = git(worktree, &["rev-parse", "--git-path", name]).await else {
1269            continue;
1270        };
1271        let p = Path::new(p.trim());
1272        let full = if p.is_absolute() {
1273            p.to_path_buf()
1274        } else {
1275            worktree.join(p)
1276        };
1277        if full.exists() {
1278            return true;
1279        }
1280    }
1281    false
1282}
1283
1284/// Paths git reports as unmerged in `worktree`.
1285pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1286    let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1287    Ok(out
1288        .split('\0')
1289        .filter(|l| !l.is_empty())
1290        .map(str::to_owned)
1291        .collect())
1292}
1293
1294/// Abandon a rebase left standing by [`rebase_start`] and drop its worktree.
1295/// The branch is exactly where it was before the rebase began.
1296pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1297    git_raw(scratch, &["rebase", "--abort"]).await.ok();
1298    worktree_remove(repo, scratch).await.ok();
1299}
1300
1301/// Rebase a branch onto `onto`, inside a throwaway worktree.
1302///
1303/// `Ok(None)` means it applied and the branch now points at the rebased
1304/// commits. `Ok(Some(why))` means it did not: the branch is untouched, and
1305/// the string is what git said - a person has to decide. Nothing half-rebased
1306/// is left behind; see [`rebase_start`] for the variant that keeps a conflict
1307/// standing.
1308pub async fn rebase_branch_in_temp(
1309    repo: &Path,
1310    scratch: &Path,
1311    branch: &str,
1312    onto: &str,
1313) -> Result<Option<String>> {
1314    match rebase_start(repo, scratch, branch, onto).await? {
1315        RebaseStart::Applied => Ok(None),
1316        RebaseStart::Failed(why) => Ok(Some(why)),
1317        RebaseStart::Conflicted(why) => {
1318            rebase_abort(repo, scratch).await;
1319            Ok(Some(why))
1320        }
1321    }
1322}
1323
1324/// Bring an *attached* worktree's index and files in line with wherever its
1325/// branch now points.
1326///
1327/// [`rebase_branch_in_temp`] moves a branch from a throwaway worktree on
1328/// purpose - the whole point is never touching the tree someone else has
1329/// checked out. But a worktree that already had that branch checked out
1330/// shares the same ref: its `HEAD` resolves to the new commit the moment the
1331/// rebase lands elsewhere, while its index and working directory keep
1332/// whatever the old commit put there until something says otherwise. Left
1333/// alone, the next `git status` there reads as the whole rebase turning up
1334/// as an unstaged diff, and the next commit would be staged against stale
1335/// content.
1336pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1337    git(worktree, &["reset", "--hard", "HEAD"]).await?;
1338    git(worktree, &["clean", "-fdx"]).await?;
1339    Ok(())
1340}
1341
1342/// Fetch one branch from `remote`, updating its remote-tracking ref.
1343///
1344/// The refspec is spelled out rather than left to `git fetch <remote>
1345/// <branch>`, which writes `FETCH_HEAD` and updates
1346/// `refs/remotes/<remote>/<branch>` only as a side effect of the remote's
1347/// configured refspec. Naming the destination makes the thing this function
1348/// exists for - a tracking ref that moved - the operation rather than a
1349/// consequence of configuration magi does not own.
1350///
1351/// Honest note: a CI failure was first read as proof that some git versions do
1352/// not update the tracking ref here. That was wrong - the fetch had nothing to
1353/// update because the test had pushed to the wrong branch - so this is
1354/// determinism, not a fix for a demonstrated portability bug.
1355///
1356/// Refs, not the working copy: nothing is checked out and no local branch
1357/// moves, so this is safe to run while the operator has uncommitted work.
1358/// Returned as a [`GitOut`] rather than an error so the caller can decide - a
1359/// machine with no network must still be able to start a run.
1360pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1361    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
1362    git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
1363}
1364
1365/// The best common ancestor of `a` and `b`, or an error when there is none.
1366pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
1367    Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
1368}
1369
1370/// Is `ancestor` an ancestor of (or equal to) `of`?
1371pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
1372    git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
1373        .await
1374        .is_ok_and(|o| o.ok())
1375}
1376
1377/// [`is_ancestor`] that keeps "no" apart from "could not tell": `merge-base
1378/// --is-ancestor` exits 0 for yes, 1 for no and anything else for an error
1379/// (an unknown object, a shallow clone), and reading an error as "no" would
1380/// report a merged change as unmerged.
1381pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
1382    let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
1383    match out.code {
1384        Some(0) => Ok(true),
1385        Some(1) => Ok(false),
1386        _ => bail!(
1387            "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
1388            crate::notices::exit_status(out.code),
1389            out.stderr
1390        ),
1391    }
1392}
1393
1394/// The commit `rev` names, or `None` when it names no commit here.
1395pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
1396    let spec = format!("{rev}^{{commit}}");
1397    let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
1398        .await
1399        .ok()?;
1400    (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
1401}
1402
1403/// Local and remote-tracking branches that contain `commit`.
1404pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
1405    let out = git(
1406        repo,
1407        &[
1408            "branch",
1409            "-a",
1410            "--contains",
1411            commit,
1412            "--format=%(refname:short)",
1413        ],
1414    )
1415    .await?;
1416    Ok(out
1417        .lines()
1418        .map(str::trim)
1419        .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
1420        .map(str::to_owned)
1421        .collect())
1422}
1423
1424/// Cherry-pick `commit` onto the worktree's HEAD under a neutral committer.
1425/// On a conflict the pick is aborted, so the worktree is left as it was, and
1426/// git's own words come back as the error.
1427pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
1428    let out = git_raw(
1429        worktree,
1430        &[
1431            "-c",
1432            "user.name=magi candidate",
1433            "-c",
1434            "user.email=magi@localhost",
1435            "cherry-pick",
1436            "-x",
1437            commit,
1438        ],
1439    )
1440    .await?;
1441    if out.ok() {
1442        return Ok(());
1443    }
1444    let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
1445    bail!(
1446        "cherry-pick of {commit} failed: {}",
1447        if out.stderr.is_empty() {
1448            out.stdout
1449        } else {
1450            out.stderr
1451        }
1452    )
1453}
1454
1455/// The tree object id of `rev`.
1456pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
1457    git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
1458}
1459
1460/// Does this ref resolve?
1461pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
1462    git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
1463        .await
1464        .is_ok_and(|o| o.ok())
1465}
1466
1467#[cfg(test)]
1468mod tests {
1469    #[test]
1470    fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
1471        for (native, expected) in [
1472            (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
1473            (
1474                r"\\?\UNC\server\share\work tree",
1475                "//server/share/work tree",
1476            ),
1477            (r"C:\temp\work tree", "C:/temp/work tree"),
1478            ("C:/temp/work tree", "C:/temp/work tree"),
1479        ] {
1480            assert_eq!(super::windows_cli_path(native), expected);
1481        }
1482    }
1483
1484    #[test]
1485    fn git_cli_path_spelling_does_not_alias_extended_only_names() {
1486        for path in [
1487            r"\\?\C:\temp.\copy",
1488            r"\\?\C:\temp \copy",
1489            r"\\?\C:\NUL.txt\copy",
1490            r"\\?\C:\COM1\copy",
1491        ] {
1492            assert!(super::windows_cli_path(path).starts_with("//?/"));
1493        }
1494    }
1495
1496    #[cfg(unix)]
1497    #[test]
1498    fn git_cli_path_spelling_preserves_native_paths_on_unix() {
1499        assert_eq!(
1500            super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
1501            r"/tmp/back\slash"
1502        );
1503    }
1504
1505    #[test]
1506    fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
1507        let temp = tempfile::tempdir().unwrap();
1508        let canonical = temp.path().canonicalize().unwrap();
1509        let printed = super::path_arg(&canonical);
1510        assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
1511        // Joining onto a Windows verbatim path normalizes parent components.
1512        // Preserve the spelling so the boundary, rather than PathBuf, rejects it.
1513        let noncanonical = format!("{printed}/child/..");
1514        std::fs::create_dir(canonical.join("child")).unwrap();
1515        assert!(super::canonical_output_path(&noncanonical).is_err());
1516        #[cfg(unix)]
1517        {
1518            let alias = canonical.join("alias");
1519            std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
1520            assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
1521        }
1522    }
1523
1524    use super::*;
1525
1526    #[test]
1527    fn worktree_holder_is_read_from_the_porcelain_listing() {
1528        let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
1529                       worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
1530                       worktree /wt/detached\nHEAD ccc\ndetached\n";
1531        assert_eq!(
1532            parse_worktree_holder(listing, "magi/f82f/A"),
1533            Some(PathBuf::from("/wt/cand-A"))
1534        );
1535        assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
1536        assert_eq!(parse_worktree_holder(listing, "other"), None);
1537    }
1538
1539    async fn scratch() -> (tempfile::TempDir, PathBuf) {
1540        let dir = tempfile::tempdir().unwrap();
1541        let repo = dir.path().join("repo");
1542        tokio::fs::create_dir_all(&repo).await.unwrap();
1543        git(&repo, &["init", "-b", "main"]).await.unwrap();
1544        git(&repo, &["config", "user.name", "test"]).await.unwrap();
1545        git(&repo, &["config", "user.email", "test@example.com"])
1546            .await
1547            .unwrap();
1548        tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
1549        git(&repo, &["add", "-A"]).await.unwrap();
1550        git(&repo, &["commit", "-m", "init"]).await.unwrap();
1551        (dir, repo)
1552    }
1553
1554    #[tokio::test]
1555    async fn restore_to_removes_nested_repositories_inside_submodules() {
1556        let (_parent_dir, repo) = scratch().await;
1557        let (_source_dir, source) = scratch().await;
1558        sh(
1559            &repo,
1560            &[
1561                "-c",
1562                "protocol.file.allow=always",
1563                "submodule",
1564                "add",
1565                &source.to_string_lossy(),
1566                "sub",
1567            ],
1568        );
1569        sh(&repo, &["commit", "-am", "add submodule"]);
1570        let pre = rev_parse(&repo, "HEAD").await.unwrap();
1571        let sub = repo.join("sub");
1572        sh(&sub, &["init", "nested"]);
1573        tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
1574            .await
1575            .unwrap();
1576
1577        restore_to(&repo, &pre).await.unwrap();
1578
1579        assert!(!sub.join("nested").exists());
1580        assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
1581        assert_eq!(
1582            rev_parse(&sub, "HEAD").await.unwrap(),
1583            rev_parse(&source, "HEAD").await.unwrap()
1584        );
1585        assert!(
1586            git(&repo, &["status", "--porcelain"])
1587                .await
1588                .unwrap()
1589                .is_empty()
1590        );
1591    }
1592
1593    #[tokio::test]
1594    async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
1595        let (_g, repo) = scratch().await;
1596
1597        // A side branch touching a different file: rebases cleanly.
1598        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1599        tokio::fs::write(repo.join("b.txt"), "side\n")
1600            .await
1601            .unwrap();
1602        git(&repo, &["add", "-A"]).await.unwrap();
1603        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1604
1605        // main moves under it, which is what a repository merging other
1606        // pull requests does to a competition that took two hours.
1607        git(&repo, &["checkout", "main"]).await.unwrap();
1608        tokio::fs::write(repo.join("c.txt"), "main\n")
1609            .await
1610            .unwrap();
1611        git(&repo, &["add", "-A"]).await.unwrap();
1612        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1613
1614        let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
1615        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1616            .await
1617            .unwrap();
1618        assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
1619        assert_eq!(
1620            commits_ahead(&repo, "main", "side").await.unwrap(),
1621            1,
1622            "one commit, replayed onto the new base"
1623        );
1624        assert!(
1625            !scratch_tree.exists(),
1626            "the throwaway worktree is not left behind"
1627        );
1628
1629        // A real conflict: both sides edit the same line.
1630        git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
1631        tokio::fs::write(repo.join("a.txt"), "clash\n")
1632            .await
1633            .unwrap();
1634        git(&repo, &["add", "-A"]).await.unwrap();
1635        git(&repo, &["commit", "-m", "clash"]).await.unwrap();
1636        git(&repo, &["checkout", "main"]).await.unwrap();
1637        tokio::fs::write(repo.join("a.txt"), "main edit\n")
1638            .await
1639            .unwrap();
1640        git(&repo, &["add", "-A"]).await.unwrap();
1641        git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
1642
1643        let before = rev_parse(&repo, "clash").await.unwrap();
1644        let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
1645            .await
1646            .unwrap()
1647            .expect("a same-line clash cannot be rebased silently");
1648        assert!(
1649            why.to_lowercase().contains("conflict"),
1650            "the reason is what git said, which is what a person needs: {why}"
1651        );
1652        assert_eq!(
1653            rev_parse(&repo, "clash").await.unwrap(),
1654            before,
1655            "a failed rebase leaves the branch exactly where it was"
1656        );
1657        assert!(!scratch_tree.exists(), "and cleans up after itself");
1658    }
1659
1660    #[tokio::test]
1661    async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
1662        let (_g, repo) = scratch().await;
1663        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1664        for name in ["b.txt", "c.txt"] {
1665            tokio::fs::write(repo.join(name), "side\n").await.unwrap();
1666            git(&repo, &["add", "-A"]).await.unwrap();
1667            git(
1668                &repo,
1669                &["commit", "-m", "magi: candidate A (uncommitted work)"],
1670            )
1671            .await
1672            .unwrap();
1673        }
1674        git(&repo, &["checkout", "main"]).await.unwrap();
1675        let before = rev_parse(&repo, "main").await.unwrap();
1676
1677        let out = merge_squash(&repo, "side", "an explicit subject")
1678            .await
1679            .unwrap();
1680        assert!(out.ok(), "{}", out.stderr);
1681        assert_eq!(
1682            commits_ahead(&repo, &before, "main").await.unwrap(),
1683            1,
1684            "squash adds exactly one commit onto the tip, not one per candidate commit"
1685        );
1686        let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
1687        assert_eq!(
1688            subject, "an explicit subject",
1689            "the candidate's own placeholder subject must not survive: {subject}"
1690        );
1691    }
1692
1693    #[tokio::test]
1694    async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
1695        let (_g, repo) = scratch().await;
1696        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1697        tokio::fs::write(repo.join("b.txt"), "side\n")
1698            .await
1699            .unwrap();
1700        git(&repo, &["add", "-A"]).await.unwrap();
1701        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1702        git(&repo, &["checkout", "main"]).await.unwrap();
1703
1704        let before = rev_parse(&repo, "side").await.unwrap();
1705        let out = merge_ff_only(&repo, "side").await.unwrap();
1706        assert!(out.ok(), "{}", out.stderr);
1707        assert_eq!(
1708            rev_parse(&repo, "main").await.unwrap(),
1709            before,
1710            "a fast-forward moves the base tip to the branch, no merge commit"
1711        );
1712    }
1713
1714    #[tokio::test]
1715    async fn merge_ff_only_refuses_to_write_a_merge_commit() {
1716        let (_g, repo) = scratch().await;
1717        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1718        tokio::fs::write(repo.join("b.txt"), "side\n")
1719            .await
1720            .unwrap();
1721        git(&repo, &["add", "-A"]).await.unwrap();
1722        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1723
1724        // main diverges, so a fast-forward is no longer possible.
1725        git(&repo, &["checkout", "main"]).await.unwrap();
1726        tokio::fs::write(repo.join("c.txt"), "main\n")
1727            .await
1728            .unwrap();
1729        git(&repo, &["add", "-A"]).await.unwrap();
1730        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1731
1732        let before = rev_parse(&repo, "main").await.unwrap();
1733        let out = merge_ff_only(&repo, "side").await.unwrap();
1734        assert!(!out.ok(), "a divergent branch cannot fast-forward");
1735        assert_eq!(
1736            rev_parse(&repo, "main").await.unwrap(),
1737            before,
1738            "a refused fast-forward must not touch main"
1739        );
1740    }
1741
1742    #[tokio::test]
1743    async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
1744        let (guard, repo) = scratch().await;
1745
1746        // An attached worktree of an existing branch - the shape a winner's
1747        // worktree keeps in `graph::Runner`, not the detached checkouts used
1748        // for judges and reviewers.
1749        git(&repo, &["branch", "side"]).await.unwrap();
1750        let side_wt = guard.path().join("side-wt");
1751        git(
1752            &repo,
1753            &["worktree", "add", &side_wt.to_string_lossy(), "side"],
1754        )
1755        .await
1756        .unwrap();
1757        tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
1758            .await
1759            .unwrap();
1760        git(&side_wt, &["add", "-A"]).await.unwrap();
1761        git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
1762
1763        // main moves under it.
1764        git(&repo, &["checkout", "main"]).await.unwrap();
1765        tokio::fs::write(repo.join("c.txt"), "main\n")
1766            .await
1767            .unwrap();
1768        git(&repo, &["add", "-A"]).await.unwrap();
1769        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1770
1771        // Rebase from a throwaway worktree, never from `side_wt` itself.
1772        let scratch_tree = guard.path().join("rebase-scratch");
1773        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1774            .await
1775            .unwrap();
1776        assert!(clean.is_none());
1777
1778        // `HEAD` in the sibling worktree already resolves to the rebased
1779        // commit - the ref is shared - but nothing has told its index or its
1780        // files, which still hold the pre-rebase checkout.
1781        assert_eq!(
1782            rev_parse(&side_wt, "HEAD").await.unwrap(),
1783            rev_parse(&repo, "side").await.unwrap(),
1784            "HEAD follows the moved ref"
1785        );
1786        assert!(
1787            !side_wt.join("c.txt").exists(),
1788            "stale until synced: main's new file has not reached this worktree's disk"
1789        );
1790
1791        sync_to_head(&side_wt).await.unwrap();
1792        assert!(side_wt.join("c.txt").is_file(), "synced now");
1793        assert!(
1794            side_wt.join("b.txt").is_file(),
1795            "the worktree's own committed work survives the sync"
1796        );
1797        assert!(is_clean(&side_wt).await.unwrap());
1798    }
1799
1800    #[tokio::test]
1801    async fn clean_repo_reports_clean_then_dirty() {
1802        let (_g, repo) = scratch().await;
1803        assert!(is_clean(&repo).await.unwrap());
1804        tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
1805        assert!(!is_clean(&repo).await.unwrap());
1806    }
1807
1808    async fn track(repo: &Path, name: &str, body: &str) {
1809        let p = repo.join(name);
1810        if let Some(d) = p.parent() {
1811            tokio::fs::create_dir_all(d).await.unwrap();
1812        }
1813        tokio::fs::write(&p, body).await.unwrap();
1814        git(repo, &["add", name]).await.unwrap();
1815        git(
1816            repo,
1817            &[
1818                "-c",
1819                "user.name=t",
1820                "-c",
1821                "user.email=t@localhost",
1822                "commit",
1823                "-q",
1824                "-m",
1825                "seed",
1826            ],
1827        )
1828        .await
1829        .unwrap();
1830    }
1831
1832    #[tokio::test]
1833    async fn rescue_withholds_a_foreign_lockfile() {
1834        let (_g, repo) = scratch().await;
1835        track(&repo, "web/bun.lock", "a\n").await;
1836        tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
1837            .await
1838            .unwrap();
1839        tokio::fs::write(repo.join("web/app.ts"), "real\n")
1840            .await
1841            .unwrap();
1842
1843        let r = rescue_commit(&repo, "rescue").await.unwrap();
1844        assert!(r.committed);
1845        assert_eq!(
1846            r.withheld,
1847            [Stray {
1848                path: "web/pnpm-lock.yaml".to_owned(),
1849                manager: "pnpm".to_owned(),
1850                kept_by: "web/bun.lock".to_owned(),
1851            }]
1852        );
1853        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1854            .await
1855            .unwrap();
1856        assert!(files.contains("web/app.ts"), "{files}");
1857        assert!(!files.contains("pnpm-lock"), "{files}");
1858        assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
1859    }
1860
1861    #[tokio::test]
1862    async fn rescue_with_only_a_stray_commits_nothing() {
1863        let (_g, repo) = scratch().await;
1864        track(&repo, "bun.lock", "a\n").await;
1865        tokio::fs::write(repo.join("yarn.lock"), "x\n")
1866            .await
1867            .unwrap();
1868        let r = rescue_commit(&repo, "rescue").await.unwrap();
1869        assert!(!r.committed);
1870        assert_eq!(r.withheld.len(), 1);
1871    }
1872
1873    #[tokio::test]
1874    async fn rescue_keeps_a_same_manager_lockfile_update() {
1875        let (_g, repo) = scratch().await;
1876        track(&repo, "bun.lock", "a\n").await;
1877        tokio::fs::write(repo.join("bun.lock"), "b\n")
1878            .await
1879            .unwrap();
1880        let r = rescue_commit(&repo, "rescue").await.unwrap();
1881        assert!(r.committed);
1882        assert!(r.withheld.is_empty());
1883        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1884            .await
1885            .unwrap();
1886        assert_eq!(files, "bun.lock");
1887    }
1888
1889    #[tokio::test]
1890    async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
1891        let (_g, repo) = scratch().await;
1892        track(&repo, "other/bun.lock", "a\n").await;
1893        tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
1894        tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
1895            .await
1896            .unwrap();
1897        let r = rescue_commit(&repo, "rescue").await.unwrap();
1898        assert!(r.committed);
1899        assert!(r.withheld.is_empty());
1900    }
1901
1902    #[test]
1903    fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
1904        let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
1905        assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
1906        assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
1907        assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
1908        // A manifest in another directory does not count.
1909        assert_eq!(
1910            stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
1911            1
1912        );
1913    }
1914
1915    #[tokio::test]
1916    async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
1917        let (guard, repo) = scratch().await;
1918        let wt = guard.path().join("scratch-wt");
1919        worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
1920        tokio::fs::write(wt.join("built.txt"), "build output")
1921            .await
1922            .unwrap();
1923        assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
1924        assert!(wt.join("built.txt").exists());
1925        let listing = git(&repo, &["worktree", "list", "--porcelain"])
1926            .await
1927            .unwrap();
1928        let registered = listing
1929            .lines()
1930            .filter_map(|line| line.strip_prefix("worktree "))
1931            .map(PathBuf::from)
1932            .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
1933            .expect("the refused removal must retain the worktree registration");
1934        assert!(worktree_remove(&repo, &wt).await.unwrap());
1935        assert!(!wt.exists());
1936        let listing = git(&repo, &["worktree", "list", "--porcelain"])
1937            .await
1938            .unwrap();
1939        assert!(!listing.lines().any(|line| {
1940            line.strip_prefix("worktree ")
1941                .is_some_and(|path| Path::new(path) == registered)
1942        }));
1943    }
1944
1945    #[tokio::test]
1946    async fn worktree_lifecycle_and_diff() {
1947        let (guard, repo) = scratch().await;
1948        let base = rev_parse(&repo, "HEAD").await.unwrap();
1949        let wt = guard.path().join("wt-a");
1950        worktree_add_branch(&repo, &wt, "magi/test/a", &base)
1951            .await
1952            .unwrap();
1953        tokio::fs::write(wt.join("b.txt"), "candidate\n")
1954            .await
1955            .unwrap();
1956
1957        assert!(commit_all(&wt, "candidate work").await.unwrap());
1958        assert!(!commit_all(&wt, "nothing left").await.unwrap());
1959
1960        assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
1961        let patch = diff(&wt, &base, "HEAD").await.unwrap();
1962        assert!(patch.contains("b.txt"), "patch was: {patch}");
1963        assert_eq!(
1964            changed_files(&wt, &base, "HEAD").await.unwrap(),
1965            ["b.txt".to_owned()]
1966        );
1967
1968        // The rescue commit must not carry the operator's identity.
1969        let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
1970            .await
1971            .unwrap();
1972        assert_eq!(author, "magi candidate <magi@localhost>");
1973
1974        assert!(worktree_remove(&repo, &wt).await.unwrap());
1975        assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
1976        assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
1977        assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
1978    }
1979
1980    #[tokio::test]
1981    async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
1982        let (guard, repo) = scratch().await;
1983        let base = rev_parse(&repo, "HEAD").await.unwrap();
1984        let wt = guard.path().join("wt-h");
1985        worktree_add_branch(&repo, &wt, "magi/test/h", &base)
1986            .await
1987            .unwrap();
1988        let hooks = guard.path().join("hooks");
1989        tokio::fs::create_dir_all(&hooks).await.unwrap();
1990
1991        assert!(enable_worktree_config(&repo).await.unwrap());
1992        set_worktree_hooks_path(&wt, &hooks).await.unwrap();
1993
1994        let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
1995            .await
1996            .unwrap();
1997        assert!(!in_wt.is_empty());
1998        let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
1999            .await
2000            .unwrap();
2001        assert!(
2002            !in_primary.ok(),
2003            "primary worktree must keep its own hooks: {in_primary:?}"
2004        );
2005
2006        disable_worktree_config(&repo).await.unwrap();
2007    }
2008
2009    #[tokio::test]
2010    async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
2011        let (_g, repo) = scratch().await;
2012
2013        // Two runs in the same repository, as `Config::daemon.max_concurrent_runs`
2014        // now allows: both acquire before either is done.
2015        acquire_worktree_config(&repo).await.unwrap();
2016        acquire_worktree_config(&repo).await.unwrap();
2017
2018        let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2019            .await
2020            .unwrap();
2021        assert_eq!(on, "true");
2022
2023        // The first run to finish releases its own reference. A plain
2024        // `disable_worktree_config` here is exactly the bug: it would turn
2025        // the setting off while the second run still depends on it.
2026        release_worktree_config(&repo).await.unwrap();
2027        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2028            .await
2029            .unwrap();
2030        assert_eq!(
2031            still_on, "true",
2032            "a sibling run's release must not disable the setting for the one still working"
2033        );
2034
2035        // Only the last release actually turns it back off.
2036        release_worktree_config(&repo).await.unwrap();
2037        let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
2038            .await
2039            .unwrap();
2040        assert!(
2041            !after.ok(),
2042            "the last release must turn the setting back off: {after:?}"
2043        );
2044    }
2045
2046    #[tokio::test]
2047    async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
2048        let (_g, repo) = scratch().await;
2049        git(&repo, &["config", "extensions.worktreeConfig", "true"])
2050            .await
2051            .unwrap();
2052
2053        // magi did not turn this on, so even after every acquire is released,
2054        // it must not turn it off - that is what a bare `enable_worktree_config`
2055        // already promised for the single-run case, and the ref-counted
2056        // version must keep that promise.
2057        acquire_worktree_config(&repo).await.unwrap();
2058        release_worktree_config(&repo).await.unwrap();
2059
2060        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2061            .await
2062            .unwrap();
2063        assert_eq!(still_on, "true");
2064    }
2065
2066    #[tokio::test]
2067    async fn local_exclude_is_idempotent() {
2068        let (_g, repo) = scratch().await;
2069        local_exclude(&repo, "/.magi/").await.unwrap();
2070        local_exclude(&repo, "/.magi/").await.unwrap();
2071        let path = repo.join(".git/info/exclude");
2072        let body = tokio::fs::read_to_string(&path).await.unwrap();
2073        assert_eq!(body.matches("/.magi/").count(), 1);
2074    }
2075
2076    fn sh(cwd: &Path, args: &[&str]) {
2077        let out = std::process::Command::new("git")
2078            .quiet()
2079            .args(args)
2080            .current_dir(cwd)
2081            .output()
2082            .unwrap();
2083        assert!(
2084            out.status.success(),
2085            "git {args:?}: {}",
2086            String::from_utf8_lossy(&out.stderr)
2087        );
2088    }
2089
2090    /// A checkout whose `origin` is a local bare repository holding `trunk`,
2091    /// with `origin/HEAD` unset (as after `git remote add` + push).
2092    async fn with_remote() -> (tempfile::TempDir, PathBuf) {
2093        let (g, repo) = scratch().await;
2094        let bare = g.path().join("bare.git");
2095        sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2096        sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2097        sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
2098        sh(&repo, &["fetch", "origin"]);
2099        (g, repo)
2100    }
2101
2102    #[test]
2103    fn remote_head_branch_strips_only_the_matching_remote() {
2104        assert_eq!(
2105            remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
2106            Some("main")
2107        );
2108        assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
2109        assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
2110    }
2111
2112    #[tokio::test]
2113    async fn merge_base_branch_reads_origin_head_when_present() {
2114        let (_g, repo) = with_remote().await;
2115        sh(&repo, &["remote", "set-head", "origin", "trunk"]);
2116        assert_eq!(
2117            merge_base_branch(&repo, "origin", None).await.unwrap(),
2118            "trunk"
2119        );
2120    }
2121
2122    #[tokio::test]
2123    async fn merge_base_branch_recovers_a_missing_origin_head() {
2124        let (_g, repo) = with_remote().await;
2125        // Newer git sets it on fetch; make the precondition true everywhere.
2126        sh(&repo, &["remote", "set-head", "origin", "-d"]);
2127        let head = git_raw(
2128            &repo,
2129            &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
2130        )
2131        .await
2132        .unwrap();
2133        assert!(!head.ok(), "precondition: no origin/HEAD");
2134        assert_eq!(
2135            merge_base_branch(&repo, "origin", None).await.unwrap(),
2136            "trunk"
2137        );
2138    }
2139
2140    #[tokio::test]
2141    async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
2142        let (_g, repo) = scratch().await;
2143        let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
2144        assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
2145    }
2146
2147    #[tokio::test]
2148    async fn merge_base_branch_prefers_the_explicit_base() {
2149        let (_g, repo) = with_remote().await;
2150        assert_eq!(
2151            merge_base_branch(&repo, "origin", Some("release"))
2152                .await
2153                .unwrap(),
2154            "release"
2155        );
2156    }
2157
2158    #[tokio::test]
2159    async fn merge_base_branch_names_an_unfetched_default_branch() {
2160        // A remote added after the fact, never fetched: no tracking refs, so
2161        // `set-head -a` cannot work, but the remote's own HEAD still names it.
2162        let (g, repo) = scratch().await;
2163        let bare = g.path().join("bare.git");
2164        sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2165        sh(
2166            &repo,
2167            &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
2168        );
2169        sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2170        assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
2171        assert_eq!(
2172            merge_base_branch(&repo, "origin", None).await.unwrap(),
2173            "trunk"
2174        );
2175    }
2176
2177    #[test]
2178    fn symref_branch_reads_ls_remote_output() {
2179        assert_eq!(
2180            symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
2181            Some("main")
2182        );
2183        assert_eq!(symref_branch("abc\tHEAD\n"), None);
2184    }
2185}