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