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