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
1219async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1220    anyhow::ensure!(
1221        !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1222        "invalid rebase commit id: {sha}"
1223    );
1224    rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1225}
1226
1227enum Instruction<'a> {
1228    Pick(&'a str),
1229    Record,
1230}
1231
1232fn instructions<'a>(
1233    text: &'a str,
1234    exec: &'a str,
1235) -> impl DoubleEndedIterator<Item = Result<Instruction<'a>>> {
1236    text.lines()
1237        .map(str::trim)
1238        .filter(|line| !line.is_empty() && !line.starts_with('#'))
1239        .map(move |line| match line.split_once(' ') {
1240            Some(("pick" | "p", args)) => Ok(Instruction::Pick(
1241                args.split_whitespace()
1242                    .next()
1243                    .context("pick without commit")?,
1244            )),
1245            Some(("exec" | "x", command)) if command == exec => Ok(Instruction::Record),
1246            _ => bail!("unexpected rebase instruction: {line}"),
1247        })
1248}
1249
1250/// Only a pick at the end of `done` can own a textual conflict. REBASE_HEAD
1251/// alone can still name the previous pick after a subsequent exec stopped.
1252pub(crate) async fn stopped_pick(scratch: &Path) -> Result<Option<String>> {
1253    stopped_pick_with_exec(scratch, REBASE_EXEC).await
1254}
1255
1256async fn stopped_pick_with_exec(scratch: &Path, exec: &str) -> Result<Option<String>> {
1257    let done = std::fs::read_to_string(rebase_file(scratch, "rebase-merge/done").await?)?;
1258    let mut steps = instructions(&done, exec);
1259    let Some(Instruction::Pick(id)) = steps.next_back().transpose()? else {
1260        return Ok(None);
1261    };
1262    let pick = full_commit(scratch, id).await?;
1263    ensure!(
1264        rev_parse(scratch, "REBASE_HEAD^{commit}").await? == pick,
1265        "REBASE_HEAD does not match the stopped pick"
1266    );
1267    let saved = std::fs::read_to_string(rebase_file(scratch, "magi-rebase-picks").await?)?;
1268    let mut picks = saved.lines();
1269    for step in steps {
1270        if let Instruction::Pick(id) = step? {
1271            ensure!(
1272                picks.next().is_some_and(|sha| sha.starts_with(id)),
1273                "completed picks do not match the saved replay"
1274            );
1275        }
1276    }
1277    ensure!(
1278        picks.next() == Some(pick.as_str()),
1279        "stopped pick does not match its position in the saved replay"
1280    );
1281    Ok(Some(pick))
1282}
1283
1284/// Save Git's exact picks before a fixer can change its todo list. Resolve
1285/// abbreviations while the sequencer still exists; ambiguity is an error.
1286async fn save_rebase_picks(scratch: &Path, exec: &str) -> Result<()> {
1287    let mut picks = Vec::new();
1288    for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1289        let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1290        for step in instructions(&text, exec) {
1291            if let Instruction::Pick(id) = step? {
1292                picks.push(full_commit(scratch, id).await?);
1293            }
1294        }
1295    }
1296    let path = rebase_file(scratch, "magi-rebase-picks").await?;
1297    let tmp = path.with_extension("tmp");
1298    std::fs::write(&tmp, picks.join("\n") + "\n")?;
1299    std::fs::rename(tmp, path)?;
1300    Ok(())
1301}
1302
1303/// Only a launcher-marked, not-yet-admitted replay may capture its pick
1304/// ledger. Once a fixer can run, a missing ledger must never be rebuilt.
1305pub(crate) async fn finish_rebase_pick_capture(scratch: &Path, exec: &str) -> Result<()> {
1306    let pending = rebase_file(scratch, REBASE_PICKS_PENDING).await?;
1307    match pending.symlink_metadata() {
1308        Ok(meta) => ensure!(meta.is_file(), "invalid pick capture marker"),
1309        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1310        Err(e) => return Err(e).context("inspect pick capture marker"),
1311    }
1312    let ledger = pending.with_file_name("magi-rebase-picks");
1313    match ledger.symlink_metadata() {
1314        Ok(meta) => ensure!(meta.is_file(), "invalid pick ledger"),
1315        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1316            save_rebase_picks(scratch, exec).await?;
1317        }
1318        Err(e) => return Err(e).context("inspect pick ledger"),
1319    }
1320    std::fs::remove_file(pending).context("finish pick capture")
1321}
1322
1323/// Under the caller's repository lease, prove that the next `--continue`
1324/// retries our unrecorded exec, then spend the retry *before* running Git.
1325/// Only a separate owner resumption can authorize another attempt.
1326pub(crate) async fn claim_recording_retry(
1327    repo: &Path,
1328    scratch: &Path,
1329    branch: &str,
1330    original: &str,
1331    onto_sha: &str,
1332    owner_retry: Option<u64>,
1333    exec: &str,
1334) -> Result<()> {
1335    let admin = rebase_scratch_admin(repo, scratch).await?;
1336    let seq = admin.join("rebase-merge");
1337    let read = |path: PathBuf| -> Result<String> {
1338        ensure!(
1339            path.symlink_metadata()?.is_file(),
1340            "not a regular file: {}",
1341            path.display()
1342        );
1343        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))
1344    };
1345    let branch_ref = format!("refs/heads/{branch}");
1346    ensure!(
1347        seq.symlink_metadata()?.is_dir()
1348            && seq
1349                .join("reschedule-failed-exec")
1350                .symlink_metadata()?
1351                .is_file()
1352            && read(seq.join("head-name"))?.trim_end() == branch_ref
1353            && read(seq.join("orig-head"))?.trim_end() == original
1354            && read(seq.join("onto"))?.trim_end() == onto_sha
1355            && rev_parse(repo, &branch_ref).await? == original
1356            && git_raw(scratch, &["symbolic-ref", "-q", "HEAD"])
1357                .await?
1358                .code
1359                == Some(1),
1360        "scratch rebase does not match the reserved operation"
1361    );
1362    let automatic = admin.join("magi-rebase-recording-retry");
1363    let (marker, previously_retried) = match owner_retry {
1364        Some(generation) => match automatic.symlink_metadata() {
1365            Ok(meta) => {
1366                ensure!(meta.is_file(), "invalid automatic retry marker");
1367                (
1368                    admin.join(format!("magi-rebase-recording-retry-{generation}")),
1369                    true,
1370                )
1371            }
1372            // The first stop may have failed validation before any claim.
1373            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (automatic, false),
1374            Err(e) => return Err(e).context("inspect automatic retry marker"),
1375        },
1376        None => (automatic, false),
1377    };
1378    ensure!(!marker.try_exists()?, "recording retry already spent");
1379    ensure!(
1380        git(scratch, &["status", "--porcelain", "--untracked-files=all"])
1381            .await?
1382            .is_empty(),
1383        "scratch has uncommitted changes"
1384    );
1385
1386    let saved = read(admin.join("magi-rebase-picks"))?;
1387    ensure!(saved.ends_with('\n'), "incomplete saved pick ledger");
1388    let mut picks = saved.lines();
1389    let mut done_picks = 0;
1390    for (file, done) in [("done", true), ("git-rebase-todo", false)] {
1391        let text = read(seq.join(file))?;
1392        let mut steps = instructions(&text, exec).peekable();
1393        // Git appends the failed exec to `done` AND puts it back first in the
1394        // todo. A previous retry adds another identical exec in `done`.
1395        if !done {
1396            ensure!(
1397                matches!(steps.next().transpose()?, Some(Instruction::Record)),
1398                "the recording exec was not rescheduled"
1399            );
1400        }
1401        while let Some(step) = steps.next() {
1402            let Instruction::Pick(sha) = step? else {
1403                bail!("expected a pick in {file}");
1404            };
1405            let pick = full_commit(scratch, sha).await?;
1406            ensure!(
1407                picks.next() == Some(pick.as_str())
1408                    && is_ancestor(repo, &pick, original).await
1409                    && matches!(steps.next().transpose()?, Some(Instruction::Record)),
1410                "{file} does not match the saved pick/exec sequence"
1411            );
1412            done_picks += usize::from(done);
1413            if done && previously_retried {
1414                while steps
1415                    .next_if(|step| matches!(step, Ok(Instruction::Record)))
1416                    .is_some()
1417                {}
1418            }
1419        }
1420    }
1421    ensure!(
1422        picks.next().is_none() && done_picks > 0,
1423        "incomplete pick sequence"
1424    );
1425
1426    let heads = read(admin.join("magi-rebase-heads"))?;
1427    ensure!(
1428        (heads.is_empty() || heads.ends_with('\n')) && heads.lines().count() == done_picks - 1,
1429        "cannot prove the failed exec has not already recorded a HEAD"
1430    );
1431    let head = rev_parse(scratch, "HEAD^{commit}").await?;
1432    let mut previous = onto_sha;
1433    for sha in heads.lines().chain(std::iter::once(head.as_str())) {
1434        ensure!(
1435            sha.len() == head.len() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1436            "partial or invalid recorded HEAD"
1437        );
1438        if sha != previous {
1439            ensure!(
1440                git(scratch, &["rev-list", "--parents", "-1", sha]).await?
1441                    == format!("{sha} {previous}"),
1442                "recorded HEADs and scratch HEAD are not a replay onto the reserved target"
1443            );
1444        }
1445        previous = sha;
1446    }
1447    std::fs::File::create_new(marker)
1448        .context("cannot claim recording retry (already spent or scratch unwritable)")?
1449        .sync_all()?;
1450    Ok(())
1451}
1452
1453/// Resolve the linked scratch Git directory and verify its backlink.
1454pub(crate) async fn rebase_scratch_admin(repo: &Path, scratch: &Path) -> Result<PathBuf> {
1455    let common = crate::repo_lock::common_dir(repo)
1456        .await?
1457        .context("not a repository")?;
1458    let admin = std::fs::canonicalize(git(scratch, &["rev-parse", "--absolute-git-dir"]).await?)?;
1459    let backlink = std::fs::read_to_string(admin.join("gitdir"))?;
1460    ensure!(
1461        admin.parent() == Some(common.join("worktrees").as_path())
1462            && admin.join(backlink.trim_end()).canonicalize()?
1463                == scratch.join(".git").canonicalize()?,
1464        "not a scratch worktree of the reserved repository"
1465    );
1466    Ok(admin)
1467}
1468
1469/// Read a completed rebase's durable record, rejecting missing or corrupt data.
1470pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1471    let mut lists = Vec::new();
1472    for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1473        let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1474            .with_context(|| format!("read {name}"))?;
1475        let mut commits = Vec::new();
1476        for sha in text.lines() {
1477            let full = full_commit(scratch, sha).await?;
1478            anyhow::ensure!(full == sha, "non-full commit id in {name}");
1479            commits.push(full);
1480        }
1481        lists.push(commits);
1482    }
1483    let heads = lists.pop().unwrap();
1484    let picks = lists.pop().unwrap();
1485    anyhow::ensure!(
1486        !picks.is_empty() && picks.len() == heads.len(),
1487        "rebase pick/HEAD count mismatch"
1488    );
1489    Ok(RebaseRecord { picks, heads })
1490}
1491
1492/// Strip only the diagnostics emitted by our recording exec.
1493pub fn rebase_said(text: &str) -> String {
1494    text.trim()
1495        .split(['\r', '\n'])
1496        .filter(|line| !line.trim_start().starts_with("Executing:"))
1497        .collect::<Vec<_>>()
1498        .join("\n")
1499}
1500
1501/// How [`rebase_start`] ended.
1502#[derive(Debug, Clone, PartialEq, Eq)]
1503pub enum RebaseStart {
1504    /// It applied; the branch points at the rebased commits and the throwaway
1505    /// worktree is gone.
1506    Applied,
1507    /// It stopped on a conflict and the throwaway worktree was **kept**
1508    /// mid-rebase, for someone to resolve. Carries what git said.
1509    Conflicted(String),
1510    /// The sequencer stopped without a verified textual conflict. The scratch
1511    /// and Git output are retained for infrastructure recovery.
1512    Sequencer(String),
1513    /// It failed without leaving a rebase in progress; the worktree is gone
1514    /// and the branch is untouched. Carries what git said.
1515    Failed(String),
1516}
1517
1518/// Start rebasing `branch` onto `onto` inside a throwaway worktree, and leave
1519/// a conflict standing.
1520///
1521/// A worktree of its own for two reasons. The repository magi runs in may be
1522/// jj-colocated, where git `HEAD` is detached and a rebase in the primary
1523/// tree would move it under the operator; and a rebase that hits a conflict
1524/// leaves state behind, which is far easier to discard with the whole
1525/// directory than to unpick in a tree somebody is using.
1526///
1527/// Unlike [`rebase_branch_in_temp`] this does not abort on a conflict: the
1528/// caller decides whether to hand the conflicted tree to a fixer or to call
1529/// [`rebase_abort`]. Any leftover at `scratch` from an earlier attempt is
1530/// removed first, so callers re-entering a rebase already in progress must
1531/// check [`rebase_in_progress`] before calling this.
1532pub async fn rebase_start(
1533    repo: &Path,
1534    scratch: &Path,
1535    branch: &str,
1536    onto: &str,
1537) -> Result<RebaseStart> {
1538    rebase_prepare(repo, scratch, branch).await?;
1539    rebase_execute(repo, scratch, onto, REBASE_EXEC).await
1540}
1541
1542/// Preparation failed before any commits were replayed.
1543#[derive(Debug)]
1544pub struct RebasePreparationError(pub String);
1545
1546impl std::fmt::Display for RebasePreparationError {
1547    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1548        f.write_str(&self.0)
1549    }
1550}
1551
1552impl std::error::Error for RebasePreparationError {}
1553
1554/// Create the scratch checkout without starting the sequencer.
1555/// An interrupted sequencer belongs to its existing operation and is kept.
1556pub(crate) async fn rebase_prepare(repo: &Path, scratch: &Path, branch: &str) -> Result<()> {
1557    if checked_rebase_in_progress(scratch).await? {
1558        return Ok(());
1559    }
1560    let result = async {
1561        worktree_remove(repo, scratch).await.ok();
1562        let path = path_arg(scratch);
1563        let args = ["worktree", "add", "--force", &path, branch];
1564        let out = git_raw(repo, &args).await?;
1565        ensure!(
1566            out.ok(),
1567            "git {} (exit {:?}): {}",
1568            args.join(" "),
1569            out.code,
1570            if out.stderr.trim().is_empty() {
1571                &out.stdout
1572            } else {
1573                &out.stderr
1574            }
1575        );
1576        std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1577        Ok::<_, anyhow::Error>(())
1578    }
1579    .await;
1580    result.map_err(|e| {
1581        RebasePreparationError(format!(
1582            "prepare rebase scratch {}: {e:#}",
1583            scratch.display()
1584        ))
1585        .into()
1586    })
1587}
1588
1589/// Start the sequencer only after the caller has persisted its reservation.
1590pub(crate) async fn rebase_execute(
1591    repo: &Path,
1592    scratch: &Path,
1593    onto: &str,
1594    exec: &str,
1595) -> Result<RebaseStart> {
1596    std::fs::File::create_new(rebase_file(scratch, REBASE_PICKS_PENDING).await?)?.sync_all()?;
1597    let out = git_raw(
1598        scratch,
1599        &[
1600            "rebase",
1601            "--empty=drop",
1602            "--reschedule-failed-exec",
1603            "--exec",
1604            exec,
1605            onto,
1606        ],
1607    )
1608    .await?;
1609    if out.ok() {
1610        worktree_remove(repo, scratch).await.ok();
1611        return Ok(RebaseStart::Applied);
1612    }
1613    let why = rebase_said(&format!("{}\n{}", out.stderr, out.stdout));
1614    if checked_rebase_in_progress(scratch)
1615        .await
1616        .with_context(|| format!("{why}\ncannot read scratch rebase state"))?
1617    {
1618        finish_rebase_pick_capture(scratch, exec)
1619            .await
1620            .with_context(|| format!("{why}\ncannot record rebase picks"))?;
1621        return Ok(match unmerged_paths(scratch).await {
1622            Ok(paths) if paths.is_empty() => RebaseStart::Sequencer(why),
1623            Err(e) => RebaseStart::Sequencer(format!("{why}\ncannot read unmerged paths: {e:#}")),
1624            Ok(_) => match stopped_pick_with_exec(scratch, exec).await {
1625                Ok(Some(_)) => RebaseStart::Conflicted(why),
1626                Ok(None) => RebaseStart::Sequencer(why),
1627                Err(e) => {
1628                    RebaseStart::Sequencer(format!("{why}\ncannot identify stopped pick: {e:#}"))
1629                }
1630            },
1631        });
1632    }
1633    worktree_remove(repo, scratch).await.ok();
1634    Ok(RebaseStart::Failed(why))
1635}
1636
1637/// Is a rebase (merge or apply backend) in progress in `worktree`?
1638pub async fn rebase_in_progress(worktree: &Path) -> bool {
1639    checked_rebase_in_progress(worktree).await.unwrap_or(false)
1640}
1641
1642/// A missing scratch is idle; an unreadable scratch is not safe to replace.
1643pub(crate) async fn checked_rebase_in_progress(worktree: &Path) -> Result<bool> {
1644    match worktree.symlink_metadata() {
1645        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1646        result => ensure!(
1647            result?.is_dir(),
1648            "not a worktree directory: {}",
1649            worktree.display()
1650        ),
1651    }
1652    // Do not let Git search a parent checkout if the scratch backlink is gone.
1653    let backlink = worktree.join(".git");
1654    backlink
1655        .symlink_metadata()
1656        .with_context(|| format!("inspect scratch Git backlink {}", backlink.display()))?;
1657    for name in ["rebase-merge", "rebase-apply"] {
1658        let path = rebase_file(worktree, name).await?;
1659        match path.symlink_metadata() {
1660            Ok(meta) if meta.is_dir() => return Ok(true),
1661            Ok(_) => bail!("not a sequencer directory: {}", path.display()),
1662            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1663            Err(e) => return Err(e).with_context(|| format!("inspect {}", path.display())),
1664        }
1665    }
1666    Ok(false)
1667}
1668
1669/// Paths git reports as unmerged in `worktree`.
1670pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1671    let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1672    Ok(out
1673        .split('\0')
1674        .filter(|l| !l.is_empty())
1675        .map(str::to_owned)
1676        .collect())
1677}
1678
1679/// Abandon a rebase left standing by [`rebase_start`] and drop its worktree.
1680/// The branch is exactly where it was before the rebase began.
1681pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1682    git_raw(scratch, &["rebase", "--abort"]).await.ok();
1683    worktree_remove(repo, scratch).await.ok();
1684}
1685
1686/// Rebase a branch onto `onto`, inside a throwaway worktree.
1687///
1688/// `Ok(None)` means it applied and the branch now points at the rebased
1689/// commits. `Ok(Some(why))` means it did not: the branch is untouched, and
1690/// the string is what git said - a person has to decide. Nothing half-rebased
1691/// is left behind; see [`rebase_start`] for the variant that keeps a conflict
1692/// standing.
1693pub async fn rebase_branch_in_temp(
1694    repo: &Path,
1695    scratch: &Path,
1696    branch: &str,
1697    onto: &str,
1698) -> Result<Option<String>> {
1699    match rebase_start(repo, scratch, branch, onto).await? {
1700        RebaseStart::Applied => Ok(None),
1701        RebaseStart::Failed(why) => Ok(Some(why)),
1702        RebaseStart::Conflicted(why) | RebaseStart::Sequencer(why) => {
1703            rebase_abort(repo, scratch).await;
1704            Ok(Some(why))
1705        }
1706    }
1707}
1708
1709/// Bring an *attached* worktree's index and files in line with wherever its
1710/// branch now points.
1711///
1712/// [`rebase_branch_in_temp`] moves a branch from a throwaway worktree on
1713/// purpose - the whole point is never touching the tree someone else has
1714/// checked out. But a worktree that already had that branch checked out
1715/// shares the same ref: its `HEAD` resolves to the new commit the moment the
1716/// rebase lands elsewhere, while its index and working directory keep
1717/// whatever the old commit put there until something says otherwise. Left
1718/// alone, the next `git status` there reads as the whole rebase turning up
1719/// as an unstaged diff, and the next commit would be staged against stale
1720/// content.
1721pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1722    reset_hard_head(worktree).await?;
1723    clean_all(worktree).await
1724}
1725
1726/// The first half of [`sync_to_head`]: tracked files back on `HEAD`.
1727pub async fn reset_hard_head(worktree: &Path) -> Result<()> {
1728    git(worktree, &["reset", "--hard", "HEAD"])
1729        .await
1730        .map(|_| ())
1731}
1732
1733/// Remove untracked and ignored files after any project cleanup has finished.
1734pub async fn clean_all(worktree: &Path) -> Result<()> {
1735    git(worktree, &["clean", "-fdx"]).await.map(|_| ())
1736}
1737
1738/// Fetch one branch from `remote`, updating its remote-tracking ref.
1739///
1740/// The refspec is spelled out rather than left to `git fetch <remote>
1741/// <branch>`, which writes `FETCH_HEAD` and updates
1742/// `refs/remotes/<remote>/<branch>` only as a side effect of the remote's
1743/// configured refspec. Naming the destination makes the thing this function
1744/// exists for - a tracking ref that moved - the operation rather than a
1745/// consequence of configuration magi does not own.
1746///
1747/// Honest note: a CI failure was first read as proof that some git versions do
1748/// not update the tracking ref here. That was wrong - the fetch had nothing to
1749/// update because the test had pushed to the wrong branch - so this is
1750/// determinism, not a fix for a demonstrated portability bug.
1751///
1752/// Refs, not the working copy: nothing is checked out and no local branch
1753/// moves, so this is safe to run while the operator has uncommitted work.
1754/// Returned as a [`GitOut`] rather than an error so the caller can decide - a
1755/// machine with no network must still be able to start a run.
1756pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1757    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
1758    git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
1759}
1760
1761/// The best common ancestor of `a` and `b`, or an error when there is none.
1762pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
1763    Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
1764}
1765
1766/// Is `ancestor` an ancestor of (or equal to) `of`?
1767pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
1768    git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
1769        .await
1770        .is_ok_and(|o| o.ok())
1771}
1772
1773/// [`is_ancestor`] that keeps "no" apart from "could not tell": `merge-base
1774/// --is-ancestor` exits 0 for yes, 1 for no and anything else for an error
1775/// (an unknown object, a shallow clone), and reading an error as "no" would
1776/// report a merged change as unmerged.
1777pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
1778    let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
1779    match out.code {
1780        Some(0) => Ok(true),
1781        Some(1) => Ok(false),
1782        _ => bail!(
1783            "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
1784            crate::notices::exit_status(out.code),
1785            out.stderr
1786        ),
1787    }
1788}
1789
1790/// The commit `rev` names, or `None` when it names no commit here.
1791pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
1792    let spec = format!("{rev}^{{commit}}");
1793    let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
1794        .await
1795        .ok()?;
1796    (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
1797}
1798
1799/// Local and remote-tracking branches that contain `commit`.
1800pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
1801    let out = git(
1802        repo,
1803        &[
1804            "branch",
1805            "-a",
1806            "--contains",
1807            commit,
1808            "--format=%(refname:short)",
1809        ],
1810    )
1811    .await?;
1812    Ok(out
1813        .lines()
1814        .map(str::trim)
1815        .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
1816        .map(str::to_owned)
1817        .collect())
1818}
1819
1820/// Cherry-pick `commit` onto the worktree's HEAD under a neutral committer.
1821/// On a conflict the pick is aborted, so the worktree is left as it was, and
1822/// git's own words come back as the error.
1823pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
1824    let out = git_raw(
1825        worktree,
1826        &[
1827            "-c",
1828            "user.name=magi candidate",
1829            "-c",
1830            "user.email=magi@localhost",
1831            "cherry-pick",
1832            "-x",
1833            commit,
1834        ],
1835    )
1836    .await?;
1837    if out.ok() {
1838        return Ok(());
1839    }
1840    let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
1841    bail!(
1842        "cherry-pick of {commit} failed: {}",
1843        if out.stderr.is_empty() {
1844            out.stdout
1845        } else {
1846            out.stderr
1847        }
1848    )
1849}
1850
1851/// The tree object id of `rev`.
1852pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
1853    git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
1854}
1855
1856/// Does this ref resolve?
1857pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
1858    git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
1859        .await
1860        .is_ok_and(|o| o.ok())
1861}
1862
1863#[cfg(test)]
1864mod tests {
1865    #[tokio::test]
1866    async fn checkout_discovery_ignores_inherited_git_target() {
1867        const FIXTURE: &str = "MAGI_TEST_CHECKOUT_DISCOVERY_ROOT";
1868        if let Some(root) = std::env::var_os(FIXTURE) {
1869            let root = std::path::PathBuf::from(root);
1870            let first = root.join("first");
1871            let second = root.join("second");
1872            let plain = root.join("plain");
1873            assert_eq!(
1874                super::toplevel(&second)
1875                    .await
1876                    .unwrap()
1877                    .canonicalize()
1878                    .unwrap(),
1879                second.canonicalize().unwrap()
1880            );
1881            assert!(super::toplevel(&plain).await.is_err());
1882            assert!(!super::same_checkout(&first, &second).unwrap());
1883            assert!(super::same_checkout(&first, &plain).is_err());
1884            assert!(super::same_checkout(&first, &first.join("src")).unwrap());
1885            return;
1886        }
1887        let fixture = tempfile::tempdir().unwrap();
1888        let root = fixture.path();
1889        for name in ["first", "second"] {
1890            let checkout = root.join(name);
1891            std::fs::create_dir_all(checkout.join("src")).unwrap();
1892            super::git(&checkout, &["init", "-q"]).await.unwrap();
1893        }
1894        std::fs::create_dir(root.join("plain")).unwrap();
1895        let output = std::process::Command::new(std::env::current_exe().unwrap())
1896            .args([
1897                "--exact",
1898                "git::tests::checkout_discovery_ignores_inherited_git_target",
1899            ])
1900            .env(FIXTURE, root)
1901            .env("GIT_DIR", root.join("first/.git"))
1902            .env("GIT_WORK_TREE", root.join("first"))
1903            .env("GIT_CONFIG_COUNT", "1")
1904            .env("GIT_CONFIG_KEY_0", "core.worktree")
1905            .env("GIT_CONFIG_VALUE_0", root.join("first"))
1906            .output()
1907            .unwrap();
1908        let stdout = String::from_utf8_lossy(&output.stdout);
1909        assert!(
1910            output.status.success() && stdout.contains("1 passed"),
1911            "{stdout}"
1912        );
1913    }
1914
1915    #[test]
1916    fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
1917        for (native, expected) in [
1918            (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
1919            (
1920                r"\\?\UNC\server\share\work tree",
1921                "//server/share/work tree",
1922            ),
1923            (r"C:\temp\work tree", "C:/temp/work tree"),
1924            ("C:/temp/work tree", "C:/temp/work tree"),
1925        ] {
1926            assert_eq!(super::windows_cli_path(native), expected);
1927        }
1928    }
1929
1930    #[test]
1931    fn git_cli_path_spelling_does_not_alias_extended_only_names() {
1932        for path in [
1933            r"\\?\C:\temp.\copy",
1934            r"\\?\C:\temp \copy",
1935            r"\\?\C:\NUL.txt\copy",
1936            r"\\?\C:\COM1\copy",
1937        ] {
1938            assert!(super::windows_cli_path(path).starts_with("//?/"));
1939        }
1940    }
1941
1942    #[cfg(unix)]
1943    #[test]
1944    fn git_cli_path_spelling_preserves_native_paths_on_unix() {
1945        assert_eq!(
1946            super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
1947            r"/tmp/back\slash"
1948        );
1949    }
1950
1951    #[test]
1952    fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
1953        let temp = tempfile::tempdir().unwrap();
1954        let canonical = temp.path().canonicalize().unwrap();
1955        let printed = super::path_arg(&canonical);
1956        assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
1957        // Joining onto a Windows verbatim path normalizes parent components.
1958        // Preserve the spelling so the boundary, rather than PathBuf, rejects it.
1959        let noncanonical = format!("{printed}/child/..");
1960        std::fs::create_dir(canonical.join("child")).unwrap();
1961        assert!(super::canonical_output_path(&noncanonical).is_err());
1962        #[cfg(unix)]
1963        {
1964            let alias = canonical.join("alias");
1965            std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
1966            assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
1967        }
1968    }
1969
1970    use super::*;
1971
1972    #[tokio::test]
1973    async fn recording_exec_transient_failure() {
1974        recording_exec_fixture(false).await;
1975    }
1976
1977    #[tokio::test]
1978    async fn recording_exec_persistent_failure() {
1979        recording_exec_fixture(true).await;
1980    }
1981
1982    fn shell_script(path: &Path, body: &str) {
1983        std::fs::write(path, body).unwrap();
1984        #[cfg(unix)]
1985        {
1986            use std::os::unix::fs::PermissionsExt as _;
1987            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
1988        }
1989    }
1990
1991    #[tokio::test]
1992    async fn rebase_pick_ledger_publish_failure_can_resume() {
1993        use crate::rebase::{Rebased, SEQUENCER_INFRASTRUCTURE, rebase_prepared_with_exec};
1994        use crate::run::RunState;
1995
1996        crate::run::pin_test_home();
1997        let (_temp, repo) = scratch().await;
1998        let base = rev_parse(&repo, "main").await.unwrap();
1999        sh(&repo, &["checkout", "-qb", "topic"]);
2000        track(&repo, "topic", "topic").await;
2001        let original = rev_parse(&repo, "topic").await.unwrap();
2002        sh(&repo, &["checkout", "-q", "main"]);
2003        track(&repo, "upstream", "upstream").await;
2004        let mut state = RunState::new(
2005            repo.clone(),
2006            "main".into(),
2007            base,
2008            "sync".into(),
2009            crate::config::Config::default(),
2010        );
2011        let work = repo.parent().unwrap().join("scratch");
2012        rebase_prepare(&repo, &work, "topic").await.unwrap();
2013        let obstacle = rebase_file(&work, "magi-rebase-picks.tmp").await.unwrap();
2014        std::fs::create_dir(&obstacle).unwrap();
2015        let exec = format!(
2016            r#"if test -d "$(git rev-parse --git-path magi-rebase-picks.tmp)"; then echo 'fixture ledger failure' >&2; exit 1; fi; {REBASE_EXEC}"#
2017        );
2018        let error = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2019            .await
2020            .unwrap_err();
2021        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2022        let mut state = RunState::load(&state.id).unwrap();
2023        let block = state.resource_block.as_ref().unwrap();
2024        assert_eq!(block.kind, SEQUENCER_INFRASTRUCTURE);
2025        assert!(block.detail.contains("fixture ledger failure"), "{block:?}");
2026        assert!(
2027            block.detail.contains("cannot record rebase picks"),
2028            "{block:?}"
2029        );
2030        assert!(rebase_in_progress(&work).await);
2031        assert_eq!(rev_parse(&repo, "topic").await.unwrap(), original);
2032        std::fs::remove_dir(obstacle).unwrap();
2033
2034        assert_eq!(
2035            rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2036                .await
2037                .unwrap(),
2038            Rebased::Applied
2039        );
2040        assert!(state.rebase_fixes.is_empty());
2041        assert!(is_ancestor(&repo, "main", "topic").await);
2042    }
2043
2044    async fn recording_exec_fixture(persistent: bool) {
2045        use crate::queue::{Queue, Source, Task};
2046        use crate::rebase::{Rebased, SEQUENCER_INFRASTRUCTURE, rebase_prepared_with_exec};
2047        use crate::run::{Origin, RunState};
2048
2049        crate::run::pin_test_home();
2050        let temp = tempfile::tempdir().unwrap();
2051        let root = temp.path();
2052        let exec = format!(
2053            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}"#
2054        );
2055        let (_temp, repo) = scratch().await;
2056        sh(&repo, &["config", "magi.test-root", &path_arg(root)]);
2057        let base = rev_parse(&repo, "main").await.unwrap();
2058        sh(&repo, &["checkout", "-qb", "topic"]);
2059        track(&repo, "one", "one").await;
2060        track(&repo, "two", "two").await;
2061        let picks = git(&repo, &["rev-list", "--reverse", "main..topic"])
2062            .await
2063            .unwrap();
2064        sh(&repo, &["checkout", "-q", "main"]);
2065        track(&repo, "upstream", "upstream").await;
2066        let hooks = root.join("hooks");
2067        std::fs::create_dir(&hooks).unwrap();
2068        shell_script(
2069            &hooks.join("post-rewrite"),
2070            r#"#!/bin/sh
2071test "$1" = rebase || exit 0
2072root=$(git config --local magi.test-root) || exit 1
2073for name in picks heads; do
2074    cp "$(git rev-parse --git-path magi-rebase-$name)" "$root/$name" || exit 1
2075done
2076"#,
2077        );
2078        sh(&repo, &["config", "core.hooksPath", &path_arg(&hooks)]);
2079        let mut state = RunState::new(
2080            repo.clone(),
2081            "main".into(),
2082            base,
2083            "sync".into(),
2084            crate::config::Config::default(),
2085        );
2086        let queue = Queue::open();
2087        let mut task = Task::new("sync".into(), "sync".into(), repo.clone(), Source::Human);
2088        state.origin = Some(Origin::queue(&task.id));
2089        state.task_instruction = Some(task.instruction.clone());
2090        task.start(state.id.clone());
2091        queue.put(&mut task).unwrap();
2092        let work = root.join("scratch");
2093        rebase_prepare(&repo, &work, "topic").await.unwrap();
2094        let attempts = || std::fs::read_to_string(root.join("attempts")).unwrap();
2095        if persistent {
2096            std::fs::write(root.join("fault"), "").unwrap();
2097            // Neither the failed retry nor a restart can spend another slot.
2098            for _ in 0..2 {
2099                let error = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2100                    .await
2101                    .unwrap_err();
2102                assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
2103                state = RunState::load(&state.id).unwrap();
2104                let block = state.resource_block.as_ref().unwrap();
2105                assert_eq!(block.kind, SEQUENCER_INFRASTRUCTURE);
2106                assert!(
2107                    block.detail.contains("fixture recording exec failed"),
2108                    "{block:?}"
2109                );
2110                assert!(state.rebase_fixes.is_empty());
2111                assert_eq!(attempts().lines().collect::<Vec<_>>(), ["failed", "failed"]);
2112                assert!(rebase_in_progress(&work).await);
2113            }
2114            // A complete append reported as failed, a torn append, or an
2115            // edited todo cannot be repaired by retrying an exec.
2116            let heads_file = rebase_file(&work, "magi-rebase-heads").await.unwrap();
2117            let todo_file = rebase_file(&work, "rebase-merge/git-rebase-todo")
2118                .await
2119                .unwrap();
2120            let original = rev_parse(&repo, "topic").await.unwrap();
2121            let target = rev_parse(&repo, "main").await.unwrap();
2122            let claim =
2123                || claim_recording_retry(&repo, &work, "topic", &original, &target, Some(1), &exec);
2124            let head = rev_parse(&work, "HEAD").await.unwrap();
2125            for invalid in [format!("{head}\n"), head[..12].to_string()] {
2126                std::fs::write(&heads_file, invalid).unwrap();
2127                assert!(claim().await.is_err());
2128            }
2129            std::fs::write(&heads_file, "").unwrap();
2130            let todo = std::fs::read_to_string(&todo_file).unwrap();
2131            std::fs::write(&todo_file, format!("exec true\n{todo}")).unwrap();
2132            assert!(claim().await.is_err());
2133            std::fs::write(todo_file, todo).unwrap();
2134            std::fs::remove_file(root.join("fault")).unwrap();
2135            task.release_operator("resume", None);
2136            queue.put(&mut task).unwrap();
2137        }
2138        let result = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2139            .await
2140            .unwrap();
2141        assert_eq!(result, Rebased::Applied);
2142        assert!(state.rebase_fixes.is_empty());
2143        assert_eq!(attempts().lines().count(), if persistent { 4 } else { 3 });
2144        let heads = git(&repo, &["rev-list", "--reverse", "main..topic"])
2145            .await
2146            .unwrap();
2147        assert_eq!(heads.lines().count(), 2);
2148        assert_eq!(
2149            std::fs::read_to_string(root.join("picks")).unwrap().trim(),
2150            picks
2151        );
2152        assert_eq!(
2153            std::fs::read_to_string(root.join("heads")).unwrap().trim(),
2154            heads
2155        );
2156    }
2157
2158    #[test]
2159    fn worktree_holder_is_read_from_the_porcelain_listing() {
2160        let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
2161                       worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
2162                       worktree /wt/detached\nHEAD ccc\ndetached\n";
2163        assert_eq!(
2164            parse_worktree_holder(listing, "magi/f82f/A"),
2165            Some(PathBuf::from("/wt/cand-A"))
2166        );
2167        assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
2168        assert_eq!(parse_worktree_holder(listing, "other"), None);
2169    }
2170
2171    async fn scratch() -> (tempfile::TempDir, PathBuf) {
2172        let dir = tempfile::tempdir().unwrap();
2173        let repo = dir.path().join("repo");
2174        tokio::fs::create_dir_all(&repo).await.unwrap();
2175        git(&repo, &["init", "-b", "main"]).await.unwrap();
2176        git(&repo, &["config", "user.name", "test"]).await.unwrap();
2177        git(&repo, &["config", "user.email", "test@example.com"])
2178            .await
2179            .unwrap();
2180        tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
2181        git(&repo, &["add", "-A"]).await.unwrap();
2182        git(&repo, &["commit", "-m", "init"]).await.unwrap();
2183        (dir, repo)
2184    }
2185
2186    #[tokio::test]
2187    async fn restore_to_removes_nested_repositories_inside_submodules() {
2188        let (_parent_dir, repo) = scratch().await;
2189        let (_source_dir, source) = scratch().await;
2190        sh(
2191            &repo,
2192            &[
2193                "-c",
2194                "protocol.file.allow=always",
2195                "submodule",
2196                "add",
2197                &source.to_string_lossy(),
2198                "sub",
2199            ],
2200        );
2201        sh(&repo, &["commit", "-am", "add submodule"]);
2202        let pre = rev_parse(&repo, "HEAD").await.unwrap();
2203        let sub = repo.join("sub");
2204        sh(&sub, &["init", "nested"]);
2205        tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
2206            .await
2207            .unwrap();
2208
2209        restore_to(&repo, &pre).await.unwrap();
2210
2211        assert!(!sub.join("nested").exists());
2212        assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
2213        assert_eq!(
2214            rev_parse(&sub, "HEAD").await.unwrap(),
2215            rev_parse(&source, "HEAD").await.unwrap()
2216        );
2217        assert!(
2218            git(&repo, &["status", "--porcelain"])
2219                .await
2220                .unwrap()
2221                .is_empty()
2222        );
2223    }
2224
2225    #[tokio::test]
2226    async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
2227        let (_g, repo) = scratch().await;
2228
2229        // A side branch touching a different file: rebases cleanly.
2230        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2231        tokio::fs::write(repo.join("b.txt"), "side\n")
2232            .await
2233            .unwrap();
2234        git(&repo, &["add", "-A"]).await.unwrap();
2235        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2236
2237        // main moves under it, which is what a repository merging other
2238        // pull requests does to a competition that took two hours.
2239        git(&repo, &["checkout", "main"]).await.unwrap();
2240        tokio::fs::write(repo.join("c.txt"), "main\n")
2241            .await
2242            .unwrap();
2243        git(&repo, &["add", "-A"]).await.unwrap();
2244        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2245
2246        let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
2247        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
2248            .await
2249            .unwrap();
2250        assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
2251        assert_eq!(
2252            commits_ahead(&repo, "main", "side").await.unwrap(),
2253            1,
2254            "one commit, replayed onto the new base"
2255        );
2256        assert!(
2257            !scratch_tree.exists(),
2258            "the throwaway worktree is not left behind"
2259        );
2260
2261        // A real conflict: both sides edit the same line.
2262        git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
2263        tokio::fs::write(repo.join("a.txt"), "clash\n")
2264            .await
2265            .unwrap();
2266        git(&repo, &["add", "-A"]).await.unwrap();
2267        git(&repo, &["commit", "-m", "clash"]).await.unwrap();
2268        git(&repo, &["checkout", "main"]).await.unwrap();
2269        tokio::fs::write(repo.join("a.txt"), "main edit\n")
2270            .await
2271            .unwrap();
2272        git(&repo, &["add", "-A"]).await.unwrap();
2273        git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
2274
2275        let before = rev_parse(&repo, "clash").await.unwrap();
2276        let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
2277            .await
2278            .unwrap()
2279            .expect("a same-line clash cannot be rebased silently");
2280        assert!(
2281            why.to_lowercase().contains("conflict"),
2282            "the reason is what git said, which is what a person needs: {why}"
2283        );
2284        assert_eq!(
2285            rev_parse(&repo, "clash").await.unwrap(),
2286            before,
2287            "a failed rebase leaves the branch exactly where it was"
2288        );
2289        assert!(!scratch_tree.exists(), "and cleans up after itself");
2290    }
2291
2292    #[tokio::test]
2293    async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
2294        let (_g, repo) = scratch().await;
2295        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2296        for name in ["b.txt", "c.txt"] {
2297            tokio::fs::write(repo.join(name), "side\n").await.unwrap();
2298            git(&repo, &["add", "-A"]).await.unwrap();
2299            git(
2300                &repo,
2301                &["commit", "-m", "magi: candidate A (uncommitted work)"],
2302            )
2303            .await
2304            .unwrap();
2305        }
2306        git(&repo, &["checkout", "main"]).await.unwrap();
2307        let before = rev_parse(&repo, "main").await.unwrap();
2308
2309        let out = merge_squash(&repo, "side", "an explicit subject")
2310            .await
2311            .unwrap();
2312        assert!(out.ok(), "{}", out.stderr);
2313        assert_eq!(
2314            commits_ahead(&repo, &before, "main").await.unwrap(),
2315            1,
2316            "squash adds exactly one commit onto the tip, not one per candidate commit"
2317        );
2318        let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
2319        assert_eq!(
2320            subject, "an explicit subject",
2321            "the candidate's own placeholder subject must not survive: {subject}"
2322        );
2323    }
2324
2325    #[tokio::test]
2326    async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
2327        let (_g, repo) = scratch().await;
2328        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2329        tokio::fs::write(repo.join("b.txt"), "side\n")
2330            .await
2331            .unwrap();
2332        git(&repo, &["add", "-A"]).await.unwrap();
2333        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2334        git(&repo, &["checkout", "main"]).await.unwrap();
2335
2336        let before = rev_parse(&repo, "side").await.unwrap();
2337        let out = merge_ff_only(&repo, "side").await.unwrap();
2338        assert!(out.ok(), "{}", out.stderr);
2339        assert_eq!(
2340            rev_parse(&repo, "main").await.unwrap(),
2341            before,
2342            "a fast-forward moves the base tip to the branch, no merge commit"
2343        );
2344    }
2345
2346    #[tokio::test]
2347    async fn merge_ff_only_refuses_to_write_a_merge_commit() {
2348        let (_g, repo) = scratch().await;
2349        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2350        tokio::fs::write(repo.join("b.txt"), "side\n")
2351            .await
2352            .unwrap();
2353        git(&repo, &["add", "-A"]).await.unwrap();
2354        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2355
2356        // main diverges, so a fast-forward is no longer possible.
2357        git(&repo, &["checkout", "main"]).await.unwrap();
2358        tokio::fs::write(repo.join("c.txt"), "main\n")
2359            .await
2360            .unwrap();
2361        git(&repo, &["add", "-A"]).await.unwrap();
2362        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2363
2364        let before = rev_parse(&repo, "main").await.unwrap();
2365        let out = merge_ff_only(&repo, "side").await.unwrap();
2366        assert!(!out.ok(), "a divergent branch cannot fast-forward");
2367        assert_eq!(
2368            rev_parse(&repo, "main").await.unwrap(),
2369            before,
2370            "a refused fast-forward must not touch main"
2371        );
2372    }
2373
2374    #[tokio::test]
2375    async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
2376        let (guard, repo) = scratch().await;
2377
2378        // An attached worktree of an existing branch - the shape a winner's
2379        // worktree keeps in `graph::Runner`, not the detached checkouts used
2380        // for judges and reviewers.
2381        git(&repo, &["branch", "side"]).await.unwrap();
2382        let side_wt = guard.path().join("side-wt");
2383        git(
2384            &repo,
2385            &["worktree", "add", &side_wt.to_string_lossy(), "side"],
2386        )
2387        .await
2388        .unwrap();
2389        tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
2390            .await
2391            .unwrap();
2392        git(&side_wt, &["add", "-A"]).await.unwrap();
2393        git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
2394
2395        // main moves under it.
2396        git(&repo, &["checkout", "main"]).await.unwrap();
2397        tokio::fs::write(repo.join("c.txt"), "main\n")
2398            .await
2399            .unwrap();
2400        git(&repo, &["add", "-A"]).await.unwrap();
2401        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2402
2403        // Rebase from a throwaway worktree, never from `side_wt` itself.
2404        let scratch_tree = guard.path().join("rebase-scratch");
2405        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
2406            .await
2407            .unwrap();
2408        assert!(clean.is_none());
2409
2410        // `HEAD` in the sibling worktree already resolves to the rebased
2411        // commit - the ref is shared - but nothing has told its index or its
2412        // files, which still hold the pre-rebase checkout.
2413        assert_eq!(
2414            rev_parse(&side_wt, "HEAD").await.unwrap(),
2415            rev_parse(&repo, "side").await.unwrap(),
2416            "HEAD follows the moved ref"
2417        );
2418        assert!(
2419            !side_wt.join("c.txt").exists(),
2420            "stale until synced: main's new file has not reached this worktree's disk"
2421        );
2422
2423        sync_to_head(&side_wt).await.unwrap();
2424        assert!(side_wt.join("c.txt").is_file(), "synced now");
2425        assert!(
2426            side_wt.join("b.txt").is_file(),
2427            "the worktree's own committed work survives the sync"
2428        );
2429        assert!(is_clean(&side_wt).await.unwrap());
2430    }
2431
2432    #[tokio::test]
2433    async fn clean_repo_reports_clean_then_dirty() {
2434        let (_g, repo) = scratch().await;
2435        assert!(is_clean(&repo).await.unwrap());
2436        tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
2437        assert!(!is_clean(&repo).await.unwrap());
2438    }
2439
2440    async fn track(repo: &Path, name: &str, body: &str) {
2441        let p = repo.join(name);
2442        if let Some(d) = p.parent() {
2443            tokio::fs::create_dir_all(d).await.unwrap();
2444        }
2445        tokio::fs::write(&p, body).await.unwrap();
2446        git(repo, &["add", name]).await.unwrap();
2447        git(
2448            repo,
2449            &[
2450                "-c",
2451                "user.name=t",
2452                "-c",
2453                "user.email=t@localhost",
2454                "commit",
2455                "-q",
2456                "-m",
2457                "seed",
2458            ],
2459        )
2460        .await
2461        .unwrap();
2462    }
2463
2464    #[tokio::test]
2465    async fn rescue_withholds_a_foreign_lockfile() {
2466        let (_g, repo) = scratch().await;
2467        track(&repo, "web/bun.lock", "a\n").await;
2468        tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
2469            .await
2470            .unwrap();
2471        tokio::fs::write(repo.join("web/app.ts"), "real\n")
2472            .await
2473            .unwrap();
2474
2475        let r = rescue_commit(&repo, "rescue").await.unwrap();
2476        assert!(r.committed);
2477        assert_eq!(
2478            r.withheld,
2479            [Stray {
2480                path: "web/pnpm-lock.yaml".to_owned(),
2481                manager: "pnpm".to_owned(),
2482                kept_by: "web/bun.lock".to_owned(),
2483            }]
2484        );
2485        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2486            .await
2487            .unwrap();
2488        assert!(files.contains("web/app.ts"), "{files}");
2489        assert!(!files.contains("pnpm-lock"), "{files}");
2490        assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
2491    }
2492
2493    #[tokio::test]
2494    async fn rescue_with_only_a_stray_commits_nothing() {
2495        let (_g, repo) = scratch().await;
2496        track(&repo, "bun.lock", "a\n").await;
2497        tokio::fs::write(repo.join("yarn.lock"), "x\n")
2498            .await
2499            .unwrap();
2500        let r = rescue_commit(&repo, "rescue").await.unwrap();
2501        assert!(!r.committed);
2502        assert_eq!(r.withheld.len(), 1);
2503    }
2504
2505    #[tokio::test]
2506    async fn rescue_keeps_a_same_manager_lockfile_update() {
2507        let (_g, repo) = scratch().await;
2508        track(&repo, "bun.lock", "a\n").await;
2509        tokio::fs::write(repo.join("bun.lock"), "b\n")
2510            .await
2511            .unwrap();
2512        let r = rescue_commit(&repo, "rescue").await.unwrap();
2513        assert!(r.committed);
2514        assert!(r.withheld.is_empty());
2515        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2516            .await
2517            .unwrap();
2518        assert_eq!(files, "bun.lock");
2519    }
2520
2521    #[tokio::test]
2522    async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
2523        let (_g, repo) = scratch().await;
2524        track(&repo, "other/bun.lock", "a\n").await;
2525        tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
2526        tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
2527            .await
2528            .unwrap();
2529        let r = rescue_commit(&repo, "rescue").await.unwrap();
2530        assert!(r.committed);
2531        assert!(r.withheld.is_empty());
2532    }
2533
2534    #[test]
2535    fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
2536        let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
2537        assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
2538        assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
2539        assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
2540        // A manifest in another directory does not count.
2541        assert_eq!(
2542            stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
2543            1
2544        );
2545    }
2546
2547    #[tokio::test]
2548    async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
2549        let (guard, repo) = scratch().await;
2550        let wt = guard.path().join("scratch-wt");
2551        worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
2552        tokio::fs::write(wt.join("built.txt"), "build output")
2553            .await
2554            .unwrap();
2555        assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
2556        assert!(wt.join("built.txt").exists());
2557        let listing = git(&repo, &["worktree", "list", "--porcelain"])
2558            .await
2559            .unwrap();
2560        let registered = listing
2561            .lines()
2562            .filter_map(|line| line.strip_prefix("worktree "))
2563            .map(PathBuf::from)
2564            .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
2565            .expect("the refused removal must retain the worktree registration");
2566        assert!(worktree_remove(&repo, &wt).await.unwrap());
2567        assert!(!wt.exists());
2568        let listing = git(&repo, &["worktree", "list", "--porcelain"])
2569            .await
2570            .unwrap();
2571        assert!(!listing.lines().any(|line| {
2572            line.strip_prefix("worktree ")
2573                .is_some_and(|path| Path::new(path) == registered)
2574        }));
2575    }
2576
2577    #[tokio::test]
2578    async fn worktree_lifecycle_and_diff() {
2579        let (guard, repo) = scratch().await;
2580        let base = rev_parse(&repo, "HEAD").await.unwrap();
2581        let wt = guard.path().join("wt-a");
2582        worktree_add_branch(&repo, &wt, "magi/test/a", &base)
2583            .await
2584            .unwrap();
2585        tokio::fs::write(wt.join("b.txt"), "candidate\n")
2586            .await
2587            .unwrap();
2588
2589        assert!(commit_all(&wt, "candidate work").await.unwrap());
2590        assert!(!commit_all(&wt, "nothing left").await.unwrap());
2591
2592        assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
2593        let patch = diff(&wt, &base, "HEAD").await.unwrap();
2594        assert!(patch.contains("b.txt"), "patch was: {patch}");
2595        assert_eq!(
2596            changed_files(&wt, &base, "HEAD").await.unwrap(),
2597            ["b.txt".to_owned()]
2598        );
2599
2600        // The rescue commit must not carry the operator's identity.
2601        let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
2602            .await
2603            .unwrap();
2604        assert_eq!(author, "magi candidate <magi@localhost>");
2605
2606        assert!(worktree_remove(&repo, &wt).await.unwrap());
2607        assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
2608        assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
2609        assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
2610    }
2611
2612    #[tokio::test]
2613    async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
2614        let (guard, repo) = scratch().await;
2615        let base = rev_parse(&repo, "HEAD").await.unwrap();
2616        let wt = guard.path().join("wt-h");
2617        worktree_add_branch(&repo, &wt, "magi/test/h", &base)
2618            .await
2619            .unwrap();
2620        let hooks = guard.path().join("hooks");
2621        tokio::fs::create_dir_all(&hooks).await.unwrap();
2622
2623        assert!(enable_worktree_config(&repo).await.unwrap());
2624        set_worktree_hooks_path(&wt, &hooks).await.unwrap();
2625
2626        let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
2627            .await
2628            .unwrap();
2629        assert!(!in_wt.is_empty());
2630        let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
2631            .await
2632            .unwrap();
2633        assert!(
2634            !in_primary.ok(),
2635            "primary worktree must keep its own hooks: {in_primary:?}"
2636        );
2637
2638        disable_worktree_config(&repo).await.unwrap();
2639    }
2640
2641    #[tokio::test]
2642    async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
2643        let (_g, repo) = scratch().await;
2644
2645        // Two runs in the same repository, as `Config::daemon.max_concurrent_runs`
2646        // now allows: both acquire before either is done.
2647        acquire_worktree_config(&repo).await.unwrap();
2648        acquire_worktree_config(&repo).await.unwrap();
2649
2650        let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2651            .await
2652            .unwrap();
2653        assert_eq!(on, "true");
2654
2655        // The first run to finish releases its own reference. A plain
2656        // `disable_worktree_config` here is exactly the bug: it would turn
2657        // the setting off while the second run still depends on it.
2658        release_worktree_config(&repo).await.unwrap();
2659        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2660            .await
2661            .unwrap();
2662        assert_eq!(
2663            still_on, "true",
2664            "a sibling run's release must not disable the setting for the one still working"
2665        );
2666
2667        // Only the last release actually turns it back off.
2668        release_worktree_config(&repo).await.unwrap();
2669        let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
2670            .await
2671            .unwrap();
2672        assert!(
2673            !after.ok(),
2674            "the last release must turn the setting back off: {after:?}"
2675        );
2676    }
2677
2678    #[tokio::test]
2679    async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
2680        let (_g, repo) = scratch().await;
2681        git(&repo, &["config", "extensions.worktreeConfig", "true"])
2682            .await
2683            .unwrap();
2684
2685        // magi did not turn this on, so even after every acquire is released,
2686        // it must not turn it off - that is what a bare `enable_worktree_config`
2687        // already promised for the single-run case, and the ref-counted
2688        // version must keep that promise.
2689        acquire_worktree_config(&repo).await.unwrap();
2690        release_worktree_config(&repo).await.unwrap();
2691
2692        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2693            .await
2694            .unwrap();
2695        assert_eq!(still_on, "true");
2696    }
2697
2698    #[tokio::test]
2699    async fn local_exclude_is_idempotent() {
2700        let (_g, repo) = scratch().await;
2701        local_exclude(&repo, "/.magi/").await.unwrap();
2702        local_exclude(&repo, "/.magi/").await.unwrap();
2703        let path = repo.join(".git/info/exclude");
2704        let body = tokio::fs::read_to_string(&path).await.unwrap();
2705        assert_eq!(body.matches("/.magi/").count(), 1);
2706    }
2707
2708    fn sh(cwd: &Path, args: &[&str]) {
2709        let out = std::process::Command::new("git")
2710            .quiet()
2711            .args(args)
2712            .current_dir(cwd)
2713            .output()
2714            .unwrap();
2715        assert!(
2716            out.status.success(),
2717            "git {args:?}: {}",
2718            String::from_utf8_lossy(&out.stderr)
2719        );
2720    }
2721
2722    /// A checkout whose `origin` is a local bare repository holding `trunk`,
2723    /// with `origin/HEAD` unset (as after `git remote add` + push).
2724    async fn with_remote() -> (tempfile::TempDir, PathBuf) {
2725        let (g, repo) = scratch().await;
2726        let bare = g.path().join("bare.git");
2727        sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2728        sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2729        sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
2730        sh(&repo, &["fetch", "origin"]);
2731        (g, repo)
2732    }
2733
2734    #[test]
2735    fn remote_head_branch_strips_only_the_matching_remote() {
2736        assert_eq!(
2737            remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
2738            Some("main")
2739        );
2740        assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
2741        assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
2742    }
2743
2744    #[tokio::test]
2745    async fn merge_base_branch_reads_origin_head_when_present() {
2746        let (_g, repo) = with_remote().await;
2747        sh(&repo, &["remote", "set-head", "origin", "trunk"]);
2748        assert_eq!(
2749            merge_base_branch(&repo, "origin", None).await.unwrap(),
2750            "trunk"
2751        );
2752    }
2753
2754    #[tokio::test]
2755    async fn merge_base_branch_recovers_a_missing_origin_head() {
2756        let (_g, repo) = with_remote().await;
2757        // Newer git sets it on fetch; make the precondition true everywhere.
2758        sh(&repo, &["remote", "set-head", "origin", "-d"]);
2759        let head = git_raw(
2760            &repo,
2761            &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
2762        )
2763        .await
2764        .unwrap();
2765        assert!(!head.ok(), "precondition: no origin/HEAD");
2766        assert_eq!(
2767            merge_base_branch(&repo, "origin", None).await.unwrap(),
2768            "trunk"
2769        );
2770    }
2771
2772    #[tokio::test]
2773    async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
2774        let (_g, repo) = scratch().await;
2775        let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
2776        assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
2777    }
2778
2779    #[tokio::test]
2780    async fn merge_base_branch_prefers_the_explicit_base() {
2781        let (_g, repo) = with_remote().await;
2782        assert_eq!(
2783            merge_base_branch(&repo, "origin", Some("release"))
2784                .await
2785                .unwrap(),
2786            "release"
2787        );
2788    }
2789
2790    #[tokio::test]
2791    async fn merge_base_branch_names_an_unfetched_default_branch() {
2792        // A remote added after the fact, never fetched: no tracking refs, so
2793        // `set-head -a` cannot work, but the remote's own HEAD still names it.
2794        let (g, repo) = scratch().await;
2795        let bare = g.path().join("bare.git");
2796        sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2797        sh(
2798            &repo,
2799            &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
2800        );
2801        sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2802        assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
2803        assert_eq!(
2804            merge_base_branch(&repo, "origin", None).await.unwrap(),
2805            "trunk"
2806        );
2807    }
2808
2809    #[test]
2810    fn symref_branch_reads_ls_remote_output() {
2811        assert_eq!(
2812            symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
2813            Some("main")
2814        );
2815        assert_eq!(symref_branch("abc\tHEAD\n"), None);
2816    }
2817}