Skip to main content

magi/
git.rs

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