Skip to main content

magi/
git.rs

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