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