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