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