magi-cli 0.20.1

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Git plumbing.
//!
//! magi drives the `git` CLI rather than linking a library: every operation it
//! needs is a one-liner, and shelling out keeps the behaviour identical to what
//! the operator sees when they inspect a run by hand.
use std::path::{Path, PathBuf};
use std::process::Stdio;

use crate::proc::Quiet as _;
use anyhow::{Context as _, Result, bail};
use tokio::process::Command;

/// Output of a completed `git` invocation.
#[derive(Debug)]
pub struct GitOut {
    /// Exit status code, if the process was not killed by a signal.
    pub code: Option<i32>,
    /// Captured stdout, trailing newline trimmed.
    pub stdout: String,
    /// Captured stderr, trailing newline trimmed.
    pub stderr: String,
}

impl GitOut {
    /// Did the command succeed?
    pub fn ok(&self) -> bool {
        self.code == Some(0)
    }
}

/// Run `git` in `cwd` with `args`, returning the captured output regardless of
/// exit status.
pub async fn git_raw(cwd: &Path, args: &[&str]) -> Result<GitOut> {
    let out = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .quiet()
        // A hook that opens an editor or a credential prompt would hang a
        // headless run forever.
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_EDITOR", "true")
        .stdin(Stdio::null())
        .output()
        .await
        .with_context(|| format!("spawn git {}", args.join(" ")))?;
    Ok(GitOut {
        code: out.status.code(),
        stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
        stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
    })
}

/// Run `git`, failing on a non-zero exit status.
pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
    let out = git_raw(cwd, args).await?;
    if !out.ok() {
        bail!(
            "git {} failed in {} (exit {:?}): {}",
            args.join(" "),
            cwd.display(),
            out.code,
            if out.stderr.is_empty() {
                out.stdout.as_str()
            } else {
                out.stderr.as_str()
            }
        );
    }
    Ok(out.stdout)
}

/// Absolute path to the top level of the working tree containing `path`.
pub async fn toplevel(path: &Path) -> Result<PathBuf> {
    let out = git(path, &["rev-parse", "--show-toplevel"]).await?;
    Ok(PathBuf::from(out))
}

/// Resolve a revision to a full object id.
pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
    git(repo, &["rev-parse", rev]).await
}

/// Currently checked-out branch, or `None` when detached.
pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
    let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
    Ok(if out.ok() && !out.stdout.is_empty() {
        Some(out.stdout)
    } else {
        None
    })
}

/// Is the working tree free of tracked modifications and untracked files?
pub async fn is_clean(repo: &Path) -> Result<bool> {
    Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
}

/// `git status --porcelain`, for reporting what is dirty.
pub async fn status_porcelain(repo: &Path) -> Result<String> {
    git(repo, &["status", "--porcelain"]).await
}

/// Create a worktree at `path` with a fresh branch `branch` starting at `base`.
pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        tokio::fs::create_dir_all(parent).await.ok();
    }
    let path_s = path.to_string_lossy().to_string();
    git(repo, &["worktree", "add", "-b", branch, &path_s, base])
        .await
        .map(|_| ())
}

/// Create a worktree at `path` with a detached HEAD at `rev`.
pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        tokio::fs::create_dir_all(parent).await.ok();
    }
    let path_s = path.to_string_lossy().to_string();
    git(repo, &["worktree", "add", "--detach", &path_s, rev])
        .await
        .map(|_| ())
}

/// Move an existing detached worktree to `rev`, discarding local state.
pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
    git(worktree, &["checkout", "--detach", rev]).await?;
    git(worktree, &["reset", "--hard", rev]).await?;
    git(worktree, &["clean", "-fdx"]).await?;
    Ok(())
}

/// Remove a worktree. Returns `Ok(false)` when git refused (e.g. the path is
/// already gone), so callers can keep folding the rest of a run.
pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
    let path_s = path.to_string_lossy().to_string();
    let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
    if out.ok() {
        return Ok(true);
    }
    // A worktree whose directory was deleted by hand only needs pruning.
    git_raw(repo, &["worktree", "prune"]).await?;
    Ok(false)
}

/// Unregister a linked worktree whose directory is about to be deleted by
/// hand, so the path can be `worktree add`-ed again.
///
/// A linked worktree's `.git` is a file whose `gitdir:` line names the
/// bookkeeping entry inside its repository's admin directory; pruning from
/// there removes the registration without touching the directory. No-op when
/// `dir` is not a registered worktree (`.git` missing or not a `gitdir:`
/// link): nothing was registered, nothing survives removal.
pub async fn remove_worktree_from_linked(dir: &Path) {
    let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
        return;
    };
    let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
        return;
    };
    // `<repo>/.git/worktrees/<name>`, so the repository's git dir is two
    // levels up from here.
    let admin = Path::new(admin);
    let Some(common) = admin.parent().and_then(Path::parent) else {
        return;
    };
    let common_s = common.to_string_lossy();
    let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
}

/// Drop registrations for worktrees whose directory is already gone.
///
/// `git worktree remove` already does this for the path it just removed, but
/// a directory deleted by hand - [`crate::clean::fold_orphaned_worktrees`], or
/// an operator's own `rm -rf` - leaves the registration behind, and a
/// registered path refuses a fresh `worktree add` until something prunes it.
/// The operator's own machine had 31 such registrations sitting in one
/// repository, all of them for directories that no longer existed.
pub async fn worktree_prune(repo: &Path) -> Result<()> {
    git(repo, &["worktree", "prune"]).await.map(|_| ())
}

/// Delete a branch, ignoring "not found".
pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
    Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
}

/// Does `branch` exist?
pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
    let refname = format!("refs/heads/{branch}");
    Ok(
        git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
            .await?
            .ok(),
    )
}

/// Patch of `head` against the merge base with `base`.
pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
    let range = format!("{base}...{head}");
    git(
        worktree,
        &["diff", "--no-color", "--no-ext-diff", "-M", &range],
    )
    .await
}

/// `--stat` summary of `base...head`.
pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
    let range = format!("{base}...{head}");
    git(worktree, &["diff", "--no-color", "--stat", &range]).await
}

/// Number of files touched by `base...head`.
pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
    let range = format!("{base}...{head}");
    let out = git(worktree, &["diff", "--name-only", &range]).await?;
    Ok(out.lines().map(str::to_owned).collect())
}

/// One-line log of `base..head`, oldest first.
pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
    let range = format!("{base}..{head}");
    git(
        worktree,
        &["log", "--reverse", "--format=%s%n%b%n--", &range],
    )
    .await
}

/// How many commits `head` is ahead of `base`.
pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
    let range = format!("{base}..{head}");
    let out = git(worktree, &["rev-list", "--count", &range]).await?;
    Ok(out.trim().parse().unwrap_or(0))
}

/// Stage everything and commit under a neutral identity.
///
/// Used to rescue an agent that edited files but never committed: without this
/// its candidate would silently be empty. The neutral identity is part of the
/// blindness contract — a real `user.name` in a candidate's history would name
/// the operator, and an agent-configured one would name the vendor.
pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
        return Ok(false);
    }
    git(worktree, &["add", "-A"]).await?;
    let out = git_raw(
        worktree,
        &[
            "-c",
            "user.name=magi candidate",
            "-c",
            "user.email=magi@localhost",
            "commit",
            "--no-verify",
            "-m",
            message,
        ],
    )
    .await?;
    if !out.ok() {
        bail!("rescue commit failed: {}", out.stderr);
    }
    Ok(true)
}

/// Enable `extensions.worktreeConfig` if it is not already on.
///
/// Returns `true` when magi turned it on, so the caller can turn it back off
/// during cleanup and leave the repo exactly as it found it.
pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
    let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
    if out.ok() && out.stdout.trim() == "true" {
        return Ok(false);
    }
    git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
    Ok(true)
}

/// Undo [`enable_worktree_config`].
pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
    git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
    Ok(())
}

/// How many runs currently want `extensions.worktreeConfig` on for one
/// repository, and whether magi is the one that turned it on.
struct WorktreeConfigRef {
    /// Runs holding a reference, via [`acquire_worktree_config`].
    count: usize,
    /// Did *this process* flip the setting from off to on? If not - it was
    /// already `true` when the first run in this process asked - nothing
    /// here ever turns it off either; that is what [`enable_worktree_config`]
    /// already decided for the single-run case, and the ref-counted version
    /// must not second-guess it.
    we_enabled: bool,
}

/// One entry per repository, each guarded by its own `tokio::sync::Mutex` so
/// that two repositories' acquisitions never wait on each other - only two
/// runs in the *same* repository do, which is the point.
///
/// A `std::sync::Mutex` guards the map itself, held only long enough to find
/// or insert an entry and clone its `Arc`, never across an `.await`.
static WORKTREE_CONFIG: std::sync::LazyLock<
    std::sync::Mutex<
        std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
    >,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));

/// The per-repository slot, creating it if this is the first run to ask.
fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
    let mut map = WORKTREE_CONFIG
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    map.entry(repo.to_path_buf())
        .or_insert_with(|| {
            std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
                count: 0,
                we_enabled: false,
            }))
        })
        .clone()
}

/// Take a reference on `extensions.worktreeConfig` being on for `repo`.
///
/// [`enable_worktree_config`] alone is only safe for one run in a repository
/// at a time: it is a plain get-then-set, so a second run's "already true?"
/// check can see the first run's write and conclude it owns nothing to turn
/// back off, while the first run's own cleanup turns the setting off under
/// the second run's feet the moment *it* finishes - the exact race that let a
/// finished run's fold disable the hook a still-running sibling in the same
/// repository depended on. This ref-counts instead: the setting is turned on
/// once, by whichever caller is first, and turned off only once every caller
/// has released it via [`release_worktree_config`].
///
/// The per-repository lock is held across the `git config` call for the
/// first acquire, so a second, concurrent acquire for the same repository
/// waits for it rather than racing it - without that, both could observe
/// "not yet counted" and both try to flip the setting on.
pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
    let slot = worktree_config_slot(repo);
    let mut entry = slot.lock().await;
    entry.count += 1;
    if entry.count == 1 {
        entry.we_enabled = enable_worktree_config(repo).await?;
    }
    Ok(())
}

/// Release a reference taken by [`acquire_worktree_config`].
///
/// Only the last release for a repository actually calls
/// [`disable_worktree_config`], and only when this process was the one that
/// turned the setting on in the first place.
pub async fn release_worktree_config(repo: &Path) -> Result<()> {
    let slot = worktree_config_slot(repo);
    let mut entry = slot.lock().await;
    entry.count = entry.count.saturating_sub(1);
    if entry.count == 0 && entry.we_enabled {
        disable_worktree_config(repo).await?;
        entry.we_enabled = false;
    }
    Ok(())
}

/// Point a single worktree at its own hooks directory.
///
/// `core.hooksPath` is normally repo-wide; scoping it with `--worktree` keeps
/// the operator's own hooks untouched in the primary worktree, and the setting
/// disappears together with the worktree.
pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
    let dir = hooks_dir.to_string_lossy().replace('\\', "/");
    git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
        .await
        .map(|_| ())
}

/// Exclude a path from a worktree's status without touching `.gitignore`.
pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
    let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
    let path = worktree.join(git_dir);
    if let Some(parent) = path.parent() {
        tokio::fs::create_dir_all(parent).await.ok();
    }
    let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
    if body.lines().any(|l| l.trim() == pattern) {
        return Ok(());
    }
    if !body.is_empty() && !body.ends_with('\n') {
        body.push('\n');
    }
    body.push_str(pattern);
    body.push('\n');
    tokio::fs::write(&path, body)
        .await
        .with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

/// `git merge --no-ff` of `branch` into the currently checked-out branch.
///
/// One of three ways to land a branch driven by [`crate::config::MergeStyle`]
/// — see [`merge_squash`] and [`merge_ff_only`] for the other two, and that
/// enum's own doc for why the choice between them lives in configuration.
pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
    git_raw(
        repo,
        &["merge", "--no-ff", "--no-edit", "-m", message, branch],
    )
    .await
}

/// `git merge --squash` of `branch`, followed by a commit under `message`.
///
/// Two `git` calls because `--squash` only stages the result — unlike
/// [`merge_no_ff`] there is no merge commit for `--no-edit` to write, and
/// skipping the second call is exactly the trap `land`'s module doc warns
/// about: a squash that inherits `branch`'s own single-commit subject
/// (`magi: candidate A (uncommitted work)`) instead of `message`. Returns the
/// `--squash` step's own output, unrun `commit` included, when staging itself
/// fails (a conflict), so a caller sees what actually went wrong rather than
/// a `git commit` complaint about nothing being staged.
pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
    let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
    if !staged.ok() {
        return Ok(staged);
    }
    git_raw(repo, &["commit", "-m", message]).await
}

/// Fast-forward `branch` into the currently checked-out branch, refusing to
/// create a merge commit.
///
/// Only ever fast-forwards because the winner was already rebased onto the
/// tracked base tip before this runs (`Runner::sync_to_base`); at that point
/// `--ff-only` is indistinguishable from GitHub's "rebase and merge" button.
/// If the base moved again in the meantime this fails rather than falling
/// back to a real rebase, the same way `merge_no_ff` fails rather than
/// resolving a conflict — landing is not the place to improvise.
pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
    git_raw(repo, &["merge", "--ff-only", branch]).await
}

/// Push a branch to `remote`.
pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
    git_raw(repo, &["push", "-u", remote, branch]).await
}

/// Force-push a branch that has been rewritten, refusing to clobber work
/// pushed since this side last looked.
///
/// `--force-with-lease` rather than `--force`: a rebase replaces the branch's
/// commits, so a plain push is rejected, but a blind force would also throw
/// away anything a person pushed to the same branch meanwhile. The lease
/// turns that case into a failure instead of a loss.
pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
    git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
}

/// Rebase a branch onto `onto`, inside a throwaway worktree.
///
/// A worktree of its own for two reasons. The repository magi runs in may be
/// jj-colocated, where git `HEAD` is detached and a rebase in the primary
/// tree would move it under the operator; and a rebase that hits a conflict
/// leaves state behind, which is far easier to discard with the whole
/// directory than to unpick in a tree somebody is using.
///
/// `Ok(None)` means it applied and the branch now points at the rebased
/// commits. `Ok(Some(why))` means it did not: the branch is untouched, and
/// the string is what git said - a person has to decide.
pub async fn rebase_branch_in_temp(
    repo: &Path,
    scratch: &Path,
    branch: &str,
    onto: &str,
) -> Result<Option<String>> {
    // Removed first so a leftover from an interrupted attempt cannot make
    // `worktree add` fail on a path that already exists.
    worktree_remove(repo, scratch).await.ok();
    git_raw(
        repo,
        &[
            "worktree",
            "add",
            "--force",
            &scratch.to_string_lossy(),
            branch,
        ],
    )
    .await?;

    let out = git_raw(scratch, &["rebase", onto]).await?;
    if out.ok() {
        worktree_remove(repo, scratch).await.ok();
        return Ok(None);
    }
    // Leave nothing half-rebased behind: abort, then drop the tree entirely.
    git_raw(scratch, &["rebase", "--abort"]).await.ok();
    let why = if out.stderr.trim().is_empty() {
        out.stdout.trim().to_owned()
    } else {
        out.stderr.trim().to_owned()
    };
    worktree_remove(repo, scratch).await.ok();
    Ok(Some(why))
}

/// Bring an *attached* worktree's index and files in line with wherever its
/// branch now points.
///
/// [`rebase_branch_in_temp`] moves a branch from a throwaway worktree on
/// purpose - the whole point is never touching the tree someone else has
/// checked out. But a worktree that already had that branch checked out
/// shares the same ref: its `HEAD` resolves to the new commit the moment the
/// rebase lands elsewhere, while its index and working directory keep
/// whatever the old commit put there until something says otherwise. Left
/// alone, the next `git status` there reads as the whole rebase turning up
/// as an unstaged diff, and the next commit would be staged against stale
/// content.
pub async fn sync_to_head(worktree: &Path) -> Result<()> {
    git(worktree, &["reset", "--hard", "HEAD"]).await?;
    git(worktree, &["clean", "-fdx"]).await?;
    Ok(())
}

/// Fetch one branch from `remote`, updating its remote-tracking ref.
///
/// The refspec is spelled out rather than left to `git fetch <remote>
/// <branch>`, which writes `FETCH_HEAD` and updates
/// `refs/remotes/<remote>/<branch>` only as a side effect of the remote's
/// configured refspec. Naming the destination makes the thing this function
/// exists for - a tracking ref that moved - the operation rather than a
/// consequence of configuration magi does not own.
///
/// Honest note: a CI failure was first read as proof that some git versions do
/// not update the tracking ref here. That was wrong - the fetch had nothing to
/// update because the test had pushed to the wrong branch - so this is
/// determinism, not a fix for a demonstrated portability bug.
///
/// Refs, not the working copy: nothing is checked out and no local branch
/// moves, so this is safe to run while the operator has uncommitted work.
/// Returned as a [`GitOut`] rather than an error so the caller can decide - a
/// machine with no network must still be able to start a run.
pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
    git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
}

/// Does this ref resolve?
pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
    git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
        .await
        .is_ok_and(|o| o.ok())
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn scratch() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join("repo");
        tokio::fs::create_dir_all(&repo).await.unwrap();
        git(&repo, &["init", "-b", "main"]).await.unwrap();
        git(&repo, &["config", "user.name", "test"]).await.unwrap();
        git(&repo, &["config", "user.email", "test@example.com"])
            .await
            .unwrap();
        tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "init"]).await.unwrap();
        (dir, repo)
    }

    #[tokio::test]
    async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
        let (_g, repo) = scratch().await;

        // A side branch touching a different file: rebases cleanly.
        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
        tokio::fs::write(repo.join("b.txt"), "side\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "side work"]).await.unwrap();

        // main moves under it, which is what a repository merging other
        // pull requests does to a competition that took two hours.
        git(&repo, &["checkout", "main"]).await.unwrap();
        tokio::fs::write(repo.join("c.txt"), "main\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();

        let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
            .await
            .unwrap();
        assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
        assert_eq!(
            commits_ahead(&repo, "main", "side").await.unwrap(),
            1,
            "one commit, replayed onto the new base"
        );
        assert!(
            !scratch_tree.exists(),
            "the throwaway worktree is not left behind"
        );

        // A real conflict: both sides edit the same line.
        git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
        tokio::fs::write(repo.join("a.txt"), "clash\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "clash"]).await.unwrap();
        git(&repo, &["checkout", "main"]).await.unwrap();
        tokio::fs::write(repo.join("a.txt"), "main edit\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "main edit"]).await.unwrap();

        let before = rev_parse(&repo, "clash").await.unwrap();
        let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
            .await
            .unwrap()
            .expect("a same-line clash cannot be rebased silently");
        assert!(
            why.to_lowercase().contains("conflict"),
            "the reason is what git said, which is what a person needs: {why}"
        );
        assert_eq!(
            rev_parse(&repo, "clash").await.unwrap(),
            before,
            "a failed rebase leaves the branch exactly where it was"
        );
        assert!(!scratch_tree.exists(), "and cleans up after itself");
    }

    #[tokio::test]
    async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
        let (_g, repo) = scratch().await;
        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
        for name in ["b.txt", "c.txt"] {
            tokio::fs::write(repo.join(name), "side\n").await.unwrap();
            git(&repo, &["add", "-A"]).await.unwrap();
            git(
                &repo,
                &["commit", "-m", "magi: candidate A (uncommitted work)"],
            )
            .await
            .unwrap();
        }
        git(&repo, &["checkout", "main"]).await.unwrap();
        let before = rev_parse(&repo, "main").await.unwrap();

        let out = merge_squash(&repo, "side", "an explicit subject")
            .await
            .unwrap();
        assert!(out.ok(), "{}", out.stderr);
        assert_eq!(
            commits_ahead(&repo, &before, "main").await.unwrap(),
            1,
            "squash adds exactly one commit onto the tip, not one per candidate commit"
        );
        let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
        assert_eq!(
            subject, "an explicit subject",
            "the candidate's own placeholder subject must not survive: {subject}"
        );
    }

    #[tokio::test]
    async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
        let (_g, repo) = scratch().await;
        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
        tokio::fs::write(repo.join("b.txt"), "side\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
        git(&repo, &["checkout", "main"]).await.unwrap();

        let before = rev_parse(&repo, "side").await.unwrap();
        let out = merge_ff_only(&repo, "side").await.unwrap();
        assert!(out.ok(), "{}", out.stderr);
        assert_eq!(
            rev_parse(&repo, "main").await.unwrap(),
            before,
            "a fast-forward moves the base tip to the branch, no merge commit"
        );
    }

    #[tokio::test]
    async fn merge_ff_only_refuses_to_write_a_merge_commit() {
        let (_g, repo) = scratch().await;
        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
        tokio::fs::write(repo.join("b.txt"), "side\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "side work"]).await.unwrap();

        // main diverges, so a fast-forward is no longer possible.
        git(&repo, &["checkout", "main"]).await.unwrap();
        tokio::fs::write(repo.join("c.txt"), "main\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();

        let before = rev_parse(&repo, "main").await.unwrap();
        let out = merge_ff_only(&repo, "side").await.unwrap();
        assert!(!out.ok(), "a divergent branch cannot fast-forward");
        assert_eq!(
            rev_parse(&repo, "main").await.unwrap(),
            before,
            "a refused fast-forward must not touch main"
        );
    }

    #[tokio::test]
    async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
        let (guard, repo) = scratch().await;

        // An attached worktree of an existing branch - the shape a winner's
        // worktree keeps in `graph::Runner`, not the detached checkouts used
        // for judges and reviewers.
        git(&repo, &["branch", "side"]).await.unwrap();
        let side_wt = guard.path().join("side-wt");
        git(
            &repo,
            &["worktree", "add", &side_wt.to_string_lossy(), "side"],
        )
        .await
        .unwrap();
        tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
            .await
            .unwrap();
        git(&side_wt, &["add", "-A"]).await.unwrap();
        git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();

        // main moves under it.
        git(&repo, &["checkout", "main"]).await.unwrap();
        tokio::fs::write(repo.join("c.txt"), "main\n")
            .await
            .unwrap();
        git(&repo, &["add", "-A"]).await.unwrap();
        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();

        // Rebase from a throwaway worktree, never from `side_wt` itself.
        let scratch_tree = guard.path().join("rebase-scratch");
        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
            .await
            .unwrap();
        assert!(clean.is_none());

        // `HEAD` in the sibling worktree already resolves to the rebased
        // commit - the ref is shared - but nothing has told its index or its
        // files, which still hold the pre-rebase checkout.
        assert_eq!(
            rev_parse(&side_wt, "HEAD").await.unwrap(),
            rev_parse(&repo, "side").await.unwrap(),
            "HEAD follows the moved ref"
        );
        assert!(
            !side_wt.join("c.txt").exists(),
            "stale until synced: main's new file has not reached this worktree's disk"
        );

        sync_to_head(&side_wt).await.unwrap();
        assert!(side_wt.join("c.txt").is_file(), "synced now");
        assert!(
            side_wt.join("b.txt").is_file(),
            "the worktree's own committed work survives the sync"
        );
        assert!(is_clean(&side_wt).await.unwrap());
    }

    #[tokio::test]
    async fn clean_repo_reports_clean_then_dirty() {
        let (_g, repo) = scratch().await;
        assert!(is_clean(&repo).await.unwrap());
        tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
        assert!(!is_clean(&repo).await.unwrap());
    }

    #[tokio::test]
    async fn worktree_lifecycle_and_diff() {
        let (guard, repo) = scratch().await;
        let base = rev_parse(&repo, "HEAD").await.unwrap();
        let wt = guard.path().join("wt-a");
        worktree_add_branch(&repo, &wt, "magi/test/a", &base)
            .await
            .unwrap();
        tokio::fs::write(wt.join("b.txt"), "candidate\n")
            .await
            .unwrap();

        assert!(commit_all(&wt, "candidate work").await.unwrap());
        assert!(!commit_all(&wt, "nothing left").await.unwrap());

        assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
        let patch = diff(&wt, &base, "HEAD").await.unwrap();
        assert!(patch.contains("b.txt"), "patch was: {patch}");
        assert_eq!(
            changed_files(&wt, &base, "HEAD").await.unwrap(),
            ["b.txt".to_owned()]
        );

        // The rescue commit must not carry the operator's identity.
        let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
            .await
            .unwrap();
        assert_eq!(author, "magi candidate <magi@localhost>");

        assert!(worktree_remove(&repo, &wt).await.unwrap());
        assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
        assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
        assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
    }

    #[tokio::test]
    async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
        let (guard, repo) = scratch().await;
        let base = rev_parse(&repo, "HEAD").await.unwrap();
        let wt = guard.path().join("wt-h");
        worktree_add_branch(&repo, &wt, "magi/test/h", &base)
            .await
            .unwrap();
        let hooks = guard.path().join("hooks");
        tokio::fs::create_dir_all(&hooks).await.unwrap();

        assert!(enable_worktree_config(&repo).await.unwrap());
        set_worktree_hooks_path(&wt, &hooks).await.unwrap();

        let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
            .await
            .unwrap();
        assert!(!in_wt.is_empty());
        let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
            .await
            .unwrap();
        assert!(
            !in_primary.ok(),
            "primary worktree must keep its own hooks: {in_primary:?}"
        );

        disable_worktree_config(&repo).await.unwrap();
    }

    #[tokio::test]
    async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
        let (_g, repo) = scratch().await;

        // Two runs in the same repository, as `Config::daemon.max_concurrent_runs`
        // now allows: both acquire before either is done.
        acquire_worktree_config(&repo).await.unwrap();
        acquire_worktree_config(&repo).await.unwrap();

        let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
            .await
            .unwrap();
        assert_eq!(on, "true");

        // The first run to finish releases its own reference. A plain
        // `disable_worktree_config` here is exactly the bug: it would turn
        // the setting off while the second run still depends on it.
        release_worktree_config(&repo).await.unwrap();
        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
            .await
            .unwrap();
        assert_eq!(
            still_on, "true",
            "a sibling run's release must not disable the setting for the one still working"
        );

        // Only the last release actually turns it back off.
        release_worktree_config(&repo).await.unwrap();
        let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
            .await
            .unwrap();
        assert!(
            !after.ok(),
            "the last release must turn the setting back off: {after:?}"
        );
    }

    #[tokio::test]
    async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
        let (_g, repo) = scratch().await;
        git(&repo, &["config", "extensions.worktreeConfig", "true"])
            .await
            .unwrap();

        // magi did not turn this on, so even after every acquire is released,
        // it must not turn it off - that is what a bare `enable_worktree_config`
        // already promised for the single-run case, and the ref-counted
        // version must keep that promise.
        acquire_worktree_config(&repo).await.unwrap();
        release_worktree_config(&repo).await.unwrap();

        let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
            .await
            .unwrap();
        assert_eq!(still_on, "true");
    }

    #[tokio::test]
    async fn local_exclude_is_idempotent() {
        let (_g, repo) = scratch().await;
        local_exclude(&repo, "/.magi/").await.unwrap();
        local_exclude(&repo, "/.magi/").await.unwrap();
        let path = repo.join(".git/info/exclude");
        let body = tokio::fs::read_to_string(&path).await.unwrap();
        assert_eq!(body.matches("/.magi/").count(), 1);
    }
}