Skip to main content

magi/
rebase.rs

1//! Rebasing the winning branch onto a moved base, with a fixer for conflicts.
2//!
3//! Both `graph::Runner::sync_to_base` (before review) and `land::Step::Rebase`
4//! (after the pull request exists) used to stop on a conflict and leave it to
5//! a person. A conflict is often a chore - two `pub mod` lines on the same
6//! spot - and what follows it (a rule the base gained meanwhile) is exactly
7//! what the gate-fix round handles, so both callers now come through
8//! [`rebase_with_fixer`], which hands the standing conflict to the fixer seat.
9//!
10//! The rules, none optional:
11//!
12//! - **magi resolves nothing itself.** No taking one side, no line merging:
13//!   the agent decides. Everything here is scaffolding around that call.
14//! - **The round is judged by what git says**, never by the fixer's report:
15//!   the rebase is no longer in progress, nothing is unmerged, no conflict
16//!   marker is left in a path that conflicted, and the base is an ancestor of
17//!   the result (an agent that ran `git rebase --abort` leaves a tidy tree
18//!   that contains no base at all). Whether the tree *builds* is left to the
19//!   review and gate that follow, which already know how to fix a breakage.
20//! - **The budget is `graph.review_rounds`, counted in
21//!   `RunState::rebase_fixes` per sequencer stop** and saved before the fixer
22//!   is called, shared by both callers, so a park or crash cannot hand a round back. It
23//!   touches neither the task's attempts nor land's own rebase budget.
24//! - **A failure restores the branch.** Whatever the fixer left, the branch
25//!   ref goes back to where it was and the throwaway worktree is removed, so
26//!   the fallback is exactly the old "conflict, a person decides".
27
28use std::path::Path;
29use std::time::Duration;
30
31use anyhow::{Context as _, Result};
32use jiff::Timestamp;
33
34use crate::agent::{self, Invocation};
35use crate::git;
36use crate::land::seat_of;
37use crate::prompt;
38use crate::run::{QuotaLoss, RebaseFixRecord, RunState};
39
40/// How [`rebase_with_fixer`] ended.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Rebased {
43    /// The branch now sits on top of the base (rebased cleanly or resolved by
44    /// the fixer); the throwaway worktree is gone.
45    Applied,
46    /// It did not apply. The branch is untouched, the worktree is gone, and
47    /// the string says what was tried: rounds spent, paths still conflicted,
48    /// and what git said.
49    Stopped(String),
50}
51
52/// Longest conflict excerpt shown to the fixer, per file and in total.
53const HUNK_PER_FILE: usize = 4_000;
54const HUNK_TOTAL: usize = 16_000;
55/// Commit subjects listed per side.
56const SUBJECTS: usize = 20;
57/// Paths named in a failure reason before "and N more".
58const PATHS_IN_REASON: usize = 8;
59
60/// Rebase `branch` onto `onto` in `scratch`, giving a conflict to the fixer.
61///
62/// Re-entrant: when `scratch` already holds a rebase in progress (a run that
63/// died in the middle of a round) it carries on from there instead of
64/// starting over, and the rounds already recorded still count.
65pub async fn rebase_with_fixer(
66    state: &mut RunState,
67    scratch: &Path,
68    branch: &str,
69    onto: &str,
70) -> Result<Rebased> {
71    prepare(state, scratch, branch).await?;
72    rebase_prepared(state, scratch, branch, onto).await
73}
74
75/// Prepare before reserving a synchronization attempt. Failures are infrastructure,
76/// not content conflicts, and must not create a fixer round.
77pub(crate) async fn prepare(state: &mut RunState, scratch: &Path, branch: &str) -> Result<()> {
78    git::rebase_prepare(&state.repo, scratch, branch)
79        .await
80        .map_err(|error| block(state, "worktree preparation", format!("{error:#}")))
81}
82
83/// Run an already prepared checkout after the caller saves its budget reservation.
84pub(crate) async fn rebase_prepared(
85    state: &mut RunState,
86    scratch: &Path,
87    branch: &str,
88    onto: &str,
89) -> Result<Rebased> {
90    let repo = state.repo.clone();
91    let cap = state.config.graph.review_rounds;
92    let orig = git::rev_parse(&repo, &format!("refs/heads/{branch}")).await?;
93
94    let mut said = String::new();
95    if !git::rebase_in_progress(scratch).await {
96        match git::rebase_execute(&repo, scratch, onto).await? {
97            git::RebaseStart::Applied => return Ok(Rebased::Applied),
98            git::RebaseStart::Failed(why) => return Ok(Rebased::Stopped(why)),
99            git::RebaseStart::Conflicted(why) => said = why,
100        }
101    }
102    // A tracking ref may have advanced while this rebase was parked. Finish
103    // the saved operation against its own target, then start an ordinary
104    // base sync if the requested target has moved.
105    let onto_sha = rebase_target(scratch).await?;
106    // Every path that was ever unmerged: the marker check on the finished
107    // tree looks at exactly these.
108    let mut touched: Vec<String> = Vec::new();
109
110    loop {
111        if !git::rebase_in_progress(scratch).await {
112            let result = finish(state, scratch, branch, &orig, &onto_sha, &touched, &said).await?;
113            if result == Rebased::Applied && git::rev_parse(&repo, onto).await? != onto_sha {
114                state.event("rebase", "saved rebase completed; syncing the newer base");
115                state.save()?;
116                return Box::pin(rebase_with_fixer(state, scratch, branch, onto)).await;
117            }
118            return Ok(result);
119        }
120        let paths = git::unmerged_paths(scratch).await.unwrap_or_default();
121        for p in &paths {
122            if !touched.contains(p) {
123                touched.push(p.clone());
124            }
125        }
126        // A fixer that already worked on *this* stop point may have left the
127        // contents resolved with only the staging undone (a run killed between
128        // the steps). Finish that before the budget is looked at:
129        // re-confirming resolved files is not a conflict round.
130        if let Launch::Advanced = launcher_stage(state, scratch, &orig, &onto_sha).await? {
131            continue;
132        }
133        let spent = stop_rounds(state, scratch).await;
134        if spent >= cap {
135            let why = reason(spent, cap, &paths, &said, "the rounds are spent");
136            abandon(&repo, scratch, branch, &orig).await;
137            return Ok(Rebased::Stopped(why));
138        }
139
140        let winner = state
141            .winner()
142            .cloned()
143            .context("resolving a rebase conflict needs a winning candidate")?;
144        let roles = state
145            .config
146            .resolve_roles()
147            .context("resolve the roster for the rebase fix")?;
148        // The chain (`crate::fixer`): one round however many agents it takes.
149        let attempts = crate::fixer::attempts(state, &roles, &winner);
150        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
151
152        let round = spent + 1;
153        let artifact_round = state.rebase_fixes.len() + 1;
154        let branch_subjects = subjects(scratch, &format!("{onto}..{branch}")).await;
155        let onto_subjects = subjects(scratch, &format!("{branch}..{onto}")).await;
156        let hunks = hunks(scratch, &paths);
157        let prompt_text = prompt::rebase_conflict(&prompt::RebaseConflict {
158            instruction: &state.instruction,
159            worktree: scratch,
160            branch,
161            onto,
162            paths: &paths,
163            branch_subjects: &branch_subjects,
164            onto_subjects: &onto_subjects,
165            hunks: &hunks,
166            round,
167            cap,
168            language: &state.config.graph.language,
169            github_language: &state.config.graph.github_language,
170        });
171        let prompt_text = if !crate::build_target::isolated(&state.config)
172            && state.config.cache_dir().is_some()
173        {
174            format!("{prompt_text}\n\n{}", prompt::build_cache_note("fix", true))
175        } else {
176            prompt_text
177        };
178
179        // Spent before the call, on disk: a run killed mid-round must not
180        // get the round back.
181        let stop = rebase_head(scratch).await;
182        let index_outside = Some(round_baseline(state, scratch, &paths).await?);
183        state.rebase_fixes.push(RebaseFixRecord {
184            outage: None,
185            agent: ids[0].clone(),
186            paths: paths.clone(),
187            from: Some(orig.clone()),
188            finished: false,
189            error: None,
190            stop,
191            index_outside,
192            launcher: None,
193            infra: None,
194        });
195        state.event(
196            "rebase",
197            format!(
198                "{branch} conflicts with {onto} ({} path(s)); fixer round {round} of {cap}",
199                paths.len()
200            ),
201        );
202        state.save()?;
203
204        // Each id at most once, forward only. The round was spent and saved
205        // above, so a chain advance inside it spends nothing further and a
206        // crash cannot hand it back; only the record's `agent` follows the
207        // asked agent (saved before its call, like the round itself).
208        let artifacts = agent::artifacts_dir(&state.dir());
209        let mut last = None;
210        for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
211            if i > 0 {
212                if let Some(r) = state.rebase_fixes.last_mut() {
213                    r.agent = spec.id.clone();
214                }
215                state.save()?;
216            }
217            let mut seat = seat_of(state, &seat_key, &spec.id);
218            let stem = if i == 0 {
219                format!("rebase-fix-{artifact_round}")
220            } else {
221                format!("rebase-fix-{artifact_round}-{}", spec.id)
222            };
223            let out = agent::invoke(
224                &spec,
225                &mut seat,
226                &Invocation {
227                    coordination: state.config.coordination.as_ref(),
228                    fetched_base: state.fetched_base.as_ref(),
229                    cwd: scratch,
230                    prompt: &prompt_text,
231                    timeout: Duration::from_secs(state.config.graph.timeout_fix),
232                    allow_write: true,
233                    sessions: state.config.graph.sessions,
234                    artifacts: &artifacts,
235                    stem: &stem,
236                    run: &state.id,
237                    node: "rebase",
238                    cache_dir: state.config.cache_dir().as_deref(),
239                    attachments: &[],
240                    writable: &[],
241                },
242            )
243            .await;
244            let seat_name = seat.key.clone();
245            state.seats.insert(seat.key.clone(), seat);
246            if let Some(next) = ids.get(i + 1)
247                && agent::chain_advances(&out)
248            {
249                let (class, why) = crate::fixer::failure_of(&out);
250                crate::graph::record_handover(
251                    state, "rebase", &seat_name, &spec.id, next, &class, &why,
252                );
253                continue;
254            }
255            last = Some((out, seat_name));
256            break;
257        }
258        let (out, seat_name) = last.expect("the fixer chain always has an entry");
259
260        let mut error = None;
261        match out {
262            Ok(o) if o.quota_exhausted() => {
263                let loss = QuotaLoss::from_report(seat_name, "rebase", o.quota.as_ref());
264                if let Some(record) = state.rebase_fixes.last_mut() {
265                    record.outage = Some(loss.cause);
266                }
267                crate::graph::block_machine_outage(state, "rebase", std::slice::from_ref(&loss));
268                state.quota.push(loss);
269                state.save()?;
270                return Err(crate::repo_lock::ResourceBlocked(
271                    "rebase fixer unavailable; restore agent availability and resume".into(),
272                )
273                .into());
274            }
275            Ok(o) if !o.usable() => {
276                error = Some(format!(
277                    "the fixer produced nothing usable ({})",
278                    crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
279                ));
280            }
281            Ok(_) => {}
282            Err(e)
283                if e.is::<crate::repo_lock::ResourceBlocked>()
284                    && crate::build_target::isolated(&state.config) =>
285            {
286                if let Some(record) = state.rebase_fixes.last_mut() {
287                    record.infra = Some(format!("{e:#}"));
288                }
289                if let Some(timeout) = e.downcast_ref::<agent::IsolatedSeatWait>() {
290                    state.event("resource", timeout.0.description());
291                    state.resource_block = Some(timeout.0.clone());
292                    state.save()?;
293                    return Err(e);
294                }
295                return Err(block(state, crate::build_target::KIND, format!("{e:#}")));
296            }
297            Err(e) => error = Some(format!("{e:#}")),
298        }
299
300        if let Some(r) = state.rebase_fixes.last_mut() {
301            r.error = error.clone();
302        }
303        // The seat resolved contents; the launcher owns Git's metadata.
304        // A denied write is a resumable stop with no further round.
305        if let Launch::Nothing(why) = launcher_stage(state, scratch, &orig, &onto_sha).await? {
306            state.event("rebase", format!("launcher staging skipped: {why}"));
307        }
308        let finished = !git::rebase_in_progress(scratch).await;
309        if let Some(r) = state.rebase_fixes.last_mut() {
310            r.finished = finished;
311        }
312        state.save()?;
313    }
314}
315
316/// What [`launcher_stage`] did.
317#[derive(Debug)]
318enum Launch {
319    /// Nothing was staged or continued; why, for the event log.
320    Nothing(String),
321    /// The sequencer moved (continued to the end or to the next stop).
322    Advanced,
323}
324
325/// The commit the sequencer is replaying right now.
326async fn rebase_head(scratch: &Path) -> Option<String> {
327    git::git(scratch, &["rev-parse", "-q", "--verify", "REBASE_HEAD"])
328        .await
329        .ok()
330        .filter(|s| !s.is_empty())
331}
332
333/// A denied or failed Git write is infrastructure: record it on the round,
334/// keep the worktree, branch and resolved contents, and stop resumably.
335fn infra_stop(state: &mut RunState, detail: String) -> anyhow::Error {
336    if let Some(r) = state.rebase_fixes.last_mut() {
337        r.infra = Some(detail.clone());
338    }
339    block(state, "git metadata write", detail)
340}
341
342fn block(state: &mut RunState, kind: &str, detail: String) -> anyhow::Error {
343    let detail = format!("rebase recovery: {detail}");
344    state.resource_block = Some(crate::run::ResourceBlock {
345        cause: crate::run::ResourceBlockCause::Other,
346        node: "rebase".into(),
347        kind: kind.into(),
348        detail: detail.clone(),
349        at: Timestamp::now(),
350    });
351    state.event("resource", detail.clone());
352    state.save().ok();
353    crate::repo_lock::ResourceBlocked(detail).into()
354}
355
356/// Status entries `(XY, path)` of the worktree, renames split.
357pub(crate) async fn status_entries(scratch: &Path) -> Result<Vec<(String, String)>> {
358    let out = git::git_raw(
359        scratch,
360        &[
361            "status",
362            "--porcelain=v1",
363            "-z",
364            "--untracked-files=all",
365            "--no-renames",
366        ],
367    )
368    .await?;
369    anyhow::ensure!(out.ok(), "git status failed: {}", out.stderr);
370    Ok(out
371        .stdout
372        .split('\0')
373        .filter(|e| e.len() > 3)
374        .map(|e| (e[..2].to_owned(), e[3..].to_owned()))
375        .collect())
376}
377
378/// Index-side changes against HEAD outside `expected` (what Git applied
379/// cleanly), as a comparable string.
380pub(crate) async fn index_outside(scratch: &Path, expected: &[String]) -> Result<String> {
381    let out = git::git_raw(
382        scratch,
383        &[
384            "diff",
385            "--cached",
386            "--raw",
387            "-z",
388            "--no-renames",
389            "--no-abbrev",
390        ],
391    )
392    .await?;
393    anyhow::ensure!(out.ok(), "git diff --cached failed: {}", out.stderr);
394    Ok(outside_diff(&out.stdout, expected))
395}
396
397fn outside_diff(raw: &str, expected: &[String]) -> String {
398    let mut parts = raw.split('\0').filter(|p| !p.is_empty());
399    let mut lines = Vec::new();
400    while let (Some(meta), Some(path)) = (parts.next(), parts.next()) {
401        if !expected.iter().any(|e| e == path) {
402            lines.push(format!("{meta}\t{path}"));
403        }
404    }
405    lines.join("\n")
406}
407
408/// Does `last` belong to the stop point the sequencer is at now?
409///
410/// A record carries the replayed commit. A record from before that was kept
411/// can only be matched by what it says about itself, so it counts only when
412/// every recorded round saw the same non-empty conflict set and none knows
413/// its stop: a different pick would not have repeated the same paths.
414async fn same_stop(state: &RunState, scratch: &Path) -> bool {
415    let Some(last) = state.rebase_fixes.last() else {
416        return false;
417    };
418    match &last.stop {
419        Some(stop) => rebase_head(scratch).await.as_deref() == Some(stop.as_str()),
420        None => {
421            !last.paths.is_empty()
422                && state
423                    .rebase_fixes
424                    .iter()
425                    .all(|r| r.stop.is_none() && r.paths == last.paths)
426        }
427    }
428}
429
430/// Records for the current stop form a contiguous suffix. Always retain the
431/// first record's paths and index baseline, even after a rejected seat edit.
432fn stop_records(state: &RunState) -> &[RebaseFixRecord] {
433    let Some(last) = state.rebase_fixes.last() else {
434        return &[];
435    };
436    let start = state
437        .rebase_fixes
438        .iter()
439        .rposition(|r| r.stop != last.stop || (r.stop.is_none() && r.paths != last.paths))
440        .map_or(0, |i| i + 1);
441    &state.rebase_fixes[start..]
442}
443
444async fn stop_rounds(state: &RunState, scratch: &Path) -> usize {
445    if same_stop(state, scratch).await {
446        stop_records(state)
447            .iter()
448            .filter(|record| record.outage.is_none())
449            .count()
450    } else {
451        0
452    }
453}
454
455async fn round_baseline(state: &mut RunState, scratch: &Path, paths: &[String]) -> Result<String> {
456    if same_stop(state, scratch).await {
457        if let Some(before) = &stop_records(state)[0].index_outside {
458            return Ok(before.clone());
459        }
460        return Err(infra_stop(state,
461            "the saved stop has no original outside-index baseline; keep the resolution and have the original owner establish a verified baseline before continuation".into()));
462    }
463    index_outside(scratch, paths)
464        .await
465        .map_err(|e| infra_stop(state, format!("cannot capture index baseline: {e:#}")))
466}
467
468/// Recompute the clean part of this pick without reading the fixer's index
469/// as a baseline. Only object data is written; the retained index, contents,
470/// branch and sequencer are untouched. Unsupported merge shapes fail closed.
471async fn legacy_baseline(
472    scratch: &Path,
473    paths: &[String],
474    lease: Option<crate::repo_lock::SeatLease>,
475) -> Result<(String, String, String)> {
476    let head = git::rev_parse(scratch, "HEAD").await?;
477    let pick = git::rev_parse(scratch, "REBASE_HEAD").await?;
478    let parent = git::rev_parse(scratch, "REBASE_HEAD^").await?;
479    let out = mutate(
480        scratch,
481        &[
482            "merge-tree",
483            "--write-tree",
484            "--name-only",
485            "--no-messages",
486            "-z",
487            &format!("--merge-base={parent}"),
488            &head,
489            &pick,
490        ],
491        lease,
492    )
493    .await?;
494    anyhow::ensure!(
495        out.code == Some(1),
496        "cannot reconstruct legacy conflict baseline: {}",
497        out.stderr
498    );
499    let mut fields = out.stdout.split('\0').filter(|p| !p.is_empty());
500    let tree = fields.next().context("merge-tree returned no tree")?;
501    let mut conflicts: Vec<&str> = fields.collect();
502    conflicts.sort_unstable();
503    let mut expected: Vec<&str> = paths.iter().map(String::as_str).collect();
504    expected.sort_unstable();
505    anyhow::ensure!(
506        conflicts == expected,
507        "reconstructed conflict paths differ from the saved stop"
508    );
509    let out = git::git_raw(
510        scratch,
511        &[
512            "diff",
513            "--raw",
514            "-z",
515            "--no-renames",
516            "--no-abbrev",
517            &head,
518            tree,
519        ],
520    )
521    .await?;
522    anyhow::ensure!(
523        out.ok(),
524        "cannot read reconstructed baseline: {}",
525        out.stderr
526    );
527    Ok((outside_diff(&out.stdout, paths), head, pick))
528}
529
530pub(crate) async fn rebase_target(scratch: &Path) -> Result<String> {
531    let path = git::git(scratch, &["rev-parse", "--git-path", "rebase-merge/onto"]).await?;
532    let target = std::fs::read_to_string(scratch.join(path))?;
533    git::rev_parse(scratch, &format!("{}^{{commit}}", target.trim())).await
534}
535
536/// Read the original branch identity retained by a paused merge-backend rebase.
537pub(crate) async fn saved_base_identity(scratch: &Path, branch: &str) -> Result<String> {
538    let read = |name: &'static str| async move {
539        let path = git::git(
540            scratch,
541            &["rev-parse", "--git-path", &format!("rebase-merge/{name}")],
542        )
543        .await?;
544        anyhow::Ok(
545            std::fs::read_to_string(scratch.join(path))?
546                .trim()
547                .to_owned(),
548        )
549    };
550    anyhow::ensure!(
551        read("head-name").await? == format!("refs/heads/{branch}"),
552        "saved rebase belongs to another branch"
553    );
554    git::rev_parse(scratch, &format!("{}^{{commit}}", read("orig-head").await?)).await
555}
556
557async fn stop_identity(scratch: &Path, original: &str, onto: &str) -> Result<()> {
558    for (name, expected) in [("orig-head", original), ("onto", onto)] {
559        let path = git::git(
560            scratch,
561            &["rev-parse", "--git-path", &format!("rebase-merge/{name}")],
562        )
563        .await?;
564        let path = Path::new(&path);
565        let path = if path.is_absolute() {
566            path.to_path_buf()
567        } else {
568            scratch.join(path)
569        };
570        anyhow::ensure!(
571            std::fs::read_to_string(path)?.trim() == expected,
572            "rebase {name} changed"
573        );
574    }
575    Ok(())
576}
577
578// The command owns coordination until all hooks and descendants have stopped,
579// even if its caller is cancelled while waiting for Git.
580async fn mutate(
581    scratch: &Path,
582    args: &[&str],
583    lease: Option<crate::repo_lock::SeatLease>,
584) -> Result<git::GitOut> {
585    use crate::proc::Quiet as _;
586    use std::process::Stdio;
587    use tokio::io::AsyncReadExt as _;
588    let wait = crate::repo_lock::WaitPolicy::current();
589    anyhow::ensure!(
590        !wait.cancelled(),
591        crate::repo_lock::ResourceBlocked("launcher Git operation cancelled".into())
592    );
593    let mut command = tokio::process::Command::new("git");
594    command
595        .quiet()
596        .args(args)
597        .current_dir(scratch)
598        .env("GIT_TERMINAL_PROMPT", "0")
599        .env("GIT_EDITOR", "true")
600        .stdin(Stdio::null())
601        .stdout(Stdio::piped())
602        .stderr(Stdio::piped())
603        .kill_on_drop(true);
604    let outputs = crate::retention::OutputLease::borrow(scratch)?
605        .into_iter()
606        .collect();
607    let mut running = crate::seat_process::Running::spawn_operation(command, lease, outputs)?;
608    let mut stdout = running.child().stdout.take().context("Git stdout")?;
609    let mut stderr = running.child().stderr.take().context("Git stderr")?;
610    let mut out = Vec::new();
611    let mut err = Vec::new();
612    let cancelled = async {
613        while !wait.cancelled() {
614            tokio::time::sleep(Duration::from_millis(50)).await;
615        }
616    };
617    let (status, _, _) = tokio::select! {
618        result = async { tokio::try_join!(
619            running.child().wait(),
620            stdout.read_to_end(&mut out),
621            stderr.read_to_end(&mut err)
622        ) } => result?,
623        () = cancelled => return Err(crate::repo_lock::ResourceBlocked("launcher Git operation cancelled".into()).into()),
624    };
625    running.finish().await;
626    Ok(git::GitOut {
627        code: status.code(),
628        stdout: String::from_utf8_lossy(&out).into_owned(),
629        stderr: String::from_utf8_lossy(&err).into_owned(),
630    })
631}
632
633/// Stage what the fixer resolved and continue the sequencer, as the launcher.
634///
635/// The seat only edits contents; staging and continuing stay with the
636/// launcher. Everything here is re-derived from Git inside the
637/// repository's coordination lease, so an interrupted pass is simply run
638/// again: the current unmerged set must lie inside the round's recorded
639/// paths, none may still hold markers, nothing outside them may have been
640/// edited, and only then are exactly those paths staged (literal pathspecs)
641/// and `rebase --continue` run with the recording exec untouched. Content
642/// problems are `Nothing` (the ordinary round machinery goes on); a refused
643/// Git write is an `Err` resource block that spends nothing and keeps the
644/// worktree, the branch and the resolved files.
645async fn launcher_stage(
646    state: &mut RunState,
647    scratch: &Path,
648    original: &str,
649    onto: &str,
650) -> Result<Launch> {
651    if !git::rebase_in_progress(scratch).await {
652        return Ok(Launch::Nothing("no rebase in progress".into()));
653    }
654    if !same_stop(state, scratch).await {
655        return Ok(Launch::Nothing(
656            "no fixer round is recorded for this stop point".into(),
657        ));
658    }
659    let wait = {
660        let inherited = crate::repo_lock::WaitPolicy::current();
661        crate::repo_lock::WaitPolicy::new(
662            Duration::from_secs(state.config.graph.timeout_resource_wait),
663            move || inherited.cancelled(),
664        )
665    };
666    if wait.cancelled() {
667        return Err(block(
668            state,
669            "repository coordination",
670            "cancelled before staging; the resolved files are kept".into(),
671        ));
672    }
673    let lease = crate::repo_lock::SeatLease::operation_with(
674        scratch,
675        state.config.coordination.as_ref(),
676        &wait,
677    )
678    .await;
679    let lease = match lease {
680        Ok(l) => l,
681        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
682            return Err(block(state, "repository coordination", e.to_string()));
683        }
684        Err(e) => return Err(e),
685    };
686
687    // Re-validated under the lease: the seat is gone, but an external
688    // updater is not.
689    if !git::rebase_in_progress(scratch).await || !same_stop(state, scratch).await {
690        return Ok(Launch::Nothing("the stop point changed".into()));
691    }
692    if let Err(e) = stop_identity(scratch, original, onto).await {
693        return Err(infra_stop(state, format!("{e:#}")));
694    }
695    let last = stop_records(state)[0].clone();
696    let lease = if last.index_outside.is_none() {
697        let (baseline, head, pick) = legacy_baseline(scratch, &last.paths, lease)
698            .await
699            .map_err(|e| infra_stop(state, format!("legacy baseline recovery: {e:#}")))?;
700        // The mutation's cleanup owner held the previous lease. Reacquire
701        // before accepting the result, then revalidate the exact stop/index.
702        let lease = crate::repo_lock::SeatLease::operation_with(
703            scratch,
704            state.config.coordination.as_ref(),
705            &wait,
706        )
707        .await
708        .map_err(|e| block(state, "repository coordination", e.to_string()))?;
709        let validation = async {
710            stop_identity(scratch, original, onto).await?;
711            anyhow::ensure!(
712                same_stop(state, scratch).await
713                    && git::rev_parse(scratch, "HEAD").await? == head
714                    && rebase_head(scratch).await.as_deref() == Some(&pick),
715                "the stop changed during legacy baseline recovery"
716            );
717            anyhow::ensure!(
718                index_outside(scratch, &last.paths).await? == baseline,
719                "the legacy index differs from the reconstructed clean baseline"
720            );
721            Ok::<_, anyhow::Error>(())
722        }
723        .await;
724        if let Err(e) = validation {
725            return Err(infra_stop(
726                state,
727                format!("legacy baseline recovery: {e:#}"),
728            ));
729        }
730        let first = state.rebase_fixes.len() - stop_records(state).len();
731        state.rebase_fixes[first].index_outside = Some(baseline);
732        for record in &mut state.rebase_fixes[first..] {
733            record.stop = Some(pick.clone());
734        }
735        state.event(
736            "rebase",
737            "verified and saved the legacy stop baseline from the original three-way merge",
738        );
739        state.save()?;
740        lease
741    } else {
742        lease
743    };
744    if last.stop.is_none() {
745        let pick = rebase_head(scratch)
746            .await
747            .context("legacy stop has no REBASE_HEAD")?;
748        let first = state.rebase_fixes.len() - stop_records(state).len();
749        for record in &mut state.rebase_fixes[first..] {
750            record.stop = Some(pick.clone());
751        }
752        state.save()?;
753    }
754    let baseline = round_baseline(state, scratch, &last.paths).await?;
755    let unmerged = match git::unmerged_paths(scratch).await {
756        Ok(u) => u,
757        Err(e) => return Err(infra_stop(state, format!("cannot read the index: {e:#}"))),
758    };
759    if let Some(p) = unmerged.iter().find(|p| !last.paths.contains(p)) {
760        return Ok(Launch::Nothing(format!(
761            "`{p}` is unmerged but was not part of the recorded conflict"
762        )));
763    }
764    for p in &last.paths {
765        match std::fs::symlink_metadata(scratch.join(p)) {
766            Ok(m) if m.is_dir() => {
767                return Ok(Launch::Nothing(format!("`{p}` is a directory")));
768            }
769            Ok(m) if m.is_file() => {
770                if let Err(e) = std::fs::read(scratch.join(p)) {
771                    return Err(infra_stop(state, format!("cannot read `{p}`: {e}")));
772                }
773                if has_markers(scratch, p, &["HEAD", "REBASE_HEAD"]).await? {
774                    return Ok(Launch::Nothing(format!(
775                        "`{p}` still holds conflict markers"
776                    )));
777                }
778            }
779            Ok(_) => {}
780            // Resolved by deleting the file.
781            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
782            Err(e) => return Err(infra_stop(state, format!("cannot inspect `{p}`: {e}"))),
783        }
784    }
785    let entries = match status_entries(scratch).await {
786        Ok(e) => e,
787        Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
788    };
789    // Whatever Git applied cleanly is staged and identical to the worktree;
790    // anything else outside the conflict is an edit nobody asked for.
791    let stray: Vec<&str> = entries
792        .iter()
793        .filter(|(_, p)| !last.paths.contains(p))
794        .filter(|(xy, _)| xy == "??" || !xy.ends_with(' '))
795        .map(|(_, p)| p.as_str())
796        .collect();
797    if !stray.is_empty() {
798        return Ok(Launch::Nothing(format!(
799            "changes outside the conflicted paths: {}",
800            stray.join(", ")
801        )));
802    }
803    match index_outside(scratch, &last.paths).await {
804        Ok(now) if now == baseline => {}
805        Ok(_) => {
806            return Ok(Launch::Nothing(
807                "the staged changes outside the conflicted paths changed".into(),
808            ));
809        }
810        Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
811    }
812
813    let set = |state: &mut RunState, step| {
814        if let Some(r) = state.rebase_fixes.last_mut() {
815            r.launcher = Some(step);
816        }
817        state.save()
818    };
819    // A previous pass may have staged the resolution before being interrupted.
820    // Include later worktree edits to those recorded paths as well, while
821    // leaving already-staged deletions (which have no path to add) alone.
822    let to_stage: Vec<&str> = last
823        .paths
824        .iter()
825        .filter(|p| {
826            unmerged.contains(p)
827                || entries
828                    .iter()
829                    .any(|(xy, path)| path == *p && !xy.ends_with(' '))
830        })
831        .map(String::as_str)
832        .collect();
833    if !to_stage.is_empty() {
834        set(state, crate::run::LauncherStep::Staging)?;
835        let mut args = vec!["--literal-pathspecs", "add", "-A", "--"];
836        args.extend(to_stage);
837        match mutate(scratch, &args, lease).await {
838            Ok(o) if o.ok() => {}
839            Ok(o) => {
840                let said = if o.stderr.is_empty() {
841                    o.stdout
842                } else {
843                    o.stderr
844                };
845                return Err(infra_stop(state, format!("staging was refused: {said}")));
846            }
847            Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
848        }
849        match git::unmerged_paths(scratch).await {
850            Ok(left) if left.is_empty() => {}
851            Ok(left) => {
852                return Err(infra_stop(
853                    state,
854                    format!("paths stayed unmerged after staging: {}", left.join(", ")),
855                ));
856            }
857            Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
858        }
859        // Running releases coordination only after all descendants stop.
860        // Reacquire it and revalidate the stop before the next mutation.
861        return Box::pin(launcher_stage(state, scratch, original, onto)).await;
862    }
863    set(state, crate::run::LauncherStep::Staged)?;
864    let before = rebase_head(scratch).await;
865    set(state, crate::run::LauncherStep::Continuing)?;
866    let out = match mutate(scratch, &["rebase", "--continue"], lease).await {
867        Ok(o) => o,
868        Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
869    };
870    if !out.ok() && git::rebase_in_progress(scratch).await {
871        let again = git::unmerged_paths(scratch).await.unwrap_or_default();
872        // A new conflict is the next stop point, not a failure; the same
873        // stop with nothing unmerged is git unable to write.
874        if again.is_empty() || rebase_head(scratch).await == before {
875            let said = git::rebase_said(&if out.stderr.is_empty() {
876                out.stdout
877            } else {
878                out.stderr
879            });
880            return Err(infra_stop(state, format!("continue failed: {said}")));
881        }
882    }
883    state.event(
884        "rebase",
885        format!(
886            "launcher staged {} path(s) and continued the rebase",
887            unmerged.len()
888        ),
889    );
890    Ok(Launch::Advanced)
891}
892
893type CompletedProblem = Option<(&'static str, Vec<String>)>;
894
895/// Read-only validation shared by normal completion and crash reconciliation.
896async fn completed_result(
897    repo: &Path,
898    scratch: &Path,
899    orig: &str,
900    onto_sha: &str,
901    touched: &[String],
902) -> Result<(String, CompletedProblem)> {
903    let unmerged = git::unmerged_paths(scratch).await.unwrap_or_default();
904    let head = git::rev_parse(scratch, "HEAD").await.unwrap_or_default();
905    // Not only the paths seen unmerged at a round's start: one round may
906    // continue through several commits, and a later commit's conflict never
907    // shows up at a loop head. Everything the result changes relative to the
908    // base is checked.
909    let mut candidates: Vec<String> = touched.to_vec();
910    if let Ok(changed) = git::git(scratch, &["diff", "--name-only", onto_sha, "HEAD"]).await {
911        for p in changed.lines().map(str::trim).filter(|l| !l.is_empty()) {
912            if !candidates.iter().any(|c| c == p) {
913                candidates.push(p.to_owned());
914            }
915        }
916    }
917    let mut marked = Vec::new();
918    for p in candidates {
919        if has_markers(scratch, &p, &[orig, onto_sha]).await? {
920            marked.push(p);
921        }
922    }
923
924    // Skipping every conflicting commit leaves the branch equal to the base:
925    // the ancestry test below passes and the branch's work is gone. Empty is
926    // only acceptable when every original commit already has a patch twin on
927    // the base.
928    let emptied = head == onto_sha
929        && git::cherry(repo, onto_sha, orig)
930            .await
931            .map_or(true, |(unmatched, _)| !unmatched.is_empty());
932
933    // A fixer that ran `git rebase --skip` on one of several commits lets the
934    // rest apply and the rebase finish; `emptied` only sees the whole change
935    // vanishing. Find the commits that are neither in the result nor already
936    // on the base.
937    let dropped = if unmerged.is_empty() && marked.is_empty() && !emptied && !head.is_empty() {
938        dropped_commits(repo, scratch, onto_sha, orig, &head).await
939    } else {
940        Ok(Vec::new())
941    };
942
943    let problem = if !unmerged.is_empty() {
944        Some(("paths are still unmerged", unmerged))
945    } else if !marked.is_empty() {
946        Some(("conflict markers were left in the tree", marked))
947    } else if emptied {
948        Some((
949            "the rebase ended with none of the branch's commits applied (all skipped)",
950            touched.to_vec(),
951        ))
952    } else if head.is_empty() || !git::is_ancestor(repo, onto_sha, &head).await {
953        Some((
954            "the rebase ended without the base in the result (abandoned or skipped)",
955            touched.to_vec(),
956        ))
957    } else if let Err(error) = &dropped {
958        Some((
959            "the rebase record could not be verified",
960            vec![format!("{error:#}")],
961        ))
962    } else if !dropped.as_ref().unwrap().is_empty() {
963        Some((
964            "the rebase dropped some of the branch's commits (skipped?)",
965            dropped.unwrap(),
966        ))
967    } else {
968        None
969    };
970    Ok((head, problem))
971}
972
973/// Revalidate retained Git evidence without rolling back or deleting a refused result.
974pub(crate) async fn recover_completed_base(
975    state: &RunState,
976    scratch: &Path,
977    branch: &str,
978    op: &crate::base_sync_recovery::Operation,
979    head: &str,
980) -> Result<bool> {
981    anyhow::ensure!(
982        scratch == state.dir().join("base-sync"),
983        "unexpected scratch location"
984    );
985    anyhow::ensure!(
986        !git::rebase_in_progress(scratch).await,
987        "scratch rebase is still active"
988    );
989    for (path, revision, expected) in [
990        (scratch, "HEAD".to_owned(), head),
991        (scratch, "ORIG_HEAD".to_owned(), op.head.as_str()),
992        (state.repo.as_path(), format!("refs/heads/{branch}"), head),
993    ] {
994        anyhow::ensure!(
995            git::rev_parse(path, &revision).await? == expected,
996            "completed scratch identity changed"
997        );
998    }
999    anyhow::ensure!(
1000        git::current_branch(scratch).await?.as_deref() == Some(branch),
1001        "scratch belongs to another branch"
1002    );
1003    let common = |path: &Path| {
1004        let path = path.to_owned();
1005        async move {
1006            let common = git::git(
1007                &path,
1008                &["rev-parse", "--path-format=absolute", "--git-common-dir"],
1009            )
1010            .await?;
1011            anyhow::Ok(std::fs::canonicalize(common)?)
1012        }
1013    };
1014    anyhow::ensure!(
1015        common(scratch).await? == common(&state.repo).await?,
1016        "scratch belongs to another repository"
1017    );
1018    anyhow::ensure!(
1019        git::is_clean(scratch).await?,
1020        "completed scratch has uncommitted changes"
1021    );
1022    let record = git::rebase_record(scratch).await?;
1023    // Bind the replay to the reserved base even though Git has removed
1024    // rebase-merge/onto. Each recording exec observes one pick's result.
1025    let mut previous = op.tip.as_str();
1026    for result in &record.heads {
1027        if result != previous {
1028            anyhow::ensure!(
1029                git::rev_parse(scratch, &format!("{result}^")).await? == previous,
1030                "recorded replay does not start at the reserved base or contains extra commits"
1031            );
1032        }
1033        previous = result;
1034    }
1035    for pick in record.picks {
1036        anyhow::ensure!(
1037            git::is_ancestor(&state.repo, &pick, &op.head).await,
1038            "record contains a foreign pick"
1039        );
1040    }
1041    let touched: Vec<_> = state
1042        .rebase_fixes
1043        .iter()
1044        .filter(|round| round.from.as_deref() == Some(op.head.as_str()))
1045        .flat_map(|round| round.paths.iter().cloned())
1046        .collect();
1047    let (result, problem) =
1048        completed_result(&state.repo, scratch, &op.head, &op.tip, &touched).await?;
1049    Ok(result == head && problem.is_none())
1050}
1051
1052/// Judge a rebase that is no longer in progress by what git says.
1053pub(crate) async fn finish(
1054    state: &mut RunState,
1055    scratch: &Path,
1056    branch: &str,
1057    orig: &str,
1058    onto_sha: &str,
1059    touched: &[String],
1060    said: &str,
1061) -> Result<Rebased> {
1062    let repo = state.repo.clone();
1063    let spent = state.rebase_fixes.len();
1064    let cap = state.config.graph.review_rounds;
1065    let (head, problem) = completed_result(&repo, scratch, orig, onto_sha, touched).await?;
1066    match problem {
1067        None => {
1068            // The validated result may legitimately have different patch IDs
1069            // after conflict resolution. Persist its exact identity before
1070            // deleting the Git evidence needed to validate it again.
1071            if scratch == state.dir().join("base-sync")
1072                && state.winner().is_some_and(|winner| winner.branch == branch)
1073                && let Some(op) = state.base_sync_recovery.operations.last_mut()
1074                && !op.finished
1075                && op.head == orig
1076                && op.tip == onto_sha
1077            {
1078                op.validated_head = Some(head.clone());
1079                state.save()?;
1080            }
1081            git::worktree_remove(&repo, scratch).await.ok();
1082            state.event(
1083                "rebase",
1084                format!("{branch} rebased after {spent} fixer round(s)"),
1085            );
1086            state.save()?;
1087            Ok(Rebased::Applied)
1088        }
1089        Some((what, paths)) => {
1090            let why = reason(spent, cap, &paths, said, what);
1091            abandon(&repo, scratch, branch, orig).await;
1092            Ok(Rebased::Stopped(why))
1093        }
1094    }
1095}
1096
1097/// Only a pick whose exec observed the previous HEAD could have been skipped.
1098/// Content checks distinguish a genuine loss from a change already upstream.
1099async fn dropped_commits(
1100    repo: &Path,
1101    scratch: &Path,
1102    onto_sha: &str,
1103    orig: &str,
1104    head: &str,
1105) -> Result<Vec<String>> {
1106    let record = git::rebase_record(scratch).await?;
1107    anyhow::ensure!(
1108        record.heads.last().map(String::as_str) == Some(head),
1109        "rebase final HEAD disagrees with record"
1110    );
1111    let mut previous = onto_sha;
1112    let mut lost = Vec::new();
1113    for (sha, picked_head) in record.picks.iter().zip(&record.heads) {
1114        if picked_head == previous
1115            && !absorbed_in_result(repo, sha, onto_sha, orig, head).await?
1116            && !already_in_result(repo, sha, orig, head).await?
1117        {
1118            lost.push(git::git(repo, &["show", "-s", "--format=%s", sha]).await?);
1119        }
1120        previous = picked_head;
1121    }
1122    Ok(lost)
1123}
1124
1125/// Paths `sha` changes, NUL-separated from git so a quoted name is never
1126/// misread. Read failures propagate to the rebase verdict.
1127async fn commit_paths(repo: &Path, sha: &str) -> Result<Vec<String>> {
1128    git::git(
1129        repo,
1130        &[
1131            "diff-tree",
1132            "--no-commit-id",
1133            "--name-only",
1134            "-r",
1135            "--root",
1136            "-z",
1137            sha,
1138        ],
1139    )
1140    .await
1141    .map(|o| {
1142        o.split('\0')
1143            .filter(|l| !l.is_empty())
1144            .map(str::to_owned)
1145            .collect()
1146    })
1147}
1148
1149/// `mode type blob` of `path` at `rev`, or `None` when it does not exist
1150/// there. Unlike `rev-parse rev:path` this carries the file mode.
1151async fn entry(repo: &Path, rev: &str, path: &str) -> Result<Option<String>> {
1152    let out = git::git(repo, &["--literal-pathspecs", "ls-tree", rev, "--", path]).await?;
1153    Ok(out
1154        .split('\t')
1155        .next()
1156        .filter(|e| !e.is_empty())
1157        .map(str::to_owned))
1158}
1159
1160/// Is `sha`'s change represented in `head`?
1161///
1162/// First by merging: replaying `sha` onto `head` changes nothing when its
1163/// change is already there, in whatever company (extra upstream edits in the
1164/// same file included). Failing that, per touched path: `head` holds what
1165/// `sha` left there, or what the branch's final tip `orig` has there (a later
1166/// commit may have changed the path again). Mode is part of that comparison,
1167/// and paths come NUL-separated so a quoted name is never misread.
1168async fn already_in_result(repo: &Path, sha: &str, orig: &str, head: &str) -> Result<bool> {
1169    if replay_is_noop(repo, sha, head).await? {
1170        return Ok(true);
1171    }
1172    for p in &commit_paths(repo, sha).await? {
1173        let got = entry(repo, head, p).await?;
1174        if got != entry(repo, sha, p).await? && got != entry(repo, orig, p).await? {
1175            return Ok(false);
1176        }
1177    }
1178    Ok(true)
1179}
1180
1181/// Does merging `sha` (against its parent) into `head` cleanly yield `head`'s
1182/// own tree? Conflicts and changes return false; read failures propagate.
1183async fn replay_is_noop(repo: &Path, sha: &str, head: &str) -> Result<bool> {
1184    let base = format!("{sha}^");
1185    let out = git::git_raw(
1186        repo,
1187        &[
1188            "merge-tree",
1189            "--write-tree",
1190            &format!("--merge-base={base}"),
1191            head,
1192            sha,
1193        ],
1194    )
1195    .await?;
1196    anyhow::ensure!(
1197        out.code == Some(0) || out.code == Some(1),
1198        "merge-tree failed: {}",
1199        out.stderr
1200    );
1201    if !out.ok() {
1202        return Ok(false);
1203    }
1204    let merged = out
1205        .stdout
1206        .lines()
1207        .next()
1208        .context("merge-tree returned no tree")?
1209        .trim();
1210    Ok(merged == git::tree_of(repo, head).await?)
1211}
1212
1213/// An absorbed change may be superseded by later branch commits, so replaying
1214/// it alone onto the result can conflict. Starting at `sha`, merge only those
1215/// later changes with the base and require every path `sha` touched to match
1216/// the result (including modes). Project all four trees onto just those paths
1217/// first: conflicts elsewhere cannot invalidate this commit's surviving effect.
1218/// A conflict on a candidate path or a failed lookup is not evidence of survival.
1219async fn absorbed_in_result(
1220    repo: &Path,
1221    sha: &str,
1222    onto: &str,
1223    orig: &str,
1224    head: &str,
1225) -> Result<bool> {
1226    if !replay_is_noop(repo, sha, onto).await? {
1227        return Ok(false);
1228    }
1229    let paths = commit_paths(repo, sha).await?;
1230    if paths.is_empty() {
1231        return Ok(false);
1232    }
1233    let base = path_tree(repo, sha, &paths).await?;
1234    let upstream = path_tree(repo, onto, &paths).await?;
1235    let branch = path_tree(repo, orig, &paths).await?;
1236    let result = path_tree(repo, head, &paths).await?;
1237    let out = git::git_raw(
1238        repo,
1239        &[
1240            "merge-tree",
1241            "--write-tree",
1242            &format!("--merge-base={base}"),
1243            &upstream,
1244            &branch,
1245        ],
1246    )
1247    .await?;
1248    anyhow::ensure!(
1249        out.code == Some(0) || out.code == Some(1),
1250        "merge-tree failed: {}",
1251        out.stderr
1252    );
1253    if !out.ok() {
1254        return Ok(false);
1255    }
1256    Ok(out
1257        .stdout
1258        .lines()
1259        .next()
1260        .context("merge-tree returned no tree")?
1261        == result)
1262}
1263
1264/// A tree containing only the candidate paths, under stable synthetic names.
1265/// Preserve each entry's object and mode, and leave missing entries absent.
1266/// Flattening the names lets mktree handle nested and unusual paths without
1267/// an index or a working tree, and keeps unrelated paths out of the merge.
1268async fn path_tree(repo: &Path, rev: &str, paths: &[String]) -> Result<String> {
1269    use crate::proc::Quiet as _;
1270    use std::fmt::Write as _;
1271    use std::process::Stdio;
1272    use tokio::io::AsyncWriteExt as _;
1273
1274    let mut entries = String::new();
1275    for (i, path) in paths.iter().enumerate() {
1276        let out = git::git(
1277            repo,
1278            &["--literal-pathspecs", "ls-tree", "-z", rev, "--", path],
1279        )
1280        .await?;
1281        if !out.is_empty() {
1282            let (entry, _) = out
1283                .split_once('\t')
1284                .context("ls-tree returned an invalid entry")?;
1285            writeln!(entries, "{entry}\t{i:016x}")?;
1286        }
1287    }
1288    #[cfg(test)]
1289    crate::web::request_cost::git();
1290    let mut child = tokio::process::Command::new("git")
1291        .args(["mktree"])
1292        .current_dir(repo)
1293        .quiet()
1294        .stdin(Stdio::piped())
1295        .stdout(Stdio::piped())
1296        .stderr(Stdio::piped())
1297        .kill_on_drop(true)
1298        .spawn()?;
1299    let mut stdin = child.stdin.take().context("mktree stdin missing")?;
1300    stdin.write_all(entries.as_bytes()).await?;
1301    drop(stdin);
1302    let out = child.wait_with_output().await?;
1303    anyhow::ensure!(
1304        out.status.success(),
1305        "mktree failed: {}",
1306        String::from_utf8_lossy(&out.stderr)
1307    );
1308    Ok(String::from_utf8(out.stdout)?.trim().to_owned())
1309}
1310
1311/// Give up: abort whatever is standing, drop the worktree and put the branch
1312/// ref back where it was, whatever a fixer did to it.
1313async fn abandon(repo: &Path, scratch: &Path, branch: &str, orig: &str) {
1314    git::rebase_abort(repo, scratch).await;
1315    let full = format!("refs/heads/{branch}");
1316    if git::rev_parse(repo, &full).await.ok().as_deref() != Some(orig) {
1317        git::git_raw(repo, &["update-ref", &full, orig]).await.ok();
1318    }
1319}
1320
1321/// The reason a caller records and the conductor quotes: it says what was
1322/// tried, so nobody has to open the run directory to find out.
1323fn reason(spent: usize, cap: usize, paths: &[String], said: &str, what: &str) -> String {
1324    let shown: Vec<&str> = paths
1325        .iter()
1326        .take(PATHS_IN_REASON)
1327        .map(String::as_str)
1328        .collect();
1329    let mut list = shown.join(", ");
1330    if paths.len() > shown.len() {
1331        list.push_str(&format!(" and {} more", paths.len() - shown.len()));
1332    }
1333    if list.is_empty() {
1334        list.push_str("none recorded");
1335    }
1336    let mut s = format!(
1337        "conflict not resolved after {spent} of {cap} fixer round(s) ({what}); remaining \
1338         conflicted path(s): {list}"
1339    );
1340    let said = git::rebase_said(said);
1341    let said = said.trim();
1342    if !said.is_empty() {
1343        s.push_str("; git said: ");
1344        s.extend(said.chars().take(250));
1345    }
1346    s
1347}
1348
1349/// Commit subjects in `range`, newest first, capped.
1350async fn subjects(worktree: &Path, range: &str) -> Vec<String> {
1351    let n = format!("-n{SUBJECTS}");
1352    git::git(worktree, &["log", "--format=%s", &n, range])
1353        .await
1354        .map(|o| o.lines().map(str::to_owned).collect())
1355        .unwrap_or_default()
1356}
1357
1358/// A separator alone is ambiguous (for example a Setext heading). Allow
1359/// separators already present under the same heading on either side, while
1360/// rejecting new ones left by a resolution. Opening, closing and diff3 markers stand on their own.
1361pub(crate) async fn has_markers(worktree: &Path, path: &str, sides: &[&str]) -> Result<bool> {
1362    let Ok(text) = std::fs::read_to_string(worktree.join(path)) else {
1363        return Ok(false);
1364    };
1365    if text
1366        .lines()
1367        .any(|l| l.starts_with("<<<<<<<") || l.starts_with(">>>>>>>") || l.starts_with("|||||||"))
1368    {
1369        return Ok(true);
1370    }
1371    fn separators(text: &str) -> std::collections::BTreeMap<String, usize> {
1372        let mut counts = std::collections::BTreeMap::new();
1373        let mut previous = "";
1374        for line in text.lines() {
1375            if line == "=======" {
1376                *counts.entry(previous.to_owned()).or_default() += 1;
1377            }
1378            previous = line;
1379        }
1380        counts
1381    }
1382    let current = separators(&text);
1383    if current.is_empty() {
1384        return Ok(false);
1385    }
1386    let mut existing = std::collections::BTreeMap::<String, usize>::new();
1387    for side in sides {
1388        // A missing file is expected for add/add conflicts. Other failures
1389        // must not be interpreted as an empty baseline.
1390        let spec = format!("{side}:{path}");
1391        let exists = git::git_raw(worktree, &["cat-file", "-e", &spec]).await?;
1392        if exists.ok() {
1393            for (heading, count) in separators(&git::git(worktree, &["show", &spec]).await?) {
1394                let before = existing.entry(heading).or_default();
1395                *before = (*before).max(count);
1396            }
1397        } else {
1398            // Verify the tree itself remains readable before treating a
1399            // missing entry as an empty side.
1400            git::rev_parse(worktree, &format!("{side}^{{tree}}")).await?;
1401        }
1402    }
1403    Ok(current
1404        .into_iter()
1405        .any(|(heading, count)| count > existing.get(&heading).copied().unwrap_or(0)))
1406}
1407
1408/// The conflicted regions of `paths`, marker lines included, truncated. This
1409/// only *shows* the conflict; nothing here decides how to resolve it.
1410fn hunks(worktree: &Path, paths: &[String]) -> String {
1411    let mut out = String::new();
1412    for p in paths {
1413        if out.len() >= HUNK_TOTAL {
1414            out.push_str("\n(more conflicted files omitted)\n");
1415            break;
1416        }
1417        out.push_str(&format!("=== {p} ===\n"));
1418        let Ok(text) = std::fs::read_to_string(worktree.join(p)) else {
1419            out.push_str("(not readable as text; use git to inspect it)\n");
1420            continue;
1421        };
1422        let mut file = String::new();
1423        let mut inside = false;
1424        for line in text.lines() {
1425            if line.starts_with("<<<<<<< ") {
1426                inside = true;
1427            }
1428            if inside {
1429                file.push_str(line);
1430                file.push('\n');
1431            }
1432            if line.starts_with(">>>>>>> ") {
1433                inside = false;
1434            }
1435        }
1436        if file.len() > HUNK_PER_FILE {
1437            file = file.chars().take(HUNK_PER_FILE).collect();
1438            file.push_str("\n(truncated)\n");
1439        }
1440        out.push_str(&file);
1441    }
1442    out
1443}
1444
1445#[cfg(test)]
1446mod tests {
1447    use super::*;
1448    use crate::proc::Quiet as _;
1449    use std::path::PathBuf;
1450
1451    fn sh(dir: &Path, args: &[&str]) {
1452        let o = std::process::Command::new("git")
1453            .quiet()
1454            .args(args)
1455            .current_dir(dir)
1456            .output()
1457            .unwrap();
1458        assert!(
1459            o.status.success(),
1460            "{args:?}: {}",
1461            String::from_utf8_lossy(&o.stderr)
1462        );
1463    }
1464
1465    async fn record(d: &Path, picks: &[String], heads: &[String]) {
1466        for (name, values) in [("magi-rebase-picks", picks), ("magi-rebase-heads", heads)] {
1467            let path = git::git(d, &["rev-parse", "--git-path", name])
1468                .await
1469                .unwrap();
1470            std::fs::write(d.join(path), values.join("\n") + "\n").unwrap();
1471        }
1472    }
1473
1474    #[tokio::test]
1475    async fn a_lost_mode_change_is_not_already_in_the_result() {
1476        let t = tempfile::tempdir().unwrap();
1477        let d = t.path();
1478        sh(d, &["init", "-q", "-b", "main"]);
1479        sh(d, &["config", "user.name", "t"]);
1480        sh(d, &["config", "user.email", "t@example.com"]);
1481        sh(d, &["config", "core.fileMode", "true"]);
1482        std::fs::write(d.join("script.sh"), "echo\n").unwrap();
1483        sh(d, &["add", "-A"]);
1484        sh(d, &["commit", "-q", "-m", "base"]);
1485        sh(d, &["update-index", "--chmod=+x", "script.sh"]);
1486        sh(d, &["commit", "-q", "-m", "chmod"]);
1487        let sha = git::git(d, &["rev-parse", "HEAD"]).await.unwrap();
1488        let base = git::git(d, &["rev-parse", "HEAD~1"]).await.unwrap();
1489        // The result is the base: same blob, lost mode.
1490        assert!(!already_in_result(d, &sha, &sha, &base).await.unwrap());
1491        assert!(already_in_result(d, &sha, &sha, &sha).await.unwrap());
1492    }
1493
1494    async fn commit(d: &Path, msg: &str) -> String {
1495        sh(d, &["add", "-A"]);
1496        sh(d, &["commit", "-q", "-m", msg]);
1497        git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
1498    }
1499
1500    #[tokio::test]
1501    async fn rebase_preparation_reports_git_rejection_before_using_scratch() {
1502        let t = tempfile::tempdir().unwrap();
1503        let d = t.path();
1504        sh(d, &["init", "-q", "-b", "main"]);
1505        let scratch = d.join("scratch");
1506        let error = git::rebase_start(d, &scratch, "missing-branch", "main")
1507            .await
1508            .unwrap_err();
1509        assert!(error.is::<git::RebasePreparationError>());
1510        let why = error.to_string();
1511        assert!(why.contains("worktree add --force"), "{why}");
1512        assert!(why.contains("missing-branch"), "{why}");
1513        assert!(why.contains("fatal:"), "{why}");
1514        assert!(why.contains("exit Some("), "{why}");
1515        assert!(!why.contains("rev-parse"), "{why}");
1516        assert!(!scratch.exists());
1517    }
1518
1519    #[tokio::test]
1520    async fn rebase_canonical_scratch_with_checked_out_winner() {
1521        let t = tempfile::tempdir().unwrap();
1522        let d = t.path().canonicalize().unwrap();
1523        sh(&d, &["init", "-q", "-b", "main"]);
1524        sh(&d, &["config", "user.name", "t"]);
1525        sh(&d, &["config", "user.email", "t@example.com"]);
1526        std::fs::write(d.join("base"), "base\n").unwrap();
1527        let base = commit(&d, "base").await;
1528        sh(&d, &["checkout", "-qb", "winner"]);
1529        std::fs::write(d.join("change"), "change\n").unwrap();
1530        commit(&d, "winner").await;
1531        sh(&d, &["checkout", "main"]);
1532        std::fs::write(d.join("advance"), "advance\n").unwrap();
1533        let onto = commit(&d, "advance").await;
1534        let winner = d.join("winner-tree");
1535        git::git(&d, &["worktree", "add", &git::path_arg(&winner), "winner"])
1536            .await
1537            .unwrap();
1538        let scratch = d.join("scratch");
1539        #[cfg(windows)]
1540        {
1541            let out = git::git_raw(
1542                &d,
1543                &[
1544                    "worktree",
1545                    "add",
1546                    "--force",
1547                    &scratch.to_string_lossy(),
1548                    "winner",
1549                ],
1550            )
1551            .await
1552            .unwrap();
1553            assert!(!out.ok(), "{out:?}");
1554            assert!(!scratch.exists());
1555            eprintln!("verbatim worktree add rejection: {}", out.stderr);
1556        }
1557        assert_eq!(
1558            git::rebase_start(&d, &scratch, "winner", &onto)
1559                .await
1560                .unwrap(),
1561            git::RebaseStart::Applied
1562        );
1563        git::sync_to_head(&winner).await.unwrap();
1564        assert!(git::is_ancestor(&d, &onto, "winner").await);
1565        assert!(git::is_ancestor(&d, &base, "winner").await);
1566        assert_eq!(
1567            std::fs::read_to_string(winner.join("change"))
1568                .unwrap()
1569                .replace("\r\n", "\n"),
1570            "change\n"
1571        );
1572        assert_eq!(
1573            std::fs::read_to_string(winner.join("advance"))
1574                .unwrap()
1575                .replace("\r\n", "\n"),
1576            "advance\n"
1577        );
1578        assert!(git::is_clean(&winner).await.unwrap());
1579        assert!(!scratch.exists());
1580    }
1581
1582    #[tokio::test]
1583    async fn candidate_path_trees_preserve_modes_deletions_and_unusual_names() {
1584        let t = tempfile::tempdir().unwrap();
1585        let d = t.path();
1586        sh(d, &["init", "-q", "-b", "main"]);
1587        sh(d, &["config", "user.name", "t"]);
1588        sh(d, &["config", "user.email", "t@example.com"]);
1589        sh(d, &["config", "core.fileMode", "true"]);
1590        let path = if cfg!(windows) {
1591            "nested/日本語 [literal].txt"
1592        } else {
1593            "nested/日本語\tline\n.txt"
1594        };
1595        std::fs::create_dir(d.join("nested")).unwrap();
1596        std::fs::write(d.join(path), "contents\n").unwrap();
1597        std::fs::write(d.join("g.txt"), "old\n").unwrap();
1598        let base = commit(d, "base").await;
1599        let paths = vec![path.to_owned()];
1600        let tree = path_tree(d, &base, &paths).await.unwrap();
1601        std::fs::write(d.join("g.txt"), "unrelated\n").unwrap();
1602        let other = commit(d, "unrelated path").await;
1603        assert_eq!(path_tree(d, &other, &paths).await.unwrap(), tree);
1604        sh(d, &["update-index", "--chmod=+x", path]);
1605        sh(d, &["commit", "-q", "-m", "chmod"]);
1606        assert_ne!(path_tree(d, "HEAD", &paths).await.unwrap(), tree);
1607        std::fs::remove_file(d.join(path)).unwrap();
1608        let removed = commit(d, "delete").await;
1609        let absent = path_tree(d, &removed, &paths).await.unwrap();
1610        assert_ne!(absent, tree);
1611        assert_eq!(absent, path_tree(d, &removed, &[]).await.unwrap());
1612        assert!(path_tree(d, "not-a-revision", &paths).await.is_err());
1613    }
1614
1615    #[tokio::test]
1616    async fn a_change_inside_a_larger_upstream_edit_is_in_the_result() {
1617        let t = tempfile::tempdir().unwrap();
1618        let d = t.path();
1619        sh(d, &["init", "-q", "-b", "main"]);
1620        sh(d, &["config", "user.name", "t"]);
1621        sh(d, &["config", "user.email", "t@example.com"]);
1622        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
1623        std::fs::write(d.join("f.txt"), body).unwrap();
1624        commit(d, "base").await;
1625        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
1626        let c = commit(d, "c1").await;
1627        sh(d, &["checkout", "-q", "-b", "up", "HEAD~1"]);
1628        let up = body.replacen("old", "new", 1).replace("end", "end plus");
1629        std::fs::write(d.join("f.txt"), up).unwrap();
1630        let head = commit(d, "upstream").await;
1631        assert!(already_in_result(d, &c, &c, &head).await.unwrap());
1632    }
1633
1634    #[tokio::test]
1635    async fn a_dropped_commit_on_a_non_ascii_path_is_still_noticed() {
1636        let t = tempfile::tempdir().unwrap();
1637        let d = t.path();
1638        sh(d, &["init", "-q", "-b", "main"]);
1639        sh(d, &["config", "user.name", "t"]);
1640        sh(d, &["config", "user.email", "t@example.com"]);
1641        std::fs::write(d.join("a.txt"), "a\n").unwrap();
1642        let base = commit(d, "base").await;
1643        std::fs::write(d.join("日本語.txt"), "x\n").unwrap();
1644        let c = commit(d, "c").await;
1645        assert!(!already_in_result(d, &c, &c, &base).await.unwrap());
1646    }
1647
1648    async fn commit_dated(d: &Path, msg: &str) -> String {
1649        sh(d, &["add", "-A"]);
1650        let st = std::process::Command::new("git")
1651            .quiet()
1652            .current_dir(d)
1653            .env("GIT_AUTHOR_DATE", "2020-01-01T00:00:00+0000")
1654            .env("GIT_COMMITTER_DATE", "2020-01-01T00:00:00+0000")
1655            .args(["commit", "-q", "-m", msg])
1656            .status()
1657            .unwrap();
1658        assert!(st.success());
1659        git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
1660    }
1661
1662    #[tokio::test]
1663    async fn a_recorded_resolved_pick_after_an_absorbed_one_is_not_lost() {
1664        let t = tempfile::tempdir().unwrap();
1665        let d = t.path();
1666        sh(d, &["init", "-q", "-b", "main"]);
1667        sh(d, &["config", "user.name", "t"]);
1668        sh(d, &["config", "user.email", "t@example.com"]);
1669        std::fs::write(d.join("z.txt"), "z\n").unwrap();
1670        let base = commit(d, "base").await;
1671        std::fs::write(d.join("a.txt"), "a\n").unwrap();
1672        commit_dated(d, "same").await;
1673        std::fs::write(d.join("b.txt"), "b\n").unwrap();
1674        let orig = commit_dated(d, "same").await;
1675        // Upstream folds the first change into a differently-shaped commit
1676        // and adds a conflicting b.txt.
1677        sh(d, &["checkout", "-q", "-b", "up", &base]);
1678        std::fs::write(d.join("a.txt"), "a\n").unwrap();
1679        std::fs::write(d.join("y.txt"), "y\n").unwrap();
1680        std::fs::write(d.join("b.txt"), "other\n").unwrap();
1681        let onto = commit(d, "upstream").await;
1682        // The rebase result: first commit omitted as empty, second resolved.
1683        std::fs::write(d.join("b.txt"), "other\nb\n").unwrap();
1684        let head = commit_dated(d, "same").await;
1685        record(
1686            d,
1687            &[
1688                git::rev_parse(d, &format!("{orig}^")).await.unwrap(),
1689                orig.clone(),
1690            ],
1691            &[onto.clone(), head.clone()],
1692        )
1693        .await;
1694        assert!(
1695            dropped_commits(d, d, &onto, &orig, &head)
1696                .await
1697                .unwrap()
1698                .is_empty()
1699        );
1700    }
1701
1702    #[tokio::test]
1703    async fn a_skipped_commit_is_not_masked_by_a_surviving_one_in_the_same_file() {
1704        let t = tempfile::tempdir().unwrap();
1705        let d = t.path();
1706        sh(d, &["init", "-q", "-b", "main"]);
1707        sh(d, &["config", "user.name", "t"]);
1708        sh(d, &["config", "user.email", "t@example.com"]);
1709        let body = "first\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
1710        std::fs::write(d.join("f.txt"), body).unwrap();
1711        let base = commit(d, "base").await;
1712        std::fs::write(d.join("f.txt"), body.replacen("first", "mine", 1)).unwrap();
1713        commit_dated(d, "same").await;
1714        let two = body
1715            .replacen("first", "mine", 1)
1716            .replacen("last", "tail", 1);
1717        std::fs::write(d.join("f.txt"), &two).unwrap();
1718        let orig = commit_dated(d, "same").await;
1719        sh(d, &["checkout", "-q", "-b", "up", &base]);
1720        std::fs::write(d.join("f.txt"), body.replacen("first", "theirs", 1)).unwrap();
1721        let onto = commit(d, "upstream").await;
1722        // First commit skipped, second applied untouched.
1723        std::fs::write(
1724            d.join("f.txt"),
1725            body.replacen("first", "theirs", 1)
1726                .replacen("last", "tail", 1),
1727        )
1728        .unwrap();
1729        let head = commit_dated(d, "same").await;
1730        record(
1731            d,
1732            &[
1733                git::rev_parse(d, &format!("{orig}^")).await.unwrap(),
1734                orig.clone(),
1735            ],
1736            &[onto.clone(), head.clone()],
1737        )
1738        .await;
1739        assert_eq!(
1740            dropped_commits(d, d, &onto, &orig, &head).await.unwrap(),
1741            vec!["same"]
1742        );
1743    }
1744
1745    #[tokio::test]
1746    async fn git_records_a_skipped_middle_pick_after_an_applied_pick() {
1747        let t = tempfile::tempdir().unwrap();
1748        let d = t.path();
1749        sh(d, &["init", "-q", "-b", "main"]);
1750        sh(d, &["config", "user.name", "t"]);
1751        sh(d, &["config", "user.email", "t@example.com"]);
1752        std::fs::write(d.join("f"), "base\n").unwrap();
1753        let base = commit(d, "base").await;
1754        sh(d, &["checkout", "-q", "-b", "topic"]);
1755        std::fs::write(d.join("absorbed"), "upstream too\n").unwrap();
1756        commit(d, "already upstream").await;
1757        std::fs::write(d.join("a"), "first\n").unwrap();
1758        let first = commit(d, "first").await;
1759        std::fs::write(d.join("f"), "middle\n").unwrap();
1760        let middle = commit(d, "lost middle").await;
1761        std::fs::write(d.join("z"), "last\n").unwrap();
1762        let orig = commit(d, "last").await;
1763        sh(d, &["checkout", "-q", "main"]);
1764        std::fs::write(d.join("absorbed"), "upstream too\n").unwrap();
1765        commit(d, "patch twin").await;
1766        std::fs::write(d.join("f"), "upstream\n").unwrap();
1767        let onto = commit(d, "upstream").await;
1768        let scratch = d.join("scratch");
1769        let git::RebaseStart::Conflicted(why) = git::rebase_start(d, &scratch, "topic", &onto)
1770            .await
1771            .unwrap()
1772        else {
1773            panic!("expected a conflict");
1774        };
1775        assert!(!why.contains("Executing:"), "{why}");
1776        let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
1777        assert!(skipped.ok(), "{}", skipped.stderr);
1778        let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
1779        let record = git::rebase_record(&scratch).await.unwrap();
1780        assert_eq!(record.picks, vec![first, middle, orig.clone()]);
1781        assert_eq!(record.heads[0], record.heads[1]);
1782        assert_ne!(record.heads[1], record.heads[2]);
1783        assert_eq!(
1784            dropped_commits(d, &scratch, &onto, &orig, &head)
1785                .await
1786                .unwrap(),
1787            vec!["lost middle"]
1788        );
1789        git::rebase_abort(d, &scratch).await;
1790        assert!(git::is_ancestor(d, &base, &head).await);
1791    }
1792
1793    #[test]
1794    fn recording_diagnostics_do_not_hide_other_git_output() {
1795        assert_eq!(
1796            git::rebase_said("before\nExecuting: record\nafter\n"),
1797            "before\nafter"
1798        );
1799    }
1800
1801    // Exercise the actual rebase and finish path. C0 conflicts in another
1802    // file; C1 and C2 successively change the first line of f.txt. Upstream
1803    // also changes a distant line, so neither C1 nor the original tip has
1804    // the result's whole-file snapshot.
1805    async fn rebase_successive_edits(
1806        absorbed: bool,
1807        extra_hunk: bool,
1808        unrelated_conflict: bool,
1809    ) -> Rebased {
1810        rebase_successive_edits_record(absorbed, extra_hunk, unrelated_conflict, None).await
1811    }
1812
1813    async fn rebase_successive_edits_record(
1814        absorbed: bool,
1815        extra_hunk: bool,
1816        unrelated_conflict: bool,
1817        damage: Option<&str>,
1818    ) -> Rebased {
1819        crate::run::pin_test_home();
1820        let t = tempfile::tempdir().unwrap();
1821        let d = t.path();
1822        sh(d, &["init", "-q", "-b", "main"]);
1823        sh(d, &["config", "user.name", "t"]);
1824        sh(d, &["config", "user.email", "t@example.com"]);
1825        // Keep Git checkouts consistent with this fixture's LF byte strings,
1826        // even when the host enables automatic CRLF conversion.
1827        sh(d, &["config", "core.autocrlf", "false"]);
1828        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
1829        std::fs::write(d.join("f.txt"), body).unwrap();
1830        std::fs::write(d.join("conflict.txt"), "old\n").unwrap();
1831        if unrelated_conflict {
1832            std::fs::write(d.join("g.txt"), "old\n").unwrap();
1833        }
1834        let base = commit(d, "base").await;
1835        sh(d, &["checkout", "-q", "-b", "topic"]);
1836        std::fs::write(d.join("conflict.txt"), "branch\n").unwrap();
1837        commit(d, "c0").await;
1838        let mut middle = body.replacen("old", "new", 1);
1839        if extra_hunk {
1840            middle = middle.replace("\n5\n", "\nmissing\n");
1841        }
1842        std::fs::write(d.join("f.txt"), &middle).unwrap();
1843        let c1 = commit(d, "c1").await;
1844        std::fs::write(d.join("f.txt"), middle.replacen("new", "newer", 1)).unwrap();
1845        if unrelated_conflict {
1846            std::fs::write(d.join("g.txt"), "branch\n").unwrap();
1847        }
1848        let orig = commit(d, "c2").await;
1849        sh(d, &["checkout", "-q", "main"]);
1850        std::fs::write(d.join("conflict.txt"), "branch plus upstream\n").unwrap();
1851        let mut upstream = body
1852            .replacen("old", if absorbed { "new" } else { "theirs" }, 1)
1853            .replace("end", "upstream tail");
1854        if extra_hunk {
1855            upstream = upstream.replace("\n5\n", "\nupstream middle\n");
1856        }
1857        std::fs::write(d.join("f.txt"), &upstream).unwrap();
1858        if unrelated_conflict {
1859            std::fs::write(d.join("g.txt"), "upstream\n").unwrap();
1860        }
1861        let onto = commit(d, "upstream composite").await;
1862        // The composite has no patch-id twin for C1.
1863        assert!(git::cherry(d, &onto, &orig).await.unwrap().0.contains(&c1));
1864        let scratch = d.join("scratch");
1865        assert!(matches!(
1866            git::rebase_start(d, &scratch, "topic", &onto)
1867                .await
1868                .unwrap(),
1869            git::RebaseStart::Conflicted(_)
1870        ));
1871        std::fs::write(
1872            scratch.join("conflict.txt"),
1873            "branch plus upstream resolved\n",
1874        )
1875        .unwrap();
1876        sh(&scratch, &["add", "conflict.txt"]);
1877        let continued = git::git_raw(
1878            &scratch,
1879            &["-c", "core.editor=true", "rebase", "--continue"],
1880        )
1881        .await
1882        .unwrap();
1883        if absorbed && !extra_hunk {
1884            // C1 becomes empty automatically. C2 may conflict on a path C1
1885            // never touched, while its f.txt change has applied correctly.
1886            if unrelated_conflict {
1887                assert!(!continued.ok());
1888                assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), vec!["g.txt"]);
1889                assert_eq!(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap(), orig);
1890                std::fs::write(scratch.join("g.txt"), "branch plus upstream resolved\n").unwrap();
1891                sh(&scratch, &["add", "g.txt"]);
1892                let resolved = git::git_raw(&scratch, &["rebase", "--continue"])
1893                    .await
1894                    .unwrap();
1895                assert!(resolved.ok(), "{}", resolved.stderr);
1896                // A whole-tree merge would reject the correctly rebased C1
1897                // solely because of the unrelated g.txt conflict.
1898                let full = git::git_raw(
1899                    d,
1900                    &[
1901                        "merge-tree",
1902                        "--write-tree",
1903                        &format!("--merge-base={c1}"),
1904                        &onto,
1905                        &orig,
1906                    ],
1907                )
1908                .await
1909                .unwrap();
1910                assert_eq!(full.code, Some(1));
1911            } else {
1912                assert!(continued.ok(), "{}", continued.stderr);
1913            }
1914        } else {
1915            assert!(!continued.ok());
1916            assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), vec!["f.txt"]);
1917            let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
1918            if !absorbed {
1919                // C2 now conflicts because its predecessor was really skipped.
1920                assert!(!skipped.ok());
1921                std::fs::write(
1922                    scratch.join("f.txt"),
1923                    upstream.replacen("theirs", "newer", 1),
1924                )
1925                .unwrap();
1926                sh(&scratch, &["add", "f.txt"]);
1927                let resolved = git::git_raw(
1928                    &scratch,
1929                    &["-c", "core.editor=true", "rebase", "--continue"],
1930                )
1931                .await
1932                .unwrap();
1933                assert!(resolved.ok(), "{}", resolved.stderr);
1934            } else {
1935                assert!(skipped.ok(), "{}", skipped.stderr);
1936            }
1937        }
1938        assert!(!git::rebase_in_progress(&scratch).await);
1939        assert_eq!(
1940            std::fs::read_to_string(scratch.join("f.txt")).unwrap(),
1941            upstream.replacen(if absorbed { "new" } else { "theirs" }, "newer", 1)
1942        );
1943        let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
1944        // The old final-tree-only check cannot account for C1 in any case.
1945        assert!(!already_in_result(d, &c1, &orig, &head).await.unwrap());
1946        let mut state = RunState::new(
1947            d.to_path_buf(),
1948            "main".into(),
1949            base,
1950            "rebase".into(),
1951            crate::config::Config::default(),
1952        );
1953        if let Some(damage) = damage {
1954            let path = git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
1955                .await
1956                .unwrap();
1957            match damage {
1958                "missing" => std::fs::remove_file(&path).unwrap(),
1959                "count" => std::fs::write(&path, "").unwrap(),
1960                "final" => {
1961                    let text = std::fs::read_to_string(&path).unwrap();
1962                    let mut heads: Vec<_> = text.lines().map(str::to_owned).collect();
1963                    *heads.last_mut().unwrap() = onto.clone();
1964                    std::fs::write(&path, heads.join("\n") + "\n").unwrap();
1965                }
1966                "invalid" => std::fs::write(&path, "invalid\n").unwrap(),
1967                _ => unreachable!(),
1968            }
1969        }
1970        let outcome = finish(
1971            &mut state,
1972            &scratch,
1973            "topic",
1974            &orig,
1975            &onto,
1976            &["conflict.txt".into()],
1977            "",
1978        )
1979        .await
1980        .unwrap();
1981        std::fs::remove_dir_all(state.dir()).ok();
1982        outcome
1983    }
1984
1985    #[tokio::test]
1986    async fn missing_or_inconsistent_rebase_records_stop_the_rebase() {
1987        for damage in ["missing", "count", "final", "invalid"] {
1988            let outcome = rebase_successive_edits_record(true, false, false, Some(damage)).await;
1989            assert!(
1990                matches!(outcome, Rebased::Stopped(why) if why.contains("record could not be verified")),
1991                "{damage}"
1992            );
1993        }
1994    }
1995
1996    #[tokio::test]
1997    async fn an_absorbed_middle_commit_superseded_by_a_later_edit_is_applied() {
1998        assert_eq!(
1999            rebase_successive_edits(true, false, false).await,
2000            Rebased::Applied
2001        );
2002    }
2003
2004    #[tokio::test]
2005    async fn an_unrelated_later_conflict_does_not_hide_an_absorbed_commit() {
2006        assert_eq!(
2007            rebase_successive_edits(true, false, true).await,
2008            Rebased::Applied
2009        );
2010    }
2011
2012    #[tokio::test]
2013    async fn a_skipped_middle_commit_superseded_by_a_later_edit_is_dropped() {
2014        let Rebased::Stopped(why) = rebase_successive_edits(false, false, false).await else {
2015            panic!("a skipped middle commit must stop the rebase");
2016        };
2017        assert!(why.contains("the rebase dropped some of the branch's commits (skipped?)"));
2018        assert!(why.contains("c1"));
2019    }
2020
2021    #[tokio::test]
2022    async fn a_partially_absorbed_middle_commit_with_a_skipped_hunk_is_dropped() {
2023        let Rebased::Stopped(why) = rebase_successive_edits(true, true, false).await else {
2024            panic!("an unabsorbed hunk must stop the rebase");
2025        };
2026        assert!(why.contains("the rebase dropped some of the branch's commits (skipped?)"));
2027        assert!(why.contains("c1"));
2028    }
2029
2030    #[tokio::test]
2031    async fn an_absorbed_commit_erased_by_the_fixer_is_dropped() {
2032        crate::run::pin_test_home();
2033        let t = tempfile::tempdir().unwrap();
2034        let d = t.path();
2035        sh(d, &["init", "-q", "-b", "main"]);
2036        sh(d, &["config", "user.name", "t"]);
2037        sh(d, &["config", "user.email", "t@example.com"]);
2038        // This fixture controls each resolution itself; inherited rerere can
2039        // interfere with that sequence (including MERGE_RR lock contention).
2040        sh(d, &["config", "rerere.enabled", "false"]);
2041        let body =
2042            "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlater\n10\n11\n12\n13\n14\n15\n16\n17\n18\nend\n";
2043        std::fs::write(d.join("f.txt"), body).unwrap();
2044        std::fs::write(d.join("conflict.txt"), "old\n").unwrap();
2045        let base = commit(d, "base").await;
2046        sh(d, &["checkout", "-q", "-b", "topic"]);
2047        std::fs::write(d.join("conflict.txt"), "branch\n").unwrap();
2048        commit(d, "c0").await;
2049        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
2050        let c1 = commit(d, "c1").await;
2051        std::fs::write(
2052            d.join("f.txt"),
2053            body.replacen("old", "new", 1)
2054                .replace("later", "branch tail"),
2055        )
2056        .unwrap();
2057        let orig = commit(d, "c2").await;
2058        sh(d, &["checkout", "-q", "main"]);
2059        std::fs::write(d.join("conflict.txt"), "upstream\n").unwrap();
2060        let upstream = body
2061            .replacen("old", "new", 1)
2062            .replace("end", "upstream tail");
2063        std::fs::write(d.join("f.txt"), &upstream).unwrap();
2064        let onto = commit(d, "upstream composite").await;
2065        let scratch = d.join("scratch");
2066        assert!(matches!(
2067            git::rebase_start(d, &scratch, "topic", &onto)
2068                .await
2069                .unwrap(),
2070            git::RebaseStart::Conflicted(_)
2071        ));
2072        // While resolving C0, the fixer erases C1's absorbed first-line edit.
2073        std::fs::write(scratch.join("conflict.txt"), "resolved\n").unwrap();
2074        std::fs::write(scratch.join("f.txt"), upstream.replacen("new", "theirs", 1)).unwrap();
2075        sh(&scratch, &["add", "conflict.txt", "f.txt"]);
2076        let continued = git::git_raw(&scratch, &["rebase", "--continue"])
2077            .await
2078            .unwrap();
2079        assert_eq!(
2080            continued.code,
2081            Some(1),
2082            "{}\n{}",
2083            continued.stdout,
2084            continued.stderr
2085        );
2086        assert_eq!(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap(), c1);
2087        let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
2088        assert!(skipped.ok(), "{}", skipped.stderr);
2089        let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
2090        assert!(replay_is_noop(d, &c1, &onto).await.unwrap());
2091        // The later branch commit edits a different hunk, so the clean merge
2092        // still requires "new" on line one. The final result has "theirs".
2093        let expected = git::git_raw(
2094            d,
2095            &[
2096                "merge-tree",
2097                "--write-tree",
2098                &format!("--merge-base={c1}"),
2099                &onto,
2100                &orig,
2101            ],
2102        )
2103        .await
2104        .unwrap();
2105        assert!(expected.ok(), "{}", expected.stderr);
2106        assert!(
2107            !absorbed_in_result(d, &c1, &onto, &orig, &head)
2108                .await
2109                .unwrap()
2110        );
2111        assert_eq!(
2112            dropped_commits(d, &scratch, &onto, &orig, &head)
2113                .await
2114                .unwrap(),
2115            vec!["c1"]
2116        );
2117        let mut state = RunState::new(
2118            d.to_path_buf(),
2119            "main".into(),
2120            base,
2121            "rebase".into(),
2122            crate::config::Config::default(),
2123        );
2124        let outcome = finish(
2125            &mut state,
2126            &scratch,
2127            "topic",
2128            &orig,
2129            &onto,
2130            &["conflict.txt".into()],
2131            "",
2132        )
2133        .await
2134        .unwrap();
2135        assert!(
2136            matches!(outcome, Rebased::Stopped(why) if why.contains("the rebase dropped some of the branch's commits (skipped?)") && why.contains("c1"))
2137        );
2138        std::fs::remove_dir_all(state.dir()).ok();
2139    }
2140
2141    #[tokio::test]
2142    async fn a_partially_absorbed_commit_missing_an_unrelated_hunk_is_dropped() {
2143        let t = tempfile::tempdir().unwrap();
2144        let d = t.path();
2145        sh(d, &["init", "-q", "-b", "main"]);
2146        sh(d, &["config", "user.name", "t"]);
2147        sh(d, &["config", "user.email", "t@example.com"]);
2148        std::fs::write(d.join("c0.txt"), "base c0\n").unwrap();
2149        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
2150        std::fs::write(d.join("f.txt"), body).unwrap();
2151        std::fs::write(d.join("extra.txt"), "initial\n").unwrap();
2152        let base = commit(d, "base").await;
2153
2154        // Branch commits: C0, C1 (touches f.txt AND extra.txt), C2
2155        std::fs::write(d.join("c0.txt"), "branch c0\n").unwrap();
2156        commit_dated(d, "c0").await;
2157        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
2158        std::fs::write(d.join("extra.txt"), "c1 edit\n").unwrap();
2159        commit_dated(d, "c1").await;
2160        std::fs::write(d.join("f.txt"), body.replacen("old", "newer", 1)).unwrap();
2161        let orig = commit_dated(d, "c2").await;
2162
2163        // Upstream absorbed C1's f.txt edit, but NOT extra.txt
2164        sh(d, &["checkout", "-q", "-b", "up", &base]);
2165        std::fs::write(d.join("c0.txt"), "upstream c0\n").unwrap();
2166        let up = body.replacen("old", "new", 1).replace("last", "tail");
2167        std::fs::write(d.join("f.txt"), &up).unwrap();
2168        let onto = commit(d, "upstream").await;
2169
2170        // Result: C0 resolved, C1 was skipped or dropped despite extra.txt missing, C2 applied
2171        std::fs::write(d.join("c0.txt"), "resolved c0\n").unwrap();
2172        commit_dated(d, "c0").await;
2173        let res = up.replacen("new", "newer", 1);
2174        std::fs::write(d.join("f.txt"), &res).unwrap();
2175        // extra.txt remains "initial\n"
2176        let head = commit_dated(d, "c2").await;
2177
2178        let c0 = git::rev_parse(d, &format!("{orig}~2")).await.unwrap();
2179        let c1 = git::rev_parse(d, &format!("{orig}^")).await.unwrap();
2180        let resolved = git::rev_parse(d, &format!("{head}^")).await.unwrap();
2181        record(
2182            d,
2183            &[c0, c1, orig.clone()],
2184            &[resolved.clone(), resolved, head.clone()],
2185        )
2186        .await;
2187        assert_eq!(
2188            dropped_commits(d, d, &onto, &orig, &head).await.unwrap(),
2189            vec!["c1"]
2190        );
2191    }
2192
2193    // ---- launcher-owned staging -------------------------------------------
2194
2195    const UPSTREAM: &str = "a\nupstream test\nz\n";
2196    const TOPIC: &str = "a\ntopic test\nz\n";
2197    const BOTH: &str = "a\nupstream test\ntopic test\nz\n";
2198
2199    struct Fixture {
2200        _dir: tempfile::TempDir,
2201        scratch: PathBuf,
2202        state: RunState,
2203    }
2204
2205    impl Fixture {
2206        fn read(&self, name: &str) -> String {
2207            std::fs::read_to_string(self.scratch.join(name)).unwrap()
2208        }
2209    }
2210
2211    /// `topic` has two commits on `main`'s fork point: the first conflicts on
2212    /// `f.txt`, the second adds `g.txt`. The rebase stands on the first and
2213    /// one fixer round is recorded, as `rebase_with_fixer` would have.
2214    async fn fixture(stop_recorded: bool) -> Fixture {
2215        fixture_with(stop_recorded, "f.txt", 2).await
2216    }
2217
2218    async fn fixture_with(stop_recorded: bool, conflict: &str, commits: usize) -> Fixture {
2219        fixture_stops(stop_recorded, conflict, commits, false).await
2220    }
2221
2222    async fn fixture_stops(
2223        stop_recorded: bool,
2224        conflict: &str,
2225        commits: usize,
2226        second: bool,
2227    ) -> Fixture {
2228        crate::run::pin_test_home();
2229        let t = tempfile::tempdir().unwrap();
2230        let d = t.path().join("repo");
2231        std::fs::create_dir(&d).unwrap();
2232        sh(&d, &["init", "-q", "-b", "main"]);
2233        sh(&d, &["config", "user.name", "t"]);
2234        sh(&d, &["config", "user.email", "t@example.com"]);
2235        sh(&d, &["config", "core.autocrlf", "false"]);
2236        std::fs::write(d.join(conflict), "a\nbase\nz\n").unwrap();
2237        std::fs::write(d.join("automatic"), "base\n").unwrap();
2238        sh(&d, &["add", "."]);
2239        sh(&d, &["commit", "-qm", "base"]);
2240        let base = git::rev_parse(&d, "HEAD").await.unwrap();
2241        sh(&d, &["checkout", "-qb", "topic"]);
2242        std::fs::write(d.join(conflict), TOPIC).unwrap();
2243        std::fs::write(d.join("README.md"), "Heading\n=======\n").unwrap();
2244        sh(&d, &["add", "README.md"]);
2245        std::fs::write(d.join("automatic"), "topic applied cleanly\n").unwrap();
2246        sh(&d, &["commit", "-qam", "topic test"]);
2247        std::fs::write(d.join("g.txt"), "g\n").unwrap();
2248        sh(&d, &["add", "g.txt"]);
2249        sh(&d, &["commit", "-qm", "topic g"]);
2250        for n in 2..commits {
2251            std::fs::write(d.join(format!("commit-{n}")), format!("{n}\n")).unwrap();
2252            sh(&d, &["add", "."]);
2253            sh(&d, &["commit", "-qm", &format!("topic {n}")]);
2254        }
2255        sh(&d, &["checkout", "-q", "main"]);
2256        std::fs::write(d.join(conflict), UPSTREAM).unwrap();
2257        if second {
2258            std::fs::write(d.join("g.txt"), "upstream g\n").unwrap();
2259            sh(&d, &["add", "g.txt"]);
2260        }
2261        sh(&d, &["commit", "-qam", "upstream test"]);
2262        let scratch = t.path().join("scratch");
2263        let started = git::rebase_start(&d, &scratch, "topic", "main")
2264            .await
2265            .unwrap();
2266        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
2267        let mut state = RunState::new(
2268            d.clone(),
2269            "main".into(),
2270            base,
2271            "rebase".into(),
2272            crate::config::Config::default(),
2273        );
2274        let paths = git::unmerged_paths(&scratch).await.unwrap();
2275        assert_eq!(paths, vec![conflict]);
2276        state.rebase_fixes.push(RebaseFixRecord {
2277            outage: None,
2278            agent: "mock".into(),
2279            index_outside: index_outside(&scratch, &paths).await.ok(),
2280            stop: if stop_recorded {
2281                rebase_head(&scratch).await
2282            } else {
2283                None
2284            },
2285            paths,
2286            from: None,
2287            finished: false,
2288            error: None,
2289            launcher: None,
2290            infra: None,
2291        });
2292        Fixture {
2293            _dir: t,
2294            scratch,
2295            state,
2296        }
2297    }
2298
2299    async fn stage(f: &mut Fixture) -> Result<Launch> {
2300        let original = git::rev_parse(&f.state.repo, "topic").await?;
2301        let onto = git::rev_parse(&f.state.repo, "main").await?;
2302        launcher_stage(&mut f.state, &f.scratch, &original, &onto).await
2303    }
2304
2305    async fn topic_subjects(f: &Fixture) -> Vec<String> {
2306        subjects(&f.scratch, "main..HEAD").await
2307    }
2308
2309    #[tokio::test]
2310    async fn resolved_contents_with_an_unmerged_index_are_staged_and_continued() {
2311        let mut f = fixture(true).await;
2312        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2313        let out = stage(&mut f).await.unwrap();
2314        assert!(matches!(out, Launch::Advanced));
2315        assert!(!git::rebase_in_progress(&f.scratch).await);
2316        // Both sides' tests survive and the later commit was replayed too.
2317        assert_eq!(f.read("f.txt"), BOTH);
2318        assert_eq!(f.read("g.txt"), "g\n");
2319        assert_eq!(topic_subjects(&f).await, vec!["topic g", "topic test"]);
2320        let rec = git::rebase_record(&f.scratch).await.unwrap();
2321        assert_eq!(rec.picks.len(), 2);
2322        assert_eq!(f.state.rebase_fixes.len(), 1, "no further round was spent");
2323        std::fs::remove_dir_all(f.state.dir()).ok();
2324    }
2325
2326    #[tokio::test]
2327    async fn a_pre_staging_record_is_matched_by_its_repeated_conflict_set() {
2328        let mut f = fixture(false).await;
2329        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2330        let again = f.state.rebase_fixes[0].clone();
2331        f.state.rebase_fixes.push(again);
2332        let out = stage(&mut f).await.unwrap();
2333        assert!(matches!(out, Launch::Advanced));
2334        assert!(!git::rebase_in_progress(&f.scratch).await);
2335
2336        // Records that disagree about the conflict identify nothing.
2337        let mut f = fixture(false).await;
2338        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2339        let mut other = f.state.rebase_fixes[0].clone();
2340        other.paths = vec!["elsewhere.txt".into()];
2341        f.state.rebase_fixes.insert(0, other);
2342        let out = stage(&mut f).await.unwrap();
2343        assert!(matches!(out, Launch::Nothing(_)));
2344        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2345        std::fs::remove_dir_all(f.state.dir()).ok();
2346    }
2347
2348    #[tokio::test]
2349    async fn remaining_markers_stage_nothing() {
2350        let mut f = fixture(true).await;
2351        let out = stage(&mut f).await.unwrap();
2352        assert!(matches!(&out, Launch::Nothing(why) if why.contains("markers")));
2353        assert!(git::rebase_in_progress(&f.scratch).await);
2354        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2355        assert!(f.state.resource_block.is_none());
2356        std::fs::remove_dir_all(f.state.dir()).ok();
2357    }
2358
2359    #[tokio::test]
2360    async fn partial_markers_are_rejected_even_after_staging() {
2361        for marker in ["<<<<<<< HEAD", "=======", ">>>>>>> topic", "||||||| base"] {
2362            for staged in [false, true] {
2363                let mut f = fixture(true).await;
2364                std::fs::write(f.scratch.join("f.txt"), format!("{BOTH}{marker}\n")).unwrap();
2365                if staged {
2366                    sh(&f.scratch, &["add", "f.txt"]);
2367                }
2368                assert!(
2369                    has_markers(&f.scratch, "f.txt", &["HEAD", "REBASE_HEAD"])
2370                        .await
2371                        .unwrap()
2372                );
2373                let out = stage(&mut f).await.unwrap();
2374                assert!(matches!(&out, Launch::Nothing(why) if why.contains("markers")));
2375                assert!(git::rebase_in_progress(&f.scratch).await);
2376                std::fs::remove_dir_all(f.state.dir()).ok();
2377            }
2378        }
2379    }
2380
2381    #[tokio::test]
2382    async fn existing_markdown_headings_are_not_conflict_markers() {
2383        let f = fixture(true).await;
2384        assert!(
2385            !has_markers(&f.scratch, "README.md", &["HEAD", "REBASE_HEAD"])
2386                .await
2387                .unwrap()
2388        );
2389        std::fs::write(
2390            f.scratch.join("README.md"),
2391            "Heading\n=======\nextra separator\n=======\n",
2392        )
2393        .unwrap();
2394        assert!(
2395            has_markers(&f.scratch, "README.md", &["HEAD", "REBASE_HEAD"])
2396                .await
2397                .unwrap()
2398        );
2399        std::fs::write(f.scratch.join("README.md"), "resolved code\n=======\n").unwrap();
2400        assert!(
2401            has_markers(&f.scratch, "README.md", &["HEAD", "REBASE_HEAD"])
2402                .await
2403                .unwrap()
2404        );
2405        std::fs::remove_dir_all(f.state.dir()).ok();
2406    }
2407
2408    #[tokio::test]
2409    async fn retries_keep_the_first_index_baseline() {
2410        let mut f = fixture(true).await;
2411        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2412        std::fs::write(f.scratch.join("automatic"), "unrelated staged edit\n").unwrap();
2413        sh(&f.scratch, &["add", "automatic"]);
2414        let out = stage(&mut f).await.unwrap();
2415        assert!(matches!(&out, Launch::Nothing(why) if why.contains("staged changes")));
2416        let paths = f.state.rebase_fixes[0].paths.clone();
2417        let baseline = round_baseline(&mut f.state, &f.scratch, &paths)
2418            .await
2419            .unwrap();
2420        assert_eq!(
2421            Some(&baseline),
2422            f.state.rebase_fixes[0].index_outside.as_ref()
2423        );
2424        assert_ne!(baseline, index_outside(&f.scratch, &paths).await.unwrap());
2425        let mut retry = f.state.rebase_fixes[0].clone();
2426        // Even a polluted later record cannot replace the first baseline.
2427        retry.index_outside = index_outside(&f.scratch, &paths).await.ok();
2428        f.state.rebase_fixes.push(retry);
2429        let out = stage(&mut f).await.unwrap();
2430        assert!(matches!(&out, Launch::Nothing(why) if why.contains("staged changes")));
2431        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2432        std::fs::remove_dir_all(f.state.dir()).ok();
2433    }
2434
2435    #[tokio::test]
2436    async fn legacy_records_without_a_baseline_block_without_adopting_the_index() {
2437        let mut f = fixture(false).await;
2438        f.state.rebase_fixes[0].index_outside = None;
2439        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2440        std::fs::write(f.scratch.join("automatic"), "unrelated staged edit\n").unwrap();
2441        sh(&f.scratch, &["add", "automatic"]);
2442        let error = stage(&mut f).await.unwrap_err();
2443        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2444        assert!(error.to_string().contains("baseline"));
2445        assert_eq!(f.state.rebase_fixes.len(), 1);
2446        assert!(f.state.rebase_fixes[0].index_outside.is_none());
2447        assert_eq!(f.read("f.txt"), BOTH);
2448        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2449        std::fs::remove_dir_all(f.state.dir()).ok();
2450    }
2451
2452    #[tokio::test]
2453    async fn legacy_baseline_is_reconstructed_and_saved_without_another_fixer() {
2454        for staged in [false, true] {
2455            let mut f = fixture_with(false, "f.txt", 16).await;
2456            f.state.rebase_fixes[0].index_outside = None;
2457            let again = f.state.rebase_fixes[0].clone();
2458            f.state.rebase_fixes.push(again);
2459            f.state.config.graph.review_rounds = 1;
2460            std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2461            if staged {
2462                sh(&f.scratch, &["add", "f.txt"]);
2463            }
2464            let original = git::rev_parse(&f.state.repo, "topic").await.unwrap();
2465            assert!(matches!(stage(&mut f).await.unwrap(), Launch::Advanced));
2466            assert_eq!(f.state.rebase_fixes.len(), 2);
2467            assert!(f.state.rebase_fixes[0].index_outside.is_some());
2468            assert!(f.state.rebase_fixes.iter().all(|r| r.stop.is_some()));
2469            let saved = RunState::load(&f.state.id).unwrap();
2470            assert_eq!(
2471                saved.rebase_fixes[0].index_outside,
2472                f.state.rebase_fixes[0].index_outside
2473            );
2474            assert_eq!(f.read("f.txt"), BOTH);
2475            assert_eq!(topic_subjects(&f).await.len(), 16);
2476            assert_eq!(f.read("automatic"), "topic applied cleanly\n");
2477            let onto = git::rev_parse(&f.state.repo, "main").await.unwrap();
2478            assert_eq!(
2479                finish(
2480                    &mut f.state,
2481                    &f.scratch,
2482                    "topic",
2483                    &original,
2484                    &onto,
2485                    &["f.txt".into()],
2486                    ""
2487                )
2488                .await
2489                .unwrap(),
2490                Rebased::Applied
2491            );
2492            std::fs::remove_dir_all(f.state.dir()).ok();
2493        }
2494    }
2495
2496    #[tokio::test]
2497    async fn successful_progression_gets_a_budget_for_the_next_conflicting_commit() {
2498        let mut f = fixture_stops(true, "f.txt", 2, true).await;
2499        f.state.config.graph.review_rounds = 1;
2500        assert_eq!(stop_rounds(&f.state, &f.scratch).await, 1);
2501        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2502        assert!(matches!(stage(&mut f).await.unwrap(), Launch::Advanced));
2503        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["g.txt"]);
2504        assert_eq!(stop_rounds(&f.state, &f.scratch).await, 0);
2505        let paths = git::unmerged_paths(&f.scratch).await.unwrap();
2506        let mut round = f.state.rebase_fixes[0].clone();
2507        round.index_outside = Some(
2508            round_baseline(&mut f.state, &f.scratch, &paths)
2509                .await
2510                .unwrap(),
2511        );
2512        round.paths = paths;
2513        round.stop = rebase_head(&f.scratch).await;
2514        f.state.rebase_fixes.push(round);
2515        assert_eq!(stop_rounds(&f.state, &f.scratch).await, 1);
2516        std::fs::write(f.scratch.join("g.txt"), "upstream g\ng\n").unwrap();
2517        assert_eq!(
2518            rebase_with_fixer(&mut f.state, &f.scratch, "topic", "main")
2519                .await
2520                .unwrap(),
2521            Rebased::Applied
2522        );
2523        assert_eq!(
2524            git::git(&f.state.repo, &["show", "topic:f.txt"])
2525                .await
2526                .unwrap(),
2527            BOTH.trim_end()
2528        );
2529        assert_eq!(
2530            git::git(&f.state.repo, &["show", "topic:g.txt"])
2531                .await
2532                .unwrap(),
2533            "upstream g\ng"
2534        );
2535        std::fs::remove_dir_all(f.state.dir()).ok();
2536    }
2537
2538    #[tokio::test]
2539    async fn resume_after_staging_denial_uses_the_saved_target_when_upstream_moves() {
2540        let mut f = fixture(true).await;
2541        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2542        let saved = rebase_target(&f.scratch).await.unwrap();
2543        let lock = git::git(&f.scratch, &["rev-parse", "--git-path", "index.lock"])
2544            .await
2545            .unwrap();
2546        let lock = f.scratch.join(lock);
2547        std::fs::write(&lock, "").unwrap();
2548        assert!(
2549            stage(&mut f)
2550                .await
2551                .unwrap_err()
2552                .is::<crate::repo_lock::ResourceBlocked>()
2553        );
2554        std::fs::remove_file(lock).unwrap();
2555        std::fs::write(f.state.repo.join("new-upstream"), "new base\n").unwrap();
2556        sh(&f.state.repo, &["add", "new-upstream"]);
2557        sh(&f.state.repo, &["commit", "-qm", "new upstream"]);
2558        assert_ne!(saved, git::rev_parse(&f.state.repo, "main").await.unwrap());
2559        assert_eq!(
2560            rebase_with_fixer(&mut f.state, &f.scratch, "topic", "main")
2561                .await
2562                .unwrap(),
2563            Rebased::Applied
2564        );
2565        assert!(git::is_ancestor(&f.state.repo, &saved, "topic").await);
2566        assert!(git::is_ancestor(&f.state.repo, "main", "topic").await);
2567        assert_eq!(
2568            git::git(&f.state.repo, &["show", "topic:f.txt"])
2569                .await
2570                .unwrap(),
2571            BOTH.trim_end()
2572        );
2573        assert_eq!(f.state.rebase_fixes.len(), 1);
2574        std::fs::remove_dir_all(f.state.dir()).ok();
2575    }
2576
2577    #[tokio::test]
2578    async fn unrelated_edits_and_unexpected_unmerged_paths_stage_nothing() {
2579        let mut f = fixture(true).await;
2580        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2581        std::fs::write(f.scratch.join("stray.txt"), "x\n").unwrap();
2582        let out = stage(&mut f).await.unwrap();
2583        assert!(matches!(&out, Launch::Nothing(why) if why.contains("stray.txt")));
2584        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2585        std::fs::remove_file(f.scratch.join("stray.txt")).unwrap();
2586
2587        // The round only ever covered some other path.
2588        f.state.rebase_fixes[0].paths = vec!["other.txt".into()];
2589        let out = stage(&mut f).await.unwrap();
2590        assert!(matches!(&out, Launch::Nothing(why) if why.contains("not part of")));
2591        assert!(git::rebase_in_progress(&f.scratch).await);
2592        std::fs::remove_dir_all(f.state.dir()).ok();
2593    }
2594
2595    #[tokio::test]
2596    async fn a_denied_index_write_is_an_infrastructure_stop_that_keeps_everything() {
2597        let mut f = fixture(true).await;
2598        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2599        let lock = git::git(&f.scratch, &["rev-parse", "--git-path", "index.lock"])
2600            .await
2601            .unwrap();
2602        let lock = f.scratch.join(lock);
2603        std::fs::write(&lock, "").unwrap();
2604
2605        let err = stage(&mut f).await.unwrap_err();
2606        assert!(err.is::<crate::repo_lock::ResourceBlocked>(), "{err:#}");
2607        let block = f.state.resource_block.clone().expect("a resource block");
2608        assert_eq!(block.kind, "git metadata write");
2609        assert!(f.state.rebase_fixes[0].infra.is_some());
2610        assert_eq!(f.state.rebase_fixes.len(), 1, "no round was spent");
2611        assert!(git::rebase_in_progress(&f.scratch).await);
2612        assert_eq!(f.read("f.txt"), BOTH);
2613
2614        // A later pass (the lock gone) finishes the same stop point.
2615        std::fs::remove_file(&lock).unwrap();
2616        f.state.resource_block = None;
2617        let out = stage(&mut f).await.unwrap();
2618        assert!(matches!(out, Launch::Advanced));
2619        assert!(!git::rebase_in_progress(&f.scratch).await);
2620        assert_eq!(f.read("f.txt"), BOTH);
2621        std::fs::remove_dir_all(f.state.dir()).ok();
2622    }
2623
2624    #[tokio::test]
2625    async fn a_pass_interrupted_after_staging_is_continued_not_repeated() {
2626        let mut f = fixture(true).await;
2627        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2628        sh(&f.scratch, &["add", "f.txt"]);
2629        f.state.rebase_fixes[0].launcher = Some(crate::run::LauncherStep::Staged);
2630        assert!(git::unmerged_paths(&f.scratch).await.unwrap().is_empty());
2631        let out = stage(&mut f).await.unwrap();
2632        assert!(matches!(out, Launch::Advanced));
2633        assert!(!git::rebase_in_progress(&f.scratch).await);
2634        assert_eq!(topic_subjects(&f).await, vec!["topic g", "topic test"]);
2635        // Nothing is left to do on a second pass.
2636        let out = stage(&mut f).await.unwrap();
2637        assert!(matches!(out, Launch::Nothing(_)));
2638        std::fs::remove_dir_all(f.state.dir()).ok();
2639    }
2640
2641    #[tokio::test]
2642    async fn recorded_conflict_edits_after_interrupted_staging_are_restaged() {
2643        for deleted in [false, true] {
2644            let mut f = fixture(true).await;
2645            std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2646            sh(&f.scratch, &["add", "f.txt"]);
2647            f.state.rebase_fixes[0].launcher = Some(crate::run::LauncherStep::Staged);
2648            assert!(git::unmerged_paths(&f.scratch).await.unwrap().is_empty());
2649
2650            let revised = format!("{BOTH}additional test\n");
2651            if deleted {
2652                std::fs::remove_file(f.scratch.join("f.txt")).unwrap();
2653            } else {
2654                std::fs::write(f.scratch.join("f.txt"), &revised).unwrap();
2655            }
2656            let out = stage(&mut f).await.unwrap();
2657            assert!(matches!(out, Launch::Advanced));
2658            assert!(!git::rebase_in_progress(&f.scratch).await);
2659            assert_eq!(topic_subjects(&f).await, vec!["topic g", "topic test"]);
2660            if deleted {
2661                assert!(
2662                    git::git(&f.scratch, &["ls-tree", "HEAD", "--", "f.txt"])
2663                        .await
2664                        .unwrap()
2665                        .is_empty()
2666                );
2667            } else {
2668                assert_eq!(f.read("f.txt"), revised);
2669                assert_eq!(
2670                    git::git(&f.scratch, &["show", "HEAD:f.txt"]).await.unwrap(),
2671                    revised.trim_end()
2672                );
2673            }
2674            assert!(status_entries(&f.scratch).await.unwrap().is_empty());
2675            assert_eq!(f.state.rebase_fixes.len(), 1, "no further round was spent");
2676            std::fs::remove_dir_all(f.state.dir()).ok();
2677        }
2678    }
2679
2680    #[tokio::test]
2681    async fn a_cancelled_run_stages_nothing_and_keeps_the_resolved_files() {
2682        let mut f = fixture(true).await;
2683        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2684        let cancelled = crate::repo_lock::WaitPolicy::new(Duration::from_secs(5), || true);
2685        let err = cancelled.scope(stage(&mut f)).await.unwrap_err();
2686        assert!(err.is::<crate::repo_lock::ResourceBlocked>());
2687        assert!(git::rebase_in_progress(&f.scratch).await);
2688        assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2689        assert_eq!(f.read("f.txt"), BOTH);
2690        std::fs::remove_dir_all(f.state.dir()).ok();
2691    }
2692    #[cfg(unix)]
2693    #[tokio::test]
2694    async fn cancelled_launcher_git_terminates_descendants_before_releasing_coordination() {
2695        for abort in [true, false] {
2696            cancelled_git_operation(abort).await;
2697        }
2698    }
2699
2700    #[cfg(unix)]
2701    async fn cancelled_git_operation(abort: bool) {
2702        let mut f = fixture(true).await;
2703        let scratch = f.scratch.clone();
2704        let state = &mut f.state;
2705        let policy = crate::config::test_coordination().unwrap();
2706        let common = crate::repo_lock::common_dir(&scratch)
2707            .await
2708            .unwrap()
2709            .unwrap();
2710        std::fs::write(common.join(&policy.contract_file), &policy.contract_token).unwrap();
2711        state.config.coordination = Some(policy.clone());
2712        let wait = crate::repo_lock::WaitPolicy::default();
2713        let lease = crate::repo_lock::SeatLease::operation_with(&scratch, Some(&policy), &wait)
2714            .await
2715            .unwrap();
2716        sh(
2717            &scratch,
2718            &[
2719                "config",
2720                "alias.block",
2721                "!echo $$ > operation.pid; exec sleep 30",
2722            ],
2723        );
2724        let cwd = scratch.clone();
2725        let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2726        let signal = cancelled.clone();
2727        let cancellation = crate::repo_lock::WaitPolicy::new(Duration::from_secs(5), move || {
2728            signal.load(std::sync::atomic::Ordering::SeqCst)
2729        });
2730        let operation =
2731            tokio::spawn(async move { cancellation.scope(mutate(&cwd, &["block"], lease)).await });
2732        let pid_file = scratch.join("operation.pid");
2733        let pid: i32 = tokio::time::timeout(Duration::from_secs(5), async {
2734            loop {
2735                if let Ok(text) = std::fs::read_to_string(&pid_file)
2736                    && let Ok(pid) = text.trim().parse()
2737                {
2738                    break pid;
2739                }
2740                tokio::time::sleep(Duration::from_millis(10)).await;
2741            }
2742        })
2743        .await
2744        .unwrap();
2745        assert!(crate::retention::OutputLease::take(&scratch, true).is_err());
2746        assert!(
2747            tokio::time::timeout(
2748                Duration::from_millis(100),
2749                crate::repo_lock::SeatLease::operation_with(&scratch, Some(&policy), &wait)
2750            )
2751            .await
2752            .is_err()
2753        );
2754        if abort {
2755            operation.abort();
2756            assert!(operation.await.unwrap_err().is_cancelled());
2757        } else {
2758            cancelled.store(true, std::sync::atomic::Ordering::SeqCst);
2759            let error = tokio::time::timeout(Duration::from_secs(5), operation)
2760                .await
2761                .unwrap()
2762                .unwrap()
2763                .unwrap_err();
2764            assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2765        }
2766        // Acquiring the same lease waits for the independent cleanup owner.
2767        let _next = crate::repo_lock::SeatLease::operation_with(&scratch, Some(&policy), &wait)
2768            .await
2769            .unwrap();
2770        // SAFETY: signal zero only checks whether the known test process lives.
2771        assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
2772        let _output = crate::retention::OutputLease::take(&scratch, true).unwrap();
2773        assert!(git::rebase_in_progress(&scratch).await);
2774        assert_eq!(state.rebase_fixes.len(), 1);
2775        std::fs::remove_dir_all(state.dir()).ok();
2776    }
2777
2778    #[tokio::test]
2779    async fn recovery_keeps_sixteen_commits_and_automatic_changes() {
2780        let mut f = fixture_with(true, "f.txt", 16).await;
2781        f.state.config.graph.review_rounds = 1;
2782        std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2783        let original = git::rev_parse(&f.state.repo, "topic").await.unwrap();
2784        let subjects = git::git(&f.scratch, &["log", "--format=%s", "main..topic"])
2785            .await
2786            .unwrap();
2787        assert_eq!(
2788            rebase_with_fixer(&mut f.state, &f.scratch, "topic", "main")
2789                .await
2790                .unwrap(),
2791            Rebased::Applied
2792        );
2793        let heads = git::git(&f.state.repo, &["rev-list", "--count", "main..topic"])
2794            .await
2795            .unwrap();
2796        assert_eq!(heads, "16");
2797        assert_eq!(
2798            git::git(&f.state.repo, &["show", "topic:f.txt"])
2799                .await
2800                .unwrap(),
2801            BOTH.trim_end()
2802        );
2803        assert_eq!(
2804            git::git(&f.state.repo, &["show", "topic:automatic"])
2805                .await
2806                .unwrap(),
2807            "topic applied cleanly"
2808        );
2809        assert_eq!(
2810            git::git(&f.state.repo, &["log", "--format=%s", "main..topic"])
2811                .await
2812                .unwrap(),
2813            subjects
2814        );
2815        for n in 2..16 {
2816            assert_eq!(
2817                git::git(&f.state.repo, &["show", &format!("topic:commit-{n}")])
2818                    .await
2819                    .unwrap(),
2820                n.to_string()
2821            );
2822        }
2823        assert_eq!(f.state.rebase_fixes.len(), 1);
2824        assert_ne!(
2825            git::rev_parse(&f.state.repo, "topic").await.unwrap(),
2826            original
2827        );
2828        std::fs::remove_dir_all(f.state.dir()).ok();
2829    }
2830
2831    #[tokio::test]
2832    async fn recovery_handles_literal_conflict_paths_with_whitespace() {
2833        // Win32 rejects trailing spaces and control characters in file names.
2834        // Exercise literal pathspecs there with valid whitespace and brackets;
2835        // retain trailing whitespace and control-character coverage on Unix.
2836        let paths = [" spaced file name", "日本語 [literal].txt", "日本語.txt"].into_iter();
2837        #[cfg(not(windows))]
2838        let paths = paths.chain([" spaced file ", "tab\tand\nnewline"]);
2839        for path in paths {
2840            let mut f = fixture_with(true, path, 2).await;
2841            assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), [path]);
2842            std::fs::write(f.scratch.join(path), BOTH).unwrap();
2843            assert!(matches!(stage(&mut f).await.unwrap(), Launch::Advanced));
2844            assert_eq!(f.read(path), BOTH);
2845            assert!(git::unmerged_paths(&f.scratch).await.unwrap().is_empty());
2846            std::fs::remove_dir_all(f.state.dir()).ok();
2847        }
2848    }
2849
2850    #[tokio::test]
2851    async fn changed_rebase_identity_blocks_staging_and_keeps_resolution() {
2852        for name in ["orig-head", "onto"] {
2853            let mut f = fixture(true).await;
2854            std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2855            let metadata = git::git(
2856                &f.scratch,
2857                &["rev-parse", "--git-path", &format!("rebase-merge/{name}")],
2858            )
2859            .await
2860            .unwrap();
2861            std::fs::write(
2862                f.scratch.join(metadata),
2863                "0000000000000000000000000000000000000000\n",
2864            )
2865            .unwrap();
2866            let error = stage(&mut f).await.unwrap_err();
2867            assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2868            assert!(error.to_string().contains(name));
2869            assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2870            assert_eq!(f.read("f.txt"), BOTH);
2871            assert_eq!(f.state.rebase_fixes.len(), 1);
2872            std::fs::remove_dir_all(f.state.dir()).ok();
2873        }
2874    }
2875}