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 || home.is_some_and(|home| {
539 state
540 .origin
541 .as_ref()
542 .and_then(|o| o.task.as_ref())
543 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
544 .is_some_and(|task| crate::repair_budget::conflict_pending(&task, state))
545 }) {
546 None
547 } else {
548 Some(ResumeRefusal::BaseSyncStop)
549 };
550 }
551 let review = crate::graph::review_conclusion(&state.reviews, state.config.graph.review_rounds);
552 let allowed = resume_checkpoint(state)
553 || state
554 .repair_grants
555 .last()
556 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
557 || home.is_some_and(|home| {
558 state
559 .origin
560 .as_ref()
561 .and_then(|o| o.task.as_ref())
562 .and_then(|id| crate::queue::Queue::at(home.join("queue")).get(id).ok())
563 .is_some_and(|task| crate::repair_budget::pending(&task, state))
564 })
565 || home.is_some_and(|home| has_resume_checkpoint(state, home))
566 || ((state.config.graph.review_rounds == 0
567 || state.reviews.iter().any(|round| round.clean))
568 && (!state.gate_ran || state.resource_block.is_some()))
569 || (state.resource_block.is_some() && review == Some(RunStatus::Gating))
570 || (review.is_none()
571 && state
572 .reviews
573 .last()
574 .is_some_and(|round| round.e2e_status() == crate::run::E2eStatus::ResourceBlocked))
575 || !(state.status == RunStatus::Blocked
576 && state.reviews.len() >= state.config.graph.review_rounds);
577 if allowed {
578 None
579 } else if state.config.graph.review_rounds == 0 {
580 Some(ResumeRefusal::ReviewDisabled)
581 } else if state.reviews.iter().any(|round| round.clean) {
582 Some(ResumeRefusal::CleanReviewGateRan)
583 } else {
584 Some(ResumeRefusal::ReviewBudget {
585 used: state.reviews.len(),
586 limit: state.config.graph.review_rounds,
587 })
588 }
589}
590
591fn resume_checkpoint(state: &RunState) -> bool {
592 state.status == RunStatus::Landing
593 || landing_checkpoint(state)
594 || state.pr_publication_pending
595 || state.land_approval.is_some()
596 || state.merge_decision.is_some()
597 || state.land_armed_head.is_some()
598 || !state.merge_repairs.is_empty()
599}
600
601pub(crate) fn has_resume_checkpoint(state: &RunState, home: &Path) -> bool {
605 state.status.resumable()
606 && (resume_checkpoint(state)
607 || crate::ask::Questions::at(home.join("questions"))
608 .list_for_effects()
609 .iter()
610 .any(|q| q.run == state.id && q.status.open()))
611}
612
613fn locked_holder(
616 home: &Path,
617 id: &str,
618 path: &Path,
619) -> Result<(RunState, usize, crate::pr_head::OwnerLock)> {
620 let owner = crate::pr_head::owner_lock(home, id)?;
621 let state = RunState::load_under(id, home)?;
622 let index = state
623 .candidates
624 .iter()
625 .position(|c| !c.folded && same_path(&c.worktree, path))
626 .ok_or_else(|| anyhow::anyhow!("worktree holder changed; retry takeover"))?;
627 anyhow::ensure!(
628 state.released_to.is_none(),
629 "run already handed over its worktree; retry takeover"
630 );
631 anyhow::ensure!(
632 path.parent()
633 .is_some_and(|p| same_path(&state.worktree_root(), p)),
634 "worktree holder root changed; retry takeover"
635 );
636 Ok((state, index, owner))
637}
638
639pub async fn release(
647 repo: &Path,
648 branch: &str,
649 new_run: &str,
650 takeover: &Takeover,
651) -> Result<Option<Released>> {
652 let Some(path) = git::worktree_holding(repo, branch).await? else {
653 return Ok(None);
654 };
655 let mut owner = None;
658 for id in &takeover.earlier {
659 let Ok(state) = RunState::load_under(id, &takeover.home) else {
660 continue;
661 };
662 if let Some(i) = state
663 .candidates
664 .iter()
665 .position(|c| !c.folded && same_path(&c.worktree, &path))
666 {
667 if !path
669 .parent()
670 .is_some_and(|b| same_path(&state.worktree_root(), b))
671 {
672 return Err(foreign(
673 branch,
674 &path,
675 &format!(
676 "run {} records it, but it is outside that run's worktree root, so \
677 magi did not make it",
678 crate::run::short_of(id)
679 ),
680 ));
681 }
682 owner = Some((state, i, Owner::EarlierAttempt));
683 break;
684 }
685 }
686 if owner.is_none() {
687 owner = match find_magi_owner(&path, &takeover.home) {
688 Ok(found) => found.map(|(s, i)| (s, i, Owner::MagiRun)),
689 Err(why) => return Err(foreign(branch, &path, &why)),
690 };
691 }
692 let Some((state, _, kind)) = owner else {
693 preflight(repo, branch, &takeover.home).await?;
694 return Ok(None);
695 };
696
697 let (mut state, index, _owner) = locked_holder(&takeover.home, &state.id, &path)?;
698 if has_resume_checkpoint(&state, &takeover.home) {
699 return Err(Refused::Unsafe {
700 branch: branch.to_owned(),
701 path: path.display().to_string(),
702 why: format!("run {} has a resumable publication, landing or decision checkpoint; resume that run instead of releasing its worktree", state.short()),
703 }.into());
704 }
705 let holder = inspect(repo, branch, &path, &state, &takeover.home).await?;
706 if let Decision::Refuse(why) = decide(&kind, &holder) {
707 return Err(Refused::Unsafe {
708 branch: branch.to_owned(),
709 path: path.display().to_string(),
710 why,
711 }
712 .into());
713 }
714 let audit = format!(
715 "run {} (status `{}`, no driver, clean, HEAD {} = branch tip, branch `{branch}` kept)",
716 crate::run::short_of(&holder.run),
717 holder.status.as_str(),
718 short(&holder.head)
719 );
720
721 let old_id = state.id.clone();
722 state.candidates[index].folded = true;
723 state.released_to = Some(new_run.to_owned());
724 if !state.released_branches.iter().any(|b| b == branch) {
725 state.released_branches.push(branch.to_owned());
726 }
727 state.event(
728 "release",
729 format!(
730 "worktree of `{branch}` released to run {}: {audit}; this run can no longer be \
731 resumed from here",
732 crate::run::short_of(new_run)
733 ),
734 );
735 state.save_under(&takeover.home)?;
736
737 let again = match RunState::load_under(&old_id, &takeover.home) {
745 Ok(fresh) => inspect(repo, branch, &path, &fresh, &takeover.home).await,
746 Err(e) => Err(e),
747 };
748 let safe = matches!(&again, Ok(h) if decide(&kind, h) == Decision::Release);
749 let removed = safe
750 && git::worktree_remove_clean(repo, &path)
751 .await
752 .unwrap_or(false);
753 if !removed || path.exists() {
754 state = RunState::load_under(&old_id, &takeover.home)?;
755 state.candidates[index].folded = false;
756 state.released_to = None;
757 state.released_branches.retain(|b| b != branch);
758 state.events.pop();
759 state.event(
760 "release",
761 format!(
762 "release of `{branch}` to run {} was undone: {audit}",
763 crate::run::short_of(new_run)
764 ),
765 );
766 state.save_under(&takeover.home)?;
767 return Err(Refused::ReleaseFailed {
768 branch: branch.to_owned(),
769 path: path.display().to_string(),
770 run: crate::run::short_of(&old_id).to_owned(),
771 }
772 .into());
773 }
774 Ok(Some(Released {
775 old_id,
776 index,
777 path,
778 home: takeover.home.clone(),
779 successor: new_run.to_owned(),
780 tip: holder.tip,
781 audit,
782 }))
783}
784
785#[cfg(test)]
786mod tests {
787 #[test]
788 fn refused_display_is_the_english_text() {
789 let r = Refused::Foreign {
790 branch: "b".into(),
791 path: "/w".into(),
792 why: "w".into(),
793 };
794 assert_eq!(
795 r.to_string(),
796 "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."
797 );
798 }
799
800 use super::*;
801
802 fn holder() -> Holder {
803 Holder {
804 run: "20260901-000000-f82f".to_owned(),
805 status: RunStatus::Gating,
806 liveness: Liveness::Dead,
807 driver_unproven: false,
808 dirty: false,
809 dirty_files: Vec::new(),
810 driver_pid: None,
811 head: "a".repeat(40),
812 tip: "a".repeat(40),
813 }
814 }
815
816 fn recorded_holder(home: &Path) -> (RunState, PathBuf) {
817 let mut state = RunState::new(
818 "repo".into(),
819 "main".into(),
820 "base".into(),
821 "task".into(),
822 crate::config::Config::default(),
823 );
824 state.config.graph.worktree_root = Some(home.join("worktrees"));
825 let path = state.worktree_root().join("cand-A");
826 std::fs::create_dir_all(&path).unwrap();
827 state.driver_exited = true;
828 state.candidates.push(crate::run::Candidate {
829 index: 0,
830 label: 'A',
831 agent: "existing".into(),
832 branch: "branch".into(),
833 worktree: path.clone(),
834 summary: String::new(),
835 stat: String::new(),
836 files: 1,
837 commits: 1,
838 empty: false,
839 failed: None,
840 verified_noop: None,
841 duration_ms: 0,
842 folded: false,
843 });
844 state.save_under(home).unwrap();
845 (state, path)
846 }
847
848 #[test]
849 fn handover_reloads_a_driver_claim_after_the_scan_and_excludes_new_claims() {
850 let home = tempfile::tempdir().unwrap();
851 let (mut state, path) = recorded_holder(home.path());
852 let scanned = state.clone();
853 state.driver_exited = false;
855 state.driver_pid = Some(std::process::id());
856 state.driver_started_at = crate::proc::process_started_at(std::process::id());
857 state.begin_pass();
858 state.save_under(home.path()).unwrap();
859 let mut driver = crate::driver::DriverGuard::acquire(home.path(), &state).unwrap();
860 driver.record(&state).unwrap();
861 let (fresh, _, owner) = locked_holder(home.path(), &scanned.id, &path).unwrap();
862 assert!(!fresh.driver_exited);
863 assert_eq!(fresh.passes, state.passes);
864 assert_ne!(fresh.liveness_under(home.path(), false), Liveness::Dead);
865 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_err());
866 assert!(path.exists());
867 assert!(
868 RunState::load_under(&state.id, home.path())
869 .unwrap()
870 .released_to
871 .is_none()
872 );
873 drop(owner);
874 assert!(crate::pr_head::owner_lock(home.path(), &state.id).is_ok());
875 }
876
877 #[test]
878 fn handover_revalidates_candidate_ownership_under_the_claim_lock() {
879 let home = tempfile::tempdir().unwrap();
880 let (mut state, path) = recorded_holder(home.path());
881 state.candidates[0].folded = true;
882 state.released_to = Some("next".into());
883 state.save_under(home.path()).unwrap();
884 assert!(locked_holder(home.path(), &state.id, &path).is_err());
885 assert!(path.exists());
886 }
887
888 #[tokio::test]
889 async fn a_stale_restore_does_not_undo_a_later_handover() {
890 let home = tempfile::tempdir().unwrap();
891 let (mut state, path) = recorded_holder(home.path());
892 state.candidates[0].folded = true;
893 state.released_to = Some("later".into());
894 state.save_under(home.path()).unwrap();
895 let released = Released {
896 old_id: state.id.clone(),
897 index: 0,
898 path,
899 home: home.path().to_owned(),
900 successor: "original".into(),
901 tip: "tip".into(),
902 audit: String::new(),
903 };
904 released.restore(Path::new("nonexistent"), "branch").await;
905 let disk = RunState::load_under(&state.id, home.path()).unwrap();
906 assert_eq!(disk.released_to.as_deref(), Some("later"));
907 assert!(disk.candidates[0].folded);
908 }
909
910 #[test]
911 fn a_clean_superseded_stale_run_is_released() {
912 assert_eq!(decide(&Owner::EarlierAttempt, &holder()), Decision::Release);
913 let dead = Holder {
914 liveness: Liveness::Dead,
915 ..holder()
916 };
917 assert_eq!(decide(&Owner::EarlierAttempt, &dead), Decision::Release);
918 }
919
920 #[test]
921 fn a_foreign_worktree_is_refused_with_its_reason() {
922 let owner = Owner::Foreign("it is a foreign path".to_owned());
923 assert_eq!(
924 decide(&owner, &holder()),
925 Decision::Refuse("it is a foreign path".to_owned())
926 );
927 }
928
929 #[test]
930 fn landing_is_protected_even_for_an_earlier_attempt() {
931 let landing = Holder {
932 status: RunStatus::Landing,
933 ..holder()
934 };
935 assert!(matches!(
936 decide(&Owner::MagiRun, &landing),
937 Decision::Refuse(_)
938 ));
939 assert!(matches!(
940 decide(&Owner::EarlierAttempt, &landing),
941 Decision::Refuse(_)
942 ));
943 }
944
945 #[test]
946 fn a_dirty_worktree_is_refused_and_says_why() {
947 let dirty = Holder {
948 dirty: true,
949 dirty_files: vec!["scratch.txt".to_owned()],
950 ..holder()
951 };
952 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &dirty) else {
953 panic!("dirty must be refused");
954 };
955 assert!(
956 why.contains("uncommitted") && why.contains("scratch.txt"),
957 "{why}"
958 );
959 assert!(why.contains("f82f") && why.contains("gating") && why.contains("dirty"));
960 }
961
962 #[test]
963 fn a_live_run_is_refused() {
964 let live = Holder {
965 liveness: Liveness::Live,
966 driver_pid: Some(4242),
967 ..holder()
968 };
969 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &live) else {
970 panic!("live must be refused");
971 };
972 assert!(
973 why.contains("right now") && why.contains("f82f") && why.contains("4242"),
974 "{why}"
975 );
976 }
977
978 #[test]
979 fn unknown_without_a_recorded_pid_is_not_proof_of_a_stopped_driver() {
980 let holder = Holder {
981 liveness: Liveness::Unknown,
982 ..holder()
983 };
984 assert!(matches!(
985 decide(&Owner::EarlierAttempt, &holder),
986 Decision::Refuse(_)
987 ));
988 }
989
990 #[test]
991 fn a_driver_that_could_not_be_shown_dead_is_refused() {
992 let unproven = Holder {
993 driver_unproven: true,
994 ..holder()
995 };
996 let Decision::Refuse(why) = decide(&Owner::EarlierAttempt, &unproven) else {
997 panic!("an unproven driver must be refused");
998 };
999 assert!(why.contains("driver"), "{why}");
1000 }
1001
1002 #[test]
1003 fn a_head_off_the_tip_is_refused() {
1004 let off = Holder {
1005 head: "b".repeat(40),
1006 ..holder()
1007 };
1008 assert!(matches!(
1009 decide(&Owner::EarlierAttempt, &off),
1010 Decision::Refuse(_)
1011 ));
1012 }
1013}