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
136impl Released {
137 pub async fn restore(&self, repo: &Path, branch: &str) {
141 let Ok(_owner) = crate::pr_head::owner_lock(&self.home, &self.old_id) else {
142 tracing::warn!("could not lock run {} for handover rollback", self.old_id);
143 return;
144 };
145 let Ok(mut state) = RunState::load_under(&self.old_id, &self.home) else {
146 return;
147 };
148 let claimed =
149 crate::daemon::is_working_on_other(&self.home, &self.old_id, jiff::Timestamp::now())
150 .unwrap_or(true);
151 if state.released_to.as_deref() != Some(self.successor.as_str())
152 || state.status == RunStatus::Superseded
153 || state.pr_taken_over_by.is_some()
154 || state.liveness_under(&self.home, claimed) != Liveness::Dead
155 {
156 tracing::warn!(
157 "run {} changed ownership; handover rollback refused",
158 self.old_id
159 );
160 return;
161 }
162 let path = self.path.to_string_lossy().to_string();
163 let refname = format!("refs/heads/{branch}");
166 if git::rev_parse(repo, &refname).await.ok().as_deref() != Some(self.tip.as_str())
167 && let Err(e) = git::git(repo, &["branch", "-f", branch, &self.tip]).await
168 {
169 tracing::warn!("could not put `{branch}` back at {}: {e:#}", self.tip);
170 return;
171 }
172 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
173 tracing::warn!(
174 "could not put run {}'s worktree back at {path}: {e:#}",
175 self.old_id
176 );
177 return;
178 }
179 if let Some(c) = state.candidates.get_mut(self.index) {
180 c.folded = false;
181 }
182 state.released_to = None;
183 state.released_branches.retain(|b| b != branch);
184 state.events.pop();
185 let put_back = state.save_under(&self.home);
186 if let Err(e) = put_back {
187 tracing::warn!("could not unmark run {}: {e:#}", self.old_id);
188 }
189 }
190}
191
192#[derive(Debug, Clone)]
194pub struct Holder {
195 pub run: String,
197 pub status: RunStatus,
199 pub liveness: Liveness,
201 pub driver_unproven: bool,
204 pub dirty: bool,
206 pub dirty_files: Vec<String>,
208 pub driver_pid: Option<u32>,
210 pub head: String,
212 pub tip: String,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq)]
218pub enum Owner {
219 EarlierAttempt,
221 MagiRun,
224 Foreign(String),
226}
227
228#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum Decision {
231 Release,
233 Refuse(String),
235}
236
237fn short(sha: &str) -> String {
238 sha.chars().take(7).collect()
239}
240
241pub fn decide(owner: &Owner, holder: &Holder) -> Decision {
247 if let Owner::Foreign(why) = owner {
248 return Decision::Refuse(why.clone());
249 }
250 let mut why = Vec::new();
251 if holder.liveness == Liveness::Live {
252 why.push(format!(
253 "run {} is being worked on right now{}",
254 crate::run::short_of(&holder.run),
255 holder
256 .driver_pid
257 .map(|p| format!(" (driver pid {p})"))
258 .unwrap_or_default()
259 ));
260 } else if holder.liveness == Liveness::Unknown || holder.driver_unproven {
261 why.push("its driver process could not be shown to be gone".to_owned());
262 }
263 if holder.status == RunStatus::Landing {
264 why.push("that run is in `landing`, possibly waiting on an approval".to_owned());
265 }
266 if holder.dirty {
267 let files = holder.dirty_files.join(", ");
268 why.push(format!("its worktree has uncommitted changes ({files})"));
269 }
270 if holder.head != holder.tip {
271 why.push("its HEAD is not at the branch tip".to_owned());
272 }
273 if why.is_empty() {
274 return Decision::Release;
275 }
276 let kind = match owner {
277 Owner::EarlierAttempt => "an earlier attempt at this task",
278 _ => "a magi run of another task",
279 };
280 Decision::Refuse(format!(
281 "run {} (status `{}`, worktree {}, HEAD {}, branch tip {}) is {kind} and still has the \
282 branch checked out, so it was not released automatically: {}",
283 crate::run::short_of(&holder.run),
284 holder.status.as_str(),
285 if holder.dirty { "dirty" } else { "clean" },
286 short(&holder.head),
287 short(&holder.tip),
288 why.join("; ")
289 ))
290}
291
292async fn inspect(
294 repo: &Path,
295 branch: &str,
296 path: &Path,
297 state: &RunState,
298 home: &Path,
299) -> Result<Holder> {
300 let claimed = crate::daemon::is_working_on_other(home, &state.id, jiff::Timestamp::now())?;
301 let liveness = state.liveness_under(home, claimed);
302 let porcelain = git::git(path, &["status", "--porcelain", "--untracked-files=normal"]).await?;
305 Ok(Holder {
306 run: state.id.clone(),
307 status: state.status,
308 liveness,
309 driver_unproven: liveness == Liveness::Unknown,
310 dirty: !porcelain.trim().is_empty(),
311 dirty_files: porcelain
312 .lines()
313 .take(5)
314 .map(|l| l.get(3..).unwrap_or(l).trim().to_owned())
315 .collect(),
316 driver_pid: state.driver_pid,
317 head: git::rev_parse(path, "HEAD").await?,
318 tip: git::rev_parse(repo, &format!("refs/heads/{branch}")).await?,
319 })
320}
321
322fn same_path(a: &Path, b: &Path) -> bool {
323 let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
324 canon(a) == canon(b)
325}
326
327fn foreign(branch: &str, path: &Path, why: &str) -> anyhow::Error {
328 Refused::Foreign {
329 branch: branch.to_owned(),
330 path: path.display().to_string(),
331 why: why.to_owned(),
332 }
333 .into()
334}
335
336pub async fn preflight(
339 repo: &Path,
340 branch: &str,
341 home: &Path,
342) -> Result<Option<crate::foreign_checkout::ForeignCheckout>> {
343 let Some(path) = git::worktree_holding(repo, branch).await? else {
344 return Ok(None);
345 };
346 match find_magi_owner(&path, home) {
347 Ok(Some(_)) => return Ok(None),
348 Err(why) => return Err(foreign(branch, &path, &why)),
349 Ok(None) => {}
350 }
351 crate::foreign_checkout::inspect(repo, branch, &path)
352 .await
353 .map(Some)
354 .map_err(|error| foreign(branch, &path, &format!("{error:#}")))
355}
356
357pub async fn preflight_review(
360 repo: &Path,
361 branch: &str,
362 home: &Path,
363 remote: &str,
364) -> Result<Option<crate::foreign_checkout::ForeignCheckout>> {
365 let checkout = preflight(repo, branch, home).await?;
366 if let Some(checkout) = &checkout {
367 let fetched = git::fetch(repo, remote, branch).await;
368 if matches!(fetched, Ok(ref out) if out.ok()) {
369 let tracking = format!("{remote}/{branch}");
370 let tip = git::rev_parse(repo, &tracking).await?;
371 if !git::is_ancestor(repo, &checkout.synced_head, &tip).await
372 && !git::is_ancestor(repo, &tip, &checkout.synced_head).await
373 {
374 return Err(foreign(
375 branch,
376 &checkout.path,
377 &format!("branch diverged from {tracking}; reconcile it before review"),
378 ));
379 }
380 }
381 }
382 Ok(checkout)
383}
384
385fn find_magi_owner(
390 path: &Path,
391 home: &Path,
392) -> std::result::Result<Option<(RunState, usize)>, String> {
393 let Some(bay) = path.parent() else {
394 return Ok(None);
395 };
396 let Some(bay_name) = bay.file_name().and_then(|n| n.to_str()) else {
397 return Ok(None);
398 };
399 let mut found = Vec::new();
400 for id in crate::run::list_ids_in(&home.join("runs")) {
401 if crate::run::short_of(&id) != bay_name {
402 continue;
403 }
404 let Ok(state) = RunState::load_under(&id, home) else {
405 return Err(format!("run {bay_name}'s record could not be read"));
406 };
407 if !same_path(&state.worktree_root(), bay) {
408 continue;
409 }
410 if let Some(i) = state
411 .candidates
412 .iter()
413 .position(|c| !c.folded && same_path(&c.worktree, path))
414 {
415 found.push((state, i));
416 }
417 }
418 match found.len() {
419 0 => Ok(None),
420 1 => Ok(found.pop()),
421 _ => Err(format!("more than one run record claims it ({bay_name})")),
422 }
423}
424
425pub(crate) fn landing_checkpoint(state: &RunState) -> bool {
428 state.status.resumable()
429 && state.config.graph.land
430 && state.pr.as_ref().is_some_and(|pr| pr.state == "open")
431 && state
432 .merge
433 .as_ref()
434 .is_some_and(|m| m.mode == crate::config::MergeMode::Pr && !m.empty)
435}
436
437#[derive(Debug, Clone, PartialEq, Eq)]
439pub(crate) enum ResumeRefusal {
440 Status(RunStatus),
441 Released(String),
442 Retired(String),
443 OwnershipTransferred(String),
444 ReviewBudget { used: usize, limit: usize },
445 ReviewDisabled,
446 CleanReviewGateRan,
447 BaseSyncStop,
448}
449
450impl ResumeRefusal {
451 pub(crate) fn successor(&self) -> Option<&str> {
453 match self {
454 Self::Released(to) | Self::Retired(to) | Self::OwnershipTransferred(to) => Some(to),
455 _ => None,
456 }
457 }
458
459 pub(crate) fn diagnostic(&self, state: &RunState) -> String {
460 let reason = match self {
461 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(),
462 Self::Status(status) => format!("status `{}` is final; there is nothing left to resume", status.as_str()),
463 Self::Released(_) => "execution was released".into(),
464 Self::Retired(_) => "execution was retired".into(),
465 Self::OwnershipTransferred(_) => "PR ownership was transferred".into(),
466 Self::ReviewBudget { used, limit } => format!("review budget exhausted ({used}/{limit} rounds used)"),
467 Self::CleanReviewGateRan => "review already has a clean round and the gate already ran; no retryable checkpoint remains".into(),
468 Self::ReviewDisabled => "review is disabled (review_rounds = 0) and no retryable checkpoint or pending gate remains".into(),
469 };
470 let mut detail = format!("run {} cannot resume: {reason}.", state.short());
471 if let Some(target) = self.successor() {
472 let target = if matches!(self, Self::Retired(_)) {
473 target
474 } else {
475 crate::run::short_of(target)
476 };
477 detail.push_str(&format!(" Successor: run {target}; inspect `magi show {target}` before choosing any further action."));
478 }
479 for (label, target) in [
480 ("released to", &state.released_to),
481 ("retired to", &state.retired_to),
482 ("PR ownership moved to", &state.pr_taken_over_by),
483 ] {
484 if let Some(target) = target {
485 if self.successor() == Some(target.as_str()) {
486 continue;
487 }
488 let target = if label == "retired to" {
489 target.as_str()
490 } else {
491 crate::run::short_of(target)
492 };
493 detail.push_str(&format!(" {label} run {target}; inspect `magi show {target}` before choosing any further action."));
494 }
495 }
496 detail.push_str(&format!(
497 " Inspect `magi show {}` for retained work and ownership.",
498 state.id
499 ));
500 if matches!(self, Self::BaseSyncStop) {
501 detail.push_str(&format!(" {}", state.base_sync_next_action()));
502 }
503 if matches!(self, Self::ReviewBudget { .. } | Self::ReviewDisabled) {
504 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.");
505 }
506 detail
507 }
508}
509
510pub(crate) fn can_resume(state: &RunState) -> bool {
514 resume_refusal(state).is_none()
515}
516
517pub(crate) fn resume_refusal(state: &RunState) -> Option<ResumeRefusal> {
518 resume_refusal_under(state, crate::run::try_home().as_deref())
519}
520
521pub(crate) fn resume_refusal_under(state: &RunState, home: Option<&Path>) -> Option<ResumeRefusal> {
523 if !state.status.resumable() {
524 return Some(ResumeRefusal::Status(state.status));
525 }
526 if let Some(to) = &state.released_to {
527 return Some(ResumeRefusal::Released(to.clone()));
528 }
529 if let Some(to) = &state.retired_to {
530 return Some(ResumeRefusal::Retired(to.clone()));
531 }
532 if let Some(to) = &state.pr_taken_over_by {
533 return Some(ResumeRefusal::OwnershipTransferred(to.clone()));
534 }
535 if state.base_sync_blocked() {
536 return if state.base_recovery_pending()
537 || state.base_sync_closure_pending()
538 || crate::repair_budget::legacy::resumable_sequencer_stop(state)
539 || home.is_some_and(|home| {
540 state
541 .origin
542 .as_ref()
543 .and_then(|o| o.task.as_ref())
544 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
545 .is_some_and(|task| crate::repair_budget::conflict_pending(&task, state))
546 }) {
547 None
548 } else {
549 Some(ResumeRefusal::BaseSyncStop)
550 };
551 }
552 let review = crate::graph::review_conclusion(&state.reviews, state.config.graph.review_rounds);
553 let allowed = resume_checkpoint(state)
554 || state
555 .repair_grants
556 .last()
557 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
558 || home.is_some_and(|home| {
559 state
560 .origin
561 .as_ref()
562 .and_then(|o| o.task.as_ref())
563 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
564 .is_some_and(|task| crate::repair_budget::pending(&task, state))
565 })
566 || home.is_some_and(|home| has_resume_checkpoint(state, home))
567 || ((state.config.graph.review_rounds == 0
568 || state.reviews.iter().any(|round| round.clean))
569 && (!state.gate_ran || state.resource_block.is_some()))
570 || (state.resource_block.is_some() && review == Some(RunStatus::Gating))
571 || (review.is_none()
572 && state
573 .reviews
574 .last()
575 .is_some_and(|round| round.e2e_status() == crate::run::E2eStatus::ResourceBlocked))
576 || !(state.status == RunStatus::Blocked
577 && state.reviews.len() >= state.config.graph.review_rounds);
578 if allowed {
579 None
580 } else if state.config.graph.review_rounds == 0 {
581 Some(ResumeRefusal::ReviewDisabled)
582 } else if state.reviews.iter().any(|round| round.clean) {
583 Some(ResumeRefusal::CleanReviewGateRan)
584 } else {
585 Some(ResumeRefusal::ReviewBudget {
586 used: state.reviews.len(),
587 limit: state.config.graph.review_rounds,
588 })
589 }
590}
591
592fn resume_checkpoint(state: &RunState) -> bool {
593 state.status == RunStatus::Landing
594 || landing_checkpoint(state)
595 || state.pending_base_operation().is_some()
596 || state.pr_publication_pending
597 || state.land_approval.is_some()
598 || state.merge_decision.is_some()
599 || state.land_armed_head.is_some()
600 || !state.merge_repairs.is_empty()
601}
602
603pub(crate) fn has_resume_checkpoint(state: &RunState, home: &Path) -> bool {
607 state.status.resumable()
608 && (resume_checkpoint(state)
609 || crate::ask::Questions::at(home.join("questions"))
610 .list_for_effects()
611 .iter()
612 .any(|q| q.run == state.id && q.status.open()))
613}
614
615fn locked_holder(
618 home: &Path,
619 id: &str,
620 path: &Path,
621) -> Result<(RunState, usize, crate::pr_head::OwnerLock)> {
622 let owner = crate::pr_head::owner_lock(home, id)?;
623 let state = RunState::load_under(id, home)?;
624 let index = state
625 .candidates
626 .iter()
627 .position(|c| !c.folded && same_path(&c.worktree, path))
628 .ok_or_else(|| anyhow::anyhow!("worktree holder changed; retry takeover"))?;
629 anyhow::ensure!(
630 state.released_to.is_none(),
631 "run already handed over its worktree; retry takeover"
632 );
633 anyhow::ensure!(
634 path.parent()
635 .is_some_and(|p| same_path(&state.worktree_root(), p)),
636 "worktree holder root changed; retry takeover"
637 );
638 Ok((state, index, owner))
639}
640
641pub async fn release(
649 repo: &Path,
650 branch: &str,
651 new_run: &str,
652 takeover: &Takeover,
653) -> Result<Option<Released>> {
654 let Some(path) = git::worktree_holding(repo, branch).await? else {
655 return Ok(None);
656 };
657 let mut owner = None;
660 for id in &takeover.earlier {
661 let Ok(state) = RunState::load_under(id, &takeover.home) else {
662 continue;
663 };
664 if let Some(i) = state
665 .candidates
666 .iter()
667 .position(|c| !c.folded && same_path(&c.worktree, &path))
668 {
669 if !path
671 .parent()
672 .is_some_and(|b| same_path(&state.worktree_root(), b))
673 {
674 return Err(foreign(
675 branch,
676 &path,
677 &format!(
678 "run {} records it, but it is outside that run's worktree root, so \
679 magi did not make it",
680 crate::run::short_of(id)
681 ),
682 ));
683 }
684 owner = Some((state, i, Owner::EarlierAttempt));
685 break;
686 }
687 }
688 if owner.is_none() {
689 owner = match find_magi_owner(&path, &takeover.home) {
690 Ok(found) => found.map(|(s, i)| (s, i, Owner::MagiRun)),
691 Err(why) => return Err(foreign(branch, &path, &why)),
692 };
693 }
694 let Some((state, _, kind)) = owner else {
695 preflight(repo, branch, &takeover.home).await?;
696 return Ok(None);
697 };
698
699 let (mut state, index, _owner) = locked_holder(&takeover.home, &state.id, &path)?;
700 if has_resume_checkpoint(&state, &takeover.home) {
701 return Err(Refused::Unsafe {
702 branch: branch.to_owned(),
703 path: path.display().to_string(),
704 why: format!("run {} has a resumable publication, landing or decision checkpoint; resume that run instead of releasing its worktree", state.short()),
705 }.into());
706 }
707 let holder = inspect(repo, branch, &path, &state, &takeover.home).await?;
708 if let Decision::Refuse(why) = decide(&kind, &holder) {
709 return Err(Refused::Unsafe {
710 branch: branch.to_owned(),
711 path: path.display().to_string(),
712 why,
713 }
714 .into());
715 }
716 let audit = format!(
717 "run {} (status `{}`, no driver, clean, HEAD {} = branch tip, branch `{branch}` kept)",
718 crate::run::short_of(&holder.run),
719 holder.status.as_str(),
720 short(&holder.head)
721 );
722
723 let old_id = state.id.clone();
724 state.candidates[index].folded = true;
725 state.released_to = Some(new_run.to_owned());
726 if !state.released_branches.iter().any(|b| b == branch) {
727 state.released_branches.push(branch.to_owned());
728 }
729 state.event(
730 "release",
731 format!(
732 "worktree of `{branch}` released to run {}: {audit}; this run can no longer be \
733 resumed from here",
734 crate::run::short_of(new_run)
735 ),
736 );
737 state.save_under(&takeover.home)?;
738
739 let again = match RunState::load_under(&old_id, &takeover.home) {
747 Ok(fresh) => inspect(repo, branch, &path, &fresh, &takeover.home).await,
748 Err(e) => Err(e),
749 };
750 let safe = matches!(&again, Ok(h) if decide(&kind, h) == Decision::Release);
751 let removed = safe
752 && git::worktree_remove_clean(repo, &path)
753 .await
754 .unwrap_or(false);
755 if !removed || path.exists() {
756 state = RunState::load_under(&old_id, &takeover.home)?;
757 state.candidates[index].folded = false;
758 state.released_to = None;
759 state.released_branches.retain(|b| b != branch);
760 state.events.pop();
761 state.event(
762 "release",
763 format!(
764 "release of `{branch}` to run {} was undone: {audit}",
765 crate::run::short_of(new_run)
766 ),
767 );
768 state.save_under(&takeover.home)?;
769 return Err(Refused::ReleaseFailed {
770 branch: branch.to_owned(),
771 path: path.display().to_string(),
772 run: crate::run::short_of(&old_id).to_owned(),
773 }
774 .into());
775 }
776 Ok(Some(Released {
777 old_id,
778 index,
779 path,
780 home: takeover.home.clone(),
781 successor: new_run.to_owned(),
782 tip: holder.tip,
783 audit,
784 }))
785}
786
787#[cfg(test)]
788mod tests {
789 #[test]
790 fn refused_display_is_the_english_text() {
791 let r = Refused::Foreign {
792 branch: "b".into(),
793 path: "/w".into(),
794 why: "w".into(),
795 };
796 assert_eq!(
797 r.to_string(),
798 "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."
799 );
800 }
801
802 use super::*;
803
804 fn holder() -> Holder {
805 Holder {
806 run: "20260901-000000-f82f".to_owned(),
807 status: RunStatus::Gating,
808 liveness: Liveness::Dead,
809 driver_unproven: false,
810 dirty: false,
811 dirty_files: Vec::new(),
812 driver_pid: None,
813 head: "a".repeat(40),
814 tip: "a".repeat(40),
815 }
816 }
817
818 fn recorded_holder(home: &Path) -> (RunState, PathBuf) {
819 let mut state = RunState::new(
820 "repo".into(),
821 "main".into(),
822 "base".into(),
823 "task".into(),
824 crate::config::Config::default(),
825 );
826 state.config.graph.worktree_root = Some(home.join("worktrees"));
827 let path = state.worktree_root().join("cand-A");
828 std::fs::create_dir_all(&path).unwrap();
829 state.driver_exited = true;
830 state.candidates.push(crate::run::Candidate {
831 index: 0,
832 label: 'A',
833 agent: "existing".into(),
834 branch: "branch".into(),
835 worktree: path.clone(),
836 summary: String::new(),
837 stat: String::new(),
838 files: 1,
839 commits: 1,
840 empty: false,
841 failed: None,
842 verified_noop: None,
843 duration_ms: 0,
844 folded: false,
845 });
846 state.save_under(home).unwrap();
847 (state, path)
848 }
849
850 #[test]
851 fn handover_reloads_a_driver_claim_after_the_scan_and_excludes_new_claims() {
852 let home = tempfile::tempdir().unwrap();
853 let (mut state, path) = recorded_holder(home.path());
854 let scanned = state.clone();
855 state.driver_exited = false;
857 state.driver_pid = Some(std::process::id());
858 state.driver_started_at = crate::proc::process_started_at(std::process::id());
859 state.begin_pass();
860 state.save_under(home.path()).unwrap();
861 let mut driver = crate::driver::DriverGuard::acquire(home.path(), &state).unwrap();
862 driver.record(&state).unwrap();
863 let (fresh, _, owner) = locked_holder(home.path(), &scanned.id, &path).unwrap();
864 assert!(!fresh.driver_exited);
865 assert_eq!(fresh.passes, state.passes);
866 assert_ne!(fresh.liveness_under(home.path(), false), Liveness::Dead);
867 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_err());
868 assert!(path.exists());
869 assert!(
870 RunState::load_under(&state.id, home.path())
871 .unwrap()
872 .released_to
873 .is_none()
874 );
875 drop(owner);
876 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_ok());
877 }
878
879 #[test]
880 fn handover_revalidates_candidate_ownership_under_the_claim_lock() {
881 let home = tempfile::tempdir().unwrap();
882 let (mut state, path) = recorded_holder(home.path());
883 state.candidates[0].folded = true;
884 state.released_to = Some("next".into());
885 state.save_under(home.path()).unwrap();
886 assert!(locked_holder(home.path(), &state.id, &path).is_err());
887 assert!(path.exists());
888 }
889
890 #[tokio::test]
891 async fn a_stale_restore_does_not_undo_a_later_handover() {
892 let home = tempfile::tempdir().unwrap();
893 let (mut state, path) = recorded_holder(home.path());
894 state.candidates[0].folded = true;
895 state.released_to = Some("later".into());
896 state.save_under(home.path()).unwrap();
897 let released = Released {
898 old_id: state.id.clone(),
899 index: 0,
900 path,
901 home: home.path().to_owned(),
902 successor: "original".into(),
903 tip: "tip".into(),
904 audit: String::new(),
905 };
906 released.restore(Path::new("nonexistent"), "branch").await;
907 let disk = RunState::load_under(&state.id, home.path()).unwrap();
908 assert_eq!(disk.released_to.as_deref(), Some("later"));
909 assert!(disk.candidates[0].folded);
910 }
911
912 #[test]
913 fn a_clean_superseded_stale_run_is_released() {
914 assert_eq!(decide(&Owner::EarlierAttempt, &holder()), Decision::Release);
915 let dead = Holder {
916 liveness: Liveness::Dead,
917 ..holder()
918 };
919 assert_eq!(decide(&Owner::EarlierAttempt, &dead), Decision::Release);
920 }
921
922 #[test]
923 fn a_foreign_worktree_is_refused_with_its_reason() {
924 let owner = Owner::Foreign("it is a foreign path".to_owned());
925 assert_eq!(
926 decide(&owner, &holder()),
927 Decision::Refuse("it is a foreign path".to_owned())
928 );
929 }
930
931 #[test]
932 fn landing_is_protected_even_for_an_earlier_attempt() {
933 let landing = Holder {
934 status: RunStatus::Landing,
935 ..holder()
936 };
937 assert!(matches!(
938 decide(&Owner::MagiRun, &landing),
939 Decision::Refuse(_)
940 ));
941 assert!(matches!(
942 decide(&Owner::EarlierAttempt, &landing),
943 Decision::Refuse(_)
944 ));
945 }
946
947 #[test]
948 fn a_dirty_worktree_is_refused_and_says_why() {
949 let dirty = Holder {
950 dirty: true,
951 dirty_files: vec!["scratch.txt".to_owned()],
952 ..holder()
953 };
954 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &dirty) else {
955 panic!("dirty must be refused");
956 };
957 assert!(
958 why.contains("uncommitted") && why.contains("scratch.txt"),
959 "{why}"
960 );
961 assert!(why.contains("f82f") && why.contains("gating") && why.contains("dirty"));
962 }
963
964 #[test]
965 fn a_live_run_is_refused() {
966 let live = Holder {
967 liveness: Liveness::Live,
968 driver_pid: Some(4242),
969 ..holder()
970 };
971 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &live) else {
972 panic!("live must be refused");
973 };
974 assert!(
975 why.contains("right now") && why.contains("f82f") && why.contains("4242"),
976 "{why}"
977 );
978 }
979
980 #[test]
981 fn unknown_without_a_recorded_pid_is_not_proof_of_a_stopped_driver() {
982 let holder = Holder {
983 liveness: Liveness::Unknown,
984 ..holder()
985 };
986 assert!(matches!(
987 decide(&Owner::EarlierAttempt, &holder),
988 Decision::Refuse(_)
989 ));
990 }
991
992 #[test]
993 fn a_driver_that_could_not_be_shown_dead_is_refused() {
994 let unproven = Holder {
995 driver_unproven: true,
996 ..holder()
997 };
998 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &unproven) else {
999 panic!("an unproven driver must be refused");
1000 };
1001 assert!(why.contains("driver"), "{why}");
1002 }
1003
1004 #[test]
1005 fn a_head_off_the_tip_is_refused() {
1006 let off = Holder {
1007 head: "b".repeat(40),
1008 ..holder()
1009 };
1010 assert!(matches!(
1011 decide(&Owner::EarlierAttempt, &off),
1012 Decision::Refuse(_)
1013 ));
1014 }
1015}