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};
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    let out = Command::new("git")
35        .args(args)
36        .current_dir(cwd)
37        .quiet()
38        // A hook that opens an editor or a credential prompt would hang a
39        // headless run forever.
40        .env("GIT_TERMINAL_PROMPT", "0")
41        .env("GIT_EDITOR", "true")
42        .stdin(Stdio::null())
43        .output()
44        .await
45        .with_context(|| format!("spawn git {}", args.join(" ")))?;
46    Ok(GitOut {
47        code: out.status.code(),
48        stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
49        stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
50    })
51}
52
53/// Run `git`, failing on a non-zero exit status.
54pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
55    let out = git_raw(cwd, args).await?;
56    if !out.ok() {
57        bail!(
58            "git {} failed in {} (exit {:?}): {}",
59            args.join(" "),
60            cwd.display(),
61            out.code,
62            if out.stderr.is_empty() {
63                out.stdout.as_str()
64            } else {
65                out.stderr.as_str()
66            }
67        );
68    }
69    Ok(out.stdout)
70}
71
72/// Absolute path to the top level of the working tree containing `path`.
73pub async fn toplevel(path: &Path) -> Result<PathBuf> {
74    let out = git(path, &["rev-parse", "--show-toplevel"]).await?;
75    Ok(PathBuf::from(out))
76}
77
78/// Resolve a revision to a full object id.
79pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
80    git(repo, &["rev-parse", rev]).await
81}
82
83/// Currently checked-out branch, or `None` when detached.
84pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
85    let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
86    Ok(if out.ok() && !out.stdout.is_empty() {
87        Some(out.stdout)
88    } else {
89        None
90    })
91}
92
93/// Is the working tree free of tracked modifications and untracked files?
94pub async fn is_clean(repo: &Path) -> Result<bool> {
95    Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
96}
97
98/// `git status --porcelain`, for reporting what is dirty.
99pub async fn status_porcelain(repo: &Path) -> Result<String> {
100    git(repo, &["status", "--porcelain"]).await
101}
102
103/// Create a worktree at `path` with a fresh branch `branch` starting at `base`.
104pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
105    if let Some(parent) = path.parent() {
106        tokio::fs::create_dir_all(parent).await.ok();
107    }
108    let path_s = path.to_string_lossy().to_string();
109    git(repo, &["worktree", "add", "-b", branch, &path_s, base])
110        .await
111        .map(|_| ())
112}
113
114/// Create a worktree at `path` with a detached HEAD at `rev`.
115pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
116    if let Some(parent) = path.parent() {
117        tokio::fs::create_dir_all(parent).await.ok();
118    }
119    let path_s = path.to_string_lossy().to_string();
120    git(repo, &["worktree", "add", "--detach", &path_s, rev])
121        .await
122        .map(|_| ())
123}
124
125/// Move an existing detached worktree to `rev`, discarding local state.
126pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
127    git(worktree, &["checkout", "--detach", rev]).await?;
128    git(worktree, &["reset", "--hard", rev]).await?;
129    git(worktree, &["clean", "-fdx"]).await?;
130    Ok(())
131}
132
133/// Where `branch` is checked out, if some worktree holds it.
134///
135/// Read from `git worktree list --porcelain` rather than out of an error
136/// message, which varies with git's version and locale.
137pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
138    let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
139    Ok(parse_worktree_holder(&listing, branch))
140}
141
142fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
143    let want = format!("refs/heads/{branch}");
144    let mut path: Option<PathBuf> = None;
145    for line in listing.lines() {
146        if let Some(p) = line.strip_prefix("worktree ") {
147            path = Some(PathBuf::from(p));
148        } else if line.strip_prefix("branch ") == Some(want.as_str()) {
149            return path;
150        }
151    }
152    None
153}
154
155/// Remove a worktree. Returns `Ok(false)` when git refused (e.g. the path is
156/// already gone), so callers can keep folding the rest of a run.
157pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
158    let path_s = path.to_string_lossy().to_string();
159    let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
160    if out.ok() {
161        return Ok(true);
162    }
163    // A worktree whose directory was deleted by hand only needs pruning.
164    git_raw(repo, &["worktree", "prune"]).await?;
165    Ok(false)
166}
167
168/// Remove a worktree only if git finds it clean: no `--force`, so a change
169/// made after the caller last looked is refused rather than thrown away.
170/// Ignored files (`target/`) do not count as changes and go with it.
171pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
172    let path_s = path.to_string_lossy().to_string();
173    Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
174}
175
176/// Unregister a linked worktree whose directory is about to be deleted by
177/// hand, so the path can be `worktree add`-ed again.
178///
179/// A linked worktree's `.git` is a file whose `gitdir:` line names the
180/// bookkeeping entry inside its repository's admin directory; pruning from
181/// there removes the registration without touching the directory. No-op when
182/// `dir` is not a registered worktree (`.git` missing or not a `gitdir:`
183/// link): nothing was registered, nothing survives removal.
184pub async fn remove_worktree_from_linked(dir: &Path) {
185    let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
186        return;
187    };
188    let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
189        return;
190    };
191    // `<repo>/.git/worktrees/<name>`, so the repository's git dir is two
192    // levels up from here.
193    let admin = Path::new(admin);
194    let Some(common) = admin.parent().and_then(Path::parent) else {
195        return;
196    };
197    let common_s = common.to_string_lossy();
198    let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
199}
200
201/// Drop registrations for worktrees whose directory is already gone.
202///
203/// `git worktree remove` already does this for the path it just removed, but
204/// a directory deleted by hand - [`crate::clean::fold_orphaned_worktrees`], or
205/// an operator's own `rm -rf` - leaves the registration behind, and a
206/// registered path refuses a fresh `worktree add` until something prunes it.
207/// The operator's own machine had 31 such registrations sitting in one
208/// repository, all of them for directories that no longer existed.
209pub async fn worktree_prune(repo: &Path) -> Result<()> {
210    git(repo, &["worktree", "prune"]).await.map(|_| ())
211}
212
213/// Delete a branch, ignoring "not found".
214pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
215    Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
216}
217
218/// Does `branch` exist?
219pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
220    let refname = format!("refs/heads/{branch}");
221    Ok(
222        git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
223            .await?
224            .ok(),
225    )
226}
227
228/// Does `remote` have `branch`? `Err` when that cannot be told (unreachable
229/// remote), which callers must not read as "no".
230pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
231    let refname = format!("refs/heads/{branch}");
232    let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
233    match out.code {
234        Some(0) => Ok(true),
235        Some(2) => Ok(false),
236        code => bail!(
237            "git ls-remote {remote} failed (exit {code:?}): {}",
238            out.stderr
239        ),
240    }
241}
242
243/// Patch of `head` against the merge base with `base`.
244pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
245    let range = format!("{base}...{head}");
246    git(
247        worktree,
248        &["diff", "--no-color", "--no-ext-diff", "-M", &range],
249    )
250    .await
251}
252
253/// `--stat` summary of `base...head`.
254pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
255    let range = format!("{base}...{head}");
256    git(worktree, &["diff", "--no-color", "--stat", &range]).await
257}
258
259/// Number of files touched by `base...head`.
260pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
261    let range = format!("{base}...{head}");
262    let out = git(worktree, &["diff", "--name-only", &range]).await?;
263    Ok(out.lines().map(str::to_owned).collect())
264}
265
266/// One-line log of `base..head`, oldest first.
267pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
268    let range = format!("{base}..{head}");
269    git(
270        worktree,
271        &["log", "--reverse", "--format=%s%n%b%n--", &range],
272    )
273    .await
274}
275
276/// Subjects of the commits in `base..head`, oldest first. NUL-terminated so an
277/// empty subject keeps its place instead of shifting the later ones forward.
278pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
279    let range = format!("{base}..{head}");
280    let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
281    let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
282    // Whatever follows the last terminator is just the trailing newline.
283    parts.pop();
284    Ok(parts)
285}
286
287/// How many commits `head` is ahead of `base`.
288pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
289    let range = format!("{base}..{head}");
290    let out = git(worktree, &["rev-list", "--count", &range]).await?;
291    Ok(out.trim().parse().unwrap_or(0))
292}
293
294/// Stage everything and commit under a neutral identity.
295///
296/// Used to rescue an agent that edited files but never committed: without this
297/// its candidate would silently be empty. The neutral identity is part of the
298/// blindness contract — a real `user.name` in a candidate's history would name
299/// the operator, and an agent-configured one would name the vendor.
300pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
301    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
302        return Ok(false);
303    }
304    git(worktree, &["add", "-A"]).await?;
305    let out = git_raw(
306        worktree,
307        &[
308            "-c",
309            "user.name=magi candidate",
310            "-c",
311            "user.email=magi@localhost",
312            "commit",
313            "--no-verify",
314            "-m",
315            message,
316        ],
317    )
318    .await?;
319    if !out.ok() {
320        bail!("rescue commit failed: {}", out.stderr);
321    }
322    Ok(true)
323}
324
325/// A freshly created lockfile that belongs to a package manager the directory
326/// does not use, and was therefore left out of a rescue commit.
327#[derive(Debug, Clone, PartialEq, Eq)]
328pub struct Stray {
329    /// Repo-relative path, forward slashes.
330    pub path: String,
331    /// The package manager the file belongs to (`pnpm`, `cargo`, ...).
332    pub manager: String,
333    /// What made it foreign: the tracked lockfile (or `Cargo.toml`'s absence)
334    /// that says which manager the directory really uses.
335    pub kept_by: String,
336}
337
338/// What [`rescue_commit`] did.
339#[derive(Debug, Default)]
340pub struct Rescue {
341    /// Whether a commit was made.
342    pub committed: bool,
343    /// Files left untracked in the worktree instead of being committed.
344    pub withheld: Vec<Stray>,
345}
346
347/// `(ecosystem, manager)` for a lockfile's file name.
348fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
349    Some(match name {
350        "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
351        "yarn.lock" => ("node", "yarn"),
352        "pnpm-lock.yaml" => ("node", "pnpm"),
353        "bun.lock" | "bun.lockb" => ("node", "bun"),
354        "poetry.lock" => ("python", "poetry"),
355        "uv.lock" => ("python", "uv"),
356        "Pipfile.lock" => ("python", "pipenv"),
357        "pdm.lock" => ("python", "pdm"),
358        "Cargo.lock" => ("rust", "cargo"),
359        _ => return None,
360    })
361}
362
363fn split_dir(path: &str) -> (&str, &str) {
364    path.rsplit_once('/').unwrap_or(("", path))
365}
366
367/// Which of the newly created `untracked` files are lockfiles of a manager the
368/// repo does not use in that directory.
369///
370/// Foreign means: a lockfile of the same ecosystem but another manager is
371/// already tracked *in the same directory* (no recursion — a workspace root and
372/// a sub-package may legitimately differ), or, for `Cargo.lock`, there is no
373/// `Cargo.toml` beside it. A first lockfile in a directory with none is normal.
374pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
375    let mut out = Vec::new();
376    for path in untracked {
377        let (dir, name) = split_dir(path);
378        let Some((eco, manager)) = lock_kind(name) else {
379            continue;
380        };
381        let beside = |other: &String| split_dir(other).0 == dir;
382        let kept_by = if manager == "cargo" {
383            let has_manifest = tracked
384                .iter()
385                .chain(untracked)
386                .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
387            if has_manifest {
388                continue;
389            }
390            "no Cargo.toml in the directory".to_owned()
391        } else {
392            let Some(other) = tracked.iter().find(|p| {
393                beside(p)
394                    && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
395            }) else {
396                continue;
397            };
398            other.clone()
399        };
400        out.push(Stray {
401            path: path.clone(),
402            manager: manager.to_owned(),
403            kept_by,
404        });
405    }
406    out
407}
408
409async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
410    let out = git(worktree, args).await?;
411    Ok(out
412        .split('\0')
413        .filter(|s| !s.is_empty())
414        .map(str::to_owned)
415        .collect())
416}
417
418/// [`commit_all`] for an agent's leftover work, minus stray foreign lockfiles.
419///
420/// The withheld files stay untracked in the worktree (nothing is deleted) and
421/// are returned so the caller can record them: silently dropping them could
422/// lose a file the task really asked for.
423pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
424    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
425        return Ok(Rescue::default());
426    }
427    let untracked = nul_list(
428        worktree,
429        &["ls-files", "-z", "--others", "--exclude-standard"],
430    )
431    .await?;
432    let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
433    let withheld = stray_lockfiles(&untracked, &tracked);
434
435    git(worktree, &["add", "-A"]).await?;
436    if !withheld.is_empty() {
437        let mut args = vec!["reset", "-q", "--"];
438        args.extend(withheld.iter().map(|s| s.path.as_str()));
439        git(worktree, &args).await?;
440    }
441    if git_raw(worktree, &["diff", "--cached", "--quiet"])
442        .await?
443        .ok()
444    {
445        return Ok(Rescue {
446            committed: false,
447            withheld,
448        });
449    }
450    let out = git_raw(
451        worktree,
452        &[
453            "-c",
454            "user.name=magi candidate",
455            "-c",
456            "user.email=magi@localhost",
457            "commit",
458            "--no-verify",
459            "-m",
460            message,
461        ],
462    )
463    .await?;
464    if !out.ok() {
465        bail!("rescue commit failed: {}", out.stderr);
466    }
467    Ok(Rescue {
468        committed: true,
469        withheld,
470    })
471}
472
473/// Enable `extensions.worktreeConfig` if it is not already on.
474///
475/// Returns `true` when magi turned it on, so the caller can turn it back off
476/// during cleanup and leave the repo exactly as it found it.
477pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
478    let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
479    if out.ok() && out.stdout.trim() == "true" {
480        return Ok(false);
481    }
482    git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
483    Ok(true)
484}
485
486/// Undo [`enable_worktree_config`].
487pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
488    git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
489    Ok(())
490}
491
492/// How many runs currently want `extensions.worktreeConfig` on for one
493/// repository, and whether magi is the one that turned it on.
494struct WorktreeConfigRef {
495    /// Runs holding a reference, via [`acquire_worktree_config`].
496    count: usize,
497    /// Did *this process* flip the setting from off to on? If not - it was
498    /// already `true` when the first run in this process asked - nothing
499    /// here ever turns it off either; that is what [`enable_worktree_config`]
500    /// already decided for the single-run case, and the ref-counted version
501    /// must not second-guess it.
502    we_enabled: bool,
503}
504
505/// One entry per repository, each guarded by its own `tokio::sync::Mutex` so
506/// that two repositories' acquisitions never wait on each other - only two
507/// runs in the *same* repository do, which is the point.
508///
509/// A `std::sync::Mutex` guards the map itself, held only long enough to find
510/// or insert an entry and clone its `Arc`, never across an `.await`.
511static WORKTREE_CONFIG: std::sync::LazyLock<
512    std::sync::Mutex<
513        std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
514    >,
515> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
516
517/// The per-repository slot, creating it if this is the first run to ask.
518fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
519    let mut map = WORKTREE_CONFIG
520        .lock()
521        .unwrap_or_else(std::sync::PoisonError::into_inner);
522    map.entry(repo.to_path_buf())
523        .or_insert_with(|| {
524            std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
525                count: 0,
526                we_enabled: false,
527            }))
528        })
529        .clone()
530}
531
532/// Take a reference on `extensions.worktreeConfig` being on for `repo`.
533///
534/// [`enable_worktree_config`] alone is only safe for one run in a repository
535/// at a time: it is a plain get-then-set, so a second run's "already true?"
536/// check can see the first run's write and conclude it owns nothing to turn
537/// back off, while the first run's own cleanup turns the setting off under
538/// the second run's feet the moment *it* finishes - the exact race that let a
539/// finished run's fold disable the hook a still-running sibling in the same
540/// repository depended on. This ref-counts instead: the setting is turned on
541/// once, by whichever caller is first, and turned off only once every caller
542/// has released it via [`release_worktree_config`].
543///
544/// The per-repository lock is held across the `git config` call for the
545/// first acquire, so a second, concurrent acquire for the same repository
546/// waits for it rather than racing it - without that, both could observe
547/// "not yet counted" and both try to flip the setting on.
548pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
549    let slot = worktree_config_slot(repo);
550    let mut entry = slot.lock().await;
551    entry.count += 1;
552    if entry.count == 1 {
553        entry.we_enabled = enable_worktree_config(repo).await?;
554    }
555    Ok(())
556}
557
558/// Release a reference taken by [`acquire_worktree_config`].
559///
560/// Only the last release for a repository actually calls
561/// [`disable_worktree_config`], and only when this process was the one that
562/// turned the setting on in the first place.
563pub async fn release_worktree_config(repo: &Path) -> Result<()> {
564    let slot = worktree_config_slot(repo);
565    let mut entry = slot.lock().await;
566    entry.count = entry.count.saturating_sub(1);
567    if entry.count == 0 && entry.we_enabled {
568        disable_worktree_config(repo).await?;
569        entry.we_enabled = false;
570    }
571    Ok(())
572}
573
574/// Point a single worktree at its own hooks directory.
575///
576/// `core.hooksPath` is normally repo-wide; scoping it with `--worktree` keeps
577/// the operator's own hooks untouched in the primary worktree, and the setting
578/// disappears together with the worktree.
579pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
580    let dir = hooks_dir.to_string_lossy().replace('\\', "/");
581    git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
582        .await
583        .map(|_| ())
584}
585
586/// Exclude a path from a worktree's status without touching `.gitignore`.
587pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
588    let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
589    let path = worktree.join(git_dir);
590    if let Some(parent) = path.parent() {
591        tokio::fs::create_dir_all(parent).await.ok();
592    }
593    let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
594    if body.lines().any(|l| l.trim() == pattern) {
595        return Ok(());
596    }
597    if !body.is_empty() && !body.ends_with('\n') {
598        body.push('\n');
599    }
600    body.push_str(pattern);
601    body.push('\n');
602    tokio::fs::write(&path, body)
603        .await
604        .with_context(|| format!("write {}", path.display()))?;
605    Ok(())
606}
607
608/// `git merge --no-ff` of `branch` into the currently checked-out branch.
609///
610/// One of three ways to land a branch driven by [`crate::config::MergeStyle`]
611/// — see [`merge_squash`] and [`merge_ff_only`] for the other two, and that
612/// enum's own doc for why the choice between them lives in configuration.
613pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
614    git_raw(
615        repo,
616        &["merge", "--no-ff", "--no-edit", "-m", message, branch],
617    )
618    .await
619}
620
621/// `git merge --squash` of `branch`, followed by a commit under `message`.
622///
623/// Two `git` calls because `--squash` only stages the result — unlike
624/// [`merge_no_ff`] there is no merge commit for `--no-edit` to write, and
625/// skipping the second call is exactly the trap `land`'s module doc warns
626/// about: a squash that inherits `branch`'s own single-commit subject
627/// (`magi: candidate A (uncommitted work)`) instead of `message`. Returns the
628/// `--squash` step's own output, unrun `commit` included, when staging itself
629/// fails (a conflict), so a caller sees what actually went wrong rather than
630/// a `git commit` complaint about nothing being staged.
631pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
632    let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
633    if !staged.ok() {
634        return Ok(staged);
635    }
636    git_raw(repo, &["commit", "-m", message]).await
637}
638
639/// Fast-forward `branch` into the currently checked-out branch, refusing to
640/// create a merge commit.
641///
642/// Only ever fast-forwards because the winner was already rebased onto the
643/// tracked base tip before this runs (`Runner::sync_to_base`); at that point
644/// `--ff-only` is indistinguishable from GitHub's "rebase and merge" button.
645/// If the base moved again in the meantime this fails rather than falling
646/// back to a real rebase, the same way `merge_no_ff` fails rather than
647/// resolving a conflict — landing is not the place to improvise.
648pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
649    git_raw(repo, &["merge", "--ff-only", branch]).await
650}
651
652/// Push a branch to `remote`.
653pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
654    git_raw(repo, &["push", "-u", remote, branch]).await
655}
656
657/// Force-push a branch that has been rewritten, refusing to clobber work
658/// pushed since this side last looked.
659///
660/// `--force-with-lease` rather than `--force`: a rebase replaces the branch's
661/// commits, so a plain push is rejected, but a blind force would also throw
662/// away anything a person pushed to the same branch meanwhile. The lease
663/// turns that case into a failure instead of a loss.
664pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
665    git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
666}
667
668/// Force-push `branch` only if `remote` still has it at `expected`.
669///
670/// The lease is pinned to a sha the caller read itself, not to whatever the
671/// remote-tracking ref says at push time: a `fetch` in between moves the
672/// tracking ref, and a bare lease would then be measured against the very
673/// commit it was meant to protect a person's push from. A remote that has
674/// moved on refuses the push, so a concurrent push fails the step instead of
675/// being lost.
676pub async fn push_pinned(
677    repo: &Path,
678    remote: &str,
679    branch: &str,
680    expected: &str,
681) -> Result<GitOut> {
682    let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
683    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
684    git_raw(repo, &["push", &lease, remote, &refspec]).await
685}
686
687/// `git cherry <upstream> <head>`, split into the commits of `head` that have
688/// no patch-id twin in `upstream` (`+`) and those that do (`-`).
689pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
690    let out = git(repo, &["cherry", upstream, head]).await?;
691    let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
692    for line in out.lines() {
693        if let Some(sha) = line.strip_prefix("+ ") {
694            unmatched.push(sha.trim().to_owned());
695        } else if let Some(sha) = line.strip_prefix("- ") {
696            matched.push(sha.trim().to_owned());
697        }
698    }
699    Ok((unmatched, matched))
700}
701
702/// How [`rebase_start`] ended.
703#[derive(Debug, Clone, PartialEq, Eq)]
704pub enum RebaseStart {
705    /// It applied; the branch points at the rebased commits and the throwaway
706    /// worktree is gone.
707    Applied,
708    /// It stopped on a conflict and the throwaway worktree was **kept**
709    /// mid-rebase, for someone to resolve. Carries what git said.
710    Conflicted(String),
711    /// It failed without leaving a rebase in progress; the worktree is gone
712    /// and the branch is untouched. Carries what git said.
713    Failed(String),
714}
715
716/// Start rebasing `branch` onto `onto` inside a throwaway worktree, and leave
717/// a conflict standing.
718///
719/// A worktree of its own for two reasons. The repository magi runs in may be
720/// jj-colocated, where git `HEAD` is detached and a rebase in the primary
721/// tree would move it under the operator; and a rebase that hits a conflict
722/// leaves state behind, which is far easier to discard with the whole
723/// directory than to unpick in a tree somebody is using.
724///
725/// Unlike [`rebase_branch_in_temp`] this does not abort on a conflict: the
726/// caller decides whether to hand the conflicted tree to a fixer or to call
727/// [`rebase_abort`]. Any leftover at `scratch` from an earlier attempt is
728/// removed first, so callers re-entering a rebase already in progress must
729/// check [`rebase_in_progress`] before calling this.
730pub async fn rebase_start(
731    repo: &Path,
732    scratch: &Path,
733    branch: &str,
734    onto: &str,
735) -> Result<RebaseStart> {
736    // Removed first so a leftover from an interrupted attempt cannot make
737    // `worktree add` fail on a path that already exists.
738    worktree_remove(repo, scratch).await.ok();
739    git_raw(
740        repo,
741        &[
742            "worktree",
743            "add",
744            "--force",
745            &scratch.to_string_lossy(),
746            branch,
747        ],
748    )
749    .await?;
750
751    let out = git_raw(scratch, &["rebase", onto]).await?;
752    if out.ok() {
753        worktree_remove(repo, scratch).await.ok();
754        return Ok(RebaseStart::Applied);
755    }
756    let why = if out.stderr.trim().is_empty() {
757        out.stdout.trim().to_owned()
758    } else {
759        out.stderr.trim().to_owned()
760    };
761    if rebase_in_progress(scratch).await {
762        return Ok(RebaseStart::Conflicted(why));
763    }
764    worktree_remove(repo, scratch).await.ok();
765    Ok(RebaseStart::Failed(why))
766}
767
768/// Is a rebase (merge or apply backend) in progress in `worktree`?
769pub async fn rebase_in_progress(worktree: &Path) -> bool {
770    for name in ["rebase-merge", "rebase-apply"] {
771        let Ok(p) = git(worktree, &["rev-parse", "--git-path", name]).await else {
772            continue;
773        };
774        let p = Path::new(p.trim());
775        let full = if p.is_absolute() {
776            p.to_path_buf()
777        } else {
778            worktree.join(p)
779        };
780        if full.exists() {
781            return true;
782        }
783    }
784    false
785}
786
787/// Paths git reports as unmerged in `worktree`.
788pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
789    let out = git(worktree, &["diff", "--name-only", "--diff-filter=U"]).await?;
790    Ok(out
791        .lines()
792        .map(str::trim)
793        .filter(|l| !l.is_empty())
794        .map(str::to_owned)
795        .collect())
796}
797
798/// Abandon a rebase left standing by [`rebase_start`] and drop its worktree.
799/// The branch is exactly where it was before the rebase began.
800pub async fn rebase_abort(repo: &Path, scratch: &Path) {
801    git_raw(scratch, &["rebase", "--abort"]).await.ok();
802    worktree_remove(repo, scratch).await.ok();
803}
804
805/// Rebase a branch onto `onto`, inside a throwaway worktree.
806///
807/// `Ok(None)` means it applied and the branch now points at the rebased
808/// commits. `Ok(Some(why))` means it did not: the branch is untouched, and
809/// the string is what git said - a person has to decide. Nothing half-rebased
810/// is left behind; see [`rebase_start`] for the variant that keeps a conflict
811/// standing.
812pub async fn rebase_branch_in_temp(
813    repo: &Path,
814    scratch: &Path,
815    branch: &str,
816    onto: &str,
817) -> Result<Option<String>> {
818    match rebase_start(repo, scratch, branch, onto).await? {
819        RebaseStart::Applied => Ok(None),
820        RebaseStart::Failed(why) => Ok(Some(why)),
821        RebaseStart::Conflicted(why) => {
822            rebase_abort(repo, scratch).await;
823            Ok(Some(why))
824        }
825    }
826}
827
828/// Bring an *attached* worktree's index and files in line with wherever its
829/// branch now points.
830///
831/// [`rebase_branch_in_temp`] moves a branch from a throwaway worktree on
832/// purpose - the whole point is never touching the tree someone else has
833/// checked out. But a worktree that already had that branch checked out
834/// shares the same ref: its `HEAD` resolves to the new commit the moment the
835/// rebase lands elsewhere, while its index and working directory keep
836/// whatever the old commit put there until something says otherwise. Left
837/// alone, the next `git status` there reads as the whole rebase turning up
838/// as an unstaged diff, and the next commit would be staged against stale
839/// content.
840pub async fn sync_to_head(worktree: &Path) -> Result<()> {
841    git(worktree, &["reset", "--hard", "HEAD"]).await?;
842    git(worktree, &["clean", "-fdx"]).await?;
843    Ok(())
844}
845
846/// Fetch one branch from `remote`, updating its remote-tracking ref.
847///
848/// The refspec is spelled out rather than left to `git fetch <remote>
849/// <branch>`, which writes `FETCH_HEAD` and updates
850/// `refs/remotes/<remote>/<branch>` only as a side effect of the remote's
851/// configured refspec. Naming the destination makes the thing this function
852/// exists for - a tracking ref that moved - the operation rather than a
853/// consequence of configuration magi does not own.
854///
855/// Honest note: a CI failure was first read as proof that some git versions do
856/// not update the tracking ref here. That was wrong - the fetch had nothing to
857/// update because the test had pushed to the wrong branch - so this is
858/// determinism, not a fix for a demonstrated portability bug.
859///
860/// Refs, not the working copy: nothing is checked out and no local branch
861/// moves, so this is safe to run while the operator has uncommitted work.
862/// Returned as a [`GitOut`] rather than an error so the caller can decide - a
863/// machine with no network must still be able to start a run.
864pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
865    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
866    git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
867}
868
869/// Is `ancestor` an ancestor of (or equal to) `of`?
870pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
871    git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
872        .await
873        .is_ok_and(|o| o.ok())
874}
875
876/// [`is_ancestor`] that keeps "no" apart from "could not tell": `merge-base
877/// --is-ancestor` exits 0 for yes, 1 for no and anything else for an error
878/// (an unknown object, a shallow clone), and reading an error as "no" would
879/// report a merged change as unmerged.
880pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
881    let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
882    match out.code {
883        Some(0) => Ok(true),
884        Some(1) => Ok(false),
885        _ => bail!(
886            "git merge-base --is-ancestor {ancestor} {of} failed (exit {:?}): {}",
887            out.code,
888            out.stderr
889        ),
890    }
891}
892
893/// The commit `rev` names, or `None` when it names no commit here.
894pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
895    let spec = format!("{rev}^{{commit}}");
896    let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
897        .await
898        .ok()?;
899    (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
900}
901
902/// Local and remote-tracking branches that contain `commit`.
903pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
904    let out = git(
905        repo,
906        &[
907            "branch",
908            "-a",
909            "--contains",
910            commit,
911            "--format=%(refname:short)",
912        ],
913    )
914    .await?;
915    Ok(out
916        .lines()
917        .map(str::trim)
918        .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
919        .map(str::to_owned)
920        .collect())
921}
922
923/// Cherry-pick `commit` onto the worktree's HEAD under a neutral committer.
924/// On a conflict the pick is aborted, so the worktree is left as it was, and
925/// git's own words come back as the error.
926pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
927    let out = git_raw(
928        worktree,
929        &[
930            "-c",
931            "user.name=magi candidate",
932            "-c",
933            "user.email=magi@localhost",
934            "cherry-pick",
935            "-x",
936            commit,
937        ],
938    )
939    .await?;
940    if out.ok() {
941        return Ok(());
942    }
943    let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
944    bail!(
945        "cherry-pick of {commit} failed: {}",
946        if out.stderr.is_empty() {
947            out.stdout
948        } else {
949            out.stderr
950        }
951    )
952}
953
954/// The tree object id of `rev`.
955pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
956    git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
957}
958
959/// Does this ref resolve?
960pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
961    git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
962        .await
963        .is_ok_and(|o| o.ok())
964}
965
966#[cfg(test)]
967mod tests {
968    use super::*;
969
970    #[test]
971    fn worktree_holder_is_read_from_the_porcelain_listing() {
972        let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
973                       worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
974                       worktree /wt/detached\nHEAD ccc\ndetached\n";
975        assert_eq!(
976            parse_worktree_holder(listing, "magi/f82f/A"),
977            Some(PathBuf::from("/wt/cand-A"))
978        );
979        assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
980        assert_eq!(parse_worktree_holder(listing, "other"), None);
981    }
982
983    async fn scratch() -> (tempfile::TempDir, PathBuf) {
984        let dir = tempfile::tempdir().unwrap();
985        let repo = dir.path().join("repo");
986        tokio::fs::create_dir_all(&repo).await.unwrap();
987        git(&repo, &["init", "-b", "main"]).await.unwrap();
988        git(&repo, &["config", "user.name", "test"]).await.unwrap();
989        git(&repo, &["config", "user.email", "test@example.com"])
990            .await
991            .unwrap();
992        tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
993        git(&repo, &["add", "-A"]).await.unwrap();
994        git(&repo, &["commit", "-m", "init"]).await.unwrap();
995        (dir, repo)
996    }
997
998    #[tokio::test]
999    async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
1000        let (_g, repo) = scratch().await;
1001
1002        // A side branch touching a different file: rebases cleanly.
1003        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1004        tokio::fs::write(repo.join("b.txt"), "side\n")
1005            .await
1006            .unwrap();
1007        git(&repo, &["add", "-A"]).await.unwrap();
1008        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1009
1010        // main moves under it, which is what a repository merging other
1011        // pull requests does to a competition that took two hours.
1012        git(&repo, &["checkout", "main"]).await.unwrap();
1013        tokio::fs::write(repo.join("c.txt"), "main\n")
1014            .await
1015            .unwrap();
1016        git(&repo, &["add", "-A"]).await.unwrap();
1017        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1018
1019        let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
1020        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1021            .await
1022            .unwrap();
1023        assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
1024        assert_eq!(
1025            commits_ahead(&repo, "main", "side").await.unwrap(),
1026            1,
1027            "one commit, replayed onto the new base"
1028        );
1029        assert!(
1030            !scratch_tree.exists(),
1031            "the throwaway worktree is not left behind"
1032        );
1033
1034        // A real conflict: both sides edit the same line.
1035        git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
1036        tokio::fs::write(repo.join("a.txt"), "clash\n")
1037            .await
1038            .unwrap();
1039        git(&repo, &["add", "-A"]).await.unwrap();
1040        git(&repo, &["commit", "-m", "clash"]).await.unwrap();
1041        git(&repo, &["checkout", "main"]).await.unwrap();
1042        tokio::fs::write(repo.join("a.txt"), "main edit\n")
1043            .await
1044            .unwrap();
1045        git(&repo, &["add", "-A"]).await.unwrap();
1046        git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
1047
1048        let before = rev_parse(&repo, "clash").await.unwrap();
1049        let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
1050            .await
1051            .unwrap()
1052            .expect("a same-line clash cannot be rebased silently");
1053        assert!(
1054            why.to_lowercase().contains("conflict"),
1055            "the reason is what git said, which is what a person needs: {why}"
1056        );
1057        assert_eq!(
1058            rev_parse(&repo, "clash").await.unwrap(),
1059            before,
1060            "a failed rebase leaves the branch exactly where it was"
1061        );
1062        assert!(!scratch_tree.exists(), "and cleans up after itself");
1063    }
1064
1065    #[tokio::test]
1066    async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
1067        let (_g, repo) = scratch().await;
1068        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1069        for name in ["b.txt", "c.txt"] {
1070            tokio::fs::write(repo.join(name), "side\n").await.unwrap();
1071            git(&repo, &["add", "-A"]).await.unwrap();
1072            git(
1073                &repo,
1074                &["commit", "-m", "magi: candidate A (uncommitted work)"],
1075            )
1076            .await
1077            .unwrap();
1078        }
1079        git(&repo, &["checkout", "main"]).await.unwrap();
1080        let before = rev_parse(&repo, "main").await.unwrap();
1081
1082        let out = merge_squash(&repo, "side", "an explicit subject")
1083            .await
1084            .unwrap();
1085        assert!(out.ok(), "{}", out.stderr);
1086        assert_eq!(
1087            commits_ahead(&repo, &before, "main").await.unwrap(),
1088            1,
1089            "squash adds exactly one commit onto the tip, not one per candidate commit"
1090        );
1091        let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
1092        assert_eq!(
1093            subject, "an explicit subject",
1094            "the candidate's own placeholder subject must not survive: {subject}"
1095        );
1096    }
1097
1098    #[tokio::test]
1099    async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
1100        let (_g, repo) = scratch().await;
1101        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1102        tokio::fs::write(repo.join("b.txt"), "side\n")
1103            .await
1104            .unwrap();
1105        git(&repo, &["add", "-A"]).await.unwrap();
1106        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1107        git(&repo, &["checkout", "main"]).await.unwrap();
1108
1109        let before = rev_parse(&repo, "side").await.unwrap();
1110        let out = merge_ff_only(&repo, "side").await.unwrap();
1111        assert!(out.ok(), "{}", out.stderr);
1112        assert_eq!(
1113            rev_parse(&repo, "main").await.unwrap(),
1114            before,
1115            "a fast-forward moves the base tip to the branch, no merge commit"
1116        );
1117    }
1118
1119    #[tokio::test]
1120    async fn merge_ff_only_refuses_to_write_a_merge_commit() {
1121        let (_g, repo) = scratch().await;
1122        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1123        tokio::fs::write(repo.join("b.txt"), "side\n")
1124            .await
1125            .unwrap();
1126        git(&repo, &["add", "-A"]).await.unwrap();
1127        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1128
1129        // main diverges, so a fast-forward is no longer possible.
1130        git(&repo, &["checkout", "main"]).await.unwrap();
1131        tokio::fs::write(repo.join("c.txt"), "main\n")
1132            .await
1133            .unwrap();
1134        git(&repo, &["add", "-A"]).await.unwrap();
1135        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1136
1137        let before = rev_parse(&repo, "main").await.unwrap();
1138        let out = merge_ff_only(&repo, "side").await.unwrap();
1139        assert!(!out.ok(), "a divergent branch cannot fast-forward");
1140        assert_eq!(
1141            rev_parse(&repo, "main").await.unwrap(),
1142            before,
1143            "a refused fast-forward must not touch main"
1144        );
1145    }
1146
1147    #[tokio::test]
1148    async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
1149        let (guard, repo) = scratch().await;
1150
1151        // An attached worktree of an existing branch - the shape a winner's
1152        // worktree keeps in `graph::Runner`, not the detached checkouts used
1153        // for judges and reviewers.
1154        git(&repo, &["branch", "side"]).await.unwrap();
1155        let side_wt = guard.path().join("side-wt");
1156        git(
1157            &repo,
1158            &["worktree", "add", &side_wt.to_string_lossy(), "side"],
1159        )
1160        .await
1161        .unwrap();
1162        tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
1163            .await
1164            .unwrap();
1165        git(&side_wt, &["add", "-A"]).await.unwrap();
1166        git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
1167
1168        // main moves under it.
1169        git(&repo, &["checkout", "main"]).await.unwrap();
1170        tokio::fs::write(repo.join("c.txt"), "main\n")
1171            .await
1172            .unwrap();
1173        git(&repo, &["add", "-A"]).await.unwrap();
1174        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1175
1176        // Rebase from a throwaway worktree, never from `side_wt` itself.
1177        let scratch_tree = guard.path().join("rebase-scratch");
1178        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1179            .await
1180            .unwrap();
1181        assert!(clean.is_none());
1182
1183        // `HEAD` in the sibling worktree already resolves to the rebased
1184        // commit - the ref is shared - but nothing has told its index or its
1185        // files, which still hold the pre-rebase checkout.
1186        assert_eq!(
1187            rev_parse(&side_wt, "HEAD").await.unwrap(),
1188            rev_parse(&repo, "side").await.unwrap(),
1189            "HEAD follows the moved ref"
1190        );
1191        assert!(
1192            !side_wt.join("c.txt").exists(),
1193            "stale until synced: main's new file has not reached this worktree's disk"
1194        );
1195
1196        sync_to_head(&side_wt).await.unwrap();
1197        assert!(side_wt.join("c.txt").is_file(), "synced now");
1198        assert!(
1199            side_wt.join("b.txt").is_file(),
1200            "the worktree's own committed work survives the sync"
1201        );
1202        assert!(is_clean(&side_wt).await.unwrap());
1203    }
1204
1205    #[tokio::test]
1206    async fn clean_repo_reports_clean_then_dirty() {
1207        let (_g, repo) = scratch().await;
1208        assert!(is_clean(&repo).await.unwrap());
1209        tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
1210        assert!(!is_clean(&repo).await.unwrap());
1211    }
1212
1213    async fn track(repo: &Path, name: &str, body: &str) {
1214        let p = repo.join(name);
1215        if let Some(d) = p.parent() {
1216            tokio::fs::create_dir_all(d).await.unwrap();
1217        }
1218        tokio::fs::write(&p, body).await.unwrap();
1219        git(repo, &["add", name]).await.unwrap();
1220        git(
1221            repo,
1222            &[
1223                "-c",
1224                "user.name=t",
1225                "-c",
1226                "user.email=t@localhost",
1227                "commit",
1228                "-q",
1229                "-m",
1230                "seed",
1231            ],
1232        )
1233        .await
1234        .unwrap();
1235    }
1236
1237    #[tokio::test]
1238    async fn rescue_withholds_a_foreign_lockfile() {
1239        let (_g, repo) = scratch().await;
1240        track(&repo, "web/bun.lock", "a\n").await;
1241        tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
1242            .await
1243            .unwrap();
1244        tokio::fs::write(repo.join("web/app.ts"), "real\n")
1245            .await
1246            .unwrap();
1247
1248        let r = rescue_commit(&repo, "rescue").await.unwrap();
1249        assert!(r.committed);
1250        assert_eq!(
1251            r.withheld,
1252            [Stray {
1253                path: "web/pnpm-lock.yaml".to_owned(),
1254                manager: "pnpm".to_owned(),
1255                kept_by: "web/bun.lock".to_owned(),
1256            }]
1257        );
1258        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1259            .await
1260            .unwrap();
1261        assert!(files.contains("web/app.ts"), "{files}");
1262        assert!(!files.contains("pnpm-lock"), "{files}");
1263        assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
1264    }
1265
1266    #[tokio::test]
1267    async fn rescue_with_only_a_stray_commits_nothing() {
1268        let (_g, repo) = scratch().await;
1269        track(&repo, "bun.lock", "a\n").await;
1270        tokio::fs::write(repo.join("yarn.lock"), "x\n")
1271            .await
1272            .unwrap();
1273        let r = rescue_commit(&repo, "rescue").await.unwrap();
1274        assert!(!r.committed);
1275        assert_eq!(r.withheld.len(), 1);
1276    }
1277
1278    #[tokio::test]
1279    async fn rescue_keeps_a_same_manager_lockfile_update() {
1280        let (_g, repo) = scratch().await;
1281        track(&repo, "bun.lock", "a\n").await;
1282        tokio::fs::write(repo.join("bun.lock"), "b\n")
1283            .await
1284            .unwrap();
1285        let r = rescue_commit(&repo, "rescue").await.unwrap();
1286        assert!(r.committed);
1287        assert!(r.withheld.is_empty());
1288        let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1289            .await
1290            .unwrap();
1291        assert_eq!(files, "bun.lock");
1292    }
1293
1294    #[tokio::test]
1295    async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
1296        let (_g, repo) = scratch().await;
1297        track(&repo, "other/bun.lock", "a\n").await;
1298        tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
1299        tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
1300            .await
1301            .unwrap();
1302        let r = rescue_commit(&repo, "rescue").await.unwrap();
1303        assert!(r.committed);
1304        assert!(r.withheld.is_empty());
1305    }
1306
1307    #[test]
1308    fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
1309        let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
1310        assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
1311        assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
1312        assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
1313        // A manifest in another directory does not count.
1314        assert_eq!(
1315            stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
1316            1
1317        );
1318    }
1319
1320    #[tokio::test]
1321    async fn worktree_lifecycle_and_diff() {
1322        let (guard, repo) = scratch().await;
1323        let base = rev_parse(&repo, "HEAD").await.unwrap();
1324        let wt = guard.path().join("wt-a");
1325        worktree_add_branch(&repo, &wt, "magi/test/a", &base)
1326            .await
1327            .unwrap();
1328        tokio::fs::write(wt.join("b.txt"), "candidate\n")
1329            .await
1330            .unwrap();
1331
1332        assert!(commit_all(&wt, "candidate work").await.unwrap());
1333        assert!(!commit_all(&wt, "nothing left").await.unwrap());
1334
1335        assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
1336        let patch = diff(&wt, &base, "HEAD").await.unwrap();
1337        assert!(patch.contains("b.txt"), "patch was: {patch}");
1338        assert_eq!(
1339            changed_files(&wt, &base, "HEAD").await.unwrap(),
1340            ["b.txt".to_owned()]
1341        );
1342
1343        // The rescue commit must not carry the operator's identity.
1344        let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
1345            .await
1346            .unwrap();
1347        assert_eq!(author, "magi candidate <magi@localhost>");
1348
1349        assert!(worktree_remove(&repo, &wt).await.unwrap());
1350        assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
1351        assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
1352        assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
1353    }
1354
1355    #[tokio::test]
1356    async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
1357        let (guard, repo) = scratch().await;
1358        let base = rev_parse(&repo, "HEAD").await.unwrap();
1359        let wt = guard.path().join("wt-h");
1360        worktree_add_branch(&repo, &wt, "magi/test/h", &base)
1361            .await
1362            .unwrap();
1363        let hooks = guard.path().join("hooks");
1364        tokio::fs::create_dir_all(&hooks).await.unwrap();
1365
1366        assert!(enable_worktree_config(&repo).await.unwrap());
1367        set_worktree_hooks_path(&wt, &hooks).await.unwrap();
1368
1369        let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
1370            .await
1371            .unwrap();
1372        assert!(!in_wt.is_empty());
1373        let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
1374            .await
1375            .unwrap();
1376        assert!(
1377            !in_primary.ok(),
1378            "primary worktree must keep its own hooks: {in_primary:?}"
1379        );
1380
1381        disable_worktree_config(&repo).await.unwrap();
1382    }
1383
1384    #[tokio::test]
1385    async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
1386        let (_g, repo) = scratch().await;
1387
1388        // Two runs in the same repository, as `Config::daemon.max_concurrent_runs`
1389        // now allows: both acquire before either is done.
1390        acquire_worktree_config(&repo).await.unwrap();
1391        acquire_worktree_config(&repo).await.unwrap();
1392
1393        let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
1394            .await
1395            .unwrap();
1396        assert_eq!(on, "true");
1397
1398        // The first run to finish releases its own reference. A plain
1399        // `disable_worktree_config` here is exactly the bug: it would turn
1400        // the setting off while the second run still depends on it.
1401        release_worktree_config(&repo).await.unwrap();
1402        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
1403            .await
1404            .unwrap();
1405        assert_eq!(
1406            still_on, "true",
1407            "a sibling run's release must not disable the setting for the one still working"
1408        );
1409
1410        // Only the last release actually turns it back off.
1411        release_worktree_config(&repo).await.unwrap();
1412        let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
1413            .await
1414            .unwrap();
1415        assert!(
1416            !after.ok(),
1417            "the last release must turn the setting back off: {after:?}"
1418        );
1419    }
1420
1421    #[tokio::test]
1422    async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
1423        let (_g, repo) = scratch().await;
1424        git(&repo, &["config", "extensions.worktreeConfig", "true"])
1425            .await
1426            .unwrap();
1427
1428        // magi did not turn this on, so even after every acquire is released,
1429        // it must not turn it off - that is what a bare `enable_worktree_config`
1430        // already promised for the single-run case, and the ref-counted
1431        // version must keep that promise.
1432        acquire_worktree_config(&repo).await.unwrap();
1433        release_worktree_config(&repo).await.unwrap();
1434
1435        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
1436            .await
1437            .unwrap();
1438        assert_eq!(still_on, "true");
1439    }
1440
1441    #[tokio::test]
1442    async fn local_exclude_is_idempotent() {
1443        let (_g, repo) = scratch().await;
1444        local_exclude(&repo, "/.magi/").await.unwrap();
1445        local_exclude(&repo, "/.magi/").await.unwrap();
1446        let path = repo.join(".git/info/exclude");
1447        let body = tokio::fs::read_to_string(&path).await.unwrap();
1448        assert_eq!(body.matches("/.magi/").count(), 1);
1449    }
1450}