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(target) = self.successor() {
522 let target = if matches!(self, Self::Retired(_)) {
523 target
524 } else {
525 crate::run::short_of(target)
526 };
527 detail.push_str(&format!(" Successor: run {target}; inspect `magi show {target}` before choosing any further action."));
528 }
529 for (label, target) in [
530 ("released to", &state.released_to),
531 ("retired to", &state.retired_to),
532 ("PR ownership moved to", &state.pr_taken_over_by),
533 ] {
534 if let Some(target) = target {
535 if self.successor() == Some(target.as_str()) {
536 continue;
537 }
538 let target = if label == "retired to" {
539 target.as_str()
540 } else {
541 crate::run::short_of(target)
542 };
543 detail.push_str(&format!(" {label} run {target}; inspect `magi show {target}` before choosing any further action."));
544 }
545 }
546 detail.push_str(&format!(
547 " Inspect `magi show {}` for retained work and ownership.",
548 state.id
549 ));
550 if matches!(self, Self::BaseSyncStop) {
551 detail.push_str(&format!(" {}", state.base_sync_next_action()));
552 }
553 if matches!(self, Self::ReviewBudget { .. } | Self::ReviewDisabled) {
554 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.");
555 }
556 detail
557 }
558}
559
560pub(crate) fn can_resume(state: &RunState) -> bool {
564 resume_refusal(state).is_none()
565}
566
567pub(crate) fn resume_refusal(state: &RunState) -> Option<ResumeRefusal> {
568 resume_refusal_under(state, crate::run::try_home().as_deref())
569}
570
571pub(crate) fn resume_refusal_under(state: &RunState, home: Option<&Path>) -> Option<ResumeRefusal> {
573 if !state.status.resumable() {
574 return Some(ResumeRefusal::Status(state.status));
575 }
576 if let Some(to) = &state.released_to {
577 return Some(ResumeRefusal::Released(to.clone()));
578 }
579 if let Some(to) = &state.retired_to {
580 return Some(ResumeRefusal::Retired(to.clone()));
581 }
582 if let Some(to) = &state.pr_taken_over_by {
583 return Some(ResumeRefusal::OwnershipTransferred(to.clone()));
584 }
585 if state.base_sync_blocked() {
586 return if state.base_recovery_pending()
587 || state.base_sync_closure_pending()
588 || crate::repair_budget::legacy::resumable_sequencer_stop(state)
589 || home.is_some_and(|home| {
590 state
591 .origin
592 .as_ref()
593 .and_then(|o| o.task.as_ref())
594 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
595 .is_some_and(|task| crate::repair_budget::conflict_pending(&task, state))
596 }) {
597 None
598 } else {
599 Some(ResumeRefusal::BaseSyncStop)
600 };
601 }
602 let review = crate::graph::review_conclusion(&state.reviews, state.config.graph.review_rounds);
603 let allowed = resume_checkpoint(state)
604 || state
605 .repair_grants
606 .last()
607 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
608 || home.is_some_and(|home| {
609 state
610 .origin
611 .as_ref()
612 .and_then(|o| o.task.as_ref())
613 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
614 .is_some_and(|task| crate::repair_budget::pending(&task, state))
615 })
616 || home.is_some_and(|home| has_resume_checkpoint(state, home))
617 || ((state.config.graph.review_rounds == 0
618 || state.reviews.iter().any(|round| round.clean))
619 && (!state.gate_ran || state.resource_block.is_some()))
620 || (state.resource_block.is_some() && review == Some(RunStatus::Gating))
621 || (review.is_none()
622 && state
623 .reviews
624 .last()
625 .is_some_and(|round| round.e2e_status() == crate::run::E2eStatus::ResourceBlocked))
626 || !(state.status == RunStatus::Blocked
627 && state.reviews.len() >= state.config.graph.review_rounds);
628 if allowed {
629 None
630 } else if state.config.graph.review_rounds == 0 {
631 Some(ResumeRefusal::ReviewDisabled)
632 } else if state.reviews.iter().any(|round| round.clean) {
633 Some(ResumeRefusal::CleanReviewGateRan)
634 } else {
635 Some(ResumeRefusal::ReviewBudget {
636 used: state.reviews.len(),
637 limit: state.config.graph.review_rounds,
638 })
639 }
640}
641
642fn resume_checkpoint(state: &RunState) -> bool {
643 state.status == RunStatus::Landing
644 || landing_checkpoint(state)
645 || state.pending_base_operation().is_some()
646 || state.pr_publication_pending
647 || state.land_approval.is_some()
648 || state.merge_decision.is_some()
649 || state.land_armed_head.is_some()
650 || !state.merge_repairs.is_empty()
651}
652
653pub(crate) fn has_resume_checkpoint(state: &RunState, home: &Path) -> bool {
657 state.status.resumable()
658 && (resume_checkpoint(state)
659 || crate::ask::Questions::at(home.join("questions"))
660 .list_for_effects()
661 .iter()
662 .any(|q| q.run == state.id && q.status.open()))
663}
664
665async fn locked_holder(
668 home: &Path,
669 id: &str,
670 path: &Path,
671) -> Result<(RunState, usize, crate::pr_head::OwnerLock)> {
672 locked_holder_within(home, id, path, OWNER_LOCK_WAIT).await
673}
674
675async fn locked_holder_within(
676 home: &Path,
677 id: &str,
678 path: &Path,
679 wait: std::time::Duration,
680) -> Result<(RunState, usize, crate::pr_head::OwnerLock)> {
681 let owner = owner_lock_retrying(home, id, wait).await?;
682 let state = RunState::load_under(id, home)?;
683 let index = state
684 .candidates
685 .iter()
686 .position(|c| !c.folded && same_path(&c.worktree, path))
687 .ok_or_else(|| anyhow::anyhow!("worktree holder changed; retry takeover"))?;
688 anyhow::ensure!(
689 state.released_to.is_none(),
690 "run already handed over its worktree; retry takeover"
691 );
692 anyhow::ensure!(
693 path.parent()
694 .is_some_and(|p| same_path(&state.worktree_root(), p)),
695 "worktree holder root changed; retry takeover"
696 );
697 Ok((state, index, owner))
698}
699
700pub async fn release(
708 repo: &Path,
709 branch: &str,
710 new_run: &str,
711 takeover: &Takeover,
712) -> Result<Option<Released>> {
713 let Some(path) = git::worktree_holding(repo, branch).await? else {
714 return Ok(None);
715 };
716 let mut owner = None;
719 for id in &takeover.earlier {
720 let Ok(state) = RunState::load_under(id, &takeover.home) else {
721 continue;
722 };
723 if let Some(i) = state
724 .candidates
725 .iter()
726 .position(|c| !c.folded && same_path(&c.worktree, &path))
727 {
728 if !path
730 .parent()
731 .is_some_and(|b| same_path(&state.worktree_root(), b))
732 {
733 return Err(foreign(
734 branch,
735 &path,
736 &format!(
737 "run {} records it, but it is outside that run's worktree root, so \
738 magi did not make it",
739 crate::run::short_of(id)
740 ),
741 ));
742 }
743 owner = Some((state, i, Owner::EarlierAttempt));
744 break;
745 }
746 }
747 if owner.is_none() {
748 owner = match find_magi_owner(&path, &takeover.home) {
749 Ok(found) => found.map(|(s, i)| (s, i, Owner::MagiRun)),
750 Err(why) => return Err(foreign(branch, &path, &why)),
751 };
752 }
753 let Some((state, _, kind)) = owner else {
754 preflight(repo, branch, &takeover.home).await?;
755 return Ok(None);
756 };
757
758 let (mut state, index, _owner) = locked_holder(&takeover.home, &state.id, &path).await?;
759 if has_resume_checkpoint(&state, &takeover.home) {
760 return Err(Refused::Unsafe {
761 branch: branch.to_owned(),
762 path: path.display().to_string(),
763 why: format!("run {} has a resumable publication, landing or decision checkpoint; resume that run instead of releasing its worktree", state.short()),
764 }.into());
765 }
766 let holder = inspect(repo, branch, &path, &state, &takeover.home).await?;
767 if let Decision::Refuse(why) = decide(&kind, &holder) {
768 return Err(Refused::Unsafe {
769 branch: branch.to_owned(),
770 path: path.display().to_string(),
771 why,
772 }
773 .into());
774 }
775 let audit = format!(
776 "run {} (status `{}`, no driver, clean, HEAD {} = branch tip, branch `{branch}` kept)",
777 crate::run::short_of(&holder.run),
778 holder.status.as_str(),
779 short(&holder.head)
780 );
781
782 let old_id = state.id.clone();
783 state.candidates[index].folded = true;
784 state.released_to = Some(new_run.to_owned());
785 if !state.released_branches.iter().any(|b| b == branch) {
786 state.released_branches.push(branch.to_owned());
787 }
788 state.event(
789 "release",
790 format!(
791 "worktree of `{branch}` released to run {}: {audit}; this run can no longer be \
792 resumed from here",
793 crate::run::short_of(new_run)
794 ),
795 );
796 state.save_under(&takeover.home)?;
797
798 let again = match RunState::load_under(&old_id, &takeover.home) {
806 Ok(fresh) => inspect(repo, branch, &path, &fresh, &takeover.home).await,
807 Err(e) => Err(e),
808 };
809 let safe = matches!(&again, Ok(h) if decide(&kind, h) == Decision::Release);
810 let removed = safe
811 && git::worktree_remove_clean(repo, &path)
812 .await
813 .unwrap_or(false);
814 if !removed || path.exists() {
815 state = RunState::load_under(&old_id, &takeover.home)?;
816 state.candidates[index].folded = false;
817 state.released_to = None;
818 state.released_branches.retain(|b| b != branch);
819 state.events.pop();
820 state.event(
821 "release",
822 format!(
823 "release of `{branch}` to run {} was undone: {audit}",
824 crate::run::short_of(new_run)
825 ),
826 );
827 state.save_under(&takeover.home)?;
828 return Err(Refused::ReleaseFailed {
829 branch: branch.to_owned(),
830 path: path.display().to_string(),
831 run: crate::run::short_of(&old_id).to_owned(),
832 }
833 .into());
834 }
835 Ok(Some(Released {
836 old_id,
837 index,
838 path,
839 home: takeover.home.clone(),
840 successor: new_run.to_owned(),
841 tip: holder.tip,
842 audit,
843 }))
844}
845
846#[cfg(test)]
847mod tests {
848 #[test]
849 fn refused_display_is_the_english_text() {
850 let r = Refused::Foreign {
851 branch: "b".into(),
852 path: "/w".into(),
853 why: "w".into(),
854 };
855 assert_eq!(
856 r.to_string(),
857 "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."
858 );
859 }
860
861 use super::*;
862
863 fn holder() -> Holder {
864 Holder {
865 run: "20260901-000000-f82f".to_owned(),
866 status: RunStatus::Gating,
867 liveness: Liveness::Dead,
868 driver_unproven: false,
869 dirty: false,
870 dirty_files: Vec::new(),
871 driver_pid: None,
872 head: "a".repeat(40),
873 tip: "a".repeat(40),
874 }
875 }
876
877 fn recorded_holder(home: &Path) -> (RunState, PathBuf) {
878 let mut state = RunState::new(
879 "repo".into(),
880 "main".into(),
881 "base".into(),
882 "task".into(),
883 crate::config::Config::default(),
884 );
885 state.config.graph.worktree_root = Some(home.join("worktrees"));
886 let path = state.worktree_root().join("cand-A");
887 std::fs::create_dir_all(&path).unwrap();
888 state.driver_exited = true;
889 state.candidates.push(crate::run::Candidate {
890 index: 0,
891 label: 'A',
892 agent: "existing".into(),
893 branch: "branch".into(),
894 worktree: path.clone(),
895 summary: String::new(),
896 stat: String::new(),
897 files: 1,
898 commits: 1,
899 empty: false,
900 failed: None,
901 verified_noop: None,
902 duration_ms: 0,
903 folded: false,
904 });
905 state.save_under(home).unwrap();
906 (state, path)
907 }
908
909 #[tokio::test]
910 async fn handover_reloads_a_driver_claim_after_the_scan_and_excludes_new_claims() {
911 let home = tempfile::tempdir().unwrap();
912 let (mut state, path) = recorded_holder(home.path());
913 let scanned = state.clone();
914 state.driver_exited = false;
916 state.driver_pid = Some(std::process::id());
917 state.driver_started_at = crate::proc::process_started_at(std::process::id());
918 state.begin_pass();
919 state.save_under(home.path()).unwrap();
920 let mut driver = crate::driver::DriverGuard::acquire(home.path(), &state).unwrap();
921 driver.record(&state).unwrap();
922 let (fresh, _, owner) = locked_holder(home.path(), &scanned.id, &path)
923 .await
924 .unwrap();
925 assert!(!fresh.driver_exited);
926 assert_eq!(fresh.passes, state.passes);
927 assert_ne!(fresh.liveness_under(home.path(), false), Liveness::Dead);
928 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_err());
929 assert!(path.exists());
930 assert!(
931 RunState::load_under(&state.id, home.path())
932 .unwrap()
933 .released_to
934 .is_none()
935 );
936 drop(owner);
937 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_ok());
938 }
939
940 #[tokio::test]
941 async fn handover_revalidates_candidate_ownership_under_the_claim_lock() {
942 let home = tempfile::tempdir().unwrap();
943 let (mut state, path) = recorded_holder(home.path());
944 state.candidates[0].folded = true;
945 state.released_to = Some("next".into());
946 state.save_under(home.path()).unwrap();
947 assert!(locked_holder(home.path(), &state.id, &path).await.is_err());
948 assert!(path.exists());
949 }
950
951 async fn released_predecessor(home: &Path, repo: &Path) -> (RunState, Released) {
954 crate::clean::tests::init_repo(repo);
955 let mut state = RunState::new(
956 repo.to_owned(),
957 "main".into(),
958 "base".into(),
959 "task".into(),
960 crate::config::Config::default(),
961 );
962 state.config.graph.worktree_root = Some(home.join("worktrees"));
963 let path = state.worktree_root().join("cand-A");
964 let branch = "magi/restore/A";
965 git::worktree_add_branch(repo, &path, branch, "main")
966 .await
967 .unwrap();
968 let tip = git::rev_parse(repo, branch).await.unwrap();
969 state.driver_exited = true;
970 state.status = RunStatus::Ready;
971 state.candidates.push(crate::run::Candidate {
972 index: 0,
973 label: 'A',
974 agent: "existing".into(),
975 branch: branch.into(),
976 worktree: path.clone(),
977 summary: String::new(),
978 stat: String::new(),
979 files: 1,
980 commits: 1,
981 empty: false,
982 failed: None,
983 verified_noop: None,
984 duration_ms: 0,
985 folded: true,
986 });
987 state.released_to = Some("successor".into());
988 state.released_branches.push(branch.into());
989 state.event("release", "worktree released");
990 state.save_under(home).unwrap();
991 git::git(repo, &["worktree", "remove", path.to_str().unwrap()])
992 .await
993 .unwrap();
994 let released = Released {
995 old_id: state.id.clone(),
996 index: 0,
997 path,
998 home: home.to_owned(),
999 successor: "successor".into(),
1000 tip,
1001 audit: String::new(),
1002 };
1003 (state, released)
1004 }
1005
1006 #[tokio::test]
1010 async fn a_rollback_waits_out_a_brief_hold_on_the_owner_lock() {
1011 let home = tempfile::tempdir().unwrap();
1012 let repo = home.path().join("repo");
1013 std::fs::create_dir_all(&repo).unwrap();
1014 let (state, released) = released_predecessor(home.path(), &repo).await;
1015 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1016 let release = std::thread::spawn(move || {
1017 std::thread::sleep(std::time::Duration::from_millis(300));
1018 drop(held);
1019 });
1020 released
1021 .restore_within(&repo, "magi/restore/A", std::time::Duration::from_secs(30))
1022 .await;
1023 release.join().unwrap();
1024 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1025 assert!(released.path.exists(), "the worktree is back");
1026 assert!(disk.released_to.is_none() && !disk.candidates[0].folded);
1027 }
1028
1029 #[tokio::test]
1031 async fn a_rollback_gives_up_on_a_lock_held_beyond_its_bound() {
1032 let home = tempfile::tempdir().unwrap();
1033 let repo = home.path().join("repo");
1034 std::fs::create_dir_all(&repo).unwrap();
1035 let (state, released) = released_predecessor(home.path(), &repo).await;
1036 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1037 released
1038 .restore_within(
1039 &repo,
1040 "magi/restore/A",
1041 std::time::Duration::from_millis(150),
1042 )
1043 .await;
1044 drop(held);
1045 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1046 assert!(!released.path.exists());
1047 assert_eq!(disk.released_to.as_deref(), Some("successor"));
1048 assert!(disk.candidates[0].folded);
1049 }
1050
1051 async fn held_predecessor(home: &Path, repo: &Path) -> (RunState, PathBuf, Takeover) {
1054 crate::clean::tests::init_repo(repo);
1055 let mut state = RunState::new(
1056 repo.to_owned(),
1057 "main".into(),
1058 "base".into(),
1059 "task".into(),
1060 crate::config::Config::default(),
1061 );
1062 state.config.graph.worktree_root = Some(home.join("worktrees"));
1063 let path = state.worktree_root().join("cand-A");
1064 let branch = "magi/take/A";
1065 git::worktree_add_branch(repo, &path, branch, "main")
1066 .await
1067 .unwrap();
1068 state.driver_exited = true;
1069 state.status = RunStatus::Gating;
1070 state.candidates.push(crate::run::Candidate {
1071 index: 0,
1072 label: 'A',
1073 agent: "existing".into(),
1074 branch: branch.into(),
1075 worktree: path.clone(),
1076 summary: String::new(),
1077 stat: String::new(),
1078 files: 1,
1079 commits: 1,
1080 empty: false,
1081 failed: None,
1082 verified_noop: None,
1083 duration_ms: 0,
1084 folded: false,
1085 });
1086 state.save_under(home).unwrap();
1087 let takeover = Takeover {
1088 earlier: vec![state.id.clone()],
1089 home: home.to_owned(),
1090 choice: None,
1091 task_instruction: None,
1092 };
1093 (state, path, takeover)
1094 }
1095
1096 #[tokio::test]
1100 async fn a_handover_waits_out_a_brief_hold_on_the_owner_lock() {
1101 let home = tempfile::tempdir().unwrap();
1102 let repo = home.path().join("repo");
1103 std::fs::create_dir_all(&repo).unwrap();
1104 let (state, path, takeover) = held_predecessor(home.path(), &repo).await;
1105 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1106 let fold = std::thread::spawn(move || {
1107 std::thread::sleep(std::time::Duration::from_millis(300));
1108 drop(held);
1109 });
1110 let released = release(&repo, "magi/take/A", "successor", &takeover)
1111 .await
1112 .expect("the handover is not failed by a brief hold")
1113 .expect("the worktree is released");
1114 fold.join().unwrap();
1115 assert_eq!(released.old_id, state.id);
1116 assert!(!path.exists(), "the worktree was released");
1117 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1118 assert_eq!(disk.released_to.as_deref(), Some("successor"));
1119 }
1120
1121 #[tokio::test]
1124 async fn a_handover_fails_on_a_lock_held_beyond_its_bound() {
1125 let home = tempfile::tempdir().unwrap();
1126 let repo = home.path().join("repo");
1127 std::fs::create_dir_all(&repo).unwrap();
1128 let (state, path, _) = held_predecessor(home.path(), &repo).await;
1129 let held = crate::pr_head::owner_lock(home.path(), &state.id).unwrap();
1130 let error = locked_holder_within(
1131 home.path(),
1132 &state.id,
1133 &path,
1134 std::time::Duration::from_millis(150),
1135 )
1136 .await
1137 .err()
1138 .expect("the lock is still held after the bound");
1139 assert!(crate::graph::held_by_live_owner(&error), "{error:#}");
1140 drop(held);
1141 assert!(path.exists());
1142 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1143 assert!(disk.released_to.is_none() && !disk.candidates[0].folded);
1144 }
1145
1146 #[test]
1149 fn the_last_pause_is_clipped_to_the_remaining_bound() {
1150 use std::time::Duration;
1151 assert_eq!(
1152 pause_within(Duration::from_millis(80), Duration::from_millis(500)),
1153 Duration::from_millis(80)
1154 );
1155 assert_eq!(
1156 pause_within(Duration::from_millis(80), Duration::from_millis(30)),
1157 Duration::from_millis(30)
1158 );
1159 }
1160
1161 #[tokio::test]
1162 async fn a_stale_restore_does_not_undo_a_later_handover() {
1163 let home = tempfile::tempdir().unwrap();
1164 let (mut state, path) = recorded_holder(home.path());
1165 state.candidates[0].folded = true;
1166 state.released_to = Some("later".into());
1167 state.save_under(home.path()).unwrap();
1168 let released = Released {
1169 old_id: state.id.clone(),
1170 index: 0,
1171 path,
1172 home: home.path().to_owned(),
1173 successor: "original".into(),
1174 tip: "tip".into(),
1175 audit: String::new(),
1176 };
1177 released.restore(Path::new("nonexistent"), "branch").await;
1178 let disk = RunState::load_under(&state.id, home.path()).unwrap();
1179 assert_eq!(disk.released_to.as_deref(), Some("later"));
1180 assert!(disk.candidates[0].folded);
1181 }
1182
1183 #[test]
1184 fn a_clean_superseded_stale_run_is_released() {
1185 assert_eq!(decide(&Owner::EarlierAttempt, &holder()), Decision::Release);
1186 let dead = Holder {
1187 liveness: Liveness::Dead,
1188 ..holder()
1189 };
1190 assert_eq!(decide(&Owner::EarlierAttempt, &dead), Decision::Release);
1191 }
1192
1193 #[test]
1194 fn a_foreign_worktree_is_refused_with_its_reason() {
1195 let owner = Owner::Foreign("it is a foreign path".to_owned());
1196 assert_eq!(
1197 decide(&owner, &holder()),
1198 Decision::Refuse("it is a foreign path".to_owned())
1199 );
1200 }
1201
1202 #[test]
1203 fn landing_is_protected_even_for_an_earlier_attempt() {
1204 let landing = Holder {
1205 status: RunStatus::Landing,
1206 ..holder()
1207 };
1208 assert!(matches!(
1209 decide(&Owner::MagiRun, &landing),
1210 Decision::Refuse(_)
1211 ));
1212 assert!(matches!(
1213 decide(&Owner::EarlierAttempt, &landing),
1214 Decision::Refuse(_)
1215 ));
1216 }
1217
1218 #[test]
1219 fn a_dirty_worktree_is_refused_and_says_why() {
1220 let dirty = Holder {
1221 dirty: true,
1222 dirty_files: vec!["scratch.txt".to_owned()],
1223 ..holder()
1224 };
1225 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &dirty) else {
1226 panic!("dirty must be refused");
1227 };
1228 assert!(
1229 why.contains("uncommitted") && why.contains("scratch.txt"),
1230 "{why}"
1231 );
1232 assert!(why.contains("f82f") && why.contains("gating") && why.contains("dirty"));
1233 }
1234
1235 #[test]
1236 fn a_live_run_is_refused() {
1237 let live = Holder {
1238 liveness: Liveness::Live,
1239 driver_pid: Some(4242),
1240 ..holder()
1241 };
1242 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &live) else {
1243 panic!("live must be refused");
1244 };
1245 assert!(
1246 why.contains("right now") && why.contains("f82f") && why.contains("4242"),
1247 "{why}"
1248 );
1249 }
1250
1251 #[test]
1252 fn unknown_without_a_recorded_pid_is_not_proof_of_a_stopped_driver() {
1253 let holder = Holder {
1254 liveness: Liveness::Unknown,
1255 ..holder()
1256 };
1257 assert!(matches!(
1258 decide(&Owner::EarlierAttempt, &holder),
1259 Decision::Refuse(_)
1260 ));
1261 }
1262
1263 #[test]
1264 fn a_driver_that_could_not_be_shown_dead_is_refused() {
1265 let unproven = Holder {
1266 driver_unproven: true,
1267 ..holder()
1268 };
1269 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &unproven) else {
1270 panic!("an unproven driver must be refused");
1271 };
1272 assert!(why.contains("driver"), "{why}");
1273 }
1274
1275 #[test]
1276 fn a_head_off_the_tip_is_refused() {
1277 let off = Holder {
1278 head: "b".repeat(40),
1279 ..holder()
1280 };
1281 assert!(matches!(
1282 decide(&Owner::EarlierAttempt, &off),
1283 Decision::Refuse(_)
1284 ));
1285 }
1286}