1use std::path::{Path, PathBuf};
28
29use anyhow::Result;
30
31use crate::git;
32use crate::run::{Liveness, RunState, RunStatus};
33
34#[derive(Debug, Clone)]
36pub struct Takeover {
37 pub earlier: Vec<String>,
40 pub home: PathBuf,
42 pub choice: Option<crate::reconcile::Choice>,
46 pub task_instruction: Option<String>,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Refused {
61 Foreign {
63 branch: String,
65 path: String,
67 why: String,
69 },
70 Unsafe {
72 branch: String,
74 path: String,
76 why: String,
78 },
79 ReleaseFailed {
81 branch: String,
83 path: String,
85 run: String,
87 },
88}
89
90impl std::fmt::Display for Refused {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 match self {
93 Refused::Foreign { branch, path, why } => write!(
94 f,
95 "branch `{branch}` is checked out in {path}, which magi will not remove by \
96 itself: {why}. Commit or stash changes first. If no longer needed, run: \
97 git worktree remove {} (or renri remove {} -y --non-interactive), then try again.",
98 crate::foreign_checkout::quote(path),
99 crate::foreign_checkout::quote(branch)
100 ),
101 Refused::Unsafe { branch, path, why } => write!(
102 f,
103 "branch `{branch}` is checked out in {path}: {why}. Commit or discard the work \
104 there and remove that worktree (`git worktree remove`), or say the run may be \
105 discarded, and try again."
106 ),
107 Refused::ReleaseFailed { branch, path, run } => write!(
108 f,
109 "branch `{branch}` is checked out in {path} by run {run}, and releasing that \
110 worktree failed or found it changed (git refuses to remove a worktree with \
111 uncommitted changes); it was left as it was"
112 ),
113 }
114 }
115}
116
117impl std::error::Error for Refused {}
118
119#[derive(Debug, Clone)]
122pub struct Released {
123 pub old_id: String,
125 index: usize,
126 path: PathBuf,
127 home: PathBuf,
128 successor: String,
129 tip: String,
132 pub audit: String,
134}
135
136const OWNER_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
150
151async fn owner_lock_retrying(
155 home: &Path,
156 id: &str,
157 wait: std::time::Duration,
158) -> Result<crate::pr_head::OwnerLock> {
159 let deadline = tokio::time::Instant::now() + wait;
160 let mut pause = std::time::Duration::from_millis(10);
161 loop {
162 match crate::pr_head::owner_lock(home, id) {
163 Err(error) if crate::graph::held_by_live_owner(&error) => {
164 let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
165 if remaining.is_zero() {
166 return Err(error);
167 }
168 tokio::time::sleep(pause_within(pause, remaining)).await;
169 pause = (pause * 2).min(std::time::Duration::from_millis(250));
170 }
171 result => return result,
172 }
173 }
174}
175
176fn pause_within(pause: std::time::Duration, remaining: std::time::Duration) -> std::time::Duration {
179 pause.min(remaining)
180}
181
182impl Released {
183 pub async fn restore(&self, repo: &Path, branch: &str) {
187 self.restore_within(repo, branch, OWNER_LOCK_WAIT).await;
188 }
189
190 async fn restore_within(&self, repo: &Path, branch: &str, wait: std::time::Duration) {
191 let Ok(_owner) = owner_lock_retrying(&self.home, &self.old_id, wait).await else {
192 tracing::warn!("could not lock run {} for handover rollback", self.old_id);
193 return;
194 };
195 let Ok(mut state) = RunState::load_under(&self.old_id, &self.home) else {
196 return;
197 };
198 let claimed =
199 crate::daemon::is_working_on_other(&self.home, &self.old_id, jiff::Timestamp::now())
200 .unwrap_or(true);
201 if state.released_to.as_deref() != Some(self.successor.as_str())
202 || state.status == RunStatus::Superseded
203 || state.pr_taken_over_by.is_some()
204 || state.liveness_under(&self.home, claimed) != Liveness::Dead
205 {
206 tracing::warn!(
207 "run {} changed ownership; handover rollback refused",
208 self.old_id
209 );
210 return;
211 }
212 let path = self.path.to_string_lossy().to_string();
213 let refname = format!("refs/heads/{branch}");
216 if git::rev_parse(repo, &refname).await.ok().as_deref() != Some(self.tip.as_str())
217 && let Err(e) = git::git(repo, &["branch", "-f", branch, &self.tip]).await
218 {
219 tracing::warn!("could not put `{branch}` back at {}: {e:#}", self.tip);
220 return;
221 }
222 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
223 tracing::warn!(
224 "could not put run {}'s worktree back at {path}: {e:#}",
225 self.old_id
226 );
227 return;
228 }
229 if let Some(c) = state.candidates.get_mut(self.index) {
230 c.folded = false;
231 }
232 state.released_to = None;
233 state.released_branches.retain(|b| b != branch);
234 state.events.pop();
235 let put_back = state.save_under(&self.home);
236 if let Err(e) = put_back {
237 tracing::warn!("could not unmark run {}: {e:#}", self.old_id);
238 }
239 }
240}
241
242#[derive(Debug, Clone)]
244pub struct Holder {
245 pub run: String,
247 pub status: RunStatus,
249 pub liveness: Liveness,
251 pub driver_unproven: bool,
254 pub dirty: bool,
256 pub dirty_files: Vec<String>,
258 pub driver_pid: Option<u32>,
260 pub head: String,
262 pub tip: String,
264}
265
266#[derive(Debug, Clone, PartialEq, Eq)]
268pub enum Owner {
269 EarlierAttempt,
271 MagiRun,
274 Foreign(String),
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
280pub enum Decision {
281 Release,
283 Refuse(String),
285}
286
287fn short(sha: &str) -> String {
288 sha.chars().take(7).collect()
289}
290
291pub fn decide(owner: &Owner, holder: &Holder) -> Decision {
297 if let Owner::Foreign(why) = owner {
298 return Decision::Refuse(why.clone());
299 }
300 let mut why = Vec::new();
301 if holder.liveness == Liveness::Live {
302 why.push(format!(
303 "run {} is being worked on right now{}",
304 crate::run::short_of(&holder.run),
305 holder
306 .driver_pid
307 .map(|p| format!(" (driver pid {p})"))
308 .unwrap_or_default()
309 ));
310 } else if holder.liveness == Liveness::Unknown || holder.driver_unproven {
311 why.push("its driver process could not be shown to be gone".to_owned());
312 }
313 if holder.status == RunStatus::Landing {
314 why.push("that run is in `landing`, possibly waiting on an approval".to_owned());
315 }
316 if holder.dirty {
317 let files = holder.dirty_files.join(", ");
318 why.push(format!("its worktree has uncommitted changes ({files})"));
319 }
320 if holder.head != holder.tip {
321 why.push("its HEAD is not at the branch tip".to_owned());
322 }
323 if why.is_empty() {
324 return Decision::Release;
325 }
326 let kind = match owner {
327 Owner::EarlierAttempt => "an earlier attempt at this task",
328 _ => "a magi run of another task",
329 };
330 Decision::Refuse(format!(
331 "run {} (status `{}`, worktree {}, HEAD {}, branch tip {}) is {kind} and still has the \
332 branch checked out, so it was not released automatically: {}",
333 crate::run::short_of(&holder.run),
334 holder.status.as_str(),
335 if holder.dirty { "dirty" } else { "clean" },
336 short(&holder.head),
337 short(&holder.tip),
338 why.join("; ")
339 ))
340}
341
342async fn inspect(
344 repo: &Path,
345 branch: &str,
346 path: &Path,
347 state: &RunState,
348 home: &Path,
349) -> Result<Holder> {
350 let claimed = crate::daemon::is_working_on_other(home, &state.id, jiff::Timestamp::now())?;
351 let liveness = state.liveness_under(home, claimed);
352 let porcelain = git::git(path, &["status", "--porcelain", "--untracked-files=normal"]).await?;
355 Ok(Holder {
356 run: state.id.clone(),
357 status: state.status,
358 liveness,
359 driver_unproven: liveness == Liveness::Unknown,
360 dirty: !porcelain.trim().is_empty(),
361 dirty_files: porcelain
362 .lines()
363 .take(5)
364 .map(|l| l.get(3..).unwrap_or(l).trim().to_owned())
365 .collect(),
366 driver_pid: state.driver_pid,
367 head: git::rev_parse(path, "HEAD").await?,
368 tip: git::rev_parse(repo, &format!("refs/heads/{branch}")).await?,
369 })
370}
371
372fn same_path(a: &Path, b: &Path) -> bool {
373 let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
374 canon(a) == canon(b)
375}
376
377fn foreign(branch: &str, path: &Path, why: &str) -> anyhow::Error {
378 Refused::Foreign {
379 branch: branch.to_owned(),
380 path: path.display().to_string(),
381 why: why.to_owned(),
382 }
383 .into()
384}
385
386pub async fn preflight(
389 repo: &Path,
390 branch: &str,
391 home: &Path,
392) -> Result<Option<crate::foreign_checkout::ForeignCheckout>> {
393 let Some(path) = git::worktree_holding(repo, branch).await? else {
394 return Ok(None);
395 };
396 match find_magi_owner(&path, home) {
397 Ok(Some(_)) => return Ok(None),
398 Err(why) => return Err(foreign(branch, &path, &why)),
399 Ok(None) => {}
400 }
401 crate::foreign_checkout::inspect(repo, branch, &path)
402 .await
403 .map(Some)
404 .map_err(|error| foreign(branch, &path, &format!("{error:#}")))
405}
406
407pub async fn preflight_review(
410 repo: &Path,
411 branch: &str,
412 home: &Path,
413 remote: &str,
414) -> Result<Option<crate::foreign_checkout::ForeignCheckout>> {
415 let checkout = preflight(repo, branch, home).await?;
416 if let Some(checkout) = &checkout {
417 let fetched = git::fetch(repo, remote, branch).await;
418 if matches!(fetched, Ok(ref out) if out.ok()) {
419 let tracking = format!("{remote}/{branch}");
420 let tip = git::rev_parse(repo, &tracking).await?;
421 if !git::is_ancestor(repo, &checkout.synced_head, &tip).await
422 && !git::is_ancestor(repo, &tip, &checkout.synced_head).await
423 {
424 return Err(foreign(
425 branch,
426 &checkout.path,
427 &format!("branch diverged from {tracking}; reconcile it before review"),
428 ));
429 }
430 }
431 }
432 Ok(checkout)
433}
434
435fn find_magi_owner(
440 path: &Path,
441 home: &Path,
442) -> std::result::Result<Option<(RunState, usize)>, String> {
443 let Some(bay) = path.parent() else {
444 return Ok(None);
445 };
446 let Some(bay_name) = bay.file_name().and_then(|n| n.to_str()) else {
447 return Ok(None);
448 };
449 let mut found = Vec::new();
450 for id in crate::run::list_ids_in(&home.join("runs")) {
451 if crate::run::short_of(&id) != bay_name {
452 continue;
453 }
454 let Ok(state) = RunState::load_under(&id, home) else {
455 return Err(format!("run {bay_name}'s record could not be read"));
456 };
457 if !same_path(&state.worktree_root(), bay) {
458 continue;
459 }
460 if let Some(i) = state
461 .candidates
462 .iter()
463 .position(|c| !c.folded && same_path(&c.worktree, path))
464 {
465 found.push((state, i));
466 }
467 }
468 match found.len() {
469 0 => Ok(None),
470 1 => Ok(found.pop()),
471 _ => Err(format!("more than one run record claims it ({bay_name})")),
472 }
473}
474
475pub(crate) fn landing_checkpoint(state: &RunState) -> bool {
478 state.status.resumable()
479 && state.config.graph.land
480 && state.pr.as_ref().is_some_and(|pr| pr.state == "open")
481 && state
482 .merge
483 .as_ref()
484 .is_some_and(|m| m.mode == crate::config::MergeMode::Pr && !m.empty)
485}
486
487#[derive(Debug, Clone, PartialEq, Eq)]
489pub(crate) enum ResumeRefusal {
490 Status(RunStatus),
491 Released(String),
492 Retired(String),
493 OwnershipTransferred(String),
494 ReviewBudget { used: usize, limit: usize },
495 ReviewDisabled,
496 CleanReviewGateRan,
497 BaseSyncStop,
498}
499
500impl ResumeRefusal {
501 pub(crate) fn successor(&self) -> Option<&str> {
503 match self {
504 Self::Released(to) | Self::Retired(to) | Self::OwnershipTransferred(to) => Some(to),
505 _ => None,
506 }
507 }
508
509 pub(crate) fn diagnostic(&self, state: &RunState) -> String {
510 let reason = match self {
511 Self::BaseSyncStop => "base synchronization is stopped; inspect the retained work. For movement exhaustion only, use `magi run --resume <run> --recover-base` (standing chat: `magi task control recover-base <run> --request <id> --head <retained-sha>`, full SHA or 7+ hex digits) to authorize a new bounded synchronization interval and fresh verification".into(),
512 Self::Status(status) => format!("status `{}` is final; there is nothing left to resume", status.as_str()),
513 Self::Released(_) => "execution was released".into(),
514 Self::Retired(_) => "execution was retired".into(),
515 Self::OwnershipTransferred(_) => "PR ownership was transferred".into(),
516 Self::ReviewBudget { used, limit } => format!("review budget exhausted ({used}/{limit} rounds used)"),
517 Self::CleanReviewGateRan => "review already has a clean round and the gate already ran; no retryable checkpoint remains".into(),
518 Self::ReviewDisabled => "review is disabled (review_rounds = 0) and no retryable checkpoint or pending gate remains".into(),
519 };
520 let mut detail = format!("run {} cannot resume: {reason}.", state.short());
521 if let Some(cause) = state.stale_pr_cause() {
522 detail.push(' ');
523 detail.push_str(&cause);
524 }
525 if let Some(target) = self.successor() {
526 let target = if matches!(self, Self::Retired(_)) {
527 target
528 } else {
529 crate::run::short_of(target)
530 };
531 detail.push_str(&format!(" Successor: run {target}; inspect `magi show {target}` before choosing any further action."));
532 }
533 for (label, target) in [
534 ("released to", &state.released_to),
535 ("retired to", &state.retired_to),
536 ("PR ownership moved to", &state.pr_taken_over_by),
537 ] {
538 if let Some(target) = target {
539 if self.successor() == Some(target.as_str()) {
540 continue;
541 }
542 let target = if label == "retired to" {
543 target.as_str()
544 } else {
545 crate::run::short_of(target)
546 };
547 detail.push_str(&format!(" {label} run {target}; inspect `magi show {target}` before choosing any further action."));
548 }
549 }
550 detail.push_str(&format!(
551 " Inspect `magi show {}` for retained work and ownership.",
552 state.id
553 ));
554 if matches!(self, Self::BaseSyncStop) {
555 detail.push_str(&format!(" {}", state.base_sync_next_action()));
556 }
557 if matches!(self, Self::ReviewBudget { .. } | Self::ReviewDisabled) {
558 detail.push_str(" To continue the retained implementation, first confirm its saved candidate branch and owning task with `magi task show <task-id>`. When the task is eligible and no driver is live, explicitly use `magi review <saved-branch> --task <task-id> --merge none --review-rounds <positive-rounds>`. This creates a review-only successor with a new review budget; it does not resume this run or start a new implementation competition. Existing ownership and checkpoint checks still apply.");
559 }
560 detail
561 }
562}
563
564pub(crate) fn can_resume(state: &RunState) -> bool {
568 resume_refusal(state).is_none()
569}
570
571pub(crate) fn resume_refusal(state: &RunState) -> Option<ResumeRefusal> {
572 resume_refusal_under(state, crate::run::try_home().as_deref())
573}
574
575pub(crate) fn resume_refusal_under(state: &RunState, home: Option<&Path>) -> Option<ResumeRefusal> {
577 if !state.status.resumable() {
578 return Some(ResumeRefusal::Status(state.status));
579 }
580 if let Some(to) = &state.released_to {
581 return Some(ResumeRefusal::Released(to.clone()));
582 }
583 if let Some(to) = &state.retired_to {
584 return Some(ResumeRefusal::Retired(to.clone()));
585 }
586 if let Some(to) = &state.pr_taken_over_by {
587 return Some(ResumeRefusal::OwnershipTransferred(to.clone()));
588 }
589 if state.base_sync_blocked() {
590 return if state.base_recovery_pending()
591 || state.base_sync_closure_pending()
592 || crate::repair_budget::legacy::resumable_sequencer_stop(state)
593 || home.is_some_and(|home| {
594 state
595 .origin
596 .as_ref()
597 .and_then(|o| o.task.as_ref())
598 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
599 .is_some_and(|task| crate::repair_budget::conflict_pending(&task, state))
600 }) {
601 None
602 } else {
603 Some(ResumeRefusal::BaseSyncStop)
604 };
605 }
606 let review = crate::graph::review_conclusion(&state.reviews, state.config.graph.review_rounds);
607 let allowed = resume_checkpoint(state)
608 || state
609 .repair_grants
610 .last()
611 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
612 || home.is_some_and(|home| {
613 state
614 .origin
615 .as_ref()
616 .and_then(|o| o.task.as_ref())
617 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
618 .is_some_and(|task| crate::repair_budget::pending(&task, state))
619 })
620 || home.is_some_and(|home| has_resume_checkpoint(state, home))
621 || ((state.config.graph.review_rounds == 0
622 || state.reviews.iter().any(|round| round.clean))
623 && (!state.gate_ran || state.resource_block.is_some()))
624 || (state.resource_block.is_some() && review == Some(RunStatus::Gating))
625 || (review.is_none()
626 && state
627 .reviews
628 .last()
629 .is_some_and(|round| round.e2e_status() == crate::run::E2eStatus::ResourceBlocked))
630 || !(state.status == RunStatus::Blocked
631 && state.reviews.len() >= state.config.graph.review_rounds);
632 if allowed {
633 None
634 } else if state.config.graph.review_rounds == 0 {
635 Some(ResumeRefusal::ReviewDisabled)
636 } else if state.reviews.iter().any(|round| round.clean) {
637 Some(ResumeRefusal::CleanReviewGateRan)
638 } else {
639 Some(ResumeRefusal::ReviewBudget {
640 used: state.reviews.len(),
641 limit: state.config.graph.review_rounds,
642 })
643 }
644}
645
646fn resume_checkpoint(state: &RunState) -> bool {
647 state.status == RunStatus::Landing
648 || landing_checkpoint(state)
649 || state.pending_base_operation().is_some()
650 || state.pr_publication_pending
651 || state.land_approval.is_some()
652 || state.merge_decision.is_some()
653 || state.land_armed_head.is_some()
654 || !state.merge_repairs.is_empty()
655}
656
657pub(crate) fn has_resume_checkpoint(state: &RunState, home: &Path) -> bool {
661 state.status.resumable()
662 && (resume_checkpoint(state)
663 || crate::ask::Questions::at(home.join("questions"))
664 .list_for_effects()
665 .iter()
666 .any(|q| q.run == state.id && q.status.open()))
667}
668
669async fn locked_holder(
672 home: &Path,
673 id: &str,
674 path: &Path,
675) -> Result<(RunState, usize, crate::pr_head::OwnerLock)> {
676 locked_holder_within(home, id, path, OWNER_LOCK_WAIT).await
677}
678
679async fn locked_holder_within(
680 home: &Path,
681 id: &str,
682 path: &Path,
683 wait: std::time::Duration,
684) -> Result<(RunState, usize, crate::pr_head::OwnerLock)> {
685 let owner = owner_lock_retrying(home, id, wait).await?;
686 let state = RunState::load_under(id, home)?;
687 let index = state
688 .candidates
689 .iter()
690 .position(|c| !c.folded && same_path(&c.worktree, path))
691 .ok_or_else(|| anyhow::anyhow!("worktree holder changed; retry takeover"))?;
692 anyhow::ensure!(
693 state.released_to.is_none(),
694 "run already handed over its worktree; retry takeover"
695 );
696 anyhow::ensure!(
697 path.parent()
698 .is_some_and(|p| same_path(&state.worktree_root(), p)),
699 "worktree holder root changed; retry takeover"
700 );
701 Ok((state, index, owner))
702}
703
704pub async fn release(
712 repo: &Path,
713 branch: &str,
714 new_run: &str,
715 takeover: &Takeover,
716) -> Result<Option<Released>> {
717 let Some(path) = git::worktree_holding(repo, branch).await? else {
718 return Ok(None);
719 };
720 let mut owner = None;
723 for id in &takeover.earlier {
724 let Ok(state) = RunState::load_under(id, &takeover.home) else {
725 continue;
726 };
727 if let Some(i) = state
728 .candidates
729 .iter()
730 .position(|c| !c.folded && same_path(&c.worktree, &path))
731 {
732 if !path
734 .parent()
735 .is_some_and(|b| same_path(&state.worktree_root(), b))
736 {
737 return Err(foreign(
738 branch,
739 &path,
740 &format!(
741 "run {} records it, but it is outside that run's worktree root, so \
742 magi did not make it",
743 crate::run::short_of(id)
744 ),
745 ));
746 }
747 owner = Some((state, i, Owner::EarlierAttempt));
748 break;
749 }
750 }
751 if owner.is_none() {
752 owner = match find_magi_owner(&path, &takeover.home) {
753 Ok(found) => found.map(|(s, i)| (s, i, Owner::MagiRun)),
754 Err(why) => return Err(foreign(branch, &path, &why)),
755 };
756 }
757 let Some((state, _, kind)) = owner else {
758 preflight(repo, branch, &takeover.home).await?;
759 return Ok(None);
760 };
761
762 let (mut state, index, _owner) = locked_holder(&takeover.home, &state.id, &path).await?;
763 if has_resume_checkpoint(&state, &takeover.home) {
764 return Err(Refused::Unsafe {
765 branch: branch.to_owned(),
766 path: path.display().to_string(),
767 why: format!("run {} has a resumable publication, landing or decision checkpoint; resume that run instead of releasing its worktree", state.short()),
768 }.into());
769 }
770 let holder = inspect(repo, branch, &path, &state, &takeover.home).await?;
771 if let Decision::Refuse(why) = decide(&kind, &holder) {
772 return Err(Refused::Unsafe {
773 branch: branch.to_owned(),
774 path: path.display().to_string(),
775 why,
776 }
777 .into());
778 }
779 let audit = format!(
780 "run {} (status `{}`, no driver, clean, HEAD {} = branch tip, branch `{branch}` kept)",
781 crate::run::short_of(&holder.run),
782 holder.status.as_str(),
783 short(&holder.head)
784 );
785
786 let old_id = state.id.clone();
787 state.candidates[index].folded = true;
788 state.released_to = Some(new_run.to_owned());
789 if !state.released_branches.iter().any(|b| b == branch) {
790 state.released_branches.push(branch.to_owned());
791 }
792 state.event(
793 "release",
794 format!(
795 "worktree of `{branch}` released to run {}: {audit}; this run can no longer be \
796 resumed from here",
797 crate::run::short_of(new_run)
798 ),
799 );
800 state.save_under(&takeover.home)?;
801
802 let again = match RunState::load_under(&old_id, &takeover.home) {
810 Ok(fresh) => inspect(repo, branch, &path, &fresh, &takeover.home).await,
811 Err(e) => Err(e),
812 };
813 let safe = matches!(&again, Ok(h) if decide(&kind, h) == Decision::Release);
814 let removed = safe
815 && git::worktree_remove_clean(repo, &path)
816 .await
817 .unwrap_or(false);
818 if !removed || path.exists() {
819 state = RunState::load_under(&old_id, &takeover.home)?;
820 state.candidates[index].folded = false;
821 state.released_to = None;
822 state.released_branches.retain(|b| b != branch);
823 state.events.pop();
824 state.event(
825 "release",
826 format!(
827 "release of `{branch}` to run {} was undone: {audit}",
828 crate::run::short_of(new_run)
829 ),
830 );
831 state.save_under(&takeover.home)?;
832 return Err(Refused::ReleaseFailed {
833 branch: branch.to_owned(),
834 path: path.display().to_string(),
835 run: crate::run::short_of(&old_id).to_owned(),
836 }
837 .into());
838 }
839 Ok(Some(Released {
840 old_id,
841 index,
842 path,
843 home: takeover.home.clone(),
844 successor: new_run.to_owned(),
845 tip: holder.tip,
846 audit,
847 }))
848}
849
850#[cfg(test)]
851mod tests {
852 #[test]
853 fn refused_display_is_the_english_text() {
854 let r = Refused::Foreign {
855 branch: "b".into(),
856 path: "/w".into(),
857 why: "w".into(),
858 };
859 assert_eq!(
860 r.to_string(),
861 "branch `b` is checked out in /w, which magi will not remove by itself: w. Commit or stash changes first. If no longer needed, run: git worktree remove '/w' (or renri remove 'b' -y --non-interactive), then try again."
862 );
863 }
864
865 use super::*;
866
867 fn holder() -> Holder {
868 Holder {
869 run: "20260901-000000-f82f".to_owned(),
870 status: RunStatus::Gating,
871 liveness: Liveness::Dead,
872 driver_unproven: false,
873 dirty: false,
874 dirty_files: Vec::new(),
875 driver_pid: None,
876 head: "a".repeat(40),
877 tip: "a".repeat(40),
878 }
879 }
880
881 fn recorded_holder(home: &Path) -> (RunState, PathBuf) {
882 let mut state = RunState::new(
883 "repo".into(),
884 "main".into(),
885 "base".into(),
886 "task".into(),
887 crate::config::Config::default(),
888 );
889 state.config.graph.worktree_root = Some(home.join("worktrees"));
890 let path = state.worktree_root().join("cand-A");
891 std::fs::create_dir_all(&path).unwrap();
892 state.driver_exited = true;
893 state.candidates.push(crate::run::Candidate {
894 index: 0,
895 label: 'A',
896 agent: "existing".into(),
897 branch: "branch".into(),
898 worktree: path.clone(),
899 summary: String::new(),
900 stat: String::new(),
901 files: 1,
902 commits: 1,
903 empty: false,
904 failed: None,
905 verified_noop: None,
906 duration_ms: 0,
907 folded: false,
908 });
909 state.save_under(home).unwrap();
910 (state, path)
911 }
912
913 #[tokio::test]
914 async fn handover_reloads_a_driver_claim_after_the_scan_and_excludes_new_claims() {
915 let home = tempfile::tempdir().unwrap();
916 let (mut state, path) = recorded_holder(home.path());
917 let scanned = state.clone();
918 state.driver_exited = false;
920 state.driver_pid = Some(std::process::id());
921 state.driver_started_at = crate::proc::process_started_at(std::process::id());
922 state.begin_pass();
923 state.save_under(home.path()).unwrap();
924 let mut driver = crate::driver::DriverGuard::acquire(home.path(), &state).unwrap();
925 driver.record(&state).unwrap();
926 let (fresh, _, owner) = locked_holder(home.path(), &scanned.id, &path)
927 .await
928 .unwrap();
929 assert!(!fresh.driver_exited);
930 assert_eq!(fresh.passes, state.passes);
931 assert_ne!(fresh.liveness_under(home.path(), false), Liveness::Dead);
932 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_err());
933 assert!(path.exists());
934 assert!(
935 RunState::load_under(&state.id, home.path())
936 .unwrap()
937 .released_to
938 .is_none()
939 );
940 drop(owner);
941 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_ok());
942 }
943
944 #[tokio::test]
945 async fn handover_revalidates_candidate_ownership_under_the_claim_lock() {
946 let home = tempfile::tempdir().unwrap();
947 let (mut state, path) = recorded_holder(home.path());
948 state.candidates[0].folded = true;
949 state.released_to = Some("next".into());
950 state.save_under(home.path()).unwrap();
951 assert!(locked_holder(home.path(), &state.id, &path).await.is_err());
952 assert!(path.exists());
953 }
954
955 async fn released_predecessor(home: &Path, repo: &Path) -> (RunState, Released) {
958 crate::clean::tests::init_repo(repo);
959 let mut state = RunState::new(
960 repo.to_owned(),
961 "main".into(),
962 "base".into(),
963 "task".into(),
964 crate::config::Config::default(),
965 );
966 state.config.graph.worktree_root = Some(home.join("worktrees"));
967 let path = state.worktree_root().join("cand-A");
968 let branch = "magi/restore/A";
969 git::worktree_add_branch(repo, &path, branch, "main")
970 .await
971 .unwrap();
972 let tip = git::rev_parse(repo, branch).await.unwrap();
973 state.driver_exited = true;
974 state.status = RunStatus::Ready;
975 state.candidates.push(crate::run::Candidate {
976 index: 0,
977 label: 'A',
978 agent: "existing".into(),
979 branch: branch.into(),
980 worktree: path.clone(),
981 summary: String::new(),
982 stat: String::new(),
983 files: 1,
984 commits: 1,
985 empty: false,
986 failed: None,
987 verified_noop: None,
988 duration_ms: 0,
989 folded: true,
990 });
991 state.released_to = Some("successor".into());
992 state.released_branches.push(branch.into());
993 state.event("release", "worktree released");
994 state.save_under(home).unwrap();
995 git::git(repo, &["worktree", "remove", path.to_str().unwrap()])
996 .await
997 .unwrap();
998 let released = Released {
999 old_id: state.id.clone(),
1000 index: 0,
1001 path,
1002 home: home.to_owned(),
1003 successor: "successor".into(),
1004 tip,
1005 audit: String::new(),
1006 };
1007 (state, released)
1008 }
1009
1010 #[tokio::test]
1014 async fn a_rollback_waits_out_a_brief_hold_on_the_owner_lock() {
1015 let home = tempfile::tempdir().unwrap();
1016 let repo = home.path().join("repo");
1017 std::fs::create_dir_all(&repo).unwrap();
1018 let (state, released) = released_predecessor(home.path(), &repo).await;
1019 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1020 let release = std::thread::spawn(move || {
1021 std::thread::sleep(std::time::Duration::from_millis(300));
1022 drop(held);
1023 });
1024 released
1025 .restore_within(&repo, "magi/restore/A", std::time::Duration::from_secs(30))
1026 .await;
1027 release.join().unwrap();
1028 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1029 assert!(released.path.exists(), "the worktree is back");
1030 assert!(disk.released_to.is_none() && !disk.candidates[0].folded);
1031 }
1032
1033 #[tokio::test]
1035 async fn a_rollback_gives_up_on_a_lock_held_beyond_its_bound() {
1036 let home = tempfile::tempdir().unwrap();
1037 let repo = home.path().join("repo");
1038 std::fs::create_dir_all(&repo).unwrap();
1039 let (state, released) = released_predecessor(home.path(), &repo).await;
1040 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1041 released
1042 .restore_within(
1043 &repo,
1044 "magi/restore/A",
1045 std::time::Duration::from_millis(150),
1046 )
1047 .await;
1048 drop(held);
1049 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1050 assert!(!released.path.exists());
1051 assert_eq!(disk.released_to.as_deref(), Some("successor"));
1052 assert!(disk.candidates[0].folded);
1053 }
1054
1055 async fn held_predecessor(home: &Path, repo: &Path) -> (RunState, PathBuf, Takeover) {
1058 crate::clean::tests::init_repo(repo);
1059 let mut state = RunState::new(
1060 repo.to_owned(),
1061 "main".into(),
1062 "base".into(),
1063 "task".into(),
1064 crate::config::Config::default(),
1065 );
1066 state.config.graph.worktree_root = Some(home.join("worktrees"));
1067 let path = state.worktree_root().join("cand-A");
1068 let branch = "magi/take/A";
1069 git::worktree_add_branch(repo, &path, branch, "main")
1070 .await
1071 .unwrap();
1072 state.driver_exited = true;
1073 state.status = RunStatus::Gating;
1074 state.candidates.push(crate::run::Candidate {
1075 index: 0,
1076 label: 'A',
1077 agent: "existing".into(),
1078 branch: branch.into(),
1079 worktree: path.clone(),
1080 summary: String::new(),
1081 stat: String::new(),
1082 files: 1,
1083 commits: 1,
1084 empty: false,
1085 failed: None,
1086 verified_noop: None,
1087 duration_ms: 0,
1088 folded: false,
1089 });
1090 state.save_under(home).unwrap();
1091 let takeover = Takeover {
1092 earlier: vec![state.id.clone()],
1093 home: home.to_owned(),
1094 choice: None,
1095 task_instruction: None,
1096 };
1097 (state, path, takeover)
1098 }
1099
1100 #[tokio::test]
1104 async fn a_handover_waits_out_a_brief_hold_on_the_owner_lock() {
1105 let home = tempfile::tempdir().unwrap();
1106 let repo = home.path().join("repo");
1107 std::fs::create_dir_all(&repo).unwrap();
1108 let (state, path, takeover) = held_predecessor(home.path(), &repo).await;
1109 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1110 let fold = std::thread::spawn(move || {
1111 std::thread::sleep(std::time::Duration::from_millis(300));
1112 drop(held);
1113 });
1114 let released = release(&repo, "magi/take/A", "successor", &takeover)
1115 .await
1116 .expect("the handover is not failed by a brief hold")
1117 .expect("the worktree is released");
1118 fold.join().unwrap();
1119 assert_eq!(released.old_id, state.id);
1120 assert!(!path.exists(), "the worktree was released");
1121 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1122 assert_eq!(disk.released_to.as_deref(), Some("successor"));
1123 }
1124
1125 #[tokio::test]
1128 async fn a_handover_fails_on_a_lock_held_beyond_its_bound() {
1129 let home = tempfile::tempdir().unwrap();
1130 let repo = home.path().join("repo");
1131 std::fs::create_dir_all(&repo).unwrap();
1132 let (state, path, _) = held_predecessor(home.path(), &repo).await;
1133 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1134 let error = locked_holder_within(
1135 home.path(),
1136 &state.id,
1137 &path,
1138 std::time::Duration::from_millis(150),
1139 )
1140 .await
1141 .err()
1142 .expect("the lock is still held after the bound");
1143 assert!(crate::graph::held_by_live_owner(&error), "{error:#}");
1144 drop(held);
1145 assert!(path.exists());
1146 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1147 assert!(disk.released_to.is_none() && !disk.candidates[0].folded);
1148 }
1149
1150 #[test]
1153 fn the_last_pause_is_clipped_to_the_remaining_bound() {
1154 use std::time::Duration;
1155 assert_eq!(
1156 pause_within(Duration::from_millis(80), Duration::from_millis(500)),
1157 Duration::from_millis(80)
1158 );
1159 assert_eq!(
1160 pause_within(Duration::from_millis(80), Duration::from_millis(30)),
1161 Duration::from_millis(30)
1162 );
1163 }
1164
1165 #[tokio::test]
1166 async fn a_stale_restore_does_not_undo_a_later_handover() {
1167 let home = tempfile::tempdir().unwrap();
1168 let (mut state, path) = recorded_holder(home.path());
1169 state.candidates[0].folded = true;
1170 state.released_to = Some("later".into());
1171 state.save_under(home.path()).unwrap();
1172 let released = Released {
1173 old_id: state.id.clone(),
1174 index: 0,
1175 path,
1176 home: home.path().to_owned(),
1177 successor: "original".into(),
1178 tip: "tip".into(),
1179 audit: String::new(),
1180 };
1181 released.restore(Path::new("nonexistent"), "branch").await;
1182 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1183 assert_eq!(disk.released_to.as_deref(), Some("later"));
1184 assert!(disk.candidates[0].folded);
1185 }
1186
1187 #[test]
1188 fn a_clean_superseded_stale_run_is_released() {
1189 assert_eq!(decide(&Owner::EarlierAttempt, &holder()), Decision::Release);
1190 let dead = Holder {
1191 liveness: Liveness::Dead,
1192 ..holder()
1193 };
1194 assert_eq!(decide(&Owner::EarlierAttempt, &dead), Decision::Release);
1195 }
1196
1197 #[test]
1198 fn a_foreign_worktree_is_refused_with_its_reason() {
1199 let owner = Owner::Foreign("it is a foreign path".to_owned());
1200 assert_eq!(
1201 decide(&owner, &holder()),
1202 Decision::Refuse("it is a foreign path".to_owned())
1203 );
1204 }
1205
1206 #[test]
1207 fn landing_is_protected_even_for_an_earlier_attempt() {
1208 let landing = Holder {
1209 status: RunStatus::Landing,
1210 ..holder()
1211 };
1212 assert!(matches!(
1213 decide(&Owner::MagiRun, &landing),
1214 Decision::Refuse(_)
1215 ));
1216 assert!(matches!(
1217 decide(&Owner::EarlierAttempt, &landing),
1218 Decision::Refuse(_)
1219 ));
1220 }
1221
1222 #[test]
1223 fn a_dirty_worktree_is_refused_and_says_why() {
1224 let dirty = Holder {
1225 dirty: true,
1226 dirty_files: vec!["scratch.txt".to_owned()],
1227 ..holder()
1228 };
1229 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &dirty) else {
1230 panic!("dirty must be refused");
1231 };
1232 assert!(
1233 why.contains("uncommitted") && why.contains("scratch.txt"),
1234 "{why}"
1235 );
1236 assert!(why.contains("f82f") && why.contains("gating") && why.contains("dirty"));
1237 }
1238
1239 #[test]
1240 fn a_live_run_is_refused() {
1241 let live = Holder {
1242 liveness: Liveness::Live,
1243 driver_pid: Some(4242),
1244 ..holder()
1245 };
1246 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &live) else {
1247 panic!("live must be refused");
1248 };
1249 assert!(
1250 why.contains("right now") && why.contains("f82f") && why.contains("4242"),
1251 "{why}"
1252 );
1253 }
1254
1255 #[test]
1256 fn unknown_without_a_recorded_pid_is_not_proof_of_a_stopped_driver() {
1257 let holder = Holder {
1258 liveness: Liveness::Unknown,
1259 ..holder()
1260 };
1261 assert!(matches!(
1262 decide(&Owner::EarlierAttempt, &holder),
1263 Decision::Refuse(_)
1264 ));
1265 }
1266
1267 #[test]
1268 fn a_driver_that_could_not_be_shown_dead_is_refused() {
1269 let unproven = Holder {
1270 driver_unproven: true,
1271 ..holder()
1272 };
1273 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &unproven) else {
1274 panic!("an unproven driver must be refused");
1275 };
1276 assert!(why.contains("driver"), "{why}");
1277 }
1278
1279 #[test]
1280 fn a_head_off_the_tip_is_refused() {
1281 let off = Holder {
1282 head: "b".repeat(40),
1283 ..holder()
1284 };
1285 assert!(matches!(
1286 decide(&Owner::EarlierAttempt, &off),
1287 Decision::Refuse(_)
1288 ));
1289 }
1290}