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    git_raw_command(cwd, args, false).await
35}
36
37pub(crate) async fn git_raw_command(
38    cwd: &Path,
39    args: &[&str],
40    kill_on_drop: bool,
41) -> Result<GitOut> {
42    #[cfg(test)]
43    crate::web::request_cost::git();
44    let out = Command::new("git")
45        .args(args)
46        .current_dir(cwd)
47        .quiet()
48        // A hook that opens an editor or a credential prompt would hang a
49        // headless run forever.
50        .env("GIT_TERMINAL_PROMPT", "0")
51        .env("GIT_EDITOR", "true")
52        .stdin(Stdio::null())
53        .kill_on_drop(kill_on_drop)
54        .output()
55        .await
56        .with_context(|| format!("spawn git {}", args.join(" ")))?;
57    Ok(GitOut {
58        code: out.status.code(),
59        stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
60        stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
61    })
62}
63
64/// Native filesystem paths stay canonical internally; Git for Windows needs
65/// conventional drive/UNC spelling for path arguments instead of `\\?\`.
66pub(crate) fn path_arg(path: &Path) -> String {
67    #[cfg(windows)]
68    let unicode = path.to_str().is_some();
69    let path = path.to_string_lossy();
70    #[cfg(windows)]
71    {
72        if unicode {
73            windows_cli_path(&path)
74        } else {
75            path.into_owned()
76        }
77    }
78    #[cfg(not(windows))]
79    {
80        path.into_owned()
81    }
82}
83
84#[cfg(any(windows, test))]
85fn windows_cli_path(path: &str) -> String {
86    let path = path.replace('\\', "/");
87    if path.starts_with("//?/")
88        && path[4..].split('/').any(|part| {
89            let name = part.split('.').next().unwrap_or("").to_ascii_uppercase();
90            part.ends_with(['.', ' '])
91                || matches!(
92                    name.as_str(),
93                    "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
94                )
95                || (name.len() == 4
96                    && (name.starts_with("COM") || name.starts_with("LPT"))
97                    && matches!(name.as_bytes()[3], b'1'..=b'9'))
98        })
99    {
100        // These names need the native namespace; stripping it can select a
101        // different file. Leave them unsupported by Git rather than alias them.
102        return path;
103    }
104    if let Some(unc) = path.strip_prefix("//?/UNC/") {
105        return format!("//{unc}");
106    }
107    if let Some(drive) = path.strip_prefix("//?/")
108        && drive.as_bytes().get(1) == Some(&b':')
109        && drive.as_bytes().get(2) == Some(&b'/')
110        && drive.as_bytes()[0].is_ascii_alphabetic()
111    {
112        return drive.to_owned();
113    }
114    path
115}
116
117/// Accept Git's platform spelling only when it names a canonical filesystem
118/// path. Symlink aliases and redirects still fail this comparison.
119pub(crate) fn canonical_output_path(value: &str) -> Result<PathBuf> {
120    let path = PathBuf::from(value);
121    let canonical = path.canonicalize()?;
122    #[cfg(windows)]
123    let same_path = windows_cli_path(path.to_str().context("non UTF-8 Git path")?)
124        == windows_cli_path(canonical.to_str().context("non UTF-8 canonical Git path")?);
125    #[cfg(not(windows))]
126    let same_path = path == canonical;
127    ensure!(same_path, "noncanonical Git path: {}", path.display());
128    Ok(canonical)
129}
130
131/// Fetch `origin`'s branches into `refs/remotes/origin/*` in `cwd`, bounded by
132/// `timeout`.
133///
134/// The destination is fixed on the command line and the remote is addressed by
135/// its URL rather than its name. A plain `git fetch origin` follows the
136/// configured `remote.origin.fetch`, which can map onto local branches
137/// (`+refs/heads/main:refs/heads/main`) or a single branch, and even a fetch
138/// with an explicit refspec updates remote-tracking refs from that config
139/// when the remote is named. By URL, nothing but the refspec given here is
140/// written: no local branch, HEAD, index or working tree. A child still
141/// running at the deadline is killed on drop.
142pub async fn fetch_origin(cwd: &Path, timeout: std::time::Duration) -> Result<()> {
143    let url = git(cwd, &["remote", "get-url", "origin"]).await?;
144    #[cfg(test)]
145    crate::web::request_cost::git();
146    let fut = Command::new("git")
147        .args([
148            "fetch",
149            "--quiet",
150            "--no-tags",
151            "--no-recurse-submodules",
152            "--no-write-fetch-head",
153            "--",
154            url.as_str(),
155            "+refs/heads/*:refs/remotes/origin/*",
156        ])
157        .current_dir(cwd)
158        .quiet()
159        .env("GIT_TERMINAL_PROMPT", "0")
160        .stdin(Stdio::null())
161        .kill_on_drop(true)
162        .output();
163    let out = tokio::time::timeout(timeout, fut)
164        .await
165        .map_err(|_| anyhow::anyhow!("git fetch timed out after {}s", timeout.as_secs()))?
166        .context("spawn git fetch")?;
167    if !out.status.success() {
168        bail!(
169            "git fetch failed ({}): {}",
170            crate::notices::exit_status(out.status.code()),
171            String::from_utf8_lossy(&out.stderr).trim_end()
172        );
173    }
174    Ok(())
175}
176
177/// Run `git`, failing on a non-zero exit status.
178pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
179    let out = git_raw(cwd, args).await?;
180    if !out.ok() {
181        bail!(
182            "git {} failed in {} ({}): {}",
183            args.join(" "),
184            cwd.display(),
185            crate::notices::exit_status(out.code),
186            if out.stderr.is_empty() {
187                out.stdout.as_str()
188            } else {
189                out.stderr.as_str()
190            }
191        );
192    }
193    Ok(out.stdout)
194}
195
196/// Absolute path to the top level of the working tree containing `path`.
197pub async fn toplevel(path: &Path) -> Result<PathBuf> {
198    let out = Command::from(toplevel_command(path))
199        .kill_on_drop(true)
200        .output()
201        .await;
202    toplevel_output(path, out)
203}
204
205/// Canonical checkout root for synchronous record validation.
206pub(crate) fn toplevel_blocking(path: &Path) -> Result<PathBuf> {
207    toplevel_output(path, toplevel_command(path).output())?
208        .canonicalize()
209        .with_context(|| format!("canonicalize Git checkout root of {}", path.display()))
210}
211
212fn toplevel_command(path: &Path) -> std::process::Command {
213    #[cfg(test)]
214    crate::web::request_cost::git();
215    let mut command = std::process::Command::new("git");
216    command
217        .args(["rev-parse", "--show-toplevel"])
218        .current_dir(path)
219        .quiet()
220        .stdin(Stdio::null());
221    // Checkout identity comes from cwd, never the invoking Git process.
222    for key in [
223        "GIT_DIR",
224        "GIT_WORK_TREE",
225        "GIT_IMPLICIT_WORK_TREE",
226        "GIT_COMMON_DIR",
227        "GIT_CONFIG",
228        "GIT_CONFIG_PARAMETERS",
229        "GIT_CONFIG_COUNT",
230        "GIT_CONFIG_GLOBAL",
231        "GIT_CONFIG_SYSTEM",
232        "GIT_CEILING_DIRECTORIES",
233        "GIT_DISCOVERY_ACROSS_FILESYSTEM",
234        "GIT_PREFIX",
235    ] {
236        command.env_remove(key);
237    }
238    command
239}
240
241fn toplevel_output(path: &Path, out: std::io::Result<std::process::Output>) -> Result<PathBuf> {
242    let out = out.with_context(|| format!("read Git checkout root of {}", path.display()))?;
243    ensure!(
244        out.status.success(),
245        "cannot read Git checkout root of {}: {}",
246        path.display(),
247        String::from_utf8_lossy(&out.stderr).trim_end()
248    );
249    Ok(PathBuf::from(
250        std::str::from_utf8(&out.stdout)?.trim_end_matches(['\r', '\n']),
251    ))
252}
253
254/// Compare checkout roots, not common Git dirs. Paths already equal (including
255/// canonical aliases) need no Git lookup, preserving non-Git conversation scopes.
256pub(crate) fn same_checkout(left: &Path, right: &Path) -> Result<bool> {
257    if left == right {
258        return Ok(true);
259    }
260    let canonical = |path: &Path| {
261        path.canonicalize()
262            .with_context(|| format!("resolve repository {}", path.display()))
263    };
264    let left = canonical(left)?;
265    let right = canonical(right)?;
266    Ok(left == right || toplevel_blocking(&left)? == toplevel_blocking(&right)?)
267}
268
269/// Resolve a revision to a full object id.
270pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
271    git(repo, &["rev-parse", rev]).await
272}
273
274/// Currently checked-out branch, or `None` when detached.
275pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
276    let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
277    Ok(if out.ok() && !out.stdout.is_empty() {
278        Some(out.stdout)
279    } else {
280        None
281    })
282}
283
284/// The branch a `refs/remotes/<remote>/HEAD` symref names, e.g.
285/// `refs/remotes/origin/main` -> `main`. Pure, and shared with
286/// `Config::discover` so the branch magi reads its config from and the branch
287/// a run starts from can never come from two different readings.
288pub fn remote_head_branch(remote: &str, symref: &str) -> Option<String> {
289    symref
290        .trim()
291        .strip_prefix(&format!("refs/remotes/{remote}/"))
292        .filter(|b| !b.is_empty() && *b != "HEAD")
293        .map(str::to_owned)
294}
295
296/// Record `refs/remotes/<remote>/HEAD` -> `<remote>/<base>` when it is absent,
297/// so a later read of the remote's default (`Config::discover`) agrees with
298/// the branch just resolved even when git did not create the symref on fetch
299/// (`followRemoteHEAD=never`, old git). Moves only `refs/remotes`; an existing
300/// symref is left alone. Best effort.
301pub async fn ensure_remote_head(repo: &Path, remote: &str, base: &str) {
302    let head = format!("refs/remotes/{remote}/HEAD");
303    if git_raw(repo, &["symbolic-ref", "--quiet", &head])
304        .await
305        .is_ok_and(|o| o.ok())
306    {
307        return;
308    }
309    let target = format!("refs/remotes/{remote}/{base}");
310    let _ = git_raw(repo, &["symbolic-ref", &head, &target]).await;
311}
312
313/// The branch in `git ls-remote --symref <remote> HEAD` output
314/// (`ref: refs/heads/main\tHEAD`).
315fn symref_branch(out: &str) -> Option<String> {
316    out.lines()
317        .find_map(|l| l.strip_prefix("ref: refs/heads/"))
318        .and_then(|l| l.split_whitespace().next())
319        .map(str::to_owned)
320}
321
322/// Which branch of `remote` is the base: `explicit` (`[merge] base`) wins,
323/// else the remote's default branch as recorded in `refs/remotes/<remote>/HEAD`.
324/// When that ref is missing (a checkout that was never cloned from it), ask the
325/// remote once with `git remote set-head <remote> -a`, which moves only
326/// `refs/remotes`. Never the checked-out branch: a detached or stale primary
327/// checkout must not decide what a run branches off.
328pub async fn merge_base_branch(
329    repo: &Path,
330    remote: &str,
331    explicit: Option<&str>,
332) -> Result<String> {
333    if let Some(b) = explicit.map(str::trim).filter(|b| !b.is_empty()) {
334        return Ok(b.to_owned());
335    }
336    let head = format!("refs/remotes/{remote}/HEAD");
337    let read = || async {
338        let out = git_raw(repo, &["symbolic-ref", "--quiet", &head])
339            .await
340            .ok()?;
341        if out.ok() {
342            remote_head_branch(remote, &out.stdout)
343        } else {
344            None
345        }
346    };
347    if let Some(b) = read().await {
348        return Ok(b);
349    }
350    let set = git_raw(repo, &["remote", "set-head", remote, "-a"]).await;
351    if let Some(b) = read().await {
352        return Ok(b);
353    }
354    // `set-head -a` insists the tracking ref already exists, which it does not
355    // for a remote that was never fetched (or a single-branch clone of another
356    // branch). Ask the remote for its HEAD symref instead: that only names the
357    // branch, and the fetch that follows (`resolve_base`) creates the ref.
358    if let Ok(o) = git_raw(repo, &["ls-remote", "--symref", remote, "HEAD"]).await
359        && o.ok()
360        && let Some(b) = symref_branch(&o.stdout)
361    {
362        return Ok(b);
363    }
364    let why = match set {
365        Ok(o) if !o.ok() => o.stderr.lines().next().unwrap_or("").trim().to_owned(),
366        Ok(_) => "the remote reported no default branch".to_owned(),
367        Err(e) => e.to_string(),
368    };
369    bail!(
370        "cannot tell which branch of `{remote}` is the base ({why}): set [merge] base \
371         (and remote) in magi.toml, or run `git remote set-head {remote} -a`. magi does \
372         not fall back to the checked-out branch, which may be detached or stale"
373    )
374}
375
376/// Is the working tree free of tracked modifications and untracked files?
377pub async fn is_clean(repo: &Path) -> Result<bool> {
378    Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
379}
380
381/// `git status --porcelain`, for reporting what is dirty.
382pub async fn status_porcelain(repo: &Path) -> Result<String> {
383    git(repo, &["status", "--porcelain"]).await
384}
385
386/// Create a worktree at `path` with a fresh branch `branch` starting at `base`.
387pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
388    if let Some(parent) = path.parent() {
389        tokio::fs::create_dir_all(parent).await.ok();
390    }
391    let path_s = path_arg(path);
392    git(repo, &["worktree", "add", "-b", branch, &path_s, base])
393        .await
394        .map(|_| ())
395}
396
397/// Check out an existing branch, optionally retaining the caller's force policy.
398pub(crate) async fn worktree_add_existing(
399    repo: &Path,
400    path: &Path,
401    branch: &str,
402    force: bool,
403) -> Result<()> {
404    if let Some(parent) = path.parent() {
405        tokio::fs::create_dir_all(parent).await.ok();
406    }
407    let path_s = path_arg(path);
408    if force {
409        git(repo, &["worktree", "add", "--force", &path_s, branch]).await
410    } else {
411        git(repo, &["worktree", "add", &path_s, branch]).await
412    }
413    .map(|_| ())
414}
415
416/// Create a worktree at `path` with a detached HEAD at `rev`.
417pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
418    if let Some(parent) = path.parent() {
419        tokio::fs::create_dir_all(parent).await.ok();
420    }
421    let path_s = path_arg(path);
422    git(repo, &["worktree", "add", "--detach", &path_s, rev])
423        .await
424        .map(|_| ())
425}
426
427/// Move an existing detached worktree to `rev`, discarding local state.
428pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
429    reset_detached_keep_ignored(worktree, rev).await?;
430    clean_all(worktree).await
431}
432
433/// [`reset_detached`] without its final `clean -fdx`, so a caller can run
434/// project cleanup between the reset and the clean.
435pub async fn reset_detached_keep_ignored(worktree: &Path, rev: &str) -> Result<()> {
436    git(worktree, &["checkout", "--detach", rev]).await?;
437    git(worktree, &["reset", "--hard", rev]).await.map(|_| ())
438}
439
440/// Where `branch` is checked out, if some worktree holds it.
441///
442/// Read from `git worktree list --porcelain` rather than out of an error
443/// message, which varies with git's version and locale.
444pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
445    let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
446    Ok(parse_worktree_holder(&listing, branch))
447}
448
449fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
450    let want = format!("refs/heads/{branch}");
451    let mut path: Option<PathBuf> = None;
452    for line in listing.lines() {
453        if let Some(p) = line.strip_prefix("worktree ") {
454            path = Some(PathBuf::from(p));
455        } else if line.strip_prefix("branch ") == Some(want.as_str()) {
456            return path;
457        }
458    }
459    None
460}
461
462/// Force removal of a disposable worktree, including build output or conflicts.
463/// Candidate work must use [`worktree_remove_clean`] instead.
464/// Returns `Ok(false)` on refusal; callers must retain their ownership record.
465pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
466    let path_s = path_arg(path);
467    let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
468    if out.ok() {
469        return Ok(true);
470    }
471    // Do not prune metadata for an existing tree after any refusal.
472    if !path.exists() {
473        git_raw(repo, &["worktree", "prune"]).await?;
474    }
475    Ok(false)
476}
477
478/// Remove a worktree only if git finds it clean: no `--force`, so a change
479/// made after the caller last looked is refused rather than thrown away.
480/// Ignored files (`target/`) do not count as changes and go with it.
481pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
482    let path_s = path_arg(path);
483    Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
484}
485
486/// Unregister a linked worktree whose directory is about to be deleted by
487/// hand, so the path can be `worktree add`-ed again.
488///
489/// A linked worktree's `.git` is a file whose `gitdir:` line names the
490/// bookkeeping entry inside its repository's admin directory; pruning from
491/// there removes the registration without touching the directory. No-op when
492/// `dir` is not a registered worktree (`.git` missing or not a `gitdir:`
493/// link): nothing was registered, nothing survives removal.
494pub async fn remove_worktree_from_linked(dir: &Path) {
495    let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
496        return;
497    };
498    let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
499        return;
500    };
501    // `<repo>/.git/worktrees/<name>`, so the repository's git dir is two
502    // levels up from here.
503    let admin = Path::new(admin);
504    let Some(common) = admin.parent().and_then(Path::parent) else {
505        return;
506    };
507    let common_s = common.to_string_lossy();
508    let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
509}
510
511/// Drop registrations for worktrees whose directory is already gone.
512///
513/// `git worktree remove` already does this for the path it just removed, but
514/// a directory deleted by hand - [`crate::clean::fold_orphaned_worktrees`], or
515/// an operator's own `rm -rf` - leaves the registration behind, and a
516/// registered path refuses a fresh `worktree add` until something prunes it.
517/// The operator's own machine had 31 such registrations sitting in one
518/// repository, all of them for directories that no longer existed.
519pub async fn worktree_prune(repo: &Path) -> Result<()> {
520    git(repo, &["worktree", "prune"]).await.map(|_| ())
521}
522
523/// Delete a branch, ignoring "not found".
524pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
525    Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
526}
527
528/// Does `branch` exist?
529pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
530    let refname = format!("refs/heads/{branch}");
531    Ok(
532        git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
533            .await?
534            .ok(),
535    )
536}
537
538/// Does `remote` have `branch`? `Err` when that cannot be told (unreachable
539/// remote), which callers must not read as "no".
540pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
541    let refname = format!("refs/heads/{branch}");
542    let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
543    match out.code {
544        Some(0) => Ok(true),
545        Some(2) => Ok(false),
546        code => bail!(
547            "git ls-remote {remote} failed ({}): {}",
548            crate::notices::exit_status(code),
549            out.stderr
550        ),
551    }
552}
553
554/// Patch of `head` against the merge base with `base`.
555pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
556    let range = format!("{base}...{head}");
557    git(
558        worktree,
559        &["diff", "--no-color", "--no-ext-diff", "-M", &range],
560    )
561    .await
562}
563
564/// `--stat` summary of `base...head`.
565pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
566    let range = format!("{base}...{head}");
567    git(worktree, &["diff", "--no-color", "--stat", &range]).await
568}
569
570/// Total changed lines (added + removed) between two revisions, from
571/// `--numstat`. `None` when git could not say, or a binary file changed
572/// (numstat prints `-` for it). This measurement does not determine acceptance.
573pub async fn changed_lines(worktree: &Path, base: &str, head: &str) -> Option<usize> {
574    let out = git_raw(worktree, &["diff", "--numstat", base, head])
575        .await
576        .ok()?;
577    if !out.ok() {
578        return None;
579    }
580    let mut total = 0usize;
581    for line in out.stdout.lines().filter(|l| !l.trim().is_empty()) {
582        let mut cols = line.split('\t');
583        let added: usize = cols.next()?.parse().ok()?;
584        let removed: usize = cols.next()?.parse().ok()?;
585        total = total.saturating_add(added).saturating_add(removed);
586    }
587    Some(total)
588}
589
590/// Put the worktree back on `rev`: tracked files reset, untracked files
591/// removed. Ignored paths (a `[worktree] setup`'s products are hidden through
592/// the per-worktree excludes) are left alone.
593pub async fn restore_to(worktree: &Path, rev: &str) -> Result<()> {
594    git(worktree, &["reset", "--hard", "-q", rev]).await?;
595    // `-ff`: a single `-f` skips untracked nested git repositories, which is
596    // what a submodule or clone added by a rejected change leaves behind.
597    git(worktree, &["clean", "-ffdq"]).await?;
598    // The parent's reset leaves an initialised submodule's own tree alone
599    // (`submodule.recurse` defaults to false): put each back on the commit the
600    // parent records (`--checkout` overrides a configured
601    // `submodule.<name>.update` such as `none`), and drop what is untracked inside. No-ops without
602    // submodules; an error is an unconfirmed restore.
603    git(
604        worktree,
605        &[
606            "submodule",
607            "--quiet",
608            "update",
609            "--recursive",
610            "--force",
611            "--checkout",
612        ],
613    )
614    .await?;
615    git(
616        worktree,
617        &[
618            "submodule",
619            "--quiet",
620            "foreach",
621            "--recursive",
622            "git clean -ffdq",
623        ],
624    )
625    .await?;
626    Ok(())
627}
628
629/// Number of files touched by `base...head`.
630pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
631    let range = format!("{base}...{head}");
632    let out = git(worktree, &["diff", "--name-only", &range]).await?;
633    Ok(out.lines().map(str::to_owned).collect())
634}
635
636/// Subject and body of every commit in `base..head`, oldest first. Fields are
637/// split on control characters git never prints in a message, so an empty
638/// subject or a body full of separators cannot shift a record.
639pub async fn commit_log(worktree: &Path, base: &str, head: &str) -> Result<Vec<(String, String)>> {
640    let range = format!("{base}..{head}");
641    let out = git(
642        worktree,
643        &[
644            "log",
645            "--reverse",
646            "--no-color",
647            "--format=%s%x1f%b%x00",
648            &range,
649        ],
650    )
651    .await?;
652    Ok(out
653        .split('\0')
654        .filter_map(|rec| {
655            let rec = rec.trim_start_matches('\n');
656            if rec.trim().is_empty() {
657                return None;
658            }
659            let (subject, body) = rec.split_once('\x1f').unwrap_or((rec, ""));
660            Some((subject.trim().to_owned(), body.trim().to_owned()))
661        })
662        .collect())
663}
664
665/// One-line log of `base..head`, oldest first.
666pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
667    let range = format!("{base}..{head}");
668    git(
669        worktree,
670        &["log", "--reverse", "--format=%s%n%b%n--", &range],
671    )
672    .await
673}
674
675/// Subjects of the commits in `base..head`, oldest first. NUL-terminated so an
676/// empty subject keeps its place instead of shifting the later ones forward.
677pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
678    let range = format!("{base}..{head}");
679    let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
680    let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
681    // Whatever follows the last terminator is just the trailing newline.
682    parts.pop();
683    Ok(parts)
684}
685
686/// How many commits `head` is ahead of `base`.
687pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
688    let range = format!("{base}..{head}");
689    let out = git(worktree, &["rev-list", "--count", &range]).await?;
690    Ok(out.trim().parse().unwrap_or(0))
691}
692
693/// Neutral git author/committer name used for magi-owned mechanical and rescue commits.
694pub const NEUTRAL_IDENTITY_NAME: &str = "magi candidate";
695
696/// Neutral git author/committer email used for magi-owned mechanical and rescue commits.
697pub const NEUTRAL_IDENTITY_EMAIL: &str = "magi@localhost";
698
699/// Commit header and message metadata read directly from a git commit object.
700#[derive(Debug, Clone, PartialEq, Eq)]
701pub struct CommitProvenance {
702    /// Full 40-hex commit SHA (`%H`).
703    pub commit: String,
704    /// Parent commit SHAs in order (`%P`).
705    pub parents: Vec<String>,
706    /// Raw author name (`%an`, ignoring `.mailmap`).
707    pub author_name: String,
708    /// Raw author email (`%ae`, ignoring `.mailmap`).
709    pub author_email: String,
710    /// Raw committer name (`%cn`, ignoring `.mailmap`).
711    pub committer_name: String,
712    /// Raw committer email (`%ce`, ignoring `.mailmap`).
713    pub committer_email: String,
714    /// Full commit message (`%B`), with at most one trailing line ending removed.
715    pub message: String,
716}
717
718/// Inspect exact parent, identity, and message metadata for commit `rev`.
719pub async fn commit_provenance(repo: &Path, rev: &str) -> Result<CommitProvenance> {
720    let spec = format!("{rev}^{{commit}}");
721    let out = git_raw(
722        repo,
723        &[
724            "-c",
725            "log.showSignature=false",
726            "show",
727            "-s",
728            "--format=%H%x00%P%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x00end",
729            &spec,
730            "--",
731        ],
732    )
733    .await?;
734    ensure!(
735        out.ok(),
736        "git show commit provenance for {rev} failed: {}",
737        out.stderr
738    );
739    let parts: Vec<&str> = out.stdout.split('\0').collect();
740    ensure!(
741        parts.len() == 8 && parts[7] == "end",
742        "unexpected git commit provenance output for {rev}"
743    );
744    let parents = parts[1].split_whitespace().map(str::to_owned).collect();
745    let message = parts[6]
746        .strip_suffix("\r\n")
747        .or_else(|| parts[6].strip_suffix('\n'))
748        .unwrap_or(parts[6])
749        .to_owned();
750    Ok(CommitProvenance {
751        commit: parts[0].to_owned(),
752        parents,
753        author_name: parts[2].to_owned(),
754        author_email: parts[3].to_owned(),
755        committer_name: parts[4].to_owned(),
756        committer_email: parts[5].to_owned(),
757        message,
758    })
759}
760
761/// Stage everything and commit under a neutral identity.
762///
763/// Used to rescue an agent that edited files but never committed: without this
764/// its candidate would silently be empty. The neutral identity is part of the
765/// blindness contract — a real `user.name` in a candidate's history would name
766/// the operator, and an agent-configured one would name the vendor.
767pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
768    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
769        return Ok(false);
770    }
771    git(worktree, &["add", "-A"]).await?;
772    // What `[worktree] setup` produced is not the agent's work.
773    if !crate::worktree_setup::withheld_paths(worktree)
774        .await
775        .is_empty()
776    {
777        crate::worktree_setup::unstage_products(worktree).await?;
778        if git_raw(worktree, &["diff", "--cached", "--quiet"])
779            .await?
780            .ok()
781        {
782            return Ok(false);
783        }
784    }
785    let user_name = format!("user.name={NEUTRAL_IDENTITY_NAME}");
786    let user_email = format!("user.email={NEUTRAL_IDENTITY_EMAIL}");
787    let out = git_raw(
788        worktree,
789        &[
790            "-c",
791            &user_name,
792            "-c",
793            &user_email,
794            "commit",
795            "--no-verify",
796            "-m",
797            message,
798        ],
799    )
800    .await?;
801    if !out.ok() {
802        bail!("rescue commit failed: {}", out.stderr);
803    }
804    Ok(true)
805}
806
807/// A freshly created lockfile that belongs to a package manager the directory
808/// does not use, and was therefore left out of a rescue commit.
809#[derive(Debug, Clone, PartialEq, Eq)]
810pub struct Stray {
811    /// Repo-relative path, forward slashes.
812    pub path: String,
813    /// The package manager the file belongs to (`pnpm`, `cargo`, ...).
814    pub manager: String,
815    /// What made it foreign: the tracked lockfile (or `Cargo.toml`'s absence)
816    /// that says which manager the directory really uses.
817    pub kept_by: String,
818}
819
820/// What [`rescue_commit`] did.
821#[derive(Debug, Default)]
822pub struct Rescue {
823    /// Whether a commit was made.
824    pub committed: bool,
825    /// Files left untracked in the worktree instead of being committed.
826    pub withheld: Vec<Stray>,
827}
828
829/// `(ecosystem, manager)` for a lockfile's file name.
830fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
831    Some(match name {
832        "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
833        "yarn.lock" => ("node", "yarn"),
834        "pnpm-lock.yaml" => ("node", "pnpm"),
835        "bun.lock" | "bun.lockb" => ("node", "bun"),
836        "poetry.lock" => ("python", "poetry"),
837        "uv.lock" => ("python", "uv"),
838        "Pipfile.lock" => ("python", "pipenv"),
839        "pdm.lock" => ("python", "pdm"),
840        "Cargo.lock" => ("rust", "cargo"),
841        _ => return None,
842    })
843}
844
845fn split_dir(path: &str) -> (&str, &str) {
846    path.rsplit_once('/').unwrap_or(("", path))
847}
848
849/// Which of the newly created `untracked` files are lockfiles of a manager the
850/// repo does not use in that directory.
851///
852/// Foreign means: a lockfile of the same ecosystem but another manager is
853/// already tracked *in the same directory* (no recursion — a workspace root and
854/// a sub-package may legitimately differ), or, for `Cargo.lock`, there is no
855/// `Cargo.toml` beside it. A first lockfile in a directory with none is normal.
856pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
857    let mut out = Vec::new();
858    for path in untracked {
859        let (dir, name) = split_dir(path);
860        let Some((eco, manager)) = lock_kind(name) else {
861            continue;
862        };
863        let beside = |other: &String| split_dir(other).0 == dir;
864        let kept_by = if manager == "cargo" {
865            let has_manifest = tracked
866                .iter()
867                .chain(untracked)
868                .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
869            if has_manifest {
870                continue;
871            }
872            "no Cargo.toml in the directory".to_owned()
873        } else {
874            let Some(other) = tracked.iter().find(|p| {
875                beside(p)
876                    && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
877            }) else {
878                continue;
879            };
880            other.clone()
881        };
882        out.push(Stray {
883            path: path.clone(),
884            manager: manager.to_owned(),
885            kept_by,
886        });
887    }
888    out
889}
890
891async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
892    let out = git(worktree, args).await?;
893    Ok(out
894        .split('\0')
895        .filter(|s| !s.is_empty())
896        .map(str::to_owned)
897        .collect())
898}
899
900/// Index-independent recovery evidence. Never treats a snapshot as a commit.
901/// Preserve staged and working tree changes separately, plus untracked bytes.
902/// Failure leaves the original tree untouched and is reported by the caller.
903pub async fn snapshot_uncommitted(worktree: &Path, destination: &Path) -> Result<()> {
904    if destination.exists() {
905        if destination.join("complete").exists() {
906            return Ok(());
907        }
908        bail!("earlier recovery snapshot is incomplete; retain original worktree");
909    }
910    std::fs::create_dir_all(destination)?;
911    for (name, args) in [
912        ("status.txt", vec!["status", "--porcelain=v1"]),
913        ("staged.patch", vec!["diff", "--binary", "--cached"]),
914        ("unstaged.patch", vec!["diff", "--binary"]),
915    ] {
916        // GitOut trims stdout for display. Recovery patches need exact bytes,
917        // including trailing whitespace and no-final-newline markers.
918        let out = Command::new("git")
919            .args(&args)
920            .current_dir(worktree)
921            .quiet()
922            .stdin(Stdio::null())
923            .output()
924            .await?;
925        if !out.status.success() {
926            bail!(
927                "recovery snapshot failed: {}",
928                String::from_utf8_lossy(&out.stderr)
929            );
930        }
931        std::fs::write(destination.join(name), out.stdout)?;
932    }
933    let paths = nul_list(
934        worktree,
935        &["ls-files", "-z", "--others", "--exclude-standard"],
936    )
937    .await?;
938    for name in paths {
939        let relative = Path::new(&name);
940        if relative
941            .components()
942            .any(|c| !matches!(c, std::path::Component::Normal(_)))
943        {
944            bail!("unsafe recovery path");
945        }
946        let source = worktree.join(relative);
947        let target = destination.join("untracked").join(relative);
948        std::fs::create_dir_all(target.parent().context("untracked recovery parent")?)?;
949        if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
950            // Do not follow a link outside the checkout or silently flatten it.
951            bail!("untracked symlink requires manual recovery: {name}");
952        }
953        std::fs::copy(source, target)?;
954    }
955    std::fs::write(destination.join("complete"), "snapshot captured\n")?;
956    Ok(())
957}
958
959/// [`commit_all`] for an agent's leftover work, minus stray foreign lockfiles.
960///
961/// The withheld files stay untracked in the worktree (nothing is deleted) and
962/// are returned so the caller can record them: silently dropping them could
963/// lose a file the task really asked for.
964pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
965    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
966        return Ok(Rescue::default());
967    }
968    let untracked = nul_list(
969        worktree,
970        &["ls-files", "-z", "--others", "--exclude-standard"],
971    )
972    .await?;
973    let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
974    let withheld = stray_lockfiles(&untracked, &tracked);
975
976    git(worktree, &["add", "-A"]).await?;
977    if !withheld.is_empty() {
978        let mut args = vec!["reset", "-q", "--"];
979        args.extend(withheld.iter().map(|s| s.path.as_str()));
980        git(worktree, &args).await?;
981    }
982    crate::worktree_setup::unstage_products(worktree).await?;
983    if git_raw(worktree, &["diff", "--cached", "--quiet"])
984        .await?
985        .ok()
986    {
987        return Ok(Rescue {
988            committed: false,
989            withheld,
990        });
991    }
992    let out = git_raw(
993        worktree,
994        &[
995            "-c",
996            "user.name=magi candidate",
997            "-c",
998            "user.email=magi@localhost",
999            "commit",
1000            "--no-verify",
1001            "-m",
1002            message,
1003        ],
1004    )
1005    .await?;
1006    if !out.ok() {
1007        bail!("rescue commit failed: {}", out.stderr);
1008    }
1009    Ok(Rescue {
1010        committed: true,
1011        withheld,
1012    })
1013}
1014
1015/// Enable `extensions.worktreeConfig` if it is not already on.
1016///
1017/// Returns `true` when magi turned it on, so the caller can turn it back off
1018/// during cleanup and leave the repo exactly as it found it.
1019pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
1020    let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
1021    if out.ok() && out.stdout.trim() == "true" {
1022        return Ok(false);
1023    }
1024    git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
1025    Ok(true)
1026}
1027
1028/// Undo [`enable_worktree_config`].
1029pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
1030    git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
1031    Ok(())
1032}
1033
1034/// How many runs currently want `extensions.worktreeConfig` on for one
1035/// repository, and whether magi is the one that turned it on.
1036struct WorktreeConfigRef {
1037    /// Runs holding a reference, via [`acquire_worktree_config`].
1038    count: usize,
1039    /// Did *this process* flip the setting from off to on? If not - it was
1040    /// already `true` when the first run in this process asked - nothing
1041    /// here ever turns it off either; that is what [`enable_worktree_config`]
1042    /// already decided for the single-run case, and the ref-counted version
1043    /// must not second-guess it.
1044    we_enabled: bool,
1045}
1046
1047/// One entry per repository, each guarded by its own `tokio::sync::Mutex` so
1048/// that two repositories' acquisitions never wait on each other - only two
1049/// runs in the *same* repository do, which is the point.
1050///
1051/// A `std::sync::Mutex` guards the map itself, held only long enough to find
1052/// or insert an entry and clone its `Arc`, never across an `.await`.
1053static WORKTREE_CONFIG: std::sync::LazyLock<
1054    std::sync::Mutex<
1055        std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
1056    >,
1057> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1058
1059/// The per-repository slot, creating it if this is the first run to ask.
1060fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
1061    let mut map = WORKTREE_CONFIG
1062        .lock()
1063        .unwrap_or_else(std::sync::PoisonError::into_inner);
1064    map.entry(repo.to_path_buf())
1065        .or_insert_with(|| {
1066            std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
1067                count: 0,
1068                we_enabled: false,
1069            }))
1070        })
1071        .clone()
1072}
1073
1074/// Take a reference on `extensions.worktreeConfig` being on for `repo`.
1075///
1076/// [`enable_worktree_config`] alone is only safe for one run in a repository
1077/// at a time: it is a plain get-then-set, so a second run's "already true?"
1078/// check can see the first run's write and conclude it owns nothing to turn
1079/// back off, while the first run's own cleanup turns the setting off under
1080/// the second run's feet the moment *it* finishes - the exact race that let a
1081/// finished run's fold disable the hook a still-running sibling in the same
1082/// repository depended on. This ref-counts instead: the setting is turned on
1083/// once, by whichever caller is first, and turned off only once every caller
1084/// has released it via [`release_worktree_config`].
1085///
1086/// The per-repository lock is held across the `git config` call for the
1087/// first acquire, so a second, concurrent acquire for the same repository
1088/// waits for it rather than racing it - without that, both could observe
1089/// "not yet counted" and both try to flip the setting on.
1090pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
1091    let slot = worktree_config_slot(repo);
1092    let mut entry = slot.lock().await;
1093    entry.count += 1;
1094    if entry.count == 1 {
1095        entry.we_enabled = enable_worktree_config(repo).await?;
1096    }
1097    Ok(())
1098}
1099
1100/// Release a reference taken by [`acquire_worktree_config`].
1101///
1102/// Only the last release for a repository actually calls
1103/// [`disable_worktree_config`], and only when this process was the one that
1104/// turned the setting on in the first place.
1105pub async fn release_worktree_config(repo: &Path) -> Result<()> {
1106    let slot = worktree_config_slot(repo);
1107    let mut entry = slot.lock().await;
1108    entry.count = entry.count.saturating_sub(1);
1109    if entry.count == 0 && entry.we_enabled {
1110        disable_worktree_config(repo).await?;
1111        entry.we_enabled = false;
1112    }
1113    Ok(())
1114}
1115
1116/// Point a single worktree at its own hooks directory.
1117///
1118/// `core.hooksPath` is normally repo-wide; scoping it with `--worktree` keeps
1119/// the operator's own hooks untouched in the primary worktree, and the setting
1120/// disappears together with the worktree.
1121pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
1122    let dir = hooks_dir.to_string_lossy().replace('\\', "/");
1123    git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
1124        .await
1125        .map(|_| ())
1126}
1127
1128/// Exclude a path from a worktree's status without touching `.gitignore`.
1129pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
1130    let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
1131    let path = worktree.join(git_dir);
1132    if let Some(parent) = path.parent() {
1133        tokio::fs::create_dir_all(parent).await.ok();
1134    }
1135    let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
1136    if body.lines().any(|l| l.trim() == pattern) {
1137        return Ok(());
1138    }
1139    if !body.is_empty() && !body.ends_with('\n') {
1140        body.push('\n');
1141    }
1142    body.push_str(pattern);
1143    body.push('\n');
1144    tokio::fs::write(&path, body)
1145        .await
1146        .with_context(|| format!("write {}", path.display()))?;
1147    Ok(())
1148}
1149
1150/// `git merge --no-ff` of `branch` into the currently checked-out branch.
1151///
1152/// One of three ways to land a branch driven by [`crate::config::MergeStyle`]
1153/// — see [`merge_squash`] and [`merge_ff_only`] for the other two, and that
1154/// enum's own doc for why the choice between them lives in configuration.
1155pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1156    git_raw(
1157        repo,
1158        &["merge", "--no-ff", "--no-edit", "-m", message, branch],
1159    )
1160    .await
1161}
1162
1163/// `git merge --squash` of `branch`, followed by a commit under `message`.
1164///
1165/// Two `git` calls because `--squash` only stages the result — unlike
1166/// [`merge_no_ff`] there is no merge commit for `--no-edit` to write, and
1167/// skipping the second call is exactly the trap `land`'s module doc warns
1168/// about: a squash that inherits `branch`'s own single-commit subject
1169/// (`magi: candidate A (uncommitted work)`) instead of `message`. Returns the
1170/// `--squash` step's own output, unrun `commit` included, when staging itself
1171/// fails (a conflict), so a caller sees what actually went wrong rather than
1172/// a `git commit` complaint about nothing being staged.
1173pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1174    let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
1175    if !staged.ok() {
1176        return Ok(staged);
1177    }
1178    git_raw(repo, &["commit", "-m", message]).await
1179}
1180
1181/// Fast-forward `branch` into the currently checked-out branch, refusing to
1182/// create a merge commit.
1183///
1184/// Only ever fast-forwards because the winner was already rebased onto the
1185/// tracked base tip before this runs (`Runner::sync_to_base`); at that point
1186/// `--ff-only` is indistinguishable from GitHub's "rebase and merge" button.
1187/// If the base moved again in the meantime this fails rather than falling
1188/// back to a real rebase, the same way `merge_no_ff` fails rather than
1189/// resolving a conflict — landing is not the place to improvise.
1190pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
1191    git_raw(repo, &["merge", "--ff-only", branch]).await
1192}
1193
1194/// Push a branch to `remote`.
1195pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1196    git_raw(repo, &["push", "-u", remote, branch]).await
1197}
1198
1199/// Push a local branch to a separate public head with an explicit lease.
1200/// An empty expected SHA requires the remote branch to be absent.
1201pub async fn push_as(
1202    repo: &Path,
1203    remote: &str,
1204    local: &str,
1205    head: &str,
1206    expected: &str,
1207) -> Result<GitOut> {
1208    let lease = format!("--force-with-lease=refs/heads/{head}:{expected}");
1209    let refspec = format!("refs/heads/{local}:refs/heads/{head}");
1210    git_raw(repo, &["push", &lease, remote, &refspec]).await
1211}
1212
1213/// Read a remote head without moving a tracking ref. Unreadable is an error.
1214pub async fn remote_head(repo: &Path, remote: &str, branch: &str) -> Result<Option<String>> {
1215    let reference = format!("refs/heads/{branch}");
1216    let out = git(repo, &["ls-remote", "--refs", remote, &reference]).await?;
1217    Ok(out.split_whitespace().next().map(str::to_owned))
1218}
1219
1220/// Force-push a branch that has been rewritten, refusing to clobber work
1221/// pushed since this side last looked.
1222///
1223/// `--force-with-lease` rather than `--force`: a rebase replaces the branch's
1224/// commits, so a plain push is rejected, but a blind force would also throw
1225/// away anything a person pushed to the same branch meanwhile. The lease
1226/// turns that case into a failure instead of a loss.
1227pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1228    git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
1229}
1230
1231/// Force-push `branch` only if `remote` still has it at `expected`.
1232///
1233/// The lease is pinned to a sha the caller read itself, not to whatever the
1234/// remote-tracking ref says at push time: a `fetch` in between moves the
1235/// tracking ref, and a bare lease would then be measured against the very
1236/// commit it was meant to protect a person's push from. A remote that has
1237/// moved on refuses the push, so a concurrent push fails the step instead of
1238/// being lost.
1239pub async fn push_pinned(
1240    repo: &Path,
1241    remote: &str,
1242    branch: &str,
1243    expected: &str,
1244) -> Result<GitOut> {
1245    let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
1246    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1247    git_raw(repo, &["push", &lease, remote, &refspec]).await
1248}
1249
1250/// `git cherry <upstream> <head>`, split into the commits of `head` that have
1251/// no patch-id twin in `upstream` (`+`) and those that do (`-`).
1252pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
1253    let out = git(repo, &["cherry", upstream, head]).await?;
1254    let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
1255    for line in out.lines() {
1256        if let Some(sha) = line.strip_prefix("+ ") {
1257            unmatched.push(sha.trim().to_owned());
1258        } else if let Some(sha) = line.strip_prefix("- ") {
1259            matched.push(sha.trim().to_owned());
1260        }
1261    }
1262    Ok((unmatched, matched))
1263}
1264
1265/// Git's pick order and the HEAD observed by the exec following each pick.
1266#[derive(Debug)]
1267pub struct RebaseRecord {
1268    /// Full original commit ids in Git's replay order.
1269    pub picks: Vec<String>,
1270    /// Full HEAD ids observed immediately after those picks.
1271    pub heads: Vec<String>,
1272}
1273
1274pub(crate) const REBASE_EXEC: &str =
1275    "git rev-parse HEAD >> \"$(git rev-parse --git-path magi-rebase-heads)\"";
1276
1277const REBASE_PICKS_PENDING: &str = "magi-rebase-picks-pending";
1278
1279async fn rebase_file(scratch: &Path, name: &str) -> Result<PathBuf> {
1280    let path = git(scratch, &["rev-parse", "--git-path", name]).await?;
1281    let path = Path::new(path.trim());
1282    Ok(if path.is_absolute() {
1283        path.to_path_buf()
1284    } else {
1285        scratch.join(path)
1286    })
1287}
1288
1289/// Read-only admission checks shared by inspection and the preparation probe.
1290pub(crate) async fn check_rebase_preparation(
1291    state: &crate::run::RunState,
1292    head: &str,
1293    dir: &Path,
1294) -> Result<()> {
1295    let winner = state.winner().context("missing retained winner")?;
1296    let common = crate::repo_lock::common_dir(&state.repo).await?;
1297    ensure!(
1298        common.is_some() && common == crate::repo_lock::common_dir(&winner.worktree).await?,
1299        "retained worktree repository changed"
1300    );
1301    ensure!(
1302        !dir.join("base-sync").try_exists()?,
1303        "retained scratch exists; inspect it before recovery"
1304    );
1305    let scratch = path_arg(&dir.join("base-sync"));
1306    let listing = git(&state.repo, &["worktree", "list", "--porcelain", "-z"]).await?;
1307    ensure!(
1308        !listing
1309            .split('\0')
1310            .filter_map(|line| line.strip_prefix("worktree "))
1311            .any(|path| {
1312                if cfg!(windows) {
1313                    path.eq_ignore_ascii_case(&scratch)
1314                } else {
1315                    path == scratch
1316                }
1317            }),
1318        "retained scratch Git registration exists; inspect it before recovery"
1319    );
1320    for name in [
1321        "rebase-merge",
1322        "rebase-apply",
1323        "MERGE_HEAD",
1324        "CHERRY_PICK_HEAD",
1325        "REVERT_HEAD",
1326        "sequencer",
1327        "index.lock",
1328    ] {
1329        ensure!(
1330            !rebase_file(&winner.worktree, name).await?.try_exists()?,
1331            "retained Git operation: {name}"
1332        );
1333    }
1334    ensure!(
1335        is_clean(&winner.worktree).await?,
1336        "retained worktree changed"
1337    );
1338    ensure!(
1339        current_branch(&winner.worktree).await?.as_deref() == Some(winner.branch.as_str()),
1340        "retained worktree branch changed"
1341    );
1342    ensure!(
1343        rev_parse(&winner.worktree, "HEAD").await? == head
1344            && rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1345        "retained HEAD changed"
1346    );
1347    Ok(())
1348}
1349
1350/// Exercise the current preparation path without replaying a commit or moving
1351/// the retained branch. A failed cleanup is a failed proof.
1352pub(crate) async fn probe_rebase_preparation(
1353    state: &crate::run::RunState,
1354    head: &str,
1355    dir: &Path,
1356    wait: &crate::repo_lock::WaitPolicy,
1357) -> Result<()> {
1358    let _lease = crate::repo_lock::SeatLease::operation_with(
1359        &state.repo,
1360        state.config.coordination.as_ref(),
1361        wait,
1362    )
1363    .await?;
1364    check_rebase_preparation(state, head, dir).await?;
1365    let scratch = dir.join(format!(
1366        "base-sync-probe-{}-{:016x}",
1367        std::process::id(),
1368        crate::rng::entropy()
1369    ));
1370    ensure!(
1371        !scratch.try_exists()?,
1372        "previous preparation probe requires inspection"
1373    );
1374    worktree_add_detached(&state.repo, &scratch, head).await?;
1375    let result = initialize_rebase_record(&scratch).await;
1376    let removed = worktree_remove_clean(&state.repo, &scratch).await?;
1377    result?;
1378    ensure!(
1379        removed && !scratch.try_exists()?,
1380        "preparation probe cleanup failed"
1381    );
1382    Ok(())
1383}
1384
1385async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1386    anyhow::ensure!(
1387        !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1388        "invalid rebase commit id: {sha}"
1389    );
1390    rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1391}
1392
1393enum Instruction<'a> {
1394    Pick(&'a str),
1395    Record,
1396}
1397
1398fn instructions<'a>(
1399    text: &'a str,
1400    exec: &'a str,
1401) -> impl DoubleEndedIterator<Item = Result<Instruction<'a>>> {
1402    text.lines()
1403        .map(str::trim)
1404        .filter(|line| !line.is_empty() && !line.starts_with('#'))
1405        .map(move |line| match line.split_once(' ') {
1406            Some(("pick" | "p", args)) => Ok(Instruction::Pick(
1407                args.split_whitespace()
1408                    .next()
1409                    .context("pick without commit")?,
1410            )),
1411            Some(("exec" | "x", command)) if command == exec => Ok(Instruction::Record),
1412            _ => bail!("unexpected rebase instruction: {line}"),
1413        })
1414}
1415
1416/// Only a pick at the end of `done` can own a textual conflict. REBASE_HEAD
1417/// alone can still name the previous pick after a subsequent exec stopped.
1418pub(crate) async fn stopped_pick(scratch: &Path) -> Result<Option<String>> {
1419    stopped_pick_with_exec(scratch, REBASE_EXEC).await
1420}
1421
1422async fn stopped_pick_with_exec(scratch: &Path, exec: &str) -> Result<Option<String>> {
1423    let done = std::fs::read_to_string(rebase_file(scratch, "rebase-merge/done").await?)?;
1424    let mut steps = instructions(&done, exec);
1425    let Some(Instruction::Pick(id)) = steps.next_back().transpose()? else {
1426        return Ok(None);
1427    };
1428    let pick = full_commit(scratch, id).await?;
1429    ensure!(
1430        rev_parse(scratch, "REBASE_HEAD^{commit}").await? == pick,
1431        "REBASE_HEAD does not match the stopped pick"
1432    );
1433    let saved = std::fs::read_to_string(rebase_file(scratch, "magi-rebase-picks").await?)?;
1434    let mut picks = saved.lines();
1435    for step in steps {
1436        if let Instruction::Pick(id) = step? {
1437            ensure!(
1438                picks.next().is_some_and(|sha| sha.starts_with(id)),
1439                "completed picks do not match the saved replay"
1440            );
1441        }
1442    }
1443    ensure!(
1444        picks.next() == Some(pick.as_str()),
1445        "stopped pick does not match its position in the saved replay"
1446    );
1447    Ok(Some(pick))
1448}
1449
1450/// Save Git's exact picks before a fixer can change its todo list. Resolve
1451/// abbreviations while the sequencer still exists; ambiguity is an error.
1452async fn save_rebase_picks(scratch: &Path, exec: &str) -> Result<()> {
1453    let mut picks = Vec::new();
1454    for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1455        let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1456        for step in instructions(&text, exec) {
1457            if let Instruction::Pick(id) = step? {
1458                picks.push(full_commit(scratch, id).await?);
1459            }
1460        }
1461    }
1462    let path = rebase_file(scratch, "magi-rebase-picks").await?;
1463    let tmp = path.with_extension("tmp");
1464    std::fs::write(&tmp, picks.join("\n") + "\n")?;
1465    std::fs::rename(tmp, path)?;
1466    Ok(())
1467}
1468
1469/// Only a launcher-marked, not-yet-admitted replay may capture its pick
1470/// ledger. Once a fixer can run, a missing ledger must never be rebuilt.
1471pub(crate) async fn finish_rebase_pick_capture(scratch: &Path, exec: &str) -> Result<()> {
1472    let pending = rebase_file(scratch, REBASE_PICKS_PENDING).await?;
1473    match pending.symlink_metadata() {
1474        Ok(meta) => ensure!(meta.is_file(), "invalid pick capture marker"),
1475        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1476        Err(e) => return Err(e).context("inspect pick capture marker"),
1477    }
1478    let ledger = pending.with_file_name("magi-rebase-picks");
1479    match ledger.symlink_metadata() {
1480        Ok(meta) => ensure!(meta.is_file(), "invalid pick ledger"),
1481        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1482            save_rebase_picks(scratch, exec).await?;
1483        }
1484        Err(e) => return Err(e).context("inspect pick ledger"),
1485    }
1486    std::fs::remove_file(pending).context("finish pick capture")
1487}
1488
1489/// Under the caller's repository lease, prove that the next `--continue`
1490/// retries our unrecorded exec, then spend the retry *before* running Git.
1491/// Only a separate owner resumption can authorize another attempt.
1492pub(crate) async fn claim_recording_retry(
1493    repo: &Path,
1494    scratch: &Path,
1495    branch: &str,
1496    original: &str,
1497    onto_sha: &str,
1498    owner_retry: Option<u64>,
1499    exec: &str,
1500) -> Result<()> {
1501    let admin = rebase_scratch_admin(repo, scratch).await?;
1502    let seq = admin.join("rebase-merge");
1503    let read = |path: PathBuf| -> Result<String> {
1504        ensure!(
1505            path.symlink_metadata()?.is_file(),
1506            "not a regular file: {}",
1507            path.display()
1508        );
1509        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))
1510    };
1511    let branch_ref = format!("refs/heads/{branch}");
1512    ensure!(
1513        seq.symlink_metadata()?.is_dir()
1514            && seq
1515                .join("reschedule-failed-exec")
1516                .symlink_metadata()?
1517                .is_file()
1518            && read(seq.join("head-name"))?.trim_end() == branch_ref
1519            && read(seq.join("orig-head"))?.trim_end() == original
1520            && read(seq.join("onto"))?.trim_end() == onto_sha
1521            && rev_parse(repo, &branch_ref).await? == original
1522            && git_raw(scratch, &["symbolic-ref", "-q", "HEAD"])
1523                .await?
1524                .code
1525                == Some(1),
1526        "scratch rebase does not match the reserved operation"
1527    );
1528    let automatic = admin.join("magi-rebase-recording-retry");
1529    let (marker, previously_retried) = match owner_retry {
1530        Some(generation) => match automatic.symlink_metadata() {
1531            Ok(meta) => {
1532                ensure!(meta.is_file(), "invalid automatic retry marker");
1533                (
1534                    admin.join(format!("magi-rebase-recording-retry-{generation}")),
1535                    true,
1536                )
1537            }
1538            // The first stop may have failed validation before any claim.
1539            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (automatic, false),
1540            Err(e) => return Err(e).context("inspect automatic retry marker"),
1541        },
1542        None => (automatic, false),
1543    };
1544    ensure!(!marker.try_exists()?, "recording retry already spent");
1545    ensure!(
1546        git(scratch, &["status", "--porcelain", "--untracked-files=all"])
1547            .await?
1548            .is_empty(),
1549        "scratch has uncommitted changes"
1550    );
1551
1552    let saved = read(admin.join("magi-rebase-picks"))?;
1553    ensure!(saved.ends_with('\n'), "incomplete saved pick ledger");
1554    let mut picks = saved.lines();
1555    let mut done_picks = 0;
1556    for (file, done) in [("done", true), ("git-rebase-todo", false)] {
1557        let text = read(seq.join(file))?;
1558        let mut steps = instructions(&text, exec).peekable();
1559        // Git appends the failed exec to `done` AND puts it back first in the
1560        // todo. A previous retry adds another identical exec in `done`.
1561        if !done {
1562            ensure!(
1563                matches!(steps.next().transpose()?, Some(Instruction::Record)),
1564                "the recording exec was not rescheduled"
1565            );
1566        }
1567        while let Some(step) = steps.next() {
1568            let Instruction::Pick(sha) = step? else {
1569                bail!("expected a pick in {file}");
1570            };
1571            let pick = full_commit(scratch, sha).await?;
1572            ensure!(
1573                picks.next() == Some(pick.as_str())
1574                    && is_ancestor(repo, &pick, original).await
1575                    && matches!(steps.next().transpose()?, Some(Instruction::Record)),
1576                "{file} does not match the saved pick/exec sequence"
1577            );
1578            done_picks += usize::from(done);
1579            if done && previously_retried {
1580                while steps
1581                    .next_if(|step| matches!(step, Ok(Instruction::Record)))
1582                    .is_some()
1583                {}
1584            }
1585        }
1586    }
1587    ensure!(
1588        picks.next().is_none() && done_picks > 0,
1589        "incomplete pick sequence"
1590    );
1591
1592    let heads = read(admin.join("magi-rebase-heads"))?;
1593    ensure!(
1594        (heads.is_empty() || heads.ends_with('\n')) && heads.lines().count() == done_picks - 1,
1595        "cannot prove the failed exec has not already recorded a HEAD"
1596    );
1597    let head = rev_parse(scratch, "HEAD^{commit}").await?;
1598    let mut previous = onto_sha;
1599    for sha in heads.lines().chain(std::iter::once(head.as_str())) {
1600        ensure!(
1601            sha.len() == head.len() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1602            "partial or invalid recorded HEAD"
1603        );
1604        if sha != previous {
1605            ensure!(
1606                git(scratch, &["rev-list", "--parents", "-1", sha]).await?
1607                    == format!("{sha} {previous}"),
1608                "recorded HEADs and scratch HEAD are not a replay onto the reserved target"
1609            );
1610        }
1611        previous = sha;
1612    }
1613    std::fs::File::create_new(marker)
1614        .context("cannot claim recording retry (already spent or scratch unwritable)")?
1615        .sync_all()?;
1616    Ok(())
1617}
1618
1619/// Resolve the linked scratch Git directory and verify its backlink.
1620pub(crate) async fn rebase_scratch_admin(repo: &Path, scratch: &Path) -> Result<PathBuf> {
1621    let common = crate::repo_lock::common_dir(repo)
1622        .await?
1623        .context("not a repository")?;
1624    let admin = std::fs::canonicalize(git(scratch, &["rev-parse", "--absolute-git-dir"]).await?)?;
1625    let backlink = std::fs::read_to_string(admin.join("gitdir"))?;
1626    ensure!(
1627        admin.parent() == Some(common.join("worktrees").as_path())
1628            && admin.join(backlink.trim_end()).canonicalize()?
1629                == scratch.join(".git").canonicalize()?,
1630        "not a scratch worktree of the reserved repository"
1631    );
1632    Ok(admin)
1633}
1634
1635/// Read a completed rebase's durable record, rejecting missing or corrupt data.
1636pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1637    let mut lists = Vec::new();
1638    for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1639        let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1640            .with_context(|| format!("read {name}"))?;
1641        let mut commits = Vec::new();
1642        for sha in text.lines() {
1643            let full = full_commit(scratch, sha).await?;
1644            anyhow::ensure!(full == sha, "non-full commit id in {name}");
1645            commits.push(full);
1646        }
1647        lists.push(commits);
1648    }
1649    let heads = lists.pop().unwrap();
1650    let picks = lists.pop().unwrap();
1651    anyhow::ensure!(
1652        !picks.is_empty() && picks.len() == heads.len(),
1653        "rebase pick/HEAD count mismatch"
1654    );
1655    Ok(RebaseRecord { picks, heads })
1656}
1657
1658/// Strip only the diagnostics emitted by our recording exec.
1659pub fn rebase_said(text: &str) -> String {
1660    text.trim()
1661        .split(['\r', '\n'])
1662        .filter(|line| !line.trim_start().starts_with("Executing:"))
1663        .collect::<Vec<_>>()
1664        .join("\n")
1665}
1666
1667/// How [`rebase_start`] ended.
1668#[derive(Debug, Clone, PartialEq, Eq)]
1669pub enum RebaseStart {
1670    /// It applied; the branch points at the rebased commits and the throwaway
1671    /// worktree is gone.
1672    Applied,
1673    /// It stopped on a conflict and the throwaway worktree was **kept**
1674    /// mid-rebase, for someone to resolve. Carries what git said.
1675    Conflicted(String),
1676    /// The sequencer stopped without a verified textual conflict. The scratch
1677    /// and Git output are retained for infrastructure recovery.
1678    Sequencer(String),
1679    /// It failed without leaving a rebase in progress; the worktree is gone
1680    /// and the branch is untouched. Carries what git said.
1681    Failed(String),
1682}
1683
1684/// Start rebasing `branch` onto `onto` inside a throwaway worktree, and leave
1685/// a conflict standing.
1686///
1687/// A worktree of its own for two reasons. The repository magi runs in may be
1688/// jj-colocated, where git `HEAD` is detached and a rebase in the primary
1689/// tree would move it under the operator; and a rebase that hits a conflict
1690/// leaves state behind, which is far easier to discard with the whole
1691/// directory than to unpick in a tree somebody is using.
1692///
1693/// Unlike [`rebase_branch_in_temp`] this does not abort on a conflict: the
1694/// caller decides whether to hand the conflicted tree to a fixer or to call
1695/// [`rebase_abort`]. Any leftover at `scratch` from an earlier attempt is
1696/// removed first, so callers re-entering a rebase already in progress must
1697/// check [`rebase_in_progress`] before calling this.
1698pub async fn rebase_start(
1699    repo: &Path,
1700    scratch: &Path,
1701    branch: &str,
1702    onto: &str,
1703) -> Result<RebaseStart> {
1704    rebase_prepare(repo, scratch, branch).await?;
1705    rebase_execute(repo, scratch, onto, REBASE_EXEC).await
1706}
1707
1708/// Preparation failed before any commits were replayed.
1709#[derive(Debug)]
1710pub struct RebasePreparationError(pub String);
1711
1712impl std::fmt::Display for RebasePreparationError {
1713    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1714        f.write_str(&self.0)
1715    }
1716}
1717
1718impl std::error::Error for RebasePreparationError {}
1719
1720async fn initialize_rebase_record(scratch: &Path) -> Result<()> {
1721    std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1722    Ok(())
1723}
1724
1725/// Create the scratch checkout without starting the sequencer.
1726/// An interrupted sequencer belongs to its existing operation and is kept.
1727pub(crate) async fn rebase_prepare(repo: &Path, scratch: &Path, branch: &str) -> Result<()> {
1728    if checked_rebase_in_progress(scratch).await? {
1729        return Ok(());
1730    }
1731    let result = async {
1732        worktree_remove(repo, scratch).await.ok();
1733        let path = path_arg(scratch);
1734        let args = ["worktree", "add", "--force", &path, branch];
1735        let out = git_raw(repo, &args).await?;
1736        ensure!(
1737            out.ok(),
1738            "git {} (exit {:?}): {}",
1739            args.join(" "),
1740            out.code,
1741            if out.stderr.trim().is_empty() {
1742                &out.stdout
1743            } else {
1744                &out.stderr
1745            }
1746        );
1747        initialize_rebase_record(scratch).await
1748    }
1749    .await;
1750    result.map_err(|e| {
1751        RebasePreparationError(format!(
1752            "prepare rebase scratch {}: {e:#}",
1753            scratch.display()
1754        ))
1755        .into()
1756    })
1757}
1758
1759/// Start the sequencer only after the caller has persisted its reservation.
1760pub(crate) async fn rebase_execute(
1761    repo: &Path,
1762    scratch: &Path,
1763    onto: &str,
1764    exec: &str,
1765) -> Result<RebaseStart> {
1766    std::fs::File::create_new(rebase_file(scratch, REBASE_PICKS_PENDING).await?)?.sync_all()?;
1767    let out = git_raw(
1768        scratch,
1769        &[
1770            "rebase",
1771            "--empty=drop",
1772            "--reschedule-failed-exec",
1773            "--exec",
1774            exec,
1775            onto,
1776        ],
1777    )
1778    .await?;
1779    if out.ok() {
1780        worktree_remove(repo, scratch).await.ok();
1781        return Ok(RebaseStart::Applied);
1782    }
1783    let why = rebase_said(&format!("{}\n{}", out.stderr, out.stdout));
1784    if checked_rebase_in_progress(scratch)
1785        .await
1786        .with_context(|| format!("{why}\ncannot read scratch rebase state"))?
1787    {
1788        finish_rebase_pick_capture(scratch, exec)
1789            .await
1790            .with_context(|| format!("{why}\ncannot record rebase picks"))?;
1791        return Ok(match unmerged_paths(scratch).await {
1792            Ok(paths) if paths.is_empty() => RebaseStart::Sequencer(why),
1793            Err(e) => RebaseStart::Sequencer(format!("{why}\ncannot read unmerged paths: {e:#}")),
1794            Ok(_) => match stopped_pick_with_exec(scratch, exec).await {
1795                Ok(Some(_)) => RebaseStart::Conflicted(why),
1796                Ok(None) => RebaseStart::Sequencer(why),
1797                Err(e) => {
1798                    RebaseStart::Sequencer(format!("{why}\ncannot identify stopped pick: {e:#}"))
1799                }
1800            },
1801        });
1802    }
1803    worktree_remove(repo, scratch).await.ok();
1804    Ok(RebaseStart::Failed(why))
1805}
1806
1807/// Is a rebase (merge or apply backend) in progress in `worktree`?
1808pub async fn rebase_in_progress(worktree: &Path) -> bool {
1809    checked_rebase_in_progress(worktree).await.unwrap_or(false)
1810}
1811
1812/// A missing scratch is idle; an unreadable scratch is not safe to replace.
1813pub(crate) async fn checked_rebase_in_progress(worktree: &Path) -> Result<bool> {
1814    match worktree.symlink_metadata() {
1815        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1816        result => ensure!(
1817            result?.is_dir(),
1818            "not a worktree directory: {}",
1819            worktree.display()
1820        ),
1821    }
1822    // Do not let Git search a parent checkout if the scratch backlink is gone.
1823    let backlink = worktree.join(".git");
1824    backlink
1825        .symlink_metadata()
1826        .with_context(|| format!("inspect scratch Git backlink {}", backlink.display()))?;
1827    for name in ["rebase-merge", "rebase-apply"] {
1828        let path = rebase_file(worktree, name).await?;
1829        match path.symlink_metadata() {
1830            Ok(meta) if meta.is_dir() => return Ok(true),
1831            Ok(_) => bail!("not a sequencer directory: {}", path.display()),
1832            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1833            Err(e) => return Err(e).with_context(|| format!("inspect {}", path.display())),
1834        }
1835    }
1836    Ok(false)
1837}
1838
1839/// Paths git reports as unmerged in `worktree`.
1840pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1841    let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1842    Ok(out
1843        .split('\0')
1844        .filter(|l| !l.is_empty())
1845        .map(str::to_owned)
1846        .collect())
1847}
1848
1849/// Abandon a rebase left standing by [`rebase_start`] and drop its worktree.
1850/// The branch is exactly where it was before the rebase began.
1851pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1852    git_raw(scratch, &["rebase", "--abort"]).await.ok();
1853    worktree_remove(repo, scratch).await.ok();
1854}
1855
1856/// Rebase a branch onto `onto`, inside a throwaway worktree.
1857///
1858/// `Ok(None)` means it applied and the branch now points at the rebased
1859/// commits. `Ok(Some(why))` means it did not: the branch is untouched, and
1860/// the string is what git said - a person has to decide. Nothing half-rebased
1861/// is left behind; see [`rebase_start`] for the variant that keeps a conflict
1862/// standing.
1863pub async fn rebase_branch_in_temp(
1864    repo: &Path,
1865    scratch: &Path,
1866    branch: &str,
1867    onto: &str,
1868) -> Result<Option<String>> {
1869    match rebase_start(repo, scratch, branch, onto).await? {
1870        RebaseStart::Applied => Ok(None),
1871        RebaseStart::Failed(why) => Ok(Some(why)),
1872        RebaseStart::Conflicted(why) | RebaseStart::Sequencer(why) => {
1873            rebase_abort(repo, scratch).await;
1874            Ok(Some(why))
1875        }
1876    }
1877}
1878
1879/// Bring an *attached* worktree's index and files in line with wherever its
1880/// branch now points.
1881///
1882/// [`rebase_branch_in_temp`] moves a branch from a throwaway worktree on
1883/// purpose - the whole point is never touching the tree someone else has
1884/// checked out. But a worktree that already had that branch checked out
1885/// shares the same ref: its `HEAD` resolves to the new commit the moment the
1886/// rebase lands elsewhere, while its index and working directory keep
1887/// whatever the old commit put there until something says otherwise. Left
1888/// alone, the next `git status` there reads as the whole rebase turning up
1889/// as an unstaged diff, and the next commit would be staged against stale
1890/// content.
1891pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1892    reset_hard_head(worktree).await?;
1893    clean_all(worktree).await
1894}
1895
1896/// The first half of [`sync_to_head`]: tracked files back on `HEAD`.
1897pub async fn reset_hard_head(worktree: &Path) -> Result<()> {
1898    git(worktree, &["reset", "--hard", "HEAD"])
1899        .await
1900        .map(|_| ())
1901}
1902
1903/// Remove untracked and ignored files after any project cleanup has finished.
1904pub async fn clean_all(worktree: &Path) -> Result<()> {
1905    git(worktree, &["clean", "-fdx"]).await.map(|_| ())
1906}
1907
1908/// Fetch one branch from `remote`, updating its remote-tracking ref.
1909///
1910/// The refspec is spelled out rather than left to `git fetch <remote>
1911/// <branch>`, which writes `FETCH_HEAD` and updates
1912/// `refs/remotes/<remote>/<branch>` only as a side effect of the remote's
1913/// configured refspec. Naming the destination makes the thing this function
1914/// exists for - a tracking ref that moved - the operation rather than a
1915/// consequence of configuration magi does not own.
1916///
1917/// Honest note: a CI failure was first read as proof that some git versions do
1918/// not update the tracking ref here. That was wrong - the fetch had nothing to
1919/// update because the test had pushed to the wrong branch - so this is
1920/// determinism, not a fix for a demonstrated portability bug.
1921///
1922/// Refs, not the working copy: nothing is checked out and no local branch
1923/// moves, so this is safe to run while the operator has uncommitted work.
1924/// Returned as a [`GitOut`] rather than an error so the caller can decide - a
1925/// machine with no network must still be able to start a run.
1926pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1927    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
1928    git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
1929}
1930
1931/// The best common ancestor of `a` and `b`, or an error when there is none.
1932pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
1933    Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
1934}
1935
1936/// Is `ancestor` an ancestor of (or equal to) `of`?
1937pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
1938    git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
1939        .await
1940        .is_ok_and(|o| o.ok())
1941}
1942
1943/// [`is_ancestor`] that keeps "no" apart from "could not tell": `merge-base
1944/// --is-ancestor` exits 0 for yes, 1 for no and anything else for an error
1945/// (an unknown object, a shallow clone), and reading an error as "no" would
1946/// report a merged change as unmerged.
1947pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
1948    let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
1949    match out.code {
1950        Some(0) => Ok(true),
1951        Some(1) => Ok(false),
1952        _ => bail!(
1953            "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
1954            crate::notices::exit_status(out.code),
1955            out.stderr
1956        ),
1957    }
1958}
1959
1960/// The commit `rev` names, or `None` when it names no commit here.
1961pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
1962    let spec = format!("{rev}^{{commit}}");
1963    let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
1964        .await
1965        .ok()?;
1966    (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
1967}
1968
1969/// Local and remote-tracking branches that contain `commit`.
1970pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
1971    let out = git(
1972        repo,
1973        &[
1974            "branch",
1975            "-a",
1976            "--contains",
1977            commit,
1978            "--format=%(refname:short)",
1979        ],
1980    )
1981    .await?;
1982    Ok(out
1983        .lines()
1984        .map(str::trim)
1985        .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
1986        .map(str::to_owned)
1987        .collect())
1988}
1989
1990/// Cherry-pick `commit` onto the worktree's HEAD under a neutral committer.
1991/// On a conflict the pick is aborted, so the worktree is left as it was, and
1992/// git's own words come back as the error.
1993pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
1994    let out = git_raw(
1995        worktree,
1996        &[
1997            "-c",
1998            "user.name=magi candidate",
1999            "-c",
2000            "user.email=magi@localhost",
2001            "cherry-pick",
2002            "-x",
2003            commit,
2004        ],
2005    )
2006    .await?;
2007    if out.ok() {
2008        return Ok(());
2009    }
2010    let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
2011    bail!(
2012        "cherry-pick of {commit} failed: {}",
2013        if out.stderr.is_empty() {
2014            out.stdout
2015        } else {
2016            out.stderr
2017        }
2018    )
2019}
2020
2021/// The tree object id of `rev`.
2022pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
2023    git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
2024}
2025
2026/// Does this ref resolve?
2027pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
2028    git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
2029        .await
2030        .is_ok_and(|o| o.ok())
2031}
2032
2033#[cfg(test)]
2034mod tests {
2035    #[tokio::test]
2036    async fn checkout_discovery_ignores_inherited_git_target() {
2037        const FIXTURE: &str = "MAGI_TEST_CHECKOUT_DISCOVERY_ROOT";
2038        if let Some(root) = std::env::var_os(FIXTURE) {
2039            let root = std::path::PathBuf::from(root);
2040            let first = root.join("first");
2041            let second = root.join("second");
2042            let plain = root.join("plain");
2043            assert_eq!(
2044                super::toplevel(&second)
2045                    .await
2046                    .unwrap()
2047                    .canonicalize()
2048                    .unwrap(),
2049                second.canonicalize().unwrap()
2050            );
2051            assert!(super::toplevel(&plain).await.is_err());
2052            assert!(!super::same_checkout(&first, &second).unwrap());
2053            assert!(super::same_checkout(&first, &plain).is_err());
2054            assert!(super::same_checkout(&first, &first.join("src")).unwrap());
2055            return;
2056        }
2057        let fixture = tempfile::tempdir().unwrap();
2058        let root = fixture.path();
2059        for name in ["first", "second"] {
2060            let checkout = root.join(name);
2061            std::fs::create_dir_all(checkout.join("src")).unwrap();
2062            super::git(&checkout, &["init", "-q"]).await.unwrap();
2063        }
2064        std::fs::create_dir(root.join("plain")).unwrap();
2065        let output = std::process::Command::new(std::env::current_exe().unwrap())
2066            .args([
2067                "--exact",
2068                "git::tests::checkout_discovery_ignores_inherited_git_target",
2069            ])
2070            .env(FIXTURE, root)
2071            .env("GIT_DIR", root.join("first/.git"))
2072            .env("GIT_WORK_TREE", root.join("first"))
2073            .env("GIT_CONFIG_COUNT", "1")
2074            .env("GIT_CONFIG_KEY_0", "core.worktree")
2075            .env("GIT_CONFIG_VALUE_0", root.join("first"))
2076            .output()
2077            .unwrap();
2078        let stdout = String::from_utf8_lossy(&output.stdout);
2079        assert!(
2080            output.status.success() && stdout.contains("1 passed"),
2081            "{stdout}"
2082        );
2083    }
2084
2085    #[test]
2086    fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
2087        for (native, expected) in [
2088            (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
2089            (
2090                r"\\?\UNC\server\share\work tree",
2091                "//server/share/work tree",
2092            ),
2093            (r"C:\temp\work tree", "C:/temp/work tree"),
2094            ("C:/temp/work tree", "C:/temp/work tree"),
2095        ] {
2096            assert_eq!(super::windows_cli_path(native), expected);
2097        }
2098    }
2099
2100    #[test]
2101    fn git_cli_path_spelling_does_not_alias_extended_only_names() {
2102        for path in [
2103            r"\\?\C:\temp.\copy",
2104            r"\\?\C:\temp \copy",
2105            r"\\?\C:\NUL.txt\copy",
2106            r"\\?\C:\COM1\copy",
2107        ] {
2108            assert!(super::windows_cli_path(path).starts_with("//?/"));
2109        }
2110    }
2111
2112    #[cfg(unix)]
2113    #[test]
2114    fn git_cli_path_spelling_preserves_native_paths_on_unix() {
2115        assert_eq!(
2116            super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
2117            r"/tmp/back\slash"
2118        );
2119    }
2120
2121    #[test]
2122    fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
2123        let temp = tempfile::tempdir().unwrap();
2124        let canonical = temp.path().canonicalize().unwrap();
2125        let printed = super::path_arg(&canonical);
2126        assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
2127        // Joining onto a Windows verbatim path normalizes parent components.
2128        // Preserve the spelling so the boundary, rather than PathBuf, rejects it.
2129        let noncanonical = format!("{printed}/child/..");
2130        std::fs::create_dir(canonical.join("child")).unwrap();
2131        assert!(super::canonical_output_path(&noncanonical).is_err());
2132        #[cfg(unix)]
2133        {
2134            let alias = canonical.join("alias");
2135            std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
2136            assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
2137        }
2138    }
2139
2140    use super::*;
2141
2142    #[tokio::test]
2143    async fn recording_exec_transient_failure() {
2144        recording_exec_fixture(false).await;
2145    }
2146
2147    #[tokio::test]
2148    async fn recording_exec_persistent_failure() {
2149        recording_exec_fixture(true).await;
2150    }
2151
2152    fn shell_script(path: &Path, body: &str) {
2153        std::fs::write(path, body).unwrap();
2154        #[cfg(unix)]
2155        {
2156            use std::os::unix::fs::PermissionsExt as _;
2157            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
2158        }
2159    }
2160
2161    #[tokio::test]
2162    async fn rebase_pick_ledger_publish_failure_can_resume() {
2163        use crate::rebase::{Rebased, SEQUENCER_INFRASTRUCTURE, rebase_prepared_with_exec};
2164        use crate::run::RunState;
2165
2166        crate::run::pin_test_home();
2167        let (_temp, repo) = scratch().await;
2168        let base = rev_parse(&repo, "main").await.unwrap();
2169        sh(&repo, &["checkout", "-qb", "topic"]);
2170        track(&repo, "topic", "topic").await;
2171        let original = rev_parse(&repo, "topic").await.unwrap();
2172        sh(&repo, &["checkout", "-q", "main"]);
2173        track(&repo, "upstream", "upstream").await;
2174        let mut state = RunState::new(
2175            repo.clone(),
2176            "main".into(),
2177            base,
2178            "sync".into(),
2179            crate::config::Config::default(),
2180        );
2181        let work = repo.parent().unwrap().join("scratch");
2182        rebase_prepare(&repo, &work, "topic").await.unwrap();
2183        let obstacle = rebase_file(&work, "magi-rebase-picks.tmp").await.unwrap();
2184        std::fs::create_dir(&obstacle).unwrap();
2185        let exec = format!(
2186            r#"if test -d "$(git rev-parse --git-path magi-rebase-picks.tmp)"; then echo 'fixture ledger failure' >&2; exit 1; fi; {REBASE_EXEC}"#
2187        );
2188        let error = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2189            .await
2190            .unwrap_err();
2191        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2192        let mut state = RunState::load(&state.id).unwrap();
2193        let block = state.resource_block.as_ref().unwrap();
2194        assert_eq!(block.kind, SEQUENCER_INFRASTRUCTURE);
2195        assert!(block.detail.contains("fixture ledger failure"), "{block:?}");
2196        assert!(
2197            block.detail.contains("cannot record rebase picks"),
2198            "{block:?}"
2199        );
2200        assert!(rebase_in_progress(&work).await);
2201        assert_eq!(rev_parse(&repo, "topic").await.unwrap(), original);
2202        std::fs::remove_dir(obstacle).unwrap();
2203
2204        assert_eq!(
2205            rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2206                .await
2207                .unwrap(),
2208            Rebased::Applied
2209        );
2210        assert!(state.rebase_fixes.is_empty());
2211        assert!(is_ancestor(&repo, "main", "topic").await);
2212    }
2213
2214    async fn recording_exec_fixture(persistent: bool) {
2215        use crate::queue::{Queue, Source, Task};
2216        use crate::rebase::{Rebased, SEQUENCER_INFRASTRUCTURE, rebase_prepared_with_exec};
2217        use crate::run::{Origin, RunState};
2218
2219        crate::run::pin_test_home();
2220        let temp = tempfile::tempdir().unwrap();
2221        let root = temp.path();
2222        let exec = format!(
2223            r#"root=$(git config --local magi.test-root) && if test ! -f "$root/attempts" || test -f "$root/fault"; then echo failed >> "$root/attempts"; echo 'fixture recording exec failed' >&2; exit 1; fi; echo recorded >> "$root/attempts" && {REBASE_EXEC}"#
2224        );
2225        let (_temp, repo) = scratch().await;
2226        sh(&repo, &["config", "magi.test-root", &path_arg(root)]);
2227        let base = rev_parse(&repo, "main").await.unwrap();
2228        sh(&repo, &["checkout", "-qb", "topic"]);
2229        track(&repo, "one", "one").await;
2230        track(&repo, "two", "two").await;
2231        let picks = git(&repo, &["rev-list", "--reverse", "main..topic"])
2232            .await
2233            .unwrap();
2234        sh(&repo, &["checkout", "-q", "main"]);
2235        track(&repo, "upstream", "upstream").await;
2236        let hooks = root.join("hooks");
2237        std::fs::create_dir(&hooks).unwrap();
2238        shell_script(
2239            &hooks.join("post-rewrite"),
2240            r#"#!/bin/sh
2241test "$1" = rebase || exit 0
2242root=$(git config --local magi.test-root) || exit 1
2243for name in picks heads; do
2244    cp "$(git rev-parse --git-path magi-rebase-$name)" "$root/$name" || exit 1
2245done
2246"#,
2247        );
2248        sh(&repo, &["config", "core.hooksPath", &path_arg(&hooks)]);
2249        let mut state = RunState::new(
2250            repo.clone(),
2251            "main".into(),
2252            base,
2253            "sync".into(),
2254            crate::config::Config::default(),
2255        );
2256        let queue = Queue::open();
2257        let mut task = Task::new("sync".into(), "sync".into(), repo.clone(), Source::Human);
2258        state.origin = Some(Origin::queue(&task.id));
2259        state.task_instruction = Some(task.instruction.clone());
2260        task.start(state.id.clone());
2261        queue.put(&mut task).unwrap();
2262        let work = root.join("scratch");
2263        rebase_prepare(&repo, &work, "topic").await.unwrap();
2264        let attempts = || std::fs::read_to_string(root.join("attempts")).unwrap();
2265        if persistent {
2266            std::fs::write(root.join("fault"), "").unwrap();
2267            // Neither the failed retry nor a restart can spend another slot.
2268            for _ in 0..2 {
2269                let error = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2270                    .await
2271                    .unwrap_err();
2272                assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
2273                state = RunState::load(&state.id).unwrap();
2274                let block = state.resource_block.as_ref().unwrap();
2275                assert_eq!(block.kind, SEQUENCER_INFRASTRUCTURE);
2276                assert!(
2277                    block.detail.contains("fixture recording exec failed"),
2278                    "{block:?}"
2279                );
2280                assert!(state.rebase_fixes.is_empty());
2281                assert_eq!(attempts().lines().collect::<Vec<_>>(), ["failed", "failed"]);
2282                assert!(rebase_in_progress(&work).await);
2283            }
2284            // A complete append reported as failed, a torn append, or an
2285            // edited todo cannot be repaired by retrying an exec.
2286            let heads_file = rebase_file(&work, "magi-rebase-heads").await.unwrap();
2287            let todo_file = rebase_file(&work, "rebase-merge/git-rebase-todo")
2288                .await
2289                .unwrap();
2290            let original = rev_parse(&repo, "topic").await.unwrap();
2291            let target = rev_parse(&repo, "main").await.unwrap();
2292            let claim =
2293                || claim_recording_retry(&repo, &work, "topic", &original, &target, Some(1), &exec);
2294            let head = rev_parse(&work, "HEAD").await.unwrap();
2295            for invalid in [format!("{head}\n"), head[..12].to_string()] {
2296                std::fs::write(&heads_file, invalid).unwrap();
2297                assert!(claim().await.is_err());
2298            }
2299            std::fs::write(&heads_file, "").unwrap();
2300            let todo = std::fs::read_to_string(&todo_file).unwrap();
2301            std::fs::write(&todo_file, format!("exec true\n{todo}")).unwrap();
2302            assert!(claim().await.is_err());
2303            std::fs::write(todo_file, todo).unwrap();
2304            std::fs::remove_file(root.join("fault")).unwrap();
2305            task.release_operator("resume", None);
2306            queue.put(&mut task).unwrap();
2307        }
2308        let result = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2309            .await
2310            .unwrap();
2311        assert_eq!(result, Rebased::Applied);
2312        assert!(state.rebase_fixes.is_empty());
2313        assert_eq!(attempts().lines().count(), if persistent { 4 } else { 3 });
2314        let heads = git(&repo, &["rev-list", "--reverse", "main..topic"])
2315            .await
2316            .unwrap();
2317        assert_eq!(heads.lines().count(), 2);
2318        assert_eq!(
2319            std::fs::read_to_string(root.join("picks")).unwrap().trim(),
2320            picks
2321        );
2322        assert_eq!(
2323            std::fs::read_to_string(root.join("heads")).unwrap().trim(),
2324            heads
2325        );
2326    }
2327
2328    #[test]
2329    fn worktree_holder_is_read_from_the_porcelain_listing() {
2330        let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
2331                       worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
2332                       worktree /wt/detached\nHEAD ccc\ndetached\n";
2333        assert_eq!(
2334            parse_worktree_holder(listing, "magi/f82f/A"),
2335            Some(PathBuf::from("/wt/cand-A"))
2336        );
2337        assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
2338        assert_eq!(parse_worktree_holder(listing, "other"), None);
2339    }
2340
2341    async fn scratch() -> (tempfile::TempDir, PathBuf) {
2342        let dir = tempfile::tempdir().unwrap();
2343        let repo = dir.path().join("repo");
2344        tokio::fs::create_dir_all(&repo).await.unwrap();
2345        git(&repo, &["init", "-b", "main"]).await.unwrap();
2346        git(&repo, &["config", "user.name", "test"]).await.unwrap();
2347        git(&repo, &["config", "user.email", "test@example.com"])
2348            .await
2349            .unwrap();
2350        tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
2351        git(&repo, &["add", "-A"]).await.unwrap();
2352        git(&repo, &["commit", "-m", "init"]).await.unwrap();
2353        (dir, repo)
2354    }
2355
2356    #[tokio::test]
2357    async fn restore_to_removes_nested_repositories_inside_submodules() {
2358        let (_parent_dir, repo) = scratch().await;
2359        let (_source_dir, source) = scratch().await;
2360        sh(
2361            &repo,
2362            &[
2363                "-c",
2364                "protocol.file.allow=always",
2365                "submodule",
2366                "add",
2367                &source.to_string_lossy(),
2368                "sub",
2369            ],
2370        );
2371        sh(&repo, &["commit", "-am", "add submodule"]);
2372        let pre = rev_parse(&repo, "HEAD").await.unwrap();
2373        let sub = repo.join("sub");
2374        sh(&sub, &["init", "nested"]);
2375        tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
2376            .await
2377            .unwrap();
2378
2379        restore_to(&repo, &pre).await.unwrap();
2380
2381        assert!(!sub.join("nested").exists());
2382        assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
2383        assert_eq!(
2384            rev_parse(&sub, "HEAD").await.unwrap(),
2385            rev_parse(&source, "HEAD").await.unwrap()
2386        );
2387        assert!(
2388            git(&repo, &["status", "--porcelain"])
2389                .await
2390                .unwrap()
2391                .is_empty()
2392        );
2393    }
2394
2395    #[tokio::test]
2396    async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
2397        let (_g, repo) = scratch().await;
2398
2399        // A side branch touching a different file: rebases cleanly.
2400        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2401        tokio::fs::write(repo.join("b.txt"), "side\n")
2402            .await
2403            .unwrap();
2404        git(&repo, &["add", "-A"]).await.unwrap();
2405        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2406
2407        // main moves under it, which is what a repository merging other
2408        // pull requests does to a competition that took two hours.
2409        git(&repo, &["checkout", "main"]).await.unwrap();
2410        tokio::fs::write(repo.join("c.txt"), "main\n")
2411            .await
2412            .unwrap();
2413        git(&repo, &["add", "-A"]).await.unwrap();
2414        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2415
2416        let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
2417        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
2418            .await
2419            .unwrap();
2420        assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
2421        assert_eq!(
2422            commits_ahead(&repo, "main", "side").await.unwrap(),
2423            1,
2424            "one commit, replayed onto the new base"
2425        );
2426        assert!(
2427            !scratch_tree.exists(),
2428            "the throwaway worktree is not left behind"
2429        );
2430
2431        // A real conflict: both sides edit the same line.
2432        git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
2433        tokio::fs::write(repo.join("a.txt"), "clash\n")
2434            .await
2435            .unwrap();
2436        git(&repo, &["add", "-A"]).await.unwrap();
2437        git(&repo, &["commit", "-m", "clash"]).await.unwrap();
2438        git(&repo, &["checkout", "main"]).await.unwrap();
2439        tokio::fs::write(repo.join("a.txt"), "main edit\n")
2440            .await
2441            .unwrap();
2442        git(&repo, &["add", "-A"]).await.unwrap();
2443        git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
2444
2445        let before = rev_parse(&repo, "clash").await.unwrap();
2446        let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
2447            .await
2448            .unwrap()
2449            .expect("a same-line clash cannot be rebased silently");
2450        assert!(
2451            why.to_lowercase().contains("conflict"),
2452            "the reason is what git said, which is what a person needs: {why}"
2453        );
2454        assert_eq!(
2455            rev_parse(&repo, "clash").await.unwrap(),
2456            before,
2457            "a failed rebase leaves the branch exactly where it was"
2458        );
2459        assert!(!scratch_tree.exists(), "and cleans up after itself");
2460    }
2461
2462    #[tokio::test]
2463    async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
2464        let (_g, repo) = scratch().await;
2465        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2466        for name in ["b.txt", "c.txt"] {
2467            tokio::fs::write(repo.join(name), "side\n").await.unwrap();
2468            git(&repo, &["add", "-A"]).await.unwrap();
2469            git(
2470                &repo,
2471                &["commit", "-m", "magi: candidate A (uncommitted work)"],
2472            )
2473            .await
2474            .unwrap();
2475        }
2476        git(&repo, &["checkout", "main"]).await.unwrap();
2477        let before = rev_parse(&repo, "main").await.unwrap();
2478
2479        let out = merge_squash(&repo, "side", "an explicit subject")
2480            .await
2481            .unwrap();
2482        assert!(out.ok(), "{}", out.stderr);
2483        assert_eq!(
2484            commits_ahead(&repo, &before, "main").await.unwrap(),
2485            1,
2486            "squash adds exactly one commit onto the tip, not one per candidate commit"
2487        );
2488        let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
2489        assert_eq!(
2490            subject, "an explicit subject",
2491            "the candidate's own placeholder subject must not survive: {subject}"
2492        );
2493    }
2494
2495    #[tokio::test]
2496    async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
2497        let (_g, repo) = scratch().await;
2498        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2499        tokio::fs::write(repo.join("b.txt"), "side\n")
2500            .await
2501            .unwrap();
2502        git(&repo, &["add", "-A"]).await.unwrap();
2503        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2504        git(&repo, &["checkout", "main"]).await.unwrap();
2505
2506        let before = rev_parse(&repo, "side").await.unwrap();
2507        let out = merge_ff_only(&repo, "side").await.unwrap();
2508        assert!(out.ok(), "{}", out.stderr);
2509        assert_eq!(
2510            rev_parse(&repo, "main").await.unwrap(),
2511            before,
2512            "a fast-forward moves the base tip to the branch, no merge commit"
2513        );
2514    }
2515
2516    #[tokio::test]
2517    async fn merge_ff_only_refuses_to_write_a_merge_commit() {
2518        let (_g, repo) = scratch().await;
2519        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2520        tokio::fs::write(repo.join("b.txt"), "side\n")
2521            .await
2522            .unwrap();
2523        git(&repo, &["add", "-A"]).await.unwrap();
2524        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2525
2526        // main diverges, so a fast-forward is no longer possible.
2527        git(&repo, &["checkout", "main"]).await.unwrap();
2528        tokio::fs::write(repo.join("c.txt"), "main\n")
2529            .await
2530            .unwrap();
2531        git(&repo, &["add", "-A"]).await.unwrap();
2532        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2533
2534        let before = rev_parse(&repo, "main").await.unwrap();
2535        let out = merge_ff_only(&repo, "side").await.unwrap();
2536        assert!(!out.ok(), "a divergent branch cannot fast-forward");
2537        assert_eq!(
2538            rev_parse(&repo, "main").await.unwrap(),
2539            before,
2540            "a refused fast-forward must not touch main"
2541        );
2542    }
2543
2544    #[tokio::test]
2545    async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
2546        let (guard, repo) = scratch().await;
2547
2548        // An attached worktree of an existing branch - the shape a winner's
2549        // worktree keeps in `graph::Runner`, not the detached checkouts used
2550        // for judges and reviewers.
2551        git(&repo, &["branch", "side"]).await.unwrap();
2552        let side_wt = guard.path().join("side-wt");
2553        git(
2554            &repo,
2555            &["worktree", "add", &side_wt.to_string_lossy(), "side"],
2556        )
2557        .await
2558        .unwrap();
2559        tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
2560            .await
2561            .unwrap();
2562        git(&side_wt, &["add", "-A"]).await.unwrap();
2563        git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
2564
2565        // main moves under it.
2566        git(&repo, &["checkout", "main"]).await.unwrap();
2567        tokio::fs::write(repo.join("c.txt"), "main\n")
2568            .await
2569            .unwrap();
2570        git(&repo, &["add", "-A"]).await.unwrap();
2571        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2572
2573        // Rebase from a throwaway worktree, never from `side_wt` itself.
2574        let scratch_tree = guard.path().join("rebase-scratch");
2575        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
2576            .await
2577            .unwrap();
2578        assert!(clean.is_none());
2579
2580        // `HEAD` in the sibling worktree already resolves to the rebased
2581        // commit - the ref is shared - but nothing has told its index or its
2582        // files, which still hold the pre-rebase checkout.
2583        assert_eq!(
2584            rev_parse(&side_wt, "HEAD").await.unwrap(),
2585            rev_parse(&repo, "side").await.unwrap(),
2586            "HEAD follows the moved ref"
2587        );
2588        assert!(
2589            !side_wt.join("c.txt").exists(),
2590            "stale until synced: main's new file has not reached this worktree's disk"
2591        );
2592
2593        sync_to_head(&side_wt).await.unwrap();
2594        assert!(side_wt.join("c.txt").is_file(), "synced now");
2595        assert!(
2596            side_wt.join("b.txt").is_file(),
2597            "the worktree's own committed work survives the sync"
2598        );
2599        assert!(is_clean(&side_wt).await.unwrap());
2600    }
2601
2602    #[tokio::test]
2603    async fn clean_repo_reports_clean_then_dirty() {
2604        let (_g, repo) = scratch().await;
2605        assert!(is_clean(&repo).await.unwrap());
2606        tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
2607        assert!(!is_clean(&repo).await.unwrap());
2608    }
2609
2610    async fn track(repo: &Path, name: &str, body: &str) {
2611        let p = repo.join(name);
2612        if let Some(d) = p.parent() {
2613            tokio::fs::create_dir_all(d).await.unwrap();
2614        }
2615        tokio::fs::write(&p, body).await.unwrap();
2616        git(repo, &["add", name]).await.unwrap();
2617        git(
2618            repo,
2619            &[
2620                "-c",
2621                "user.name=t",
2622                "-c",
2623                "user.email=t@localhost",
2624                "commit",
2625                "-q",
2626                "-m",
2627                "seed",
2628            ],
2629        )
2630        .await
2631        .unwrap();
2632    }
2633
2634    #[tokio::test]
2635    async fn rescue_withholds_a_foreign_lockfile() {
2636        let (_g, repo) = scratch().await;
2637        track(&repo, "web/bun.lock", "a\n").await;
2638        tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
2639            .await
2640            .unwrap();
2641        tokio::fs::write(repo.join("web/app.ts"), "real\n")
2642            .await
2643            .unwrap();
2644
2645        let r = rescue_commit(&repo, "rescue").await.unwrap();
2646        assert!(r.committed);
2647        assert_eq!(
2648            r.withheld,
2649            [Stray {
2650                path: "web/pnpm-lock.yaml".to_owned(),
2651                manager: "pnpm".to_owned(),
2652                kept_by: "web/bun.lock".to_owned(),
2653            }]
2654        );
2655        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2656            .await
2657            .unwrap();
2658        assert!(files.contains("web/app.ts"), "{files}");
2659        assert!(!files.contains("pnpm-lock"), "{files}");
2660        assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
2661    }
2662
2663    #[tokio::test]
2664    async fn rescue_with_only_a_stray_commits_nothing() {
2665        let (_g, repo) = scratch().await;
2666        track(&repo, "bun.lock", "a\n").await;
2667        tokio::fs::write(repo.join("yarn.lock"), "x\n")
2668            .await
2669            .unwrap();
2670        let r = rescue_commit(&repo, "rescue").await.unwrap();
2671        assert!(!r.committed);
2672        assert_eq!(r.withheld.len(), 1);
2673    }
2674
2675    #[tokio::test]
2676    async fn rescue_keeps_a_same_manager_lockfile_update() {
2677        let (_g, repo) = scratch().await;
2678        track(&repo, "bun.lock", "a\n").await;
2679        tokio::fs::write(repo.join("bun.lock"), "b\n")
2680            .await
2681            .unwrap();
2682        let r = rescue_commit(&repo, "rescue").await.unwrap();
2683        assert!(r.committed);
2684        assert!(r.withheld.is_empty());
2685        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2686            .await
2687            .unwrap();
2688        assert_eq!(files, "bun.lock");
2689    }
2690
2691    #[tokio::test]
2692    async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
2693        let (_g, repo) = scratch().await;
2694        track(&repo, "other/bun.lock", "a\n").await;
2695        tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
2696        tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
2697            .await
2698            .unwrap();
2699        let r = rescue_commit(&repo, "rescue").await.unwrap();
2700        assert!(r.committed);
2701        assert!(r.withheld.is_empty());
2702    }
2703
2704    #[test]
2705    fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
2706        let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
2707        assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
2708        assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
2709        assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
2710        // A manifest in another directory does not count.
2711        assert_eq!(
2712            stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
2713            1
2714        );
2715    }
2716
2717    #[tokio::test]
2718    async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
2719        let (guard, repo) = scratch().await;
2720        let wt = guard.path().join("scratch-wt");
2721        worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
2722        tokio::fs::write(wt.join("built.txt"), "build output")
2723            .await
2724            .unwrap();
2725        assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
2726        assert!(wt.join("built.txt").exists());
2727        let listing = git(&repo, &["worktree", "list", "--porcelain"])
2728            .await
2729            .unwrap();
2730        let registered = listing
2731            .lines()
2732            .filter_map(|line| line.strip_prefix("worktree "))
2733            .map(PathBuf::from)
2734            .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
2735            .expect("the refused removal must retain the worktree registration");
2736        assert!(worktree_remove(&repo, &wt).await.unwrap());
2737        assert!(!wt.exists());
2738        let listing = git(&repo, &["worktree", "list", "--porcelain"])
2739            .await
2740            .unwrap();
2741        assert!(!listing.lines().any(|line| {
2742            line.strip_prefix("worktree ")
2743                .is_some_and(|path| Path::new(path) == registered)
2744        }));
2745    }
2746
2747    #[tokio::test]
2748    async fn worktree_lifecycle_and_diff() {
2749        let (guard, repo) = scratch().await;
2750        let base = rev_parse(&repo, "HEAD").await.unwrap();
2751        let wt = guard.path().join("wt-a");
2752        worktree_add_branch(&repo, &wt, "magi/test/a", &base)
2753            .await
2754            .unwrap();
2755        tokio::fs::write(wt.join("b.txt"), "candidate\n")
2756            .await
2757            .unwrap();
2758
2759        assert!(commit_all(&wt, "candidate work").await.unwrap());
2760        assert!(!commit_all(&wt, "nothing left").await.unwrap());
2761
2762        assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
2763        let patch = diff(&wt, &base, "HEAD").await.unwrap();
2764        assert!(patch.contains("b.txt"), "patch was: {patch}");
2765        assert_eq!(
2766            changed_files(&wt, &base, "HEAD").await.unwrap(),
2767            ["b.txt".to_owned()]
2768        );
2769
2770        // The rescue commit must not carry the operator's identity.
2771        let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
2772            .await
2773            .unwrap();
2774        assert_eq!(author, "magi candidate <magi@localhost>");
2775
2776        let head = rev_parse(&wt, "HEAD").await.unwrap();
2777        let prov = commit_provenance(&wt, &head).await.unwrap();
2778        assert_eq!(prov.commit, head);
2779        assert_eq!(prov.parents, vec![base.clone()]);
2780        assert_eq!(prov.author_name, NEUTRAL_IDENTITY_NAME);
2781        assert_eq!(prov.author_email, NEUTRAL_IDENTITY_EMAIL);
2782        assert_eq!(prov.committer_name, NEUTRAL_IDENTITY_NAME);
2783        assert_eq!(prov.committer_email, NEUTRAL_IDENTITY_EMAIL);
2784        assert_eq!(prov.message, "candidate work");
2785
2786        assert!(worktree_remove(&repo, &wt).await.unwrap());
2787        assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
2788        assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
2789        assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
2790    }
2791
2792    #[tokio::test]
2793    async fn commit_provenance_distinguishes_merge_commits_body_and_identities() {
2794        let (_guard, repo) = scratch().await;
2795        let base = rev_parse(&repo, "HEAD").await.unwrap();
2796
2797        // Non-neutral author with neutral committer and extra body line.
2798        tokio::fs::write(repo.join("body.txt"), "one\n")
2799            .await
2800            .unwrap();
2801        git(&repo, &["add", "body.txt"]).await.unwrap();
2802        let out = tokio::process::Command::new("git")
2803            .current_dir(&repo)
2804            .env("GIT_AUTHOR_NAME", "Alice")
2805            .env("GIT_AUTHOR_EMAIL", "alice@example.com")
2806            .env("GIT_COMMITTER_NAME", NEUTRAL_IDENTITY_NAME)
2807            .env("GIT_COMMITTER_EMAIL", NEUTRAL_IDENTITY_EMAIL)
2808            .args(["commit", "--no-verify", "-m", "subject\n\nextra body"])
2809            .output()
2810            .await
2811            .unwrap();
2812        assert!(out.status.success());
2813        let extra = rev_parse(&repo, "HEAD").await.unwrap();
2814        let prov = commit_provenance(&repo, &extra).await.unwrap();
2815        assert_eq!(prov.parents, vec![base.clone()]);
2816        assert_eq!(prov.author_name, "Alice");
2817        assert_eq!(prov.author_email, "alice@example.com");
2818        assert_eq!(prov.committer_name, NEUTRAL_IDENTITY_NAME);
2819        assert_eq!(prov.committer_email, NEUTRAL_IDENTITY_EMAIL);
2820        assert_eq!(prov.message, "subject\n\nextra body");
2821
2822        // Merge commit reports two parents.
2823        git(&repo, &["checkout", "-b", "side", &base])
2824            .await
2825            .unwrap();
2826        tokio::fs::write(repo.join("side.txt"), "two\n")
2827            .await
2828            .unwrap();
2829        assert!(commit_all(&repo, "side change").await.unwrap());
2830        let side = rev_parse(&repo, "HEAD").await.unwrap();
2831        git(&repo, &["checkout", "-"]).await.unwrap();
2832        let merge_out = git_raw(
2833            &repo,
2834            &[
2835                "-c",
2836                &format!("user.name={NEUTRAL_IDENTITY_NAME}"),
2837                "-c",
2838                &format!("user.email={NEUTRAL_IDENTITY_EMAIL}"),
2839                "merge",
2840                "--no-ff",
2841                "-m",
2842                "merge side",
2843                &side,
2844            ],
2845        )
2846        .await
2847        .unwrap();
2848        assert!(merge_out.ok(), "{}", merge_out.stderr);
2849        let merged = rev_parse(&repo, "HEAD").await.unwrap();
2850        let merged_prov = commit_provenance(&repo, &merged).await.unwrap();
2851        assert_eq!(merged_prov.parents, vec![extra, side]);
2852        assert_eq!(merged_prov.message, "merge side");
2853    }
2854
2855    #[tokio::test]
2856    async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
2857        let (guard, repo) = scratch().await;
2858        let base = rev_parse(&repo, "HEAD").await.unwrap();
2859        let wt = guard.path().join("wt-h");
2860        worktree_add_branch(&repo, &wt, "magi/test/h", &base)
2861            .await
2862            .unwrap();
2863        let hooks = guard.path().join("hooks");
2864        tokio::fs::create_dir_all(&hooks).await.unwrap();
2865
2866        assert!(enable_worktree_config(&repo).await.unwrap());
2867        set_worktree_hooks_path(&wt, &hooks).await.unwrap();
2868
2869        let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
2870            .await
2871            .unwrap();
2872        assert!(!in_wt.is_empty());
2873        let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
2874            .await
2875            .unwrap();
2876        assert!(
2877            !in_primary.ok(),
2878            "primary worktree must keep its own hooks: {in_primary:?}"
2879        );
2880
2881        disable_worktree_config(&repo).await.unwrap();
2882    }
2883
2884    #[tokio::test]
2885    async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
2886        let (_g, repo) = scratch().await;
2887
2888        // Two runs in the same repository, as `Config::daemon.max_concurrent_runs`
2889        // now allows: both acquire before either is done.
2890        acquire_worktree_config(&repo).await.unwrap();
2891        acquire_worktree_config(&repo).await.unwrap();
2892
2893        let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2894            .await
2895            .unwrap();
2896        assert_eq!(on, "true");
2897
2898        // The first run to finish releases its own reference. A plain
2899        // `disable_worktree_config` here is exactly the bug: it would turn
2900        // the setting off while the second run still depends on it.
2901        release_worktree_config(&repo).await.unwrap();
2902        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2903            .await
2904            .unwrap();
2905        assert_eq!(
2906            still_on, "true",
2907            "a sibling run's release must not disable the setting for the one still working"
2908        );
2909
2910        // Only the last release actually turns it back off.
2911        release_worktree_config(&repo).await.unwrap();
2912        let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
2913            .await
2914            .unwrap();
2915        assert!(
2916            !after.ok(),
2917            "the last release must turn the setting back off: {after:?}"
2918        );
2919    }
2920
2921    #[tokio::test]
2922    async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
2923        let (_g, repo) = scratch().await;
2924        git(&repo, &["config", "extensions.worktreeConfig", "true"])
2925            .await
2926            .unwrap();
2927
2928        // magi did not turn this on, so even after every acquire is released,
2929        // it must not turn it off - that is what a bare `enable_worktree_config`
2930        // already promised for the single-run case, and the ref-counted
2931        // version must keep that promise.
2932        acquire_worktree_config(&repo).await.unwrap();
2933        release_worktree_config(&repo).await.unwrap();
2934
2935        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2936            .await
2937            .unwrap();
2938        assert_eq!(still_on, "true");
2939    }
2940
2941    #[tokio::test]
2942    async fn local_exclude_is_idempotent() {
2943        let (_g, repo) = scratch().await;
2944        local_exclude(&repo, "/.magi/").await.unwrap();
2945        local_exclude(&repo, "/.magi/").await.unwrap();
2946        let path = repo.join(".git/info/exclude");
2947        let body = tokio::fs::read_to_string(&path).await.unwrap();
2948        assert_eq!(body.matches("/.magi/").count(), 1);
2949    }
2950
2951    fn sh(cwd: &Path, args: &[&str]) {
2952        let out = std::process::Command::new("git")
2953            .quiet()
2954            .args(args)
2955            .current_dir(cwd)
2956            .output()
2957            .unwrap();
2958        assert!(
2959            out.status.success(),
2960            "git {args:?}: {}",
2961            String::from_utf8_lossy(&out.stderr)
2962        );
2963    }
2964
2965    /// A checkout whose `origin` is a local bare repository holding `trunk`,
2966    /// with `origin/HEAD` unset (as after `git remote add` + push).
2967    async fn with_remote() -> (tempfile::TempDir, PathBuf) {
2968        let (g, repo) = scratch().await;
2969        let bare = g.path().join("bare.git");
2970        sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2971        sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2972        sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
2973        sh(&repo, &["fetch", "origin"]);
2974        (g, repo)
2975    }
2976
2977    #[test]
2978    fn remote_head_branch_strips_only_the_matching_remote() {
2979        assert_eq!(
2980            remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
2981            Some("main")
2982        );
2983        assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
2984        assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
2985    }
2986
2987    #[tokio::test]
2988    async fn merge_base_branch_reads_origin_head_when_present() {
2989        let (_g, repo) = with_remote().await;
2990        sh(&repo, &["remote", "set-head", "origin", "trunk"]);
2991        assert_eq!(
2992            merge_base_branch(&repo, "origin", None).await.unwrap(),
2993            "trunk"
2994        );
2995    }
2996
2997    #[tokio::test]
2998    async fn merge_base_branch_recovers_a_missing_origin_head() {
2999        let (_g, repo) = with_remote().await;
3000        // Newer git sets it on fetch; make the precondition true everywhere.
3001        sh(&repo, &["remote", "set-head", "origin", "-d"]);
3002        let head = git_raw(
3003            &repo,
3004            &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
3005        )
3006        .await
3007        .unwrap();
3008        assert!(!head.ok(), "precondition: no origin/HEAD");
3009        assert_eq!(
3010            merge_base_branch(&repo, "origin", None).await.unwrap(),
3011            "trunk"
3012        );
3013    }
3014
3015    #[tokio::test]
3016    async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
3017        let (_g, repo) = scratch().await;
3018        let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
3019        assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
3020    }
3021
3022    #[tokio::test]
3023    async fn merge_base_branch_prefers_the_explicit_base() {
3024        let (_g, repo) = with_remote().await;
3025        assert_eq!(
3026            merge_base_branch(&repo, "origin", Some("release"))
3027                .await
3028                .unwrap(),
3029            "release"
3030        );
3031    }
3032
3033    #[tokio::test]
3034    async fn merge_base_branch_names_an_unfetched_default_branch() {
3035        // A remote added after the fact, never fetched: no tracking refs, so
3036        // `set-head -a` cannot work, but the remote's own HEAD still names it.
3037        let (g, repo) = scratch().await;
3038        let bare = g.path().join("bare.git");
3039        sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
3040        sh(
3041            &repo,
3042            &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
3043        );
3044        sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
3045        assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
3046        assert_eq!(
3047            merge_base_branch(&repo, "origin", None).await.unwrap(),
3048            "trunk"
3049        );
3050    }
3051
3052    #[test]
3053    fn symref_branch_reads_ls_remote_output() {
3054        assert_eq!(
3055            symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
3056            Some("main")
3057        );
3058        assert_eq!(symref_branch("abc\tHEAD\n"), None);
3059    }
3060}