1use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49pub const SCHEMA: u32 = 1;
51
52pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57pub const STALE_SECS: i64 = 30;
66
67pub const POLL: Duration = Duration::from_secs(5);
69
70pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub worker: Option<String>,
102 pub task: String,
104 pub run: String,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116 pub schema: u32,
118 pub pid: u32,
120 pub started_at: Timestamp,
122 pub updated_at: Timestamp,
124 pub idle: bool,
126 pub current: Vec<Current>,
132 pub completed: usize,
134 pub polls: u64,
136 #[serde(default)]
138 pub question_recovery: Option<crate::question_delivery::Recovery>,
139 #[serde(default)]
141 pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145 #[must_use]
147 pub fn new() -> Self {
148 let now = Timestamp::now();
149 Self {
150 schema: SCHEMA,
151 pid: std::process::id(),
152 started_at: now,
153 updated_at: now,
154 idle: true,
155 current: Vec::new(),
156 completed: 0,
157 polls: 0,
158 question_recovery: None,
159 worker_protocol: Some(1),
160 }
161 }
162}
163
164impl Default for Status {
165 fn default() -> Self {
166 Self::new()
167 }
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174 pub repo: PathBuf,
176 pub config: Option<PathBuf>,
178 pub poll: Duration,
180 pub max_attempts: usize,
182 pub once: bool,
184 pub merge: Option<String>,
186 pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198 fn default() -> Self {
199 Self {
200 repo: PathBuf::from("."),
201 config: None,
202 poll: POLL,
203 max_attempts: 2,
204 once: false,
205 merge: None,
206 worktrees_root: None,
207 }
208 }
209}
210
211impl Opts {
212 fn absolute(&self) -> Result<Self> {
213 let mut opts = self.clone();
214 opts.repo = std::path::absolute(&opts.repo)?;
215 opts.config = opts
216 .config
217 .as_deref()
218 .map(std::path::absolute)
219 .transpose()?;
220 opts.worktrees_root = opts
221 .worktrees_root
222 .as_deref()
223 .map(std::path::absolute)
224 .transpose()?;
225 Ok(opts)
226 }
227}
228
229fn max_concurrent(n: usize) -> usize {
234 n.max(1)
235}
236
237#[must_use]
239pub fn status_path() -> PathBuf {
240 crate::run::home().join("daemon.json")
241}
242
243pub fn write_status(status: &Status) -> Result<()> {
245 write_status_to(&status_path(), status)
246}
247
248pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253 if let Some(parent) = path.parent() {
254 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255 }
256 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257 let tmp = path.with_extension("json.tmp");
258 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260 Ok(())
261}
262
263pub fn clear_status() {
266 clear_status_at(&status_path());
267}
268
269fn clear_status_at(path: &Path) {
273 let _ = std::fs::remove_file(path);
274}
275
276#[derive(Debug, Clone, Default)]
288pub struct Stop {
289 stopped: Arc<AtomicBool>,
293 busy: Arc<std::sync::atomic::AtomicUsize>,
295 wake: Arc<Notify>,
299 pause: crate::graph::Pause,
302}
303
304impl Stop {
305 #[must_use]
307 pub fn new() -> Self {
308 Self::default()
309 }
310
311 pub fn stop(&self) {
314 self.stopped.store(true, Ordering::SeqCst);
315 self.wake.notify_one();
319 }
320
321 #[must_use]
323 pub fn stopped(&self) -> bool {
324 self.stopped.load(Ordering::SeqCst)
325 }
326
327 #[must_use]
330 pub fn finishing(&self) -> bool {
331 self.stopped() && self.busy_now()
332 }
333
334 pub fn park(&self, cause: crate::run::ParkCause) {
340 self.pause.park_for(cause);
341 self.stop();
342 }
343
344 #[must_use]
346 pub fn parking(&self) -> bool {
347 self.pause.parked()
348 }
349
350 #[must_use]
352 pub fn pause(&self) -> crate::graph::Pause {
353 self.pause.clone()
354 }
355
356 #[must_use]
358 pub fn busy_now(&self) -> bool {
359 self.busy.load(Ordering::SeqCst) > 0
360 }
361
362 async fn idle(&self, poll: Duration) {
364 tokio::select! {
365 () = tokio::time::sleep(poll) => {}
366 () = self.wake.notified() => {}
367 }
368 }
369}
370
371#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380 pub schema: u32,
382 pub pid: Option<u32>,
384 pub started_at: Option<Timestamp>,
386 pub updated_at: Option<Timestamp>,
388 pub idle: bool,
390 #[serde(deserialize_with = "de_current")]
402 pub current: Vec<Current>,
403 pub completed: u64,
405 pub polls: u64,
407 #[serde(default)]
409 pub question_recovery: Option<crate::question_delivery::Recovery>,
410 pub worker_protocol: Option<u32>,
412}
413
414fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418 D: serde::Deserializer<'de>,
419{
420 #[derive(Deserialize)]
421 #[serde(untagged)]
422 enum Shape {
423 Many(Vec<Current>),
424 One(Current),
425 }
426 Ok(
427 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428 Shape::Many(v) => v,
429 Shape::One(c) => vec![c],
430 }),
431 )
432}
433
434impl Reading {
435 #[must_use]
438 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439 self.updated_at
440 .map(|at| (now.as_second() - at.as_second()).max(0))
441 }
442
443 #[must_use]
447 pub fn running(&self, now: Timestamp) -> bool {
448 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449 }
450}
451
452#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461 serde_json::from_str(&body).ok()
462}
463
464#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474 let mut current = read_status(home)
475 .filter(|reading| reading.running(now))
476 .map(|reading| reading.current)
477 .unwrap_or_default();
478 let workers = crate::worker::observe_active(home).and_then(|jobs| {
479 jobs.into_iter()
480 .filter(|job| job.kind == "task")
481 .map(|job| {
482 let request: TaskWorker = serde_json::from_value(job.payload)?;
483 let run = Queue::at(request.queue)
484 .get(&request.task)
485 .ok()
486 .and_then(|task| task.runs.last().cloned())
487 .unwrap_or_default();
488 Ok(Current {
489 worker: Some(job.id),
490 task: request.task,
491 run,
492 })
493 })
494 .collect::<Result<Vec<_>>>()
495 });
496 match workers {
497 Ok(workers) => {
498 for worker in workers {
499 if !current.iter().any(|claim| {
500 claim.task == worker.task
501 && claim.run == worker.run
502 && claim.worker == worker.worker
503 }) {
504 current.push(worker);
505 }
506 }
507 }
508 Err(error) => {
509 tracing::error!("cannot determine active workers: {error:#}");
512 current.extend(
513 Queue::at(home.join("queue"))
514 .list()
515 .into_iter()
516 .map(|task| Current {
517 worker: None,
518 task: task.id,
519 run: task.runs.last().cloned().unwrap_or_default(),
520 }),
521 );
522 current.extend(
523 crate::run::list_ids_in(&home.join("runs"))
524 .into_iter()
525 .map(|run| Current {
526 worker: None,
527 task: String::new(),
528 run,
529 }),
530 );
531 }
532 }
533 current
534}
535
536#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539 current_work(home, now).iter().any(|c| c.run == run)
540}
541
542pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547 let same_home = std::env::var_os("MAGI_WORKER_HOME")
550 .is_some_and(|worker_home| Path::new(&worker_home) == home);
551 let caller = if same_home {
552 crate::worker::current_job(home)?
553 } else {
554 None
555 }
556 .filter(|job| {
557 job.kind == "task"
558 && job.status == crate::worker::Status::Running
559 && job.pid == Some(std::process::id())
560 });
561 Ok(other_claims_run(
562 ¤t_work(home, now),
563 run,
564 caller.as_ref().map(|job| job.id.as_str()),
565 ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569 claims
570 .iter()
571 .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585 current_work(home, now)
586 .iter()
587 .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593 current_work(home, now).iter().any(|c| c.task == task)
594}
595
596pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644 F: Fn(u32) -> bool,
645{
646 let this_process = std::process::id();
647 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648 .into_iter()
649 .flatten()
650 .flatten()
651 .map(|e| e.path())
652 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653 .filter(|p| {
654 match std::fs::read_to_string(p)
655 .ok()
656 .and_then(|body| body.trim().parse::<u32>().ok())
657 {
658 Some(pid) if pid == this_process => false,
662 Some(pid) => !pid_alive(pid),
663 None => p
664 .metadata()
665 .and_then(|m| m.modified())
666 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667 .is_ok_and(|age| age >= older_than),
668 }
669 })
670 .filter(|p| std::fs::remove_file(p).is_ok())
671 .filter_map(|p| {
672 p.file_stem()
673 .and_then(|s| s.to_str())
674 .map(std::borrow::ToOwned::to_owned)
675 })
676 .collect();
677 swept.sort_unstable();
678 swept
679}
680
681fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686 task.status == TaskStatus::Running
687 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688 && !is_working_on_task(home, &task.id, now)
689}
690
691fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694 queue
695 .list()
696 .into_iter()
697 .filter(|t| is_stalled(t, home, now))
698 .collect()
699}
700
701fn queued_tasks(queue: &Queue) -> Vec<Task> {
707 queue
708 .list()
709 .into_iter()
710 .filter(|t| t.status == TaskStatus::Queued)
711 .collect()
712}
713
714fn finished_tasks(queue: &Queue) -> Vec<Task> {
717 queue
718 .list()
719 .into_iter()
720 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721 .collect()
722}
723
724fn resolve_blockers(queue: &Queue, questions: &Questions) {
741 for listed in queue.list() {
742 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743 continue;
744 }
745 let Ok(_claim) = queue.claim(&listed.id) else {
746 continue;
747 };
748 let Ok(mut task) = queue.get(&listed.id) else {
749 continue;
750 };
751 if task.status != TaskStatus::Blocked {
752 continue;
753 }
754 let deleted = queue.apply_deleted_blockers(&mut task, questions);
758 if !deleted.is_empty() {
759 record(queue, &mut task);
760 for id in &deleted {
761 queue.note_dependency_deleted(&task, id);
762 }
763 if task.status != TaskStatus::Blocked {
764 continue;
765 }
766 }
767 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768 if !missing.is_empty() {
769 let language = language_of(&task, Path::new("."));
770 let mut cause = missing.clone();
771 cause.sort();
772 cause.dedup();
773 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775 &task.blocked_by,
776 &missing,
777 &language,
778 )));
779 record(queue, &mut task);
780 continue;
781 }
782 if let Some(q) = task.blocked_by.iter().find_map(|id| {
785 let crate::queue::Dependency::Question(full) =
786 crate::queue::dependency(queue, questions, id)
787 else {
788 return None;
789 };
790 questions.get(&full).ok().filter(|q| {
791 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792 })
793 }) {
794 let language = language_of(&task, Path::new("."));
795 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797 record(queue, &mut task);
798 continue;
799 }
800 let mut changed = false;
801 for id in task.blocked_by.clone() {
802 let resolved = crate::queue::dependency(queue, questions, &id);
803 if let crate::queue::Dependency::Task(full) = &resolved {
804 if queue
805 .get(full)
806 .is_ok_and(|dep| dep.status == TaskStatus::Done)
807 {
808 task.unblock(&id);
809 changed = true;
810 }
811 continue;
812 }
813 if let crate::queue::Dependency::Question(full) = resolved
814 && let Ok(q) = questions.get(&full)
815 && q.status == ask::QuestionStatus::Answered
816 {
817 if q.node == crate::conduct::NODE
821 && q.chosen_action().is_some()
822 && !task.action_applied(&q.id)
823 {
824 continue;
825 }
826 let answer = match &q.answer {
827 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828 None => String::new(),
829 };
830 task.record_answer(q.summary.clone(), answer);
831 task.unblock(&id);
832 changed = true;
833 }
834 }
835 if changed {
836 record(queue, &mut task);
837 }
838 }
839}
840
841fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843 if crate::lang::is_japanese(language) {
844 format!(
845 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846 q.short(),
847 q.summary
848 )
849 } else {
850 format!(
851 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852 q.short(),
853 q.summary
854 )
855 }
856}
857
858#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862 NoAction,
864 Pending,
866 Applied,
869 Stale,
871 Busy,
873}
874
875impl ActionStanding {
876 pub(crate) fn daemon_owns(self) -> bool {
878 matches!(self, Self::Pending | Self::Applied | Self::Stale)
879 }
880}
881
882pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886 if q.chosen_action().is_none() {
887 ActionStanding::NoAction
888 } else if task.action_applied(&q.id) {
889 ActionStanding::Applied
890 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891 ActionStanding::Stale
892 } else if matches!(
893 task.status,
894 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895 ) {
896 ActionStanding::Busy
897 } else {
898 ActionStanding::Pending
899 }
900}
901
902#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905 Skip,
907 Resume(String),
909 Requeue,
911 Hold,
913 Done,
915 Stale,
918 Refuse(String),
921}
922
923fn decide_action<F>(
932 home: &Path,
933 task: &Task,
934 q: &ask::Question,
935 p: &Phrases,
936 load: F,
937) -> ActionDecision
938where
939 F: FnOnce(&str) -> Result<RunState>,
940{
941 let Some(action) = q.chosen_action() else {
942 return ActionDecision::Skip;
943 };
944 if task.action_applied(&q.id)
945 || matches!(
946 task.status,
947 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
948 )
949 {
950 return ActionDecision::Skip;
951 }
952 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
955 return ActionDecision::Stale;
956 }
957 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
958 let stopping = q.node == land::APPROVAL_NODE
959 && q.resolution()
960 .as_deref()
961 .is_some_and(crate::merge_decision::stops);
962 let decision_at = q.answered_at.unwrap_or(q.asked_at);
966 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
967 return if repair || stopping {
968 ActionDecision::Refuse(format!(
969 "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
970 if repair { "repair" } else { "stop" },
971 q.id,
972 q.run,
973 task.id
974 ))
975 } else {
976 ActionDecision::Stale
977 };
978 }
979 match action {
980 a if a.maintenance() => ActionDecision::Skip,
981 ask::ChoiceAction::ResumeRun { .. }
982 | ask::ChoiceAction::ReleaseTask { .. }
983 | ask::ChoiceAction::RerunChecks { .. }
984 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
985 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
986 ask::ChoiceAction::Hold => ActionDecision::Hold,
987 ask::ChoiceAction::Done => ActionDecision::Done,
988 ask::ChoiceAction::Resume { run } => {
989 if task.runs.last() != Some(run) {
990 return ActionDecision::Refuse((p.resume_not_latest)(
991 q.short(),
992 ask::short_id(run),
993 ));
994 }
995 match load(run) {
996 Ok(s) if stopping => {
997 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
998 || !s
999 .land_approval
1000 .as_ref()
1001 .is_some_and(|binding| binding.question == q.id)
1002 {
1003 ActionDecision::Stale
1004 } else if s.liveness_under(home, false) == Liveness::Live {
1005 ActionDecision::Skip
1006 } else if s.status == RunStatus::Landing
1007 && !s.released()
1008 && s.retired_to.is_none()
1009 {
1010 ActionDecision::Resume(run.clone())
1011 } else {
1012 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1013 }
1014 }
1015 Ok(s)
1016 if q.node == land::APPROVAL_NODE
1017 && q.resolution().as_deref() == Some(land::REPAIR) =>
1018 {
1019 if s.merge_repairs.iter().any(|r| r.question == q.id)
1020 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1021 {
1022 ActionDecision::Stale
1025 } else if s.liveness_under(home, false) == Liveness::Live {
1026 ActionDecision::Skip
1027 } else if s.status != RunStatus::Landing
1028 || s.released()
1029 || s.reviews.is_empty()
1030 || !implementers_match(task, &s)
1031 || !s
1032 .land_approval
1033 .as_ref()
1034 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1035 {
1036 ActionDecision::Refuse(format!(
1037 "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
1038 q.id, run, run
1039 ))
1040 } else {
1041 ActionDecision::Resume(run.clone())
1042 }
1043 }
1044 Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1045 ActionDecision::Refuse("run already has a live driver".into())
1046 }
1047 Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1048 None => ActionDecision::Resume(run.clone()),
1049 Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1050 q.short(),
1051 ask::short_id(run),
1052 &reason.diagnostic(&s),
1053 )),
1054 },
1055 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1056 q.short(),
1057 ask::short_id(run),
1058 &format!("{e:#}"),
1059 )),
1060 }
1061 }
1062 }
1063}
1064
1065struct Phrases {
1079 graph_stopped: fn(&str, &str) -> String,
1081 quorum_lost: &'static str,
1082 quota_took_out: &'static str,
1084 run_ended: &'static str,
1086 waiting_for_answer: &'static str,
1088 recovered_running: &'static str,
1089 no_run_to_recover: &'static str,
1090 could_not_start: &'static str,
1091 resume_not_latest: fn(&str, &str) -> String,
1092 resume_cannot_progress: fn(&str, &str, &str) -> String,
1093 resume_unreadable: fn(&str, &str, &str) -> String,
1094 handover_refused: fn(&crate::handover::Refused) -> String,
1097 handover_hint: &'static str,
1099 reviewers_never_answered: fn(usize, usize) -> String,
1102}
1103
1104const PHRASES_EN: Phrases = Phrases {
1105 graph_stopped: |status, detail| {
1106 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1107 },
1108 quorum_lost: "the judging panel lost its quorum",
1109 quota_took_out: "; quota took out ",
1110 run_ended: "run ended ",
1111 waiting_for_answer: " - waiting for operator answer to question ",
1112 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1113 no_run_to_recover: "task was `running` with no live daemon and no readable \
1114 run to recover; held for a human to check what happened",
1115 could_not_start: "could not start the run: ",
1116 resume_not_latest: |q, run| {
1117 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1118 },
1119 resume_cannot_progress: |q, run, reason| {
1120 format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1121 },
1122 resume_unreadable: |q, run, e| {
1123 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1124 },
1125 handover_refused: |r| r.to_string(),
1126 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1127 reviewers_never_answered: |missing, rounds| {
1128 format!(
1129 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1130 refusing to call it clean"
1131 )
1132 },
1133};
1134
1135const PHRASES_JA: Phrases = Phrases {
1136 graph_stopped: |status, detail| {
1137 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1138 },
1139 quorum_lost: "審査パネルが定足数を失いました",
1140 quota_took_out: "。クォータで脱落: ",
1141 run_ended: "run 終了: ",
1142 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1143 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1144 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1145 何が起きたか人が確認するため保留にしました",
1146 could_not_start: "run を開始できませんでした: ",
1147 resume_not_latest: |q, run| {
1148 format!(
1149 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1150 )
1151 },
1152 resume_cannot_progress: |q, run, reason| {
1153 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1154 },
1155 resume_unreadable: |q, run, e| {
1156 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1157 },
1158 handover_refused: |r| {
1159 use crate::handover::Refused;
1160 match r {
1161 Refused::Foreign { branch, path, why } => format!(
1162 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1163 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1164 から、やり直してください(詳細: {why})"
1165 ),
1166 Refused::Unsafe { branch, path, why } => format!(
1167 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1168 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1169 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1170 ),
1171 Refused::ReleaseFailed { branch, path, run } => format!(
1172 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1173 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1174 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1175 ),
1176 }
1177 },
1178 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1179 reviewers_never_answered: |missing, rounds| {
1180 format!(
1181 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1182 クリーンとは認めません"
1183 )
1184 },
1185};
1186
1187fn phrases(language: &str) -> &'static Phrases {
1188 if crate::lang::is_japanese(language) {
1189 &PHRASES_JA
1190 } else {
1191 &PHRASES_EN
1192 }
1193}
1194
1195fn language_of(task: &Task, fallback: &Path) -> String {
1199 crate::lang::of_repo(&repo_for(task, fallback))
1200}
1201
1202pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1206 if q.node == crate::conduct::NODE {
1207 return tasks.iter().find(|t| t.id == q.run);
1208 }
1209 tasks.iter().find(|t| t.runs.contains(&q.run))
1210}
1211
1212fn repair_choice_offers(questions: &Questions) {
1215 for q in questions.list().into_iter().filter(|q| {
1216 q.status.open()
1217 && q.node == crate::conduct::NODE
1218 && q.choices
1219 .iter()
1220 .any(|c| crate::choice_effect::describe(q, c).is_none())
1221 }) {
1222 let _ = questions.update(&q.id, |current| {
1223 if current.status.open() {
1224 crate::choice_effect::executable_conductor(current);
1225 if let Some(deputy) = &mut current.deputy {
1226 deputy.brief = crate::deputy::brief(
1227 ¤t.run,
1228 ¤t.detail,
1229 ¤t.choices,
1230 ¤t.actions,
1231 );
1232 }
1233 }
1234 Ok(())
1235 });
1236 }
1237}
1238
1239pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1242 apply_maintenance_choices(queue, questions, home).await;
1243 apply_task_choice_actions(queue, questions, home);
1244}
1245
1246async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1249 for q in questions.list() {
1250 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1251 continue;
1252 };
1253 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1256 continue;
1257 }
1258 let dir = home.join("choice-actions");
1259 if std::fs::create_dir_all(&dir).is_err() {
1260 continue;
1261 }
1262 let Ok(lock) = std::fs::OpenOptions::new()
1263 .create(true)
1264 .truncate(false)
1265 .write(true)
1266 .open(dir.join(format!("{}.lock", q.id)))
1267 else {
1268 continue;
1269 };
1270 if crate::pr_head::try_lock_file(&lock).is_err() {
1271 continue;
1272 }
1273 let fresh = !home
1274 .join("choice-actions")
1275 .join(format!("{}.json", q.id))
1276 .exists();
1277 let result = async {
1278 let receipt = dir.join(format!("{}.json", q.id));
1279 if receipt.exists() {
1280 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1281 anyhow::ensure!(
1282 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1283 "previous maintenance attempt did not confirm completion; inspect its receipt"
1284 );
1285 return Ok::<_, anyhow::Error>(());
1286 }
1287 let record = |status: &str| -> anyhow::Result<()> {
1290 let tmp = receipt.with_extension("tmp");
1291 std::fs::write(
1292 &tmp,
1293 serde_json::to_vec(&serde_json::json!({
1294 "action": action, "status": status,
1295 }))?,
1296 )?;
1297 std::fs::rename(tmp, &receipt)?;
1298 Ok(())
1299 };
1300 let applied = async {
1301 match action {
1302 ask::ChoiceAction::ResumeRun { run } => {
1303 crate::resume::validate(home, run)?;
1304 record("started")?;
1305 let decided = q.answered_at.unwrap_or(q.asked_at);
1306 if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1307 crate::resume::validate_unqueued(home, run)?;
1308 crate::resume::start(home, run.clone()).await?;
1309 }
1310 }
1311 ask::ChoiceAction::ReleaseTask {
1312 task,
1313 held_at,
1314 reason,
1315 } => {
1316 anyhow::ensure!(
1317 queue.resolve_id(task)? == *task,
1318 "task action requires an exact task ID"
1319 );
1320 let _claim = queue.claim(task)?;
1321 let mut task = queue.get(task)?;
1322 if task.action_applied(&q.id) {
1323 return Ok(());
1324 }
1325 if q.node == crate::conduct::NODE
1330 && q.run == task.id
1331 && task.status == TaskStatus::Blocked
1332 && task.blocked_from == Some(TaskStatus::Held)
1333 && task.blocked_by.as_slice() == [q.id.as_str()]
1334 {
1335 task.unblock(&q.id);
1336 }
1337 anyhow::ensure!(
1338 task.status == TaskStatus::Held
1339 && task.held_at == Some(*held_at)
1340 && task.hold_reason.as_deref() == reason.as_deref()
1341 && task
1342 .operator_decided_at
1343 .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1344 "task no longer has the hold this question names"
1345 );
1346 task.release_operator("choice", Some(&q.id));
1347 task.mark_action_applied(&q.id);
1348 queue.put(&mut task)?;
1349 }
1350 ask::ChoiceAction::AbandonRun { run } => {
1351 record("started")?;
1352 crate::driver::abandon_proven_dead(home, run)?;
1353 }
1354 ask::ChoiceAction::RerunChecks {
1355 repo,
1356 pr,
1357 head,
1358 runs,
1359 } => {
1360 rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1361 .await?;
1362 }
1363 _ => unreachable!(),
1364 }
1365 Ok::<_, anyhow::Error>(())
1366 }
1367 .await;
1368 match applied {
1369 Ok(()) => record("applied"),
1370 Err(e) => {
1371 record(&format!("refused or failed: {e:#}"))?;
1372 Err(e)
1373 }
1374 }
1375 }
1376 .await;
1377 if home
1382 .join("choice-actions")
1383 .join(format!("{}.json", q.id))
1384 .exists()
1385 && let Some(listed) = task_of_question(&queue.list(), &q)
1386 && !listed.action_applied(&q.id)
1387 && let Ok(_claim) = queue.claim(&listed.id)
1388 && let Ok(mut origin) = queue.get(&listed.id)
1389 {
1390 if !origin.operator_held()
1391 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1392 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1393 {
1394 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1395 origin.hold_machine(Some(format!(
1396 "Maintenance choice {} settled; inspect its target before releasing this task",
1397 q.id
1398 )));
1399 } else {
1400 origin.unblock(&q.id);
1401 }
1402 }
1403 origin.mark_action_applied(&q.id);
1404 let _ = queue.put(&mut origin);
1405 }
1406 if let Err(e) = result
1407 && fresh
1408 {
1409 notices::raise_in(
1410 home,
1411 Notice::warn(
1412 &format!("action:{}", q.id),
1413 format!("Choice action {} was not completed: {e:#}", q.id),
1414 )
1415 .link(if q.run_names_task() {
1416 Link::Task { id: q.run.clone() }
1417 } else {
1418 Link::Run { id: q.run.clone() }
1419 }),
1420 );
1421 }
1422 }
1423}
1424
1425pub(crate) async fn rerun_checks_once(
1432 home: &Path,
1433 request: &str,
1434 repo: &Path,
1435 pr: &str,
1436 head: &str,
1437 runs: &[String],
1438 started: impl FnOnce() -> anyhow::Result<()>,
1439) -> anyhow::Result<()> {
1440 use crate::release_watch::{GhForge, ReleaseForge};
1441 anyhow::ensure!(
1442 !runs.is_empty()
1443 && runs.len() <= 20
1444 && runs
1445 .iter()
1446 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1447 && !pr.starts_with('-'),
1448 "invalid rerun targets"
1449 );
1450 let snap = GhForge.snapshot(repo, pr).await?;
1451 anyhow::ensure!(
1452 snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1453 "pull request head or lifecycle changed"
1454 );
1455 anyhow::ensure!(
1456 runs.iter().all(|r| snap
1457 .checks
1458 .iter()
1459 .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1460 "named workflow is no longer failed on this pull request"
1461 );
1462 started()?;
1463 let dir = home.join("choice-actions");
1464 std::fs::create_dir_all(&dir)?;
1465 let rerun_lock = std::fs::OpenOptions::new()
1466 .create(true)
1467 .truncate(false)
1468 .write(true)
1469 .open(dir.join("reruns.lock"))?;
1470 crate::pr_head::try_lock_file(&rerun_lock)?;
1471 let ledger = dir.join("reruns.json");
1472 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1473 serde_json::from_slice(&std::fs::read(&ledger)?)?
1474 } else {
1475 Default::default()
1476 };
1477 for run in runs {
1478 let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1479 if !recorded.insert(key) {
1480 continue;
1481 }
1482 let tmp = ledger.with_extension("tmp");
1483 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1484 std::fs::rename(tmp, &ledger)?;
1485 GhForge.rerun(repo, run).await?;
1486 }
1487 Ok(())
1488}
1489
1490pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1499 let tasks = queue.list();
1500 for q in questions.list() {
1501 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1503 continue;
1504 }
1505 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1506 continue;
1507 }
1508 let Some(listed) = task_of_question(&tasks, &q) else {
1509 if q.node == land::APPROVAL_NODE
1510 && q.resolution().as_deref().is_some_and(|choice| {
1511 choice == land::REPAIR || crate::merge_decision::stops(choice)
1512 })
1513 {
1514 notices::raise_in(
1515 home,
1516 Notice::warn(
1517 &format!("repair-owner:{}", q.id),
1518 format!(
1519 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1520 q.run, q.run
1521 ),
1522 ).link(Link::Run { id: q.run.clone() }),
1523 );
1524 }
1525 continue;
1526 };
1527 if listed.action_applied(&q.id) {
1528 continue;
1529 }
1530 let Ok(_claim) = queue.claim(&listed.id) else {
1531 continue;
1532 };
1533 let Ok(mut task) = queue.get(&listed.id) else {
1534 continue;
1535 };
1536 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1539 let blockers: Vec<_> = task
1540 .blocked_by
1541 .iter()
1542 .filter(|id| {
1543 crate::queue::dependency(queue, questions, id)
1544 == crate::queue::Dependency::Question(q.id.clone())
1545 })
1546 .cloned()
1547 .collect();
1548 if !blockers.is_empty() {
1549 for id in blockers {
1550 task.unblock(&id);
1551 }
1552 let answer = match &q.answer {
1553 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1554 None => String::new(),
1555 };
1556 task.record_answer(q.summary.clone(), answer);
1557 }
1558 }
1559 let language = language_of(&task, Path::new("."));
1560 let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1561 RunState::load_under(id, home)
1562 });
1563 let ran = matches!(
1564 decision,
1565 ActionDecision::Resume(_)
1566 | ActionDecision::Requeue
1567 | ActionDecision::Hold
1568 | ActionDecision::Done
1569 );
1570 if ran && asker_may_still_read(questions, &q, home) {
1571 continue;
1580 }
1581 let done = matches!(decision, ActionDecision::Done);
1582 match decision {
1583 ActionDecision::Skip => continue,
1584 ActionDecision::Resume(run) => {
1585 task.release_operator("choice", Some(&q.id));
1586 task.resume_override = Some(crate::queue::OperatorResume {
1587 question_id: q.id.clone(),
1588 at: Timestamp::now(),
1589 conductor_rehold: None,
1590 forced: true,
1591 pinned_run: Some(run),
1592 });
1593 }
1594 ActionDecision::Stale => {}
1595 ActionDecision::Requeue => {
1596 task.release_operator("choice-requeue", Some(&q.id));
1597 task.requeue();
1598 }
1599 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1600 ActionDecision::Done => task.succeed(),
1601 ActionDecision::Refuse(why) => {
1602 if task.operator_held() {
1603 task.hold_reason = Some(match task.hold_reason.take() {
1606 Some(reason) => format!("{reason}\n\n{why}"),
1607 None => why,
1608 });
1609 } else {
1610 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1611 task.hold_machine(Some(why));
1612 }
1613 notices::raise(
1614 Notice::warn(
1615 &format!("action:{}", q.id),
1616 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1617 )
1618 .link(Link::Task {
1619 id: task.id.clone(),
1620 }),
1621 );
1622 }
1623 }
1624 task.mark_action_applied(&q.id);
1625 record(queue, &mut task);
1628 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1629 supersede_prior_runs(&task, home);
1630 }
1631 let _ = questions.update(&q.id, |r| {
1634 r.answer_delivered = true;
1635 Ok(())
1636 });
1637 }
1638}
1639
1640fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1644 let now = Timestamp::now();
1645 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1646 return true;
1647 }
1648 q.node != crate::conduct::NODE
1649 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1650 s.seats_active()
1651 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1652 })
1653}
1654
1655fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1666 let tasks = queue.list();
1667 let by_id: std::collections::BTreeMap<&str, &Task> =
1668 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1669 let referenced: Vec<&str> = tasks
1670 .iter()
1671 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1672 .collect();
1673
1674 for mut question in questions.list() {
1675 if !question.status.open() || question.node != crate::conduct::NODE {
1676 continue;
1677 }
1678 if referenced
1683 .iter()
1684 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1685 {
1686 continue;
1687 }
1688 let Some(task) = by_id.get(question.run.as_str()) else {
1689 continue;
1690 };
1691 question.abandon(format!(
1692 "task {} no longer waits for this answer",
1693 task.short()
1694 ));
1695 if let Err(e) = questions.put(&mut question) {
1696 tracing::warn!(
1697 "could not retire question {} for task {}: {e:#}",
1698 question.short(),
1699 task.short()
1700 );
1701 }
1702 }
1703}
1704
1705#[derive(Debug, Clone, Copy)]
1712pub struct Verdict {
1713 pub status: RunStatus,
1715 pub left_pr: bool,
1717 pub quota_hit: bool,
1719 pub parked: bool,
1721 pub no_viable_candidates: bool,
1728}
1729
1730pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1789 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1790}
1791
1792fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1794 if verdict.parked {
1800 task.park(detail);
1801 return;
1802 }
1803 match verdict.status {
1804 RunStatus::Merged | RunStatus::Ready
1805 if task.pr_recovery.as_ref().is_some_and(|s| {
1806 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1807 }) =>
1808 {
1809 task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1810 }
1811 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1812 RunStatus::AlreadyInBase => task.already_landed(detail),
1813 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1814 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1815 task.stall(detail)
1816 }
1817 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1818 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1819 RunStatus::Blocked => task.fail(detail, max_attempts),
1820 RunStatus::VerifiedNoop => task.handed_off(detail),
1821 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1822 }
1823}
1824
1825pub fn supersede_prior_runs(task: &Task, home: &Path) {
1874 let now = Timestamp::now();
1875 let last_run_succeeded = task
1882 .runs
1883 .last()
1884 .and_then(|id| RunState::load_under(id, home).ok())
1885 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1886 for id in task.superseded_attempts(last_run_succeeded) {
1887 let mut state = match RunState::load_under(id, home) {
1888 Ok(s) => s,
1889 Err(e) => {
1890 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1891 continue;
1892 }
1893 };
1894 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1895 continue;
1896 }
1897 let daemon_claims = is_working_on(home, id, now);
1898 if state.liveness(daemon_claims) == Liveness::Live {
1899 continue;
1900 }
1901 state.status = RunStatus::Superseded;
1902 if let Err(e) = state.save_under(home) {
1903 tracing::warn!("could not mark run {id} superseded: {e:#}");
1904 }
1905 }
1906}
1907
1908fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1930 for task in queue.list() {
1931 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1932 continue;
1933 }
1934 supersede_prior_runs(&task, home);
1935 }
1936}
1937
1938fn settle_and_diagnose(
1945 task: &mut Task,
1946 verdict: Verdict,
1947 detail: &str,
1948 max_attempts: usize,
1949 state: &RunState,
1950) {
1951 let p = phrases(&state.config.graph.language);
1952 if let Some(d) = &state.merge_decision {
1955 use crate::merge_decision as md;
1956 if task.runs.last().is_some_and(|id| id != &state.id) {
1957 return;
1958 }
1959 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1960 task.succeed();
1961 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1962 if state.liveness(false) != Liveness::Dead {
1963 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1964 return;
1965 }
1966 let replacement = md::Replacement {
1967 question: d.question.clone(),
1968 run: state.id.clone(),
1969 pr: d.target.pr.clone(),
1970 agent: agent.to_owned(),
1971 context: format!(
1972 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1973 d.target.pr,
1974 state.id,
1975 serde_json::to_string(&state.reviews).unwrap_or_default()
1976 ),
1977 };
1978 task.requeue();
1979 task.pr_recovery = None;
1980 task.review_of = None;
1981 task.replacement = Some(replacement);
1982 } else {
1983 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1984 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1985 } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
1986 }
1987 task.mark_action_applied(&d.question);
1988 if let Some(pass) = state.passes.last() {
1989 task.record_pass_at(
1990 &state.id,
1991 pass.index,
1992 Some(pass.started_at),
1993 task.attempts,
1994 None,
1995 );
1996 }
1997 return;
1998 }
1999 if let Some(replacement) = &task.replacement
2000 && !state.parked
2001 && state.resource_block.is_none()
2002 && (state.viable().is_empty()
2003 || (state.status == RunStatus::Blocked && state.tally.is_none()))
2004 {
2005 task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
2006 return;
2007 }
2008 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2009 let mut agents: Vec<_> = state
2010 .quota
2011 .iter()
2012 .filter(|q| {
2013 q.cause == crate::agent::QuotaCause::Authentication
2014 && state
2015 .passes
2016 .last()
2017 .is_none_or(|pass| q.at >= pass.started_at)
2018 })
2019 .map(|q| q.agent.as_str())
2020 .collect();
2021 agents.sort_unstable();
2022 agents.dedup();
2023 if !agents.is_empty() {
2024 task.stall(detail);
2025 task.notice_cause("agent-authentication", None, None);
2026 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2027 return;
2028 }
2029 }
2030 let attempts_before = task.attempts;
2031 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2038 task.notice_cause(
2039 &format!("resource:{}:{}", block.kind, block.node),
2040 None,
2041 None,
2042 );
2043 task.last_error = Some(detail.to_owned());
2044 task.diagnostic = None;
2045 task.attempts = task.attempts.saturating_sub(1);
2046 if block.kind == "agent authentication" {
2047 task.hold_machine(Some(format!(
2048 "[authentication] {}; no attempt was spent",
2049 block.detail
2050 )));
2051 } else if block.kind == "agent usage limit" {
2052 if let Some(agent) = &state.config.graph.selected_implementer {
2054 task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2055 } else {
2056 task.status = TaskStatus::Failed;
2057 task.last_error = Some(block.detail.clone());
2058 }
2059 } else if block.kind == "disk pressure" {
2060 task.hold_machine(Some(format!(
2061 "{}{}",
2062 crate::disk::RUNNING_PRESSURE,
2063 block.detail
2064 )));
2065 } else {
2066 task.hold_machine(Some(format!(
2067 "{}{}; no attempt was spent; resume to retry the affected operation",
2068 crate::cache::RESOURCE_HOLD,
2069 block.description()
2070 )));
2071 }
2072 if let Some(pass) = state.passes.last() {
2073 task.record_pass_at(
2074 &state.id,
2075 pass.index,
2076 Some(pass.started_at),
2077 attempts_before,
2078 None,
2079 );
2080 }
2081 return;
2082 }
2083 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2084 state.parked
2085 && state.status == RunStatus::Landing
2086 && state
2087 .pr_pushed_head
2088 .as_ref()
2089 .is_none_or(|h| h == &hold.head)
2090 && task.runs.last() == Some(&state.id)
2091 }) {
2092 let pass = state.passes.last().map_or(0, |p| p.index);
2095 if !task
2096 .passes
2097 .iter()
2098 .any(|p| p.run == state.id && p.pass_index == pass)
2099 {
2100 task.attempts = task.attempts.saturating_sub(1);
2101 }
2102 task.hold_machine(Some(format!(
2103 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2104 hold.question
2105 )));
2106 task.last_error = Some(detail.to_owned());
2107 task.diagnostic = None;
2108 task.record_pass_at(
2109 &state.id,
2110 pass,
2111 state.passes.last().map(|p| p.started_at),
2112 attempts_before,
2113 Some(crate::run::ParkCause::Question),
2114 );
2115 return;
2116 }
2117 let unresolved = task.hold_notice_cause.clone();
2118 if state.base_sync_blocked() {
2119 task.hold_machine(Some(detail.to_owned()));
2121 task.last_error = Some(detail.to_owned());
2122 } else if !verdict.parked
2123 && task
2124 .pr_recovery
2125 .as_ref()
2126 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2127 && matches!(
2128 verdict.status,
2129 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2130 )
2131 {
2132 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2133 task.succeed();
2134 } else {
2135 task.hold_manual(Some("Selected PR delivery is incomplete: local review or publication is not a confirmed public merge. Inspect the run and PR; use recover-pr --disposition land with --source-head <reviewed-full-SHA> and the required verification configuration. No automatic new attempt will start.".into()));
2136 }
2137 } else if !verdict.parked
2138 && task.pr_recovery.is_some()
2139 && matches!(
2140 verdict.status,
2141 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2142 )
2143 && !verdict.quota_hit
2144 {
2145 task.hold_unrequested_retry(Some(format!("Selected recovery stopped: {detail}. Inspect the retained source and run; correct the cause before explicitly releasing or selecting again. No automatic replacement will start.")));
2146 } else {
2147 settle_in(task, verdict, detail, max_attempts, p);
2148 }
2149 if !verdict.parked
2150 && !verdict.quota_hit
2151 && matches!(
2152 verdict.status,
2153 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2154 )
2155 {
2156 task.recovery_failed(state);
2157 }
2158 if state.prep_failure.is_some() {
2159 task.hold_notice_cause = unresolved;
2162 task.startup_notice_cause("startup-candidates");
2163 }
2164 if let Some(pass) = state.passes.last() {
2167 let parked = match &pass.end {
2168 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2169 _ => None,
2170 };
2171 task.record_pass_at(
2172 &state.id,
2173 pass.index,
2174 Some(pass.started_at),
2175 attempts_before,
2176 parked,
2177 );
2178 }
2179 if task.status == TaskStatus::Held {
2180 if state.base_sync_blocked() {
2181 task.base_sync_notice(state);
2182 } else if state.prep_failure.is_none() {
2183 task.notice_cause(
2184 label(verdict.status),
2185 Some(&state.id),
2186 state.passes.last().map(|p| p.index),
2187 );
2188 }
2189 task.diagnostic = diagnostic(state);
2190 note_open_question(task, &state.id, p);
2191 }
2192}
2193
2194fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2209 let Some(home) = crate::run::try_home() else {
2210 return;
2211 };
2212 let open = Questions::at(home.join("questions")).open_for(run);
2213 let Some(q) = open.first() else {
2214 return;
2215 };
2216 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2217 decisions.sort_unstable();
2218 task.notice_cause(
2219 &format!("questions:{}", decisions.join(",")),
2220 Some(run),
2221 None,
2222 );
2223 let base = task.hold_reason.clone().unwrap_or_default();
2224 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2225}
2226
2227fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2238 match last_run {
2239 Some(state) => {
2240 let verdict = Verdict {
2241 status: state.status,
2242 left_pr: state.pr.is_some(),
2243 quota_hit: state.quota.iter().any(|loss| {
2244 state
2245 .passes
2246 .last()
2247 .is_none_or(|pass| loss.at >= pass.started_at)
2248 }),
2249 parked: state.parked,
2250 no_viable_candidates: state.viable().is_empty(),
2251 };
2252 let detail = format!(
2253 "{}{}",
2254 phrases(&state.config.graph.language).recovered_running,
2255 describe(&state)
2256 );
2257 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2258 }
2259 None => {
2260 let why = phrases(language).no_run_to_recover;
2263 task.last_error = Some(why.to_owned());
2264 task.notice_cause("missing-run", None, None);
2267 task.hold_machine(Some(why.to_owned()));
2268 }
2269 }
2270}
2271
2272fn reclaim_orphaned_running(
2294 queue: &Queue,
2295 max_attempts: usize,
2296 live_workers: &std::collections::BTreeSet<String>,
2297) -> Vec<String> {
2298 let mut reclaimed = Vec::new();
2299 for listed in queue.list() {
2300 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2301 continue;
2302 }
2303 let Ok(_claim) = queue.claim(&listed.id) else {
2304 continue;
2305 };
2306 let Ok(mut task) = queue.get(&listed.id) else {
2310 continue;
2311 };
2312 if task.status != TaskStatus::Running {
2313 continue;
2314 }
2315 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2316 if let Some(state) = &last_run
2326 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2327 {
2328 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2329 }
2330 let language = if last_run.is_none() {
2331 language_of(&task, Path::new("."))
2332 } else {
2333 String::new()
2334 };
2335 reclaim(&mut task, last_run, max_attempts, &language);
2336 if task.status == TaskStatus::Done {
2337 supersede_prior_runs(&task, &crate::run::home());
2338 }
2339 record(queue, &mut task);
2340 reclaimed.push(task.id.clone());
2341 }
2342 reclaimed
2343}
2344
2345fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2377 reclaim_abandoned_runs_with(
2378 home,
2379 now,
2380 crate::proc::pid_status,
2381 crate::proc::process_started_at,
2382 )
2383}
2384
2385fn reclaim_abandoned_runs_with<F, G>(
2391 home: &Path,
2392 now: Timestamp,
2393 query: F,
2394 identity: G,
2395) -> Vec<String>
2396where
2397 F: Fn(u32) -> Option<bool>,
2398 G: Fn(u32) -> Option<String>,
2399{
2400 let mut abandoned = Vec::new();
2401 for entry in std::fs::read_dir(home.join("runs"))
2402 .into_iter()
2403 .flatten()
2404 .flatten()
2405 {
2406 let id = entry.file_name().to_string_lossy().into_owned();
2407 if !crate::run::is_run_id(&id) {
2408 continue;
2409 }
2410 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2413 continue;
2414 };
2415 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2423 continue;
2424 };
2425 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2426 continue;
2427 };
2428 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2429 continue;
2430 }
2431 let daemon_claims = is_working_on(home, &id, now);
2443 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2444 != crate::run::Liveness::Dead
2445 {
2446 continue;
2447 }
2448 state.abandon("daemon");
2449 if let Err(e) = state.save_under(home) {
2450 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2451 continue;
2452 }
2453 if let Some(notice) = notices::run_ended(&state) {
2456 notices::raise_in(home, notice);
2457 }
2458 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2466 tracing::warn!("abandon questions for {id}: {e:#}");
2467 }
2468 abandoned.push(id);
2469 }
2470 abandoned
2471}
2472
2473#[derive(Debug, Clone, Serialize, Deserialize)]
2474struct TaskWorker {
2475 opts: Opts,
2476 queue: PathBuf,
2477 task: String,
2478 #[serde(default)]
2479 lane: PermitKind,
2480 #[serde(default)]
2481 standalone: bool,
2482}
2483
2484fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2485 Ok(crate::worker::active(home)?
2486 .into_iter()
2487 .filter(|job| job.kind == "task")
2488 .collect())
2489}
2490
2491fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2492 task_jobs(home)?
2493 .into_iter()
2494 .filter_map(
2495 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2496 Ok(request) if !request.standalone => Some(Ok(job)),
2497 Ok(_) => None,
2498 Err(error) => Some(Err(error.into())),
2499 },
2500 )
2501 .collect()
2502}
2503
2504#[must_use]
2506pub fn managed(home: &Path) -> bool {
2507 match crate::worker::active(home) {
2508 Err(error) => {
2509 tracing::error!("cannot determine scheduler ownership: {error:#}");
2510 true
2511 }
2512 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2513 Ok(_) => {
2514 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2515 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2516 }
2517 }
2518}
2519
2520pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2522 anyhow::ensure!(
2523 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2524 "the scheduler is stopping; wait for retirement before starting it again"
2525 );
2526 crate::worker::spawn(
2527 home,
2528 "scheduler",
2529 "scheduler",
2530 serde_json::to_value(opts.absolute()?)?,
2531 )
2532 .await
2533}
2534
2535fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2536 home.join("worker-parks").join(format!("{}.json", job.id))
2537}
2538
2539fn request_task_park(
2540 home: &Path,
2541 job: &crate::worker::Job,
2542 cause: crate::run::ParkCause,
2543) -> Result<()> {
2544 let path = park_request_path(home, job);
2545 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2546 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2547 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2548}
2549
2550pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2552 if control == crate::worker::Control::Park {
2553 for job in owned_task_jobs(home)? {
2554 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2555 }
2556 }
2557 crate::worker::request(home, "scheduler", control)
2558}
2559
2560pub async fn restart_detached(home: &Path) -> Result<()> {
2562 let active = crate::worker::active(home)?;
2563 let prior = active.into_iter().find(|job| job.kind == "scheduler");
2564 if prior.is_none() && !managed(home) {
2565 return Ok(());
2566 }
2567 let opts: Opts = match prior {
2568 Some(job) => serde_json::from_value(job.payload)?,
2569 None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2570 };
2571 request_control(home, crate::worker::Control::Stop)?;
2572 loop {
2573 let reserved = crate::worker::active(home)?
2574 .iter()
2575 .any(|job| job.kind == "scheduler");
2576 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2577 break;
2578 }
2579 tokio::time::sleep(Duration::from_millis(100)).await;
2580 }
2581 spawn_detached(home, &opts).await?;
2582 Ok(())
2583}
2584
2585pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2587 let opts: Opts = serde_json::from_value(payload)?;
2588 let _ = home;
2589 serve_until(opts, Stop::new()).await
2590}
2591
2592pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2594 let request: TaskWorker = serde_json::from_value(payload)?;
2595 let queue = Queue::at(request.queue);
2596 let key = format!("task:{}", request.task);
2597 let job = task_jobs(home)?
2598 .into_iter()
2599 .find(|job| job.key == key)
2600 .context("task worker reservation is missing")?;
2601 let park_path = park_request_path(home, &job);
2602 let _claim = loop {
2605 match queue.claim(&request.task) {
2606 Ok(claim) => break claim,
2607 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2610 return Err(e.context("claim the task for its worker"));
2611 }
2612 Err(_) => {
2613 sweep_stale_claims(&queue, STALE_CLAIM);
2614 tokio::time::sleep(Duration::from_millis(50)).await;
2615 }
2616 }
2617 };
2618 let mut task = queue.get(&request.task)?;
2619 if !task.status.runnable()
2620 || (!request.standalone
2621 && request.lane
2622 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2623 {
2624 return Ok(());
2625 }
2626 let stop = Stop::new();
2627 let watcher = {
2628 let home = home.to_path_buf();
2629 let stop = stop.clone();
2630 let park_path = park_path.clone();
2631 tokio::spawn(async move {
2632 loop {
2633 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2634 let cause = std::fs::read(&park_path)
2635 .ok()
2636 .and_then(|body| serde_json::from_slice(&body).ok())
2637 .unwrap_or(crate::run::ParkCause::Operator);
2638 stop.park(cause);
2639 return;
2640 }
2641 tokio::time::sleep(Duration::from_millis(200)).await;
2642 }
2643 })
2644 };
2645 let quota = if request.standalone {
2646 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2647 } else {
2648 let status = Arc::new(Mutex::new(Status::new()));
2649 Box::pin(attempt(
2650 &request.opts,
2651 &queue,
2652 &status,
2653 &stop,
2654 crate::graph::Pause::new(),
2655 &mut task,
2656 ))
2657 .await
2658 };
2659 watcher.abort();
2660 let _ = std::fs::remove_file(park_path);
2661 persist_cooldown(home, "a).await?;
2662 Ok(())
2663}
2664
2665pub async fn spawn_claimed(
2668 home: &Path,
2669 opts: &Opts,
2670 queue: &Queue,
2671 task: &Task,
2672 claim: crate::queue::Claim,
2673) -> Result<crate::worker::Job> {
2674 let request = TaskWorker {
2675 opts: opts.absolute()?,
2676 queue: std::path::absolute(queue.root())?,
2677 task: task.id.clone(),
2678 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2679 standalone: true,
2680 };
2681 let job = crate::worker::spawn(
2682 home,
2683 "task",
2684 &format!("task:{}", task.id),
2685 serde_json::to_value(request)?,
2686 )
2687 .await?;
2688 drop(claim);
2689 Ok(job)
2690}
2691
2692pub async fn run_detached_claimed(
2695 opts: &Opts,
2696 queue: &Queue,
2697 task: &mut Task,
2698 claim: crate::queue::Claim,
2699) -> Result<()> {
2700 let home = crate::run::home();
2701 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2702 loop {
2703 crate::worker::active(&home)?;
2706 let current = crate::worker::get(&home, &job.id)?;
2707 if matches!(
2708 current.status,
2709 crate::worker::Status::Finished | crate::worker::Status::Failed
2710 ) {
2711 *task = queue.get(&task.id)?;
2712 anyhow::ensure!(
2713 current.status != crate::worker::Status::Failed,
2714 "task worker failed: {}",
2715 current.result.as_deref().unwrap_or("unknown failure")
2716 );
2717 return Ok(());
2718 }
2719 tokio::time::sleep(Duration::from_millis(200)).await;
2720 }
2721}
2722
2723async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2724 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2725 let _lease = loop {
2726 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2727 break lease;
2728 }
2729 tokio::time::sleep(Duration::from_millis(10)).await;
2730 };
2731 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2732 let path = home.join("task-quota-cooldown.json");
2733 let temporary = path.with_extension("json.tmp");
2734 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2735 std::fs::rename(temporary, path)?;
2736 }
2737 }
2738 Ok(())
2739}
2740
2741fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2742 match std::fs::read(home.join("task-quota-cooldown.json")) {
2743 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2744 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2745 Err(error) => Err(error.into()),
2746 }
2747}
2748
2749pub async fn serve(opts: Opts) -> Result<()> {
2755 tracing::info!(
2756 "automatic update and restart requires magi web; standalone serve does not restart"
2757 );
2758 serve_until(opts, Stop::new()).await
2759}
2760
2761pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2772 let opts = opts.absolute()?;
2773 let home = crate::run::home();
2774 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2775 .context("another scheduler already owns this home")?;
2776 if let Some(reading) = read_status(&home)
2777 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2778 {
2779 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2780 }
2781 if !crate::worker::active(&home)?
2782 .iter()
2783 .any(|job| job.kind == "scheduler")
2784 {
2785 crate::worker::clear_control(&home, "scheduler")?;
2786 }
2787 std::fs::write(
2788 home.join("scheduler-options.json"),
2789 serde_json::to_vec(&opts)?,
2790 )?;
2791 let control = {
2792 let home = home.clone();
2793 let stop = stop.clone();
2794 tokio::spawn(async move {
2795 loop {
2796 match crate::worker::control(&home, "scheduler").ok().flatten() {
2797 Some(crate::worker::Control::Park) => {
2798 let _ = request_control(&home, crate::worker::Control::Park);
2799 stop.park(crate::run::ParkCause::Operator);
2800 break;
2801 }
2802 Some(crate::worker::Control::Stop) => {
2803 stop.stop();
2804 break;
2805 }
2806 None => {}
2807 }
2808 tokio::time::sleep(Duration::from_millis(100)).await;
2809 }
2810 })
2811 };
2812 let signal = {
2813 let stop = stop.clone();
2814 tokio::spawn(async move {
2815 if tokio::signal::ctrl_c().await.is_ok() {
2816 stop.stop();
2817 tracing::info!("scheduler shutdown requested; independent workers continue");
2818 }
2819 })
2820 };
2821
2822 let worktrees_root = opts
2823 .worktrees_root
2824 .clone()
2825 .unwrap_or_else(crate::run::default_worktree_root);
2826 let outcome = drive(
2827 &opts,
2828 &Queue::open(),
2829 &status_path(),
2830 &crate::run::home(),
2831 &worktrees_root,
2832 &stop,
2833 )
2834 .await;
2835
2836 signal.abort();
2837 control.abort();
2838 outcome
2839}
2840
2841async fn drive(
2854 opts: &Opts,
2855 queue: &Queue,
2856 status_file: &Path,
2857 home: &Path,
2858 worktrees_root: &Path,
2859 stop: &Stop,
2860) -> Result<()> {
2861 let recovery_cfg = prepare(&opts.repo, opts).ok();
2869 let daemon_cfg = recovery_cfg
2870 .as_ref()
2871 .map(|c| c.daemon.clone())
2872 .unwrap_or_default();
2873 let reconciled = crate::driver::reconcile(home);
2874 if !reconciled.is_empty() {
2875 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2876 }
2877 let mut initial_status = Status::new();
2878 let owned = owned_task_jobs(home)?;
2879 initial_status.current = current_work(home, Timestamp::now())
2880 .into_iter()
2881 .filter(|current| {
2882 owned
2883 .iter()
2884 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2885 })
2886 .collect();
2887 initial_status.idle = initial_status.current.is_empty();
2888 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2889 recovery_cfg.as_ref(),
2890 daemon_cfg.max_deputies,
2891 ));
2892 let status = Arc::new(Mutex::new(initial_status));
2893 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2894 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2895
2896 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2902
2903 tracing::info!(
2904 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2905 queue.root().display(),
2906 opts.poll.as_secs(),
2907 opts.max_attempts,
2908 concurrency,
2909 if daemon_cfg.pause_for_interrupts {
2910 ", interrupts enabled"
2911 } else {
2912 ""
2913 }
2914 );
2915
2916 let outcome = tokio::select! {
2917 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2918 max_concurrent: concurrency,
2919 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2920 recovery_cfg,
2921 }) => outcome,
2922 () = async {
2923 while !stop.stopped() {
2924 tokio::time::sleep(Duration::from_millis(25)).await;
2925 }
2926 } => {
2927 if stop.parking() {
2928 request_control(home, crate::worker::Control::Park)?;
2929 }
2930 Ok(())
2931 }
2932 };
2933
2934 stop.busy.store(0, Ordering::SeqCst);
2935 beat.abort();
2936 clear_status_at(status_file);
2937 outcome
2938}
2939
2940pub(crate) fn release_watch_settings_from_config(
2943 home: &Path,
2944 repo: &Path,
2945 cfg: &Config,
2946) -> (Vec<PathBuf>, u64) {
2947 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2948 .into_iter()
2949 .map(|r| r.path)
2950 .collect();
2951 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2954 .list()
2955 .into_iter()
2956 .map(|t| t.repo)
2957 .collect();
2958 let runs = home.join("runs");
2959 for id in crate::run::list_ids_in(&runs) {
2960 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2961 .ok()
2962 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2963 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2964 known.extend(repo);
2965 }
2966 for k in known {
2967 let k = k.canonicalize().unwrap_or(k);
2968 if k.join(".git").exists() && !paths.contains(&k) {
2969 paths.push(k);
2970 }
2971 }
2972 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2973 if !paths.contains(&own) {
2974 paths.push(own);
2975 }
2976 (paths, cfg.daemon.release_stall_minutes)
2977}
2978
2979const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2981
2982async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2988 loop {
2989 tokio::time::sleep(HEARTBEAT).await;
2990 let snapshot = {
2991 let mut guard = lock(&status);
2992 guard.updated_at = Timestamp::now();
2993 guard.clone()
2994 };
2995 if let Err(e) = write_status_to(&path, &snapshot) {
2996 tracing::warn!("could not refresh the daemon status file: {e:#}");
2999 }
3000 }
3001}
3002
3003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3006enum LandResume {
3007 NotLanding,
3010 StillWaiting,
3015 Ready,
3019}
3020
3021fn land_resume_state(task: &Task) -> LandResume {
3025 let Some(run_id) = task.runs.last() else {
3026 return LandResume::NotLanding;
3027 };
3028 let Ok(state) = RunState::load(run_id) else {
3029 return LandResume::NotLanding;
3030 };
3031 if !state.parked {
3032 return LandResume::NotLanding;
3033 }
3034 if state.status == RunStatus::Landing
3035 && state.land_approval.as_ref().is_some_and(|binding| {
3036 ask::Questions::open()
3037 .get(&binding.question)
3038 .is_ok_and(|q| {
3039 q.run == state.id
3040 && q.resolution()
3041 .as_deref()
3042 .is_some_and(crate::merge_decision::stops)
3043 })
3044 })
3045 {
3046 return LandResume::Ready;
3047 }
3048 if !implementers_match(task, &state) {
3049 return LandResume::NotLanding;
3050 }
3051 let node = if state.status == RunStatus::Landing {
3055 land::APPROVAL_NODE
3056 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3057 crate::github_text::ASK_NODE
3058 } else {
3059 return LandResume::NotLanding;
3060 };
3061 let store = ask::Questions::open();
3062 let waiting = store
3063 .list()
3064 .into_iter()
3065 .filter(|q| &q.run == run_id && q.node == node)
3066 .max_by(|a, b| a.id.cmp(&b.id));
3067 let Some(mut q) = waiting else {
3068 return LandResume::Ready;
3069 };
3070 if !q.status.open() {
3071 if q.resolution().as_deref() == Some(land::REPAIR) {
3074 return if state.liveness(false) == Liveness::Live {
3075 LandResume::StillWaiting
3076 } else {
3077 LandResume::NotLanding
3078 };
3079 }
3080 return LandResume::Ready;
3081 }
3082 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3089 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3090 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3091 q.abandon(format!(
3092 "no answer within {}s of asking",
3093 timeout.as_secs().max(1)
3094 ));
3095 if store.put(&mut q).is_ok() {
3098 return LandResume::Ready;
3099 }
3100 }
3101 LandResume::StillWaiting
3102}
3103
3104const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3112
3113const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3125
3126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3139enum Interrupt {
3140 Idle,
3142 Parking {
3154 parked: Vec<String>,
3155 interrupt_task: String,
3156 },
3157 Running {
3165 parked: Vec<String>,
3166 interrupt_task: String,
3167 },
3168 Resuming { parked: Vec<String> },
3175}
3176
3177fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3198 match state {
3199 Interrupt::Idle => {
3200 if in_flight.len() != 1 {
3212 return Interrupt::Idle;
3213 }
3214 match runnable.iter().find(|t| t.interrupt) {
3215 Some(t) => Interrupt::Parking {
3216 parked: in_flight.to_vec(),
3217 interrupt_task: t.id.clone(),
3218 },
3219 None => Interrupt::Idle,
3220 }
3221 }
3222 Interrupt::Parking {
3223 parked,
3224 interrupt_task,
3225 } => {
3226 if in_flight.iter().any(|id| parked.contains(id)) {
3227 Interrupt::Parking {
3229 parked,
3230 interrupt_task,
3231 }
3232 } else if in_flight.contains(&interrupt_task) {
3233 Interrupt::Running {
3234 parked,
3235 interrupt_task,
3236 }
3237 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3238 Interrupt::Parking {
3242 parked,
3243 interrupt_task,
3244 }
3245 } else {
3246 Interrupt::Resuming { parked }
3251 }
3252 }
3253 Interrupt::Running {
3254 parked,
3255 interrupt_task,
3256 } => {
3257 if in_flight.contains(&interrupt_task) {
3258 Interrupt::Running {
3259 parked,
3260 interrupt_task,
3261 }
3262 } else {
3263 Interrupt::Resuming { parked }
3269 }
3270 }
3271 Interrupt::Resuming { parked } => {
3272 if in_flight.iter().any(|id| parked.contains(id)) {
3273 Interrupt::Idle
3279 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3280 Interrupt::Resuming { parked }
3281 } else {
3282 Interrupt::Idle
3285 }
3286 }
3287 }
3288}
3289
3290fn advance_interrupt_tick(
3296 enabled: bool,
3297 state: Interrupt,
3298 in_flight: &[String],
3299 runnable: &[Task],
3300) -> Interrupt {
3301 if !enabled {
3302 return Interrupt::Idle;
3303 }
3304 advance_interrupt(state, in_flight, runnable)
3305}
3306
3307fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3312 match state {
3313 Interrupt::Idle => candidates,
3314 Interrupt::Parking {
3315 parked,
3316 interrupt_task,
3317 } => {
3318 if in_flight.iter().any(|id| parked.contains(id)) {
3319 Vec::new()
3320 } else {
3321 candidates
3322 .into_iter()
3323 .filter(|t| &t.id == interrupt_task)
3324 .collect()
3325 }
3326 }
3327 Interrupt::Running { .. } => Vec::new(),
3328 Interrupt::Resuming { parked } => candidates
3336 .into_iter()
3337 .find(|t| parked.contains(&t.id))
3338 .into_iter()
3339 .collect(),
3340 }
3341}
3342
3343struct DispatchLimits {
3347 max_concurrent: usize,
3350 pause_for_interrupts: bool,
3352 recovery_cfg: Option<Config>,
3353}
3354
3355#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3364enum PermitKind {
3365 None,
3370 Urgent,
3377 #[default]
3380 Ordinary,
3381}
3382
3383fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3386 if priority {
3387 PermitKind::None
3388 } else if urgent {
3389 PermitKind::Urgent
3390 } else {
3391 PermitKind::Ordinary
3392 }
3393}
3394
3395fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3396 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3397 (0usize, 0usize),
3398 |(ordinary, urgent), request| match request.lane {
3399 PermitKind::Ordinary => (ordinary + 1, urgent),
3400 PermitKind::Urgent => (ordinary, urgent + 1),
3401 PermitKind::None => (ordinary, urgent),
3402 },
3403 );
3404 (
3405 limit.saturating_sub(ordinary),
3406 1usize.saturating_sub(urgent),
3407 )
3408}
3409
3410struct DispatchClaim {
3411 task: Task,
3412 claim: crate::queue::Claim,
3413 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3414}
3415
3416fn claim_dispatch(
3419 queue: &Queue,
3420 candidate: &Task,
3421 cooling_down: bool,
3422 ordinary: &Arc<tokio::sync::Semaphore>,
3423 urgent: &Arc<tokio::sync::Semaphore>,
3424) -> Option<DispatchClaim> {
3425 let Ok(claim) = queue.claim(&candidate.id) else {
3426 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3427 return None;
3428 };
3429 let task = match queue.get(&candidate.id) {
3430 Ok(t) if t.status.runnable() => t,
3431 Ok(_) => return None,
3432 Err(e) => {
3433 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3434 return None;
3435 }
3436 };
3437 let resume = land_resume_state(&task);
3438 if resume == LandResume::StillWaiting {
3439 return None;
3440 }
3441 let priority = resume == LandResume::Ready;
3442 if !priority && cooling_down {
3443 return None;
3444 }
3445 let permit = match permit_kind(priority, task.urgent) {
3448 PermitKind::None => None,
3449 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3450 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3451 };
3452 let stamp = Timestamp::now();
3455 let mut task = task;
3456 task.dispatched_at = Some(stamp);
3457 if let Err(e) = queue.modify(&task.id, |t| {
3458 t.dispatched_at = Some(stamp);
3459 true
3460 }) {
3461 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3462 }
3463 Some(DispatchClaim {
3464 task,
3465 claim,
3466 permit,
3467 })
3468}
3469
3470#[derive(Serialize, Deserialize)]
3489struct ServiceWorker {
3490 opts: Opts,
3491 queue: PathBuf,
3492 worktrees_root: PathBuf,
3493 operation: String,
3494}
3495
3496fn load_conductor(home: &Path) -> Result<Conductor> {
3497 match std::fs::read(home.join("conductor-state.json")) {
3498 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3499 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3500 Err(error) => Err(error.into()),
3501 }
3502}
3503
3504fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3505 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3506 .into_iter()
3507 .map(|c| c.task)
3508 .collect();
3509 let stalled = stalled_tasks(queue, home, Timestamp::now());
3510 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3511 let finished = finished_tasks(queue)
3512 .into_iter()
3513 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3514 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3515 .collect();
3516 let queued = queued_tasks(queue)
3517 .into_iter()
3518 .filter(|t| !live.contains(&t.id))
3519 .collect();
3520 (queued, stalled, finished)
3521}
3522
3523async fn start_service(
3524 home: &Path,
3525 opts: &Opts,
3526 queue: &Queue,
3527 worktrees_root: &Path,
3528 operation: &str,
3529 cfg: Option<&Config>,
3530 busy: bool,
3531) -> Result<()> {
3532 let fetch_cfg = if operation == "fetch" {
3535 match prepare(&opts.repo, opts) {
3536 Ok(cfg) => Some(cfg),
3537 Err(error) => {
3538 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3539 return Ok(());
3540 }
3541 }
3542 } else {
3543 None
3544 };
3545 let cfg = fetch_cfg.as_ref().or(cfg);
3546 let ticks = home.join("service-ticks");
3547 std::fs::create_dir_all(&ticks)?;
3548 let receipt = ticks.join(format!("daemon-{operation}"));
3549 let last = std::fs::read(&receipt)
3550 .ok()
3551 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3552 let interval = match operation {
3553 "disk-pressure" => 30,
3554 "cache" => CACHE_CHECK_INTERVAL_SECS,
3555 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3556 _ => opts.poll.as_secs().max(1),
3557 };
3558 let now = Timestamp::now();
3559 if !cache_check_due(last, now, interval) {
3560 return Ok(());
3561 }
3562 let key = format!("service:daemon-{operation}");
3563 if crate::worker::active(home)?
3564 .iter()
3565 .any(|job| job.key == key)
3566 {
3567 return Ok(());
3568 }
3569 let eligible = match operation {
3570 "conductor" => {
3571 let (queued, stalled, finished) = conductor_work(queue, home);
3572 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3573 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3574 }
3575 "maintenance" => Questions::at(home.join("questions"))
3576 .list()
3577 .iter()
3578 .any(|q| {
3579 q.chosen_action().is_some_and(|action| action.maintenance())
3580 && !home
3581 .join("choice-actions")
3582 .join(format!("{}.json", q.id))
3583 .exists()
3584 }),
3585 "housekeeping" => !busy && runnable(queue).is_empty(),
3586 "cache" => {
3587 !busy
3588 && !runnable(queue).is_empty()
3589 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3590 }
3591 "disk-pressure" => busy,
3592 "fetch" => {
3593 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3594 }
3595 _ => false,
3596 };
3597 if !eligible {
3598 return Ok(());
3599 }
3600 let request = ServiceWorker {
3601 opts: opts.absolute()?,
3602 queue: std::path::absolute(queue.root())?,
3603 worktrees_root: std::path::absolute(worktrees_root)?,
3604 operation: operation.to_owned(),
3605 };
3606 if let Err(error) =
3607 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3608 {
3609 tracing::warn!(operation, "could not launch daemon service: {error:#}");
3610 }
3611 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3612 Ok(())
3613}
3614
3615pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3618 let request: ServiceWorker = serde_json::from_value(payload)?;
3619 let opts = &request.opts;
3620 let queue = Queue::at(request.queue);
3621 let questions = Questions::at(home.join("questions"));
3622 match request.operation.as_str() {
3623 "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3624 "conductor" => {
3625 let path = home.join("conductor-state.json");
3626 let mut conductor = load_conductor(home)?;
3627 let (queued, stalled, finished) = conductor_work(&queue, home);
3628 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3629 && conductor.worth_a_look(&queue, &stalled, &finished)
3630 {
3631 let cfg = prepare(&opts.repo, opts)?;
3632 conductor
3633 .maybe_run(
3634 &cfg,
3635 &opts.repo,
3636 &queue,
3637 &questions,
3638 home,
3639 &queued,
3640 &stalled,
3641 &finished,
3642 opts.max_attempts,
3643 )
3644 .await;
3645 let temporary = path.with_extension("json.tmp");
3646 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3647 std::fs::rename(temporary, path)?;
3648 }
3649 }
3650 "fetch" => {
3651 let cfg = prepare(&opts.repo, opts)?;
3652 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3653 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3654 tracing::debug!("fetch origins: {outcome:?}");
3655 }
3656 }
3657 "cache" => {
3658 if task_jobs(home)?.is_empty() {
3659 let mut checked = None;
3660 maybe_prune_cache_between_runs(
3661 &opts.repo,
3662 opts,
3663 home,
3664 &Stop::new(),
3665 &mut checked,
3666 Timestamp::now(),
3667 )
3668 .await;
3669 }
3670 }
3671 "disk-pressure" => {
3672 if let Ok(cfg) = prepare(&opts.repo, opts) {
3673 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3674 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3675 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3676 }
3677 for current in current_work(home, Timestamp::now()) {
3678 if let Ok(state) = RunState::load_under(¤t.run, home)
3679 && let Some(reason) = disk_gate(&state.repo, &state.config)
3680 {
3681 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3682 job.key.strip_prefix("task:") == Some(current.task.as_str())
3683 }) {
3684 request_task_park(
3685 home,
3686 &job,
3687 crate::run::ParkCause::Interrupt {
3688 reason: reason.clone(),
3689 },
3690 )?;
3691 }
3692 notices::raise_in(
3693 home,
3694 Notice::warn(
3695 "disk:pressure",
3696 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3697 ),
3698 );
3699 }
3700 }
3701 }
3702 }
3703 "housekeeping" => {
3704 if task_jobs(home)?.is_empty() {
3705 if let Ok(cfg) = prepare(&opts.repo, opts) {
3706 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3707 }
3708 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3709 resweep_superseded_attempts(&queue, home);
3710 triage_held(&queue, home, opts).await;
3711 }
3712 }
3713 operation => bail!("unknown daemon service {operation}"),
3714 }
3715 Ok(())
3716}
3717
3718fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3722 let key = format!("task:{}", request.task);
3723 let payload = serde_json::to_value(request)?;
3724 if crate::worker::active(home)?
3725 .iter()
3726 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3727 {
3728 tracing::warn!(
3729 "task {} acquired a competing worker reservation: {error:#}",
3730 crate::run::short_of(&request.task)
3731 );
3732 return Ok(());
3733 }
3734 tracing::error!("task worker startup stopped dispatch: {error:#}");
3735 notices::raise_in(
3736 home,
3737 Notice::error(
3738 "loop:worker-startup",
3739 format!("Task {} worker could not be started or acknowledged. Scheduler dispatch stopped; already reserved workers may still complete. Inspect the local execution log and reservation worker.log for startup details.", request.task),
3742 ).link(Link::Task { id: request.task.clone() }),
3743 );
3744 Err(error).with_context(|| {
3745 format!(
3746 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3747 crate::run::short_of(&request.task)
3748 )
3749 })
3750}
3751
3752async fn poll(
3753 opts: &Opts,
3754 queue: &Queue,
3755 status: &Arc<Mutex<Status>>,
3756 home: &Path,
3757 worktrees_root: &Path,
3758 stop: &Stop,
3759 limits: DispatchLimits,
3760) -> Result<()> {
3761 let mut attempted = Vec::new();
3762 let mut settling_once_services = false;
3763 let interrupt_path = home.join("scheduler-interrupt.json");
3764 let mut interrupt = match std::fs::read(&interrupt_path) {
3765 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3766 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3767 Err(error) => return Err(error.into()),
3768 };
3769 let mut previous = std::collections::BTreeSet::<String>::new();
3770 while !stop.stopped() {
3771 let jobs: Vec<_> = crate::worker::active(home)?
3772 .into_iter()
3773 .filter(|job| job.kind == "task")
3774 .collect();
3775 let requests: Vec<_> = jobs
3776 .iter()
3777 .map(|job| {
3778 serde_json::from_value::<TaskWorker>(job.payload.clone())
3779 .with_context(|| format!("read live task worker {}", job.id))
3780 })
3781 .collect::<Result<_>>()?;
3782 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3783 let owned: std::collections::BTreeSet<_> = requests
3784 .iter()
3785 .filter(|r| !r.standalone)
3786 .map(|r| r.task.clone())
3787 .collect();
3788 let current: Vec<_> = requests
3789 .iter()
3790 .zip(&jobs)
3791 .filter(|(request, _)| !request.standalone)
3792 .map(|(request, job)| Current {
3793 worker: Some(job.id.clone()),
3794 task: request.task.clone(),
3795 run: queue
3796 .get(&request.task)
3797 .ok()
3798 .and_then(|task| task.runs.last().cloned())
3799 .unwrap_or_default(),
3800 })
3801 .collect();
3802 {
3803 let mut snapshot = lock(status);
3804 snapshot.polls += 1;
3805 snapshot.completed += previous.difference(&owned).count();
3806 snapshot.current = current;
3807 snapshot.idle = owned.is_empty();
3808 }
3809 previous = owned.clone();
3810 stop.busy.store(owned.len(), Ordering::SeqCst);
3811
3812 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3815 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3816 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3817 let mut permits = Vec::new();
3818 sweep_stale_claims(queue, STALE_CLAIM);
3819 reclaim_orphaned_running(queue, opts.max_attempts, &live);
3820 reclaim_abandoned_runs(home, Timestamp::now());
3821 let questions = Questions::at(home.join("questions"));
3822
3823 crate::task_chat::sweep(
3826 queue,
3827 &crate::talk::Talks::at(home.join("talks")),
3828 &questions,
3829 home,
3830 );
3831 repair_choice_offers(&questions);
3832 resolve_blockers(queue, &questions);
3833 apply_task_choice_actions(queue, &questions, home);
3834 triage::apply_answers(queue, &questions);
3835 reconcile_task_questions(queue, &questions);
3836 let talks = crate::talk::Talks::at(home.join("talks"));
3837 crate::chat_notify::sweep(queue, &talks, home);
3838 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3839 crate::chat_watch::sweep(home, &talks);
3840 let mut turns = tokio::task::JoinSet::new();
3841 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3842 while turns.join_next().await.is_some() {}
3844
3845 crate::consult::start_services(
3846 home,
3847 &opts.repo,
3848 limits.recovery_cfg.as_ref(),
3849 opts.config.as_deref(),
3850 )
3851 .await?;
3852 for operation in [
3853 "conductor",
3854 "maintenance",
3855 "housekeeping",
3856 "disk-pressure",
3857 "cache",
3858 "fetch",
3859 ] {
3860 if settling_once_services {
3864 break;
3865 }
3866 start_service(
3867 home,
3868 opts,
3869 queue,
3870 worktrees_root,
3871 operation,
3872 limits.recovery_cfg.as_ref(),
3873 !live.is_empty(),
3874 )
3875 .await?;
3876 }
3877 let latest = crate::worker::active(home)?;
3878 if latest.iter().any(|job| job.key == "service:daemon-cache")
3879 || latest
3880 .iter()
3881 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3882 {
3883 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3884 continue;
3885 }
3886 let candidates: Vec<Task> = runnable(queue)
3887 .into_iter()
3888 .filter(|task| !live.contains(&task.id))
3889 .filter(|task| !opts.once || !attempted.contains(&task.id))
3890 .collect();
3891 let in_flight: Vec<_> = owned.iter().cloned().collect();
3892 let prior_interrupt = std::mem::discriminant(&interrupt);
3893 interrupt = advance_interrupt_tick(
3894 limits.pause_for_interrupts,
3895 interrupt,
3896 &in_flight,
3897 &candidates,
3898 );
3899 if prior_interrupt != std::mem::discriminant(&interrupt) {
3902 let temporary = interrupt_path.with_extension("json.tmp");
3903 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3904 std::fs::rename(temporary, &interrupt_path)?;
3905 }
3906 if let Interrupt::Parking {
3907 parked,
3908 interrupt_task,
3909 } = &interrupt
3910 {
3911 for job in jobs.iter().filter(|job| {
3912 parked
3913 .iter()
3914 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3915 }) {
3916 if crate::worker::control(home, &job.key)?.is_none() {
3917 request_task_park(
3918 home,
3919 job,
3920 crate::run::ParkCause::Interrupt {
3921 reason: format!(
3922 "task {} asked to run first",
3923 crate::run::short_of(interrupt_task)
3924 ),
3925 },
3926 )?;
3927 }
3928 }
3929 }
3930 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3931 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3932 let mut started = false;
3933 let mut resync = false;
3934 for candidate in candidates {
3935 if stop.stopped() {
3936 break;
3937 }
3938 let Some(DispatchClaim {
3939 task,
3940 claim,
3941 permit,
3942 }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3943 else {
3944 continue;
3945 };
3946 if crate::worker::active(home)?
3947 .iter()
3948 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3949 {
3950 drop(claim);
3951 resync = true;
3952 break;
3953 }
3954 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3955 let request = TaskWorker {
3956 opts: opts.absolute()?,
3957 queue: std::path::absolute(queue.root())?,
3958 task: task.id.clone(),
3959 lane,
3960 standalone: false,
3961 };
3962 if let Err(error) = crate::worker::spawn(
3965 home,
3966 "task",
3967 &format!("task:{}", task.id),
3968 serde_json::to_value(&request)?,
3969 )
3970 .await
3971 {
3972 task_worker_spawn_error(home, &request, error)?;
3973 drop(claim);
3974 resync = true;
3975 break;
3976 }
3977 drop(claim);
3978 permits.extend(permit);
3979 attempted.push(task.id);
3980 started = true;
3981 }
3982 if started || resync {
3983 continue;
3984 }
3985 if owned.is_empty() && opts.once {
3986 settling_once_services = true;
3987 if crate::worker::active(home)?.iter().any(|job| {
3991 job.kind == "daemon-service"
3992 && matches!(
3993 job.key.as_str(),
3994 "service:daemon-housekeeping"
3995 | "service:daemon-conductor"
3996 | "service:daemon-maintenance"
3997 )
3998 }) {
3999 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4000 continue;
4001 }
4002 break;
4003 }
4004 stop.idle(if live.is_empty() {
4005 opts.poll
4006 } else {
4007 RECHECK_WHILE_BUSY.min(opts.poll)
4008 })
4009 .await;
4010 }
4011 stop.busy.store(0, Ordering::SeqCst);
4014 Ok(())
4015}
4016
4017async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4021 let busy = |error: &anyhow::Error| {
4022 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4023 error.kind() == std::io::ErrorKind::WouldBlock
4024 || cfg!(windows) && error.raw_os_error() == Some(33)
4025 })
4026 };
4027 match crate::pr_head::owner_lock(home, id) {
4028 Ok(lock) => return Ok(lock),
4029 Err(error) if busy(&error) => {}
4030 Err(error) => return Err(error),
4031 }
4032 let wait = RunState::load_under(id, home)?
4033 .config
4034 .graph
4035 .timeout_resource_wait;
4036 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4037}
4038
4039async fn public_resume_owner(
4043 home: &Path,
4044 runs: &[String],
4045 repo: &Path,
4046) -> Result<Option<RunState>> {
4047 let mut owner = None;
4048 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4049 let _lock = resume_owner_lock(home, id).await?;
4050 let state = RunState::load_under(id, home)?;
4051 if state.released()
4052 || state.retired_to.is_some()
4053 || state.pr_taken_over_by.is_some()
4054 || !crate::handover::landing_checkpoint(&state)
4055 {
4056 continue;
4057 }
4058 anyhow::ensure!(
4059 crate::git::toplevel(&state.repo).await?.canonicalize()?
4060 == crate::git::toplevel(repo).await?.canonicalize()?,
4061 "public owner repository differs; inspect run lineage"
4062 );
4063 anyhow::ensure!(
4064 owner.is_none(),
4065 "multiple retained public owners; inspect run lineage"
4066 );
4067 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4068 anyhow::bail!(reason.diagnostic(&state));
4069 }
4070 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4071 anyhow::ensure!(
4072 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4073 "public owner's driver is live or unknown; wait before retrying"
4074 );
4075 owner = Some(state);
4076 }
4077 Ok(owner)
4078}
4079
4080async fn attempt(
4086 opts: &Opts,
4087 queue: &Queue,
4088 status: &Arc<Mutex<Status>>,
4089 stop: &Stop,
4090 interrupt_pause: crate::graph::Pause,
4091 task: &mut Task,
4092) -> Vec<QuotaLoss> {
4093 let repo = repo_for(task, &opts.repo);
4094 tracing::info!(
4095 "task {} — {} (repo {})",
4096 task.short(),
4097 task.title,
4098 repo.display()
4099 );
4100
4101 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4102 Ok(owner) => owner,
4103 Err(e) => {
4104 task.hold_machine(Some(format!(
4105 "Cannot verify existing public owner: {e:#}; no attempt started."
4106 )));
4107 record(queue, task);
4108 return Vec::new();
4109 }
4110 };
4111 let resume_runs = public_owner
4112 .as_ref()
4113 .map(|s| vec![s.id.clone()])
4114 .unwrap_or_else(|| task.runs.clone());
4115
4116 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4120 && previous
4121 .merge_decision
4122 .as_ref()
4123 .is_some_and(|decision| !decision.closed)
4124 && previous.status != RunStatus::Landing
4125 && !crate::merge_decision::resumable_hold(&previous)
4126 {
4127 task.hold_unrequested_retry(Some(format!("The existing owner stop decision remains held. Inspect run {} and its PR; request an explicit fresh review/decision before further work. No replacement or merge was started.", previous.id)));
4128 record(queue, task);
4129 return Vec::new();
4130 }
4131 let stop_owner = resume_runs
4132 .last()
4133 .and_then(|id| RunState::load(id).ok())
4134 .filter(|state| {
4135 crate::merge_decision::resumable_hold(state)
4136 || state.status == RunStatus::Landing
4137 && state.land_approval.as_ref().is_some_and(|binding| {
4138 Questions::open().get(&binding.question).is_ok_and(|q| {
4139 q.run == state.id
4140 && q.resolution()
4141 .as_deref()
4142 .is_some_and(crate::merge_decision::stops)
4143 })
4144 })
4145 });
4146 if let Some(owner) = stop_owner {
4147 let mut runner = match Runner::resume(&owner.id) {
4148 Ok(runner) => runner,
4149 Err(e) => {
4150 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4151 record(queue, task);
4152 return Vec::new();
4153 }
4154 };
4155 runner.on_pause(stop.pause());
4156 runner.watch_interrupt(interrupt_pause);
4157 let quota_before = runner.state.quota.clone();
4158 task.start(owner.id.clone());
4159 record(queue, task);
4160 lock(status).current.push(Current {
4161 worker: None,
4162 task: task.id.clone(),
4163 run: owner.id,
4164 });
4165 runner.state.next_pass_task_entry = true;
4166 let result = runner.execute().await;
4167 return finish_attempt(
4168 opts.max_attempts,
4169 queue,
4170 task,
4171 &runner.state,
4172 "a_before,
4173 result,
4174 );
4175 }
4176
4177 if let Some(owner) = &public_owner
4178 && (task.fresh_start || !may_resume_run(owner, task))
4179 {
4180 task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. No attempt started.", owner.id)));
4181 record(queue, task);
4182 return Vec::new();
4183 }
4184
4185 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4186 && !task.fresh_start
4187 && task.review_branch.is_none()
4188 && task.pr_recovery.is_none()
4189 {
4190 let authorized = if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4193 let home = queue.root().parent().expect("queue has a home");
4194 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4195 Ok(()) => true,
4196 Err(error) => {
4197 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4198 false
4199 }
4200 }
4201 } else {
4202 false
4203 };
4204 if !authorized {
4205 task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
4206 task.base_sync_notice(&held);
4208 task.resume_override = None;
4209 record(queue, task);
4210 return Vec::new();
4211 }
4212 }
4213 let unfinished = (!task.fresh_start)
4214 .then(|| unfinished_run(&resume_runs, task.short()))
4215 .flatten()
4216 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4217 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4218 if !task.fresh_start
4219 && task.pr_recovery.is_none()
4220 && task.review_branch.is_none()
4221 && task.resume_override.is_none()
4222 && previous
4223 .as_ref()
4224 .is_some_and(|run| run.retired_to.is_some())
4225 && unfinished.is_none()
4226 {
4227 task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
4228 record(queue, task);
4229 return Vec::new();
4230 }
4231
4232 let saved_recovery = previous.as_ref().filter(|run| {
4233 task.replacement.is_none()
4234 && task.pr_recovery.as_ref().is_some_and(|selected| {
4235 selected.check_task(&task.id, &task.instruction).is_ok()
4236 && selected_starter(selected, Some(run), unfinished.as_deref())
4237 == Starter::Resume(run.id.clone())
4238 })
4239 });
4240
4241 let explicit = match &task.overrides {
4245 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4246 Some(_) => opts.config.as_deref(),
4247 None => opts.config.as_deref(),
4248 };
4249 let (mut config, layers) = if let Some(run) = saved_recovery {
4250 let mut saved = run.clone();
4253 if let Err(e) = saved.configure_recovery_resume() {
4254 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4255 record(queue, task);
4256 return Vec::new();
4257 }
4258 (saved.config, Vec::new())
4259 } else {
4260 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4261 Ok(loaded) => loaded,
4262 Err(e) => {
4263 let reason = format!("[config] {e:#}");
4264 record_config_failure(task, &e);
4265 task.last_error = Some(reason.clone());
4266 task.hold_machine(Some(reason));
4267 record(queue, task);
4268 return Vec::new();
4269 }
4270 };
4271 if let Err(e) = apply_options(&mut config, opts, task) {
4272 task.hold_manual(Some(format!(
4273 "[config] {e:#}; correct the merge override before releasing the task"
4274 )));
4275 record(queue, task);
4276 return Vec::new();
4277 }
4278 if let Some(selected) = &task.pr_recovery
4279 && let Err(e) = selected.configure(&mut config)
4280 {
4281 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4282 record(queue, task);
4283 return Vec::new();
4284 }
4285 (config, layers)
4286 };
4287 let config_evidence = crate::pr_recovery::ConfigEvidence {
4288 layers,
4289 overrides: task.overrides.clone(),
4290 daemon_merge: task
4291 .overrides
4292 .as_ref()
4293 .is_none_or(|o| o.inherit_daemon_options)
4294 .then(|| opts.merge.clone())
4295 .flatten(),
4296 };
4297 apply_task_implementers(&mut config, task);
4298 if let Some(replacement) = &task.replacement {
4299 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4300 old.liveness(false) == Liveness::Dead
4301 && old.merge_decision.as_ref().is_some_and(|d| {
4302 d.closed
4303 && d.question == replacement.question
4304 && d.replacement_run.as_ref().is_none_or(|run| {
4305 task.runs.last() == Some(run)
4306 && RunState::load(run).is_ok_and(|current| {
4307 current.replaces.as_ref().is_some_and(|pin| {
4308 pin.question == replacement.question
4309 && pin.agent == replacement.agent
4310 })
4311 })
4312 })
4313 })
4314 });
4315 if !safe {
4316 task.hold_manual(Some("Replacement ownership cannot be confirmed, or a replacement run was already minted before a crash. Inspect the task and its linked runs; no second replacement was started.".into()));
4317 record(queue, task);
4318 return Vec::new();
4319 }
4320 match config.agent(&replacement.agent) {
4321 Ok(agent) if crate::agent::installed(agent) => {}
4322 _ => {
4323 task.hold_manual(Some(format!("Selected implementer `{}` is unavailable or no longer configured. No substitute was dispatched. Restore it and explicitly release the task.", replacement.agent)));
4324 record(queue, task);
4325 return Vec::new();
4326 }
4327 }
4328 config.graph.implementers = 1;
4329 config.graph.land_approval = true;
4330 config.merge.mode = MergeMode::Pr;
4331 config.graph.selected_implementer = Some(replacement.agent.clone());
4332 }
4333 let p = phrases(&config.graph.language);
4334 let start_failed = p.could_not_start;
4335 if let Ok(base) =
4340 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4341 .await
4342 && let Ok(head) =
4343 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4344 {
4345 let mut inputs = crate::queue::recovery_inputs(&task.sources);
4346 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4347 let source = crate::git::rev_parse(&repo, branch)
4348 .await
4349 .unwrap_or_default();
4350 inputs.push_str(&format!(";review:{branch}:{source}"));
4351 }
4352 if let Some(reason) = task
4353 .recovery_exhausted(
4354 &head,
4355 &inputs,
4356 task.attempt_limit
4357 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4358 )
4359 .filter(|_| {
4360 !task.repair_grants.last().is_some_and(|receipt| {
4361 RunState::load(&receipt.request.run)
4362 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4363 })
4364 })
4365 {
4366 task.hold_unrequested_retry(Some(reason));
4367 record(queue, task);
4368 return Vec::new();
4369 }
4370 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4371 }
4372
4373 if let Some(reason) = disk_gate(&repo, &config) {
4381 task.notice_cause("disk-space", None, None);
4382 task.last_error = Some(reason.clone());
4383 task.hold_machine(Some(reason.clone()));
4384 record(queue, task);
4385 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4386 notices::raise(
4389 Notice::warn(
4390 &format!("disk:{}", repo.display()),
4391 format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4392 )
4393 .link(Link::Task {
4394 id: task.id.clone(),
4395 }),
4396 );
4397 return Vec::new();
4398 }
4399
4400 let review_branch = take_review_branch(task, previous.as_ref());
4425 let branch_exists = match &review_branch {
4426 Some(branch) => crate::git::branch_exists(&repo, branch)
4427 .await
4428 .unwrap_or(false),
4429 None => false,
4430 };
4431 let proposed = review_retry_starter(
4435 task,
4436 previous.as_ref(),
4437 review_branch.as_deref(),
4438 branch_exists,
4439 unfinished.as_deref(),
4440 );
4441 let retry_selected = task.replacement.is_some()
4442 && task.resumption.is_some()
4443 && !task.fresh_start
4444 && previous.as_ref().is_some_and(|run| {
4445 run.replaces.is_some()
4446 && ((run.status == RunStatus::Failed && run.viable().is_empty())
4447 || (run.status == RunStatus::Blocked && run.tally.is_none()))
4448 });
4449 let stop_pin = task
4450 .resume_override
4451 .as_ref()
4452 .filter(|pin| {
4453 Questions::open().get(&pin.question_id).is_ok_and(|q| {
4454 q.node == land::APPROVAL_NODE
4455 && q.resolution()
4456 .as_deref()
4457 .is_some_and(crate::merge_decision::stops)
4458 })
4459 })
4460 .and_then(|pin| pin.pinned_run.clone());
4461 let granted_run = task.repair_grants.last().and_then(|receipt| {
4462 let state = RunState::load(&receipt.request.run).ok()?;
4463 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4464 });
4465 let starter = if let Some(run) = granted_run {
4466 Starter::Resume(run)
4467 } else if let Some(owner) = &public_owner {
4468 Starter::Resume(owner.id.clone())
4469 } else if let Some(run) = stop_pin {
4470 Starter::Resume(run)
4473 } else if retry_selected {
4474 Starter::Resume(previous.as_ref().unwrap().id.clone())
4475 } else if let Some(selected) = &task.pr_recovery {
4476 if selected.check_task(&task.id, &task.instruction).is_ok() {
4477 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4478 } else {
4479 Starter::Review(selected.branch.clone())
4480 }
4481 } else {
4482 starter_with_implementers(task, previous.as_ref(), proposed)
4483 };
4484 if let Some(pin) = &task.resume_override
4487 && let Some(run) = &pin.pinned_run
4488 && starter != Starter::Resume(run.clone())
4489 {
4490 let run = run.clone();
4491 task.notice_cause("resume-owner", Some(&run), None);
4492 task.hold_machine(Some(format!(
4493 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4494 task.id
4495 )));
4496 record(queue, task);
4497 return Vec::new();
4498 }
4499 if task.replacement.is_some()
4500 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4501 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4502 {
4503 task.hold_manual(Some("The selected replacement already has an attempt. It cannot be resumed safely; inspect its saved pin and restore the existing run. No additional replacement was started.".into()));
4504 record(queue, task);
4505 return Vec::new();
4506 }
4507 if let Some(reason) = retained_attempt_hold(
4508 task,
4509 &starter,
4510 config.disk.retained_attempt_limit,
4511 RunState::load,
4512 ) {
4513 if let Starter::Review(branch) = &starter {
4516 task.review_branch = Some(branch.clone());
4517 }
4518 task.hold_unrequested_retry(Some(reason));
4519 record(queue, task);
4520 return Vec::new();
4521 }
4522 let attachments = match task_attachments(queue, task) {
4527 Ok(a) => a,
4528 Err(e) => {
4529 task.attempts += 1;
4530 task.fail_startup_target(
4531 "startup-attachments",
4532 e.name.clone(),
4533 format!("{start_failed}{e:#}"),
4534 opts.max_attempts,
4535 );
4536 record(queue, task);
4537 return Vec::new();
4538 }
4539 };
4540 let startup_pause = stop.pause();
4541 let startup_interrupt = interrupt_pause.clone();
4542 let wait = crate::repo_lock::WaitPolicy::new(
4543 Duration::from_secs(config.graph.timeout_resource_wait),
4544 move || startup_pause.parked() || startup_interrupt.parked(),
4545 );
4546 let started = wait.scope(Box::pin(async { match &starter {
4549 Starter::Review(_) if task.pr_recovery.is_some() => {
4550 let selected = task.pr_recovery.clone().expect("selected recovery");
4551 match selected.check_task(&task.id, &task.instruction) {
4552 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4553 .await
4554 .map(|mut r| {
4555 r.state.attachments = attachments.clone();
4556 r
4557 }),
4558 Err(e) => Err(e),
4559 }
4560 }
4561 Starter::Review(branch) => {
4562 tracing::info!(
4563 "task {} reopens `{branch}` as a review-only pass",
4564 task.short()
4565 );
4566 let takeover = crate::handover::Takeover {
4569 earlier: task.earlier_attempts().to_vec(),
4570 home: crate::run::home(),
4571 choice: take_divergence_answer(branch, &config.merge.remote, task),
4572 task_instruction: Some(instruction_for(task)),
4573 };
4574 Runner::review_taking_over(
4575 &repo,
4576 branch,
4577 config,
4578 Some(takeover),
4579 crate::run::Origin::queue(&task.id),
4580 )
4581 .await
4582 }
4583 Starter::Resume(id) => {
4584 tracing::info!("resuming run {id} rather than competing again");
4585 Runner::resume(id).and_then(|mut r| {
4586 if retry_selected {
4587 for candidate in &mut r.state.candidates {
4590 candidate.failed = None;
4591 candidate.empty = false;
4592 candidate.commits = 0;
4593 }
4594 r.state.status = RunStatus::Implementing;
4595 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4596 }
4597 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4598 r.state.sources = task.sources.clone();
4599 }
4600 if r.state.prep_failure.is_some() {
4601 let approval = task
4602 .resumption
4603 .as_ref()
4604 .context("preparation retry requires an explicit task release")?;
4605 r.retry_preparation(approval.at)?;
4606 }
4607 if let Some(instruction) =
4608 prepare_instruction(&starter, Some(&r.state.instruction), task)
4609 {
4610 r.state.instruction = instruction;
4611 }
4612 r.state.attachments = attachments.clone();
4613 if task.replacement.is_some() {
4614 r.state.config.merge.mode = MergeMode::Pr;
4615 r.state.config.graph.land_approval = true;
4616 }
4617 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4621 .overrides
4622 .as_ref()
4623 .and_then(|o| o.merge.as_deref())
4624 .and_then(|m| merge_mode(m).ok())
4625 {
4626 r.state.config.merge.mode = mode;
4627 }
4628 Ok(r)
4629 })
4630 }
4631 Starter::Start => {
4632 if let Some(branch) = &review_branch {
4633 tracing::warn!(
4634 "conductor chose review for task {} but branch `{branch}` no longer \
4635 exists; requeuing as a fresh competition instead",
4636 task.short()
4637 );
4638 }
4639 let instruction = prepare_instruction(&starter, None, task)
4640 .unwrap_or_else(|| task.instruction.clone());
4641 Runner::start_naming(
4642 &repo,
4643 instruction,
4644 &task.title,
4645 config,
4646 crate::run::Origin::queue(&task.id),
4647 )
4648 .await
4649 .map(|mut r| {
4650 r.state.attachments = attachments.clone();
4651 r.state.sources = task.sources.clone();
4652 r
4653 })
4654 }
4655 }})).await;
4656 if let Err(error) = &started
4657 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4658 {
4659 task.record_startup_failure(failure.clone());
4660 }
4661 let mut runner = match started {
4662 Ok(r) => r,
4663 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4664 task.last_error = Some(e.to_string());
4665 if stop.parking() || interrupt_pause.parked() {
4666 let attempts = task.attempts;
4667 task.park(e.to_string());
4668 task.attempts = attempts;
4670 } else {
4671 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4672 }
4673 record(queue, task);
4674 return Vec::new();
4675 }
4676 Err(e) if task.pr_recovery.is_some() => {
4680 task.startup_notice_cause("startup-public-head");
4681 task.attempts += 1;
4682 task.last_error = Some(format!("{start_failed}{e:#}"));
4683 task.hold_unrequested_retry(Some(format!(
4684 "Selected public-head recovery could not start: {e:#}. Correct the cause and use `magi task recover-pr` with the approved public head; automatic recovery is stopped."
4685 )));
4686 record(queue, task);
4687 return Vec::new();
4688 }
4689 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4690 let detail = match e.downcast_ref::<crate::handover::Refused>() {
4691 Some(r) => (p.handover_refused)(r),
4692 None => format!("{e:#}"),
4693 };
4694 task.startup_notice_cause("startup-handover");
4695 let reason = format!("{start_failed}{detail}");
4696 task.last_error = Some(reason.clone());
4697 let branch = match &starter {
4700 Starter::Review(branch) => Some(branch.clone()),
4701 _ => None,
4702 };
4703 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4707 record(queue, task);
4708 tracing::warn!(
4709 "holding {} for a branch it cannot take over: {e:#}",
4710 task.short()
4711 );
4712 return Vec::new();
4713 }
4714 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4719 let d = e
4720 .downcast_ref::<crate::reconcile::Diverged>()
4721 .expect("checked by the guard");
4722 let mut q = ask::Question::new(
4723 task.id.clone(),
4724 crate::reconcile::NODE.to_owned(),
4725 crate::reconcile::SEAT.to_owned(),
4726 d.summary(),
4727 d.detail(),
4728 d.choices(),
4729 );
4730 match Questions::open().put(&mut q) {
4731 Ok(()) => {
4732 task.last_error = Some(format!("{e:#}"));
4733 task.review_branch = Some(d.branch.clone());
4736 task.review_instruction = Some(task.instruction.clone());
4737 task.block(vec![q.id.clone()], Some(d.summary()));
4738 }
4739 Err(put) => {
4740 tracing::warn!("could not file the divergence question: {put:#}");
4741 task.attempts += 1;
4742 task.fail_startup(
4743 "startup-question-store",
4744 format!("{start_failed}{e:#}"),
4745 opts.max_attempts,
4746 );
4747 }
4748 }
4749 record(queue, task);
4750 return Vec::new();
4751 }
4752 Err(e) => {
4753 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4759 && let Starter::Review(branch) = &starter
4760 {
4761 task.review_branch = Some(branch.clone());
4762 task.review_instruction = Some(task.instruction.clone());
4763 task.last_error = Some(format!("{start_failed}{e:#}"));
4764 task.status = crate::queue::TaskStatus::Failed;
4765 record(queue, task);
4766 return Vec::new();
4767 }
4768 task.attempts += 1;
4769 task.last_error = Some(format!("{start_failed}{e:#}"));
4770 task.startup_notice_cause("startup-source");
4771 task.hold_unrequested_retry(Some(format!(
4772 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4773 )));
4774 record(queue, task);
4775 return Vec::new();
4776 }
4777 };
4778 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4779 runner.state.recovery_config = Some(config_evidence);
4780 }
4781 if let Some(replacement) = &task.replacement {
4782 if matches!(starter, Starter::Start) {
4783 runner.state.instruction.push_str(&format!(
4784 "\n\n# Replacement review context\n{}",
4785 replacement.context
4786 ));
4787 }
4788 runner.state.replaces = Some(replacement.clone());
4789 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4790 if let Ok(mut old) = RunState::load(&replacement.run)
4791 && let Some(d) = &mut old.merge_decision
4792 {
4793 d.replacement_run = Some(runner.state.id.clone());
4794 old.event(
4795 "replacement",
4796 format!(
4797 "replacement run {} owns the next attempt; old PR remains closed",
4798 runner.state.id
4799 ),
4800 );
4801 if let Err(e) = old.save() {
4802 let error = runner.fail_startup("replacement-history", e);
4803 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4804 task.record_startup_failure(failure.clone());
4805 }
4806 task.hold_manual(Some(format!(
4807 "Could not link replacement history: {error:#}; no agents dispatched"
4808 )));
4809 record(queue, task);
4810 return Vec::new();
4811 }
4812 }
4813 }
4814 runner.state.task_instruction = Some(task.instruction.clone());
4815 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4818 if runner.state.origin_chat.is_none() {
4819 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4820 }
4821 runner.on_pause(stop.pause());
4823 runner.watch_interrupt(interrupt_pause);
4827
4828 let run = runner.state.id.clone();
4831 let before_start = task.clone();
4832 task.start(run.clone());
4833 if let Err(error) = queue.put(task) {
4834 *task = before_start;
4835 let error = runner.fail_startup("task-start", error);
4836 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4837 task.record_startup_failure(failure.clone());
4838 }
4839 task.hold_manual(Some(format!(
4840 "Could not persist task start; no agents dispatched: {error:#}"
4841 )));
4842 record(queue, task);
4843 return Vec::new();
4844 }
4845 lock(status).current.push(Current {
4846 worker: None,
4847 task: task.id.clone(),
4848 run,
4849 });
4850
4851 let quota_before = runner.state.quota.clone();
4854 runner.state.next_pass_task_entry = true;
4855 let result = runner.execute().await;
4856 finish_attempt(
4857 opts.max_attempts,
4858 queue,
4859 task,
4860 &runner.state,
4861 "a_before,
4862 result,
4863 )
4864}
4865
4866pub fn finish_attempt(
4871 max_attempts: usize,
4872 queue: &Queue,
4873 task: &mut Task,
4874 state: &RunState,
4875 quota_before: &[QuotaLoss],
4876 result: Result<()>,
4877) -> Vec<QuotaLoss> {
4878 let detail = match result {
4879 Ok(()) => describe(state),
4880 Err(e) => format!("{e:#}"),
4881 };
4882 let fresh = losses_this_attempt(quota_before, &state.quota);
4883 let verdict = Verdict {
4884 status: state.status,
4885 left_pr: state.pr.is_some(),
4888 quota_hit: !fresh.is_empty(),
4894 parked: state.parked,
4898 no_viable_candidates: state.viable().is_empty(),
4901 };
4902 if let Some(replacement) = &state.replaces
4903 && let Some(pr) = &state.pr
4904 && let Ok(mut old) = RunState::load(&replacement.run)
4905 && let Some(d) = &mut old.merge_decision
4906 {
4907 d.replacement_pr = Some(pr.url.clone());
4908 let _ = old.save();
4909 }
4910 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4911 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4912 task.hold_unrequested_retry(Some(format!(
4913 "Candidate setup failed: {detail}. Correct the explicit sources with `magi task sources {}` (README, \"Use\": implementation imports), or select a complete implementation with `magi task recover-pr`, then explicitly release the task.",
4914 task.short()
4915 )));
4916 }
4917 if task.status == TaskStatus::Done {
4918 supersede_prior_runs(task, &crate::run::home());
4919 }
4920 record(queue, task);
4921 tracing::info!(
4922 "task {} is {} after run {} ({})",
4923 task.short(),
4924 task.status.as_str(),
4925 state.short(),
4926 label(state.status)
4927 );
4928 fresh
4929}
4930
4931pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4935 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4938 && !awaiting_resume_with(task, RunState::load)
4939 && withheld_text_wait(task).is_none()
4943 && !(task.fresh_start && task.replacement.is_some())
4944 {
4945 let why = task.last_error.clone().map_or_else(
4946 || "the run did not finish".to_owned(),
4947 |e| format!("the run did not finish: {e}"),
4948 );
4949 task.hold_unrequested_retry(Some(format!(
4950 "{why}. It was started by hand, so it is not retried \
4951 automatically; `magi task release` retries it."
4952 )));
4953 record(queue, task);
4954 }
4955}
4956
4957#[must_use]
4961pub fn loop_would_resume(run: &str) -> bool {
4962 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4963}
4964
4965#[must_use]
4975pub fn foreign_loop(
4976 reading: Option<&Reading>,
4977 now: Timestamp,
4978 own_pid: u32,
4979) -> Option<Option<u32>> {
4980 let reading = reading.filter(|r| r.running(now))?;
4981 match reading.pid {
4982 Some(pid) if pid == own_pid => None,
4983 pid => Some(pid),
4984 }
4985}
4986
4987fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4988 reading.worker_protocol != Some(1)
4989 && (foreign_loop(Some(reading), now, own_pid).is_some()
4990 || reading
4991 .pid
4992 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4993}
4994
4995pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5006 run_claimed_until(opts, queue, task, &Stop::new()).await;
5007}
5008
5009async fn run_claimed_until(
5010 opts: &Opts,
5011 queue: &Queue,
5012 task: &mut Task,
5013 stop: &Stop,
5014) -> Vec<QuotaLoss> {
5015 let status = Arc::new(Mutex::new(Status::new()));
5016 let mut quota = Box::pin(attempt(
5019 opts,
5020 queue,
5021 &status,
5022 stop,
5023 crate::graph::Pause::new(),
5024 task,
5025 ))
5026 .await;
5027 let mut resumes = 0;
5036 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5037 let Some(timeout) = withheld_text_wait(task) else {
5038 break;
5039 };
5040 eprintln!(
5041 "waiting for the owner's answer on a withheld pull request text \
5042 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5043 );
5044 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5047 let ready = loop {
5048 match land_resume_state(task) {
5049 LandResume::StillWaiting
5050 if !stop.parking() && std::time::Instant::now() < limit =>
5051 {
5052 tokio::time::sleep(WITHHELD_POLL).await;
5053 }
5054 LandResume::Ready => break true,
5055 _ => break false,
5056 }
5057 };
5058 if !ready || stop.parking() {
5059 break;
5060 }
5061 resumes += 1;
5062 quota.extend(
5063 Box::pin(attempt(
5064 opts,
5065 queue,
5066 &status,
5067 stop,
5068 crate::graph::Pause::new(),
5069 task,
5070 ))
5071 .await,
5072 );
5073 }
5074 hold_if_runnable(queue, task);
5075 quota
5076}
5077
5078const MAX_WITHHELD_RESUMES: u32 = 3;
5081
5082const WITHHELD_POLL: Duration = Duration::from_secs(15);
5084
5085fn withheld_text_wait(task: &Task) -> Option<u64> {
5088 let id = task.runs.last()?;
5089 let s = RunState::load(id).ok()?;
5090 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5091 .then_some(s.config.graph.answer_timeout)
5092}
5093
5094fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5104 after
5105 .iter()
5106 .filter(|q| !before.contains(q))
5107 .cloned()
5108 .collect()
5109}
5110
5111fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5114 let quota: Vec<_> = quota
5115 .iter()
5116 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5117 .collect();
5118 if quota.is_empty() {
5119 return None;
5120 }
5121 let with_hint = quota.iter().find(|q| q.reset.is_some());
5122 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5123 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5124 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5125 Some(
5126 now.checked_add(jiff::SignedDuration::from_secs(secs))
5127 .unwrap_or(Timestamp::MAX),
5128 )
5129}
5130
5131fn implementers_match(task: &Task, state: &RunState) -> bool {
5133 task.replacement.as_ref().map_or_else(
5134 || {
5135 task.implementers()
5136 .is_none_or(|n| n == state.config.graph.implementers)
5137 },
5138 |replacement| {
5139 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5140 && state.config.graph.implementers == 1
5141 },
5142 )
5143}
5144
5145fn starter_with_implementers(
5147 task: &Task,
5148 previous: Option<&RunState>,
5149 proposed: Starter,
5150) -> Starter {
5151 if previous.is_some_and(|s| !implementers_match(task, s)) {
5152 task.review_of
5153 .as_ref()
5154 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5155 } else {
5156 proposed
5157 }
5158}
5159
5160fn apply_task_implementers(config: &mut Config, task: &Task) {
5162 if let Some(n) = task.implementers() {
5163 config.graph.implementers = n;
5164 }
5165}
5166
5167#[cfg(test)]
5172fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5173 let explicit = match &task.overrides {
5174 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5175 _ => opts.config.as_deref(),
5176 };
5177 let (mut config, _) = Config::discover(repo, explicit)?;
5178 apply_options(&mut config, opts, task)?;
5179 Ok(config)
5180}
5181
5182fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5183 if task
5184 .overrides
5185 .as_ref()
5186 .is_none_or(|o| o.inherit_daemon_options)
5187 && let Some(mode) = opts.merge.as_deref()
5188 {
5189 config.merge.mode = merge_mode(mode)?;
5190 }
5191 if let Some(o) = &task.overrides {
5192 o.apply(config);
5193 }
5194 Ok(())
5195}
5196
5197fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5199 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5200 if let Some(mode) = &opts.merge {
5201 config.merge.mode = merge_mode(mode)?;
5202 }
5203 Ok(config)
5204}
5205
5206async fn maybe_prune_cache_between_runs(
5211 repo: &Path,
5212 opts: &Opts,
5213 home: &Path,
5214 stop: &Stop,
5215 last_checked: &mut Option<Timestamp>,
5216 now: Timestamp,
5217) {
5218 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5219 return;
5220 }
5221 *last_checked = Some(now);
5222 let cfg = match prepare(repo, opts) {
5223 Ok(cfg) => cfg,
5224 Err(e) => {
5225 tracing::warn!("cache check: no config: {e:#}");
5226 return;
5227 }
5228 };
5229 match clean::prune_cache_if_over_limit(&cfg, home) {
5230 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5231 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5232 pruned.files,
5233 pruned.freed
5234 ),
5235 Ok(_) => {}
5236 Err(e) => {
5237 tracing::warn!("housekeep: prune cache: {e:#}");
5238 notices::raise_in(
5239 home,
5240 Notice::warn(
5241 "housekeep:cache",
5242 format!(
5243 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5244 e.to_string()
5245 .lines()
5246 .next()
5247 .unwrap_or("unknown cleanup error")
5248 ),
5249 ),
5250 );
5251 }
5252 }
5253}
5254
5255fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5259 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5260}
5261
5262async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5281 let cfg = match prepare(repo, opts) {
5282 Ok(cfg) => cfg,
5283 Err(e) => {
5284 tracing::warn!("housekeep: no config: {e:#}");
5285 return;
5286 }
5287 };
5288 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5297 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5298 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5303 let mut extra = Vec::new();
5304 if out.unreadable > 0 {
5305 extra.push(format!("{} unreadable", out.unreadable));
5306 }
5307 if out.orphaned_worktrees > 0 {
5308 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5309 }
5310 let detail = if extra.is_empty() {
5311 String::new()
5312 } else {
5313 format!(" ({})", extra.join(", "))
5314 };
5315 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5316 }
5317 if out.external_merges_recorded > 0 {
5318 tracing::info!(
5319 "housekeep: recorded {} run(s) as merged externally",
5320 out.external_merges_recorded
5321 );
5322 }
5323 if out.stale_pr_states_repaired > 0 {
5324 tracing::info!(
5325 "housekeep: rewrote {} run record(s) whose pull request had already settled",
5326 out.stale_pr_states_repaired
5327 );
5328 }
5329 if out.cache_files > 0 {
5330 tracing::info!(
5331 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5332 out.cache_files,
5333 out.cache_freed
5334 );
5335 }
5336 if out.questions_abandoned > 0 {
5337 tracing::info!(
5338 "housekeep: abandoned {} question(s) left open by a finished run",
5339 out.questions_abandoned
5340 );
5341 }
5342}
5343
5344async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5353 let questions = Questions::at(home.join("questions"));
5354 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5355 if report.is_empty() {
5356 return;
5357 }
5358 if !report.quarantined.is_empty() {
5359 tracing::info!(
5360 "triage: held {} blocked task(s) whose blocked-on task or \
5361 question no longer exists: {}",
5362 report.quarantined.len(),
5363 report.quarantined.join(", ")
5364 );
5365 }
5366 if !report.resumed.is_empty() {
5367 tracing::info!(
5368 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5369 report.resumed.len(),
5370 report.resumed.join(", ")
5371 );
5372 }
5373 if !report.asked.is_empty() {
5374 tracing::info!(
5375 "triage: asked about {} held task(s): {}",
5376 report.asked.len(),
5377 report.asked.join(", ")
5378 );
5379 }
5380 if !report.answered.is_empty() {
5381 tracing::info!(
5382 "triage: applied {} operator answer(s): {}",
5383 report.answered.len(),
5384 report.answered.join(", ")
5385 );
5386 }
5387}
5388
5389pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5396 disk_gate_with(repo, config, crate::disk::free_bytes)
5397}
5398
5399fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5403 repo: &Path,
5404 config: &Config,
5405 free_bytes: F,
5406) -> Option<String> {
5407 let min = config.disk.min_free_bytes;
5408 if min == 0 {
5409 return None;
5410 }
5411 let mut paths = vec![repo.to_owned()];
5412 if let Some(cache) = config.cache_dir() {
5413 paths.push(cache);
5414 }
5415 if let Some(root) = &config.graph.worktree_root {
5416 paths.push(root.clone());
5417 }
5418 for path in paths {
5419 let probe = if path == repo {
5420 path.as_path()
5421 } else {
5422 path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5423 };
5424 let reason = match free_bytes(probe) {
5425 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5426 Err(e) => Some(crate::disk::unmeasured_in(
5427 probe,
5428 &e,
5429 &config.graph.language,
5430 )),
5431 };
5432 if reason.is_some() {
5433 return reason;
5434 }
5435 }
5436 None
5437}
5438
5439const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5446
5447const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5451
5452fn quota_wait(
5461 reset_at: Option<Timestamp>,
5462 now: Timestamp,
5463 fallback: Duration,
5464 cap: Duration,
5465) -> Duration {
5466 match reset_at {
5467 Some(at) if at > now => {
5468 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5469 Duration::from_secs(secs).min(cap)
5470 }
5471 _ => fallback,
5472 }
5473}
5474
5475fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5489 parse_reset_hint_zoned(text, now)
5490 .or_else(|| parse_reset_hint_dated(text))
5491 .or_else(|| parse_reset_hint_relative(text, recorded))
5492}
5493
5494fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5498 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5499 let mut rest = rest.trim();
5500 if rest.is_empty() {
5501 return None;
5502 }
5503 let mut total: i64 = 0;
5504 let mut matched = false;
5505 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5506 if let Some((digits, tail)) = rest.split_once(unit)
5507 && !digits.is_empty()
5508 && digits.bytes().all(|b| b.is_ascii_digit())
5509 {
5510 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5511 rest = tail;
5512 matched = true;
5513 }
5514 }
5515 if !rest.is_empty() || !matched {
5516 return None;
5517 }
5518 recorded
5519 .checked_add(jiff::SignedDuration::from_secs(total))
5520 .ok()
5521}
5522
5523fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5527 let clock = clock.trim().to_lowercase();
5528 let (digits, pm) = clock
5529 .strip_suffix("am")
5530 .map(|d| (d, false))
5531 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5532 let (h, m) = digits.trim().split_once(':')?;
5533 let mut hour: i8 = h.trim().parse().ok()?;
5534 let minute: i8 = m.trim().parse().ok()?;
5535 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5536 return None;
5537 }
5538 if pm && hour != 12 {
5539 hour += 12;
5540 } else if !pm && hour == 12 {
5541 hour = 0;
5542 }
5543 Some((hour, minute))
5544}
5545
5546fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5551 let open = text.find('(')?;
5552 let close = text.rfind(')')?;
5553 if close <= open {
5554 return None;
5555 }
5556 let zone = text[open + 1..close].trim();
5557 let (hour, minute) = parse_12h_clock(&text[..open])?;
5558 let tz = jiff::tz::TimeZone::get(zone).ok()?;
5559 let candidate = now
5560 .to_zoned(tz)
5561 .with()
5562 .hour(hour)
5563 .minute(minute)
5564 .second(0)
5565 .millisecond(0)
5566 .microsecond(0)
5567 .nanosecond(0)
5568 .build()
5569 .ok()?;
5570 let mut at = candidate.timestamp();
5571 if at <= now {
5572 at += jiff::SignedDuration::from_hours(24);
5573 }
5574 Some(at)
5575}
5576
5577fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5586 let words: Vec<&str> = text.split_whitespace().collect();
5587 if words.len() < 5 {
5588 return None;
5589 }
5590 (0..=words.len() - 5)
5591 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5592}
5593
5594fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5600 if trailing.is_some_and(|next| next.starts_with('(')) {
5601 return None;
5602 }
5603 let month = month_number(window[0])?;
5604 let day_token = window[1].strip_suffix(',')?.to_lowercase();
5605 let day_digits = ["st", "nd", "rd", "th"]
5606 .iter()
5607 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5608 let day: i8 = day_digits.parse().ok()?;
5609 let year_token = window[2];
5610 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5611 return None;
5612 }
5613 let year: i16 = year_token.parse().ok()?;
5614 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5618 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5619 let date = jiff::civil::Date::new(year, month, day).ok()?;
5620 let candidate = date
5621 .at(hour, minute, 0, 0)
5622 .to_zoned(jiff::tz::TimeZone::UTC)
5623 .ok()?;
5624 Some(candidate.timestamp())
5625}
5626
5627fn month_number(name: &str) -> Option<i8> {
5630 const NAMES: [&str; 12] = [
5631 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5632 ];
5633 let lower = name.to_lowercase();
5634 NAMES
5635 .iter()
5636 .position(|n| *n == lower.as_str())
5637 .map(|i| i as i8 + 1)
5638}
5639
5640#[cfg(test)]
5642fn exhausted_review_budget(state: &RunState) -> bool {
5643 !crate::handover::can_resume(state)
5646 && state.status == RunStatus::Blocked
5647 && !state.released()
5648 && state.retired_to.is_none()
5649}
5650
5651fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5688 unfinished_run_with(runs, short, RunState::load)
5689}
5690
5691pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5694where
5695 F: FnMut(&str) -> Result<RunState>,
5696{
5697 let mut id = runs.last()?.clone();
5698 let mut visited = std::collections::BTreeSet::new();
5699 let mut repo = None;
5700 loop {
5701 if !runs.contains(&id) || !visited.insert(id.clone()) {
5702 tracing::warn!("invalid or cyclic recovery authority for task {short}");
5703 return None;
5704 }
5705 let state = match load(&id) {
5706 Ok(state) if state.id == id => state,
5707 Ok(_) => return None,
5708 Err(e) => {
5709 tracing::warn!("could not read run {id} for task {short}: {e:#}");
5710 return None;
5711 }
5712 };
5713 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5714 return None;
5715 }
5716 repo = Some(state.repo.clone());
5717 if let Some(authority) = state.retired_to {
5718 id = authority;
5719 continue;
5720 }
5721 return (crate::handover::can_resume(&state)
5722 && state.liveness(false) != crate::run::Liveness::Live)
5723 .then_some(id);
5724 }
5725}
5726
5727fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5735where
5736 F: FnOnce(&str) -> Result<RunState>,
5737{
5738 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5740 || task.fresh_start
5741 || task.review_branch.is_some()
5742 {
5743 return false;
5744 }
5745 let Some(id) = task.runs.last() else {
5746 return false;
5747 };
5748 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5749}
5750
5751#[derive(Debug, Clone, PartialEq, Eq)]
5754enum Starter {
5755 Review(String),
5758 Resume(String),
5760 Start,
5762}
5763
5764fn retained_attempt_hold(
5769 task: &Task,
5770 starter: &Starter,
5771 limit: usize,
5772 mut load: impl FnMut(&str) -> Result<RunState>,
5773) -> Option<String> {
5774 if limit == 0 || matches!(starter, Starter::Resume(_)) {
5775 return None;
5776 }
5777 let mut retained = 0;
5778 for id in task
5779 .runs
5780 .iter()
5781 .chain(task.startup_failures.iter().map(|failure| &failure.run))
5782 .collect::<std::collections::BTreeSet<_>>()
5783 {
5784 let state = match load(id) {
5785 Ok(state) if state.id == *id => state,
5786 _ => {
5787 return Some(format!(
5788 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5789 ));
5790 }
5791 };
5792 if state.retired_to.is_some() || state.released() {
5793 continue;
5794 }
5795 retained += 1;
5798 }
5799 (retained >= limit).then(|| format!(
5800 "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
5801 ))
5802}
5803
5804fn selected_starter(
5806 selected: &crate::pr_recovery::Selection,
5807 previous: Option<&RunState>,
5808 unfinished: Option<&str>,
5809) -> Starter {
5810 if let Some(id) = unfinished
5811 && previous.is_some_and(|r| {
5812 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5813 })
5814 {
5815 Starter::Resume(id.to_owned())
5816 } else {
5817 Starter::Review(selected.branch.clone())
5818 }
5819}
5820
5821fn take_divergence_answer(
5825 branch: &str,
5826 remote: &str,
5827 task: &mut Task,
5828) -> Option<crate::reconcile::Choice> {
5829 let summary = crate::reconcile::summary_for(branch, remote);
5830 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5831 (a.question == summary)
5832 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5833 .flatten()
5834 .map(|c| (i, c))
5835 })?;
5836 task.answers.remove(idx);
5837 Some(choice)
5838}
5839
5840fn choose_starter(
5852 review_branch: Option<&str>,
5853 branch_exists: bool,
5854 unfinished: Option<&str>,
5855) -> Starter {
5856 match review_branch {
5857 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5858 Some(_) => Starter::Start,
5859 None => match unfinished {
5860 Some(id) => Starter::Resume(id.to_owned()),
5861 None => Starter::Start,
5862 },
5863 }
5864}
5865
5866fn review_retry_starter(
5870 task: &Task,
5871 previous: Option<&RunState>,
5872 branch: Option<&str>,
5873 exists: bool,
5874 unfinished: Option<&str>,
5875) -> Starter {
5876 if let Some(run) = previous
5877 && unfinished == Some(run.id.as_str())
5878 && run.reviewed_commits.is_some()
5879 && branch.is_some_and(|branch| {
5880 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5881 })
5882 && may_resume_run(run, task)
5883 {
5884 return Starter::Resume(run.id.clone());
5885 }
5886 match (branch, unfinished, &task.review_of) {
5887 (None, None, Some(branch)) => Starter::Review(branch.clone()),
5888 _ => choose_starter(branch, exists, unfinished),
5889 }
5890}
5891
5892fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5894 let branch = task.review_branch.take();
5895 let instruction = task.review_instruction.take();
5896 branch.filter(|branch| match &instruction {
5897 Some(authored) => *authored == task.instruction,
5898 None => previous.map_or_else(
5901 || task.review_of.as_ref() == Some(branch),
5902 |run| compatible_run_instruction(run, task),
5903 ),
5904 })
5905}
5906
5907fn may_resume_run(run: &RunState, task: &Task) -> bool {
5910 task.resume_override
5911 .as_ref()
5912 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5913 || compatible_run_instruction(run, task)
5914}
5915
5916pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5918 if let Some(authored) = &run.task_instruction {
5919 return compatible_instruction(authored, task);
5920 }
5921 if compatible_instruction(&run.instruction, task) {
5922 return true;
5923 }
5924 if run.reviewed_commits.is_some() {
5927 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5928 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5929 }
5930 if let Some(branch) = &task.review_of {
5931 let canonical = format!(
5932 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5933 );
5934 let generated = format!(
5935 "Review the work already on branch `{branch}`. There is no task statement: what the change claims to do is whatever its commits say.\n\n"
5936 );
5937 return task.instruction == canonical && run.instruction.starts_with(&generated);
5938 }
5939 }
5940 false
5941}
5942
5943pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5945 strip_answers_block(old, task) == task.instruction
5946}
5947
5948fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5951 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5952 return fallback.to_path_buf();
5953 }
5954 task.repo.clone()
5955}
5956
5957const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5961
5962fn answers_block(task: &Task, count: usize) -> String {
5964 let mut s = ANSWERS_HEADER.to_owned();
5965 for a in &task.answers[..count] {
5966 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5967 }
5968 s
5969}
5970
5971fn resumption_block(r: &crate::queue::Resumption) -> String {
5974 format!(
5975 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5976 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5977 r.generation, r.at, r.instruction, r.answers_through,
5978 )
5979}
5980
5981fn append_answers(base: &str, task: &Task) -> String {
5983 let mut s = base.to_owned();
5984 if !task.answers.is_empty() {
5985 s.push_str(&answers_block(task, task.answers.len()));
5986 }
5987 if let Some(r) = &task.resumption {
5988 s.push_str(&resumption_block(r));
5989 }
5990 s
5991}
5992
5993fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5997 let mut instruction = instruction;
5998 for approval in task
5999 .resumption
6000 .iter()
6001 .chain(task.resumption_history.iter().rev())
6002 {
6003 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6004 instruction = base;
6005 break;
6006 }
6007 }
6008 for count in (1..=task.answers.len()).rev() {
6009 let block = answers_block(task, count);
6010 if let Some(base) = instruction.strip_suffix(&block) {
6011 return base;
6012 }
6013 }
6014 instruction
6015}
6016
6017fn instruction_for(task: &Task) -> String {
6025 append_answers(&task.instruction, task)
6026}
6027
6028fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6040 append_answers(strip_answers_block(old_instruction, task), task)
6041}
6042
6043fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6045 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6046 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6047 if let Some(cause) = task.hold_notice_cause.as_mut() {
6048 cause.target = failure.map(|f| f.target.clone());
6049 }
6050}
6051
6052#[derive(Debug, thiserror::Error)]
6053#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6054struct MissingAttachment {
6055 name: String,
6056 path: PathBuf,
6057}
6058
6059fn task_attachments(
6061 queue: &Queue,
6062 task: &Task,
6063) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6064 let paths = queue.attachment_paths(task);
6065 for (name, path) in task.attachments.iter().zip(&paths) {
6066 if !path.is_file() {
6067 return Err(MissingAttachment {
6068 name: name.clone(),
6069 path: path.clone(),
6070 });
6071 }
6072 }
6073 Ok(paths)
6074}
6075
6076fn prepare_instruction(
6087 starter: &Starter,
6088 old_instruction: Option<&str>,
6089 task: &Task,
6090) -> Option<String> {
6091 match starter {
6092 Starter::Start => Some(instruction_for(task)),
6093 Starter::Resume(_) => Some(resumed_instruction(
6094 old_instruction.expect("a resumed run always has a prior instruction"),
6095 task,
6096 )),
6097 Starter::Review(_) => None,
6098 }
6099}
6100
6101fn record(queue: &Queue, task: &mut Task) {
6105 if let Err(e) = queue.put(task) {
6106 tracing::error!("could not record task {}: {e:#}", task.short());
6107 let notice = Notice::error(
6108 "loop:record",
6109 format!(
6110 "Task {} state could not be saved: {}. Check the disk.",
6111 task.id,
6112 e.to_string().lines().next().unwrap_or("unknown save error")
6113 ),
6114 )
6115 .link(Link::Task {
6116 id: task.id.clone(),
6117 });
6118 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6120 Some(home) => notices::raise_in(home, notice),
6121 None => notices::raise(notice),
6122 }
6123 }
6124}
6125
6126fn runnable(queue: &Queue) -> Vec<Task> {
6132 let mut tasks: Vec<Task> = queue
6133 .list()
6134 .into_iter()
6135 .filter(|t| t.status.runnable())
6136 .collect();
6137 tasks.sort_unstable_by(crate::queue::dispatch_order);
6138 tasks
6139}
6140
6141fn describe(state: &RunState) -> String {
6155 let p = phrases(&state.config.graph.language);
6156 let mut detail = if state.status == RunStatus::Stalled {
6157 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6158 seats.sort_unstable();
6159 seats.dedup();
6160 if seats.is_empty() {
6161 p.quorum_lost.to_owned()
6162 } else {
6163 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6164 }
6165 } else {
6166 format!("{}{}", p.run_ended, state.status.display_label())
6167 };
6168 if let Some(cause) = state.verification_blocking_cause() {
6169 detail.push_str(&format!(" ({cause})"));
6170 } else if let Some(last) = state.events.last() {
6171 let unanswered = state
6175 .reviews
6176 .last()
6177 .filter(|r| {
6178 state.status == RunStatus::Blocked
6179 && last.node == "review"
6180 && r.incomplete()
6181 && r.blocking == 0
6182 && r.round == state.config.graph.review_rounds
6183 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6184 })
6185 .map(|r| (r.expected - r.answered, r.round));
6186 match unanswered {
6187 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6188 detail.push_str(&format!(
6189 " ({}: {})",
6190 last.node,
6191 (p.reviewers_never_answered)(missing, rounds)
6192 ));
6193 }
6194 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6195 }
6196 }
6197 detail.push_str(&format!(" [run {}]", state.id));
6198 detail
6199}
6200
6201const DIAGNOSTIC_MAX: usize = 4_000;
6207
6208const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6213
6214fn diagnostic(state: &RunState) -> Option<String> {
6228 let mut parts: Vec<String> = Vec::new();
6229
6230 for o in state.gate.iter().filter(|o| !o.ok()) {
6232 parts.push(format!(
6233 "gate `{}` failed ({}):\n{}",
6234 o.command,
6235 notices::exit_status(o.code),
6236 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6237 ));
6238 }
6239
6240 if let Some(last) = state
6243 .events
6244 .iter()
6245 .rev()
6246 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6247 {
6248 parts.push(last.message.clone());
6249 }
6250
6251 if state.viable().is_empty() {
6258 for c in &state.candidates {
6259 if let Some(evidence) = &c.verified_noop {
6260 parts.push(format!(
6261 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6262 c.label
6263 ));
6264 } else if !c.summary.trim().is_empty() {
6265 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6266 } else if let Some(why) = &c.failed {
6267 parts.push(format!("candidate {}: {why}", c.label));
6268 }
6269 }
6270 }
6271
6272 if parts.is_empty() {
6273 return None;
6274 }
6275 Some(crate::run::tail(
6280 &parts.join("\n\n"),
6281 DIAGNOSTIC_MAX.saturating_sub(100),
6282 ))
6283}
6284
6285fn label(status: RunStatus) -> &'static str {
6293 status.as_str()
6294}
6295
6296pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6298 match mode {
6299 "none" => Ok(MergeMode::None),
6300 "local" => Ok(MergeMode::Local),
6301 "pr" => Ok(MergeMode::Pr),
6302 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6303 }
6304}
6305
6306fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6311 mutex
6312 .lock()
6313 .unwrap_or_else(std::sync::PoisonError::into_inner)
6314}
6315
6316#[cfg(test)]
6317mod tests {
6318 use super::*;
6319 use crate::queue::{Source, TaskStatus};
6320 use crate::run::{Candidate, CommandOutcome};
6321 use pretty_assertions::assert_eq;
6322
6323 fn task() -> Task {
6324 Task::new(
6325 "add retries".to_owned(),
6326 "add retries".to_owned(),
6327 PathBuf::from("/repo"),
6328 Source::Human,
6329 )
6330 }
6331
6332 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6333 let job = crate::worker::Job {
6334 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6335 sequence: 1,
6336 kind: "task".into(),
6337 key: format!("task:{}", request.task),
6338 payload: serde_json::to_value(request).unwrap(),
6339 generation: "a".repeat(64),
6340 version: None,
6341 status: crate::worker::Status::Starting,
6342 result: None,
6343 pid: None,
6344 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6345 finished_at: None,
6346 };
6347 let dir = home.join("workers/jobs").join(&job.id);
6348 std::fs::create_dir_all(&dir).unwrap();
6349 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6350 job
6351 }
6352
6353 #[test]
6354 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6355 let home = tempfile::tempdir().unwrap();
6356 let request = TaskWorker {
6357 opts: Opts::default(),
6358 queue: home.path().join("queue"),
6359 task: "startup".into(),
6360 lane: PermitKind::Ordinary,
6361 standalone: false,
6362 };
6363 let job = starting_task_reservation(home.path(), &request);
6364 let error = task_worker_spawn_error(
6365 home.path(),
6366 &request,
6367 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6368 )
6369 .expect_err("our own reservation must not turn a failed spawn into a resync");
6370 let active = crate::worker::active(home.path()).unwrap();
6371 assert_eq!(active.len(), 1);
6372 assert_eq!(active[0].id, job.id);
6373 assert_eq!(active[0].status, crate::worker::Status::Starting);
6374 assert!(
6375 crate::worker::control(home.path(), &job.key)
6376 .unwrap()
6377 .is_none()
6378 );
6379 let notices = notices::Notices::at(home.path().join("notifications")).list();
6380 assert_eq!(notices.len(), 1);
6381 assert_eq!(notices[0].key, "loop:worker-startup");
6382 assert!(!notices[0].message.contains("private-error-detail"));
6383 assert!(notices[0].message.contains(&request.task));
6384 assert!(
6385 notices[0]
6386 .message
6387 .contains("could not be started or acknowledged")
6388 );
6389 assert!(notices[0].message.contains("worker.log"));
6390 assert_eq!(
6391 notices[0].link,
6392 Some(Link::Task {
6393 id: request.task.clone()
6394 })
6395 );
6396 assert!(format!("{error:#}").contains("private-error-detail"));
6397 }
6398
6399 #[test]
6400 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6401 let home = tempfile::tempdir().unwrap();
6402 let mut request = TaskWorker {
6403 opts: Opts::default(),
6404 queue: home.path().join("queue"),
6405 task: "handoff".into(),
6406 lane: PermitKind::Ordinary,
6407 standalone: true,
6408 };
6409 let job = starting_task_reservation(home.path(), &request);
6410 request.standalone = false;
6411 task_worker_spawn_error(
6412 home.path(),
6413 &request,
6414 anyhow::anyhow!("operation key is already reserved for a different request"),
6415 )
6416 .expect("a different standalone request is the handoff race, not our startup failure");
6417 let active = crate::worker::active(home.path()).unwrap();
6418 assert_eq!(active.len(), 1);
6419 assert_eq!(active[0].id, job.id);
6420 assert_eq!(active[0].payload, job.payload);
6421 assert!(
6422 notices::Notices::at(home.path().join("notifications"))
6423 .list()
6424 .is_empty()
6425 );
6426 }
6427
6428 #[test]
6429 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6430 let home = tempfile::tempdir().unwrap();
6431 let queue = Queue::at(home.path().join("queue"));
6432 let mut task = task();
6433 task.runs = vec!["previous".into()];
6434 queue.put(&mut task).unwrap();
6435 let request = TaskWorker {
6436 opts: Opts::default(),
6437 queue: home.path().join("queue"),
6438 task: task.id.clone(),
6439 lane: PermitKind::Ordinary,
6440 standalone: false,
6441 };
6442 let job = starting_task_reservation(home.path(), &request);
6443 let claims = current_work(home.path(), Timestamp::now());
6444 assert_eq!(claims.len(), 1);
6445 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6446 assert_eq!(claims[0].run, "previous");
6447 assert!(other_claims_run(&claims, "previous", None));
6448 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6451 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6452 }
6453
6454 #[test]
6455 fn admission_excludes_only_the_callers_exact_reservation() {
6456 let own = Current {
6457 worker: Some("own".into()),
6458 task: "same-task".into(),
6459 run: "previous".into(),
6460 };
6461 assert!(!other_claims_run(
6462 std::slice::from_ref(&own),
6463 "previous",
6464 Some("own")
6465 ));
6466 assert!(other_claims_run(
6467 std::slice::from_ref(&own),
6468 "previous",
6469 None
6470 ));
6471 for worker in [None, Some("other".into())] {
6472 let other = Current {
6473 worker,
6474 ..own.clone()
6475 };
6476 assert!(other_claims_run(
6477 &[own.clone(), other],
6478 "previous",
6479 Some("own")
6480 ));
6481 }
6482 let legacy: Current =
6483 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6484 assert!(other_claims_run(&[legacy], "previous", Some("own")));
6485 }
6486
6487 #[test]
6488 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6489 let mut task = task();
6490 let mut run = run_state(RunStatus::Reviewing);
6491 run.task_instruction = Some(task.instruction.clone());
6492 run.reviewed_commits = Some(vec!["committed-fix".into()]);
6493 let branch = "magi/test/B";
6494 run.candidates.push(crate::run::Candidate {
6495 branch: branch.into(),
6496 ..candidate('B', "preserved work", false, None)
6497 });
6498 task.runs = vec![run.id.clone()];
6499 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6500 assert_eq!(
6501 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6502 Starter::Resume(run.id.clone())
6503 );
6504 assert!(matches!(
6505 review_retry_starter(
6506 &task,
6507 Some(&run),
6508 Some("different"),
6509 true,
6510 unfinished.as_deref()
6511 ),
6512 Starter::Review(_)
6513 ));
6514 assert_eq!(
6515 review_retry_starter(
6516 &task,
6517 Some(&run),
6518 Some(branch),
6519 false,
6520 unfinished.as_deref()
6521 ),
6522 Starter::Start
6523 );
6524 task.instruction.push_str(" changed criteria");
6525 assert!(matches!(
6526 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6527 Starter::Review(_)
6528 ));
6529 assert!(matches!(
6530 review_retry_starter(&task, Some(&run), Some(branch), true, None),
6531 Starter::Review(_)
6532 ));
6533 }
6534
6535 #[test]
6536 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6537 let dir = tempfile::tempdir().unwrap();
6538 let queue = Queue::at(dir.path().join("queue"));
6539 let mut task = task();
6540 task.status = TaskStatus::Running;
6541 task.attempts = 1;
6542 queue.put(&mut task).unwrap();
6543 let live = std::collections::BTreeSet::from([task.id.clone()]);
6544 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6545 drop(queue.claim(&task.id).unwrap());
6546 let saved = queue.get(&task.id).unwrap();
6547 assert_eq!(saved.status, TaskStatus::Running);
6548 assert_eq!(saved.attempts, 1);
6549 assert!(saved.last_error.is_none());
6550 }
6551
6552 #[test]
6553 fn standalone_workers_do_not_consume_scheduler_lanes() {
6554 let request = |task: &str, lane, standalone| TaskWorker {
6555 opts: Opts::default(),
6556 queue: PathBuf::from("/queue"),
6557 task: task.to_owned(),
6558 lane,
6559 standalone,
6560 };
6561 let mut jobs = vec![
6562 request("ordinary", PermitKind::Ordinary, false),
6563 request("standalone-urgent", PermitKind::Urgent, true),
6564 request("standalone-ordinary", PermitKind::Ordinary, true),
6565 request("decision", PermitKind::None, false),
6566 ];
6567 assert_eq!(available_slots(&jobs, 2), (1, 1));
6568 jobs.push(request("urgent", PermitKind::Urgent, false));
6569 assert_eq!(available_slots(&jobs, 2), (1, 0));
6570 assert_eq!(available_slots(&jobs, 0), (0, 0));
6571 }
6572
6573 #[test]
6574 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6575 let now = Timestamp::now();
6576 let mut reading = Reading {
6577 pid: Some(std::process::id()),
6578 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6579 ..Reading::default()
6580 };
6581 assert!(!reading.running(now));
6582 assert!(legacy_scheduler_running(&reading, now, 0));
6583 reading.worker_protocol = Some(1);
6584 assert!(!legacy_scheduler_running(&reading, now, 0));
6585 }
6586
6587 #[test]
6588 fn selected_public_head_overrides_historical_resume_and_pin() {
6589 let mut t = task();
6590 let mut old = run_state(RunStatus::Blocked);
6591 let selection = crate::pr_recovery::Selection {
6592 url: "url".into(),
6593 branch: format!("magi/task-{}", t.id),
6594 head: "a".repeat(40),
6595 source_head: None,
6596 source_run: None,
6597 source_proof: None,
6598 disposition: Some(crate::pr_recovery::Disposition::Review),
6599 instruction: t.instruction.clone(),
6600 approved_at: Timestamp::now(),
6601 };
6602 t.resume_override = Some(crate::queue::OperatorResume {
6603 pinned_run: Some(old.id.clone()),
6604 question_id: "choice".into(),
6605 at: Timestamp::now(),
6606 conductor_rehold: None,
6607 forced: false,
6608 });
6609 assert_eq!(
6610 selected_starter(&selection, Some(&old), Some(&old.id)),
6611 Starter::Review(selection.branch.clone())
6612 );
6613 old.pr_recovery = Some(selection.clone());
6614 assert_eq!(
6615 selected_starter(&selection, Some(&old), Some(&old.id)),
6616 Starter::Review(selection.branch.clone())
6617 );
6618 old.reviewed_commits = Some(vec!["implementation".into()]);
6619 assert_eq!(
6620 selected_starter(&selection, Some(&old), Some(&old.id)),
6621 Starter::Resume(old.id.clone())
6622 );
6623 let mut changed = selection.clone();
6624 changed.head = "b".repeat(40);
6625 assert_eq!(
6626 selected_starter(&changed, Some(&old), Some(&old.id)),
6627 Starter::Review(changed.branch)
6628 );
6629 }
6630
6631 #[test]
6632 fn candidate_transplant_failure_is_one_actionable_hold() {
6633 let dir = tempfile::tempdir().unwrap();
6634 let q = Queue::at(dir.path().join("queue"));
6635 let mut t = task();
6636 let mut state = run_state(RunStatus::Blocked);
6637 state.event("prep", "cannot apply referenced commit: conflict");
6638 state.prep_failure = Some("conflict".into());
6639 t.start(state.id.clone());
6640 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6641 assert_eq!(t.attempts, 1);
6642 assert_eq!(t.status, TaskStatus::Held);
6643 assert!(t.operator_held());
6644 assert!(!t.status.runnable());
6645 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6646 let first = t.chat_notice_key().unwrap();
6647 t.chat_notices.push(first.clone());
6648 t.release_operator("test", None);
6649 state.id = "another-unprepared-run".into();
6650 t.start(state.id.clone());
6651 finish_attempt(
6652 3,
6653 &q,
6654 &mut t,
6655 &state,
6656 &[],
6657 Err(anyhow::anyhow!("still conflicts")),
6658 );
6659 assert_eq!(
6660 t.chat_notice_key().as_ref(),
6661 Some(&first),
6662 "no work happened"
6663 );
6664 t.release_operator("test", None);
6665 state.prep_failure = None;
6666 state.status = RunStatus::Failed;
6667 state.begin_pass();
6668 t.start(state.id.clone());
6669 finish_attempt(
6670 1,
6671 &q,
6672 &mut t,
6673 &state,
6674 &[],
6675 Err(anyhow::anyhow!("new gate failure")),
6676 );
6677 let failure = t.chat_notice_key().unwrap();
6678 assert_ne!(failure, first, "approved recovery reached a real failure");
6679 t.release_operator("test", None);
6680 state.begin_pass();
6681 t.start(state.id.clone());
6682 finish_attempt(
6683 1,
6684 &q,
6685 &mut t,
6686 &state,
6687 &[],
6688 Err(anyhow::anyhow!("new failure on resume")),
6689 );
6690 assert_ne!(
6691 t.chat_notice_key().as_ref(),
6692 Some(&failure),
6693 "a new settled pass"
6694 );
6695 }
6696
6697 #[test]
6698 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6699 for source in ["cli", "web"] {
6700 let mut t = task();
6701 let mut run = run_state(RunStatus::Blocked);
6702 run.instruction = "Run A original criteria".into();
6703 run.task_instruction = Some(run.instruction.clone());
6704 t.start(run.id.clone());
6705 t.release_operator("choice", Some("resume-question"));
6706 t.resume_override = Some(crate::queue::OperatorResume {
6707 question_id: "resume-question".into(),
6708 at: Timestamp::now(),
6709 conductor_rehold: None,
6710 forced: true,
6711 pinned_run: Some(run.id.clone()),
6712 });
6713 t.hold_machine(Some("not enough free space to start a run".into()));
6714 let mut unchanged = t.clone();
6715 unchanged
6716 .edit("title changed".into(), unchanged.instruction.clone())
6717 .unwrap();
6718 unchanged.release_operator(source, None);
6719 assert_eq!(
6720 unchanged
6721 .resume_override
6722 .as_ref()
6723 .unwrap()
6724 .pinned_run
6725 .as_deref(),
6726 Some(run.id.as_str())
6727 );
6728 assert!(!compatible_run_instruction(&run, &unchanged));
6729 assert!(may_resume_run(&run, &unchanged));
6730
6731 t.edit(
6732 "approved recovery".into(),
6733 "Reuse measured PR head B; fix Clippy; review".into(),
6734 )
6735 .unwrap();
6736 assert!(t.resume_override.is_none());
6737 t.release_operator(source, None);
6738 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6739 assert!(reloaded.resume_override.is_none());
6740 assert!(!may_resume_run(&run, &reloaded));
6741 let unfinished =
6742 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6743 .filter(|_| may_resume_run(&run, &reloaded));
6744 assert_eq!(
6745 choose_starter(None, false, unfinished.as_deref()),
6746 Starter::Start
6747 );
6748 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6749 assert_eq!(
6750 reloaded.resumption_history[0].question_id.as_deref(),
6751 Some("resume-question")
6752 );
6753
6754 unchanged.instruction = "Reuse measured PR head B".into();
6757 unchanged.hold_machine(Some("disk hold".into()));
6758 unchanged.release_operator(source, None);
6759 assert!(unchanged.resume_override.is_none());
6760 assert!(!may_resume_run(&run, &unchanged));
6761 }
6762 }
6763
6764 #[test]
6765 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6766 let mut t = task();
6767 let mut run = run_state(RunStatus::Blocked);
6768 t.review_of = Some("approved-head".into());
6769 t.instruction =
6770 "Review the branch `approved-head` (review-only: no implementation, no judging)."
6771 .into();
6772 run.instruction = "Review the work already on branch `approved-head`. There is no task statement: what the change claims to do is whatever its commits say.\n\nCommit log".into();
6773 run.reviewed_commits = Some(vec!["Commit log".into()]);
6774 t.start(run.id.clone());
6775 t.hold_machine(Some("interrupted review".into()));
6776 t.release_operator("cli", None);
6777 assert!(
6778 compatible_run_instruction(&run, &t),
6779 "legacy explicit review remains resumable"
6780 );
6781 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6782 .filter(|_| compatible_run_instruction(&run, &t));
6783 assert_eq!(
6784 choose_starter(None, false, unfinished.as_deref()),
6785 Starter::Resume(run.id.clone())
6786 );
6787 run.task_instruction = Some(t.instruction.clone());
6788 assert!(compatible_run_instruction(&run, &t));
6789 let reloaded: RunState =
6790 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6791 assert!(compatible_run_instruction(&reloaded, &t));
6792 t.edit(
6793 "new approved head".into(),
6794 "Reuse measured PR head B".into(),
6795 )
6796 .unwrap();
6797 assert!(!compatible_run_instruction(&run, &t));
6798
6799 t.review_of = None;
6801 t.instruction = "Fix Clippy on approved head".into();
6802 run.task_instruction = None;
6803 run.instruction = format!(
6804 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6805 t.instruction
6806 );
6807 assert!(compatible_run_instruction(&run, &t));
6808 t.instruction.push('\n');
6809 assert!(
6810 compatible_run_instruction(&run, &t),
6811 "legacy generated review trimmed the original criteria"
6812 );
6813 t.hold_for_handover(Some("approved-head".into()), "refused".into());
6814 let mut unchanged = t.clone();
6815 assert_eq!(
6816 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6817 Some("approved-head")
6818 );
6819 t.edit("new plan".into(), "Reuse measured PR head B".into())
6820 .unwrap();
6821 assert!(take_review_branch(&mut t, Some(&run)).is_none());
6822 assert!(!compatible_run_instruction(&run, &t));
6823 t.review_branch = Some("approved-head".into());
6824 t.review_instruction = None;
6825 assert!(
6826 take_review_branch(&mut t, Some(&run)).is_none(),
6827 "legacy retained candidate cannot replace a revised approved head"
6828 );
6829 }
6830
6831 #[test]
6832 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6833 let home = crate::run::test_home();
6834 crate::run::pin_test_home();
6835 let dir = tempfile::tempdir().unwrap();
6836 let queue = Queue::at(dir.path().join("queue"));
6837 for resume in [true, false] {
6838 let state = run_state(RunStatus::Blocked);
6839 let mut t = task();
6840 t.start(state.id.clone());
6841 let action = if resume {
6842 ask::ChoiceAction::Resume {
6843 run: state.id.clone(),
6844 }
6845 } else {
6846 ask::ChoiceAction::Requeue
6847 };
6848 let mut q = action_question(&state.id, action);
6849 q.status = ask::QuestionStatus::Open;
6850 q.answer = None;
6851 q.answered_at = None;
6852 t.fail("run stopped with a question", 3);
6853 hold_if_runnable(&queue, &mut t);
6854 assert!(t.operator_decided_at.is_none());
6855 assert!(t.operator_held());
6856 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6857 let expected = if resume {
6858 ActionDecision::Resume(state.id.clone())
6859 } else {
6860 ActionDecision::Requeue
6861 };
6862 assert_eq!(
6863 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6864 expected
6865 );
6866 t.hold_manual(Some("later explicit hold".into()));
6867 assert_eq!(
6868 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6869 ActionDecision::Stale
6870 );
6871 }
6872 }
6873
6874 #[test]
6875 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6876 let mut t = task();
6877 t.answers.push(crate::queue::AnsweredQuestion {
6878 question: "Inspect the remote?".into(),
6879 answer: "Inspect then wait".into(),
6880 });
6881 let old = instruction_for(&t);
6882 assert!(compatible_instruction(&old, &t));
6883 t.instruction = "Reuse approved PR head and review".into();
6884 t.release_operator("cli", None);
6885 assert!(!compatible_instruction(&old, &t));
6886 let approved = instruction_for(&t);
6887 assert!(approved.contains("waiting premises are superseded"));
6888 assert!(compatible_instruction(&approved, &t));
6889 assert_eq!(resumed_instruction(&approved, &t), approved);
6890 t.release_operator("web", None);
6891 assert!(compatible_instruction(&approved, &t));
6892 assert_eq!(t.resumption_history.len(), 1);
6893 t.start("run".into());
6894 assert!(instruction_for(&t).contains("Explicit operator resumption"));
6895 }
6896
6897 #[test]
6901 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6902 let mut state = RunState::new(
6903 PathBuf::from("/repo"),
6904 "main".into(),
6905 "base".into(),
6906 "task".into(),
6907 Config::default(),
6908 );
6909 state.status = RunStatus::Landing;
6910 state.parked = true;
6911 state.pr_pushed_head = Some("head".into());
6912 state.land_unrelated = Some(
6913 serde_json::from_value(serde_json::json!({
6914 "head": "head", "question": "ci-question",
6915 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6916 }))
6917 .unwrap(),
6918 );
6919 let mut t = task();
6920 t.start(state.id.clone());
6921 let verdict = Verdict {
6922 status: RunStatus::Landing,
6923 left_pr: true,
6924 quota_hit: false,
6925 parked: true,
6926 no_viable_candidates: false,
6927 };
6928 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6929 assert_eq!(t.attempts, 0);
6930 assert_eq!(t.status, TaskStatus::Held);
6931 assert!(!t.operator_held());
6932 assert!(
6933 t.hold_reason
6934 .as_deref()
6935 .unwrap()
6936 .starts_with("[ci-unrelated]")
6937 );
6938 t.attempts = 1;
6940 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6941 assert_eq!(t.attempts, 1);
6942 assert_eq!(t.passes.len(), 1);
6943 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6944 state.pr_pushed_head = Some("new-head".into());
6945 state.parked = false;
6946 state.status = RunStatus::Blocked;
6947 let stale = Verdict {
6948 status: RunStatus::Blocked,
6949 parked: false,
6950 ..verdict
6951 };
6952 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6953 assert_eq!(t.attempts, 1);
6954 state.begin_pass();
6956 state.begin_pass();
6957 state.status = RunStatus::Landing;
6958 state.parked = true;
6959 state.pr_pushed_head = Some("head".into());
6960 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6961 assert_eq!(t.attempts, 0);
6962 assert_eq!(t.passes.len(), 2);
6963 }
6964
6965 #[test]
6966 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6967 let mut state = run_state(RunStatus::Failed);
6968 state
6969 .quota
6970 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6971 state.begin_pass();
6972 let mut t = task();
6973 t.start(state.id.clone());
6974 reclaim(&mut t, Some(state), 2, "en");
6975 assert_eq!(t.attempts, 1);
6976 }
6977
6978 #[test]
6979 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6980 let mut state = run_state(RunStatus::Blocked);
6981 let losses: Vec<_> = ["alpha", "beta"]
6982 .into_iter()
6983 .enumerate()
6984 .map(|(i, agent)| {
6985 QuotaLoss::from_report(
6986 format!("advisor-{i}"),
6987 "advise",
6988 Some(&crate::agent::Quota {
6989 cause: crate::agent::QuotaCause::Authentication,
6990 agent: agent.to_owned(),
6991 reset: None,
6992 }),
6993 )
6994 })
6995 .collect();
6996 crate::graph::block_machine_outage(&mut state, "advise", &losses);
6997 state.quota = losses;
6998 let mut t = task();
6999 t.start(state.id.clone());
7000 let verdict = Verdict {
7001 status: state.status,
7002 left_pr: false,
7003 quota_hit: true,
7004 parked: false,
7005 no_viable_candidates: true,
7006 };
7007 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7008 assert_eq!(t.attempts, 0);
7009 assert_eq!(t.status, TaskStatus::Held);
7010 assert!(!t.operator_held());
7011 let reason = t.hold_reason.as_deref().unwrap();
7012 assert!(reason.starts_with("[authentication]"));
7013 assert!(
7014 reason.contains("alpha")
7015 && reason.contains("beta")
7016 && reason.contains("re-authenticate")
7017 );
7018 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7019 let mut orphan = task();
7021 orphan.start(state.id.clone());
7022 reclaim(&mut orphan, Some(state), 2, "en");
7023 assert_eq!(orphan.attempts, 0);
7024 assert_eq!(orphan.status, TaskStatus::Held);
7025 }
7026
7027 #[test]
7028 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7029 let mut state = RunState::new(
7030 PathBuf::from("/repo"),
7031 "main".to_owned(),
7032 "abc1234".to_owned(),
7033 "task".to_owned(),
7034 Config::default(),
7035 );
7036 state.status = RunStatus::Blocked;
7037 state.resource_block = Some(crate::run::ResourceBlock {
7038 cause: crate::run::ResourceBlockCause::Other,
7039 node: "graft".to_owned(),
7040 kind: "shared build cache".to_owned(),
7041 detail: "timed out".to_owned(),
7042 at: jiff::Timestamp::now(),
7043 });
7044 let mut t = task();
7045 t.start("20260902-000000-aaaa".to_owned());
7046 assert_eq!(t.attempts, 1);
7047 let verdict = Verdict {
7048 status: RunStatus::Blocked,
7049 left_pr: false,
7050 quota_hit: false,
7051 parked: false,
7052 no_viable_candidates: false,
7053 };
7054 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7055 assert_eq!(t.status, TaskStatus::Held);
7056 assert_eq!(t.attempts, 0, "the attempt is refunded");
7057 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7058 assert!(
7059 !t.operator_held(),
7060 "a machine hold, released without a human"
7061 );
7062
7063 let mut selected = task();
7064 selected.start("20260902-000000-cccc".into());
7065 selected.replacement = Some(crate::merge_decision::Replacement {
7066 question: "fixture".into(),
7067 run: "earlier".into(),
7068 pr: "https://example.invalid/pr/1".into(),
7069 agent: "selected".into(),
7070 context: "fixture".into(),
7071 });
7072 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7073 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7074 assert_eq!(selected.attempts, 0);
7075 assert!(
7076 !selected.operator_held(),
7077 "a selected agent also retains a machine resource hold"
7078 );
7079 assert!(
7080 selected
7081 .hold_reason
7082 .as_deref()
7083 .unwrap()
7084 .starts_with("[resource] ")
7085 );
7086
7087 let mut p = task();
7089 p.start("20260902-000000-bbbb".to_owned());
7090 settle_and_diagnose(
7091 &mut p,
7092 Verdict {
7093 parked: true,
7094 ..verdict
7095 },
7096 "parked",
7097 2,
7098 &state,
7099 );
7100 assert_eq!(p.status, TaskStatus::Parked);
7101 assert_eq!(
7102 p.attempts, 0,
7103 "parking refunds once rather than also settling the resource hold"
7104 );
7105 }
7106
7107 #[test]
7108 fn record_failure_notice_links_the_task() {
7109 let dir = tempfile::tempdir().unwrap();
7110 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7113 let queue = Queue::at(dir.path().join("queue"));
7114 let mut t = interrupt_task("rec-fail-1");
7115 record(&queue, &mut t);
7116
7117 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7118 assert_eq!(found.len(), 1);
7119 assert_eq!(found[0].key, "loop:record");
7120 assert_eq!(
7121 found[0].link,
7122 Some(Link::Task {
7123 id: "rec-fail-1".to_owned()
7124 })
7125 );
7126 }
7127
7128 fn interrupt_task(id: &str) -> Task {
7131 let mut t = task();
7132 t.id = id.to_owned();
7133 t.interrupt = true;
7134 t
7135 }
7136
7137 fn task_with_id(id: &str) -> Task {
7139 let mut t = task();
7140 t.id = id.to_owned();
7141 t
7142 }
7143
7144 fn urgent_task(id: &str) -> Task {
7146 let mut t = task();
7147 t.id = id.to_owned();
7148 t.urgent = true;
7149 t
7150 }
7151
7152 #[test]
7153 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7154 let dir = tempfile::tempdir().unwrap();
7155 let queue = Queue::at(dir.path().join("queue"));
7156 let mut parked = task_with_id("parked");
7157 parked.start("run".into());
7158 parked.park("upgrade");
7159 parked.record_pass_at(
7160 "run",
7161 0,
7162 Some(Timestamp::now()),
7163 1,
7164 Some(crate::run::ParkCause::Upgrade {
7165 from: "old".into(),
7166 to: None,
7167 }),
7168 );
7169 let mut fresh = task_with_id("fresh");
7170 fresh.priority = 100;
7171 let mut urgent_task = urgent_task("urgent");
7172 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7173 queue.put(t).unwrap();
7174 }
7175 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7176 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7177 let candidates = runnable(&queue);
7178 assert_eq!(candidates[0].id, parked.id);
7179 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7180 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7181 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7182 drop(first);
7183 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7184 let next = runnable(&queue)
7185 .into_iter()
7186 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7187 .unwrap();
7188 assert_eq!(next.task.id, fresh.id);
7189 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7190 drop(claimed_elsewhere);
7191 drop(next);
7192 assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7193 }
7194
7195 #[test]
7196 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7197 let dir = tempfile::tempdir().unwrap();
7198 let queue = Queue::at(dir.path().join("queue"));
7199 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7200 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7201 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7202 let mut first = task();
7203 queue.put(&mut first).unwrap();
7204 let stale_plain = queue.get(&first.id).unwrap();
7205 first.set_urgent(true).unwrap();
7206 queue.put(&mut first).unwrap();
7207 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7208 let mut second = urgent_task("second");
7209 queue.put(&mut second).unwrap();
7210 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7211 drop(queue.claim(&second.id).unwrap());
7212 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7213 drop(dispatched);
7214 let stale_urgent = queue.get(&first.id).unwrap();
7215 first.set_urgent(false).unwrap();
7216 queue.put(&mut first).unwrap();
7217 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7218 assert_eq!(urgent.available_permits(), 1);
7219 drop(queue.claim(&first.id).unwrap());
7220 drop(occupied);
7221 }
7222
7223 #[test]
7224 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7225 let dir = tempfile::tempdir().unwrap();
7226 let queue = Queue::at(dir.path().join("queue"));
7227 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7228 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7229 let mut t = task();
7230 queue.put(&mut t).unwrap();
7231 for enabled in [true, false] {
7232 let stale = queue.get(&t.id).unwrap();
7233 t.set_urgent(enabled).unwrap();
7234 queue.put(&mut t).unwrap();
7235 assert_ne!(stale.urgent, enabled);
7236 let DispatchClaim {
7237 task: fresh,
7238 claim,
7239 permit,
7240 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7241 assert_eq!(fresh.urgent, enabled);
7242 assert_eq!(ordinary.available_permits(), usize::from(enabled));
7243 assert_eq!(urgent.available_permits(), usize::from(!enabled));
7244 assert!(queue.claim(&t.id).is_err());
7245 assert_eq!(fresh.attempts, stale.attempts);
7246 drop((claim, permit));
7247 assert_eq!(ordinary.available_permits(), 1);
7248 assert_eq!(urgent.available_permits(), 1);
7249 }
7250 t.set_urgent(true).unwrap();
7251 queue.put(&mut t).unwrap();
7252 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7253 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7254 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7255 drop(queue.claim(&t.id).unwrap());
7256 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7257 drop(occupied);
7258 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7259 drop(queue.claim(&t.id).unwrap());
7260 let held = queue.claim(&t.id).unwrap();
7261 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7262 drop(held);
7263 t.status = TaskStatus::Held;
7264 queue.put(&mut t).unwrap();
7265 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7266 drop(queue.claim(&t.id).unwrap());
7267 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7268 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7269 drop(queue.claim(&t.id).unwrap());
7270 assert_eq!(urgent.available_permits(), 1);
7271 }
7272
7273 #[test]
7278 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7279 assert_eq!(permit_kind(true, false), PermitKind::None);
7280 assert_eq!(permit_kind(true, true), PermitKind::None);
7281 }
7282
7283 #[test]
7288 fn permit_kind_separates_urgent_from_ordinary() {
7289 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7290 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7291 }
7292
7293 #[test]
7300 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7301 let cfg = Config::default();
7302 let repo = Path::new("/any/repo/path");
7303
7304 let reason =
7305 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7306 assert!(reason.contains("1024"), "{reason}");
7307 assert!(
7308 reason.contains(&cfg.disk.min_free_bytes.to_string()),
7309 "{reason}"
7310 );
7311
7312 assert_eq!(
7313 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7314 None,
7315 "exactly at the floor is open"
7316 );
7317 assert_eq!(
7318 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7319 None,
7320 "comfortably above the floor is open"
7321 );
7322 }
7323
7324 #[test]
7325 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7326 let mut cfg = Config::default();
7327 cfg.disk.min_free_bytes = 0;
7328 let repo = Path::new("/any/repo/path");
7329 assert_eq!(
7330 disk_gate_with(repo, &cfg, |_| Ok(0)),
7331 None,
7332 "a zero floor never measures at all"
7333 );
7334 }
7335
7336 #[test]
7337 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7338 let cfg = Config::default();
7339 let repo = Path::new("/any/repo/path");
7340 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7341 .expect("a measurement failure must close the gate, not open it");
7342 assert!(reason.contains("could not measure"), "{reason}");
7343 }
7344
7345 #[test]
7346 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7347 let ordinary = task();
7348 let next = advance_interrupt(
7349 Interrupt::Idle,
7350 std::slice::from_ref(&ordinary.id),
7351 std::slice::from_ref(&ordinary),
7352 );
7353 assert_eq!(next, Interrupt::Idle);
7354 }
7355
7356 #[test]
7357 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7358 let marked = interrupt_task("marked");
7361 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7362 assert_eq!(next, Interrupt::Idle);
7363 }
7364
7365 #[test]
7366 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7367 let marked = interrupt_task("marked");
7368 let next = advance_interrupt(
7369 Interrupt::Idle,
7370 &["running".to_owned()],
7371 std::slice::from_ref(&marked),
7372 );
7373 assert_eq!(
7374 next,
7375 Interrupt::Parking {
7376 parked: vec!["running".to_owned()],
7377 interrupt_task: "marked".to_owned(),
7378 }
7379 );
7380 }
7381
7382 #[test]
7391 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7392 let marked = interrupt_task("marked");
7393
7394 let two = advance_interrupt(
7395 Interrupt::Idle,
7396 &["a".to_owned(), "b".to_owned()],
7397 std::slice::from_ref(&marked),
7398 );
7399 assert_eq!(two, Interrupt::Idle);
7400
7401 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7402 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7403 }
7404
7405 #[test]
7406 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7407 let state = Interrupt::Parking {
7408 parked: vec!["running".to_owned()],
7409 interrupt_task: "marked".to_owned(),
7410 };
7411 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7413 assert_eq!(still_going, state);
7414
7415 let stopped_but_not_yet_dispatched =
7419 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7420 assert_eq!(stopped_but_not_yet_dispatched, state);
7421
7422 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7424 assert_eq!(
7425 dispatched,
7426 Interrupt::Running {
7427 parked: vec!["running".to_owned()],
7428 interrupt_task: "marked".to_owned(),
7429 }
7430 );
7431 }
7432
7433 #[test]
7434 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7435 let state = Interrupt::Running {
7436 parked: vec!["running".to_owned()],
7437 interrupt_task: "marked".to_owned(),
7438 };
7439 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7440 assert_eq!(still_running, state);
7441
7442 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7449 assert_eq!(
7450 ended,
7451 Interrupt::Resuming {
7452 parked: vec!["running".to_owned()]
7453 }
7454 );
7455 }
7456
7457 #[test]
7458 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7459 let state = Interrupt::Resuming {
7460 parked: vec!["running".to_owned()],
7461 };
7462 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7463 assert_eq!(still_waiting, state);
7464
7465 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7466 assert_eq!(dispatched, Interrupt::Idle);
7467 }
7468
7469 #[test]
7475 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7476 {
7477 let state = Interrupt::Parking {
7478 parked: vec!["running".to_owned()],
7479 interrupt_task: "marked".to_owned(),
7480 };
7481 let next = advance_interrupt(state, &[], &[]);
7484 assert_eq!(
7485 next,
7486 Interrupt::Resuming {
7487 parked: vec!["running".to_owned()]
7488 },
7489 "abandoning the interrupt must not abandon the resume it owes"
7490 );
7491 }
7492
7493 #[test]
7496 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7497 let state = Interrupt::Resuming {
7498 parked: vec!["running".to_owned()],
7499 };
7500 let next = advance_interrupt(state, &[], &[]);
7501 assert_eq!(
7502 next,
7503 Interrupt::Idle,
7504 "nothing is left to wait for; the loop must not stay wedged"
7505 );
7506 }
7507
7508 #[test]
7509 fn disabled_by_config_the_sequence_can_never_leave_idle() {
7510 let marked = interrupt_task("marked");
7511 let next = advance_interrupt_tick(
7512 false,
7513 Interrupt::Idle,
7514 &["running".to_owned()],
7515 std::slice::from_ref(&marked),
7516 );
7517 assert_eq!(
7518 next,
7519 Interrupt::Idle,
7520 "an unmarked, unconfigured daemon must behave exactly as before"
7521 );
7522 }
7523
7524 #[test]
7525 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7526 let state = Interrupt::Parking {
7527 parked: vec!["running".to_owned()],
7528 interrupt_task: "marked".to_owned(),
7529 };
7530 let candidates = vec![interrupt_task("marked"), task()];
7531 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7532 assert!(
7533 allowed.is_empty(),
7534 "nothing may dispatch - not even the interrupt task itself - \
7535 until the parked run has actually stopped"
7536 );
7537 }
7538
7539 #[test]
7553 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7554 for state in [
7555 Interrupt::Parking {
7556 parked: vec!["running".to_owned()],
7557 interrupt_task: "marked".to_owned(),
7558 },
7559 Interrupt::Running {
7560 parked: vec!["running".to_owned()],
7561 interrupt_task: "marked".to_owned(),
7562 },
7563 Interrupt::Resuming {
7564 parked: vec!["running".to_owned()],
7565 },
7566 ] {
7567 let candidates = vec![
7568 interrupt_task("marked"),
7569 urgent_task("hot"),
7570 task_with_id("ordinary"),
7571 ];
7572 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7573 assert!(
7574 !allowed.iter().any(|t| t.id == "hot"),
7575 "an urgent candidate must wait out the same gate as anything \
7576 else while the run it would run alongside has not actually \
7577 left flight, for state {state:?}: {allowed:?}"
7578 );
7579 }
7580 }
7581
7582 #[test]
7588 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7589 let state = Interrupt::Resuming {
7590 parked: vec!["hot".to_owned()],
7591 };
7592 let candidates = vec![urgent_task("hot"), task()];
7593 let allowed = interrupt_gate(&state, &[], candidates);
7594 assert_eq!(
7595 allowed.iter().filter(|t| t.id == "hot").count(),
7596 1,
7597 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7598 );
7599 }
7600
7601 #[test]
7602 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7603 let state = Interrupt::Parking {
7604 parked: vec!["running".to_owned()],
7605 interrupt_task: "marked".to_owned(),
7606 };
7607 let other = task();
7608 let candidates = vec![interrupt_task("marked"), other.clone()];
7609 let allowed = interrupt_gate(&state, &[], candidates);
7610 assert_eq!(allowed.len(), 1);
7611 assert_eq!(allowed[0].id, "marked");
7612 }
7613
7614 #[test]
7615 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7616 let state = Interrupt::Running {
7617 parked: vec!["running".to_owned()],
7618 interrupt_task: "marked".to_owned(),
7619 };
7620 let candidates = vec![task(), task()];
7621 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7622 assert!(allowed.is_empty());
7623 }
7624
7625 #[test]
7632 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7633 let state = Interrupt::Resuming {
7634 parked: vec!["a".to_owned(), "c".to_owned()],
7635 };
7636 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7637 let allowed = interrupt_gate(&state, &[], candidates);
7638 assert_eq!(
7639 allowed.len(),
7640 1,
7641 "at most one candidate may be offered while resuming: {allowed:?}"
7642 );
7643 assert_eq!(allowed[0].id, "a");
7644 }
7645
7646 #[test]
7647 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7648 let state = Interrupt::Resuming {
7649 parked: vec!["a".to_owned()],
7650 };
7651 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7652 assert!(allowed.is_empty());
7653 }
7654
7655 #[test]
7661 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7662 let running = task(); let marked = interrupt_task("marked");
7664
7665 let mut state = Interrupt::Idle;
7666 let in_flight = vec![running.id.clone()];
7668 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7669 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7670 assert!(gated.is_empty(), "still waiting on `running` to park");
7671
7672 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7674 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7675 assert_eq!(
7676 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7677 vec!["marked"],
7678 "only the interrupt task may be offered to the dispatcher now"
7679 );
7680
7681 state = advance_interrupt_tick(
7683 true,
7684 state,
7685 &["marked".to_owned()],
7686 std::slice::from_ref(&running),
7687 );
7688 let gated = interrupt_gate(
7689 &state,
7690 &["marked".to_owned()],
7691 vec![marked.clone(), running.clone()],
7692 );
7693 assert!(
7694 gated.is_empty(),
7695 "the parked run must not be offered back while the interrupt \
7696 task is still running"
7697 );
7698
7699 let other = task_with_id("other");
7703 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7704 assert_eq!(
7705 state,
7706 Interrupt::Resuming {
7707 parked: vec![running.id.clone()]
7708 }
7709 );
7710 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7711 assert_eq!(
7712 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7713 vec![running.id.as_str()],
7714 "exactly the parked run resumes - not the unrelated task, even \
7715 though it was offered first"
7716 );
7717
7718 state = advance_interrupt_tick(
7722 true,
7723 state,
7724 std::slice::from_ref(&running.id),
7725 std::slice::from_ref(&other),
7726 );
7727 assert_eq!(state, Interrupt::Idle);
7728 let gated = interrupt_gate(
7729 &state,
7730 std::slice::from_ref(&running.id),
7731 vec![other.clone()],
7732 );
7733 assert_eq!(
7734 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7735 vec![other.id.as_str()],
7736 "ordinary dispatch is unrestricted again"
7737 );
7738 }
7739
7740 #[test]
7741 fn every_run_status_settles_the_task_it_came_from() {
7742 let table = [
7744 (RunStatus::Merged, TaskStatus::Done, 1),
7745 (RunStatus::Ready, TaskStatus::Done, 1),
7746 (RunStatus::Stalled, TaskStatus::Failed, 0),
7747 (RunStatus::Blocked, TaskStatus::Failed, 1),
7748 (RunStatus::Failed, TaskStatus::Failed, 1),
7749 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7750 (RunStatus::Prep, TaskStatus::Failed, 1),
7751 (RunStatus::Implementing, TaskStatus::Failed, 1),
7752 (RunStatus::Judging, TaskStatus::Failed, 1),
7753 (RunStatus::Deliberating, TaskStatus::Failed, 1),
7754 (RunStatus::Voting, TaskStatus::Failed, 1),
7755 (RunStatus::Reviewing, TaskStatus::Failed, 1),
7756 (RunStatus::Gating, TaskStatus::Failed, 1),
7757 ];
7758 for (run, want, attempts) in table {
7759 let mut t = task();
7760 t.start("20260902-000000-aaaa".to_owned());
7761 settle(
7762 &mut t,
7763 Verdict {
7764 status: run,
7765 left_pr: false,
7766 parked: false,
7767 quota_hit: matches!(run, RunStatus::Stalled),
7768 no_viable_candidates: false,
7769 },
7770 "why",
7771 2,
7772 );
7773 assert_eq!(t.status, want, "task status after {}", label(run));
7774 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7775 }
7776 }
7777
7778 #[test]
7779 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7780 let mut stalled = task();
7781 stalled.start("20260902-000000-aaaa".to_owned());
7782 settle(
7783 &mut stalled,
7784 Verdict {
7785 status: RunStatus::Stalled,
7786 left_pr: false,
7787 parked: false,
7788 quota_hit: true,
7789 no_viable_candidates: false,
7790 },
7791 "quota",
7792 1,
7793 );
7794 assert_eq!(stalled.attempts, 0);
7795 assert!(
7796 stalled.status.runnable(),
7797 "a machine problem must leave the task in line"
7798 );
7799
7800 let mut blocked = task();
7801 blocked.start("20260902-000000-aaaa".to_owned());
7802 settle(
7803 &mut blocked,
7804 Verdict {
7805 status: RunStatus::Blocked,
7806 left_pr: false,
7807 parked: false,
7808 quota_hit: false,
7809 no_viable_candidates: false,
7810 },
7811 "findings open",
7812 1,
7813 );
7814 assert_eq!(blocked.attempts, 1);
7815 assert_eq!(
7816 blocked.status,
7817 TaskStatus::Held,
7818 "the last attempt hands the task to a human"
7819 );
7820 }
7821
7822 #[test]
7823 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7824 let mut delivered = task();
7827 delivered.start("20260903-080619-01c2".to_owned());
7828 settle(
7829 &mut delivered,
7830 Verdict {
7831 status: RunStatus::Blocked,
7832 left_pr: true,
7833 parked: false,
7834 quota_hit: false,
7835 no_viable_candidates: false,
7836 },
7837 "no check status",
7838 4,
7839 );
7840 assert_eq!(
7841 delivered.status,
7842 TaskStatus::Held,
7843 "a pull request waiting on CI or a person is not a retryable failure"
7844 );
7845 assert!(
7846 !delivered.status.runnable(),
7847 "the loop must not pick this task up again"
7848 );
7849 assert_eq!(
7850 delivered.last_error.as_deref(),
7851 Some("no check status"),
7852 "the operator needs to be told what the gate was waiting for"
7853 );
7854
7855 let mut empty_handed = task();
7858 empty_handed.start("20260903-080619-01c2".to_owned());
7859 settle(
7860 &mut empty_handed,
7861 Verdict {
7862 status: RunStatus::Blocked,
7863 left_pr: false,
7864 parked: false,
7865 quota_hit: false,
7866 no_viable_candidates: false,
7867 },
7868 "findings open",
7869 4,
7870 );
7871 assert_eq!(empty_handed.status, TaskStatus::Failed);
7872 assert!(empty_handed.status.runnable());
7873 }
7874
7875 #[test]
7876 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7877 let mut noop = task();
7883 noop.start("20260912-131304-391f".to_owned());
7884 settle(
7885 &mut noop,
7886 Verdict {
7887 status: RunStatus::VerifiedNoop,
7888 left_pr: false,
7889 parked: false,
7890 quota_hit: false,
7891 no_viable_candidates: true,
7892 },
7893 "candidate A: already fixed by b32cfc4, on main",
7894 4,
7895 );
7896 assert_eq!(
7897 noop.status,
7898 TaskStatus::Held,
7899 "an unverified claim is a request for a human, not a failure"
7900 );
7901 assert!(
7902 !noop.status.runnable(),
7903 "the loop must not requeue this on the same unverified claim"
7904 );
7905 assert_eq!(noop.attempts, 1);
7910 }
7911
7912 #[test]
7913 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7914 let mut parked = task();
7919 parked.start("20260903-183634-2d98".to_owned());
7920 settle(
7921 &mut parked,
7922 Verdict {
7923 status: RunStatus::Implementing,
7924 left_pr: false,
7925 quota_hit: false,
7926 parked: true,
7927 no_viable_candidates: false,
7928 },
7929 "parked after `implementing`",
7930 2,
7931 );
7932 assert_eq!(parked.attempts, 0, "a park is refunded");
7933 assert!(
7934 parked.status.runnable(),
7935 "and the task stays in line so the next loop resumes its run"
7936 );
7937 assert_eq!(parked.status, TaskStatus::Parked);
7938 assert_eq!(
7939 parked.park_reason.as_deref(),
7940 Some("parked after `implementing`"),
7941 "the card says where it stopped"
7942 );
7943 assert_eq!(parked.last_error, None, "nothing failed");
7944
7945 let mut broken = task();
7949 broken.start("20260903-183634-2d98".to_owned());
7950 settle(
7951 &mut broken,
7952 Verdict {
7953 status: RunStatus::Implementing,
7954 left_pr: false,
7955 quota_hit: false,
7956 parked: false,
7957 no_viable_candidates: false,
7958 },
7959 "returned mid-flight",
7960 2,
7961 );
7962 assert_eq!(broken.attempts, 1);
7963 }
7964
7965 #[test]
7966 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7967 let mut flaky = task();
7972 flaky.start("20260903-123023-e633".to_owned());
7973 settle(
7974 &mut flaky,
7975 Verdict {
7976 status: RunStatus::Stalled,
7977 left_pr: false,
7978 parked: false,
7979 quota_hit: false,
7980 no_viable_candidates: false,
7981 },
7982 "verdict rests on 1 of 3 judges",
7983 2,
7984 );
7985 assert_eq!(
7986 flaky.attempts, 1,
7987 "flakiness spends an attempt, so `max_attempts` still bounds it"
7988 );
7989 assert!(flaky.status.runnable(), "and it is still worth retrying");
7990
7991 let mut limited = task();
7993 limited.start("20260903-123023-e633".to_owned());
7994 settle(
7995 &mut limited,
7996 Verdict {
7997 status: RunStatus::Stalled,
7998 left_pr: false,
7999 parked: false,
8000 quota_hit: true,
8001 no_viable_candidates: false,
8002 },
8003 "judge-2, judge-3 out of quota",
8004 2,
8005 );
8006 assert_eq!(limited.attempts, 0, "a quota window is refunded");
8007 assert!(limited.status.runnable());
8008
8009 let mut worn = task();
8012 for _ in 0..2 {
8013 worn.release();
8014 }
8015 worn.start("20260903-123023-e633".to_owned());
8016 worn.attempts = 2;
8017 settle(
8018 &mut worn,
8019 Verdict {
8020 status: RunStatus::Stalled,
8021 left_pr: false,
8022 parked: false,
8023 quota_hit: false,
8024 no_viable_candidates: false,
8025 },
8026 "no quorum again",
8027 2,
8028 );
8029 assert_eq!(worn.status, TaskStatus::Held);
8030 assert!(!worn.status.runnable());
8031 }
8032
8033 #[test]
8034 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8035 let mut wiped_out = task();
8042 wiped_out.start("20260907-025000-a1b2".to_owned());
8043 settle(
8044 &mut wiped_out,
8045 Verdict {
8046 status: RunStatus::Failed,
8047 left_pr: false,
8048 parked: false,
8049 quota_hit: true,
8050 no_viable_candidates: true,
8051 },
8052 "no candidate produced a change; nothing to judge",
8053 2,
8054 );
8055 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8056 assert!(
8057 wiped_out.status.runnable(),
8058 "a machine problem must leave the task in line"
8059 );
8060
8061 let mut partial_progress = task();
8067 partial_progress.start("20260907-025500-c3d4".to_owned());
8068 settle(
8069 &mut partial_progress,
8070 Verdict {
8071 status: RunStatus::Failed,
8072 left_pr: false,
8073 parked: false,
8074 quota_hit: true,
8075 no_viable_candidates: false,
8076 },
8077 "gate failed on the winning candidate",
8078 2,
8079 );
8080 assert_eq!(
8081 partial_progress.attempts, 1,
8082 "a candidate that actually produced a change spends the attempt \
8083 even though some other seat hit its quota"
8084 );
8085 assert!(partial_progress.status.runnable());
8086 }
8087
8088 #[test]
8089 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8090 let mut t = task();
8096 t.start("20260907-025000-a1b2".to_owned());
8097 let mut state = run_state(RunStatus::Failed);
8098 state.quota.push(QuotaLoss {
8099 cause: crate::agent::QuotaCause::UsageLimit,
8100 agent: String::new(),
8101 seat: "cand-a".to_owned(),
8102 node: "implement".to_owned(),
8103 at: Timestamp::now(),
8104 reset: None,
8105 });
8106 assert!(
8107 state.viable().is_empty(),
8108 "no candidate was added, so nothing is viable"
8109 );
8110 reclaim(&mut t, Some(state), 2, "en");
8111 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8112 assert!(t.status.runnable());
8113 }
8114
8115 #[test]
8116 fn a_held_task_is_never_offered_to_the_loop() {
8117 let dir = tempfile::tempdir().unwrap();
8118 let queue = Queue::at(dir.path().to_path_buf());
8119 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8120 let mut t = task();
8121 t.id = format!("2026090{n}-000000-000{n}");
8122 t.priority = priority;
8123 queue.put(&mut t).unwrap();
8124 }
8125 let mut held = task();
8126 held.id = "20260909-000000-9999".to_owned();
8127 held.priority = 99;
8128 held.hold_machine(None);
8129 queue.put(&mut held).unwrap();
8130
8131 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8132 assert_eq!(order.len(), 3);
8133 assert!(!order.contains(&held.id));
8134 assert_eq!(
8135 order.first().cloned(),
8136 queue.next_runnable().map(|t| t.id),
8137 "the loop's first candidate is exactly what the queue offers"
8138 );
8139 assert_eq!(
8140 order,
8141 vec![
8142 "20260902-000000-0002".to_owned(),
8143 "20260903-000000-0003".to_owned(),
8144 "20260901-000000-0001".to_owned(),
8145 ],
8146 "priority first, then oldest, so nothing starves"
8147 );
8148 }
8149
8150 #[test]
8151 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8152 let dir = tempfile::tempdir().unwrap();
8153 let queue = Queue::at(dir.path().to_path_buf());
8154 let mut old = task();
8155 old.id = "20260101-000000-old0".to_owned();
8156 queue.put(&mut old).unwrap();
8157 let mut fresh = task();
8158 fresh.id = "20260101-000000-new0".to_owned();
8159 queue.put(&mut fresh).unwrap();
8160
8161 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8165 std::thread::sleep(Duration::from_millis(60));
8166 let live = queue.claim(&fresh.id).unwrap();
8167
8168 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8169 assert_eq!(swept, vec![old.id.clone()]);
8170 assert!(
8171 queue.claim(&old.id).is_ok(),
8172 "an unparseable lock older than the threshold is swept"
8173 );
8174 assert!(
8175 queue.claim(&fresh.id).is_err(),
8176 "a live pid protects its lock regardless of age"
8177 );
8178 drop(live);
8179 }
8180
8181 #[test]
8182 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8183 let dir = tempfile::tempdir().unwrap();
8186 let queue = Queue::at(dir.path().to_path_buf());
8187 let mut t = task();
8188 t.id = "20260101-000000-live".to_owned();
8189 queue.put(&mut t).unwrap();
8190
8191 let claim = queue.claim(&t.id).unwrap();
8192 std::thread::sleep(Duration::from_millis(60));
8193
8194 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8195 assert!(
8196 swept.is_empty(),
8197 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8198 );
8199 assert!(
8200 queue.claim(&t.id).is_err(),
8201 "the lock still protects its task"
8202 );
8203 drop(claim);
8204 }
8205
8206 fn injected_dead_pid() -> u32 {
8209 std::process::id().checked_add(1).unwrap_or(1)
8210 }
8211
8212 #[test]
8213 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8214 let dir = tempfile::tempdir().unwrap();
8215 let queue = Queue::at(dir.path().to_path_buf());
8216 let mut t = task();
8217 t.id = "20260101-000000-dead".to_owned();
8218 queue.put(&mut t).unwrap();
8219 let dead_pid = injected_dead_pid();
8220
8221 std::fs::write(
8226 dir.path().join(format!("{}.lock", t.id)),
8227 dead_pid.to_string(),
8228 )
8229 .unwrap();
8230
8231 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8232 pid != dead_pid
8233 });
8234 assert_eq!(
8235 swept,
8236 vec![t.id.clone()],
8237 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8238 );
8239 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8240 }
8241
8242 #[test]
8243 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8244 let dir = tempfile::tempdir().unwrap();
8245 let queue = Queue::at(dir.path().to_path_buf());
8246 let mut t = task();
8247 t.id = "20260101-000000-late".to_owned();
8248 queue.put(&mut t).unwrap();
8249 let dead_pid = injected_dead_pid();
8250
8251 assert!(
8254 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8255 "nothing has claimed the task yet"
8256 );
8257
8258 std::fs::write(
8261 dir.path().join(format!("{}.lock", t.id)),
8262 dead_pid.to_string(),
8263 )
8264 .unwrap();
8265
8266 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8270 pid != dead_pid
8271 });
8272 assert_eq!(swept, vec![t.id.clone()]);
8273 }
8274
8275 #[test]
8276 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8277 crate::run::pin_test_home();
8282 let dir = tempfile::tempdir().unwrap();
8283 let queue = Queue::at(dir.path().to_path_buf());
8284 let mut t = task();
8285 t.id = "20260101-000000-crsh".to_owned();
8286 t.status = TaskStatus::Running;
8287 t.attempts = 1;
8288 t.runs.push("20260904-000000-4043".to_owned());
8292 queue.put(&mut t).unwrap();
8293 let dead_pid = injected_dead_pid();
8294
8295 std::fs::write(
8298 dir.path().join(format!("{}.lock", t.id)),
8299 dead_pid.to_string(),
8300 )
8301 .unwrap();
8302
8303 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8309 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8310
8311 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8312 pid != dead_pid
8313 });
8314 assert_eq!(swept, vec![t.id.clone()]);
8315
8316 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8317 assert_eq!(reclaimed, vec![t.id.clone()]);
8318 let after = queue.get(&t.id).unwrap();
8319 assert_eq!(
8320 after.status,
8321 TaskStatus::Held,
8322 "no run.json to recover from, so a human is asked"
8323 );
8324 assert_eq!(
8325 after.runs,
8326 vec!["20260904-000000-4043".to_owned()],
8327 "the crashed run's id is kept as evidence, not discarded"
8328 );
8329 }
8330
8331 #[test]
8332 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8333 let dir = tempfile::tempdir().unwrap();
8334 let queue = Queue::at(dir.path().to_path_buf());
8335 let mut t = task();
8336 t.id = "20260101-000000-unknown".to_owned();
8337 queue.put(&mut t).unwrap();
8338 let dead_pid = injected_dead_pid();
8339 std::fs::write(
8340 dir.path().join(format!("{}.lock", t.id)),
8341 dead_pid.to_string(),
8342 )
8343 .unwrap();
8344
8345 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8346 assert!(swept.is_empty(), "an unknown pid must keep its lock");
8347 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8348 }
8349
8350 fn run_state_in(status: RunStatus, language: &str) -> RunState {
8351 let mut s = run_state(status);
8352 s.config.graph.language = language.to_owned();
8353 s
8354 }
8355
8356 fn unstarted_verdict(status: RunStatus) -> Verdict {
8357 Verdict {
8358 status,
8359 left_pr: false,
8360 quota_hit: false,
8361 parked: false,
8362 no_viable_candidates: false,
8363 }
8364 }
8365
8366 #[test]
8367 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8368 let mut t = task();
8369 t.attempts = 1;
8370 settle_in(
8371 &mut t,
8372 unstarted_verdict(RunStatus::AlreadyInBase),
8373 "already in main",
8374 1,
8375 phrases("en"),
8376 );
8377 assert_eq!(t.status, TaskStatus::Done);
8378 assert_eq!(t.attempts, 0);
8379 }
8380
8381 #[test]
8382 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8383 let reason = |language: &str| {
8384 let mut t = task();
8385 settle_in(
8386 &mut t,
8387 unstarted_verdict(RunStatus::Judging),
8388 "boom",
8389 1,
8390 phrases(language),
8391 );
8392 t.last_error.or(t.hold_reason).unwrap_or_default()
8393 };
8394 assert!(
8395 reason("en").starts_with("the graph stopped at `"),
8396 "{}",
8397 reason("en")
8398 );
8399 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8400 assert!(reason("日本語").contains("boom"));
8401 assert_eq!(reason("fr"), reason("en"));
8402 }
8403
8404 #[test]
8405 fn describe_follows_the_run_language_and_keeps_the_run_id() {
8406 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8407 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8408 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8409 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8410 assert!(ja.contains("[run "), "{ja}");
8411 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8412 assert!(ended.starts_with("run 終了: "), "{ended}");
8413 let mut de = run_state_in(RunStatus::Failed, "de");
8414 let mut en = run_state_in(RunStatus::Failed, "en");
8415 de.id = "same".to_owned();
8416 en.id = "same".to_owned();
8417 assert_eq!(describe(&de), describe(&en));
8418 }
8419
8420 #[test]
8421 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8422 use crate::handover::Refused;
8423 let cases = [
8424 Refused::Foreign {
8425 branch: "b".into(),
8426 path: "/w/x".into(),
8427 why: "made by hand".into(),
8428 },
8429 Refused::Unsafe {
8430 branch: "b".into(),
8431 path: "/w/x".into(),
8432 why: "its worktree has uncommitted changes (a.rs)".into(),
8433 },
8434 Refused::ReleaseFailed {
8435 branch: "b".into(),
8436 path: "/w/x".into(),
8437 run: "ab12".into(),
8438 },
8439 ];
8440 for r in &cases {
8441 let en = (phrases("en").handover_refused)(r);
8442 assert_eq!(en, r.to_string());
8443 let ja = (phrases("ja").handover_refused)(r);
8444 assert!(
8445 !ja.contains("is checked out") && !ja.contains("try again"),
8446 "{ja}"
8447 );
8448 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8449 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8450 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8451 }
8452 }
8453 assert!(phrases("en").handover_hint.contains("release the task"));
8454 assert!(phrases("ja").handover_hint.contains("解放"));
8455 }
8456
8457 #[test]
8458 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8459 let build = |lang: &str| {
8460 let mut s = run_state_in(RunStatus::Blocked, lang);
8461 s.id = "same".to_owned();
8462 s.config.graph.review_rounds = 3;
8463 let mut r = review_round(3);
8464 r.expected = 3;
8465 r.answered = 1;
8466 s.reviews.push(r);
8467 s.event(
8468 "review",
8469 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8470 );
8471 s
8472 };
8473 let en = describe(&build("en"));
8474 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8475 let ja = describe(&build("ja"));
8476 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8477 assert!(!ja.contains("never answered"), "{ja}");
8478 assert!(ja.contains("[run "), "{ja}");
8479
8480 let mut failed = build("ja");
8483 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8484 command: "cargo test".to_owned(),
8485 code: Some(1),
8486 output_tail: String::new(),
8487 duration_ms: 0,
8488 resource_blocked: false,
8489 });
8490 failed.event("review", "stopped; e2e failed: cargo test");
8491 let ja = describe(&failed);
8492 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8493 assert!(!ja.contains("席のレビュアー"), "{ja}");
8494 }
8495
8496 #[test]
8497 fn refusals_and_recovery_prose_follow_the_language() {
8498 let home = crate::run::test_home();
8499 let t = held_task_with("r1");
8500 let q = action_question(
8501 "r1",
8502 ask::ChoiceAction::Resume {
8503 run: "r1".to_owned(),
8504 },
8505 );
8506 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8507 ActionDecision::Refuse(s) => s,
8508 other => panic!("{other:?}"),
8509 };
8510 assert!(refuse(phrases("en")).contains("could not be read: gone"));
8511 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8512 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8513
8514 let mut held = task();
8515 reclaim(&mut held, None, 2, "ja");
8516 assert!(held.hold_reason.unwrap().contains("保留にしました"));
8517 let mut held = task();
8518 reclaim(&mut held, None, 2, "xx");
8519 assert!(held.hold_reason.unwrap().contains("held for a human"));
8520 }
8521
8522 fn run_state(status: RunStatus) -> RunState {
8523 let mut state = RunState::new(
8524 PathBuf::from("/repo"),
8525 "main".to_owned(),
8526 "abc1234def".to_owned(),
8527 "add retries".to_owned(),
8528 Config::default(),
8529 );
8530 state.status = status;
8531 state
8532 }
8533
8534 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8535 Candidate {
8536 index: 0,
8537 label,
8538 agent: "claude".to_owned(),
8539 branch: format!("magi/x/{label}"),
8540 worktree: PathBuf::from("/repo"),
8541 summary: summary.to_owned(),
8542 stat: String::new(),
8543 files: 0,
8544 commits: usize::from(!empty),
8545 empty,
8546 failed: failed.map(str::to_owned),
8547 verified_noop: None,
8548 duration_ms: 0,
8549 folded: false,
8550 }
8551 }
8552
8553 #[test]
8554 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8555 let mut state = run_state(RunStatus::Blocked);
8556 state.gate = vec![
8557 CommandOutcome {
8558 command: "cargo make check".to_owned(),
8559 code: Some(0),
8560 output_tail: "ok".to_owned(),
8561 duration_ms: 0,
8562 resource_blocked: false,
8563 },
8564 CommandOutcome {
8565 command: "cargo test".to_owned(),
8566 code: Some(101),
8567 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8568 duration_ms: 0,
8569 resource_blocked: false,
8570 },
8571 ];
8572 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8573 assert!(d.contains("cargo test"), "{d}");
8574 assert!(
8575 !d.contains("cargo make check"),
8576 "a passing check is not a diagnostic: {d}"
8577 );
8578 assert!(d.contains("assertion failed"), "{d}");
8579 }
8580
8581 #[test]
8582 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8583 let mut state = run_state(RunStatus::Blocked);
8584 state.event(
8585 "land",
8586 "stopped: the fixer produced no commit while 2 check(s) were failing \
8587 (build, lint); stopping instead of looping on an unchanged tree",
8588 );
8589 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8590 assert!(d.contains("build"), "{d}");
8591 assert!(d.contains("lint"), "{d}");
8592 assert!(d.contains("fixer produced no commit"), "{d}");
8593 }
8594
8595 #[test]
8596 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8597 let state = run_state(RunStatus::VerifiedNoop);
8602 let d = describe(&state);
8603 assert!(
8604 d.contains("agent-verified no-op"),
8605 "expected the display label, not the wire spelling: {d}"
8606 );
8607 assert!(!d.contains("verified_noop"), "{d}");
8608 }
8609
8610 #[test]
8611 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8612 let mut state = run_state(RunStatus::Failed);
8613 state.gate.push(crate::run::CommandOutcome {
8614 command: "cargo test".into(),
8615 code: Some(101),
8616 output_tail: format!(
8617 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8618 " 41: 0x1234 - backtrace frame\n".repeat(10000)
8619 ),
8620 duration_ms: 1,
8621 resource_blocked: false,
8622 });
8623 let d = diagnostic(&state).unwrap();
8624 assert!(d.contains("panicked at widget.rs:12"), "{d}");
8625 assert!(d.contains("assertion failed: widget missing"));
8626 assert!(d.contains("widget log"));
8627 }
8628
8629 #[test]
8630 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8631 let mut state = run_state(RunStatus::Failed);
8637 state.candidates = vec![candidate(
8638 'A',
8639 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8640 true,
8641 None,
8642 )];
8643 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8644 assert!(d.contains("candidate A"), "{d}");
8645 assert!(d.contains("tagged v1.2.3"), "{d}");
8646 }
8647
8648 #[test]
8649 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8650 let mut state = run_state(RunStatus::Failed);
8651 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8652 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8653 assert!(d.contains("candidate A"), "{d}");
8654 assert!(d.contains("agent timed out"), "{d}");
8655 }
8656
8657 #[test]
8658 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8659 let mut state = run_state(RunStatus::Failed);
8662 state.candidates = vec![candidate('A', "did the work", false, None)];
8663 assert!(diagnostic(&state).is_none());
8664 }
8665
8666 #[test]
8667 fn diagnostic_is_bounded_however_much_a_run_printed() {
8668 let mut state = run_state(RunStatus::Blocked);
8669 state.gate = vec![
8670 CommandOutcome {
8671 command: "cargo test".to_owned(),
8672 code: Some(101),
8673 output_tail: "x".repeat(50_000),
8674 duration_ms: 0,
8675 resource_blocked: false,
8676 },
8677 CommandOutcome {
8678 command: "cargo clippy".to_owned(),
8679 code: Some(1),
8680 output_tail: "y".repeat(50_000),
8681 duration_ms: 0,
8682 resource_blocked: false,
8683 },
8684 ];
8685 state.candidates = vec![
8686 candidate('A', &"z".repeat(50_000), true, None),
8687 candidate('B', &"w".repeat(50_000), true, None),
8688 ];
8689 let d = diagnostic(&state).expect("plenty here to diagnose");
8690 assert!(
8691 d.len() <= DIAGNOSTIC_MAX,
8692 "diagnostic grew to {} bytes, unbounded",
8693 d.len()
8694 );
8695 }
8696
8697 #[test]
8698 fn selected_delivery_guards_survive_recovery_failure_accounting() {
8699 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8700 let mut t = task();
8701 let mut state = run_state(status);
8702 t.pr_recovery = Some(crate::pr_recovery::Selection {
8703 url: "url".into(),
8704 branch: format!("magi/task-{}", t.id),
8705 head: "a".repeat(40),
8706 source_head: None,
8707 source_run: None,
8708 source_proof: None,
8709 disposition: Some(crate::pr_recovery::Disposition::Land),
8710 instruction: t.instruction.clone(),
8711 approved_at: Timestamp::now(),
8712 });
8713 state.pr_recovery = t.pr_recovery.clone();
8714 t.start(state.id.clone());
8715 settle_and_diagnose(
8716 &mut t,
8717 Verdict {
8718 status,
8719 left_pr: false,
8720 quota_hit: false,
8721 parked: false,
8722 no_viable_candidates: false,
8723 },
8724 "delivery stopped",
8725 5,
8726 &state,
8727 );
8728 assert_eq!(t.status, TaskStatus::Held);
8729 let reason = t.hold_reason.as_deref().unwrap();
8730 if status == RunStatus::Ready {
8731 assert!(reason.contains("Selected PR delivery is incomplete"));
8732 assert!(t.recovery_budget.is_none());
8733 } else {
8734 assert!(reason.contains("Selected recovery stopped"));
8735 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8736 }
8737 assert!(t.pr_recovery.is_some());
8738 }
8739 }
8740
8741 #[test]
8742 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8743 let mut state = run_state(RunStatus::Voting);
8744 state.base_sync = Some(crate::run::BaseSync {
8745 tip: "base-tip".into(),
8746 behind: 3,
8747 attempts: 4,
8748 conflict: Some("base stopped".into()),
8749 already_in: None,
8750 });
8751 state.record_base_sync_stop("candidate-head");
8752 let mut t = task();
8753 t.start(state.id.clone());
8754 let verdict = Verdict {
8755 status: RunStatus::Blocked,
8756 left_pr: false,
8757 quota_hit: false,
8758 parked: false,
8759 no_viable_candidates: false,
8760 };
8761 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8762 assert_eq!(
8763 t.status,
8764 TaskStatus::Held,
8765 "unspent task attempts cannot start another competition"
8766 );
8767 let at = t.held_at;
8768 let cause = t.hold_notice_cause.clone();
8769 state.begin_pass();
8770 t.release_operator("test-resume", None);
8771 t.start(state.id.clone());
8772 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8773 assert_eq!(t.status, TaskStatus::Held);
8774 assert_eq!(t.held_at, at);
8775 assert_eq!(t.hold_notice_cause, cause);
8776 }
8777
8778 #[test]
8779 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8780 let mut state = run_state(RunStatus::Blocked);
8781 state.gate = vec![CommandOutcome {
8782 command: "cargo test".to_owned(),
8783 code: Some(101),
8784 output_tail: "assertion failed".to_owned(),
8785 duration_ms: 0,
8786 resource_blocked: false,
8787 }];
8788 let verdict = Verdict {
8789 status: RunStatus::Blocked,
8790 left_pr: false,
8791 quota_hit: false,
8792 parked: false,
8793 no_viable_candidates: false,
8794 };
8795
8796 let mut t = task();
8799 t.start("run-1".to_owned());
8800 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8801 assert_eq!(t.status, TaskStatus::Failed);
8802 assert!(t.diagnostic.is_none());
8803
8804 t.start("run-2".to_owned());
8807 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8808 assert_eq!(t.status, TaskStatus::Held);
8809 let d = t.diagnostic.expect("a held task must carry its diagnostic");
8810 assert!(d.contains("cargo test"), "{d}");
8811 }
8812
8813 #[test]
8814 fn a_held_task_names_the_open_question_it_is_waiting_on() {
8815 crate::run::pin_test_home();
8820 let home = crate::run::home();
8821 let state = run_state(RunStatus::VerifiedNoop);
8822 let mut q = ask::Question::new(
8823 state.id.clone(),
8824 "implement".to_owned(),
8825 "impl-A".to_owned(),
8826 "is this really a no-op?".to_owned(),
8827 String::new(),
8828 Vec::new(),
8829 );
8830 Questions::at(home.join("questions")).put(&mut q).unwrap();
8831
8832 let verdict = Verdict {
8833 status: RunStatus::VerifiedNoop,
8834 left_pr: false,
8835 quota_hit: false,
8836 parked: false,
8837 no_viable_candidates: false,
8838 };
8839 let mut t = task();
8840 t.start(state.id.clone());
8841 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8842
8843 assert_eq!(t.status, TaskStatus::Held);
8844 let reason = t.hold_reason.expect("a held task must record why");
8845 assert!(
8846 reason.starts_with("run ended agent-verified no-op"),
8847 "the original settle reason must survive unchanged: {reason}"
8848 );
8849 assert!(
8850 reason.contains(q.short()),
8851 "the open question's id must be named so the notice is actionable: {reason}"
8852 );
8853 }
8854
8855 #[test]
8856 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8857 crate::run::pin_test_home();
8858 let state = run_state(RunStatus::VerifiedNoop);
8859
8860 let verdict = Verdict {
8861 status: RunStatus::VerifiedNoop,
8862 left_pr: false,
8863 quota_hit: false,
8864 parked: false,
8865 no_viable_candidates: false,
8866 };
8867 let mut t = task();
8868 t.start(state.id.clone());
8869 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8870
8871 assert_eq!(t.status, TaskStatus::Held);
8872 assert_eq!(
8873 t.hold_reason.as_deref(),
8874 Some("run ended agent-verified no-op"),
8875 "nothing to append when the question was already answered or never asked"
8876 );
8877 }
8878
8879 #[test]
8880 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8881 crate::run::pin_test_home();
8882 let mut first = run_state(RunStatus::Blocked);
8883 first.id = "20260101-000000-sup1".to_owned();
8884 first.save().unwrap();
8885 let mut second = run_state(RunStatus::Merged);
8886 second.id = "20260101-000000-sup2".to_owned();
8887 second.save().unwrap();
8888
8889 let mut t = task();
8890 t.runs = vec![first.id.clone(), second.id.clone()];
8891 t.status = TaskStatus::Done;
8892
8893 supersede_prior_runs(&t, &crate::run::home());
8894
8895 assert_eq!(
8896 RunState::load(&first.id).unwrap().status,
8897 RunStatus::Superseded,
8898 "the first attempt's Blocked no longer needs anyone's attention"
8899 );
8900 assert_eq!(
8901 RunState::load(&second.id).unwrap().status,
8902 RunStatus::Merged,
8903 "the run that actually succeeded is left exactly as it was"
8904 );
8905 }
8906
8907 #[test]
8908 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8909 crate::run::pin_test_home();
8915 let mut first = run_state(RunStatus::Blocked);
8916 first.id = "20260101-000000-sup9".to_owned();
8917 first.driver_pid = Some(std::process::id());
8920 first.driver_started_at = Some(
8921 crate::proc::process_started_at(std::process::id())
8922 .expect("this test process's own start time must be queryable"),
8923 );
8924 first.save().unwrap();
8925 let mut second = run_state(RunStatus::Merged);
8926 second.id = "20260101-000000-supa".to_owned();
8927 second.save().unwrap();
8928
8929 let mut t = task();
8930 t.runs = vec![first.id.clone(), second.id.clone()];
8931 t.status = TaskStatus::Done;
8932
8933 supersede_prior_runs(&t, &crate::run::home());
8934
8935 assert_eq!(
8936 RunState::load(&first.id).unwrap().status,
8937 RunStatus::Blocked,
8938 "a live driver_pid means something is still actually working this run, \
8939 even though no daemon claims it - rewriting under it would just be \
8940 undone the next time that process saves"
8941 );
8942 }
8943
8944 #[test]
8945 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8946 let dir = tempfile::tempdir().unwrap();
8952 let home = dir.path().to_path_buf();
8953 let queue = Queue::at(dir.path().join("queue"));
8954
8955 let mut first = run_state(RunStatus::Blocked);
8956 first.id = "20260101-000000-supd".to_owned();
8957 first.driver_pid = Some(std::process::id());
8958 first.driver_started_at = Some(
8959 crate::proc::process_started_at(std::process::id())
8960 .expect("this test process's own start time must be queryable"),
8961 );
8962 first.save_under(&home).unwrap();
8963 let mut second = run_state(RunStatus::Merged);
8964 second.id = "20260101-000000-supe".to_owned();
8965 second.save_under(&home).unwrap();
8966
8967 let mut t = task();
8968 t.runs = vec![first.id.clone(), second.id.clone()];
8969 t.status = TaskStatus::Done;
8970 queue.put(&mut t).unwrap();
8971
8972 resweep_superseded_attempts(&queue, &home);
8973 assert_eq!(
8974 RunState::load_under(&first.id, &home).unwrap().status,
8975 RunStatus::Blocked,
8976 "still live on the first pass, so still untouched"
8977 );
8978
8979 let mut stale = RunState::load_under(&first.id, &home).unwrap();
8985 stale.driver_started_at = Some("1".to_owned());
8986 stale.save_under(&home).unwrap();
8987
8988 resweep_superseded_attempts(&queue, &home);
8989 assert_eq!(
8990 RunState::load_under(&first.id, &home).unwrap().status,
8991 RunStatus::Superseded,
8992 "the second pass catches up what the first one correctly skipped"
8993 );
8994 }
8995
8996 #[test]
8997 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8998 crate::run::pin_test_home();
8999 let mut first = run_state(RunStatus::Blocked);
9000 first.id = "20260101-000000-sup3".to_owned();
9001 first.save().unwrap();
9002 let mut second = run_state(RunStatus::Blocked);
9003 second.id = "20260101-000000-sup4".to_owned();
9004 second.save().unwrap();
9005
9006 let mut t = task();
9007 t.runs = vec![first.id.clone(), second.id.clone()];
9008 t.status = TaskStatus::Failed;
9012
9013 supersede_prior_runs(&t, &crate::run::home());
9014
9015 assert_eq!(
9016 RunState::load(&first.id).unwrap().status,
9017 RunStatus::Blocked
9018 );
9019 assert_eq!(
9020 RunState::load(&second.id).unwrap().status,
9021 RunStatus::Blocked
9022 );
9023 }
9024
9025 #[test]
9026 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9027 crate::run::pin_test_home();
9031 let mut first = run_state(RunStatus::Blocked);
9032 first.id = "20260101-000000-sup5".to_owned();
9033 first.save().unwrap();
9034
9035 let mut t = task();
9036 t.runs = vec![first.id.clone()];
9037 t.status = TaskStatus::Done;
9038
9039 supersede_prior_runs(&t, &crate::run::home());
9040
9041 assert_eq!(
9042 RunState::load(&first.id).unwrap().status,
9043 RunStatus::Blocked,
9044 "a single-attempt task has no earlier run to supersede"
9045 );
9046 }
9047
9048 #[test]
9049 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9050 crate::run::pin_test_home();
9057 let mut first = run_state(RunStatus::Blocked);
9058 first.id = "20260101-000000-supb".to_owned();
9059 first.save().unwrap();
9060 let mut second = run_state(RunStatus::Failed);
9061 second.id = "20260101-000000-supc".to_owned();
9062 second.save().unwrap();
9063
9064 let mut t = task();
9065 t.runs = vec![first.id.clone(), second.id.clone()];
9066 t.status = TaskStatus::Done;
9067
9068 supersede_prior_runs(&t, &crate::run::home());
9069
9070 assert_eq!(
9071 RunState::load(&first.id).unwrap().status,
9072 RunStatus::Blocked,
9073 "the task's last attempt never landed, so there is nothing here \
9074 actually superseding it"
9075 );
9076 }
9077
9078 #[test]
9079 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9080 crate::run::pin_test_home();
9084 let mut failed = run_state(RunStatus::Failed);
9085 failed.id = "20260101-000000-sup6".to_owned();
9086 failed.save().unwrap();
9087 let mut noop = run_state(RunStatus::VerifiedNoop);
9088 noop.id = "20260101-000000-sup7".to_owned();
9089 noop.save().unwrap();
9090 let mut winner = run_state(RunStatus::Ready);
9091 winner.id = "20260101-000000-sup8".to_owned();
9092 winner.save().unwrap();
9093
9094 let mut t = task();
9095 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9096 t.status = TaskStatus::Done;
9097
9098 supersede_prior_runs(&t, &crate::run::home());
9099
9100 assert_eq!(
9101 RunState::load(&failed.id).unwrap().status,
9102 RunStatus::Failed
9103 );
9104 assert_eq!(
9105 RunState::load(&noop.id).unwrap().status,
9106 RunStatus::VerifiedNoop
9107 );
9108 }
9109
9110 fn approval_question(run: &str) -> ask::Question {
9111 ask::Question::new(
9112 run.to_owned(),
9113 land::APPROVAL_NODE.to_owned(),
9114 "land".to_owned(),
9115 "merge?".to_owned(),
9116 String::new(),
9117 vec!["merge".to_owned(), "hold".to_owned()],
9118 )
9119 }
9120
9121 #[test]
9122 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9123 crate::run::pin_test_home();
9124 let mut state = run_state(RunStatus::Landing);
9125 state.id = "20260101-000000-fre1".to_owned();
9126 state.parked = true;
9127 state.save().unwrap();
9128 ask::Questions::open()
9129 .put(&mut approval_question(&state.id))
9130 .unwrap();
9131
9132 let mut t = task();
9133 t.runs.push(state.id.clone());
9134 assert_eq!(
9135 land_resume_state(&t),
9136 LandResume::StillWaiting,
9137 "nobody has answered and the timeout has not passed"
9138 );
9139 }
9140
9141 #[test]
9142 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9143 crate::run::pin_test_home();
9144 let mut state = run_state(RunStatus::Gating);
9145 state.id = "20260101-000000-gt01".to_owned();
9146 state.parked = true;
9147 state.config.graph.answer_timeout = 60;
9148 state.github_text = Some(crate::run::GithubTextAsk {
9149 rewrite: None,
9150 fingerprint: "f".into(),
9151 title: true,
9152 body: false,
9153 categories: vec!["title-language".into()],
9154 question: None,
9155 asks: 1,
9156 resolved: false,
9157 chosen_title: None,
9158 choice: None,
9159 });
9160 state.save().unwrap();
9161 let store = ask::Questions::open();
9162 let mut q = ask::Question::new(
9163 state.id.clone(),
9164 crate::github_text::ASK_NODE.to_owned(),
9165 crate::github_text::ASK_SEAT.to_owned(),
9166 "s".into(),
9167 String::new(),
9168 vec!["use fallback".into()],
9169 );
9170 store.put(&mut q).unwrap();
9171 let mut t = task();
9172 t.runs.push(state.id.clone());
9173 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9174 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9175 store.put(&mut q).unwrap();
9176 assert_eq!(land_resume_state(&t), LandResume::Ready);
9177 assert!(!store.get(&q.id).unwrap().status.open());
9178 state.github_text.as_mut().unwrap().resolved = true;
9180 state.save().unwrap();
9181 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9182 }
9183
9184 #[test]
9185 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9186 crate::run::pin_test_home();
9191 let mut state = run_state(RunStatus::Landing);
9192 state.id = "20260101-000000-exp1".to_owned();
9193 state.parked = true;
9194 state.config.graph.answer_timeout = 60;
9195 state.save().unwrap();
9196
9197 let store = ask::Questions::open();
9198 let mut q = approval_question(&state.id);
9199 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9200 store.put(&mut q).unwrap();
9201
9202 let mut t = task();
9203 t.runs.push(state.id.clone());
9204 assert_eq!(
9205 land_resume_state(&t),
9206 LandResume::Ready,
9207 "an expired question must not be waited on forever"
9208 );
9209
9210 let after = store.get(&q.id).unwrap();
9211 assert!(
9212 !after.status.open(),
9213 "the question is abandoned, not silently ignored"
9214 );
9215 assert!(
9216 after.resolution().is_none(),
9217 "an abandoned question is not read as a decision"
9218 );
9219 }
9220
9221 #[test]
9222 fn reclaim_settles_a_running_task_against_its_last_run() {
9223 let mut t = task();
9224 t.start("20260904-000000-4043".to_owned());
9225 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9226 assert_eq!(
9227 t.status,
9228 TaskStatus::Done,
9229 "a run that actually finished must not stay `running` forever"
9230 );
9231 }
9232
9233 #[test]
9234 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9235 let mut t = task();
9236 t.start("20260904-000000-4043".to_owned());
9237 t.last_error = Some("earlier trouble".to_owned());
9238 let mut state = run_state(RunStatus::Judging);
9239 state.parked = true;
9240 reclaim(&mut t, Some(state), 1, "en");
9241 assert_eq!(t.status, TaskStatus::Parked);
9242 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9243 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9244 assert!(t.park_reason.is_some());
9245 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9246 assert!(!t.fresh_start);
9247 assert!(t.status.runnable());
9248 }
9249
9250 #[test]
9251 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9252 let mut t = task();
9253 t.start("20260904-000000-4043".to_owned());
9254 t.last_error = Some("earlier trouble".to_owned());
9255 settle(
9256 &mut t,
9257 Verdict {
9258 status: RunStatus::Judging,
9259 left_pr: false,
9260 quota_hit: false,
9261 parked: true,
9262 no_viable_candidates: false,
9263 },
9264 "parked after `judging`",
9265 1,
9266 );
9267 assert_eq!(t.status, TaskStatus::Parked);
9268 assert_eq!(t.attempts, 0);
9269 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9270 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9271 assert_eq!(t.schema, crate::queue::SCHEMA);
9272 assert!(
9273 crate::notices::task_held(&t).is_none(),
9274 "a park is not news"
9275 );
9276 t.start("20260904-000000-4043".to_owned());
9277 assert_eq!(t.park_reason, None);
9278 }
9279
9280 #[test]
9281 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9282 let mut t = task();
9286 t.start("20260904-000000-4043".to_owned());
9287 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9288 assert_eq!(t.status, TaskStatus::Failed);
9289 assert!(t.status.runnable());
9290 }
9291
9292 #[test]
9293 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9294 let mut t = task();
9295 t.start("20260904-000000-4043".to_owned());
9296 assert_eq!(t.attempts, 1);
9297 let mut run = run_state(RunStatus::Implementing);
9298 run.id = "20260904-000000-4043".to_owned();
9299 run.begin_pass();
9300 let cause = crate::run::ParkCause::Upgrade {
9301 from: "0.121.0".to_owned(),
9302 to: Some("0.121.1".to_owned()),
9303 };
9304 run.end_pass_parked(cause.clone());
9305 run.parked = true;
9306 let verdict = Verdict {
9307 status: run.status,
9308 left_pr: false,
9309 quota_hit: false,
9310 parked: true,
9311 no_viable_candidates: false,
9312 };
9313 let mut orphan = t.clone();
9316 reclaim(&mut orphan, Some(run.clone()), 2, "en");
9317 assert_eq!(orphan.status, TaskStatus::Parked);
9318 assert_eq!(orphan.attempts, 0);
9319 assert_eq!(
9320 orphan.upgrade_resume_key(),
9321 Some((run.passes[0].started_at, orphan.id.as_str()))
9322 );
9323 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9324 assert_eq!(t.attempts, 0);
9325 assert_eq!(t.passes.len(), 1);
9326 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9327 assert_eq!(t.passes[0].parked, Some(cause));
9328 assert_eq!(t.passes[0].pass_index, 0);
9329 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9330 assert!(t.upgrade_resume_key().is_some());
9331
9332 t.start("20260904-000000-4043".to_owned());
9335 run.begin_pass();
9336 run.status = RunStatus::Failed;
9337 let verdict = Verdict {
9338 status: RunStatus::Failed,
9339 left_pr: false,
9340 quota_hit: false,
9341 parked: false,
9342 no_viable_candidates: false,
9343 };
9344 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9345 assert_eq!(t.passes.len(), 2);
9346 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9347 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9348 assert_eq!(t.passes[1].pass_index, 1);
9349 assert_eq!(t.attempts, 1);
9350 }
9351
9352 #[test]
9353 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9354 let mut t = task();
9355 t.start("20260904-000000-4043".to_owned());
9356 reclaim(&mut t, None, 2, "en");
9357 assert_eq!(t.status, TaskStatus::Held);
9358 assert!(
9359 t.last_error
9360 .as_deref()
9361 .is_some_and(|e| e.contains("running")),
9362 "the operator needs to know why this task was held"
9363 );
9364 }
9365
9366 #[test]
9367 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9368 let dir = tempfile::tempdir().unwrap();
9369 let queue = Queue::at(dir.path().to_path_buf());
9370
9371 let mut orphaned = task();
9373 orphaned.id = "20260904-000000-orph".to_owned();
9374 orphaned.status = TaskStatus::Running;
9375 orphaned.attempts = 1;
9376 queue.put(&mut orphaned).unwrap();
9377
9378 let mut alive = task();
9379 alive.id = "20260904-000000-live".to_owned();
9380 alive.status = TaskStatus::Running;
9381 alive.attempts = 1;
9382 queue.put(&mut alive).unwrap();
9383 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9384
9385 let mut queued = task();
9386 queued.id = "20260904-000000-wait".to_owned();
9387 queue.put(&mut queued).unwrap();
9388
9389 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9390 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9391
9392 assert_eq!(
9393 queue.get(&orphaned.id).unwrap().status,
9394 TaskStatus::Held,
9395 "nothing was driving it and there was no run to recover"
9396 );
9397 assert_eq!(
9398 queue.get(&alive.id).unwrap().status,
9399 TaskStatus::Running,
9400 "a live claim must protect the task it belongs to"
9401 );
9402 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9403 }
9404
9405 fn read_run_under(home: &Path, id: &str) -> RunState {
9411 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9412 serde_json::from_str(&body).unwrap()
9413 }
9414
9415 #[test]
9416 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9417 let dir = tempfile::tempdir().unwrap();
9418 let home = dir.path().to_path_buf();
9419 let now = Timestamp::now();
9420 let overrun_seat = || crate::run::ActiveSeat {
9421 node: "implement".to_owned(),
9422 started_at: now - jiff::SignedDuration::new(21_000, 0),
9423 timeout_secs: 3_600,
9424 attempt: 0,
9425 task: None,
9426 command: None,
9427 index: None,
9428 total: None,
9429 };
9430
9431 let mut dead = run_state(RunStatus::Implementing);
9432 dead.id = "20260101-000000-dead".to_owned();
9433 dead.active.insert("impl-A".to_owned(), overrun_seat());
9434 dead.driver_pid = Some(4242);
9437 dead.save_under(&home).unwrap();
9438
9439 let mut alive = run_state(RunStatus::Implementing);
9442 alive.id = "20260101-000000-aliv".to_owned();
9443 alive.active.insert("impl-A".to_owned(), overrun_seat());
9444 alive.save_under(&home).unwrap();
9445 let mut status = Status::new();
9446 status.current = vec![Current {
9447 worker: None,
9448 task: "20260101-000000-task".to_owned(),
9449 run: alive.id.clone(),
9450 }];
9451 write_status_to(&home.join("daemon.json"), &status).unwrap();
9452
9453 let questions = Questions::at(home.join("questions"));
9457 let mut q = ask::Question::new(
9458 dead.id.clone(),
9459 "implement".to_owned(),
9460 "impl-A".to_owned(),
9461 "Which storage backend?".to_owned(),
9462 String::new(),
9463 vec!["SQLite".to_owned(), "Redis".to_owned()],
9464 );
9465 questions.put(&mut q).unwrap();
9466
9467 let abandoned = reclaim_abandoned_runs_with(
9468 &home,
9469 now,
9470 |pid| if pid == 4242 { Some(false) } else { None },
9471 |_| panic!("a query answering Dead outright needs no identity corroboration"),
9472 );
9473 assert_eq!(abandoned, vec![dead.id.clone()]);
9474
9475 let reloaded = read_run_under(&home, &dead.id);
9476 assert_eq!(reloaded.status, RunStatus::Failed);
9477 assert!(reloaded.active.is_empty());
9478 assert!(
9479 !questions.get(&q.id).unwrap().status.open(),
9480 "the failed run's own open question must be settled in the same pass"
9481 );
9482
9483 let still_alive = read_run_under(&home, &alive.id);
9484 assert_eq!(
9485 still_alive.status,
9486 RunStatus::Implementing,
9487 "a live daemon's claim protects it"
9488 );
9489 assert!(!still_alive.active.is_empty());
9490 }
9491
9492 #[test]
9502 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9503 let dir = tempfile::tempdir().unwrap();
9504 let home = dir.path().to_path_buf();
9505 let now = Timestamp::now();
9506
9507 let mut manual = run_state(RunStatus::Reviewing);
9508 manual.id = "20260101-000000-manl".to_owned();
9509 manual.active.insert(
9510 "review-1".to_owned(),
9511 crate::run::ActiveSeat {
9512 node: "review".to_owned(),
9513 started_at: now - jiff::SignedDuration::new(21_000, 0),
9514 timeout_secs: 3_600,
9515 attempt: 0,
9516 task: None,
9517 command: None,
9518 index: None,
9519 total: None,
9520 },
9521 );
9522 manual.driver_pid = Some(4242);
9526 manual.driver_started_at = Some("1790000000".to_owned());
9527 manual.save_under(&home).unwrap();
9528
9529 let abandoned = reclaim_abandoned_runs_with(
9530 &home,
9531 now,
9532 |pid| if pid == 4242 { Some(true) } else { None },
9533 |pid| {
9534 if pid == 4242 {
9535 Some("1790000000".to_owned())
9536 } else {
9537 None
9538 }
9539 },
9540 );
9541 assert!(
9542 abandoned.is_empty(),
9543 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9544 );
9545
9546 let reloaded = read_run_under(&home, &manual.id);
9547 assert_eq!(reloaded.status, RunStatus::Reviewing);
9548 assert!(!reloaded.active.is_empty());
9549 }
9550
9551 #[test]
9552 fn an_already_claimed_task_is_skipped_rather_than_failed() {
9553 let dir = tempfile::tempdir().unwrap();
9554 let queue = Queue::at(dir.path().to_path_buf());
9555 let mut only = task();
9556 queue.put(&mut only).unwrap();
9557
9558 let _elsewhere = queue.claim(&only.id).unwrap();
9559 let candidates = runnable(&queue);
9560 assert_eq!(candidates.len(), 1, "the task is still runnable");
9561 assert!(
9562 queue.claim(&candidates[0].id).is_err(),
9563 "the loop cannot take a claim somebody else holds"
9564 );
9565
9566 let after = queue.get(&only.id).unwrap();
9567 assert_eq!(after.status, TaskStatus::Queued);
9568 assert_eq!(
9569 after.attempts, 0,
9570 "losing the race is not an attempt at the task"
9571 );
9572 assert_eq!(after.last_error, None);
9573 }
9574
9575 #[test]
9576 fn the_status_file_round_trips_and_its_heartbeat_advances() {
9577 let dir = tempfile::tempdir().unwrap();
9578 let path = dir.path().join("daemon.json");
9579
9580 let mut status = Status::new();
9581 status.idle = false;
9582 status.completed = 7;
9583 status.current = vec![Current {
9584 worker: None,
9585 task: "20260902-000000-t111".to_owned(),
9586 run: "20260902-000001-r111".to_owned(),
9587 }];
9588 write_status_to(&path, &status).unwrap();
9589 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9590 assert_eq!(first.schema, SCHEMA);
9591 assert_eq!(first.pid, std::process::id());
9592 assert!(!first.idle);
9593 assert_eq!(first.completed, 7);
9594 assert_eq!(first.current, status.current);
9595 assert!(
9596 !path.with_extension("json.tmp").exists(),
9597 "the temp file is renamed, not left behind"
9598 );
9599
9600 std::thread::sleep(Duration::from_millis(5));
9601 status.updated_at = Timestamp::now();
9602 status.polls = 3;
9603 write_status_to(&path, &status).unwrap();
9604 let second: Status =
9605 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9606 assert!(
9607 second.updated_at > first.updated_at,
9608 "a reader can only detect staleness if the heartbeat moves"
9609 );
9610 assert_eq!(
9611 second.started_at, first.started_at,
9612 "the start time is not a heartbeat"
9613 );
9614 assert_eq!(second.polls, 3);
9615 }
9616
9617 #[test]
9618 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9619 let dir = tempfile::tempdir().unwrap();
9620
9621 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9622
9623 let mut status = Status::new();
9624 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9625 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9626 let stale = read_status(dir.path()).unwrap();
9627 assert!(
9628 !stale.running(Timestamp::now()),
9629 "a minute without a heartbeat is a dead daemon, not a busy one"
9630 );
9631 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9632
9633 status.updated_at = Timestamp::now();
9634 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9635 let fresh = read_status(dir.path()).unwrap();
9636 assert!(fresh.running(Timestamp::now()));
9637 }
9638
9639 #[test]
9640 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9641 let dir = tempfile::tempdir().unwrap();
9642 let now = Timestamp::now();
9643 let mine = "20260903-080619-01c2";
9644
9645 assert!(
9646 !is_working_on(dir.path(), mine, now),
9647 "no status file means nobody is working on anything"
9648 );
9649
9650 let mut status = Status::new();
9651 status.current = vec![Current {
9652 worker: None,
9653 task: "20260903-080340-0167".to_owned(),
9654 run: mine.to_owned(),
9655 }];
9656 status.updated_at = now;
9657 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9658 assert!(is_working_on(dir.path(), mine, now));
9659 assert!(
9660 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9661 "a daemon busy with one run is not working on another"
9662 );
9663
9664 status.updated_at = now - jiff::SignedDuration::from_secs(600);
9667 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9668 assert!(
9669 !is_working_on(dir.path(), mine, now),
9670 "a stale heartbeat is a dead daemon, so its run is a leftover"
9671 );
9672 }
9673
9674 #[test]
9675 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9676 let dir = tempfile::tempdir().unwrap();
9677 let now = Timestamp::now();
9678
9679 assert!(
9680 !is_working_on_short(dir.path(), "01c2", now),
9681 "no status file means nobody is working on anything"
9682 );
9683
9684 let mut status = Status::new();
9685 status.current = vec![Current {
9686 worker: None,
9687 task: "20260903-080340-0167".to_owned(),
9688 run: "20260903-080619-01c2".to_owned(),
9689 }];
9690 status.updated_at = now;
9691 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9692 assert!(
9693 is_working_on_short(dir.path(), "01c2", now),
9694 "the run's short id is the last block of its full id"
9695 );
9696 assert!(
9697 !is_working_on_short(dir.path(), "3cbf", now),
9698 "a daemon busy with one worktree bay is not working on another"
9699 );
9700 }
9701
9702 #[test]
9703 fn a_newer_status_file_still_yields_a_reading() {
9704 let dir = tempfile::tempdir().unwrap();
9705 std::fs::write(
9708 dir.path().join("daemon.json"),
9709 serde_json::json!({
9710 "schema": 2,
9711 "updated_at": Timestamp::now().to_string(),
9712 "idle": true,
9713 "surprise": { "nested": [1, 2, 3] },
9714 })
9715 .to_string(),
9716 )
9717 .unwrap();
9718
9719 let reading = read_status(dir.path()).expect("a forward-compatible read");
9720 assert!(reading.running(Timestamp::now()));
9721 assert!(reading.idle);
9722 assert!(reading.current.is_empty());
9723 }
9724
9725 #[test]
9726 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9727 let dir = tempfile::tempdir().unwrap();
9733 std::fs::write(
9734 dir.path().join("daemon.json"),
9735 serde_json::json!({
9736 "schema": 1,
9737 "pid": 4242,
9738 "updated_at": Timestamp::now().to_string(),
9739 "idle": false,
9740 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9741 "completed": 3,
9742 "polls": 9,
9743 })
9744 .to_string(),
9745 )
9746 .unwrap();
9747
9748 let reading = read_status(dir.path()).expect("an older shape must still parse");
9749 assert!(reading.running(Timestamp::now()));
9750 assert_eq!(
9751 reading.current,
9752 vec![Current {
9753 worker: None,
9754 task: "20260902-140501-aaaa".to_owned(),
9755 run: "20260902-140502-bbbb".to_owned(),
9756 }]
9757 );
9758 }
9759
9760 #[test]
9761 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9762 let dir = tempfile::tempdir().unwrap();
9763 std::fs::write(
9764 dir.path().join("daemon.json"),
9765 serde_json::json!({
9766 "schema": 1,
9767 "updated_at": Timestamp::now().to_string(),
9768 "idle": true,
9769 "current": null,
9770 })
9771 .to_string(),
9772 )
9773 .unwrap();
9774 let with_null = read_status(dir.path()).expect("null must still parse");
9775 assert!(with_null.current.is_empty());
9776
9777 std::fs::write(
9778 dir.path().join("daemon.json"),
9779 serde_json::json!({
9780 "schema": 1,
9781 "updated_at": Timestamp::now().to_string(),
9782 "idle": true,
9783 })
9784 .to_string(),
9785 )
9786 .unwrap();
9787 let absent = read_status(dir.path()).expect("a missing field must still parse");
9788 assert!(absent.current.is_empty());
9789 }
9790
9791 #[test]
9792 fn a_task_without_a_repository_runs_in_the_daemons_default() {
9793 let fallback = Path::new("/default");
9794 let mut blank = task();
9795 blank.repo = PathBuf::new();
9796 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9797 let mut dot = task();
9798 dot.repo = PathBuf::from(".");
9799 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9800 assert_eq!(
9801 repo_for(&task(), fallback),
9802 PathBuf::from("/repo"),
9803 "a task that names a repository keeps it"
9804 );
9805 }
9806
9807 #[test]
9808 fn task_implementers_edit_inherits_daemon_config_and_merge() {
9809 let dir = tempfile::tempdir().unwrap();
9810 let path = dir.path().join("explicit.toml");
9811 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9812 let opts = Opts {
9813 config: Some(path),
9814 merge: Some("none".into()),
9815 ..Default::default()
9816 };
9817 let mut t = task();
9818 t.set_implementers(
9819 2,
9820 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9821 .unwrap(),
9822 )
9823 .unwrap();
9824 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9825 assert_eq!(cfg.graph.implementers, 2);
9826 assert_eq!(cfg.graph.judges, 1);
9827 assert_eq!(cfg.merge.mode, MergeMode::None);
9828 t.set_implementers(1, &cfg).unwrap();
9829 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9830 apply_task_implementers(&mut cfg, &t);
9831 assert_eq!(cfg.graph.implementers, 1);
9832 assert_eq!(cfg.graph.judges, 1);
9833 assert_eq!(cfg.merge.mode, MergeMode::None);
9834 }
9835
9836 #[test]
9837 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9838 let dir = tempfile::tempdir().unwrap();
9839 let repo = dir.path().join("repo");
9840 std::fs::create_dir(&repo).unwrap();
9841 std::fs::write(
9842 repo.join("magi.toml"),
9843 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9844 )
9845 .unwrap();
9846 let daemon_config = dir.path().join("daemon.toml");
9847 std::fs::write(
9848 &daemon_config,
9849 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9850 )
9851 .unwrap();
9852 let opts = Opts {
9853 config: Some(daemon_config),
9854 merge: Some("pr".into()),
9855 ..Default::default()
9856 };
9857 let q = Queue::at(dir.path().join("queue"));
9858 let validation: Config =
9859 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9860 .unwrap();
9861 for record in ["{}", r#"{"candidates":2}"#] {
9863 let overrides = serde_json::from_str(record).unwrap();
9864 let filing = crate::direct::Filing {
9865 instruction: "work".into(),
9866 title: "direct".into(),
9867 repo: repo.clone(),
9868 source: crate::queue::Source::Human,
9869 solo: false,
9870 overrides,
9871 review_of: None,
9872 sources: Default::default(),
9873 };
9874 let filed =
9875 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9876 let crate::direct::Filed::Standalone {
9877 mut task,
9878 claim: _claim,
9879 } = filed
9880 else {
9881 panic!("local filing")
9882 };
9883 let before = prepare_for(&repo, &opts, &task).unwrap();
9884 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9885 assert_eq!(
9886 before.merge.mode,
9887 MergeMode::None,
9888 "daemon --merge must not leak"
9889 );
9890 for n in [2, 1, 2] {
9891 task.set_implementers(n, &validation).unwrap();
9892 q.put(&mut task).unwrap();
9893 task = q.get(&task.id).unwrap();
9894 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9895 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9896 apply_task_implementers(&mut cfg, &task);
9897 assert_eq!(cfg.graph.implementers, usize::from(n));
9898 assert_eq!(cfg.graph.judges, 2);
9899 assert_eq!(cfg.merge.mode, MergeMode::None);
9900 }
9901 }
9902 }
9903
9904 #[test]
9905 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9906 let cfg: Config =
9907 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9908 .unwrap();
9909 let mut t = task();
9910 t.review_of = Some("review-target".into());
9911 t.hold_manual(Some("retry".into()));
9912 let mut previous = RunState::new(
9913 PathBuf::from("/repo"),
9914 "main".into(),
9915 "abc1234".into(),
9916 "review".into(),
9917 cfg.clone(),
9918 );
9919 previous.config.graph.implementers = 2;
9920 for count in [1, 3] {
9921 t.set_implementers(count, &cfg).unwrap();
9922 t.release();
9923 assert_eq!(t.review_of.as_deref(), Some("review-target"));
9924 for proposed in [
9925 Starter::Resume(previous.id.clone()),
9926 Starter::Review("recovery-target".into()),
9927 ] {
9928 assert_eq!(
9929 starter_with_implementers(&t, Some(&previous), proposed),
9930 Starter::Review("review-target".into())
9931 );
9932 }
9933 let mut configured = cfg.clone();
9934 apply_task_implementers(&mut configured, &t);
9935 assert_eq!(configured.graph.implementers, usize::from(count));
9936 assert_eq!(previous.config.graph.implementers, 2);
9937 }
9938 }
9939
9940 #[test]
9941 fn task_implementers_dispatch_and_resume_agree() {
9942 let mut t = task();
9943 let cfg: crate::config::Config =
9944 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9945 .unwrap();
9946 let mut run = RunState::new(
9947 PathBuf::from("/repo"),
9948 "main".into(),
9949 "abc1234".into(),
9950 "work".into(),
9951 cfg.clone(),
9952 );
9953 run.config.graph.implementers = 2;
9954 for n in [2, 1, 3, 2] {
9955 t.set_implementers(n, &cfg).unwrap();
9956 let mut dispatched = cfg.clone();
9957 apply_task_implementers(&mut dispatched, &t);
9958 assert_eq!(dispatched.graph.implementers, usize::from(n));
9959 assert_eq!(implementers_match(&t, &run), n == 2);
9960 for proposed in [
9961 Starter::Resume(run.id.clone()),
9962 Starter::Review("old-branch".into()),
9963 ] {
9964 let expected = if n == 2 {
9965 proposed.clone()
9966 } else {
9967 Starter::Start
9968 };
9969 assert_eq!(
9970 starter_with_implementers(&t, Some(&run), proposed),
9971 expected
9972 );
9973 }
9974 assert_eq!(
9975 run.config.graph.implementers, 2,
9976 "history must not be rewritten"
9977 );
9978 }
9979 t.solo = false;
9980 t.overrides = None;
9981 assert!(implementers_match(&t, &run));
9982 }
9983
9984 #[test]
9985 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9986 let mut solo_cfg = Config::default();
9992 solo_cfg.graph.implementers = 3;
9993 let mut solo_task = task();
9994 solo_task.solo = true;
9995 apply_task_implementers(&mut solo_cfg, &solo_task);
9996 assert_eq!(solo_cfg.graph.implementers, 1);
9997
9998 let mut plain_cfg = Config::default();
9999 plain_cfg.graph.implementers = 3;
10000 let plain_task = task();
10001 assert!(!plain_task.solo);
10002 apply_task_implementers(&mut plain_cfg, &plain_task);
10003 assert_eq!(
10004 plain_cfg.graph.implementers, 3,
10005 "a task that did not ask to run alone keeps the config's candidates"
10006 );
10007 }
10008
10009 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10010 QuotaLoss {
10011 cause: crate::agent::QuotaCause::UsageLimit,
10012 agent: String::new(),
10013 seat: seat.into(),
10014 node: "judge".into(),
10015 at: at.parse().unwrap(),
10016 reset: reset.map(str::to_string),
10017 }
10018 }
10019
10020 #[test]
10021 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10022 let now = Timestamp::now();
10023 for reset in [None, Some("in 1h")] {
10024 let auth = crate::agent::Quota {
10025 cause: crate::agent::QuotaCause::Authentication,
10026 agent: "alpha".into(),
10027 reset: reset.map(str::to_owned),
10028 };
10029 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10030 assert_eq!(cooldown_until(&[loss], now), None);
10031 }
10032 }
10033
10034 #[test]
10035 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10036 let old: Vec<QuotaLoss> = (1..=4)
10037 .map(|i| {
10038 loss(
10039 &format!("judge-{i}"),
10040 "2026-09-23T05:23:00Z",
10041 Some("2:40pm (Asia/Tokyo)"),
10042 )
10043 })
10044 .collect();
10045 let fresh = losses_this_attempt(&old, &old);
10046 assert!(fresh.is_empty());
10047 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10048 }
10050
10051 #[test]
10052 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10053 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10054 let now = Timestamp::now();
10055 let mut after = old.clone();
10056 after.push(loss("judge-2", &now.to_string(), None));
10057 let fresh = losses_this_attempt(&old, &after);
10058 assert_eq!(fresh, vec![after[1].clone()]);
10059 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10060 assert_eq!(
10061 until,
10062 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10063 );
10064 }
10065
10066 #[test]
10067 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10068 let before = vec![
10071 loss("judge-1", "2026-09-23T05:23:00Z", None),
10072 loss("judge-2", "2026-09-23T05:24:00Z", None),
10073 ];
10074 let after = vec![
10075 loss("judge-2", "2026-09-23T05:24:00Z", None),
10076 loss("judge-1", "2026-09-24T01:00:00Z", None),
10077 ];
10078 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10079 }
10080
10081 #[test]
10082 fn merge_overrides_are_parsed_or_refused() {
10083 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10084 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10085 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10086 assert!(merge_mode("squash").is_err());
10087 }
10088
10089 #[test]
10090 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10091 let now = Timestamp::now();
10092 let fallback = Duration::from_secs(300);
10093 let cap = Duration::from_secs(1800);
10094
10095 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10097
10098 let soon = now + jiff::SignedDuration::from_secs(600);
10100 assert_eq!(
10101 quota_wait(Some(soon), now, fallback, cap),
10102 Duration::from_secs(600)
10103 );
10104
10105 let past = now - jiff::SignedDuration::from_secs(60);
10108 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10109
10110 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10113 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10114 }
10115
10116 #[test]
10117 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10118 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10119
10120 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10121 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10122
10123 let already_past =
10127 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10128 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10129
10130 assert!(
10131 parse_reset_hint("session limit reached", now, now).is_none(),
10132 "free text with no recognised shape is not guessed at"
10133 );
10134 assert!(
10135 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10136 "an unresolvable zone name is not guessed at either"
10137 );
10138 }
10139
10140 #[test]
10141 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10142 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10143
10144 let at = parse_reset_hint(
10145 "You've hit your usage limit. Visit \
10146 https://chatgpt.com/codex/settings/usage to purchase more \
10147 credits or try again at Sep 19th, 2026 5:10 PM.",
10148 now,
10149 now,
10150 )
10151 .expect("the codex reset wording is a recognised shape");
10152 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10153
10154 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10159 .expect("an explicit year needs no rollover");
10160 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10161
10162 assert!(
10163 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10164 "a two-digit year is not the documented shape and is not guessed at"
10165 );
10166 assert!(
10167 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10168 "a four-letter month name is not the documented three-letter abbreviation"
10169 );
10170 assert!(
10171 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10172 "an explicit zone on the dated shape is a format nobody has \
10173 documented, and is refused rather than guessed at as UTC"
10174 );
10175 }
10176
10177 #[test]
10178 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10179 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10180 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10181
10182 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10183 assert_eq!(at.as_second() - recorded.as_second(), 3769);
10184
10185 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10186 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10187
10188 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10189 assert!(
10190 parse_reset_hint(bad, now, recorded).is_none(),
10191 "{bad:?} must not be guessed at"
10192 );
10193 }
10194 }
10195
10196 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10200 let config = dir.join("magi.toml");
10201 std::fs::write(
10202 &config,
10203 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10204 )
10205 .unwrap();
10206 let opts = Opts {
10207 poll: Duration::from_secs(30),
10208 config: Some(config),
10209 repo: dir.join("repo"),
10213 ..Opts::default()
10214 };
10215 let home = dir.join("home");
10224 let stamps = home.join("service-ticks");
10227 std::fs::create_dir_all(&stamps).unwrap();
10228 for service in ["waiter", "deputies", "release-watch"] {
10229 std::fs::write(
10230 stamps.join(service),
10231 Timestamp::now().as_second().to_string(),
10232 )
10233 .unwrap();
10234 }
10235 for operation in [
10236 "conductor",
10237 "maintenance",
10238 "housekeeping",
10239 "disk-pressure",
10240 "cache",
10241 "fetch",
10242 ] {
10243 std::fs::write(
10244 stamps.join(format!("daemon-{operation}")),
10245 serde_json::to_vec(&Timestamp::now()).unwrap(),
10246 )
10247 .unwrap();
10248 }
10249 let worktrees = dir.join("wt");
10250 (
10251 opts,
10252 Queue::at(dir.join("queue")),
10253 home.join("daemon.json"),
10254 home,
10255 worktrees,
10256 )
10257 }
10258
10259 #[test]
10260 fn a_stop_is_idempotent_and_once_set_stays_set() {
10261 let stop = Stop::new();
10262 assert!(!stop.stopped());
10263
10264 stop.stop();
10265 assert!(stop.stopped());
10266 stop.stop();
10267 assert!(stop.stopped(), "a second stop is not a toggle");
10268
10269 let shared = stop.clone();
10270 assert!(
10271 shared.stopped(),
10272 "a clone is the same stop; that is how the loop and its caller share one"
10273 );
10274 }
10275
10276 #[tokio::test]
10277 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10278 for operation in ["conductor", "maintenance", "housekeeping"] {
10279 let dir = tempfile::tempdir().unwrap();
10280 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10281 opts.once = true;
10282 opts.poll = Duration::from_millis(1);
10283 let mut task = task();
10284 task.runs.push("fixture-run".into());
10285 queue.put(&mut task).unwrap();
10286 let claim = queue.claim(&task.id).unwrap();
10287
10288 let directory = home.join("workers/jobs/abcdef");
10291 std::fs::create_dir_all(&directory).unwrap();
10292 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10293 crate::pr_head::try_lock_file(&lease).unwrap();
10294 let mut job = crate::worker::Job {
10295 id: "abcdef".into(),
10296 sequence: 1,
10297 kind: "daemon-service".into(),
10298 key: format!("service:daemon-{operation}"),
10299 payload: serde_json::Value::Null,
10300 generation: "fixture".into(),
10301 version: None,
10302 status: crate::worker::Status::Running,
10303 result: None,
10304 pid: Some(std::process::id()),
10305 created_at: Timestamp::now().as_second() as u64,
10306 finished_at: None,
10307 };
10308 let record = directory.join("job.json");
10309 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10310
10311 let status = Arc::new(Mutex::new(Status::new()));
10312 let stop = Stop::new();
10313 let mut drain = Box::pin(poll(
10314 &opts,
10315 &queue,
10316 &status,
10317 &home,
10318 &worktrees,
10319 &stop,
10320 DispatchLimits {
10321 max_concurrent: 1,
10322 pause_for_interrupts: false,
10323 recovery_cfg: None,
10324 },
10325 ));
10326 std::future::poll_fn(|cx| {
10327 use std::future::Future;
10328 assert!(
10329 drain.as_mut().poll(cx).is_pending(),
10330 "--once must wait for {operation} to release its queue claim"
10331 );
10332 std::task::Poll::Ready(())
10333 })
10334 .await;
10335 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10336
10337 let questions = Questions::at(home.join("questions"));
10340 let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10341 questions.put(&mut q).unwrap();
10342 drop(claim);
10343 let expired =
10347 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10348 for service in [operation, "housekeeping"] {
10349 std::fs::write(
10350 home.join("service-ticks").join(format!("daemon-{service}")),
10351 &expired,
10352 )
10353 .unwrap();
10354 }
10355 job.status = crate::worker::Status::Finished;
10356 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10357 drop(lease);
10358 tokio::time::timeout(Duration::from_secs(2), drain)
10359 .await
10360 .expect("the settled service must allow the drain to finish")
10361 .unwrap();
10362 let after = queue.get(&task.id).unwrap();
10363 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10364 assert!(after.action_applied(&q.id));
10365 for service in [operation, "housekeeping"] {
10366 assert_eq!(
10367 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10368 .unwrap(),
10369 expired,
10370 "the final once rescan must not restart {service}"
10371 );
10372 }
10373 }
10374 }
10375
10376 #[test]
10377 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10378 let stop = Stop::new();
10379 stop.busy.store(1, Ordering::SeqCst);
10380 assert!(
10381 !stop.finishing(),
10382 "a busy loop nobody has asked to stop is just running"
10383 );
10384
10385 stop.stop();
10386 assert!(
10387 stop.finishing(),
10388 "a stop asked for mid-run has not landed until the run is settled"
10389 );
10390
10391 stop.busy.store(0, Ordering::SeqCst);
10392 assert!(
10393 !stop.finishing(),
10394 "once the run is settled the stop has landed and there is nothing to finish"
10395 );
10396 }
10397
10398 #[test]
10399 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10400 let stop = Stop::new();
10401 stop.busy.store(2, Ordering::SeqCst);
10402 stop.stop();
10403 assert!(stop.finishing(), "two runs still in flight");
10404
10405 stop.busy.store(1, Ordering::SeqCst);
10406 assert!(
10407 stop.finishing(),
10408 "one run finished, but a sibling is still working"
10409 );
10410
10411 stop.busy.store(0, Ordering::SeqCst);
10412 assert!(
10413 !stop.finishing(),
10414 "the last run out is what actually lands the stop"
10415 );
10416 }
10417
10418 #[tokio::test]
10419 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10420 let dir = tempfile::tempdir().unwrap();
10421 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10422 let stop = Stop::new();
10423 stop.stop();
10424
10425 let began = std::time::Instant::now();
10426 tokio::time::timeout(
10427 Duration::from_secs(2),
10428 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10429 )
10430 .await
10431 .expect("a stopped loop must return, not sit out its poll interval")
10432 .expect("the loop's own setup and teardown must not fail");
10433 assert!(
10434 began.elapsed() < opts.poll,
10435 "returned only after {:?}, which is a poll interval, not a stop",
10436 began.elapsed()
10437 );
10438 }
10439
10440 #[tokio::test]
10441 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10442 let dir = tempfile::tempdir().unwrap();
10443 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10444 let stop = Stop::new();
10445
10446 let asker = {
10449 let stop = stop.clone();
10450 tokio::spawn(async move {
10451 tokio::time::sleep(Duration::from_millis(20)).await;
10452 stop.stop();
10453 })
10454 };
10455
10456 let began = std::time::Instant::now();
10457 tokio::time::timeout(
10458 Duration::from_secs(2),
10459 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10460 )
10461 .await
10462 .expect("a stop asked for while idle must wake the wait")
10463 .expect("the loop's own setup and teardown must not fail");
10464 asker.await.unwrap();
10465 assert!(
10466 began.elapsed() < opts.poll,
10467 "returned only after {:?}, so the stop waited on the sleep",
10468 began.elapsed()
10469 );
10470 }
10471
10472 #[tokio::test]
10473 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10474 let dir = tempfile::tempdir().unwrap();
10475 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10476 let stop = Stop::new();
10477 stop.stop();
10478
10479 tokio::time::timeout(
10480 Duration::from_secs(2),
10481 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10482 )
10483 .await
10484 .expect("a stopped loop must return")
10485 .expect("the loop's own setup and teardown must not fail");
10486
10487 assert!(
10488 home.is_dir(),
10489 "the loop did publish a status file, so its removal is the teardown and not an absence"
10490 );
10491 assert!(
10492 !status_file.exists(),
10493 "a stopped loop clears its status file"
10494 );
10495 assert!(
10496 read_status(&home).is_none(),
10497 "a reader must see no daemon at all, not a heartbeat that merely stopped"
10498 );
10499 }
10500
10501 #[tokio::test]
10502 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10503 let dir = tempfile::tempdir().unwrap();
10504 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10505
10506 let mut settled = RunState::new(
10507 dir.path().join("repo"),
10508 "main".to_owned(),
10509 "abc1234".to_owned(),
10510 "fixture".to_owned(),
10511 Config::default(),
10512 );
10513 settled.status = RunStatus::Ready;
10514 let run_dir = home.join("runs").join(&settled.id);
10515 std::fs::create_dir_all(&run_dir).unwrap();
10516 std::fs::write(
10517 run_dir.join("run.json"),
10518 serde_json::to_string_pretty(&settled).unwrap(),
10519 )
10520 .unwrap();
10521 let questions = Questions::at(home.join("questions"));
10522 let mut question = ask::Question::new(
10523 settled.id.clone(),
10524 "review".to_owned(),
10525 "reviewer-1".to_owned(),
10526 "Continue?".to_owned(),
10527 String::new(),
10528 Vec::new(),
10529 );
10530 questions.put(&mut question).unwrap();
10531
10532 run_service_worker(
10533 &home,
10534 serde_json::to_value(ServiceWorker {
10535 opts,
10536 queue: queue.root().to_path_buf(),
10537 worktrees_root: worktrees,
10538 operation: "housekeeping".to_owned(),
10539 })
10540 .unwrap(),
10541 )
10542 .await
10543 .unwrap();
10544
10545 assert_eq!(
10546 questions.get(&question.id).unwrap().status,
10547 ask::QuestionStatus::Abandoned,
10548 "the independent housekeeping worker settles ended-run questions"
10549 );
10550 }
10551
10552 #[test]
10553 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10554 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10555
10556 assert!(
10557 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10558 "never checked before: due at once"
10559 );
10560
10561 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10562 assert!(
10563 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10564 "well inside the interval: not due yet"
10565 );
10566
10567 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10568 assert!(
10569 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10570 "exactly at the edge: not yet due, same convention as `clean::due`"
10571 );
10572
10573 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10574 assert!(
10575 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10576 "past the interval: due again"
10577 );
10578 }
10579
10580 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10585 let config = dir.join("magi.toml");
10586 std::fs::write(
10592 &config,
10593 format!(
10594 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10595 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10596 cache_dir.display()
10597 ),
10598 )
10599 .unwrap();
10600 Opts {
10601 config: Some(config),
10602 repo: dir.join("repo"),
10603 ..Opts::default()
10604 }
10605 }
10606
10607 #[tokio::test]
10608 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10609 let dir = tempfile::tempdir().unwrap();
10610 let home = dir.path().join("home");
10611 let cache_dir = dir.path().join("cache");
10612 std::fs::create_dir_all(&cache_dir).unwrap();
10613 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10614 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10615
10616 let running = Stop::new();
10619 let mut last_checked = None;
10620 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10621 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10622 .await;
10623 assert_eq!(
10624 crate::disk::dir_size(&cache_dir),
10625 0,
10626 "over the cap on the first check ever: pruned at once, no idle queue required"
10627 );
10628 assert_eq!(last_checked, Some(t0));
10629
10630 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10632 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10633 maybe_prune_cache_between_runs(
10634 &opts.repo,
10635 &opts,
10636 &home,
10637 &running,
10638 &mut last_checked,
10639 too_soon,
10640 )
10641 .await;
10642 assert_eq!(
10643 crate::disk::dir_size(&cache_dir),
10644 10,
10645 "too soon since the last check: left alone rather than rescanned every call"
10646 );
10647 assert_eq!(
10648 last_checked,
10649 Some(t0),
10650 "an idle check does not reset the clock"
10651 );
10652
10653 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10655 maybe_prune_cache_between_runs(
10656 &opts.repo,
10657 &opts,
10658 &home,
10659 &running,
10660 &mut last_checked,
10661 due_again,
10662 )
10663 .await;
10664 assert_eq!(
10665 crate::disk::dir_size(&cache_dir),
10666 0,
10667 "due again: pruned back under the cap"
10668 );
10669 }
10670
10671 #[tokio::test]
10679 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10680 let dir = tempfile::tempdir().unwrap();
10681 let home = dir.path().join("home");
10682 let cache_dir = dir.path().join("cache");
10683 std::fs::create_dir_all(&cache_dir).unwrap();
10684 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10685 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10686
10687 let stop = Stop::new();
10688 stop.stop();
10689 assert!(
10690 !stop.finishing(),
10691 "no run is in flight at a between-runs boundary, so nothing else \
10692 would tell the operator this stop had not taken effect yet"
10693 );
10694
10695 let mut last_checked = None;
10696 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10697 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10698 .await;
10699 assert_eq!(
10700 crate::disk::dir_size(&cache_dir),
10701 10,
10702 "over its cap, and due for the first check ever, but a stop outranks \
10703 it: the cap is a standing policy the next start measures again"
10704 );
10705 assert_eq!(
10706 last_checked, None,
10707 "a check that never happened must not claim the interval"
10708 );
10709 }
10710
10711 #[tokio::test]
10714 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10715 let dir = tempfile::tempdir().unwrap();
10716 let cache_dir = dir.path().join("cache");
10717 std::fs::create_dir_all(&cache_dir).unwrap();
10718 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10719
10720 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10721 opts.poll = Duration::from_millis(20);
10722 opts.max_attempts = 1_000;
10723
10724 let queue = Queue::at(dir.path().join("queue"));
10725 for i in 0..128 {
10726 let mut task = Task::new(
10727 format!("queued work {i}"),
10728 format!("queued work {i}"),
10729 opts.repo.clone(),
10730 Source::Human,
10731 );
10732 queue.put(&mut task).unwrap();
10733 }
10734
10735 let home = dir.path().join("home");
10736 let worktrees = dir.path().join("wt");
10737 run_service_worker(
10738 &home,
10739 serde_json::to_value(ServiceWorker {
10740 opts,
10741 queue: queue.root().to_path_buf(),
10742 worktrees_root: worktrees,
10743 operation: "cache".to_owned(),
10744 })
10745 .unwrap(),
10746 )
10747 .await
10748 .unwrap();
10749 let after = queue.list();
10750 assert_eq!(after.len(), 128);
10751 assert!(
10752 after
10753 .iter()
10754 .all(|task| task.status.runnable() && task.attempts == 0)
10755 );
10756
10757 assert_eq!(
10758 crate::disk::dir_size(&cache_dir),
10759 0,
10760 "an oversized cache must not be left to grow unboundedly just because the \
10761 queue kept the loop busy the whole time"
10762 );
10763 }
10764
10765 #[test]
10766 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10767 let dir = tempfile::tempdir().unwrap();
10768 let queue = Queue::at(dir.path().join("queue"));
10769 let questions = Questions::at(dir.path().join("questions"));
10770 let mut task = task();
10771 queue.put(&mut task).unwrap();
10772
10773 let mut task_question = ask::Question::new(
10774 task.id.clone(),
10775 crate::conduct::NODE.to_owned(),
10776 "conduct".to_owned(),
10777 "Which backend?".to_owned(),
10778 String::new(),
10779 Vec::new(),
10780 );
10781 questions.put(&mut task_question).unwrap();
10782 task.block(vec![task_question.id.clone()], None);
10783 queue.put(&mut task).unwrap();
10784
10785 let mut run_question = ask::Question::new(
10786 "20260101-000000-run1".to_owned(),
10787 "review".to_owned(),
10788 "reviewer-1".to_owned(),
10789 "Run question".to_owned(),
10790 String::new(),
10791 Vec::new(),
10792 );
10793 questions.put(&mut run_question).unwrap();
10794
10795 let mut coincidental = ask::Question::new(
10800 task.id.clone(),
10801 "review".to_owned(),
10802 "reviewer-1".to_owned(),
10803 "Unrelated review question".to_owned(),
10804 String::new(),
10805 Vec::new(),
10806 );
10807 questions.put(&mut coincidental).unwrap();
10808
10809 reconcile_task_questions(&queue, &questions);
10810 assert!(questions.get(&task_question.id).unwrap().status.open());
10811 assert!(questions.get(&run_question.id).unwrap().status.open());
10812 assert!(questions.get(&coincidental.id).unwrap().status.open());
10813
10814 task.release();
10815 queue.put(&mut task).unwrap();
10816 reconcile_task_questions(&queue, &questions);
10817 assert_eq!(
10818 questions.get(&task_question.id).unwrap().status,
10819 ask::QuestionStatus::Abandoned
10820 );
10821 assert!(
10822 questions.get(&run_question.id).unwrap().status.open(),
10823 "run questions remain the run janitor's responsibility"
10824 );
10825 assert!(
10826 questions.get(&coincidental.id).unwrap().status.open(),
10827 "a non-conductor question must not be abandoned just because its \
10828 run id coincides with a task id"
10829 );
10830 }
10831
10832 #[test]
10833 fn a_freshly_started_running_task_is_never_stalled() {
10834 let dir = tempfile::tempdir().unwrap();
10835 let mut t = task();
10836 t.start("run-1".to_owned());
10837 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10840 }
10841
10842 #[test]
10843 fn a_long_running_task_with_no_live_daemon_is_stalled() {
10844 let dir = tempfile::tempdir().unwrap();
10845 let mut t = task();
10846 t.start("run-1".to_owned());
10847 t.updated_at = Timestamp::now()
10848 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10849 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10850 assert_eq!(
10851 stalled_tasks(
10852 &Queue::at(dir.path().join("q")),
10853 dir.path(),
10854 Timestamp::now()
10855 )
10856 .len(),
10857 0,
10858 "the task was never written to this queue"
10859 );
10860 }
10861
10862 #[test]
10863 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10864 let dir = tempfile::tempdir().unwrap();
10865 let mut t = task();
10866 t.id = "20260903-080340-0167".to_owned();
10867 t.start("20260903-080619-01c2".to_owned());
10868 t.updated_at = Timestamp::now()
10869 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10870
10871 let mut status = Status::new();
10872 status.current = vec![Current {
10873 worker: None,
10874 task: t.id.clone(),
10875 run: "20260903-080619-01c2".to_owned(),
10876 }];
10877 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10878
10879 assert!(
10880 !is_stalled(&t, dir.path(), Timestamp::now()),
10881 "a live daemon's own heartbeat rules out stalled, however long the task has run"
10882 );
10883 }
10884
10885 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10889 let path = queue.path_of(id);
10890 let body = std::fs::read_to_string(&path).unwrap();
10891 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10892 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10893 v["updated_at"] = serde_json::Value::String(old.to_string());
10894 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10895 }
10896
10897 #[test]
10898 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10899 let dir = tempfile::tempdir().unwrap();
10912 let queue = Queue::at(dir.path().join("queue"));
10913 let home = dir.path().join("home");
10914
10915 let mut t = task();
10916 t.id = "20260101-000001-lock".to_owned();
10917 t.start("run-1".to_owned());
10918 queue.put(&mut t).unwrap();
10919 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10920 std::fs::write(
10921 dir.path().join("queue").join(format!("{}.lock", t.id)),
10922 "not a pid",
10923 )
10924 .unwrap();
10925
10926 let now = Timestamp::now();
10927 assert!(
10928 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10929 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10930 and reclaim must leave the task alone"
10931 );
10932 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10933
10934 let stalled = stalled_tasks(&queue, &home, now);
10935 assert_eq!(
10936 stalled.len(),
10937 1,
10938 "reclaim's inability to claim it yet must not hide it from the conductor"
10939 );
10940 assert_eq!(stalled[0].id, t.id);
10941 }
10942
10943 #[test]
10944 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10945 let dir = tempfile::tempdir().unwrap();
10946 crate::run::set_home(dir.path().join("run-home"));
10947 let queue = Queue::at(dir.path().join("queue"));
10948 let home = dir.path().join("home");
10949 let questions = Questions::at(dir.path().join("questions"));
10950
10951 let mut t = task();
10952 t.id = "20260101-000003-dead".to_owned();
10953 t.start("missing-run".to_owned());
10954 queue.put(&mut t).unwrap();
10955 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10956
10957 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10960 assert_eq!(
10961 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10962 [&t.id]
10963 );
10964 assert_eq!(
10965 reclaim_orphaned_running(&queue, 2, &Default::default()),
10966 [t.id.clone()]
10967 );
10968 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10969
10970 crate::conduct::apply(
10973 &queue,
10974 &questions,
10975 &crate::conduct::Verdict {
10976 decisions: vec![crate::conduct::Decision {
10977 id: t.id.clone(),
10978 recovery: Some(crate::conduct::Recovery::Requeue),
10979 ..crate::conduct::Decision::default()
10980 }],
10981 },
10982 )
10983 .unwrap();
10984 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10985 }
10986
10987 #[test]
10988 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10989 let dir = tempfile::tempdir().unwrap();
10990 let queue = Queue::at(dir.path().join("queue"));
10991 let home = dir.path().join("home");
10992
10993 let mut fresh = task();
10994 fresh.id = "20260101-000001-aaaa".to_owned();
10995 fresh.start("run-1".to_owned());
10996 queue.put(&mut fresh).unwrap();
10997
10998 let mut old = task();
10999 old.id = "20260101-000002-bbbb".to_owned();
11000 old.start("run-2".to_owned());
11001 queue.put(&mut old).unwrap();
11002 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11003
11004 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11005 assert_eq!(stalled.len(), 1);
11006 assert_eq!(stalled[0].id, old.id);
11007 }
11008
11009 #[test]
11010 fn queued_and_finished_task_views_partition_by_status() {
11011 let dir = tempfile::tempdir().unwrap();
11012 let queue = Queue::at(dir.path().join("queue"));
11013
11014 let mut queued = task();
11015 queued.id = "20260101-000001-aaaa".to_owned();
11016 queue.put(&mut queued).unwrap();
11017
11018 let mut failed = task();
11019 failed.id = "20260101-000002-bbbb".to_owned();
11020 failed.start("run-1".to_owned());
11021 failed.fail("gate red", 5);
11022 queue.put(&mut failed).unwrap();
11023
11024 let mut held = task();
11025 held.id = "20260101-000003-cccc".to_owned();
11026 held.hold_machine(None);
11027 queue.put(&mut held).unwrap();
11028
11029 let mut running = task();
11030 running.id = "20260101-000004-dddd".to_owned();
11031 running.start("run-2".to_owned());
11032 queue.put(&mut running).unwrap();
11033
11034 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11035 assert_eq!(queued_ids, [queued.id.clone()]);
11036
11037 let mut finished_ids: Vec<String> =
11038 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11039 finished_ids.sort_unstable();
11040 let mut want = vec![failed.id.clone(), held.id.clone()];
11041 want.sort_unstable();
11042 assert_eq!(finished_ids, want);
11043 }
11044
11045 #[test]
11046 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11047 for short in [false, true] {
11048 let dir = tempfile::tempdir().unwrap();
11049 let queue = Queue::at(dir.path().join("queue"));
11050 let questions = ask::Questions::at(dir.path().join("questions"));
11051 let mut running = task();
11052 running.id = "20261013-192213-feb2".into();
11053 running.start("existing-run".into());
11054 queue.put(&mut running).unwrap();
11055 let mut middle = task();
11056 middle.id = "20261013-193611-ca5b".into();
11057 middle.block(
11058 vec![if short {
11059 "feb2".into()
11060 } else {
11061 running.id.clone()
11062 }],
11063 None,
11064 );
11065 queue.put(&mut middle).unwrap();
11066 let mut waiting = task();
11067 waiting.id = "20261013-202849-ee37".into();
11068 waiting.block(
11069 vec![if short {
11070 "ca5b".into()
11071 } else {
11072 middle.id.clone()
11073 }],
11074 Some("wait for implementation".into()),
11075 );
11076 queue.put(&mut waiting).unwrap();
11077 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11078 let inv = crate::blockers::Inventory::load(&queue, &questions);
11079 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11080 assert!(inv.stuck().is_empty());
11081 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11082 assert!(report.quarantined.is_empty());
11083 assert!(report.asked.is_empty());
11084 resolve_blockers(&queue, &questions);
11085 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11086 assert!(questions.list().is_empty());
11087 running.succeed();
11090 queue.put(&mut running).unwrap();
11091 resolve_blockers(&queue, &questions);
11092 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11093 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11094 middle = queue.get(&middle.id).unwrap();
11095 middle.succeed();
11096 queue.put(&mut middle).unwrap();
11097 resolve_blockers(&queue, &questions);
11098 let after = queue.get(&waiting.id).unwrap();
11099 assert_eq!(after.status, TaskStatus::Queued);
11100 assert!(after.blocked_by.is_empty());
11101 assert_eq!(after.instruction, waiting.instruction);
11102 }
11103 }
11104
11105 #[test]
11106 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11107 for future_schema in [false, true] {
11108 let name = "20261013-193611-ca5b";
11109 let mut future = task();
11110 future.id = name.into();
11111 future.schema = crate::queue::SCHEMA + 1;
11112 let contents = if future_schema {
11113 serde_json::to_string(&future).unwrap()
11114 } else {
11115 "corrupt".into()
11116 };
11117 let dir = tempfile::tempdir().unwrap();
11118 let queue = Queue::at(dir.path().join("queue"));
11119 let questions = ask::Questions::at(dir.path().join("questions"));
11120 let mut waiting = task();
11121 waiting.id = "20261013-202849-ee37".into();
11122 waiting.block(vec!["ca5b".into()], None);
11123 queue.put(&mut waiting).unwrap();
11124 std::fs::write(queue.path_of(name), contents).unwrap();
11125 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11126 assert!(
11127 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11128 );
11129 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11130 assert!(report.asked.is_empty());
11131 resolve_blockers(&queue, &questions);
11132 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11133 assert!(questions.list().is_empty());
11134 }
11135 let dir = tempfile::tempdir().unwrap();
11136 let queue = Queue::at(dir.path().join("queue"));
11137 let questions = ask::Questions::at(dir.path().join("questions"));
11138 let mut waiting = task();
11139 waiting.id = "20261013-202849-ee37".into();
11140 waiting.block(vec!["ca5b".into()], None);
11141 queue.put(&mut waiting).unwrap();
11142 let mut done = task();
11143 done.id = "20261013-193611-ca5b".into();
11144 done.succeed();
11145 queue.put(&mut done).unwrap();
11146 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11149 assert!(queue.get("ca5b").is_err());
11150 assert_eq!(
11151 crate::queue::dependency(&queue, &questions, "ca5b"),
11152 crate::queue::Dependency::Ambiguous
11153 );
11154 resolve_blockers(&queue, &questions);
11155 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11156 assert!(report.asked.is_empty());
11157 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11158 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11159 }
11160
11161 #[test]
11162 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11163 for held in [false, true] {
11164 for question in [false, true] {
11165 for reference in ["ca5b", "20261013-193611-ca5b"] {
11166 let dir = tempfile::tempdir().unwrap();
11167 let queue = Queue::at(dir.path().join("queue"));
11168 let questions = ask::Questions::at(dir.path().join("questions"));
11169 let mut prerequisite = task();
11170 prerequisite.id = "20261013-193611-ca5b".into();
11171 prerequisite.start("existing-run".into());
11172 queue.put(&mut prerequisite).unwrap();
11173 let mut waiting = task();
11174 waiting.id = "20261013-202849-ee37".into();
11175 if held {
11176 waiting.hold_machine(Some("waiting for separate consent".into()));
11177 }
11178 queue.put(&mut waiting).unwrap();
11179 let reason = "Deleting saved data requires separate owner consent";
11180 crate::conduct::apply(
11181 &queue,
11182 &questions,
11183 &crate::conduct::Verdict {
11184 decisions: vec![crate::conduct::Decision {
11185 id: waiting.id.clone(),
11186 blocked_by: vec![reference.into()],
11187 question: question.then(|| "May the saved data be deleted?".into()),
11188 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11189 reason: Some(reason.into()),
11190 ..crate::conduct::Decision::default()
11191 }],
11192 },
11193 )
11194 .unwrap();
11195 let before = queue.get(&waiting.id).unwrap();
11196 if question {
11197 assert_eq!(before.status, TaskStatus::Blocked);
11198 let q = questions.get(&before.blocked_by[0]).unwrap();
11199 assert_eq!(q.summary, "May the saved data be deleted?");
11200 assert!(q.status.open());
11201 } else {
11202 assert_eq!(before.status, TaskStatus::Held);
11203 let recorded_reason = before.hold_reason.as_deref().unwrap();
11204 assert!(recorded_reason.starts_with(reason));
11205 if held {
11206 assert!(recorded_reason.contains("waiting for separate consent"));
11207 }
11208 }
11209 prerequisite.succeed();
11210 queue.put(&mut prerequisite).unwrap();
11211 resolve_blockers(&queue, &questions);
11212 let after = queue.get(&waiting.id).unwrap();
11213 assert_eq!(after.status, before.status);
11214 assert_eq!(after.blocked_by, before.blocked_by);
11215 assert_eq!(after.hold_reason, before.hold_reason);
11216 assert_eq!(after.instruction, waiting.instruction);
11217 if question {
11218 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11219 }
11220 assert!(
11221 queue.next_runnable().is_none(),
11222 "dependency completion is not consent"
11223 );
11224 }
11225 }
11226 }
11227 }
11228
11229 #[test]
11230 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11231 let dir = tempfile::tempdir().unwrap();
11232 let queue = Queue::at(dir.path().join("queue"));
11233 let questions = ask::Questions::at(dir.path().join("questions"));
11234
11235 let mut dep = task();
11236 dep.id = "20260101-000001-dep0".to_owned();
11237 dep.succeed();
11238 queue.put(&mut dep).unwrap();
11239
11240 let mut still_going = task();
11241 still_going.id = "20260101-000002-dep1".to_owned();
11242 queue.put(&mut still_going).unwrap();
11243
11244 let mut blocked = task();
11245 blocked.id = "20260101-000003-main".to_owned();
11246 blocked.block(
11247 vec![dep.id.clone(), still_going.id.clone()],
11248 Some("waits on both".to_owned()),
11249 );
11250 queue.put(&mut blocked).unwrap();
11251
11252 resolve_blockers(&queue, &questions);
11253
11254 let after = queue.get(&blocked.id).unwrap();
11255 assert_eq!(
11256 after.status,
11257 TaskStatus::Blocked,
11258 "one dependency is still outstanding"
11259 );
11260 assert_eq!(after.blocked_by, [still_going.id.clone()]);
11261 }
11262
11263 #[test]
11264 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11265 let dir = tempfile::tempdir().unwrap();
11266 let queue = Queue::at(dir.path().join("queue"));
11267 let questions = ask::Questions::at(dir.path().join("questions"));
11268
11269 let mut q = crate::ask::Question::new(
11270 "20260101-000001-main".to_owned(),
11271 crate::conduct::NODE.to_owned(),
11272 "conduct".to_owned(),
11273 "Which backend?".to_owned(),
11274 String::new(),
11275 Vec::new(),
11276 );
11277 questions.put(&mut q).unwrap();
11278 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11279 .unwrap();
11280 questions.put(&mut q).unwrap();
11281
11282 let mut blocked = task();
11283 blocked.id = "20260101-000001-main".to_owned();
11284 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11285 queue.put(&mut blocked).unwrap();
11286
11287 resolve_blockers(&queue, &questions);
11288
11289 let after = queue.get(&blocked.id).unwrap();
11290 assert_eq!(
11291 after.status,
11292 TaskStatus::Queued,
11293 "the only blocker resolved"
11294 );
11295 assert_eq!(after.answers.len(), 1);
11296 assert_eq!(after.answers[0].question, "Which backend?");
11297 assert_eq!(after.answers[0].answer, "SQLite");
11298
11299 let instruction = instruction_for(&after);
11301 assert!(instruction.contains("Which backend?"));
11302 assert!(instruction.contains("SQLite"));
11303 }
11304
11305 #[test]
11306 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11307 let dir = tempfile::tempdir().unwrap();
11308 let queue = Queue::at(dir.path().join("queue"));
11309 let questions = ask::Questions::at(dir.path().join("questions"));
11310
11311 let mut q = crate::ask::Question::new(
11312 "20260101-000001-main".to_owned(),
11313 crate::conduct::NODE.to_owned(),
11314 "conduct".to_owned(),
11315 "Is the setup done?".to_owned(),
11316 String::new(),
11317 Vec::new(),
11318 );
11319 q.abandon("no answer within 60s of asking");
11320 questions.put(&mut q).unwrap();
11321
11322 let mut blocked = task();
11323 blocked.id = "20260101-000001-main".to_owned();
11324 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11325 queue.put(&mut blocked).unwrap();
11326
11327 resolve_blockers(&queue, &questions);
11328
11329 let after = queue.get(&blocked.id).unwrap();
11330 assert_eq!(
11331 after.status,
11332 TaskStatus::Held,
11333 "never left blocked on nothing"
11334 );
11335 assert!(!after.operator_held(), "a machine hold, for triage");
11336 assert!(
11337 after
11338 .hold_reason
11339 .as_deref()
11340 .unwrap_or_default()
11341 .contains("went unanswered")
11342 );
11343 }
11344
11345 #[test]
11346 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11347 let dir = tempfile::tempdir().unwrap();
11353 let queue = Queue::at(dir.path().join("queue"));
11354 let questions = ask::Questions::at(dir.path().join("questions"));
11355
11356 let mut q = crate::ask::Question::new(
11357 "20260101-000001-main".to_owned(),
11358 crate::conduct::NODE.to_owned(),
11359 "conduct".to_owned(),
11360 "How should this be handled?".to_owned(),
11361 String::new(),
11362 Vec::new(),
11363 );
11364 questions.put(&mut q).unwrap();
11365 q.answer(crate::ask::Answer::Text(
11366 "leave it held, a human will look at it later".to_owned(),
11367 ))
11368 .unwrap();
11369 questions.put(&mut q).unwrap();
11370
11371 let mut held = task();
11372 held.id = "20260101-000001-main".to_owned();
11373 held.hold_machine(Some("out of attempts".to_owned()));
11374 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11375 queue.put(&mut held).unwrap();
11376
11377 resolve_blockers(&queue, &questions);
11378
11379 let after = queue.get(&held.id).unwrap();
11380 assert_eq!(after.status, TaskStatus::Held);
11381 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11382 assert_eq!(
11383 after.answers[0].answer,
11384 "leave it held, a human will look at it later"
11385 );
11386 }
11387
11388 #[test]
11389 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11390 let dir = tempfile::tempdir().unwrap();
11391 let queue = Queue::at(dir.path().join("queue"));
11392 let questions = ask::Questions::at(dir.path().join("questions"));
11393 let mut dep = task();
11394 dep.id = "20260101-000001-gone".to_owned();
11395 queue.put(&mut dep).unwrap();
11396 let mut blocked = task();
11397 blocked.id = "20260101-000003-main".to_owned();
11398 blocked.block(vec![dep.id.clone()], None);
11399 queue.put(&mut blocked).unwrap();
11400
11401 let claim = queue.claim(&blocked.id).unwrap();
11403 queue.remove(&dep.id, false, &questions).unwrap();
11404 drop(claim);
11405 resolve_blockers(&queue, &questions);
11406
11407 let after = queue.get(&blocked.id).unwrap();
11408 assert_eq!(after.status, TaskStatus::Queued);
11409 assert!(after.blocked_by.is_empty());
11410 }
11411
11412 #[test]
11413 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11414 let dir = tempfile::tempdir().unwrap();
11420 let queue = Queue::at(dir.path().join("queue"));
11421 let questions = ask::Questions::at(dir.path().join("questions"));
11422
11423 let mut still_going = task();
11424 still_going.id = "20260101-000002-dep1".to_owned();
11425 queue.put(&mut still_going).unwrap();
11426
11427 let mut blocked = task();
11428 blocked.id = "20260101-000003-main".to_owned();
11429 blocked.block(
11430 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11431 Some("waits on both".to_owned()),
11432 );
11433 queue.put(&mut blocked).unwrap();
11434
11435 resolve_blockers(&queue, &questions);
11436
11437 let after = queue.get(&blocked.id).unwrap();
11438 assert_eq!(
11439 after.status,
11440 TaskStatus::Held,
11441 "a missing dependency must not leave the task blocked forever"
11442 );
11443 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11444 assert!(after.blocked_by.is_empty());
11445 let reason = after.hold_reason.as_deref().unwrap_or_default();
11446 assert!(
11447 reason.contains("20260101-000001-gone"),
11448 "the missing id must be named so an operator can tell what happened: {reason}"
11449 );
11450 assert!(
11451 reason.contains(&still_going.id),
11452 "the still-valid dependency must not silently vanish from the record: {reason}"
11453 );
11454 }
11455
11456 #[test]
11457 fn instruction_for_is_unchanged_without_any_answers() {
11458 let t = task();
11459 assert_eq!(instruction_for(&t), t.instruction);
11460 }
11461
11462 #[test]
11463 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11464 let dir = tempfile::tempdir().unwrap();
11465 let q = Queue::at(dir.path().join("queue"));
11466 let src = dir.path().join("shot.png");
11467 std::fs::write(&src, "x").unwrap();
11468 let mut t = task();
11469 q.attach(&mut t, &[src]).unwrap();
11470 let paths = task_attachments(&q, &t).unwrap();
11471 assert_eq!(paths.len(), 1);
11472 assert!(paths[0].is_absolute() && paths[0].is_file());
11473 std::fs::remove_file(&paths[0]).unwrap();
11474 let err = task_attachments(&q, &t).unwrap_err().to_string();
11475 assert!(err.contains("shot.png"), "{err}");
11476 }
11477
11478 #[tokio::test]
11479 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11480 let dir = tempfile::tempdir().unwrap();
11481 let queue_path = dir.path().join("queue");
11482 let queue = Queue::at(queue_path.clone());
11483 let mut t = task();
11484 t.source = Source::Agent {
11485 run: "originating-chat".into(),
11486 node: crate::queue::CHAT_NODE.into(),
11487 };
11488 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11489 stage: "config-fetch",
11490 target: "origin/main".into(),
11491 });
11492 record_config_failure(&mut t, &fetch);
11493 t.hold_machine(Some(format!("{fetch:#}")));
11494 let fetch_key = t.chat_notice_due().unwrap();
11495 t.chat_notices.push(fetch_key.clone());
11496 queue.put(&mut t).unwrap();
11497
11498 let queue = Queue::at(queue_path);
11499 let mut t = queue.get(&t.id).unwrap();
11500 let a = dir.path().join("a.toml");
11501 let b = dir.path().join("b.toml");
11502 for (path, text, new_cause) in [
11503 (&a, "[graph", true),
11504 (&a, "[verify", false),
11505 (&a, "[graph]\nimplementers = 'invalid-type'", true),
11506 (&b, "[graph]\nimplementers = 'invalid-type'", true),
11507 ] {
11508 t.release_operator("test", None);
11509 std::fs::write(path, text).unwrap();
11510 let error = Config::discover_fetched(dir.path(), Some(path))
11511 .await
11512 .unwrap_err();
11513 record_config_failure(&mut t, &error);
11514 t.hold_machine(Some(format!("{error:#}")));
11515 let due = t.chat_notice_due();
11516 assert_eq!(due.is_some(), new_cause, "{error:#}");
11517 if let Some(key) = due {
11518 assert_ne!(key, fetch_key);
11519 t.chat_notices.push(key);
11520 }
11521 }
11522 t.succeed();
11523 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11524 }
11525
11526 #[test]
11527 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11528 let dir = tempfile::tempdir().unwrap();
11529 let queue_path = dir.path().join("queue");
11530 let queue = Queue::at(queue_path.clone());
11531 let mut t = task();
11532 t.source = crate::queue::Source::Agent {
11533 run: "originating-chat".into(),
11534 node: crate::queue::CHAT_NODE.into(),
11535 };
11536 let a = dir.path().join("a.png");
11537 let b = dir.path().join("b.png");
11538 std::fs::write(&a, "a").unwrap();
11539 std::fs::write(&b, "b").unwrap();
11540 queue.attach(&mut t, &[a, b]).unwrap();
11541 let paths = task_attachments(&queue, &t).unwrap();
11542 for path in &paths {
11543 std::fs::remove_file(path).unwrap();
11544 }
11545 let missing = task_attachments(&queue, &t).unwrap_err();
11546 t.attempts += 1;
11547 let reason = missing.to_string();
11548 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11549 let first = t.chat_notice_due().expect("first attachment notice");
11550 t.chat_notices.push(first.clone());
11551 queue.put(&mut t).unwrap();
11552
11553 let queue = Queue::at(queue_path.clone());
11554 let mut t = queue.get(&t.id).unwrap();
11555 assert!(t.chat_notice_due().is_none(), "restart does not replay");
11556 t.release_operator("test", None);
11557 t.attempts += 1;
11558 let missing = task_attachments(&queue, &t).unwrap_err();
11559 t.fail_startup_target(
11560 "startup-attachments",
11561 missing.name,
11562 "same missing attachment with regenerated wording",
11563 1,
11564 );
11565 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11566
11567 std::fs::write(&paths[0], "restored").unwrap();
11568 t.release_operator("test", None);
11569 t.attempts += 1;
11570 let missing = task_attachments(&queue, &t).unwrap_err();
11571 let reason = missing.to_string();
11572 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11573 let second = t
11574 .chat_notice_due()
11575 .expect("different attachment must notify");
11576 assert_ne!(first, second);
11577 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11578 }
11579
11580 #[test]
11581 fn resumed_instruction_is_unchanged_without_any_answers() {
11582 let t = task();
11583 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11584 }
11585
11586 #[test]
11587 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11588 let mut t = task();
11589 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11590 let old = t.instruction.clone();
11594
11595 let refreshed = resumed_instruction(&old, &t);
11596 assert!(refreshed.starts_with(&old), "the original text is kept");
11597 assert!(refreshed.contains("Which backend?"));
11598 assert!(refreshed.contains("SQLite"));
11599 }
11600
11601 #[test]
11602 fn resumed_instruction_keeps_an_original_answers_heading() {
11603 let mut t = task();
11604 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11605 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11606
11607 let refreshed = resumed_instruction(&t.instruction, &t);
11608
11609 assert!(
11610 refreshed.starts_with(&t.instruction),
11611 "an answers heading in the original instruction is not the appended block"
11612 );
11613 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11614 assert!(refreshed.contains("Which backend?"));
11615 assert!(refreshed.contains("SQLite"));
11616
11617 let repeated = resumed_instruction(&refreshed, &t);
11618 assert_eq!(
11619 repeated, refreshed,
11620 "only the final appended block is refreshed"
11621 );
11622 }
11623
11624 #[test]
11625 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11626 let mut t = task();
11627 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11628
11629 let once = resumed_instruction(&t.instruction, &t);
11633 let twice = resumed_instruction(&once, &t);
11634 assert_eq!(once, twice);
11635 assert_eq!(once.matches("Which backend?").count(), 1);
11636
11637 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11639 let refreshed = resumed_instruction(&once, &t);
11640 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11641 assert!(refreshed.contains("Which backend?"));
11642 assert!(refreshed.contains("Which cache?"));
11643 }
11644
11645 #[test]
11646 fn prepare_instruction_covers_all_three_starters() {
11647 let mut t = task();
11648 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11649
11650 assert_eq!(
11653 prepare_instruction(&Starter::Start, None, &t),
11654 Some(instruction_for(&t))
11655 );
11656
11657 let old = t.instruction.clone();
11660 assert_eq!(
11661 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11662 Some(resumed_instruction(&old, &t))
11663 );
11664
11665 assert_eq!(
11669 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11670 None
11671 );
11672 }
11673
11674 #[test]
11675 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11676 assert_eq!(
11677 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11678 Starter::Review("magi/eba2/A".to_owned())
11679 );
11680 }
11681
11682 #[test]
11683 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11684 assert_eq!(
11685 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11686 Starter::Start,
11687 "a vanished review branch must not fall back to resuming the old run either"
11688 );
11689 }
11690
11691 #[test]
11692 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11693 let mut t = task();
11694 t.start("old-run".to_owned());
11695 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11696 t.release();
11697 let branch = t.review_branch.take();
11698 assert_eq!(
11699 choose_starter(branch.as_deref(), true, Some("old-run")),
11700 Starter::Review("magi/eba2/A".to_owned()),
11701 "a review wins over resuming the old run"
11702 );
11703 }
11704
11705 #[test]
11706 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11707 assert_eq!(
11708 choose_starter(None, false, Some("some-run")),
11709 Starter::Resume("some-run".to_owned())
11710 );
11711 assert_eq!(choose_starter(None, false, None), Starter::Start);
11712 }
11713
11714 #[test]
11715 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11716 let mut released = task();
11717 released.start("stalled-run".to_owned());
11718 released.requeue();
11719 let unfinished = (!released.fresh_start)
11720 .then(|| Some("stalled-run".to_owned()))
11721 .flatten();
11722 assert_eq!(
11723 choose_starter(None, false, unfinished.as_deref()),
11724 Starter::Start,
11725 "release keeps run history but must not resume it"
11726 );
11727 assert_eq!(released.runs, ["stalled-run"]);
11728 }
11729
11730 fn stopped_public_run(status: RunStatus) -> RunState {
11731 let mut state = run_state(status);
11732 state.driver_exited = true;
11733 state.config.graph.land = true;
11734 state.config.graph.review_rounds = 1;
11735 state.reviews = vec![review_round(1)];
11736 state.merge = Some(crate::run::MergeOutcome {
11737 mode: MergeMode::Pr,
11738 ok: false,
11739 detail: "landing stopped".into(),
11740 empty: false,
11741 });
11742 state.pr = Some(crate::run::PrRecord {
11743 url: "https://example.test/pull/1".into(),
11744 number: 1,
11745 state: "open".into(),
11746 checks: "red".into(),
11747 round: 1,
11748 rounds: 1,
11749 red_at_merge: Vec::new(),
11750 });
11751 state
11752 }
11753
11754 #[test]
11755 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11756 for status in [RunStatus::Blocked, RunStatus::Gating] {
11757 let home = tempfile::tempdir().unwrap();
11758 let mut state = stopped_public_run(status);
11759 state.save_under(home.path()).unwrap();
11760 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11761 assert!(!exhausted_review_budget(&state));
11762 let mut task = held_task_with(&state.id);
11763 task.release();
11764 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11765 assert_eq!(
11766 choose_starter(None, false, unfinished.as_deref()),
11767 Starter::Resume(state.id.clone())
11768 );
11769 let question = action_question(&state.id, resume_action(&state.id));
11770 assert_eq!(
11771 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11772 state.clone()
11773 )),
11774 ActionDecision::Resume(state.id.clone())
11775 );
11776 assert_eq!(
11778 crate::resume::validate(home.path(), &state.id).unwrap().id,
11779 state.id
11780 );
11781 let queue = Queue::at(home.path().join("queue"));
11782 let mut controlled = Task::new(
11783 "resume land".into(),
11784 state.instruction.clone(),
11785 state.repo.clone(),
11786 Source::Agent {
11787 run: "talk".into(),
11788 node: crate::queue::CHAT_NODE.into(),
11789 },
11790 );
11791 controlled.runs.push(state.id.clone());
11792 controlled.hold_machine(Some("land stopped".into()));
11793 queue.put(&mut controlled).unwrap();
11794 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11795 assert_eq!(resumed.status, TaskStatus::Queued);
11796 assert_eq!(
11797 resumed.resume_override.unwrap().pinned_run,
11798 Some(state.id.clone())
11799 );
11800 assert_eq!(resumed.attempts, 0);
11801 }
11802 }
11803
11804 #[test]
11805 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11806 for review_rounds in [0, 1] {
11807 let home = tempfile::tempdir().unwrap();
11808 let mut state = run_state(RunStatus::Blocked);
11809 state.config.graph.review_rounds = review_rounds;
11810 if review_rounds > 0 {
11811 let mut review = review_round(1);
11812 review.clean = true;
11813 state.reviews = vec![review];
11814 }
11815 state.gate_ran = true;
11816 state.gate = vec![crate::run::CommandOutcome {
11817 command: "verify".into(),
11818 code: Some(1),
11819 output_tail: "gate failed after repair budget exhausted".into(),
11820 duration_ms: 0,
11821 resource_blocked: false,
11822 }];
11823 state.save_under(home.path()).unwrap();
11824 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11825 assert!(exhausted_review_budget(&state));
11826 let mut task = held_task_with(&state.id);
11827 task.release();
11828 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11829 let question = action_question(&state.id, resume_action(&state.id));
11830 assert_ne!(
11831 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11832 state.clone()
11833 )),
11834 ActionDecision::Resume(state.id.clone())
11835 );
11836 let error = crate::resume::validate(home.path(), &state.id)
11837 .unwrap_err()
11838 .to_string();
11839 assert!(!error.contains("review budget exhausted"), "{error}");
11840 assert!(
11841 error.contains(if review_rounds == 0 {
11842 "review is disabled"
11843 } else {
11844 "gate already ran"
11845 }),
11846 "{error}"
11847 );
11848
11849 state.gate_ran = false;
11851 state.gate.clear();
11852 assert!(!exhausted_review_budget(&state));
11853 assert_eq!(
11854 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11855 Some(state.id)
11856 );
11857 }
11858 }
11859
11860 #[test]
11861 fn resource_blocked_verification_resumes_the_same_run() {
11862 for (kind, stage) in [
11863 ("cache", "clean"),
11864 ("coordination", "clean"),
11865 ("cache", "review-e2e"),
11866 ("coordination", "no-reviews"),
11867 ("coordination", "handoff"),
11868 ] {
11869 let home = tempfile::tempdir().unwrap();
11870 let mut state = run_state(RunStatus::Blocked);
11871 state.config.graph.review_rounds = 1;
11872 let mut review = review_round(1);
11873 review.clean = true;
11874 state.reviews = vec![review];
11875 if stage == "review-e2e" {
11876 let review = &mut state.reviews[0];
11877 review.clean = false;
11878 review.blocking = 1;
11879 review.e2e = vec![crate::run::CommandOutcome {
11880 command: "verify".into(),
11881 code: None,
11882 output_tail: "resource wait expired".into(),
11883 duration_ms: 0,
11884 resource_blocked: true,
11885 }];
11886 } else if stage == "no-reviews" {
11887 state.config.graph.review_rounds = 0;
11888 state.reviews.clear();
11889 } else if stage == "handoff" {
11890 let review = &mut state.reviews[0];
11893 review.clean = false;
11894 review.blocking = 1;
11895 review.e2e = vec![crate::run::CommandOutcome {
11896 command: "verify".into(),
11897 code: Some(0),
11898 output_tail: String::new(),
11899 duration_ms: 0,
11900 resource_blocked: false,
11901 }];
11902 }
11903 state.gate_ran = false;
11904 state.resource_block = Some(crate::run::ResourceBlock {
11905 cause: crate::run::ResourceBlockCause::Other,
11906 node: if stage == "review-e2e" {
11907 "review"
11908 } else {
11909 "gate"
11910 }
11911 .into(),
11912 kind: kind.into(),
11913 detail: "resource wait expired".into(),
11914 at: jiff::Timestamp::now(),
11915 });
11916 state.save_under(home.path()).unwrap();
11917 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11918 assert!(!exhausted_review_budget(&state));
11919 let mut task = held_task_with(&state.id);
11920 task.release();
11921 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11922 assert_eq!(
11923 choose_starter(None, false, unfinished.as_deref()),
11924 Starter::Resume(state.id.clone())
11925 );
11926 let question = action_question(&state.id, resume_action(&state.id));
11927 assert_eq!(
11928 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11929 state.clone()
11930 )),
11931 ActionDecision::Resume(state.id.clone())
11932 );
11933 assert_eq!(
11934 crate::resume::validate(home.path(), &state.id).unwrap().id,
11935 state.id
11936 );
11937 let queue = Queue::at(home.path().join("queue"));
11938 let mut controlled = Task::new(
11939 "resume verification".into(),
11940 state.instruction.clone(),
11941 state.repo.clone(),
11942 Source::Agent {
11943 run: "talk".into(),
11944 node: crate::queue::CHAT_NODE.into(),
11945 },
11946 );
11947 controlled.runs.push(state.id.clone());
11948 controlled.hold_machine(Some("verification resource unavailable".into()));
11949 queue.put(&mut controlled).unwrap();
11950 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11951 assert_eq!(resumed.status, TaskStatus::Queued);
11952 assert_eq!(
11953 resumed.resume_override.unwrap().pinned_run,
11954 Some(state.id.clone())
11955 );
11956 assert_eq!(resumed.attempts, 0);
11957
11958 state.config.graph.review_rounds = 1;
11960 let mut unresolved = review_round(1);
11961 unresolved.blocking = 1;
11962 state.reviews = vec![unresolved];
11963 state.resource_block = None;
11964 state.save_under(home.path()).unwrap();
11965 assert!(exhausted_review_budget(&state));
11966 assert!(crate::resume::validate(home.path(), &state.id).is_err());
11967 }
11968 }
11969
11970 #[tokio::test]
11971 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11972 if !crate::standalone_test(
11973 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11974 ) {
11975 return;
11976 }
11977 let home = tempfile::tempdir().unwrap();
11978 let mut owner = stopped_public_run(RunStatus::Blocked);
11979 owner.save_under(home.path()).unwrap();
11980 let history = vec![owner.id.clone()];
11981 let repo = owner.repo.clone();
11982 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11983 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11984 let initial =
11985 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11986 assert!(
11987 initial.is_pending(),
11988 "a busy record must not hold or resume the task"
11989 );
11990 owner.retired_to = Some("20260101-000001-bbbb".into());
11991 owner.save_under(home.path()).unwrap();
11992 drop(lock);
11993 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11994 .await
11995 .expect("ownership lock released")
11996 .expect("read settled owner");
11997 assert!(
11998 result.is_none(),
11999 "the retired owner must not be resumed from a stale read"
12000 );
12001 }
12002
12003 #[tokio::test]
12004 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12005 if !crate::standalone_test(
12006 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12007 ) {
12008 return;
12009 }
12010 let home = tempfile::tempdir().unwrap();
12011 let mut owner = stopped_public_run(RunStatus::Blocked);
12012 let repo = tempfile::tempdir().unwrap();
12013 crate::git::git(repo.path(), &["init"]).await.unwrap();
12014 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12015 owner.id = "20260101-000000-aaaa".into();
12016 owner.save_under(home.path()).unwrap();
12017 let mut successor = run_state(RunStatus::Blocked);
12018 successor.id = "20260101-000001-bbbb".into();
12019 successor.save_under(home.path()).unwrap();
12020 let runs = vec![owner.id.clone(), successor.id.clone()];
12021 assert_eq!(
12022 public_resume_owner(home.path(), &runs, &owner.repo)
12023 .await
12024 .unwrap()
12025 .unwrap()
12026 .id,
12027 owner.id
12028 );
12029 let subdir = owner.repo.join("nested");
12030 std::fs::create_dir(&subdir).unwrap();
12031 assert_eq!(
12032 public_resume_owner(home.path(), &runs, &subdir)
12033 .await
12034 .unwrap()
12035 .unwrap()
12036 .id,
12037 owner.id
12038 );
12039 #[cfg(unix)]
12040 {
12041 let alias = home.path().join("repo-alias");
12042 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12043 assert_eq!(
12044 public_resume_owner(home.path(), &runs, &alias.join("nested"))
12045 .await
12046 .unwrap()
12047 .unwrap()
12048 .id,
12049 owner.id
12050 );
12051 }
12052 let different = tempfile::tempdir().unwrap();
12053 crate::git::git(different.path(), &["init"]).await.unwrap();
12054 assert!(
12055 public_resume_owner(home.path(), &runs, different.path())
12056 .await
12057 .is_err()
12058 );
12059 std::fs::remove_file(
12060 home.path()
12061 .join("runs")
12062 .join(&successor.id)
12063 .join("run.json"),
12064 )
12065 .unwrap();
12066 assert!(
12067 public_resume_owner(home.path(), &runs, &owner.repo)
12068 .await
12069 .is_err()
12070 );
12071 }
12072
12073 #[test]
12074 fn an_ordinary_release_keeps_a_resumable_run_available() {
12075 let mut released = task();
12076 released.start("stalled-run".to_owned());
12077 released.release();
12078 let unfinished = (!released.fresh_start)
12079 .then(|| Some("stalled-run".to_owned()))
12080 .flatten();
12081 assert_eq!(
12082 choose_starter(None, false, unfinished.as_deref()),
12083 Starter::Resume("stalled-run".to_owned()),
12084 "manual release must preserve the normal resume path"
12085 );
12086 }
12087
12088 #[test]
12089 fn resume_refusals_explain_admission_without_changing_task_or_run() {
12090 use crate::handover::{ResumeRefusal, resume_refusal_under};
12091 let home = tempfile::tempdir().unwrap();
12092 let mut exhausted = run_state(RunStatus::Blocked);
12093 exhausted.driver_exited = true;
12094 exhausted.config.graph.review_rounds = 3;
12095 exhausted.reviews = (1..=3).map(review_round).collect();
12096 for refusal in [
12097 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12098 ResumeRefusal::Status(RunStatus::Ready),
12099 ResumeRefusal::Released("20261022-000000-aaaa".into()),
12100 ResumeRefusal::Retired("retirement-successor".into()),
12101 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12102 ] {
12103 let mut state = exhausted.clone();
12104 let expected = match refusal {
12105 ResumeRefusal::Status(_) => {
12106 state.status = RunStatus::Ready;
12107 "status `ready`"
12108 }
12109 ResumeRefusal::Released(ref target) => {
12110 state.released_to = Some(target.clone());
12111 "execution was released"
12112 }
12113 ResumeRefusal::Retired(ref target) => {
12114 state.retired_to = Some(target.clone());
12115 "execution was retired"
12116 }
12117 ResumeRefusal::OwnershipTransferred(ref target) => {
12118 state.pr_taken_over_by = Some(target.clone());
12119 "PR ownership was transferred"
12120 }
12121 _ => "review budget exhausted (3/3 rounds used)",
12122 };
12123 assert_eq!(
12124 resume_refusal_under(&state, Some(home.path())),
12125 Some(refusal.clone())
12126 );
12127 assert_eq!(
12128 refusal.successor(),
12129 state
12130 .released_to
12131 .as_deref()
12132 .or(state.retired_to.as_deref())
12133 .or(state.pr_taken_over_by.as_deref())
12134 );
12135 state.save_under(home.path()).unwrap();
12136 let queue = Queue::at(home.path().join("queue"));
12137 let mut task = Task::new(
12138 "retained implementation".into(),
12139 state.instruction.clone(),
12140 state.repo.clone(),
12141 Source::Agent {
12142 run: "talk".into(),
12143 node: crate::queue::CHAT_NODE.into(),
12144 },
12145 );
12146 task.runs.push(state.id.clone());
12147 task.hold_machine(Some("stopped".into()));
12148 queue.put(&mut task).unwrap();
12149 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12150 let before_run = serde_json::to_value(&state).unwrap();
12151 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12152 .unwrap_err()
12153 .to_string();
12154 assert!(error.contains(expected), "{error}");
12155 assert!(!error.contains("only a stalled or blocked"), "{error}");
12156 if matches!(refusal, ResumeRefusal::Status(_)) {
12157 assert!(
12158 error.contains("is final; there is nothing left to resume"),
12159 "{error}"
12160 );
12161 }
12162 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12163 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12164 assert!(error.contains("review-only successor with a new review budget"));
12165 assert!(error.contains("does not resume this run"));
12166 }
12167 for target in [
12168 &state.released_to,
12169 &state.retired_to,
12170 &state.pr_taken_over_by,
12171 ]
12172 .into_iter()
12173 .flatten()
12174 {
12175 let short = if state.retired_to.as_ref() == Some(target) {
12176 target.as_str()
12177 } else {
12178 crate::run::short_of(target)
12179 };
12180 assert!(
12181 error.contains(&format!("run {short}; inspect `magi show {short}`")),
12182 "{error}"
12183 );
12184 if short != target {
12185 assert!(!error.contains(target), "full successor id leaked: {error}");
12186 }
12187 }
12188 assert_eq!(
12189 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12190 before_task
12191 );
12192 assert_eq!(
12193 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12194 .unwrap(),
12195 before_run
12196 );
12197 let question = action_question(&state.id, resume_action(&state.id));
12198 for phrases in [&PHRASES_EN, &PHRASES_JA] {
12199 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12200 RunState::load_under(id, home.path())
12201 });
12202 let ActionDecision::Refuse(detail) = decision else {
12203 panic!(
12204 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12205 state.id,
12206 home.path().display()
12207 );
12208 };
12209 assert!(detail.contains(expected), "{detail}");
12210 }
12211 }
12212 exhausted.status = RunStatus::Ready;
12214 exhausted.released_to = Some("released".into());
12215 exhausted.retired_to = Some("retired".into());
12216 exhausted.pr_taken_over_by = Some("owner".into());
12217 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12218 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12219 let detail = reason.diagnostic(&exhausted);
12220 for target in ["released", "retired", "owner"] {
12221 assert!(detail.contains(&format!("magi show {target}")));
12222 }
12223 }
12224
12225 #[test]
12226 fn resume_action_ignores_question_checkpoints_in_another_home() {
12227 crate::run::pin_test_home();
12228 let home = tempfile::tempdir().unwrap();
12229 let mut state = run_state(RunStatus::Blocked);
12230 state.id = format!(
12233 "resume-context-{}",
12234 home.path().file_name().unwrap().to_str().unwrap()
12235 );
12236 state.driver_exited = true;
12237 state.config.graph.review_rounds = 1;
12238 state.reviews = vec![review_round(1)];
12239 state.save_under(home.path()).unwrap();
12240 let task = held_task_with(&state.id);
12241 let answer = action_question(&state.id, resume_action(&state.id));
12242 let mut checkpoint = approval_question(&state.id);
12243 let foreign = Questions::open();
12244 foreign.put(&mut checkpoint).unwrap();
12245 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12246 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12247 RunState::load_under(id, home.path())
12248 });
12249 let matching: Vec<_> = foreign
12250 .list()
12251 .into_iter()
12252 .filter(|q| q.run == state.id && q.status.open())
12253 .collect();
12254 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12255 assert!(
12256 matches!(decision, ActionDecision::Refuse(_)),
12257 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12258 state.id,
12259 home.path().display(),
12260 crate::run::test_home().display()
12261 );
12262 assert_eq!(
12263 refusal,
12264 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12265 );
12266 let local = Questions::at(home.path().join("questions"));
12267 for status in [
12268 ask::QuestionStatus::Open,
12269 ask::QuestionStatus::Answered,
12270 ask::QuestionStatus::Abandoned,
12271 ] {
12272 let mut question = checkpoint.clone();
12273 match status {
12274 ask::QuestionStatus::Open => {}
12275 ask::QuestionStatus::Answered => {
12276 question
12277 .answer(ask::Answer::Choice(question.choices[0].clone()))
12278 .unwrap();
12279 }
12280 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12281 }
12282 local.put(&mut question).unwrap();
12283 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12284 RunState::load_under(id, home.path())
12285 });
12286 if status.open() {
12287 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12288 } else {
12289 assert!(
12290 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12291 "status={status:?}, decision={decision:?}"
12292 );
12293 }
12294 }
12295 }
12296
12297 #[test]
12298 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12299 let home = tempfile::tempdir().unwrap();
12300 let mut state = run_state(RunStatus::Stalled);
12301 state.id = format!(
12302 "resume-driver-{}",
12303 home.path().file_name().unwrap().to_str().unwrap()
12304 );
12305 state.driver_claimed = Some(false);
12306 state.save_under(home.path()).unwrap();
12307 let task = held_task_with(&state.id);
12308 let question = action_question(&state.id, resume_action(&state.id));
12309 let decide = || {
12310 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12311 RunState::load_under(id, home.path())
12312 })
12313 };
12314 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12315 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12316 assert_eq!(
12317 decide(),
12318 ActionDecision::Refuse("run already has a live driver".into())
12319 );
12320 drop(lease);
12321 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12322 }
12323
12324 #[test]
12325 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12326 let home = tempfile::tempdir().unwrap();
12327 let mut state = run_state(RunStatus::Blocked);
12328 state.driver_exited = true;
12329 state.config.graph.review_rounds = 1;
12330 state.reviews = vec![review_round(1)];
12331 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12332 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12333 let mut saved = state.clone();
12334 match checkpoint {
12335 "publication" => saved.pr_publication_pending = true,
12336 "approval" => {
12337 saved.land_approval = Some(crate::run::LandApproval {
12338 question: "approval".into(),
12339 head: "head".into(),
12340 })
12341 }
12342 "armed" => saved.land_armed_head = Some("head".into()),
12343 "landing" => saved.status = RunStatus::Landing,
12344 _ => {
12345 let mut question = ask::Question::new(
12346 saved.id.clone(),
12347 "review".into(),
12348 "review-1".into(),
12349 "continue?".into(),
12350 String::new(),
12351 vec!["continue".into()],
12352 );
12353 ask::Questions::at(home.path().join("questions"))
12354 .put(&mut question)
12355 .unwrap();
12356 }
12357 }
12358 saved.save_under(home.path()).unwrap();
12359 assert!(
12360 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12361 "{checkpoint}"
12362 );
12363 assert!(
12364 crate::resume::validate(home.path(), &saved.id).is_ok(),
12365 "{checkpoint}"
12366 );
12367 }
12368 }
12369
12370 #[test]
12371 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12372 let mut state = run_state(RunStatus::Blocked);
12373 state.config.graph.review_rounds = 3;
12374 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12375 assert!(exhausted_review_budget(&state));
12376
12377 state.reviews.pop();
12379 assert!(!exhausted_review_budget(&state));
12380
12381 let mut stalled = run_state(RunStatus::Stalled);
12384 stalled.config.graph.review_rounds = 1;
12385 stalled.reviews = vec![review_round(1)];
12386 assert!(!exhausted_review_budget(&stalled));
12387 }
12388
12389 fn review_round(round: usize) -> crate::run::ReviewRound {
12390 crate::run::ReviewRound {
12391 round,
12392 head: "deadbeef".to_owned(),
12393 verified_head: None,
12394 verified_at: None,
12395 reviews: Vec::new(),
12396 e2e: Vec::new(),
12397 verify_retried: false,
12398 e2e_deferred: false,
12399 e2e_defer_reason: None,
12400 fix: None,
12401 blocking: 0,
12402 answered: 1,
12403 expected: 1,
12404 clean: false,
12405 progressed: true,
12406 vote_split: false,
12407 reconsideration: Vec::new(),
12408 verdict: None,
12409 }
12410 }
12411
12412 #[test]
12413 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12414 let mut run = RunState::new(
12415 PathBuf::from("/repo"),
12416 "main".to_owned(),
12417 "abc1234def".to_owned(),
12418 "add retries".to_owned(),
12419 Config::default(),
12420 );
12421 run.status = RunStatus::Judging;
12422 run.parked = true;
12423 let mut task = Task::new(
12424 "add retries".to_owned(),
12425 "add retries".to_owned(),
12426 PathBuf::from("/repo"),
12427 crate::queue::Source::Human,
12428 );
12429 task.status = TaskStatus::Failed;
12430 task.runs = vec![run.id.clone()];
12431 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12432 assert!(with(&task, &run), "parked after judging is the case");
12433 let mut parked_task = task.clone();
12434 parked_task.status = TaskStatus::Parked;
12435 assert!(with(&parked_task, &run), "the Parked status is the case");
12436
12437 let mut not_parked = run.clone();
12438 not_parked.parked = false;
12439 not_parked.status = RunStatus::Stalled;
12440 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
12441
12442 let mut fresh = task.clone();
12443 fresh.fresh_start = true;
12444 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12445
12446 let mut review = task.clone();
12447 review.review_branch = Some("magi/x/A".to_owned());
12448 assert!(!with(&review, &run), "review is ranked before resume");
12449
12450 let mut held = task.clone();
12451 held.status = TaskStatus::Held;
12452 assert!(!with(&held, &run), "a hold stays visible to the conductor");
12453
12454 let mut released = run.clone();
12455 released.released_to = Some("20260901-000000-new1".to_owned());
12456 assert!(!with(&task, &released), "nothing left to resume into");
12457
12458 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12459 "unreadable"
12460 )));
12461 }
12462
12463 #[test]
12464 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12465 let mut released = RunState::new(
12466 PathBuf::from("/repo"),
12467 "main".to_owned(),
12468 "abc1234def".to_owned(),
12469 "add retries".to_owned(),
12470 Config::default(),
12471 );
12472 released.status = RunStatus::Blocked;
12473 assert_eq!(
12474 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12475 Some(released.id.clone())
12476 );
12477 released.released_to = Some("20260901-000000-new1".to_owned());
12478 assert_eq!(
12479 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12480 None,
12481 "there is nothing left to resume it into"
12482 );
12483 }
12484
12485 #[test]
12486 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12487 let mut exhausted = RunState::new(
12496 PathBuf::from("/repo"),
12497 "main".to_owned(),
12498 "abc1234def".to_owned(),
12499 "add retries".to_owned(),
12500 Config::default(),
12501 );
12502 exhausted.status = RunStatus::Blocked;
12503 exhausted.config.graph.review_rounds = 1;
12504 exhausted.reviews = vec![review_round(1)];
12505
12506 assert_eq!(
12507 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12508 None,
12509 "an exhausted `Blocked` run must not be offered as resumable"
12510 );
12511
12512 let mut has_budget_left = RunState::new(
12515 PathBuf::from("/repo"),
12516 "main".to_owned(),
12517 "abc1234def".to_owned(),
12518 "add retries".to_owned(),
12519 Config::default(),
12520 );
12521 has_budget_left.status = RunStatus::Blocked;
12522 has_budget_left.config.graph.review_rounds = 3;
12523 has_budget_left.reviews = vec![review_round(1)];
12524
12525 assert_eq!(
12526 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12527 Ok(has_budget_left.clone())
12528 }),
12529 Some(has_budget_left.id.clone())
12530 );
12531 }
12532
12533 #[test]
12534 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12535 let mut run = RunState::new(
12536 PathBuf::from("/repo"),
12537 "main".to_owned(),
12538 "abc1234def".to_owned(),
12539 "add retries".to_owned(),
12540 Config::default(),
12541 );
12542 run.status = RunStatus::Blocked;
12543 run.config.graph.review_rounds = 1;
12544 run.reviews = vec![review_round(1)];
12545 run.pr_publication_pending = true;
12546 assert_eq!(
12547 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12548 Some(run.id.clone()),
12549 "a spent review budget must not turn a failed publication into a re-competition"
12550 );
12551 }
12552
12553 #[test]
12554 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12555 let mut task = Task::new(
12556 "recover work".into(),
12557 "recover work".into(),
12558 PathBuf::from("/repo"),
12559 crate::queue::Source::Human,
12560 );
12561 let mut history = std::collections::BTreeMap::new();
12562 for index in 0..8 {
12563 let mut run = run_state(RunStatus::Blocked);
12564 run.id = format!("20260101-000000-{index:04}");
12565 run.base_commit = format!("upstream-{index}");
12566 if index > 0 {
12568 run.candidates.clear();
12569 }
12570 task.runs.extend([run.id.clone(), run.id.clone()]);
12571 history.insert(run.id.clone(), run);
12572 task.requeue();
12573 }
12574 let check = |task: &Task, starter: &Starter, limit| {
12575 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12576 };
12577 assert!(
12578 check(&task, &Starter::Start, 8)
12579 .unwrap()
12580 .contains("8 unretired")
12581 );
12582 assert!(check(&task, &Starter::Start, 9).is_none());
12583 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12584 task.release_operator("owner", None);
12585 assert_eq!(task.attempts, 0);
12586 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12587 assert!(check(&restored, &Starter::Start, 8).is_some());
12588 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12589 assert!(check(&restored, &Starter::Start, 0).is_none());
12590 }
12591
12592 #[test]
12593 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
12594 let tmp = tempfile::tempdir().unwrap();
12595 let mut task = Task::new(
12596 "recover selected PR".into(),
12597 "preserve implementation".into(),
12598 tmp.path().join("repo"),
12599 crate::queue::Source::Human,
12600 );
12601 let mut failed = run_state(RunStatus::Failed);
12602 failed.id = "20260101-000000-fail".into();
12603 failed.candidates.clear();
12604 failed.prep_complete = Some(false);
12605 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
12606 failed.startup = Some(crate::run::Startup {
12607 kind: "pr-recovery".into(),
12608 branch: Some("selected-public-head".into()),
12609 stage: "worktree-setup".into(),
12610 complete: false,
12611 failure: Some("setup modified a tracked file and failed".into()),
12612 });
12613 let worktree = failed.worktree_root().join("under-review");
12616 std::fs::create_dir_all(&worktree).unwrap();
12617 let retained_edit = worktree.join("implementation");
12618 std::fs::write(&retained_edit, "retained setup edit").unwrap();
12619 task.record_startup_failure(crate::run::StartupFailure {
12620 run: failed.id.clone(),
12621 stage: "worktree-setup".into(),
12622 });
12623 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12624 assert!(task.runs.is_empty() && task.passes.is_empty());
12625 assert_eq!(task.attempts, 0);
12626 let starter = Starter::Review("selected-public-head".into());
12627 assert!(
12628 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
12629 .unwrap()
12630 .contains("1 unretired")
12631 );
12632 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
12633 assert!(
12634 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
12635 .unwrap()
12636 .contains("Cannot verify")
12637 );
12638 let mut mixed = task.clone();
12640 mixed.runs.push(failed.id.clone());
12641 mixed
12642 .startup_failures
12643 .push(task.startup_failures[0].clone());
12644 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
12645 failed.retired_to = Some("verified-recovery-owner".into());
12646 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
12647 assert!(
12648 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
12649 panic!("resuming the existing owner must not allocate a new attempt")
12650 })
12651 .is_none()
12652 );
12653 assert_eq!(
12654 std::fs::read_to_string(retained_edit).unwrap(),
12655 "retained setup edit"
12656 );
12657 assert!(task.runs.is_empty() && task.passes.is_empty());
12658 assert_eq!(task.attempts, 0);
12659 }
12660
12661 #[test]
12662 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12663 let mut task = Task::new(
12664 "recover work".into(),
12665 "recover work".into(),
12666 PathBuf::from("/repo"),
12667 crate::queue::Source::Human,
12668 );
12669 let mut run = run_state(RunStatus::Superseded);
12670 run.candidates.clear();
12671 task.runs.push(run.id.clone());
12672 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12673 run.retired_to = Some("authority".into());
12674 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12675 run.retired_to = None;
12676 run.released_to = Some("authority".into());
12677 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12678 assert!(
12679 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12680 .unwrap()
12681 .contains("Cannot verify")
12682 );
12683 assert!(
12685 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12686 panic!("resume must not load historical attempts")
12687 })
12688 .is_none()
12689 );
12690 }
12691
12692 #[test]
12693 fn retired_resume_requires_a_valid_same_repository_authority() {
12694 let mut source = run_state(RunStatus::Blocked);
12695 let mut empty = run_state(RunStatus::Blocked);
12696 empty.retired_to = Some(source.id.clone());
12697 let runs = vec![source.id.clone(), empty.id.clone()];
12698 let resolve = |source: &RunState, empty: &RunState| {
12699 unfinished_run_with(&runs, "fixture", |id| {
12700 if id == source.id {
12701 Ok(source.clone())
12702 } else if id == empty.id {
12703 Ok(empty.clone())
12704 } else {
12705 bail!("unreadable authority")
12706 }
12707 })
12708 };
12709 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12710 assert_eq!(
12711 choose_starter(None, false, resolve(&source, &empty).as_deref()),
12712 Starter::Resume(source.id.clone())
12713 );
12714 source.retired_to = Some(empty.id.clone());
12715 assert!(
12716 resolve(&source, &empty).is_none(),
12717 "cycles do not revive obsolete runs"
12718 );
12719 source.retired_to = None;
12720 source.repo = PathBuf::from("/another-repository");
12721 assert!(resolve(&source, &empty).is_none());
12722 source.repo = empty.repo.clone();
12723 source.released_to = Some("later".into());
12724 assert!(resolve(&source, &empty).is_none());
12725 empty.retired_to = Some("unlisted-run".into());
12726 assert!(resolve(&source, &empty).is_none());
12727 }
12728
12729 #[test]
12730 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12731 let mut older_stalled = RunState::new(
12739 PathBuf::from("/repo"),
12740 "main".to_owned(),
12741 "abc1234def".to_owned(),
12742 "add retries".to_owned(),
12743 Config::default(),
12744 );
12745 older_stalled.status = RunStatus::Stalled;
12746
12747 let mut newest_exhausted = RunState::new(
12748 PathBuf::from("/repo"),
12749 "main".to_owned(),
12750 "abc1234def".to_owned(),
12751 "add retries".to_owned(),
12752 Config::default(),
12753 );
12754 newest_exhausted.status = RunStatus::Blocked;
12755 newest_exhausted.config.graph.review_rounds = 1;
12756 newest_exhausted.reviews = vec![review_round(1)];
12757
12758 assert_eq!(
12759 unfinished_run_with(
12760 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12761 "t",
12762 |_| Ok(newest_exhausted.clone())
12763 ),
12764 None,
12765 "the newest run is exhausted, so nothing here is worth resuming - \
12766 least of all the older, already-superseded run"
12767 );
12768 }
12769
12770 #[test]
12771 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12772 assert_eq!(
12773 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12774 Err(anyhow::anyhow!("fixture is absent"))
12775 }),
12776 None
12777 );
12778 }
12779
12780 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12781 let mut q = ask::Question::new(
12782 run.to_owned(),
12783 "implement".to_owned(),
12784 "impl-A".to_owned(),
12785 "continue?".to_owned(),
12786 String::new(),
12787 vec!["resume で続行する".to_owned(), "other".to_owned()],
12788 );
12789 q.actions.insert("resume で続行する".to_owned(), action);
12790 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12791 .unwrap();
12792 q
12793 }
12794
12795 fn held_task_with(run: &str) -> Task {
12796 let mut t = task();
12797 t.runs = vec![run.to_owned()];
12798 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12799 t
12800 }
12801
12802 fn resume_action(run: &str) -> ask::ChoiceAction {
12803 ask::ChoiceAction::Resume { run: run.into() }
12804 }
12805
12806 #[test]
12807 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12808 let home = crate::run::test_home();
12809 for parked in [false, true] {
12810 let mut t = task();
12811 t.start("A".into());
12812 t.start("B".into());
12813 assert_eq!(t.runs, vec!["A", "B"]);
12814 t.start("A".into());
12815 let mut resumed = run_state(RunStatus::Blocked);
12816 resumed.id = "A".into();
12817 resumed.parked = parked;
12818 resumed.driver_exited = true;
12819 t.hold_machine(Some("resumed run stopped".into()));
12820 let q = action_question("A", resume_action("A"));
12821 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12822 assert_eq!(
12823 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
12824 assert_eq!(id, "A");
12825 Ok(resumed.clone())
12826 }),
12827 ActionDecision::Resume("A".into())
12828 );
12829 assert_eq!(
12830 action_standing(&t, &action_question("B", resume_action("B"))),
12831 ActionStanding::Stale
12832 );
12833 t.release_operator("cli", None);
12834 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12835 assert_eq!(id, "A");
12836 Ok(resumed.clone())
12837 });
12838 assert_eq!(
12839 choose_starter(None, false, unfinished.as_deref()),
12840 Starter::Resume("A".into())
12841 );
12842 assert_eq!(t.runs, vec!["B", "A"]);
12843 }
12844 }
12845
12846 #[test]
12847 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12848 let home = crate::run::test_home();
12849 let mut state = crate::land::tests::repair_state(true, true);
12850 state.status = RunStatus::Landing;
12851 state.parked = true;
12852 state.driver_exited = true;
12853 let mut q = ask::Question::new(
12854 state.id.clone(),
12855 land::APPROVAL_NODE.into(),
12856 "land".into(),
12857 "Merge?".into(),
12858 String::new(),
12859 vec![land::APPROVE.into(), land::HOLD.into()],
12860 );
12861 q.id = state.id.clone();
12862 state.land_approval = Some(crate::run::LandApproval {
12863 question: q.id.clone(),
12864 head: "current-head".into(),
12865 });
12866 assert!(land::upgrade_repair_choice(&mut q, &state));
12867 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12868 let mut task = held_task_with(&state.id);
12869 task.status = TaskStatus::Parked;
12870 assert_eq!(
12871 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12872 ActionDecision::Resume(state.id.clone())
12873 );
12874 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12875 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12876 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12877 assert_eq!(
12878 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12879 ActionDecision::Resume(state.id.clone()),
12880 "a repair answer newer than the manual hold resumes the existing owner"
12881 );
12882 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12883 for answered_at in [q.answered_at, None] {
12884 let mut older = q.clone();
12885 older.answered_at = answered_at;
12886 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
12887 panic!("a later manual hold must prevent dispatch")
12888 });
12889 let ActionDecision::Refuse(reason) = refused else {
12890 panic!("expected an actionable refusal, got {refused:?}");
12891 };
12892 assert!(reason.contains("later operator decision"));
12893 assert!(reason.contains(&format!("magi task release {}", task.id)));
12894 }
12895 task.operator_decided_at = None;
12896 let mut superseded = state.clone();
12897 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12898 assert_eq!(
12899 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
12900 ActionDecision::Stale
12901 );
12902 for case in 1..4 {
12903 let mut changed = state.clone();
12904 match case {
12905 1 => changed.status = RunStatus::Blocked,
12906 2 => changed.released_to = Some("new-owner".into()),
12907 _ => changed.land_approval.as_mut().unwrap().head.clear(),
12908 }
12909 assert!(matches!(
12910 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
12911 ActionDecision::Refuse(_)
12912 ));
12913 }
12914 assert!(matches!(
12915 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
12916 "missing owner"
12917 )),
12918 ActionDecision::Refuse(_)
12919 ));
12920 task.runs.push("replacement".into());
12921 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12922 assert_eq!(
12923 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
12924 "old owner must not load"
12925 )),
12926 ActionDecision::Stale
12927 );
12928 }
12929
12930 #[test]
12931 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12932 let mut state = crate::land::tests::repair_state(true, true);
12933 state.status = RunStatus::Landing;
12934 state.parked = true;
12935 state.driver_exited = true;
12936 let mut q = ask::Question::new(
12937 state.id.clone(),
12938 land::APPROVAL_NODE.into(),
12939 "land".into(),
12940 "Merge?".into(),
12941 String::new(),
12942 vec![land::APPROVE.into(), land::HOLD.into()],
12943 );
12944 q.id = state.id.clone();
12945 state.land_approval = Some(crate::run::LandApproval {
12946 question: q.id.clone(),
12947 head: "current-head".into(),
12948 });
12949 state.save().unwrap();
12950 land::upgrade_repair_choice(&mut q, &state);
12951 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12952 Questions::open().put(&mut q).unwrap();
12953 let tmp = tempfile::tempdir().unwrap();
12954 let queue = Queue::at(tmp.path().join("queue"));
12955 let mut task = held_task_with(&state.id);
12956 task.status = TaskStatus::Parked;
12957 queue.put(&mut task).unwrap();
12958 let empty = Arc::new(tokio::sync::Semaphore::new(0));
12959 let free = Arc::new(tokio::sync::Semaphore::new(1));
12960 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12961 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12962 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12963 assert!(claim.permit.is_some());
12964 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12965 drop(claim);
12966 Questions::open()
12967 .update(&q.id, |q| {
12968 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12969 Ok(())
12970 })
12971 .unwrap();
12972 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12973 assert!(claim.permit.is_none());
12974 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12975 }
12976
12977 #[test]
12978 fn decide_action_resumes_only_the_latest_resumable_run() {
12979 let home = crate::run::test_home();
12980 let t = held_task_with("r1");
12981 let q = action_question("r1", resume_action("r1"));
12982 let load = |s: RunState| move |_: &str| Ok(s);
12983 assert_eq!(
12984 decide_action(
12985 &home,
12986 &t,
12987 &q,
12988 &PHRASES_EN,
12989 load(run_state(RunStatus::Blocked))
12990 ),
12991 ActionDecision::Resume("r1".into())
12992 );
12993 let q_other = action_question("r1", resume_action("r0"));
12995 assert!(matches!(
12996 decide_action(
12997 &home,
12998 &t,
12999 &q_other,
13000 &PHRASES_EN,
13001 load(run_state(RunStatus::Blocked))
13002 ),
13003 ActionDecision::Refuse(_)
13004 ));
13005 assert!(matches!(
13007 decide_action(
13008 &home,
13009 &t,
13010 &q,
13011 &PHRASES_EN,
13012 load(run_state(RunStatus::Ready))
13013 ),
13014 ActionDecision::Refuse(_)
13015 ));
13016 let mut released = run_state(RunStatus::Blocked);
13018 released.released_to = Some("elsewhere".into());
13019 assert!(matches!(
13020 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13021 ActionDecision::Refuse(_)
13022 ));
13023 assert!(matches!(
13025 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13026 ActionDecision::Refuse(_)
13027 ));
13028 }
13029
13030 #[test]
13031 fn decide_action_ignores_a_question_about_an_earlier_run() {
13032 let home = crate::run::test_home();
13033 let mut t = held_task_with("r1");
13034 t.runs.push("r2".to_owned());
13035 let never = |_: &str| -> Result<RunState> { bail!("not read") };
13036 assert_eq!(
13037 decide_action(
13038 &home,
13039 &t,
13040 &action_question("r1", ask::ChoiceAction::Done),
13041 &PHRASES_EN,
13042 never
13043 ),
13044 ActionDecision::Stale
13045 );
13046 }
13047
13048 #[test]
13049 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13050 let home = crate::run::test_home();
13051 let mut t = held_task_with("r1");
13052 let never = |_: &str| -> Result<RunState> { bail!("not read") };
13053 assert_eq!(
13054 decide_action(
13055 &home,
13056 &t,
13057 &action_question("r1", ask::ChoiceAction::Requeue),
13058 &PHRASES_EN,
13059 never
13060 ),
13061 ActionDecision::Requeue
13062 );
13063 let done_q = action_question("r1", ask::ChoiceAction::Done);
13064 assert_eq!(
13065 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13066 ActionDecision::Done
13067 );
13068 t.mark_action_applied(&done_q.id);
13069 assert_eq!(
13070 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13071 ActionDecision::Skip
13072 );
13073
13074 let mut plain = action_question("r1", ask::ChoiceAction::Done);
13076 plain.actions.clear();
13077 assert_eq!(
13078 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13079 ActionDecision::Skip
13080 );
13081 let mut running = held_task_with("r1");
13083 running.status = TaskStatus::Running;
13084 assert_eq!(
13085 decide_action(
13086 &home,
13087 &running,
13088 &action_question("r1", ask::ChoiceAction::Done),
13089 &PHRASES_EN,
13090 never
13091 ),
13092 ActionDecision::Skip
13093 );
13094 }
13095
13096 #[test]
13097 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13098 crate::run::pin_test_home();
13099 for legacy in [false, true] {
13100 let dir = tempfile::tempdir().unwrap();
13101 let queue = Queue::at(dir.path().join("queue"));
13102 let questions = Questions::at(dir.path().join("questions"));
13103 let run = "20260101-000000-hold";
13104 let mut task = held_task_with(run);
13105 task.status = TaskStatus::Parked;
13106 let mut q = ask::Question::new(
13107 run.into(),
13108 land::APPROVAL_NODE.into(),
13109 "land".into(),
13110 "Repair?".into(),
13111 String::new(),
13112 vec![land::REPAIR.into()],
13113 );
13114 q.actions.insert(land::REPAIR.into(), resume_action(run));
13115 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13116 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13118 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13119 questions.put(&mut q).unwrap();
13120 task.hold_manual(Some("Keep this PR paused".into()));
13121 if legacy {
13122 task.hold_source = None;
13123 }
13124 queue.put(&mut task).unwrap();
13125
13126 apply_task_choice_actions(&queue, &questions, dir.path());
13127 let after = queue.get(&task.id).unwrap();
13128 assert!(after.operator_held());
13129 assert_eq!(after.hold_source, task.hold_source);
13130 assert_eq!(after.operator_decided_at, task.operator_decided_at);
13131 assert_eq!(after.runs, task.runs);
13132 assert_eq!(after.instruction, task.instruction);
13133 assert!(after.resume_override.is_none());
13134 assert!(after.action_applied(&q.id));
13135 let reason = after.hold_reason.as_deref().unwrap();
13136 assert!(reason.starts_with("Keep this PR paused"));
13137 assert!(reason.contains("later operator decision"));
13138 assert!(reason.contains(&format!("magi task release {}", task.id)));
13139
13140 for recovery in [
13141 crate::conduct::Recovery::Review,
13142 crate::conduct::Recovery::Requeue,
13143 ] {
13144 crate::conduct::apply(
13145 &queue,
13146 &questions,
13147 &crate::conduct::Verdict {
13148 decisions: vec![crate::conduct::Decision {
13149 id: task.id.clone(),
13150 recovery: Some(recovery),
13151 ..Default::default()
13152 }],
13153 },
13154 )
13155 .unwrap();
13156 }
13157 apply_task_choice_actions(&queue, &questions, dir.path());
13160 let still_held = queue.get(&task.id).unwrap();
13161 assert!(still_held.operator_held());
13162 assert_eq!(still_held.hold_reason, after.hold_reason);
13163 assert_eq!(still_held.runs, task.runs);
13164 assert!(still_held.review_branch.is_none());
13165 assert!(!still_held.fresh_start);
13166 assert!(queue.next_runnable().is_none());
13167 }
13168 }
13169
13170 #[test]
13171 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13172 for held in [false, true] {
13173 for retry in [false, true] {
13174 let dir = tempfile::tempdir().unwrap();
13175 let queue = Queue::at(dir.path().join("queue"));
13176 let questions = Questions::at(dir.path().join("questions"));
13177 let home = dir.path().join("home");
13178 let mut t = task();
13179 if held {
13180 t.hold_machine(Some("driver state unknown".into()));
13181 }
13182 queue.put(&mut t).unwrap();
13183 let verdict = serde_json::from_value(serde_json::json!({
13184 "decisions": [{
13185 "id": t.id,
13186 "question": "Driver state unknown; retry the checks or hold?",
13187 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13188 "actions": {
13189 "daemon: recheck and retry": {"do": "requeue"},
13190 "daemon: hold the task": {"do": "hold"}
13191 }
13192 }]
13193 }))
13194 .unwrap();
13195 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13196 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13197 let mut q = questions.list().pop().unwrap();
13198 let choice = if retry {
13199 "daemon: recheck and retry"
13200 } else {
13201 "daemon: hold the task"
13202 };
13203 assert_eq!(q.actions.len(), 2);
13204 q.answer(ask::Answer::Choice(choice.into())).unwrap();
13205 questions.put(&mut q).unwrap();
13206
13207 questions.beat(&q.id, ask::WaiterKind::Deputy);
13209 for _ in 0..2 {
13210 resolve_blockers(&queue, &questions);
13211 apply_task_choice_actions(&queue, &questions, &home);
13212 let waiting = queue.get(&t.id).unwrap();
13213 assert_eq!(waiting.status, TaskStatus::Blocked);
13214 assert_eq!(waiting.blocked_by, [q.id.clone()]);
13215 assert!(waiting.answers.is_empty());
13216 assert!(!waiting.action_applied(&q.id));
13217 assert!(runnable(&queue).is_empty());
13218 let free = Arc::new(tokio::sync::Semaphore::new(1));
13219 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13220 }
13221 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13222
13223 resolve_blockers(&queue, &questions);
13225 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13226 apply_task_choice_actions(&queue, &questions, &home);
13227 let after = queue.get(&t.id).unwrap();
13228 assert_eq!(
13229 after.status,
13230 if retry {
13231 TaskStatus::Queued
13232 } else {
13233 TaskStatus::Held
13234 }
13235 );
13236 assert!(after.action_applied(&q.id));
13237 assert_eq!(after.operator_held(), !retry);
13238 assert_eq!(after.answers.len(), 1);
13239
13240 let mut changed = after;
13242 if retry {
13243 changed.hold_manual(Some("later hold".into()));
13244 } else {
13245 changed.release_operator("test", None);
13246 }
13247 let expected = changed.status;
13248 queue.put(&mut changed).unwrap();
13249 apply_task_choice_actions(&queue, &questions, &home);
13250 assert_eq!(queue.get(&t.id).unwrap().status, expected);
13251 }
13252 }
13253 }
13254
13255 #[test]
13256 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13257 let dir = tempfile::tempdir().unwrap();
13258 let queue = Queue::at(dir.path().join("queue"));
13259 let questions = Questions::at(dir.path().join("questions"));
13260 let home = dir.path().join("home");
13261 let mut state = run_state(RunStatus::Blocked);
13262 state.id = "20260101-000000-act1".to_owned();
13263 state.save_under(&home).unwrap();
13264
13265 let mut t = held_task_with(&state.id);
13266 queue.put(&mut t).unwrap();
13267 let mut q = action_question(&state.id, resume_action(&state.id));
13268 questions.put(&mut q).unwrap();
13269
13270 apply_task_choice_actions(&queue, &questions, &home);
13271 let after = queue.get(&t.id).unwrap();
13272 assert_eq!(after.status, TaskStatus::Queued);
13273 assert!(!after.fresh_start);
13274 assert!(after.action_applied(&q.id));
13275 let pin = after.resume_override.clone().unwrap();
13276 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13277 assert!(pin.forced);
13278
13279 let mut again = queue.get(&t.id).unwrap();
13281 again.hold_machine(Some("later".into()));
13282 queue.put(&mut again).unwrap();
13283 apply_task_choice_actions(&queue, &questions, &home);
13284 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13285 }
13286
13287 #[test]
13288 fn a_delivered_answer_is_still_acted_on_exactly_once() {
13289 let dir = tempfile::tempdir().unwrap();
13290 let queue = Queue::at(dir.path().join("queue"));
13291 let questions = Questions::at(dir.path().join("questions"));
13292 let home = dir.path().join("home");
13293 let mut state = run_state(RunStatus::Blocked);
13294 state.id = "20260101-000000-act2".to_owned();
13295 state.save_under(&home).unwrap();
13296
13297 let mut t = held_task_with(&state.id);
13298 queue.put(&mut t).unwrap();
13299 let mut q = action_question(&state.id, resume_action(&state.id));
13300 q.answer_delivered = true;
13301 questions.put(&mut q).unwrap();
13302
13303 apply_task_choice_actions(&queue, &questions, &home);
13306 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13307 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13308
13309 let mut again = queue.get(&t.id).unwrap();
13311 again.hold_machine(Some("later".into()));
13312 queue.put(&mut again).unwrap();
13313 apply_task_choice_actions(&queue, &questions, &home);
13314 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13315 }
13316
13317 #[test]
13318 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13319 let dir = tempfile::tempdir().unwrap();
13320 let queue = Queue::at(dir.path().join("queue"));
13321 let questions = Questions::at(dir.path().join("questions"));
13322 let home = dir.path().join("home");
13323 let mut state = run_state(RunStatus::Blocked);
13324 state.id = "20260101-000000-act3".to_owned();
13325 state.save_under(&home).unwrap();
13326 let mut t = held_task_with(&state.id);
13327 queue.put(&mut t).unwrap();
13328 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13329 questions.put(&mut q).unwrap();
13330
13331 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13332 apply_task_choice_actions(&queue, &questions, &home);
13333 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13334
13335 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13336 apply_task_choice_actions(&queue, &questions, &home);
13337 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13338 }
13339
13340 #[test]
13341 fn action_standing_tells_the_reasons_apart() {
13342 let mut t = held_task_with("r1");
13343 let q = action_question("r1", ask::ChoiceAction::Requeue);
13344 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13345 let mut plain = q.clone();
13346 plain.actions.clear();
13347 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13348
13349 t.mark_action_applied(&q.id);
13351 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13352
13353 let mut t = held_task_with("r1");
13355 t.start("r2".to_owned());
13356 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13357 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13359 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13360 t.status = TaskStatus::Blocked;
13361 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13362
13363 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13365 c.node = crate::conduct::NODE.to_owned();
13366 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13367 assert!(!ActionStanding::Busy.daemon_owns());
13368 }
13369
13370 #[test]
13371 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13372 let dir = tempfile::tempdir().unwrap();
13373 let queue = Queue::at(dir.path().join("queue"));
13374 let questions = Questions::at(dir.path().join("questions"));
13375 let home = dir.path().join("home");
13376 let mut state = run_state(RunStatus::Blocked);
13377 state.id = "20260101-000000-act4".to_owned();
13378 state.save_under(&home).unwrap();
13379 let mut t = held_task_with(&state.id);
13380 t.status = TaskStatus::Running;
13381 queue.put(&mut t).unwrap();
13382 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13383 q.cwd = Some(dir.path().display().to_string());
13384 questions.put(&mut q).unwrap();
13385
13386 let running = queue.get(&t.id).unwrap();
13389 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13390 assert!(matches!(
13391 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13392 crate::waiter::Action::Deliver(_)
13393 ));
13394 apply_task_choice_actions(&queue, &questions, &home);
13396 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13397 let mut back = queue.get(&t.id).unwrap();
13398 back.hold_machine(Some("later".into()));
13399 queue.put(&mut back).unwrap();
13400 apply_task_choice_actions(&queue, &questions, &home);
13401 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13402 let mut again = queue.get(&t.id).unwrap();
13403 again.hold_machine(Some("again".into()));
13404 queue.put(&mut again).unwrap();
13405 apply_task_choice_actions(&queue, &questions, &home);
13406 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13407 }
13408}