Skip to main content

magi/
handover.rs

1//! Taking a branch over from an earlier attempt at the same task.
2//!
3//! A retried task can reopen a branch (`magi/f82f/A`) that the *previous*
4//! run still has checked out in its own worktree. Git holds a branch in one
5//! worktree at a time, so the new run's review cannot start, and the only way
6//! forward used to be an agent asking the operator whether the old worktree
7//! may be deleted. Auto-fold cannot help: it only folds terminal runs, and an
8//! unfinished run keeps its worktrees on purpose so it can be resumed.
9//!
10//! When the run holding the branch is one this attempt supersedes
11//! ([`crate::queue::Task::earlier_attempts`]), nothing is left to resume it
12//! into, so its worktree - and only its worktree - is released before the
13//! review starts. The branch, every commit and any pull request stay
14//! exactly where they were.
15//!
16//! [`decide`] is pure; [`release`] is the only function here that touches git
17//! or disk. Only a queue-driven review takes over anything: a hand-run
18//! `magi review` has no task, so it carries no [`Takeover`] and behaves as it
19//! always did.
20
21use std::path::{Path, PathBuf};
22
23use anyhow::Result;
24
25use crate::git;
26use crate::run::{Liveness, RunState, RunStatus};
27
28/// The earlier attempts at a task a new run may take a branch over from.
29#[derive(Debug, Clone)]
30pub struct Takeover {
31    /// Ids of runs the new attempt supersedes, from
32    /// [`crate::queue::Task::earlier_attempts`].
33    pub earlier: Vec<String>,
34    /// The magi home their records live under.
35    pub home: PathBuf,
36}
37
38/// The operator has to decide: the takeover was refused, and the text says why.
39///
40/// A distinct type so the queue loop can hold the task for a person instead
41/// of spending an attempt on it (see `daemon::attempt`).
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Refused(pub String);
44
45impl std::fmt::Display for Refused {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.write_str(&self.0)
48    }
49}
50
51impl std::error::Error for Refused {}
52
53/// A worktree that was released, with what is needed to put it back if the
54/// review that took the branch over never starts.
55#[derive(Debug, Clone)]
56pub struct Released {
57    /// The run whose worktree was released.
58    pub old_id: String,
59    index: usize,
60    path: PathBuf,
61    home: PathBuf,
62    /// The branch tip when the worktree was released; the branch sync may
63    /// have moved it since.
64    tip: String,
65}
66
67impl Released {
68    /// Undo the release after the new run failed to start: check the branch
69    /// out again at the old path and unmark the old run. Best-effort - if the
70    /// worktree cannot be re-added the old run stays marked, which is true.
71    pub async fn restore(&self, repo: &Path, branch: &str) {
72        let path = self.path.to_string_lossy().to_string();
73        // Nothing holds the branch now, so it can be put back where the old
74        // run left it before its worktree is recreated at that commit.
75        let refname = format!("refs/heads/{branch}");
76        if git::rev_parse(repo, &refname).await.ok().as_deref() != Some(self.tip.as_str())
77            && let Err(e) = git::git(repo, &["branch", "-f", branch, &self.tip]).await
78        {
79            tracing::warn!("could not put `{branch}` back at {}: {e:#}", self.tip);
80            return;
81        }
82        if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
83            tracing::warn!(
84                "could not put run {}'s worktree back at {path}: {e:#}",
85                self.old_id
86            );
87            return;
88        }
89        let put_back = RunState::load_under(&self.old_id, &self.home).and_then(|mut s| {
90            if let Some(c) = s.candidates.get_mut(self.index) {
91                c.folded = false;
92            }
93            s.released_to = None;
94            s.released_branches.retain(|b| b != branch);
95            s.events.pop();
96            s.save_under(&self.home)
97        });
98        if let Err(e) = put_back {
99            tracing::warn!("could not unmark run {}: {e:#}", self.old_id);
100        }
101    }
102}
103
104/// What is known about the run and worktree holding the branch.
105#[derive(Debug, Clone)]
106pub struct Holder {
107    /// The run's id.
108    pub run: String,
109    /// Where the run got to.
110    pub status: RunStatus,
111    /// Whether anything is driving it.
112    pub liveness: Liveness,
113    /// A driver pid is recorded but could not be shown dead: it may well be
114    /// running, so "unknown" must not read as "gone".
115    pub driver_unproven: bool,
116    /// Any uncommitted change, untracked files included.
117    pub dirty: bool,
118    /// HEAD of the worktree.
119    pub head: String,
120    /// The branch tip in the repository.
121    pub tip: String,
122}
123
124/// The verdict of [`decide`].
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub enum Decision {
127    /// Safe to release the worktree.
128    Release,
129    /// Ours to decide about, but not safe; the text says why, for the
130    /// operator.
131    Refuse(String),
132    /// Not a superseded run's worktree: leave it alone and let git's own
133    /// refusal stand.
134    NotOurs,
135}
136
137fn short(sha: &str) -> String {
138    sha.chars().take(7).collect()
139}
140
141/// Whether `holder`'s worktree may be released to a new run.
142///
143/// [`Liveness::Unknown`] releases only when no driver pid was ever recorded
144/// (nothing that could still be running); a recorded pid that could not be
145/// shown dead is refused like a live one.
146pub fn decide(superseded: bool, holder: &Holder) -> Decision {
147    if !superseded {
148        return Decision::NotOurs;
149    }
150    let mut why = Vec::new();
151    if holder.liveness == Liveness::Live {
152        why.push("that run is being worked on right now".to_owned());
153    } else if holder.driver_unproven {
154        why.push("its driver process could not be shown to be gone".to_owned());
155    }
156    if holder.dirty {
157        why.push("its worktree has uncommitted changes".to_owned());
158    }
159    if holder.head != holder.tip {
160        why.push("its HEAD is not at the branch tip".to_owned());
161    }
162    if why.is_empty() {
163        return Decision::Release;
164    }
165    Decision::Refuse(format!(
166        "run {} (status `{}`, worktree {}, HEAD {}, branch tip {}) is an earlier attempt \
167         at this task and still has the branch checked out, so it was not released \
168         automatically: {}",
169        crate::run::short_of(&holder.run),
170        holder.status.as_str(),
171        if holder.dirty { "dirty" } else { "clean" },
172        short(&holder.head),
173        short(&holder.tip),
174        why.join("; ")
175    ))
176}
177
178/// Read what [`decide`] needs from disk and git.
179async fn inspect(
180    repo: &Path,
181    branch: &str,
182    path: &Path,
183    state: &RunState,
184    home: &Path,
185) -> Result<Holder> {
186    let claimed = crate::daemon::is_working_on(home, &state.id, jiff::Timestamp::now());
187    let liveness = state.liveness(claimed);
188    Ok(Holder {
189        run: state.id.clone(),
190        status: state.status,
191        liveness,
192        driver_unproven: liveness == Liveness::Unknown && state.driver_pid.is_some(),
193        dirty: !git::status_porcelain(path).await?.trim().is_empty(),
194        head: git::rev_parse(path, "HEAD").await?,
195        tip: git::rev_parse(repo, &format!("refs/heads/{branch}")).await?,
196    })
197}
198
199fn same_path(a: &Path, b: &Path) -> bool {
200    let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
201    canon(a) == canon(b)
202}
203
204/// Release the worktree holding `branch` to `new_run`, when an earlier attempt
205/// at the same task holds it and it is safe. Returns the run whose worktree
206/// was released (see [`Released`]), or `None` when nothing needed (or was allowed) to happen.
207///
208/// An `Err` is a refusal or a failed removal; the message is what the
209/// operator reads. Nothing is left half-done: the old run's record is written
210/// before the removal and rolled back if git refuses it.
211pub async fn release(
212    repo: &Path,
213    branch: &str,
214    new_run: &str,
215    takeover: &Takeover,
216) -> Result<Option<Released>> {
217    let Some(path) = git::worktree_holding(repo, branch).await? else {
218        return Ok(None);
219    };
220    // The holder has to be an unfolded candidate worktree of a run in the
221    // list. One nobody recorded (made by hand, say) is not ours to touch.
222    let mut owner = None;
223    for id in &takeover.earlier {
224        let Ok(state) = RunState::load_under(id, &takeover.home) else {
225            continue;
226        };
227        if let Some(i) = state
228            .candidates
229            .iter()
230            .position(|c| !c.folded && same_path(&c.worktree, &path))
231        {
232            owner = Some((state, i));
233            break;
234        }
235    }
236    let Some((mut state, index)) = owner else {
237        return Err(Refused(format!(
238            "branch `{branch}` is checked out in {}, which is not a worktree of an earlier \
239             attempt at this task (a run of another task, or one made by hand), so it was \
240             not touched. Remove that worktree (`git worktree remove`) if it is not needed, \
241             and try again.",
242            path.display()
243        ))
244        .into());
245    };
246
247    let holder = inspect(repo, branch, &path, &state, &takeover.home).await?;
248    match decide(true, &holder) {
249        Decision::NotOurs => return Ok(None),
250        Decision::Refuse(why) => {
251            return Err(Refused(format!(
252                "branch `{branch}` is checked out in {}: {why}. Commit or discard the work \
253                 there and remove that worktree (`git worktree remove`), or say the run may be \
254                 discarded, and try again.",
255                path.display()
256            ))
257            .into());
258        }
259        Decision::Release => {}
260    }
261
262    let old_id = state.id.clone();
263    state.candidates[index].folded = true;
264    state.released_to = Some(new_run.to_owned());
265    if !state.released_branches.iter().any(|b| b == branch) {
266        state.released_branches.push(branch.to_owned());
267    }
268    state.event(
269        "release",
270        format!(
271            "worktree of `{branch}` released to run {}; this run can no longer be resumed \
272             from here",
273            crate::run::short_of(new_run)
274        ),
275    );
276    state.save_under(&takeover.home)?;
277
278    // Re-read right before the removal for the driver and the tip, and let git
279    // itself refuse a dirty worktree: the removal is *not* `--force`, so an
280    // edit made after the first look is refused rather than thrown away.
281    // Ignored files such as `target/` go with the worktree by design.
282    // Against the record as it is on disk now, not the copy read earlier: a
283    // resume that started in between has saved its driver there. (The resume
284    // side refuses a released run too - see `Runner::execute_graph`.)
285    let again = match RunState::load_under(&old_id, &takeover.home) {
286        Ok(fresh) => inspect(repo, branch, &path, &fresh, &takeover.home).await,
287        Err(e) => Err(e),
288    };
289    let safe = matches!(&again, Ok(h) if decide(true, h) == Decision::Release);
290    let removed = safe
291        && git::worktree_remove_clean(repo, &path)
292            .await
293            .unwrap_or(false);
294    if !removed || path.exists() {
295        state = RunState::load_under(&old_id, &takeover.home)?;
296        state.candidates[index].folded = false;
297        state.released_to = None;
298        state.released_branches.retain(|b| b != branch);
299        state.events.pop();
300        state.save_under(&takeover.home)?;
301        return Err(Refused(format!(
302            "branch `{branch}` is checked out in {} by run {}, and releasing that worktree \
303             failed or found it changed (git refuses to remove a worktree with uncommitted \
304             changes); it was left as it was",
305            path.display(),
306            crate::run::short_of(&old_id)
307        ))
308        .into());
309    }
310    Ok(Some(Released {
311        old_id,
312        index,
313        path,
314        home: takeover.home.clone(),
315        tip: holder.tip,
316    }))
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    fn holder() -> Holder {
324        Holder {
325            run: "20260901-000000-f82f".to_owned(),
326            status: RunStatus::Gating,
327            liveness: Liveness::Unknown,
328            driver_unproven: false,
329            dirty: false,
330            head: "a".repeat(40),
331            tip: "a".repeat(40),
332        }
333    }
334
335    #[test]
336    fn a_clean_superseded_stale_run_is_released() {
337        assert_eq!(decide(true, &holder()), Decision::Release);
338        let dead = Holder {
339            liveness: Liveness::Dead,
340            ..holder()
341        };
342        assert_eq!(decide(true, &dead), Decision::Release);
343    }
344
345    #[test]
346    fn a_run_that_is_not_superseded_is_not_ours() {
347        assert_eq!(decide(false, &holder()), Decision::NotOurs);
348    }
349
350    #[test]
351    fn a_dirty_worktree_is_refused_and_says_why() {
352        let dirty = Holder {
353            dirty: true,
354            ..holder()
355        };
356        let Decision::Refuse(why) = decide(true, &dirty) else {
357            panic!("dirty must be refused");
358        };
359        assert!(why.contains("uncommitted"), "{why}");
360        assert!(why.contains("f82f") && why.contains("gating") && why.contains("dirty"));
361    }
362
363    #[test]
364    fn a_live_run_is_refused() {
365        let live = Holder {
366            liveness: Liveness::Live,
367            ..holder()
368        };
369        let Decision::Refuse(why) = decide(true, &live) else {
370            panic!("live must be refused");
371        };
372        assert!(why.contains("right now"), "{why}");
373    }
374
375    #[test]
376    fn a_driver_that_could_not_be_shown_dead_is_refused() {
377        let unproven = Holder {
378            driver_unproven: true,
379            ..holder()
380        };
381        let Decision::Refuse(why) = decide(true, &unproven) else {
382            panic!("an unproven driver must be refused");
383        };
384        assert!(why.contains("driver"), "{why}");
385    }
386
387    #[test]
388    fn a_head_off_the_tip_is_refused() {
389        let off = Holder {
390            head: "b".repeat(40),
391            ..holder()
392        };
393        assert!(matches!(decide(true, &off), Decision::Refuse(_)));
394    }
395}