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