magi-cli 0.170.0

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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
//! Rebasing the winning branch onto a moved base, with a fixer for conflicts.
//!
//! Both `graph::Runner::sync_to_base` (before review) and `land::Step::Rebase`
//! (after the pull request exists) used to stop on a conflict and leave it to
//! a person. A conflict is often a chore - two `pub mod` lines on the same
//! spot - and what follows it (a rule the base gained meanwhile) is exactly
//! what the gate-fix round handles, so both callers now come through
//! [`rebase_with_fixer`], which hands the standing conflict to the fixer seat.
//!
//! The rules, none optional:
//!
//! - **magi resolves nothing itself.** No taking one side, no line merging:
//!   the agent decides. Everything here is scaffolding around that call.
//! - **The round is judged by what git says**, never by the fixer's report:
//!   the rebase is no longer in progress, nothing is unmerged, no conflict
//!   marker is left in a path that conflicted, and the base is an ancestor of
//!   the result (an agent that ran `git rebase --abort` leaves a tidy tree
//!   that contains no base at all). Whether the tree *builds* is left to the
//!   review and gate that follow, which already know how to fix a breakage.
//! - **The budget is `graph.review_rounds`, counted in
//!   `RunState::rebase_fixes`** and saved before the fixer is called, shared
//!   by both callers, so a park or a crash cannot hand a round back. It
//!   touches neither the task's attempts nor land's own rebase budget.
//! - **A failure restores the branch.** Whatever the fixer left, the branch
//!   ref goes back to where it was and the throwaway worktree is removed, so
//!   the fallback is exactly the old "conflict, a person decides".

use std::path::Path;
use std::time::Duration;

use anyhow::{Context as _, Result};
use jiff::Timestamp;

use crate::agent::{self, Invocation};
use crate::git;
use crate::land::seat_of;
use crate::prompt;
use crate::run::{QuotaLoss, RebaseFixRecord, RunState};

/// How [`rebase_with_fixer`] ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Rebased {
    /// The branch now sits on top of the base (rebased cleanly or resolved by
    /// the fixer); the throwaway worktree is gone.
    Applied,
    /// It did not apply. The branch is untouched, the worktree is gone, and
    /// the string says what was tried: rounds spent, paths still conflicted,
    /// and what git said.
    Stopped(String),
}

/// Longest conflict excerpt shown to the fixer, per file and in total.
const HUNK_PER_FILE: usize = 4_000;
const HUNK_TOTAL: usize = 16_000;
/// Commit subjects listed per side.
const SUBJECTS: usize = 20;
/// Paths named in a failure reason before "and N more".
const PATHS_IN_REASON: usize = 8;

/// Rebase `branch` onto `onto` in `scratch`, giving a conflict to the fixer.
///
/// Re-entrant: when `scratch` already holds a rebase in progress (a run that
/// died in the middle of a round) it carries on from there instead of
/// starting over, and the rounds already recorded still count.
pub async fn rebase_with_fixer(
    state: &mut RunState,
    scratch: &Path,
    branch: &str,
    onto: &str,
) -> Result<Rebased> {
    let repo = state.repo.clone();
    let cap = state.config.graph.review_rounds;
    let orig = git::rev_parse(&repo, &format!("refs/heads/{branch}")).await?;

    let mut said = String::new();
    if !git::rebase_in_progress(scratch).await {
        match git::rebase_start(&repo, scratch, branch, onto).await? {
            git::RebaseStart::Applied => return Ok(Rebased::Applied),
            git::RebaseStart::Failed(why) => return Ok(Rebased::Stopped(why)),
            git::RebaseStart::Conflicted(why) => said = why,
        }
    }
    let onto_sha = git::rev_parse(&repo, onto).await?;
    // Every path that was ever unmerged: the marker check on the finished
    // tree looks at exactly these.
    let mut touched: Vec<String> = Vec::new();

    loop {
        if !git::rebase_in_progress(scratch).await {
            return finish(state, scratch, branch, &orig, &onto_sha, &touched, &said).await;
        }
        let paths = git::unmerged_paths(scratch).await.unwrap_or_default();
        for p in &paths {
            if !touched.contains(p) {
                touched.push(p.clone());
            }
        }
        let spent = state.rebase_fixes.len();
        if spent >= cap {
            let why = reason(spent, cap, &paths, &said, "the rounds are spent");
            abandon(&repo, scratch, branch, &orig).await;
            return Ok(Rebased::Stopped(why));
        }

        let winner = state
            .winner()
            .cloned()
            .context("resolving a rebase conflict needs a winning candidate")?;
        let roles = state
            .config
            .resolve_roles()
            .context("resolve the roster for the rebase fix")?;
        // The chain (`crate::fixer`): one round however many agents it takes.
        let attempts = crate::fixer::attempts(state, &roles, &winner);
        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();

        let round = spent + 1;
        let branch_subjects = subjects(scratch, &format!("{onto}..{branch}")).await;
        let onto_subjects = subjects(scratch, &format!("{branch}..{onto}")).await;
        let hunks = hunks(scratch, &paths);
        let prompt_text = prompt::rebase_conflict(&prompt::RebaseConflict {
            instruction: &state.instruction,
            worktree: scratch,
            branch,
            onto,
            paths: &paths,
            branch_subjects: &branch_subjects,
            onto_subjects: &onto_subjects,
            hunks: &hunks,
            round,
            cap,
            language: &state.config.graph.language,
            github_language: &state.config.graph.github_language,
        });
        let prompt_text = if state.config.cache_dir().is_some() {
            format!("{prompt_text}\n\n{}", prompt::build_cache_note("fix", true))
        } else {
            prompt_text
        };

        // Spent before the call, on disk: a run killed mid-round must not
        // get the round back.
        state.rebase_fixes.push(RebaseFixRecord {
            agent: ids[0].clone(),
            paths: paths.clone(),
            from: Some(orig.clone()),
            finished: false,
            error: None,
        });
        state.event(
            "rebase",
            format!(
                "{branch} conflicts with {onto} ({} path(s)); fixer round {round} of {cap}",
                paths.len()
            ),
        );
        state.save()?;

        // Each id at most once, forward only. The round was spent and saved
        // above, so a chain advance inside it spends nothing further and a
        // crash cannot hand it back; only the record's `agent` follows the
        // asked agent (saved before its call, like the round itself).
        let artifacts = agent::artifacts_dir(&state.dir());
        let mut last = None;
        for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
            if i > 0 {
                if let Some(r) = state.rebase_fixes.last_mut() {
                    r.agent = spec.id.clone();
                }
                state.save()?;
            }
            let mut seat = seat_of(state, &seat_key, &spec.id);
            let stem = if i == 0 {
                format!("rebase-fix-{round}")
            } else {
                format!("rebase-fix-{round}-{}", spec.id)
            };
            let out = agent::invoke(
                &spec,
                &mut seat,
                &Invocation {
                    scope: crate::agent::InvocationScope::Repository,
                    coordination: state.config.coordination.as_ref(),
                    fetched_base: state.fetched_base.as_ref(),
                    cwd: scratch,
                    prompt: &prompt_text,
                    timeout: Duration::from_secs(state.config.graph.timeout_fix),
                    allow_write: true,
                    unsandboxed: false,
                    sessions: state.config.graph.sessions,
                    artifacts: &artifacts,
                    stem: &stem,
                    run: &state.id,
                    node: "rebase",
                    cache_dir: state.config.cache_dir().as_deref(),
                    attachments: &[],
                    writable: &[],
                },
            )
            .await;
            let seat_name = seat.key.clone();
            state.seats.insert(seat.key.clone(), seat);
            if let Some(next) = ids.get(i + 1)
                && agent::chain_advances(&out)
            {
                let (class, why) = crate::fixer::failure_of(&out);
                crate::graph::record_handover(
                    state, "rebase", &seat_name, &spec.id, next, &class, &why,
                );
                continue;
            }
            last = Some((out, seat_name));
            break;
        }
        let (out, seat_name) = last.expect("the fixer chain always has an entry");

        let mut error = None;
        let mut quota = false;
        match out {
            Ok(o) if o.quota_exhausted() => {
                state.quota.push(QuotaLoss {
                    seat: seat_name,
                    node: "rebase".to_owned(),
                    at: Timestamp::now(),
                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
                });
                error = Some("rate limited (quota); the fixer could not run".to_owned());
                quota = true;
            }
            Ok(o) if !o.usable() => {
                error = Some(format!(
                    "the fixer produced nothing usable ({})",
                    crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
                ));
            }
            Ok(_) => {}
            Err(e) => error = Some(format!("{e:#}")),
        }

        let finished = !git::rebase_in_progress(scratch).await;
        if let Some(r) = state.rebase_fixes.last_mut() {
            r.finished = finished;
            r.error = error.clone();
        }
        state.save()?;

        if quota {
            // A retry now fails the same way; do not burn the rest.
            let paths = git::unmerged_paths(scratch).await.unwrap_or_default();
            let why = reason(
                state.rebase_fixes.len(),
                cap,
                &paths,
                &said,
                "the fixer hit its rate limit",
            );
            abandon(&repo, scratch, branch, &orig).await;
            return Ok(Rebased::Stopped(why));
        }
    }
}

/// Judge a rebase that is no longer in progress by what git says.
async fn finish(
    state: &mut RunState,
    scratch: &Path,
    branch: &str,
    orig: &str,
    onto_sha: &str,
    touched: &[String],
    said: &str,
) -> Result<Rebased> {
    let repo = state.repo.clone();
    let spent = state.rebase_fixes.len();
    let cap = state.config.graph.review_rounds;
    let unmerged = git::unmerged_paths(scratch).await.unwrap_or_default();
    let head = git::rev_parse(scratch, "HEAD").await.unwrap_or_default();
    // Not only the paths seen unmerged at a round's start: one round may
    // continue through several commits, and a later commit's conflict never
    // shows up at a loop head. Everything the result changes relative to the
    // base is checked.
    let mut candidates: Vec<String> = touched.to_vec();
    if let Ok(changed) = git::git(scratch, &["diff", "--name-only", onto_sha, "HEAD"]).await {
        for p in changed.lines().map(str::trim).filter(|l| !l.is_empty()) {
            if !candidates.iter().any(|c| c == p) {
                candidates.push(p.to_owned());
            }
        }
    }
    let marked: Vec<String> = candidates
        .into_iter()
        .filter(|p| has_markers(scratch, p))
        .collect();

    // Skipping every conflicting commit leaves the branch equal to the base:
    // the ancestry test below passes and the branch's work is gone. Empty is
    // only acceptable when every original commit already has a patch twin on
    // the base.
    let emptied = head == onto_sha
        && git::cherry(&repo, onto_sha, orig)
            .await
            .map_or(true, |(unmatched, _)| !unmatched.is_empty());

    // A fixer that ran `git rebase --skip` on one of several commits lets the
    // rest apply and the rebase finish; `emptied` only sees the whole change
    // vanishing. Find the commits that are neither in the result nor already
    // on the base.
    let dropped = if unmerged.is_empty() && marked.is_empty() && !emptied && !head.is_empty() {
        dropped_commits(&repo, scratch, onto_sha, orig, &head).await
    } else {
        Ok(Vec::new())
    };

    let problem = if !unmerged.is_empty() {
        Some(("paths are still unmerged", unmerged))
    } else if !marked.is_empty() {
        Some(("conflict markers were left in the tree", marked))
    } else if emptied {
        Some((
            "the rebase ended with none of the branch's commits applied (all skipped)",
            touched.to_vec(),
        ))
    } else if head.is_empty() || !git::is_ancestor(&repo, onto_sha, &head).await {
        Some((
            "the rebase ended without the base in the result (abandoned or skipped)",
            touched.to_vec(),
        ))
    } else if let Err(error) = &dropped {
        Some((
            "the rebase record could not be verified",
            vec![format!("{error:#}")],
        ))
    } else if !dropped.as_ref().unwrap().is_empty() {
        Some((
            "the rebase dropped some of the branch's commits (skipped?)",
            dropped.unwrap(),
        ))
    } else {
        None
    };
    match problem {
        None => {
            git::worktree_remove(&repo, scratch).await.ok();
            state.event(
                "rebase",
                format!("{branch} rebased after {spent} fixer round(s)"),
            );
            state.save()?;
            Ok(Rebased::Applied)
        }
        Some((what, paths)) => {
            let why = reason(spent, cap, &paths, said, what);
            abandon(&repo, scratch, branch, orig).await;
            Ok(Rebased::Stopped(why))
        }
    }
}

/// Only a pick whose exec observed the previous HEAD could have been skipped.
/// Content checks distinguish a genuine loss from a change already upstream.
async fn dropped_commits(
    repo: &Path,
    scratch: &Path,
    onto_sha: &str,
    orig: &str,
    head: &str,
) -> Result<Vec<String>> {
    let record = git::rebase_record(scratch).await?;
    anyhow::ensure!(
        record.heads.last().map(String::as_str) == Some(head),
        "rebase final HEAD disagrees with record"
    );
    let mut previous = onto_sha;
    let mut lost = Vec::new();
    for (sha, picked_head) in record.picks.iter().zip(&record.heads) {
        if picked_head == previous
            && !absorbed_in_result(repo, sha, onto_sha, orig, head).await?
            && !already_in_result(repo, sha, orig, head).await?
        {
            lost.push(git::git(repo, &["show", "-s", "--format=%s", sha]).await?);
        }
        previous = picked_head;
    }
    Ok(lost)
}

/// Paths `sha` changes, NUL-separated from git so a quoted name is never
/// misread. Read failures propagate to the rebase verdict.
async fn commit_paths(repo: &Path, sha: &str) -> Result<Vec<String>> {
    git::git(
        repo,
        &[
            "diff-tree",
            "--no-commit-id",
            "--name-only",
            "-r",
            "--root",
            "-z",
            sha,
        ],
    )
    .await
    .map(|o| {
        o.split('\0')
            .filter(|l| !l.is_empty())
            .map(str::to_owned)
            .collect()
    })
}

/// `mode type blob` of `path` at `rev`, or `None` when it does not exist
/// there. Unlike `rev-parse rev:path` this carries the file mode.
async fn entry(repo: &Path, rev: &str, path: &str) -> Result<Option<String>> {
    let out = git::git(repo, &["--literal-pathspecs", "ls-tree", rev, "--", path]).await?;
    Ok(out
        .split('\t')
        .next()
        .filter(|e| !e.is_empty())
        .map(str::to_owned))
}

/// Is `sha`'s change represented in `head`?
///
/// First by merging: replaying `sha` onto `head` changes nothing when its
/// change is already there, in whatever company (extra upstream edits in the
/// same file included). Failing that, per touched path: `head` holds what
/// `sha` left there, or what the branch's final tip `orig` has there (a later
/// commit may have changed the path again). Mode is part of that comparison,
/// and paths come NUL-separated so a quoted name is never misread.
async fn already_in_result(repo: &Path, sha: &str, orig: &str, head: &str) -> Result<bool> {
    if replay_is_noop(repo, sha, head).await? {
        return Ok(true);
    }
    for p in &commit_paths(repo, sha).await? {
        let got = entry(repo, head, p).await?;
        if got != entry(repo, sha, p).await? && got != entry(repo, orig, p).await? {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Does merging `sha` (against its parent) into `head` cleanly yield `head`'s
/// own tree? Conflicts and changes return false; read failures propagate.
async fn replay_is_noop(repo: &Path, sha: &str, head: &str) -> Result<bool> {
    let base = format!("{sha}^");
    let out = git::git_raw(
        repo,
        &[
            "merge-tree",
            "--write-tree",
            &format!("--merge-base={base}"),
            head,
            sha,
        ],
    )
    .await?;
    anyhow::ensure!(
        out.code == Some(0) || out.code == Some(1),
        "merge-tree failed: {}",
        out.stderr
    );
    if !out.ok() {
        return Ok(false);
    }
    let merged = out
        .stdout
        .lines()
        .next()
        .context("merge-tree returned no tree")?
        .trim();
    Ok(merged == git::tree_of(repo, head).await?)
}

/// An absorbed change may be superseded by later branch commits, so replaying
/// it alone onto the result can conflict. Starting at `sha`, merge only those
/// later changes with the base and require every path `sha` touched to match
/// the result (including modes). Project all four trees onto just those paths
/// first: conflicts elsewhere cannot invalidate this commit's surviving effect.
/// A conflict on a candidate path or a failed lookup is not evidence of survival.
async fn absorbed_in_result(
    repo: &Path,
    sha: &str,
    onto: &str,
    orig: &str,
    head: &str,
) -> Result<bool> {
    if !replay_is_noop(repo, sha, onto).await? {
        return Ok(false);
    }
    let paths = commit_paths(repo, sha).await?;
    if paths.is_empty() {
        return Ok(false);
    }
    let base = path_tree(repo, sha, &paths).await?;
    let upstream = path_tree(repo, onto, &paths).await?;
    let branch = path_tree(repo, orig, &paths).await?;
    let result = path_tree(repo, head, &paths).await?;
    let out = git::git_raw(
        repo,
        &[
            "merge-tree",
            "--write-tree",
            &format!("--merge-base={base}"),
            &upstream,
            &branch,
        ],
    )
    .await?;
    anyhow::ensure!(
        out.code == Some(0) || out.code == Some(1),
        "merge-tree failed: {}",
        out.stderr
    );
    if !out.ok() {
        return Ok(false);
    }
    Ok(out
        .stdout
        .lines()
        .next()
        .context("merge-tree returned no tree")?
        == result)
}

/// A tree containing only the candidate paths, under stable synthetic names.
/// Preserve each entry's object and mode, and leave missing entries absent.
/// Flattening the names lets mktree handle nested and unusual paths without
/// an index or a working tree, and keeps unrelated paths out of the merge.
async fn path_tree(repo: &Path, rev: &str, paths: &[String]) -> Result<String> {
    use crate::proc::Quiet as _;
    use std::fmt::Write as _;
    use std::process::Stdio;
    use tokio::io::AsyncWriteExt as _;

    let mut entries = String::new();
    for (i, path) in paths.iter().enumerate() {
        let out = git::git(
            repo,
            &["--literal-pathspecs", "ls-tree", "-z", rev, "--", path],
        )
        .await?;
        if !out.is_empty() {
            let (entry, _) = out
                .split_once('\t')
                .context("ls-tree returned an invalid entry")?;
            writeln!(entries, "{entry}\t{i:016x}")?;
        }
    }
    #[cfg(test)]
    crate::web::request_cost::git();
    let mut child = tokio::process::Command::new("git")
        .args(["mktree"])
        .current_dir(repo)
        .quiet()
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .spawn()?;
    let mut stdin = child.stdin.take().context("mktree stdin missing")?;
    stdin.write_all(entries.as_bytes()).await?;
    drop(stdin);
    let out = child.wait_with_output().await?;
    anyhow::ensure!(
        out.status.success(),
        "mktree failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    Ok(String::from_utf8(out.stdout)?.trim().to_owned())
}

/// Give up: abort whatever is standing, drop the worktree and put the branch
/// ref back where it was, whatever a fixer did to it.
async fn abandon(repo: &Path, scratch: &Path, branch: &str, orig: &str) {
    git::rebase_abort(repo, scratch).await;
    let full = format!("refs/heads/{branch}");
    if git::rev_parse(repo, &full).await.ok().as_deref() != Some(orig) {
        git::git_raw(repo, &["update-ref", &full, orig]).await.ok();
    }
}

/// The reason a caller records and the conductor quotes: it says what was
/// tried, so nobody has to open the run directory to find out.
fn reason(spent: usize, cap: usize, paths: &[String], said: &str, what: &str) -> String {
    let shown: Vec<&str> = paths
        .iter()
        .take(PATHS_IN_REASON)
        .map(String::as_str)
        .collect();
    let mut list = shown.join(", ");
    if paths.len() > shown.len() {
        list.push_str(&format!(" and {} more", paths.len() - shown.len()));
    }
    if list.is_empty() {
        list.push_str("none recorded");
    }
    let mut s = format!(
        "conflict not resolved after {spent} of {cap} fixer round(s) ({what}); remaining \
         conflicted path(s): {list}"
    );
    let said = git::rebase_said(said);
    let said = said.trim();
    if !said.is_empty() {
        s.push_str("; git said: ");
        s.extend(said.chars().take(250));
    }
    s
}

/// Commit subjects in `range`, newest first, capped.
async fn subjects(worktree: &Path, range: &str) -> Vec<String> {
    let n = format!("-n{SUBJECTS}");
    git::git(worktree, &["log", "--format=%s", &n, range])
        .await
        .map(|o| o.lines().map(str::to_owned).collect())
        .unwrap_or_default()
}

fn has_markers(worktree: &Path, path: &str) -> bool {
    std::fs::read_to_string(worktree.join(path)).is_ok_and(|t| {
        t.lines().any(|l| l.starts_with("<<<<<<< ")) && t.lines().any(|l| l.starts_with(">>>>>>> "))
    })
}

/// The conflicted regions of `paths`, marker lines included, truncated. This
/// only *shows* the conflict; nothing here decides how to resolve it.
fn hunks(worktree: &Path, paths: &[String]) -> String {
    let mut out = String::new();
    for p in paths {
        if out.len() >= HUNK_TOTAL {
            out.push_str("\n(more conflicted files omitted)\n");
            break;
        }
        out.push_str(&format!("=== {p} ===\n"));
        let Ok(text) = std::fs::read_to_string(worktree.join(p)) else {
            out.push_str("(not readable as text; use git to inspect it)\n");
            continue;
        };
        let mut file = String::new();
        let mut inside = false;
        for line in text.lines() {
            if line.starts_with("<<<<<<< ") {
                inside = true;
            }
            if inside {
                file.push_str(line);
                file.push('\n');
            }
            if line.starts_with(">>>>>>> ") {
                inside = false;
            }
        }
        if file.len() > HUNK_PER_FILE {
            file = file.chars().take(HUNK_PER_FILE).collect();
            file.push_str("\n(truncated)\n");
        }
        out.push_str(&file);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proc::Quiet as _;

    fn sh(dir: &Path, args: &[&str]) {
        let o = std::process::Command::new("git")
            .quiet()
            .args(args)
            .current_dir(dir)
            .output()
            .unwrap();
        assert!(
            o.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&o.stderr)
        );
    }

    async fn record(d: &Path, picks: &[String], heads: &[String]) {
        for (name, values) in [("magi-rebase-picks", picks), ("magi-rebase-heads", heads)] {
            let path = git::git(d, &["rev-parse", "--git-path", name])
                .await
                .unwrap();
            std::fs::write(d.join(path), values.join("\n") + "\n").unwrap();
        }
    }

    #[tokio::test]
    async fn a_lost_mode_change_is_not_already_in_the_result() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        sh(d, &["config", "core.fileMode", "true"]);
        std::fs::write(d.join("script.sh"), "echo\n").unwrap();
        sh(d, &["add", "-A"]);
        sh(d, &["commit", "-q", "-m", "base"]);
        sh(d, &["update-index", "--chmod=+x", "script.sh"]);
        sh(d, &["commit", "-q", "-m", "chmod"]);
        let sha = git::git(d, &["rev-parse", "HEAD"]).await.unwrap();
        let base = git::git(d, &["rev-parse", "HEAD~1"]).await.unwrap();
        // The result is the base: same blob, lost mode.
        assert!(!already_in_result(d, &sha, &sha, &base).await.unwrap());
        assert!(already_in_result(d, &sha, &sha, &sha).await.unwrap());
    }

    async fn commit(d: &Path, msg: &str) -> String {
        sh(d, &["add", "-A"]);
        sh(d, &["commit", "-q", "-m", msg]);
        git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
    }

    #[tokio::test]
    async fn candidate_path_trees_preserve_modes_deletions_and_unusual_names() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        sh(d, &["config", "core.fileMode", "true"]);
        let path = if cfg!(windows) {
            "nested/日本語 [literal].txt"
        } else {
            "nested/日本語\tline\n.txt"
        };
        std::fs::create_dir(d.join("nested")).unwrap();
        std::fs::write(d.join(path), "contents\n").unwrap();
        std::fs::write(d.join("g.txt"), "old\n").unwrap();
        let base = commit(d, "base").await;
        let paths = vec![path.to_owned()];
        let tree = path_tree(d, &base, &paths).await.unwrap();
        std::fs::write(d.join("g.txt"), "unrelated\n").unwrap();
        let other = commit(d, "unrelated path").await;
        assert_eq!(path_tree(d, &other, &paths).await.unwrap(), tree);
        sh(d, &["update-index", "--chmod=+x", path]);
        sh(d, &["commit", "-q", "-m", "chmod"]);
        assert_ne!(path_tree(d, "HEAD", &paths).await.unwrap(), tree);
        std::fs::remove_file(d.join(path)).unwrap();
        let removed = commit(d, "delete").await;
        let absent = path_tree(d, &removed, &paths).await.unwrap();
        assert_ne!(absent, tree);
        assert_eq!(absent, path_tree(d, &removed, &[]).await.unwrap());
        assert!(path_tree(d, "not-a-revision", &paths).await.is_err());
    }

    #[tokio::test]
    async fn a_change_inside_a_larger_upstream_edit_is_in_the_result() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
        std::fs::write(d.join("f.txt"), body).unwrap();
        commit(d, "base").await;
        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
        let c = commit(d, "c1").await;
        sh(d, &["checkout", "-q", "-b", "up", "HEAD~1"]);
        let up = body.replacen("old", "new", 1).replace("end", "end plus");
        std::fs::write(d.join("f.txt"), up).unwrap();
        let head = commit(d, "upstream").await;
        assert!(already_in_result(d, &c, &c, &head).await.unwrap());
    }

    #[tokio::test]
    async fn a_dropped_commit_on_a_non_ascii_path_is_still_noticed() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        std::fs::write(d.join("a.txt"), "a\n").unwrap();
        let base = commit(d, "base").await;
        std::fs::write(d.join("日本語.txt"), "x\n").unwrap();
        let c = commit(d, "c").await;
        assert!(!already_in_result(d, &c, &c, &base).await.unwrap());
    }

    async fn commit_dated(d: &Path, msg: &str) -> String {
        sh(d, &["add", "-A"]);
        let st = std::process::Command::new("git")
            .quiet()
            .current_dir(d)
            .env("GIT_AUTHOR_DATE", "2020-01-01T00:00:00+0000")
            .env("GIT_COMMITTER_DATE", "2020-01-01T00:00:00+0000")
            .args(["commit", "-q", "-m", msg])
            .status()
            .unwrap();
        assert!(st.success());
        git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
    }

    #[tokio::test]
    async fn a_recorded_resolved_pick_after_an_absorbed_one_is_not_lost() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        std::fs::write(d.join("z.txt"), "z\n").unwrap();
        let base = commit(d, "base").await;
        std::fs::write(d.join("a.txt"), "a\n").unwrap();
        commit_dated(d, "same").await;
        std::fs::write(d.join("b.txt"), "b\n").unwrap();
        let orig = commit_dated(d, "same").await;
        // Upstream folds the first change into a differently-shaped commit
        // and adds a conflicting b.txt.
        sh(d, &["checkout", "-q", "-b", "up", &base]);
        std::fs::write(d.join("a.txt"), "a\n").unwrap();
        std::fs::write(d.join("y.txt"), "y\n").unwrap();
        std::fs::write(d.join("b.txt"), "other\n").unwrap();
        let onto = commit(d, "upstream").await;
        // The rebase result: first commit omitted as empty, second resolved.
        std::fs::write(d.join("b.txt"), "other\nb\n").unwrap();
        let head = commit_dated(d, "same").await;
        record(
            d,
            &[
                git::rev_parse(d, &format!("{orig}^")).await.unwrap(),
                orig.clone(),
            ],
            &[onto.clone(), head.clone()],
        )
        .await;
        assert!(
            dropped_commits(d, d, &onto, &orig, &head)
                .await
                .unwrap()
                .is_empty()
        );
    }

    #[tokio::test]
    async fn a_skipped_commit_is_not_masked_by_a_surviving_one_in_the_same_file() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        let body = "first\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
        std::fs::write(d.join("f.txt"), body).unwrap();
        let base = commit(d, "base").await;
        std::fs::write(d.join("f.txt"), body.replacen("first", "mine", 1)).unwrap();
        commit_dated(d, "same").await;
        let two = body
            .replacen("first", "mine", 1)
            .replacen("last", "tail", 1);
        std::fs::write(d.join("f.txt"), &two).unwrap();
        let orig = commit_dated(d, "same").await;
        sh(d, &["checkout", "-q", "-b", "up", &base]);
        std::fs::write(d.join("f.txt"), body.replacen("first", "theirs", 1)).unwrap();
        let onto = commit(d, "upstream").await;
        // First commit skipped, second applied untouched.
        std::fs::write(
            d.join("f.txt"),
            body.replacen("first", "theirs", 1)
                .replacen("last", "tail", 1),
        )
        .unwrap();
        let head = commit_dated(d, "same").await;
        record(
            d,
            &[
                git::rev_parse(d, &format!("{orig}^")).await.unwrap(),
                orig.clone(),
            ],
            &[onto.clone(), head.clone()],
        )
        .await;
        assert_eq!(
            dropped_commits(d, d, &onto, &orig, &head).await.unwrap(),
            vec!["same"]
        );
    }

    #[tokio::test]
    async fn git_records_a_skipped_middle_pick_after_an_applied_pick() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        std::fs::write(d.join("f"), "base\n").unwrap();
        let base = commit(d, "base").await;
        sh(d, &["checkout", "-q", "-b", "topic"]);
        std::fs::write(d.join("absorbed"), "upstream too\n").unwrap();
        commit(d, "already upstream").await;
        std::fs::write(d.join("a"), "first\n").unwrap();
        let first = commit(d, "first").await;
        std::fs::write(d.join("f"), "middle\n").unwrap();
        let middle = commit(d, "lost middle").await;
        std::fs::write(d.join("z"), "last\n").unwrap();
        let orig = commit(d, "last").await;
        sh(d, &["checkout", "-q", "main"]);
        std::fs::write(d.join("absorbed"), "upstream too\n").unwrap();
        commit(d, "patch twin").await;
        std::fs::write(d.join("f"), "upstream\n").unwrap();
        let onto = commit(d, "upstream").await;
        let scratch = d.join("scratch");
        let git::RebaseStart::Conflicted(why) = git::rebase_start(d, &scratch, "topic", &onto)
            .await
            .unwrap()
        else {
            panic!("expected a conflict");
        };
        assert!(!why.contains("Executing:"), "{why}");
        let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
        assert!(skipped.ok(), "{}", skipped.stderr);
        let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
        let record = git::rebase_record(&scratch).await.unwrap();
        assert_eq!(record.picks, vec![first, middle, orig.clone()]);
        assert_eq!(record.heads[0], record.heads[1]);
        assert_ne!(record.heads[1], record.heads[2]);
        assert_eq!(
            dropped_commits(d, &scratch, &onto, &orig, &head)
                .await
                .unwrap(),
            vec!["lost middle"]
        );
        git::rebase_abort(d, &scratch).await;
        assert!(git::is_ancestor(d, &base, &head).await);
    }

    #[test]
    fn recording_diagnostics_do_not_hide_other_git_output() {
        assert_eq!(
            git::rebase_said("before\nExecuting: record\nafter\n"),
            "before\nafter"
        );
    }

    // Exercise the actual rebase and finish path. C0 conflicts in another
    // file; C1 and C2 successively change the first line of f.txt. Upstream
    // also changes a distant line, so neither C1 nor the original tip has
    // the result's whole-file snapshot.
    async fn rebase_successive_edits(
        absorbed: bool,
        extra_hunk: bool,
        unrelated_conflict: bool,
    ) -> Rebased {
        rebase_successive_edits_record(absorbed, extra_hunk, unrelated_conflict, None).await
    }

    async fn rebase_successive_edits_record(
        absorbed: bool,
        extra_hunk: bool,
        unrelated_conflict: bool,
        damage: Option<&str>,
    ) -> Rebased {
        crate::run::pin_test_home();
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        // Keep Git checkouts consistent with this fixture's LF byte strings,
        // even when the host enables automatic CRLF conversion.
        sh(d, &["config", "core.autocrlf", "false"]);
        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
        std::fs::write(d.join("f.txt"), body).unwrap();
        std::fs::write(d.join("conflict.txt"), "old\n").unwrap();
        if unrelated_conflict {
            std::fs::write(d.join("g.txt"), "old\n").unwrap();
        }
        let base = commit(d, "base").await;
        sh(d, &["checkout", "-q", "-b", "topic"]);
        std::fs::write(d.join("conflict.txt"), "branch\n").unwrap();
        commit(d, "c0").await;
        let mut middle = body.replacen("old", "new", 1);
        if extra_hunk {
            middle = middle.replace("\n5\n", "\nmissing\n");
        }
        std::fs::write(d.join("f.txt"), &middle).unwrap();
        let c1 = commit(d, "c1").await;
        std::fs::write(d.join("f.txt"), middle.replacen("new", "newer", 1)).unwrap();
        if unrelated_conflict {
            std::fs::write(d.join("g.txt"), "branch\n").unwrap();
        }
        let orig = commit(d, "c2").await;
        sh(d, &["checkout", "-q", "main"]);
        std::fs::write(d.join("conflict.txt"), "branch plus upstream\n").unwrap();
        let mut upstream = body
            .replacen("old", if absorbed { "new" } else { "theirs" }, 1)
            .replace("end", "upstream tail");
        if extra_hunk {
            upstream = upstream.replace("\n5\n", "\nupstream middle\n");
        }
        std::fs::write(d.join("f.txt"), &upstream).unwrap();
        if unrelated_conflict {
            std::fs::write(d.join("g.txt"), "upstream\n").unwrap();
        }
        let onto = commit(d, "upstream composite").await;
        // The composite has no patch-id twin for C1.
        assert!(git::cherry(d, &onto, &orig).await.unwrap().0.contains(&c1));
        let scratch = d.join("scratch");
        assert!(matches!(
            git::rebase_start(d, &scratch, "topic", &onto)
                .await
                .unwrap(),
            git::RebaseStart::Conflicted(_)
        ));
        std::fs::write(
            scratch.join("conflict.txt"),
            "branch plus upstream resolved\n",
        )
        .unwrap();
        sh(&scratch, &["add", "conflict.txt"]);
        let continued = git::git_raw(
            &scratch,
            &["-c", "core.editor=true", "rebase", "--continue"],
        )
        .await
        .unwrap();
        if absorbed && !extra_hunk {
            // C1 becomes empty automatically. C2 may conflict on a path C1
            // never touched, while its f.txt change has applied correctly.
            if unrelated_conflict {
                assert!(!continued.ok());
                assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), vec!["g.txt"]);
                assert_eq!(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap(), orig);
                std::fs::write(scratch.join("g.txt"), "branch plus upstream resolved\n").unwrap();
                sh(&scratch, &["add", "g.txt"]);
                let resolved = git::git_raw(&scratch, &["rebase", "--continue"])
                    .await
                    .unwrap();
                assert!(resolved.ok(), "{}", resolved.stderr);
                // A whole-tree merge would reject the correctly rebased C1
                // solely because of the unrelated g.txt conflict.
                let full = git::git_raw(
                    d,
                    &[
                        "merge-tree",
                        "--write-tree",
                        &format!("--merge-base={c1}"),
                        &onto,
                        &orig,
                    ],
                )
                .await
                .unwrap();
                assert_eq!(full.code, Some(1));
            } else {
                assert!(continued.ok(), "{}", continued.stderr);
            }
        } else {
            assert!(!continued.ok());
            assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), vec!["f.txt"]);
            let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
            if !absorbed {
                // C2 now conflicts because its predecessor was really skipped.
                assert!(!skipped.ok());
                std::fs::write(
                    scratch.join("f.txt"),
                    upstream.replacen("theirs", "newer", 1),
                )
                .unwrap();
                sh(&scratch, &["add", "f.txt"]);
                let resolved = git::git_raw(
                    &scratch,
                    &["-c", "core.editor=true", "rebase", "--continue"],
                )
                .await
                .unwrap();
                assert!(resolved.ok(), "{}", resolved.stderr);
            } else {
                assert!(skipped.ok(), "{}", skipped.stderr);
            }
        }
        assert!(!git::rebase_in_progress(&scratch).await);
        assert_eq!(
            std::fs::read_to_string(scratch.join("f.txt")).unwrap(),
            upstream.replacen(if absorbed { "new" } else { "theirs" }, "newer", 1)
        );
        let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
        // The old final-tree-only check cannot account for C1 in any case.
        assert!(!already_in_result(d, &c1, &orig, &head).await.unwrap());
        let mut state = RunState::new(
            d.to_path_buf(),
            "main".into(),
            base,
            "rebase".into(),
            crate::config::Config::default(),
        );
        if let Some(damage) = damage {
            let path = git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
                .await
                .unwrap();
            match damage {
                "missing" => std::fs::remove_file(&path).unwrap(),
                "count" => std::fs::write(&path, "").unwrap(),
                "final" => {
                    let text = std::fs::read_to_string(&path).unwrap();
                    let mut heads: Vec<_> = text.lines().map(str::to_owned).collect();
                    *heads.last_mut().unwrap() = onto.clone();
                    std::fs::write(&path, heads.join("\n") + "\n").unwrap();
                }
                "invalid" => std::fs::write(&path, "invalid\n").unwrap(),
                _ => unreachable!(),
            }
        }
        let outcome = finish(
            &mut state,
            &scratch,
            "topic",
            &orig,
            &onto,
            &["conflict.txt".into()],
            "",
        )
        .await
        .unwrap();
        std::fs::remove_dir_all(state.dir()).ok();
        outcome
    }

    #[tokio::test]
    async fn missing_or_inconsistent_rebase_records_stop_the_rebase() {
        for damage in ["missing", "count", "final", "invalid"] {
            let outcome = rebase_successive_edits_record(true, false, false, Some(damage)).await;
            assert!(
                matches!(outcome, Rebased::Stopped(why) if why.contains("record could not be verified")),
                "{damage}"
            );
        }
    }

    #[tokio::test]
    async fn an_absorbed_middle_commit_superseded_by_a_later_edit_is_applied() {
        assert_eq!(
            rebase_successive_edits(true, false, false).await,
            Rebased::Applied
        );
    }

    #[tokio::test]
    async fn an_unrelated_later_conflict_does_not_hide_an_absorbed_commit() {
        assert_eq!(
            rebase_successive_edits(true, false, true).await,
            Rebased::Applied
        );
    }

    #[tokio::test]
    async fn a_skipped_middle_commit_superseded_by_a_later_edit_is_dropped() {
        let Rebased::Stopped(why) = rebase_successive_edits(false, false, false).await else {
            panic!("a skipped middle commit must stop the rebase");
        };
        assert!(why.contains("the rebase dropped some of the branch's commits (skipped?)"));
        assert!(why.contains("c1"));
    }

    #[tokio::test]
    async fn a_partially_absorbed_middle_commit_with_a_skipped_hunk_is_dropped() {
        let Rebased::Stopped(why) = rebase_successive_edits(true, true, false).await else {
            panic!("an unabsorbed hunk must stop the rebase");
        };
        assert!(why.contains("the rebase dropped some of the branch's commits (skipped?)"));
        assert!(why.contains("c1"));
    }

    #[tokio::test]
    async fn an_absorbed_commit_erased_by_the_fixer_is_dropped() {
        crate::run::pin_test_home();
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        // This fixture controls each resolution itself; inherited rerere can
        // interfere with that sequence (including MERGE_RR lock contention).
        sh(d, &["config", "rerere.enabled", "false"]);
        let body =
            "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlater\n10\n11\n12\n13\n14\n15\n16\n17\n18\nend\n";
        std::fs::write(d.join("f.txt"), body).unwrap();
        std::fs::write(d.join("conflict.txt"), "old\n").unwrap();
        let base = commit(d, "base").await;
        sh(d, &["checkout", "-q", "-b", "topic"]);
        std::fs::write(d.join("conflict.txt"), "branch\n").unwrap();
        commit(d, "c0").await;
        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
        let c1 = commit(d, "c1").await;
        std::fs::write(
            d.join("f.txt"),
            body.replacen("old", "new", 1)
                .replace("later", "branch tail"),
        )
        .unwrap();
        let orig = commit(d, "c2").await;
        sh(d, &["checkout", "-q", "main"]);
        std::fs::write(d.join("conflict.txt"), "upstream\n").unwrap();
        let upstream = body
            .replacen("old", "new", 1)
            .replace("end", "upstream tail");
        std::fs::write(d.join("f.txt"), &upstream).unwrap();
        let onto = commit(d, "upstream composite").await;
        let scratch = d.join("scratch");
        assert!(matches!(
            git::rebase_start(d, &scratch, "topic", &onto)
                .await
                .unwrap(),
            git::RebaseStart::Conflicted(_)
        ));
        // While resolving C0, the fixer erases C1's absorbed first-line edit.
        std::fs::write(scratch.join("conflict.txt"), "resolved\n").unwrap();
        std::fs::write(scratch.join("f.txt"), upstream.replacen("new", "theirs", 1)).unwrap();
        sh(&scratch, &["add", "conflict.txt", "f.txt"]);
        let continued = git::git_raw(&scratch, &["rebase", "--continue"])
            .await
            .unwrap();
        assert_eq!(
            continued.code,
            Some(1),
            "{}\n{}",
            continued.stdout,
            continued.stderr
        );
        assert_eq!(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap(), c1);
        let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
        assert!(skipped.ok(), "{}", skipped.stderr);
        let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
        assert!(replay_is_noop(d, &c1, &onto).await.unwrap());
        // The later branch commit edits a different hunk, so the clean merge
        // still requires "new" on line one. The final result has "theirs".
        let expected = git::git_raw(
            d,
            &[
                "merge-tree",
                "--write-tree",
                &format!("--merge-base={c1}"),
                &onto,
                &orig,
            ],
        )
        .await
        .unwrap();
        assert!(expected.ok(), "{}", expected.stderr);
        assert!(
            !absorbed_in_result(d, &c1, &onto, &orig, &head)
                .await
                .unwrap()
        );
        assert_eq!(
            dropped_commits(d, &scratch, &onto, &orig, &head)
                .await
                .unwrap(),
            vec!["c1"]
        );
        let mut state = RunState::new(
            d.to_path_buf(),
            "main".into(),
            base,
            "rebase".into(),
            crate::config::Config::default(),
        );
        let outcome = finish(
            &mut state,
            &scratch,
            "topic",
            &orig,
            &onto,
            &["conflict.txt".into()],
            "",
        )
        .await
        .unwrap();
        assert!(
            matches!(outcome, Rebased::Stopped(why) if why.contains("the rebase dropped some of the branch's commits (skipped?)") && why.contains("c1"))
        );
        std::fs::remove_dir_all(state.dir()).ok();
    }

    #[tokio::test]
    async fn a_partially_absorbed_commit_missing_an_unrelated_hunk_is_dropped() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        sh(d, &["init", "-q", "-b", "main"]);
        sh(d, &["config", "user.name", "t"]);
        sh(d, &["config", "user.email", "t@example.com"]);
        std::fs::write(d.join("c0.txt"), "base c0\n").unwrap();
        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
        std::fs::write(d.join("f.txt"), body).unwrap();
        std::fs::write(d.join("extra.txt"), "initial\n").unwrap();
        let base = commit(d, "base").await;

        // Branch commits: C0, C1 (touches f.txt AND extra.txt), C2
        std::fs::write(d.join("c0.txt"), "branch c0\n").unwrap();
        commit_dated(d, "c0").await;
        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
        std::fs::write(d.join("extra.txt"), "c1 edit\n").unwrap();
        commit_dated(d, "c1").await;
        std::fs::write(d.join("f.txt"), body.replacen("old", "newer", 1)).unwrap();
        let orig = commit_dated(d, "c2").await;

        // Upstream absorbed C1's f.txt edit, but NOT extra.txt
        sh(d, &["checkout", "-q", "-b", "up", &base]);
        std::fs::write(d.join("c0.txt"), "upstream c0\n").unwrap();
        let up = body.replacen("old", "new", 1).replace("last", "tail");
        std::fs::write(d.join("f.txt"), &up).unwrap();
        let onto = commit(d, "upstream").await;

        // Result: C0 resolved, C1 was skipped or dropped despite extra.txt missing, C2 applied
        std::fs::write(d.join("c0.txt"), "resolved c0\n").unwrap();
        commit_dated(d, "c0").await;
        let res = up.replacen("new", "newer", 1);
        std::fs::write(d.join("f.txt"), &res).unwrap();
        // extra.txt remains "initial\n"
        let head = commit_dated(d, "c2").await;

        let c0 = git::rev_parse(d, &format!("{orig}~2")).await.unwrap();
        let c1 = git::rev_parse(d, &format!("{orig}^")).await.unwrap();
        let resolved = git::rev_parse(d, &format!("{head}^")).await.unwrap();
        record(
            d,
            &[c0, c1, orig.clone()],
            &[resolved.clone(), resolved, head.clone()],
        )
        .await;
        assert_eq!(
            dropped_commits(d, d, &onto, &orig, &head).await.unwrap(),
            vec!["c1"]
        );
    }
}