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("Base synchronization remains stopped. Inspect the retained run; for movement exhaustion, explicitly use `magi run --resume <run> --recover-base`. A release without a new owner approval grants no additional rebase and starts no replacement competition.".into()));
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.recovery_exhausted(
4353 &head,
4354 &inputs,
4355 task.attempt_limit
4356 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4357 ) {
4358 task.hold_unrequested_retry(Some(reason));
4359 record(queue, task);
4360 return Vec::new();
4361 }
4362 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4363 }
4364
4365 if let Some(reason) = disk_gate(&repo, &config) {
4373 task.notice_cause("disk-space", None, None);
4374 task.last_error = Some(reason.clone());
4375 task.hold_machine(Some(reason.clone()));
4376 record(queue, task);
4377 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4378 notices::raise(
4381 Notice::warn(
4382 &format!("disk:{}", repo.display()),
4383 format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4384 )
4385 .link(Link::Task {
4386 id: task.id.clone(),
4387 }),
4388 );
4389 return Vec::new();
4390 }
4391
4392 let review_branch = take_review_branch(task, previous.as_ref());
4417 let branch_exists = match &review_branch {
4418 Some(branch) => crate::git::branch_exists(&repo, branch)
4419 .await
4420 .unwrap_or(false),
4421 None => false,
4422 };
4423 let proposed = review_retry_starter(
4427 task,
4428 previous.as_ref(),
4429 review_branch.as_deref(),
4430 branch_exists,
4431 unfinished.as_deref(),
4432 );
4433 let retry_selected = task.replacement.is_some()
4434 && task.resumption.is_some()
4435 && !task.fresh_start
4436 && previous.as_ref().is_some_and(|run| {
4437 run.replaces.is_some()
4438 && ((run.status == RunStatus::Failed && run.viable().is_empty())
4439 || (run.status == RunStatus::Blocked && run.tally.is_none()))
4440 });
4441 let stop_pin = task
4442 .resume_override
4443 .as_ref()
4444 .filter(|pin| {
4445 Questions::open().get(&pin.question_id).is_ok_and(|q| {
4446 q.node == land::APPROVAL_NODE
4447 && q.resolution()
4448 .as_deref()
4449 .is_some_and(crate::merge_decision::stops)
4450 })
4451 })
4452 .and_then(|pin| pin.pinned_run.clone());
4453 let starter = if let Some(owner) = &public_owner {
4454 Starter::Resume(owner.id.clone())
4455 } else if let Some(run) = stop_pin {
4456 Starter::Resume(run)
4459 } else if retry_selected {
4460 Starter::Resume(previous.as_ref().unwrap().id.clone())
4461 } else if let Some(selected) = &task.pr_recovery {
4462 if selected.check_task(&task.id, &task.instruction).is_ok() {
4463 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4464 } else {
4465 Starter::Review(selected.branch.clone())
4466 }
4467 } else {
4468 starter_with_implementers(task, previous.as_ref(), proposed)
4469 };
4470 if let Some(pin) = &task.resume_override
4473 && let Some(run) = &pin.pinned_run
4474 && starter != Starter::Resume(run.clone())
4475 {
4476 let run = run.clone();
4477 task.notice_cause("resume-owner", Some(&run), None);
4478 task.hold_machine(Some(format!(
4479 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4480 task.id
4481 )));
4482 record(queue, task);
4483 return Vec::new();
4484 }
4485 if task.replacement.is_some()
4486 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4487 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4488 {
4489 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()));
4490 record(queue, task);
4491 return Vec::new();
4492 }
4493 if let Some(reason) = retained_attempt_hold(
4494 task,
4495 &starter,
4496 config.disk.retained_attempt_limit,
4497 RunState::load,
4498 ) {
4499 if let Starter::Review(branch) = &starter {
4502 task.review_branch = Some(branch.clone());
4503 }
4504 task.hold_unrequested_retry(Some(reason));
4505 record(queue, task);
4506 return Vec::new();
4507 }
4508 let attachments = match task_attachments(queue, task) {
4513 Ok(a) => a,
4514 Err(e) => {
4515 task.attempts += 1;
4516 task.fail_startup_target(
4517 "startup-attachments",
4518 e.name.clone(),
4519 format!("{start_failed}{e:#}"),
4520 opts.max_attempts,
4521 );
4522 record(queue, task);
4523 return Vec::new();
4524 }
4525 };
4526 let startup_pause = stop.pause();
4527 let startup_interrupt = interrupt_pause.clone();
4528 let wait = crate::repo_lock::WaitPolicy::new(
4529 Duration::from_secs(config.graph.timeout_resource_wait),
4530 move || startup_pause.parked() || startup_interrupt.parked(),
4531 );
4532 let started = wait.scope(Box::pin(async { match &starter {
4535 Starter::Review(_) if task.pr_recovery.is_some() => {
4536 let selected = task.pr_recovery.clone().expect("selected recovery");
4537 match selected.check_task(&task.id, &task.instruction) {
4538 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4539 .await
4540 .map(|mut r| {
4541 r.state.attachments = attachments.clone();
4542 r
4543 }),
4544 Err(e) => Err(e),
4545 }
4546 }
4547 Starter::Review(branch) => {
4548 tracing::info!(
4549 "task {} reopens `{branch}` as a review-only pass",
4550 task.short()
4551 );
4552 let takeover = crate::handover::Takeover {
4555 earlier: task.earlier_attempts().to_vec(),
4556 home: crate::run::home(),
4557 choice: take_divergence_answer(branch, &config.merge.remote, task),
4558 task_instruction: Some(instruction_for(task)),
4559 };
4560 Runner::review_taking_over(
4561 &repo,
4562 branch,
4563 config,
4564 Some(takeover),
4565 crate::run::Origin::queue(&task.id),
4566 )
4567 .await
4568 }
4569 Starter::Resume(id) => {
4570 tracing::info!("resuming run {id} rather than competing again");
4571 Runner::resume(id).and_then(|mut r| {
4572 if retry_selected {
4573 for candidate in &mut r.state.candidates {
4576 candidate.failed = None;
4577 candidate.empty = false;
4578 candidate.commits = 0;
4579 }
4580 r.state.status = RunStatus::Implementing;
4581 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4582 }
4583 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4584 r.state.sources = task.sources.clone();
4585 }
4586 if r.state.prep_failure.is_some() {
4587 let approval = task
4588 .resumption
4589 .as_ref()
4590 .context("preparation retry requires an explicit task release")?;
4591 r.retry_preparation(approval.at)?;
4592 }
4593 if let Some(instruction) =
4594 prepare_instruction(&starter, Some(&r.state.instruction), task)
4595 {
4596 r.state.instruction = instruction;
4597 }
4598 r.state.attachments = attachments.clone();
4599 if task.replacement.is_some() {
4600 r.state.config.merge.mode = MergeMode::Pr;
4601 r.state.config.graph.land_approval = true;
4602 }
4603 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4607 .overrides
4608 .as_ref()
4609 .and_then(|o| o.merge.as_deref())
4610 .and_then(|m| merge_mode(m).ok())
4611 {
4612 r.state.config.merge.mode = mode;
4613 }
4614 Ok(r)
4615 })
4616 }
4617 Starter::Start => {
4618 if let Some(branch) = &review_branch {
4619 tracing::warn!(
4620 "conductor chose review for task {} but branch `{branch}` no longer \
4621 exists; requeuing as a fresh competition instead",
4622 task.short()
4623 );
4624 }
4625 let instruction = prepare_instruction(&starter, None, task)
4626 .unwrap_or_else(|| task.instruction.clone());
4627 Runner::start_naming(
4628 &repo,
4629 instruction,
4630 &task.title,
4631 config,
4632 crate::run::Origin::queue(&task.id),
4633 )
4634 .await
4635 .map(|mut r| {
4636 r.state.attachments = attachments.clone();
4637 r.state.sources = task.sources.clone();
4638 r
4639 })
4640 }
4641 }})).await;
4642 if let Err(error) = &started
4643 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4644 {
4645 task.record_startup_failure(failure.clone());
4646 }
4647 let mut runner = match started {
4648 Ok(r) => r,
4649 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4650 task.last_error = Some(e.to_string());
4651 if stop.parking() || interrupt_pause.parked() {
4652 let attempts = task.attempts;
4653 task.park(e.to_string());
4654 task.attempts = attempts;
4656 } else {
4657 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4658 }
4659 record(queue, task);
4660 return Vec::new();
4661 }
4662 Err(e) if task.pr_recovery.is_some() => {
4666 task.startup_notice_cause("startup-public-head");
4667 task.attempts += 1;
4668 task.last_error = Some(format!("{start_failed}{e:#}"));
4669 task.hold_unrequested_retry(Some(format!(
4670 "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."
4671 )));
4672 record(queue, task);
4673 return Vec::new();
4674 }
4675 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4676 let detail = match e.downcast_ref::<crate::handover::Refused>() {
4677 Some(r) => (p.handover_refused)(r),
4678 None => format!("{e:#}"),
4679 };
4680 task.startup_notice_cause("startup-handover");
4681 let reason = format!("{start_failed}{detail}");
4682 task.last_error = Some(reason.clone());
4683 let branch = match &starter {
4686 Starter::Review(branch) => Some(branch.clone()),
4687 _ => None,
4688 };
4689 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4693 record(queue, task);
4694 tracing::warn!(
4695 "holding {} for a branch it cannot take over: {e:#}",
4696 task.short()
4697 );
4698 return Vec::new();
4699 }
4700 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4705 let d = e
4706 .downcast_ref::<crate::reconcile::Diverged>()
4707 .expect("checked by the guard");
4708 let mut q = ask::Question::new(
4709 task.id.clone(),
4710 crate::reconcile::NODE.to_owned(),
4711 crate::reconcile::SEAT.to_owned(),
4712 d.summary(),
4713 d.detail(),
4714 d.choices(),
4715 );
4716 match Questions::open().put(&mut q) {
4717 Ok(()) => {
4718 task.last_error = Some(format!("{e:#}"));
4719 task.review_branch = Some(d.branch.clone());
4722 task.review_instruction = Some(task.instruction.clone());
4723 task.block(vec![q.id.clone()], Some(d.summary()));
4724 }
4725 Err(put) => {
4726 tracing::warn!("could not file the divergence question: {put:#}");
4727 task.attempts += 1;
4728 task.fail_startup(
4729 "startup-question-store",
4730 format!("{start_failed}{e:#}"),
4731 opts.max_attempts,
4732 );
4733 }
4734 }
4735 record(queue, task);
4736 return Vec::new();
4737 }
4738 Err(e) => {
4739 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4745 && let Starter::Review(branch) = &starter
4746 {
4747 task.review_branch = Some(branch.clone());
4748 task.review_instruction = Some(task.instruction.clone());
4749 task.last_error = Some(format!("{start_failed}{e:#}"));
4750 task.status = crate::queue::TaskStatus::Failed;
4751 record(queue, task);
4752 return Vec::new();
4753 }
4754 task.attempts += 1;
4755 task.last_error = Some(format!("{start_failed}{e:#}"));
4756 task.startup_notice_cause("startup-source");
4757 task.hold_unrequested_retry(Some(format!(
4758 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4759 )));
4760 record(queue, task);
4761 return Vec::new();
4762 }
4763 };
4764 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4765 runner.state.recovery_config = Some(config_evidence);
4766 }
4767 if let Some(replacement) = &task.replacement {
4768 if matches!(starter, Starter::Start) {
4769 runner.state.instruction.push_str(&format!(
4770 "\n\n# Replacement review context\n{}",
4771 replacement.context
4772 ));
4773 }
4774 runner.state.replaces = Some(replacement.clone());
4775 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4776 if let Ok(mut old) = RunState::load(&replacement.run)
4777 && let Some(d) = &mut old.merge_decision
4778 {
4779 d.replacement_run = Some(runner.state.id.clone());
4780 old.event(
4781 "replacement",
4782 format!(
4783 "replacement run {} owns the next attempt; old PR remains closed",
4784 runner.state.id
4785 ),
4786 );
4787 if let Err(e) = old.save() {
4788 let error = runner.fail_startup("replacement-history", e);
4789 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4790 task.record_startup_failure(failure.clone());
4791 }
4792 task.hold_manual(Some(format!(
4793 "Could not link replacement history: {error:#}; no agents dispatched"
4794 )));
4795 record(queue, task);
4796 return Vec::new();
4797 }
4798 }
4799 }
4800 runner.state.task_instruction = Some(task.instruction.clone());
4801 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4804 if runner.state.origin_chat.is_none() {
4805 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4806 }
4807 runner.on_pause(stop.pause());
4809 runner.watch_interrupt(interrupt_pause);
4813
4814 let run = runner.state.id.clone();
4817 let before_start = task.clone();
4818 task.start(run.clone());
4819 if let Err(error) = queue.put(task) {
4820 *task = before_start;
4821 let error = runner.fail_startup("task-start", error);
4822 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4823 task.record_startup_failure(failure.clone());
4824 }
4825 task.hold_manual(Some(format!(
4826 "Could not persist task start; no agents dispatched: {error:#}"
4827 )));
4828 record(queue, task);
4829 return Vec::new();
4830 }
4831 lock(status).current.push(Current {
4832 worker: None,
4833 task: task.id.clone(),
4834 run,
4835 });
4836
4837 let quota_before = runner.state.quota.clone();
4840 runner.state.next_pass_task_entry = true;
4841 let result = runner.execute().await;
4842 finish_attempt(
4843 opts.max_attempts,
4844 queue,
4845 task,
4846 &runner.state,
4847 "a_before,
4848 result,
4849 )
4850}
4851
4852pub fn finish_attempt(
4857 max_attempts: usize,
4858 queue: &Queue,
4859 task: &mut Task,
4860 state: &RunState,
4861 quota_before: &[QuotaLoss],
4862 result: Result<()>,
4863) -> Vec<QuotaLoss> {
4864 let detail = match result {
4865 Ok(()) => describe(state),
4866 Err(e) => format!("{e:#}"),
4867 };
4868 let fresh = losses_this_attempt(quota_before, &state.quota);
4869 let verdict = Verdict {
4870 status: state.status,
4871 left_pr: state.pr.is_some(),
4874 quota_hit: !fresh.is_empty(),
4880 parked: state.parked,
4884 no_viable_candidates: state.viable().is_empty(),
4887 };
4888 if let Some(replacement) = &state.replaces
4889 && let Some(pr) = &state.pr
4890 && let Ok(mut old) = RunState::load(&replacement.run)
4891 && let Some(d) = &mut old.merge_decision
4892 {
4893 d.replacement_pr = Some(pr.url.clone());
4894 let _ = old.save();
4895 }
4896 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4897 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4898 task.hold_unrequested_retry(Some(format!(
4899 "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.",
4900 task.short()
4901 )));
4902 }
4903 if task.status == TaskStatus::Done {
4904 supersede_prior_runs(task, &crate::run::home());
4905 }
4906 record(queue, task);
4907 tracing::info!(
4908 "task {} is {} after run {} ({})",
4909 task.short(),
4910 task.status.as_str(),
4911 state.short(),
4912 label(state.status)
4913 );
4914 fresh
4915}
4916
4917pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4921 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4924 && !awaiting_resume_with(task, RunState::load)
4925 && withheld_text_wait(task).is_none()
4929 && !(task.fresh_start && task.replacement.is_some())
4930 {
4931 let why = task.last_error.clone().map_or_else(
4932 || "the run did not finish".to_owned(),
4933 |e| format!("the run did not finish: {e}"),
4934 );
4935 task.hold_unrequested_retry(Some(format!(
4936 "{why}. It was started by hand, so it is not retried \
4937 automatically; `magi task release` retries it."
4938 )));
4939 record(queue, task);
4940 }
4941}
4942
4943#[must_use]
4947pub fn loop_would_resume(run: &str) -> bool {
4948 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4949}
4950
4951#[must_use]
4961pub fn foreign_loop(
4962 reading: Option<&Reading>,
4963 now: Timestamp,
4964 own_pid: u32,
4965) -> Option<Option<u32>> {
4966 let reading = reading.filter(|r| r.running(now))?;
4967 match reading.pid {
4968 Some(pid) if pid == own_pid => None,
4969 pid => Some(pid),
4970 }
4971}
4972
4973fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4974 reading.worker_protocol != Some(1)
4975 && (foreign_loop(Some(reading), now, own_pid).is_some()
4976 || reading
4977 .pid
4978 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4979}
4980
4981pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4992 run_claimed_until(opts, queue, task, &Stop::new()).await;
4993}
4994
4995async fn run_claimed_until(
4996 opts: &Opts,
4997 queue: &Queue,
4998 task: &mut Task,
4999 stop: &Stop,
5000) -> Vec<QuotaLoss> {
5001 let status = Arc::new(Mutex::new(Status::new()));
5002 let mut quota = Box::pin(attempt(
5005 opts,
5006 queue,
5007 &status,
5008 stop,
5009 crate::graph::Pause::new(),
5010 task,
5011 ))
5012 .await;
5013 let mut resumes = 0;
5022 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5023 let Some(timeout) = withheld_text_wait(task) else {
5024 break;
5025 };
5026 eprintln!(
5027 "waiting for the owner's answer on a withheld pull request text \
5028 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5029 );
5030 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5033 let ready = loop {
5034 match land_resume_state(task) {
5035 LandResume::StillWaiting
5036 if !stop.parking() && std::time::Instant::now() < limit =>
5037 {
5038 tokio::time::sleep(WITHHELD_POLL).await;
5039 }
5040 LandResume::Ready => break true,
5041 _ => break false,
5042 }
5043 };
5044 if !ready || stop.parking() {
5045 break;
5046 }
5047 resumes += 1;
5048 quota.extend(
5049 Box::pin(attempt(
5050 opts,
5051 queue,
5052 &status,
5053 stop,
5054 crate::graph::Pause::new(),
5055 task,
5056 ))
5057 .await,
5058 );
5059 }
5060 hold_if_runnable(queue, task);
5061 quota
5062}
5063
5064const MAX_WITHHELD_RESUMES: u32 = 3;
5067
5068const WITHHELD_POLL: Duration = Duration::from_secs(15);
5070
5071fn withheld_text_wait(task: &Task) -> Option<u64> {
5074 let id = task.runs.last()?;
5075 let s = RunState::load(id).ok()?;
5076 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5077 .then_some(s.config.graph.answer_timeout)
5078}
5079
5080fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5090 after
5091 .iter()
5092 .filter(|q| !before.contains(q))
5093 .cloned()
5094 .collect()
5095}
5096
5097fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5100 let quota: Vec<_> = quota
5101 .iter()
5102 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5103 .collect();
5104 if quota.is_empty() {
5105 return None;
5106 }
5107 let with_hint = quota.iter().find(|q| q.reset.is_some());
5108 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5109 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5110 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5111 Some(
5112 now.checked_add(jiff::SignedDuration::from_secs(secs))
5113 .unwrap_or(Timestamp::MAX),
5114 )
5115}
5116
5117fn implementers_match(task: &Task, state: &RunState) -> bool {
5119 task.replacement.as_ref().map_or_else(
5120 || {
5121 task.implementers()
5122 .is_none_or(|n| n == state.config.graph.implementers)
5123 },
5124 |replacement| {
5125 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5126 && state.config.graph.implementers == 1
5127 },
5128 )
5129}
5130
5131fn starter_with_implementers(
5133 task: &Task,
5134 previous: Option<&RunState>,
5135 proposed: Starter,
5136) -> Starter {
5137 if previous.is_some_and(|s| !implementers_match(task, s)) {
5138 task.review_of
5139 .as_ref()
5140 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5141 } else {
5142 proposed
5143 }
5144}
5145
5146fn apply_task_implementers(config: &mut Config, task: &Task) {
5148 if let Some(n) = task.implementers() {
5149 config.graph.implementers = n;
5150 }
5151}
5152
5153#[cfg(test)]
5158fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5159 let explicit = match &task.overrides {
5160 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5161 _ => opts.config.as_deref(),
5162 };
5163 let (mut config, _) = Config::discover(repo, explicit)?;
5164 apply_options(&mut config, opts, task)?;
5165 Ok(config)
5166}
5167
5168fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5169 if task
5170 .overrides
5171 .as_ref()
5172 .is_none_or(|o| o.inherit_daemon_options)
5173 && let Some(mode) = opts.merge.as_deref()
5174 {
5175 config.merge.mode = merge_mode(mode)?;
5176 }
5177 if let Some(o) = &task.overrides {
5178 o.apply(config);
5179 }
5180 Ok(())
5181}
5182
5183fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5185 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5186 if let Some(mode) = &opts.merge {
5187 config.merge.mode = merge_mode(mode)?;
5188 }
5189 Ok(config)
5190}
5191
5192async fn maybe_prune_cache_between_runs(
5197 repo: &Path,
5198 opts: &Opts,
5199 home: &Path,
5200 stop: &Stop,
5201 last_checked: &mut Option<Timestamp>,
5202 now: Timestamp,
5203) {
5204 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5205 return;
5206 }
5207 *last_checked = Some(now);
5208 let cfg = match prepare(repo, opts) {
5209 Ok(cfg) => cfg,
5210 Err(e) => {
5211 tracing::warn!("cache check: no config: {e:#}");
5212 return;
5213 }
5214 };
5215 match clean::prune_cache_if_over_limit(&cfg, home) {
5216 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5217 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5218 pruned.files,
5219 pruned.freed
5220 ),
5221 Ok(_) => {}
5222 Err(e) => {
5223 tracing::warn!("housekeep: prune cache: {e:#}");
5224 notices::raise_in(
5225 home,
5226 Notice::warn(
5227 "housekeep:cache",
5228 format!(
5229 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5230 e.to_string()
5231 .lines()
5232 .next()
5233 .unwrap_or("unknown cleanup error")
5234 ),
5235 ),
5236 );
5237 }
5238 }
5239}
5240
5241fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5245 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5246}
5247
5248async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5267 let cfg = match prepare(repo, opts) {
5268 Ok(cfg) => cfg,
5269 Err(e) => {
5270 tracing::warn!("housekeep: no config: {e:#}");
5271 return;
5272 }
5273 };
5274 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5283 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5284 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5289 let mut extra = Vec::new();
5290 if out.unreadable > 0 {
5291 extra.push(format!("{} unreadable", out.unreadable));
5292 }
5293 if out.orphaned_worktrees > 0 {
5294 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5295 }
5296 let detail = if extra.is_empty() {
5297 String::new()
5298 } else {
5299 format!(" ({})", extra.join(", "))
5300 };
5301 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5302 }
5303 if out.external_merges_recorded > 0 {
5304 tracing::info!(
5305 "housekeep: recorded {} run(s) as merged externally",
5306 out.external_merges_recorded
5307 );
5308 }
5309 if out.stale_pr_states_repaired > 0 {
5310 tracing::info!(
5311 "housekeep: rewrote {} run record(s) whose pull request had already settled",
5312 out.stale_pr_states_repaired
5313 );
5314 }
5315 if out.cache_files > 0 {
5316 tracing::info!(
5317 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5318 out.cache_files,
5319 out.cache_freed
5320 );
5321 }
5322 if out.questions_abandoned > 0 {
5323 tracing::info!(
5324 "housekeep: abandoned {} question(s) left open by a finished run",
5325 out.questions_abandoned
5326 );
5327 }
5328}
5329
5330async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5339 let questions = Questions::at(home.join("questions"));
5340 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5341 if report.is_empty() {
5342 return;
5343 }
5344 if !report.quarantined.is_empty() {
5345 tracing::info!(
5346 "triage: held {} blocked task(s) whose blocked-on task or \
5347 question no longer exists: {}",
5348 report.quarantined.len(),
5349 report.quarantined.join(", ")
5350 );
5351 }
5352 if !report.resumed.is_empty() {
5353 tracing::info!(
5354 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5355 report.resumed.len(),
5356 report.resumed.join(", ")
5357 );
5358 }
5359 if !report.asked.is_empty() {
5360 tracing::info!(
5361 "triage: asked about {} held task(s): {}",
5362 report.asked.len(),
5363 report.asked.join(", ")
5364 );
5365 }
5366 if !report.answered.is_empty() {
5367 tracing::info!(
5368 "triage: applied {} operator answer(s): {}",
5369 report.answered.len(),
5370 report.answered.join(", ")
5371 );
5372 }
5373}
5374
5375pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5382 disk_gate_with(repo, config, crate::disk::free_bytes)
5383}
5384
5385fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5389 repo: &Path,
5390 config: &Config,
5391 free_bytes: F,
5392) -> Option<String> {
5393 let min = config.disk.min_free_bytes;
5394 if min == 0 {
5395 return None;
5396 }
5397 let mut paths = vec![repo.to_owned()];
5398 if let Some(cache) = config.cache_dir() {
5399 paths.push(cache);
5400 }
5401 if let Some(root) = &config.graph.worktree_root {
5402 paths.push(root.clone());
5403 }
5404 for path in paths {
5405 let probe = if path == repo {
5406 path.as_path()
5407 } else {
5408 path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5409 };
5410 let reason = match free_bytes(probe) {
5411 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5412 Err(e) => Some(crate::disk::unmeasured_in(
5413 probe,
5414 &e,
5415 &config.graph.language,
5416 )),
5417 };
5418 if reason.is_some() {
5419 return reason;
5420 }
5421 }
5422 None
5423}
5424
5425const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5432
5433const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5437
5438fn quota_wait(
5447 reset_at: Option<Timestamp>,
5448 now: Timestamp,
5449 fallback: Duration,
5450 cap: Duration,
5451) -> Duration {
5452 match reset_at {
5453 Some(at) if at > now => {
5454 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5455 Duration::from_secs(secs).min(cap)
5456 }
5457 _ => fallback,
5458 }
5459}
5460
5461fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5475 parse_reset_hint_zoned(text, now)
5476 .or_else(|| parse_reset_hint_dated(text))
5477 .or_else(|| parse_reset_hint_relative(text, recorded))
5478}
5479
5480fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5484 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5485 let mut rest = rest.trim();
5486 if rest.is_empty() {
5487 return None;
5488 }
5489 let mut total: i64 = 0;
5490 let mut matched = false;
5491 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5492 if let Some((digits, tail)) = rest.split_once(unit)
5493 && !digits.is_empty()
5494 && digits.bytes().all(|b| b.is_ascii_digit())
5495 {
5496 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5497 rest = tail;
5498 matched = true;
5499 }
5500 }
5501 if !rest.is_empty() || !matched {
5502 return None;
5503 }
5504 recorded
5505 .checked_add(jiff::SignedDuration::from_secs(total))
5506 .ok()
5507}
5508
5509fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5513 let clock = clock.trim().to_lowercase();
5514 let (digits, pm) = clock
5515 .strip_suffix("am")
5516 .map(|d| (d, false))
5517 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5518 let (h, m) = digits.trim().split_once(':')?;
5519 let mut hour: i8 = h.trim().parse().ok()?;
5520 let minute: i8 = m.trim().parse().ok()?;
5521 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5522 return None;
5523 }
5524 if pm && hour != 12 {
5525 hour += 12;
5526 } else if !pm && hour == 12 {
5527 hour = 0;
5528 }
5529 Some((hour, minute))
5530}
5531
5532fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5537 let open = text.find('(')?;
5538 let close = text.rfind(')')?;
5539 if close <= open {
5540 return None;
5541 }
5542 let zone = text[open + 1..close].trim();
5543 let (hour, minute) = parse_12h_clock(&text[..open])?;
5544 let tz = jiff::tz::TimeZone::get(zone).ok()?;
5545 let candidate = now
5546 .to_zoned(tz)
5547 .with()
5548 .hour(hour)
5549 .minute(minute)
5550 .second(0)
5551 .millisecond(0)
5552 .microsecond(0)
5553 .nanosecond(0)
5554 .build()
5555 .ok()?;
5556 let mut at = candidate.timestamp();
5557 if at <= now {
5558 at += jiff::SignedDuration::from_hours(24);
5559 }
5560 Some(at)
5561}
5562
5563fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5572 let words: Vec<&str> = text.split_whitespace().collect();
5573 if words.len() < 5 {
5574 return None;
5575 }
5576 (0..=words.len() - 5)
5577 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5578}
5579
5580fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5586 if trailing.is_some_and(|next| next.starts_with('(')) {
5587 return None;
5588 }
5589 let month = month_number(window[0])?;
5590 let day_token = window[1].strip_suffix(',')?.to_lowercase();
5591 let day_digits = ["st", "nd", "rd", "th"]
5592 .iter()
5593 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5594 let day: i8 = day_digits.parse().ok()?;
5595 let year_token = window[2];
5596 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5597 return None;
5598 }
5599 let year: i16 = year_token.parse().ok()?;
5600 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5604 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5605 let date = jiff::civil::Date::new(year, month, day).ok()?;
5606 let candidate = date
5607 .at(hour, minute, 0, 0)
5608 .to_zoned(jiff::tz::TimeZone::UTC)
5609 .ok()?;
5610 Some(candidate.timestamp())
5611}
5612
5613fn month_number(name: &str) -> Option<i8> {
5616 const NAMES: [&str; 12] = [
5617 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5618 ];
5619 let lower = name.to_lowercase();
5620 NAMES
5621 .iter()
5622 .position(|n| *n == lower.as_str())
5623 .map(|i| i as i8 + 1)
5624}
5625
5626#[cfg(test)]
5628fn exhausted_review_budget(state: &RunState) -> bool {
5629 !crate::handover::can_resume(state)
5632 && state.status == RunStatus::Blocked
5633 && !state.released()
5634 && state.retired_to.is_none()
5635}
5636
5637fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5674 unfinished_run_with(runs, short, RunState::load)
5675}
5676
5677pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5680where
5681 F: FnMut(&str) -> Result<RunState>,
5682{
5683 let mut id = runs.last()?.clone();
5684 let mut visited = std::collections::BTreeSet::new();
5685 let mut repo = None;
5686 loop {
5687 if !runs.contains(&id) || !visited.insert(id.clone()) {
5688 tracing::warn!("invalid or cyclic recovery authority for task {short}");
5689 return None;
5690 }
5691 let state = match load(&id) {
5692 Ok(state) if state.id == id => state,
5693 Ok(_) => return None,
5694 Err(e) => {
5695 tracing::warn!("could not read run {id} for task {short}: {e:#}");
5696 return None;
5697 }
5698 };
5699 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5700 return None;
5701 }
5702 repo = Some(state.repo.clone());
5703 if let Some(authority) = state.retired_to {
5704 id = authority;
5705 continue;
5706 }
5707 return (crate::handover::can_resume(&state)
5708 && state.liveness(false) != crate::run::Liveness::Live)
5709 .then_some(id);
5710 }
5711}
5712
5713fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5721where
5722 F: FnOnce(&str) -> Result<RunState>,
5723{
5724 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5726 || task.fresh_start
5727 || task.review_branch.is_some()
5728 {
5729 return false;
5730 }
5731 let Some(id) = task.runs.last() else {
5732 return false;
5733 };
5734 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5735}
5736
5737#[derive(Debug, Clone, PartialEq, Eq)]
5740enum Starter {
5741 Review(String),
5744 Resume(String),
5746 Start,
5748}
5749
5750fn retained_attempt_hold(
5755 task: &Task,
5756 starter: &Starter,
5757 limit: usize,
5758 mut load: impl FnMut(&str) -> Result<RunState>,
5759) -> Option<String> {
5760 if limit == 0 || matches!(starter, Starter::Resume(_)) {
5761 return None;
5762 }
5763 let mut retained = 0;
5764 for id in task
5765 .runs
5766 .iter()
5767 .chain(task.startup_failures.iter().map(|failure| &failure.run))
5768 .collect::<std::collections::BTreeSet<_>>()
5769 {
5770 let state = match load(id) {
5771 Ok(state) if state.id == *id => state,
5772 _ => {
5773 return Some(format!(
5774 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5775 ));
5776 }
5777 };
5778 if state.retired_to.is_some() || state.released() {
5779 continue;
5780 }
5781 retained += 1;
5784 }
5785 (retained >= limit).then(|| format!(
5786 "[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."
5787 ))
5788}
5789
5790fn selected_starter(
5792 selected: &crate::pr_recovery::Selection,
5793 previous: Option<&RunState>,
5794 unfinished: Option<&str>,
5795) -> Starter {
5796 if let Some(id) = unfinished
5797 && previous.is_some_and(|r| {
5798 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5799 })
5800 {
5801 Starter::Resume(id.to_owned())
5802 } else {
5803 Starter::Review(selected.branch.clone())
5804 }
5805}
5806
5807fn take_divergence_answer(
5811 branch: &str,
5812 remote: &str,
5813 task: &mut Task,
5814) -> Option<crate::reconcile::Choice> {
5815 let summary = crate::reconcile::summary_for(branch, remote);
5816 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5817 (a.question == summary)
5818 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5819 .flatten()
5820 .map(|c| (i, c))
5821 })?;
5822 task.answers.remove(idx);
5823 Some(choice)
5824}
5825
5826fn choose_starter(
5838 review_branch: Option<&str>,
5839 branch_exists: bool,
5840 unfinished: Option<&str>,
5841) -> Starter {
5842 match review_branch {
5843 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5844 Some(_) => Starter::Start,
5845 None => match unfinished {
5846 Some(id) => Starter::Resume(id.to_owned()),
5847 None => Starter::Start,
5848 },
5849 }
5850}
5851
5852fn review_retry_starter(
5856 task: &Task,
5857 previous: Option<&RunState>,
5858 branch: Option<&str>,
5859 exists: bool,
5860 unfinished: Option<&str>,
5861) -> Starter {
5862 if let Some(run) = previous
5863 && unfinished == Some(run.id.as_str())
5864 && run.reviewed_commits.is_some()
5865 && branch.is_some_and(|branch| {
5866 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5867 })
5868 && may_resume_run(run, task)
5869 {
5870 return Starter::Resume(run.id.clone());
5871 }
5872 match (branch, unfinished, &task.review_of) {
5873 (None, None, Some(branch)) => Starter::Review(branch.clone()),
5874 _ => choose_starter(branch, exists, unfinished),
5875 }
5876}
5877
5878fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5880 let branch = task.review_branch.take();
5881 let instruction = task.review_instruction.take();
5882 branch.filter(|branch| match &instruction {
5883 Some(authored) => *authored == task.instruction,
5884 None => previous.map_or_else(
5887 || task.review_of.as_ref() == Some(branch),
5888 |run| compatible_run_instruction(run, task),
5889 ),
5890 })
5891}
5892
5893fn may_resume_run(run: &RunState, task: &Task) -> bool {
5896 task.resume_override
5897 .as_ref()
5898 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5899 || compatible_run_instruction(run, task)
5900}
5901
5902pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5904 if let Some(authored) = &run.task_instruction {
5905 return compatible_instruction(authored, task);
5906 }
5907 if compatible_instruction(&run.instruction, task) {
5908 return true;
5909 }
5910 if run.reviewed_commits.is_some() {
5913 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5914 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5915 }
5916 if let Some(branch) = &task.review_of {
5917 let canonical = format!(
5918 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5919 );
5920 let generated = format!(
5921 "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"
5922 );
5923 return task.instruction == canonical && run.instruction.starts_with(&generated);
5924 }
5925 }
5926 false
5927}
5928
5929pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5931 strip_answers_block(old, task) == task.instruction
5932}
5933
5934fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5937 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5938 return fallback.to_path_buf();
5939 }
5940 task.repo.clone()
5941}
5942
5943const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5947
5948fn answers_block(task: &Task, count: usize) -> String {
5950 let mut s = ANSWERS_HEADER.to_owned();
5951 for a in &task.answers[..count] {
5952 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5953 }
5954 s
5955}
5956
5957fn resumption_block(r: &crate::queue::Resumption) -> String {
5960 format!(
5961 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5962 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5963 r.generation, r.at, r.instruction, r.answers_through,
5964 )
5965}
5966
5967fn append_answers(base: &str, task: &Task) -> String {
5969 let mut s = base.to_owned();
5970 if !task.answers.is_empty() {
5971 s.push_str(&answers_block(task, task.answers.len()));
5972 }
5973 if let Some(r) = &task.resumption {
5974 s.push_str(&resumption_block(r));
5975 }
5976 s
5977}
5978
5979fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5983 let mut instruction = instruction;
5984 for approval in task
5985 .resumption
5986 .iter()
5987 .chain(task.resumption_history.iter().rev())
5988 {
5989 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5990 instruction = base;
5991 break;
5992 }
5993 }
5994 for count in (1..=task.answers.len()).rev() {
5995 let block = answers_block(task, count);
5996 if let Some(base) = instruction.strip_suffix(&block) {
5997 return base;
5998 }
5999 }
6000 instruction
6001}
6002
6003fn instruction_for(task: &Task) -> String {
6011 append_answers(&task.instruction, task)
6012}
6013
6014fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6026 append_answers(strip_answers_block(old_instruction, task), task)
6027}
6028
6029fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6031 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6032 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6033 if let Some(cause) = task.hold_notice_cause.as_mut() {
6034 cause.target = failure.map(|f| f.target.clone());
6035 }
6036}
6037
6038#[derive(Debug, thiserror::Error)]
6039#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6040struct MissingAttachment {
6041 name: String,
6042 path: PathBuf,
6043}
6044
6045fn task_attachments(
6047 queue: &Queue,
6048 task: &Task,
6049) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6050 let paths = queue.attachment_paths(task);
6051 for (name, path) in task.attachments.iter().zip(&paths) {
6052 if !path.is_file() {
6053 return Err(MissingAttachment {
6054 name: name.clone(),
6055 path: path.clone(),
6056 });
6057 }
6058 }
6059 Ok(paths)
6060}
6061
6062fn prepare_instruction(
6073 starter: &Starter,
6074 old_instruction: Option<&str>,
6075 task: &Task,
6076) -> Option<String> {
6077 match starter {
6078 Starter::Start => Some(instruction_for(task)),
6079 Starter::Resume(_) => Some(resumed_instruction(
6080 old_instruction.expect("a resumed run always has a prior instruction"),
6081 task,
6082 )),
6083 Starter::Review(_) => None,
6084 }
6085}
6086
6087fn record(queue: &Queue, task: &mut Task) {
6091 if let Err(e) = queue.put(task) {
6092 tracing::error!("could not record task {}: {e:#}", task.short());
6093 let notice = Notice::error(
6094 "loop:record",
6095 format!(
6096 "Task {} state could not be saved: {}. Check the disk.",
6097 task.id,
6098 e.to_string().lines().next().unwrap_or("unknown save error")
6099 ),
6100 )
6101 .link(Link::Task {
6102 id: task.id.clone(),
6103 });
6104 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6106 Some(home) => notices::raise_in(home, notice),
6107 None => notices::raise(notice),
6108 }
6109 }
6110}
6111
6112fn runnable(queue: &Queue) -> Vec<Task> {
6118 let mut tasks: Vec<Task> = queue
6119 .list()
6120 .into_iter()
6121 .filter(|t| t.status.runnable())
6122 .collect();
6123 tasks.sort_unstable_by(crate::queue::dispatch_order);
6124 tasks
6125}
6126
6127fn describe(state: &RunState) -> String {
6141 let p = phrases(&state.config.graph.language);
6142 let mut detail = if state.status == RunStatus::Stalled {
6143 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6144 seats.sort_unstable();
6145 seats.dedup();
6146 if seats.is_empty() {
6147 p.quorum_lost.to_owned()
6148 } else {
6149 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6150 }
6151 } else {
6152 format!("{}{}", p.run_ended, state.status.display_label())
6153 };
6154 if let Some(cause) = state.verification_blocking_cause() {
6155 detail.push_str(&format!(" ({cause})"));
6156 } else if let Some(last) = state.events.last() {
6157 let unanswered = state
6161 .reviews
6162 .last()
6163 .filter(|r| {
6164 state.status == RunStatus::Blocked
6165 && last.node == "review"
6166 && r.incomplete()
6167 && r.blocking == 0
6168 && r.round == state.config.graph.review_rounds
6169 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6170 })
6171 .map(|r| (r.expected - r.answered, r.round));
6172 match unanswered {
6173 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6174 detail.push_str(&format!(
6175 " ({}: {})",
6176 last.node,
6177 (p.reviewers_never_answered)(missing, rounds)
6178 ));
6179 }
6180 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6181 }
6182 }
6183 detail.push_str(&format!(" [run {}]", state.id));
6184 detail
6185}
6186
6187const DIAGNOSTIC_MAX: usize = 4_000;
6193
6194const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6199
6200fn diagnostic(state: &RunState) -> Option<String> {
6214 let mut parts: Vec<String> = Vec::new();
6215
6216 for o in state.gate.iter().filter(|o| !o.ok()) {
6218 parts.push(format!(
6219 "gate `{}` failed ({}):\n{}",
6220 o.command,
6221 notices::exit_status(o.code),
6222 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6223 ));
6224 }
6225
6226 if let Some(last) = state
6229 .events
6230 .iter()
6231 .rev()
6232 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6233 {
6234 parts.push(last.message.clone());
6235 }
6236
6237 if state.viable().is_empty() {
6244 for c in &state.candidates {
6245 if let Some(evidence) = &c.verified_noop {
6246 parts.push(format!(
6247 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6248 c.label
6249 ));
6250 } else if !c.summary.trim().is_empty() {
6251 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6252 } else if let Some(why) = &c.failed {
6253 parts.push(format!("candidate {}: {why}", c.label));
6254 }
6255 }
6256 }
6257
6258 if parts.is_empty() {
6259 return None;
6260 }
6261 Some(crate::run::tail(
6266 &parts.join("\n\n"),
6267 DIAGNOSTIC_MAX.saturating_sub(100),
6268 ))
6269}
6270
6271fn label(status: RunStatus) -> &'static str {
6279 status.as_str()
6280}
6281
6282pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6284 match mode {
6285 "none" => Ok(MergeMode::None),
6286 "local" => Ok(MergeMode::Local),
6287 "pr" => Ok(MergeMode::Pr),
6288 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6289 }
6290}
6291
6292fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6297 mutex
6298 .lock()
6299 .unwrap_or_else(std::sync::PoisonError::into_inner)
6300}
6301
6302#[cfg(test)]
6303mod tests {
6304 use super::*;
6305 use crate::queue::{Source, TaskStatus};
6306 use crate::run::{Candidate, CommandOutcome};
6307 use pretty_assertions::assert_eq;
6308
6309 fn task() -> Task {
6310 Task::new(
6311 "add retries".to_owned(),
6312 "add retries".to_owned(),
6313 PathBuf::from("/repo"),
6314 Source::Human,
6315 )
6316 }
6317
6318 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6319 let job = crate::worker::Job {
6320 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6321 sequence: 1,
6322 kind: "task".into(),
6323 key: format!("task:{}", request.task),
6324 payload: serde_json::to_value(request).unwrap(),
6325 generation: "a".repeat(64),
6326 version: None,
6327 status: crate::worker::Status::Starting,
6328 result: None,
6329 pid: None,
6330 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6331 finished_at: None,
6332 };
6333 let dir = home.join("workers/jobs").join(&job.id);
6334 std::fs::create_dir_all(&dir).unwrap();
6335 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6336 job
6337 }
6338
6339 #[test]
6340 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6341 let home = tempfile::tempdir().unwrap();
6342 let request = TaskWorker {
6343 opts: Opts::default(),
6344 queue: home.path().join("queue"),
6345 task: "startup".into(),
6346 lane: PermitKind::Ordinary,
6347 standalone: false,
6348 };
6349 let job = starting_task_reservation(home.path(), &request);
6350 let error = task_worker_spawn_error(
6351 home.path(),
6352 &request,
6353 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6354 )
6355 .expect_err("our own reservation must not turn a failed spawn into a resync");
6356 let active = crate::worker::active(home.path()).unwrap();
6357 assert_eq!(active.len(), 1);
6358 assert_eq!(active[0].id, job.id);
6359 assert_eq!(active[0].status, crate::worker::Status::Starting);
6360 assert!(
6361 crate::worker::control(home.path(), &job.key)
6362 .unwrap()
6363 .is_none()
6364 );
6365 let notices = notices::Notices::at(home.path().join("notifications")).list();
6366 assert_eq!(notices.len(), 1);
6367 assert_eq!(notices[0].key, "loop:worker-startup");
6368 assert!(!notices[0].message.contains("private-error-detail"));
6369 assert!(notices[0].message.contains(&request.task));
6370 assert!(
6371 notices[0]
6372 .message
6373 .contains("could not be started or acknowledged")
6374 );
6375 assert!(notices[0].message.contains("worker.log"));
6376 assert_eq!(
6377 notices[0].link,
6378 Some(Link::Task {
6379 id: request.task.clone()
6380 })
6381 );
6382 assert!(format!("{error:#}").contains("private-error-detail"));
6383 }
6384
6385 #[test]
6386 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6387 let home = tempfile::tempdir().unwrap();
6388 let mut request = TaskWorker {
6389 opts: Opts::default(),
6390 queue: home.path().join("queue"),
6391 task: "handoff".into(),
6392 lane: PermitKind::Ordinary,
6393 standalone: true,
6394 };
6395 let job = starting_task_reservation(home.path(), &request);
6396 request.standalone = false;
6397 task_worker_spawn_error(
6398 home.path(),
6399 &request,
6400 anyhow::anyhow!("operation key is already reserved for a different request"),
6401 )
6402 .expect("a different standalone request is the handoff race, not our startup failure");
6403 let active = crate::worker::active(home.path()).unwrap();
6404 assert_eq!(active.len(), 1);
6405 assert_eq!(active[0].id, job.id);
6406 assert_eq!(active[0].payload, job.payload);
6407 assert!(
6408 notices::Notices::at(home.path().join("notifications"))
6409 .list()
6410 .is_empty()
6411 );
6412 }
6413
6414 #[test]
6415 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6416 let home = tempfile::tempdir().unwrap();
6417 let queue = Queue::at(home.path().join("queue"));
6418 let mut task = task();
6419 task.runs = vec!["previous".into()];
6420 queue.put(&mut task).unwrap();
6421 let request = TaskWorker {
6422 opts: Opts::default(),
6423 queue: home.path().join("queue"),
6424 task: task.id.clone(),
6425 lane: PermitKind::Ordinary,
6426 standalone: false,
6427 };
6428 let job = starting_task_reservation(home.path(), &request);
6429 let claims = current_work(home.path(), Timestamp::now());
6430 assert_eq!(claims.len(), 1);
6431 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6432 assert_eq!(claims[0].run, "previous");
6433 assert!(other_claims_run(&claims, "previous", None));
6434 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6437 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6438 }
6439
6440 #[test]
6441 fn admission_excludes_only_the_callers_exact_reservation() {
6442 let own = Current {
6443 worker: Some("own".into()),
6444 task: "same-task".into(),
6445 run: "previous".into(),
6446 };
6447 assert!(!other_claims_run(
6448 std::slice::from_ref(&own),
6449 "previous",
6450 Some("own")
6451 ));
6452 assert!(other_claims_run(
6453 std::slice::from_ref(&own),
6454 "previous",
6455 None
6456 ));
6457 for worker in [None, Some("other".into())] {
6458 let other = Current {
6459 worker,
6460 ..own.clone()
6461 };
6462 assert!(other_claims_run(
6463 &[own.clone(), other],
6464 "previous",
6465 Some("own")
6466 ));
6467 }
6468 let legacy: Current =
6469 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6470 assert!(other_claims_run(&[legacy], "previous", Some("own")));
6471 }
6472
6473 #[test]
6474 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6475 let mut task = task();
6476 let mut run = run_state(RunStatus::Reviewing);
6477 run.task_instruction = Some(task.instruction.clone());
6478 run.reviewed_commits = Some(vec!["committed-fix".into()]);
6479 let branch = "magi/test/B";
6480 run.candidates.push(crate::run::Candidate {
6481 branch: branch.into(),
6482 ..candidate('B', "preserved work", false, None)
6483 });
6484 task.runs = vec![run.id.clone()];
6485 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6486 assert_eq!(
6487 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6488 Starter::Resume(run.id.clone())
6489 );
6490 assert!(matches!(
6491 review_retry_starter(
6492 &task,
6493 Some(&run),
6494 Some("different"),
6495 true,
6496 unfinished.as_deref()
6497 ),
6498 Starter::Review(_)
6499 ));
6500 assert_eq!(
6501 review_retry_starter(
6502 &task,
6503 Some(&run),
6504 Some(branch),
6505 false,
6506 unfinished.as_deref()
6507 ),
6508 Starter::Start
6509 );
6510 task.instruction.push_str(" changed criteria");
6511 assert!(matches!(
6512 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6513 Starter::Review(_)
6514 ));
6515 assert!(matches!(
6516 review_retry_starter(&task, Some(&run), Some(branch), true, None),
6517 Starter::Review(_)
6518 ));
6519 }
6520
6521 #[test]
6522 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6523 let dir = tempfile::tempdir().unwrap();
6524 let queue = Queue::at(dir.path().join("queue"));
6525 let mut task = task();
6526 task.status = TaskStatus::Running;
6527 task.attempts = 1;
6528 queue.put(&mut task).unwrap();
6529 let live = std::collections::BTreeSet::from([task.id.clone()]);
6530 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6531 drop(queue.claim(&task.id).unwrap());
6532 let saved = queue.get(&task.id).unwrap();
6533 assert_eq!(saved.status, TaskStatus::Running);
6534 assert_eq!(saved.attempts, 1);
6535 assert!(saved.last_error.is_none());
6536 }
6537
6538 #[test]
6539 fn standalone_workers_do_not_consume_scheduler_lanes() {
6540 let request = |task: &str, lane, standalone| TaskWorker {
6541 opts: Opts::default(),
6542 queue: PathBuf::from("/queue"),
6543 task: task.to_owned(),
6544 lane,
6545 standalone,
6546 };
6547 let mut jobs = vec![
6548 request("ordinary", PermitKind::Ordinary, false),
6549 request("standalone-urgent", PermitKind::Urgent, true),
6550 request("standalone-ordinary", PermitKind::Ordinary, true),
6551 request("decision", PermitKind::None, false),
6552 ];
6553 assert_eq!(available_slots(&jobs, 2), (1, 1));
6554 jobs.push(request("urgent", PermitKind::Urgent, false));
6555 assert_eq!(available_slots(&jobs, 2), (1, 0));
6556 assert_eq!(available_slots(&jobs, 0), (0, 0));
6557 }
6558
6559 #[test]
6560 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6561 let now = Timestamp::now();
6562 let mut reading = Reading {
6563 pid: Some(std::process::id()),
6564 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6565 ..Reading::default()
6566 };
6567 assert!(!reading.running(now));
6568 assert!(legacy_scheduler_running(&reading, now, 0));
6569 reading.worker_protocol = Some(1);
6570 assert!(!legacy_scheduler_running(&reading, now, 0));
6571 }
6572
6573 #[test]
6574 fn selected_public_head_overrides_historical_resume_and_pin() {
6575 let mut t = task();
6576 let mut old = run_state(RunStatus::Blocked);
6577 let selection = crate::pr_recovery::Selection {
6578 url: "url".into(),
6579 branch: format!("magi/task-{}", t.id),
6580 head: "a".repeat(40),
6581 source_head: None,
6582 source_run: None,
6583 source_proof: None,
6584 disposition: Some(crate::pr_recovery::Disposition::Review),
6585 instruction: t.instruction.clone(),
6586 approved_at: Timestamp::now(),
6587 };
6588 t.resume_override = Some(crate::queue::OperatorResume {
6589 pinned_run: Some(old.id.clone()),
6590 question_id: "choice".into(),
6591 at: Timestamp::now(),
6592 conductor_rehold: None,
6593 forced: false,
6594 });
6595 assert_eq!(
6596 selected_starter(&selection, Some(&old), Some(&old.id)),
6597 Starter::Review(selection.branch.clone())
6598 );
6599 old.pr_recovery = Some(selection.clone());
6600 assert_eq!(
6601 selected_starter(&selection, Some(&old), Some(&old.id)),
6602 Starter::Review(selection.branch.clone())
6603 );
6604 old.reviewed_commits = Some(vec!["implementation".into()]);
6605 assert_eq!(
6606 selected_starter(&selection, Some(&old), Some(&old.id)),
6607 Starter::Resume(old.id.clone())
6608 );
6609 let mut changed = selection.clone();
6610 changed.head = "b".repeat(40);
6611 assert_eq!(
6612 selected_starter(&changed, Some(&old), Some(&old.id)),
6613 Starter::Review(changed.branch)
6614 );
6615 }
6616
6617 #[test]
6618 fn candidate_transplant_failure_is_one_actionable_hold() {
6619 let dir = tempfile::tempdir().unwrap();
6620 let q = Queue::at(dir.path().join("queue"));
6621 let mut t = task();
6622 let mut state = run_state(RunStatus::Blocked);
6623 state.event("prep", "cannot apply referenced commit: conflict");
6624 state.prep_failure = Some("conflict".into());
6625 t.start(state.id.clone());
6626 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6627 assert_eq!(t.attempts, 1);
6628 assert_eq!(t.status, TaskStatus::Held);
6629 assert!(t.operator_held());
6630 assert!(!t.status.runnable());
6631 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6632 let first = t.chat_notice_key().unwrap();
6633 t.chat_notices.push(first.clone());
6634 t.release_operator("test", None);
6635 state.id = "another-unprepared-run".into();
6636 t.start(state.id.clone());
6637 finish_attempt(
6638 3,
6639 &q,
6640 &mut t,
6641 &state,
6642 &[],
6643 Err(anyhow::anyhow!("still conflicts")),
6644 );
6645 assert_eq!(
6646 t.chat_notice_key().as_ref(),
6647 Some(&first),
6648 "no work happened"
6649 );
6650 t.release_operator("test", None);
6651 state.prep_failure = None;
6652 state.status = RunStatus::Failed;
6653 state.begin_pass();
6654 t.start(state.id.clone());
6655 finish_attempt(
6656 1,
6657 &q,
6658 &mut t,
6659 &state,
6660 &[],
6661 Err(anyhow::anyhow!("new gate failure")),
6662 );
6663 let failure = t.chat_notice_key().unwrap();
6664 assert_ne!(failure, first, "approved recovery reached a real failure");
6665 t.release_operator("test", None);
6666 state.begin_pass();
6667 t.start(state.id.clone());
6668 finish_attempt(
6669 1,
6670 &q,
6671 &mut t,
6672 &state,
6673 &[],
6674 Err(anyhow::anyhow!("new failure on resume")),
6675 );
6676 assert_ne!(
6677 t.chat_notice_key().as_ref(),
6678 Some(&failure),
6679 "a new settled pass"
6680 );
6681 }
6682
6683 #[test]
6684 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6685 for source in ["cli", "web"] {
6686 let mut t = task();
6687 let mut run = run_state(RunStatus::Blocked);
6688 run.instruction = "Run A original criteria".into();
6689 run.task_instruction = Some(run.instruction.clone());
6690 t.start(run.id.clone());
6691 t.release_operator("choice", Some("resume-question"));
6692 t.resume_override = Some(crate::queue::OperatorResume {
6693 question_id: "resume-question".into(),
6694 at: Timestamp::now(),
6695 conductor_rehold: None,
6696 forced: true,
6697 pinned_run: Some(run.id.clone()),
6698 });
6699 t.hold_machine(Some("not enough free space to start a run".into()));
6700 let mut unchanged = t.clone();
6701 unchanged
6702 .edit("title changed".into(), unchanged.instruction.clone())
6703 .unwrap();
6704 unchanged.release_operator(source, None);
6705 assert_eq!(
6706 unchanged
6707 .resume_override
6708 .as_ref()
6709 .unwrap()
6710 .pinned_run
6711 .as_deref(),
6712 Some(run.id.as_str())
6713 );
6714 assert!(!compatible_run_instruction(&run, &unchanged));
6715 assert!(may_resume_run(&run, &unchanged));
6716
6717 t.edit(
6718 "approved recovery".into(),
6719 "Reuse measured PR head B; fix Clippy; review".into(),
6720 )
6721 .unwrap();
6722 assert!(t.resume_override.is_none());
6723 t.release_operator(source, None);
6724 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6725 assert!(reloaded.resume_override.is_none());
6726 assert!(!may_resume_run(&run, &reloaded));
6727 let unfinished =
6728 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6729 .filter(|_| may_resume_run(&run, &reloaded));
6730 assert_eq!(
6731 choose_starter(None, false, unfinished.as_deref()),
6732 Starter::Start
6733 );
6734 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6735 assert_eq!(
6736 reloaded.resumption_history[0].question_id.as_deref(),
6737 Some("resume-question")
6738 );
6739
6740 unchanged.instruction = "Reuse measured PR head B".into();
6743 unchanged.hold_machine(Some("disk hold".into()));
6744 unchanged.release_operator(source, None);
6745 assert!(unchanged.resume_override.is_none());
6746 assert!(!may_resume_run(&run, &unchanged));
6747 }
6748 }
6749
6750 #[test]
6751 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6752 let mut t = task();
6753 let mut run = run_state(RunStatus::Blocked);
6754 t.review_of = Some("approved-head".into());
6755 t.instruction =
6756 "Review the branch `approved-head` (review-only: no implementation, no judging)."
6757 .into();
6758 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();
6759 run.reviewed_commits = Some(vec!["Commit log".into()]);
6760 t.start(run.id.clone());
6761 t.hold_machine(Some("interrupted review".into()));
6762 t.release_operator("cli", None);
6763 assert!(
6764 compatible_run_instruction(&run, &t),
6765 "legacy explicit review remains resumable"
6766 );
6767 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6768 .filter(|_| compatible_run_instruction(&run, &t));
6769 assert_eq!(
6770 choose_starter(None, false, unfinished.as_deref()),
6771 Starter::Resume(run.id.clone())
6772 );
6773 run.task_instruction = Some(t.instruction.clone());
6774 assert!(compatible_run_instruction(&run, &t));
6775 let reloaded: RunState =
6776 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6777 assert!(compatible_run_instruction(&reloaded, &t));
6778 t.edit(
6779 "new approved head".into(),
6780 "Reuse measured PR head B".into(),
6781 )
6782 .unwrap();
6783 assert!(!compatible_run_instruction(&run, &t));
6784
6785 t.review_of = None;
6787 t.instruction = "Fix Clippy on approved head".into();
6788 run.task_instruction = None;
6789 run.instruction = format!(
6790 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6791 t.instruction
6792 );
6793 assert!(compatible_run_instruction(&run, &t));
6794 t.instruction.push('\n');
6795 assert!(
6796 compatible_run_instruction(&run, &t),
6797 "legacy generated review trimmed the original criteria"
6798 );
6799 t.hold_for_handover(Some("approved-head".into()), "refused".into());
6800 let mut unchanged = t.clone();
6801 assert_eq!(
6802 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6803 Some("approved-head")
6804 );
6805 t.edit("new plan".into(), "Reuse measured PR head B".into())
6806 .unwrap();
6807 assert!(take_review_branch(&mut t, Some(&run)).is_none());
6808 assert!(!compatible_run_instruction(&run, &t));
6809 t.review_branch = Some("approved-head".into());
6810 t.review_instruction = None;
6811 assert!(
6812 take_review_branch(&mut t, Some(&run)).is_none(),
6813 "legacy retained candidate cannot replace a revised approved head"
6814 );
6815 }
6816
6817 #[test]
6818 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6819 let home = crate::run::test_home();
6820 crate::run::pin_test_home();
6821 let dir = tempfile::tempdir().unwrap();
6822 let queue = Queue::at(dir.path().join("queue"));
6823 for resume in [true, false] {
6824 let state = run_state(RunStatus::Blocked);
6825 let mut t = task();
6826 t.start(state.id.clone());
6827 let action = if resume {
6828 ask::ChoiceAction::Resume {
6829 run: state.id.clone(),
6830 }
6831 } else {
6832 ask::ChoiceAction::Requeue
6833 };
6834 let mut q = action_question(&state.id, action);
6835 q.status = ask::QuestionStatus::Open;
6836 q.answer = None;
6837 q.answered_at = None;
6838 t.fail("run stopped with a question", 3);
6839 hold_if_runnable(&queue, &mut t);
6840 assert!(t.operator_decided_at.is_none());
6841 assert!(t.operator_held());
6842 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6843 let expected = if resume {
6844 ActionDecision::Resume(state.id.clone())
6845 } else {
6846 ActionDecision::Requeue
6847 };
6848 assert_eq!(
6849 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6850 expected
6851 );
6852 t.hold_manual(Some("later explicit hold".into()));
6853 assert_eq!(
6854 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6855 ActionDecision::Stale
6856 );
6857 }
6858 }
6859
6860 #[test]
6861 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6862 let mut t = task();
6863 t.answers.push(crate::queue::AnsweredQuestion {
6864 question: "Inspect the remote?".into(),
6865 answer: "Inspect then wait".into(),
6866 });
6867 let old = instruction_for(&t);
6868 assert!(compatible_instruction(&old, &t));
6869 t.instruction = "Reuse approved PR head and review".into();
6870 t.release_operator("cli", None);
6871 assert!(!compatible_instruction(&old, &t));
6872 let approved = instruction_for(&t);
6873 assert!(approved.contains("waiting premises are superseded"));
6874 assert!(compatible_instruction(&approved, &t));
6875 assert_eq!(resumed_instruction(&approved, &t), approved);
6876 t.release_operator("web", None);
6877 assert!(compatible_instruction(&approved, &t));
6878 assert_eq!(t.resumption_history.len(), 1);
6879 t.start("run".into());
6880 assert!(instruction_for(&t).contains("Explicit operator resumption"));
6881 }
6882
6883 #[test]
6887 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6888 let mut state = RunState::new(
6889 PathBuf::from("/repo"),
6890 "main".into(),
6891 "base".into(),
6892 "task".into(),
6893 Config::default(),
6894 );
6895 state.status = RunStatus::Landing;
6896 state.parked = true;
6897 state.pr_pushed_head = Some("head".into());
6898 state.land_unrelated = Some(
6899 serde_json::from_value(serde_json::json!({
6900 "head": "head", "question": "ci-question",
6901 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6902 }))
6903 .unwrap(),
6904 );
6905 let mut t = task();
6906 t.start(state.id.clone());
6907 let verdict = Verdict {
6908 status: RunStatus::Landing,
6909 left_pr: true,
6910 quota_hit: false,
6911 parked: true,
6912 no_viable_candidates: false,
6913 };
6914 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6915 assert_eq!(t.attempts, 0);
6916 assert_eq!(t.status, TaskStatus::Held);
6917 assert!(!t.operator_held());
6918 assert!(
6919 t.hold_reason
6920 .as_deref()
6921 .unwrap()
6922 .starts_with("[ci-unrelated]")
6923 );
6924 t.attempts = 1;
6926 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6927 assert_eq!(t.attempts, 1);
6928 assert_eq!(t.passes.len(), 1);
6929 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6930 state.pr_pushed_head = Some("new-head".into());
6931 state.parked = false;
6932 state.status = RunStatus::Blocked;
6933 let stale = Verdict {
6934 status: RunStatus::Blocked,
6935 parked: false,
6936 ..verdict
6937 };
6938 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6939 assert_eq!(t.attempts, 1);
6940 state.begin_pass();
6942 state.begin_pass();
6943 state.status = RunStatus::Landing;
6944 state.parked = true;
6945 state.pr_pushed_head = Some("head".into());
6946 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6947 assert_eq!(t.attempts, 0);
6948 assert_eq!(t.passes.len(), 2);
6949 }
6950
6951 #[test]
6952 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6953 let mut state = run_state(RunStatus::Failed);
6954 state
6955 .quota
6956 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6957 state.begin_pass();
6958 let mut t = task();
6959 t.start(state.id.clone());
6960 reclaim(&mut t, Some(state), 2, "en");
6961 assert_eq!(t.attempts, 1);
6962 }
6963
6964 #[test]
6965 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6966 let mut state = run_state(RunStatus::Blocked);
6967 let losses: Vec<_> = ["alpha", "beta"]
6968 .into_iter()
6969 .enumerate()
6970 .map(|(i, agent)| {
6971 QuotaLoss::from_report(
6972 format!("advisor-{i}"),
6973 "advise",
6974 Some(&crate::agent::Quota {
6975 cause: crate::agent::QuotaCause::Authentication,
6976 agent: agent.to_owned(),
6977 reset: None,
6978 }),
6979 )
6980 })
6981 .collect();
6982 crate::graph::block_machine_outage(&mut state, "advise", &losses);
6983 state.quota = losses;
6984 let mut t = task();
6985 t.start(state.id.clone());
6986 let verdict = Verdict {
6987 status: state.status,
6988 left_pr: false,
6989 quota_hit: true,
6990 parked: false,
6991 no_viable_candidates: true,
6992 };
6993 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
6994 assert_eq!(t.attempts, 0);
6995 assert_eq!(t.status, TaskStatus::Held);
6996 assert!(!t.operator_held());
6997 let reason = t.hold_reason.as_deref().unwrap();
6998 assert!(reason.starts_with("[authentication]"));
6999 assert!(
7000 reason.contains("alpha")
7001 && reason.contains("beta")
7002 && reason.contains("re-authenticate")
7003 );
7004 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7005 let mut orphan = task();
7007 orphan.start(state.id.clone());
7008 reclaim(&mut orphan, Some(state), 2, "en");
7009 assert_eq!(orphan.attempts, 0);
7010 assert_eq!(orphan.status, TaskStatus::Held);
7011 }
7012
7013 #[test]
7014 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7015 let mut state = RunState::new(
7016 PathBuf::from("/repo"),
7017 "main".to_owned(),
7018 "abc1234".to_owned(),
7019 "task".to_owned(),
7020 Config::default(),
7021 );
7022 state.status = RunStatus::Blocked;
7023 state.resource_block = Some(crate::run::ResourceBlock {
7024 cause: crate::run::ResourceBlockCause::Other,
7025 node: "graft".to_owned(),
7026 kind: "shared build cache".to_owned(),
7027 detail: "timed out".to_owned(),
7028 at: jiff::Timestamp::now(),
7029 });
7030 let mut t = task();
7031 t.start("20260902-000000-aaaa".to_owned());
7032 assert_eq!(t.attempts, 1);
7033 let verdict = Verdict {
7034 status: RunStatus::Blocked,
7035 left_pr: false,
7036 quota_hit: false,
7037 parked: false,
7038 no_viable_candidates: false,
7039 };
7040 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7041 assert_eq!(t.status, TaskStatus::Held);
7042 assert_eq!(t.attempts, 0, "the attempt is refunded");
7043 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7044 assert!(
7045 !t.operator_held(),
7046 "a machine hold, released without a human"
7047 );
7048
7049 let mut selected = task();
7050 selected.start("20260902-000000-cccc".into());
7051 selected.replacement = Some(crate::merge_decision::Replacement {
7052 question: "fixture".into(),
7053 run: "earlier".into(),
7054 pr: "https://example.invalid/pr/1".into(),
7055 agent: "selected".into(),
7056 context: "fixture".into(),
7057 });
7058 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7059 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7060 assert_eq!(selected.attempts, 0);
7061 assert!(
7062 !selected.operator_held(),
7063 "a selected agent also retains a machine resource hold"
7064 );
7065 assert!(
7066 selected
7067 .hold_reason
7068 .as_deref()
7069 .unwrap()
7070 .starts_with("[resource] ")
7071 );
7072
7073 let mut p = task();
7075 p.start("20260902-000000-bbbb".to_owned());
7076 settle_and_diagnose(
7077 &mut p,
7078 Verdict {
7079 parked: true,
7080 ..verdict
7081 },
7082 "parked",
7083 2,
7084 &state,
7085 );
7086 assert_eq!(p.status, TaskStatus::Parked);
7087 assert_eq!(
7088 p.attempts, 0,
7089 "parking refunds once rather than also settling the resource hold"
7090 );
7091 }
7092
7093 #[test]
7094 fn record_failure_notice_links_the_task() {
7095 let dir = tempfile::tempdir().unwrap();
7096 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7099 let queue = Queue::at(dir.path().join("queue"));
7100 let mut t = interrupt_task("rec-fail-1");
7101 record(&queue, &mut t);
7102
7103 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7104 assert_eq!(found.len(), 1);
7105 assert_eq!(found[0].key, "loop:record");
7106 assert_eq!(
7107 found[0].link,
7108 Some(Link::Task {
7109 id: "rec-fail-1".to_owned()
7110 })
7111 );
7112 }
7113
7114 fn interrupt_task(id: &str) -> Task {
7117 let mut t = task();
7118 t.id = id.to_owned();
7119 t.interrupt = true;
7120 t
7121 }
7122
7123 fn task_with_id(id: &str) -> Task {
7125 let mut t = task();
7126 t.id = id.to_owned();
7127 t
7128 }
7129
7130 fn urgent_task(id: &str) -> Task {
7132 let mut t = task();
7133 t.id = id.to_owned();
7134 t.urgent = true;
7135 t
7136 }
7137
7138 #[test]
7139 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7140 let dir = tempfile::tempdir().unwrap();
7141 let queue = Queue::at(dir.path().join("queue"));
7142 let mut parked = task_with_id("parked");
7143 parked.start("run".into());
7144 parked.park("upgrade");
7145 parked.record_pass_at(
7146 "run",
7147 0,
7148 Some(Timestamp::now()),
7149 1,
7150 Some(crate::run::ParkCause::Upgrade {
7151 from: "old".into(),
7152 to: None,
7153 }),
7154 );
7155 let mut fresh = task_with_id("fresh");
7156 fresh.priority = 100;
7157 let mut urgent_task = urgent_task("urgent");
7158 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7159 queue.put(t).unwrap();
7160 }
7161 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7162 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7163 let candidates = runnable(&queue);
7164 assert_eq!(candidates[0].id, parked.id);
7165 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7166 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7167 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7168 drop(first);
7169 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7170 let next = runnable(&queue)
7171 .into_iter()
7172 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7173 .unwrap();
7174 assert_eq!(next.task.id, fresh.id);
7175 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7176 drop(claimed_elsewhere);
7177 drop(next);
7178 assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7179 }
7180
7181 #[test]
7182 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7183 let dir = tempfile::tempdir().unwrap();
7184 let queue = Queue::at(dir.path().join("queue"));
7185 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7186 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7187 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7188 let mut first = task();
7189 queue.put(&mut first).unwrap();
7190 let stale_plain = queue.get(&first.id).unwrap();
7191 first.set_urgent(true).unwrap();
7192 queue.put(&mut first).unwrap();
7193 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7194 let mut second = urgent_task("second");
7195 queue.put(&mut second).unwrap();
7196 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7197 drop(queue.claim(&second.id).unwrap());
7198 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7199 drop(dispatched);
7200 let stale_urgent = queue.get(&first.id).unwrap();
7201 first.set_urgent(false).unwrap();
7202 queue.put(&mut first).unwrap();
7203 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7204 assert_eq!(urgent.available_permits(), 1);
7205 drop(queue.claim(&first.id).unwrap());
7206 drop(occupied);
7207 }
7208
7209 #[test]
7210 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7211 let dir = tempfile::tempdir().unwrap();
7212 let queue = Queue::at(dir.path().join("queue"));
7213 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7214 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7215 let mut t = task();
7216 queue.put(&mut t).unwrap();
7217 for enabled in [true, false] {
7218 let stale = queue.get(&t.id).unwrap();
7219 t.set_urgent(enabled).unwrap();
7220 queue.put(&mut t).unwrap();
7221 assert_ne!(stale.urgent, enabled);
7222 let DispatchClaim {
7223 task: fresh,
7224 claim,
7225 permit,
7226 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7227 assert_eq!(fresh.urgent, enabled);
7228 assert_eq!(ordinary.available_permits(), usize::from(enabled));
7229 assert_eq!(urgent.available_permits(), usize::from(!enabled));
7230 assert!(queue.claim(&t.id).is_err());
7231 assert_eq!(fresh.attempts, stale.attempts);
7232 drop((claim, permit));
7233 assert_eq!(ordinary.available_permits(), 1);
7234 assert_eq!(urgent.available_permits(), 1);
7235 }
7236 t.set_urgent(true).unwrap();
7237 queue.put(&mut t).unwrap();
7238 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7239 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7240 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7241 drop(queue.claim(&t.id).unwrap());
7242 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7243 drop(occupied);
7244 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7245 drop(queue.claim(&t.id).unwrap());
7246 let held = queue.claim(&t.id).unwrap();
7247 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7248 drop(held);
7249 t.status = TaskStatus::Held;
7250 queue.put(&mut t).unwrap();
7251 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7252 drop(queue.claim(&t.id).unwrap());
7253 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7254 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7255 drop(queue.claim(&t.id).unwrap());
7256 assert_eq!(urgent.available_permits(), 1);
7257 }
7258
7259 #[test]
7264 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7265 assert_eq!(permit_kind(true, false), PermitKind::None);
7266 assert_eq!(permit_kind(true, true), PermitKind::None);
7267 }
7268
7269 #[test]
7274 fn permit_kind_separates_urgent_from_ordinary() {
7275 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7276 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7277 }
7278
7279 #[test]
7286 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7287 let cfg = Config::default();
7288 let repo = Path::new("/any/repo/path");
7289
7290 let reason =
7291 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7292 assert!(reason.contains("1024"), "{reason}");
7293 assert!(
7294 reason.contains(&cfg.disk.min_free_bytes.to_string()),
7295 "{reason}"
7296 );
7297
7298 assert_eq!(
7299 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7300 None,
7301 "exactly at the floor is open"
7302 );
7303 assert_eq!(
7304 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7305 None,
7306 "comfortably above the floor is open"
7307 );
7308 }
7309
7310 #[test]
7311 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7312 let mut cfg = Config::default();
7313 cfg.disk.min_free_bytes = 0;
7314 let repo = Path::new("/any/repo/path");
7315 assert_eq!(
7316 disk_gate_with(repo, &cfg, |_| Ok(0)),
7317 None,
7318 "a zero floor never measures at all"
7319 );
7320 }
7321
7322 #[test]
7323 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7324 let cfg = Config::default();
7325 let repo = Path::new("/any/repo/path");
7326 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7327 .expect("a measurement failure must close the gate, not open it");
7328 assert!(reason.contains("could not measure"), "{reason}");
7329 }
7330
7331 #[test]
7332 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7333 let ordinary = task();
7334 let next = advance_interrupt(
7335 Interrupt::Idle,
7336 std::slice::from_ref(&ordinary.id),
7337 std::slice::from_ref(&ordinary),
7338 );
7339 assert_eq!(next, Interrupt::Idle);
7340 }
7341
7342 #[test]
7343 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7344 let marked = interrupt_task("marked");
7347 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7348 assert_eq!(next, Interrupt::Idle);
7349 }
7350
7351 #[test]
7352 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7353 let marked = interrupt_task("marked");
7354 let next = advance_interrupt(
7355 Interrupt::Idle,
7356 &["running".to_owned()],
7357 std::slice::from_ref(&marked),
7358 );
7359 assert_eq!(
7360 next,
7361 Interrupt::Parking {
7362 parked: vec!["running".to_owned()],
7363 interrupt_task: "marked".to_owned(),
7364 }
7365 );
7366 }
7367
7368 #[test]
7377 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7378 let marked = interrupt_task("marked");
7379
7380 let two = advance_interrupt(
7381 Interrupt::Idle,
7382 &["a".to_owned(), "b".to_owned()],
7383 std::slice::from_ref(&marked),
7384 );
7385 assert_eq!(two, Interrupt::Idle);
7386
7387 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7388 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7389 }
7390
7391 #[test]
7392 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7393 let state = Interrupt::Parking {
7394 parked: vec!["running".to_owned()],
7395 interrupt_task: "marked".to_owned(),
7396 };
7397 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7399 assert_eq!(still_going, state);
7400
7401 let stopped_but_not_yet_dispatched =
7405 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7406 assert_eq!(stopped_but_not_yet_dispatched, state);
7407
7408 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7410 assert_eq!(
7411 dispatched,
7412 Interrupt::Running {
7413 parked: vec!["running".to_owned()],
7414 interrupt_task: "marked".to_owned(),
7415 }
7416 );
7417 }
7418
7419 #[test]
7420 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7421 let state = Interrupt::Running {
7422 parked: vec!["running".to_owned()],
7423 interrupt_task: "marked".to_owned(),
7424 };
7425 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7426 assert_eq!(still_running, state);
7427
7428 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7435 assert_eq!(
7436 ended,
7437 Interrupt::Resuming {
7438 parked: vec!["running".to_owned()]
7439 }
7440 );
7441 }
7442
7443 #[test]
7444 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7445 let state = Interrupt::Resuming {
7446 parked: vec!["running".to_owned()],
7447 };
7448 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7449 assert_eq!(still_waiting, state);
7450
7451 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7452 assert_eq!(dispatched, Interrupt::Idle);
7453 }
7454
7455 #[test]
7461 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7462 {
7463 let state = Interrupt::Parking {
7464 parked: vec!["running".to_owned()],
7465 interrupt_task: "marked".to_owned(),
7466 };
7467 let next = advance_interrupt(state, &[], &[]);
7470 assert_eq!(
7471 next,
7472 Interrupt::Resuming {
7473 parked: vec!["running".to_owned()]
7474 },
7475 "abandoning the interrupt must not abandon the resume it owes"
7476 );
7477 }
7478
7479 #[test]
7482 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7483 let state = Interrupt::Resuming {
7484 parked: vec!["running".to_owned()],
7485 };
7486 let next = advance_interrupt(state, &[], &[]);
7487 assert_eq!(
7488 next,
7489 Interrupt::Idle,
7490 "nothing is left to wait for; the loop must not stay wedged"
7491 );
7492 }
7493
7494 #[test]
7495 fn disabled_by_config_the_sequence_can_never_leave_idle() {
7496 let marked = interrupt_task("marked");
7497 let next = advance_interrupt_tick(
7498 false,
7499 Interrupt::Idle,
7500 &["running".to_owned()],
7501 std::slice::from_ref(&marked),
7502 );
7503 assert_eq!(
7504 next,
7505 Interrupt::Idle,
7506 "an unmarked, unconfigured daemon must behave exactly as before"
7507 );
7508 }
7509
7510 #[test]
7511 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7512 let state = Interrupt::Parking {
7513 parked: vec!["running".to_owned()],
7514 interrupt_task: "marked".to_owned(),
7515 };
7516 let candidates = vec![interrupt_task("marked"), task()];
7517 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7518 assert!(
7519 allowed.is_empty(),
7520 "nothing may dispatch - not even the interrupt task itself - \
7521 until the parked run has actually stopped"
7522 );
7523 }
7524
7525 #[test]
7539 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7540 for state in [
7541 Interrupt::Parking {
7542 parked: vec!["running".to_owned()],
7543 interrupt_task: "marked".to_owned(),
7544 },
7545 Interrupt::Running {
7546 parked: vec!["running".to_owned()],
7547 interrupt_task: "marked".to_owned(),
7548 },
7549 Interrupt::Resuming {
7550 parked: vec!["running".to_owned()],
7551 },
7552 ] {
7553 let candidates = vec![
7554 interrupt_task("marked"),
7555 urgent_task("hot"),
7556 task_with_id("ordinary"),
7557 ];
7558 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7559 assert!(
7560 !allowed.iter().any(|t| t.id == "hot"),
7561 "an urgent candidate must wait out the same gate as anything \
7562 else while the run it would run alongside has not actually \
7563 left flight, for state {state:?}: {allowed:?}"
7564 );
7565 }
7566 }
7567
7568 #[test]
7574 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7575 let state = Interrupt::Resuming {
7576 parked: vec!["hot".to_owned()],
7577 };
7578 let candidates = vec![urgent_task("hot"), task()];
7579 let allowed = interrupt_gate(&state, &[], candidates);
7580 assert_eq!(
7581 allowed.iter().filter(|t| t.id == "hot").count(),
7582 1,
7583 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7584 );
7585 }
7586
7587 #[test]
7588 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7589 let state = Interrupt::Parking {
7590 parked: vec!["running".to_owned()],
7591 interrupt_task: "marked".to_owned(),
7592 };
7593 let other = task();
7594 let candidates = vec![interrupt_task("marked"), other.clone()];
7595 let allowed = interrupt_gate(&state, &[], candidates);
7596 assert_eq!(allowed.len(), 1);
7597 assert_eq!(allowed[0].id, "marked");
7598 }
7599
7600 #[test]
7601 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7602 let state = Interrupt::Running {
7603 parked: vec!["running".to_owned()],
7604 interrupt_task: "marked".to_owned(),
7605 };
7606 let candidates = vec![task(), task()];
7607 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7608 assert!(allowed.is_empty());
7609 }
7610
7611 #[test]
7618 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7619 let state = Interrupt::Resuming {
7620 parked: vec!["a".to_owned(), "c".to_owned()],
7621 };
7622 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7623 let allowed = interrupt_gate(&state, &[], candidates);
7624 assert_eq!(
7625 allowed.len(),
7626 1,
7627 "at most one candidate may be offered while resuming: {allowed:?}"
7628 );
7629 assert_eq!(allowed[0].id, "a");
7630 }
7631
7632 #[test]
7633 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7634 let state = Interrupt::Resuming {
7635 parked: vec!["a".to_owned()],
7636 };
7637 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7638 assert!(allowed.is_empty());
7639 }
7640
7641 #[test]
7647 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7648 let running = task(); let marked = interrupt_task("marked");
7650
7651 let mut state = Interrupt::Idle;
7652 let in_flight = vec![running.id.clone()];
7654 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7655 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7656 assert!(gated.is_empty(), "still waiting on `running` to park");
7657
7658 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7660 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7661 assert_eq!(
7662 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7663 vec!["marked"],
7664 "only the interrupt task may be offered to the dispatcher now"
7665 );
7666
7667 state = advance_interrupt_tick(
7669 true,
7670 state,
7671 &["marked".to_owned()],
7672 std::slice::from_ref(&running),
7673 );
7674 let gated = interrupt_gate(
7675 &state,
7676 &["marked".to_owned()],
7677 vec![marked.clone(), running.clone()],
7678 );
7679 assert!(
7680 gated.is_empty(),
7681 "the parked run must not be offered back while the interrupt \
7682 task is still running"
7683 );
7684
7685 let other = task_with_id("other");
7689 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7690 assert_eq!(
7691 state,
7692 Interrupt::Resuming {
7693 parked: vec![running.id.clone()]
7694 }
7695 );
7696 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7697 assert_eq!(
7698 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7699 vec![running.id.as_str()],
7700 "exactly the parked run resumes - not the unrelated task, even \
7701 though it was offered first"
7702 );
7703
7704 state = advance_interrupt_tick(
7708 true,
7709 state,
7710 std::slice::from_ref(&running.id),
7711 std::slice::from_ref(&other),
7712 );
7713 assert_eq!(state, Interrupt::Idle);
7714 let gated = interrupt_gate(
7715 &state,
7716 std::slice::from_ref(&running.id),
7717 vec![other.clone()],
7718 );
7719 assert_eq!(
7720 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7721 vec![other.id.as_str()],
7722 "ordinary dispatch is unrestricted again"
7723 );
7724 }
7725
7726 #[test]
7727 fn every_run_status_settles_the_task_it_came_from() {
7728 let table = [
7730 (RunStatus::Merged, TaskStatus::Done, 1),
7731 (RunStatus::Ready, TaskStatus::Done, 1),
7732 (RunStatus::Stalled, TaskStatus::Failed, 0),
7733 (RunStatus::Blocked, TaskStatus::Failed, 1),
7734 (RunStatus::Failed, TaskStatus::Failed, 1),
7735 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7736 (RunStatus::Prep, TaskStatus::Failed, 1),
7737 (RunStatus::Implementing, TaskStatus::Failed, 1),
7738 (RunStatus::Judging, TaskStatus::Failed, 1),
7739 (RunStatus::Deliberating, TaskStatus::Failed, 1),
7740 (RunStatus::Voting, TaskStatus::Failed, 1),
7741 (RunStatus::Reviewing, TaskStatus::Failed, 1),
7742 (RunStatus::Gating, TaskStatus::Failed, 1),
7743 ];
7744 for (run, want, attempts) in table {
7745 let mut t = task();
7746 t.start("20260902-000000-aaaa".to_owned());
7747 settle(
7748 &mut t,
7749 Verdict {
7750 status: run,
7751 left_pr: false,
7752 parked: false,
7753 quota_hit: matches!(run, RunStatus::Stalled),
7754 no_viable_candidates: false,
7755 },
7756 "why",
7757 2,
7758 );
7759 assert_eq!(t.status, want, "task status after {}", label(run));
7760 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7761 }
7762 }
7763
7764 #[test]
7765 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7766 let mut stalled = task();
7767 stalled.start("20260902-000000-aaaa".to_owned());
7768 settle(
7769 &mut stalled,
7770 Verdict {
7771 status: RunStatus::Stalled,
7772 left_pr: false,
7773 parked: false,
7774 quota_hit: true,
7775 no_viable_candidates: false,
7776 },
7777 "quota",
7778 1,
7779 );
7780 assert_eq!(stalled.attempts, 0);
7781 assert!(
7782 stalled.status.runnable(),
7783 "a machine problem must leave the task in line"
7784 );
7785
7786 let mut blocked = task();
7787 blocked.start("20260902-000000-aaaa".to_owned());
7788 settle(
7789 &mut blocked,
7790 Verdict {
7791 status: RunStatus::Blocked,
7792 left_pr: false,
7793 parked: false,
7794 quota_hit: false,
7795 no_viable_candidates: false,
7796 },
7797 "findings open",
7798 1,
7799 );
7800 assert_eq!(blocked.attempts, 1);
7801 assert_eq!(
7802 blocked.status,
7803 TaskStatus::Held,
7804 "the last attempt hands the task to a human"
7805 );
7806 }
7807
7808 #[test]
7809 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7810 let mut delivered = task();
7813 delivered.start("20260903-080619-01c2".to_owned());
7814 settle(
7815 &mut delivered,
7816 Verdict {
7817 status: RunStatus::Blocked,
7818 left_pr: true,
7819 parked: false,
7820 quota_hit: false,
7821 no_viable_candidates: false,
7822 },
7823 "no check status",
7824 4,
7825 );
7826 assert_eq!(
7827 delivered.status,
7828 TaskStatus::Held,
7829 "a pull request waiting on CI or a person is not a retryable failure"
7830 );
7831 assert!(
7832 !delivered.status.runnable(),
7833 "the loop must not pick this task up again"
7834 );
7835 assert_eq!(
7836 delivered.last_error.as_deref(),
7837 Some("no check status"),
7838 "the operator needs to be told what the gate was waiting for"
7839 );
7840
7841 let mut empty_handed = task();
7844 empty_handed.start("20260903-080619-01c2".to_owned());
7845 settle(
7846 &mut empty_handed,
7847 Verdict {
7848 status: RunStatus::Blocked,
7849 left_pr: false,
7850 parked: false,
7851 quota_hit: false,
7852 no_viable_candidates: false,
7853 },
7854 "findings open",
7855 4,
7856 );
7857 assert_eq!(empty_handed.status, TaskStatus::Failed);
7858 assert!(empty_handed.status.runnable());
7859 }
7860
7861 #[test]
7862 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7863 let mut noop = task();
7869 noop.start("20260912-131304-391f".to_owned());
7870 settle(
7871 &mut noop,
7872 Verdict {
7873 status: RunStatus::VerifiedNoop,
7874 left_pr: false,
7875 parked: false,
7876 quota_hit: false,
7877 no_viable_candidates: true,
7878 },
7879 "candidate A: already fixed by b32cfc4, on main",
7880 4,
7881 );
7882 assert_eq!(
7883 noop.status,
7884 TaskStatus::Held,
7885 "an unverified claim is a request for a human, not a failure"
7886 );
7887 assert!(
7888 !noop.status.runnable(),
7889 "the loop must not requeue this on the same unverified claim"
7890 );
7891 assert_eq!(noop.attempts, 1);
7896 }
7897
7898 #[test]
7899 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7900 let mut parked = task();
7905 parked.start("20260903-183634-2d98".to_owned());
7906 settle(
7907 &mut parked,
7908 Verdict {
7909 status: RunStatus::Implementing,
7910 left_pr: false,
7911 quota_hit: false,
7912 parked: true,
7913 no_viable_candidates: false,
7914 },
7915 "parked after `implementing`",
7916 2,
7917 );
7918 assert_eq!(parked.attempts, 0, "a park is refunded");
7919 assert!(
7920 parked.status.runnable(),
7921 "and the task stays in line so the next loop resumes its run"
7922 );
7923 assert_eq!(parked.status, TaskStatus::Parked);
7924 assert_eq!(
7925 parked.park_reason.as_deref(),
7926 Some("parked after `implementing`"),
7927 "the card says where it stopped"
7928 );
7929 assert_eq!(parked.last_error, None, "nothing failed");
7930
7931 let mut broken = task();
7935 broken.start("20260903-183634-2d98".to_owned());
7936 settle(
7937 &mut broken,
7938 Verdict {
7939 status: RunStatus::Implementing,
7940 left_pr: false,
7941 quota_hit: false,
7942 parked: false,
7943 no_viable_candidates: false,
7944 },
7945 "returned mid-flight",
7946 2,
7947 );
7948 assert_eq!(broken.attempts, 1);
7949 }
7950
7951 #[test]
7952 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7953 let mut flaky = task();
7958 flaky.start("20260903-123023-e633".to_owned());
7959 settle(
7960 &mut flaky,
7961 Verdict {
7962 status: RunStatus::Stalled,
7963 left_pr: false,
7964 parked: false,
7965 quota_hit: false,
7966 no_viable_candidates: false,
7967 },
7968 "verdict rests on 1 of 3 judges",
7969 2,
7970 );
7971 assert_eq!(
7972 flaky.attempts, 1,
7973 "flakiness spends an attempt, so `max_attempts` still bounds it"
7974 );
7975 assert!(flaky.status.runnable(), "and it is still worth retrying");
7976
7977 let mut limited = task();
7979 limited.start("20260903-123023-e633".to_owned());
7980 settle(
7981 &mut limited,
7982 Verdict {
7983 status: RunStatus::Stalled,
7984 left_pr: false,
7985 parked: false,
7986 quota_hit: true,
7987 no_viable_candidates: false,
7988 },
7989 "judge-2, judge-3 out of quota",
7990 2,
7991 );
7992 assert_eq!(limited.attempts, 0, "a quota window is refunded");
7993 assert!(limited.status.runnable());
7994
7995 let mut worn = task();
7998 for _ in 0..2 {
7999 worn.release();
8000 }
8001 worn.start("20260903-123023-e633".to_owned());
8002 worn.attempts = 2;
8003 settle(
8004 &mut worn,
8005 Verdict {
8006 status: RunStatus::Stalled,
8007 left_pr: false,
8008 parked: false,
8009 quota_hit: false,
8010 no_viable_candidates: false,
8011 },
8012 "no quorum again",
8013 2,
8014 );
8015 assert_eq!(worn.status, TaskStatus::Held);
8016 assert!(!worn.status.runnable());
8017 }
8018
8019 #[test]
8020 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8021 let mut wiped_out = task();
8028 wiped_out.start("20260907-025000-a1b2".to_owned());
8029 settle(
8030 &mut wiped_out,
8031 Verdict {
8032 status: RunStatus::Failed,
8033 left_pr: false,
8034 parked: false,
8035 quota_hit: true,
8036 no_viable_candidates: true,
8037 },
8038 "no candidate produced a change; nothing to judge",
8039 2,
8040 );
8041 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8042 assert!(
8043 wiped_out.status.runnable(),
8044 "a machine problem must leave the task in line"
8045 );
8046
8047 let mut partial_progress = task();
8053 partial_progress.start("20260907-025500-c3d4".to_owned());
8054 settle(
8055 &mut partial_progress,
8056 Verdict {
8057 status: RunStatus::Failed,
8058 left_pr: false,
8059 parked: false,
8060 quota_hit: true,
8061 no_viable_candidates: false,
8062 },
8063 "gate failed on the winning candidate",
8064 2,
8065 );
8066 assert_eq!(
8067 partial_progress.attempts, 1,
8068 "a candidate that actually produced a change spends the attempt \
8069 even though some other seat hit its quota"
8070 );
8071 assert!(partial_progress.status.runnable());
8072 }
8073
8074 #[test]
8075 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8076 let mut t = task();
8082 t.start("20260907-025000-a1b2".to_owned());
8083 let mut state = run_state(RunStatus::Failed);
8084 state.quota.push(QuotaLoss {
8085 cause: crate::agent::QuotaCause::UsageLimit,
8086 agent: String::new(),
8087 seat: "cand-a".to_owned(),
8088 node: "implement".to_owned(),
8089 at: Timestamp::now(),
8090 reset: None,
8091 });
8092 assert!(
8093 state.viable().is_empty(),
8094 "no candidate was added, so nothing is viable"
8095 );
8096 reclaim(&mut t, Some(state), 2, "en");
8097 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8098 assert!(t.status.runnable());
8099 }
8100
8101 #[test]
8102 fn a_held_task_is_never_offered_to_the_loop() {
8103 let dir = tempfile::tempdir().unwrap();
8104 let queue = Queue::at(dir.path().to_path_buf());
8105 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8106 let mut t = task();
8107 t.id = format!("2026090{n}-000000-000{n}");
8108 t.priority = priority;
8109 queue.put(&mut t).unwrap();
8110 }
8111 let mut held = task();
8112 held.id = "20260909-000000-9999".to_owned();
8113 held.priority = 99;
8114 held.hold_machine(None);
8115 queue.put(&mut held).unwrap();
8116
8117 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8118 assert_eq!(order.len(), 3);
8119 assert!(!order.contains(&held.id));
8120 assert_eq!(
8121 order.first().cloned(),
8122 queue.next_runnable().map(|t| t.id),
8123 "the loop's first candidate is exactly what the queue offers"
8124 );
8125 assert_eq!(
8126 order,
8127 vec![
8128 "20260902-000000-0002".to_owned(),
8129 "20260903-000000-0003".to_owned(),
8130 "20260901-000000-0001".to_owned(),
8131 ],
8132 "priority first, then oldest, so nothing starves"
8133 );
8134 }
8135
8136 #[test]
8137 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8138 let dir = tempfile::tempdir().unwrap();
8139 let queue = Queue::at(dir.path().to_path_buf());
8140 let mut old = task();
8141 old.id = "20260101-000000-old0".to_owned();
8142 queue.put(&mut old).unwrap();
8143 let mut fresh = task();
8144 fresh.id = "20260101-000000-new0".to_owned();
8145 queue.put(&mut fresh).unwrap();
8146
8147 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8151 std::thread::sleep(Duration::from_millis(60));
8152 let live = queue.claim(&fresh.id).unwrap();
8153
8154 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8155 assert_eq!(swept, vec![old.id.clone()]);
8156 assert!(
8157 queue.claim(&old.id).is_ok(),
8158 "an unparseable lock older than the threshold is swept"
8159 );
8160 assert!(
8161 queue.claim(&fresh.id).is_err(),
8162 "a live pid protects its lock regardless of age"
8163 );
8164 drop(live);
8165 }
8166
8167 #[test]
8168 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8169 let dir = tempfile::tempdir().unwrap();
8172 let queue = Queue::at(dir.path().to_path_buf());
8173 let mut t = task();
8174 t.id = "20260101-000000-live".to_owned();
8175 queue.put(&mut t).unwrap();
8176
8177 let claim = queue.claim(&t.id).unwrap();
8178 std::thread::sleep(Duration::from_millis(60));
8179
8180 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8181 assert!(
8182 swept.is_empty(),
8183 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8184 );
8185 assert!(
8186 queue.claim(&t.id).is_err(),
8187 "the lock still protects its task"
8188 );
8189 drop(claim);
8190 }
8191
8192 fn injected_dead_pid() -> u32 {
8195 std::process::id().checked_add(1).unwrap_or(1)
8196 }
8197
8198 #[test]
8199 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8200 let dir = tempfile::tempdir().unwrap();
8201 let queue = Queue::at(dir.path().to_path_buf());
8202 let mut t = task();
8203 t.id = "20260101-000000-dead".to_owned();
8204 queue.put(&mut t).unwrap();
8205 let dead_pid = injected_dead_pid();
8206
8207 std::fs::write(
8212 dir.path().join(format!("{}.lock", t.id)),
8213 dead_pid.to_string(),
8214 )
8215 .unwrap();
8216
8217 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8218 pid != dead_pid
8219 });
8220 assert_eq!(
8221 swept,
8222 vec![t.id.clone()],
8223 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8224 );
8225 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8226 }
8227
8228 #[test]
8229 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8230 let dir = tempfile::tempdir().unwrap();
8231 let queue = Queue::at(dir.path().to_path_buf());
8232 let mut t = task();
8233 t.id = "20260101-000000-late".to_owned();
8234 queue.put(&mut t).unwrap();
8235 let dead_pid = injected_dead_pid();
8236
8237 assert!(
8240 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8241 "nothing has claimed the task yet"
8242 );
8243
8244 std::fs::write(
8247 dir.path().join(format!("{}.lock", t.id)),
8248 dead_pid.to_string(),
8249 )
8250 .unwrap();
8251
8252 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8256 pid != dead_pid
8257 });
8258 assert_eq!(swept, vec![t.id.clone()]);
8259 }
8260
8261 #[test]
8262 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8263 crate::run::pin_test_home();
8268 let dir = tempfile::tempdir().unwrap();
8269 let queue = Queue::at(dir.path().to_path_buf());
8270 let mut t = task();
8271 t.id = "20260101-000000-crsh".to_owned();
8272 t.status = TaskStatus::Running;
8273 t.attempts = 1;
8274 t.runs.push("20260904-000000-4043".to_owned());
8278 queue.put(&mut t).unwrap();
8279 let dead_pid = injected_dead_pid();
8280
8281 std::fs::write(
8284 dir.path().join(format!("{}.lock", t.id)),
8285 dead_pid.to_string(),
8286 )
8287 .unwrap();
8288
8289 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8295 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8296
8297 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8298 pid != dead_pid
8299 });
8300 assert_eq!(swept, vec![t.id.clone()]);
8301
8302 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8303 assert_eq!(reclaimed, vec![t.id.clone()]);
8304 let after = queue.get(&t.id).unwrap();
8305 assert_eq!(
8306 after.status,
8307 TaskStatus::Held,
8308 "no run.json to recover from, so a human is asked"
8309 );
8310 assert_eq!(
8311 after.runs,
8312 vec!["20260904-000000-4043".to_owned()],
8313 "the crashed run's id is kept as evidence, not discarded"
8314 );
8315 }
8316
8317 #[test]
8318 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8319 let dir = tempfile::tempdir().unwrap();
8320 let queue = Queue::at(dir.path().to_path_buf());
8321 let mut t = task();
8322 t.id = "20260101-000000-unknown".to_owned();
8323 queue.put(&mut t).unwrap();
8324 let dead_pid = injected_dead_pid();
8325 std::fs::write(
8326 dir.path().join(format!("{}.lock", t.id)),
8327 dead_pid.to_string(),
8328 )
8329 .unwrap();
8330
8331 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8332 assert!(swept.is_empty(), "an unknown pid must keep its lock");
8333 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8334 }
8335
8336 fn run_state_in(status: RunStatus, language: &str) -> RunState {
8337 let mut s = run_state(status);
8338 s.config.graph.language = language.to_owned();
8339 s
8340 }
8341
8342 fn unstarted_verdict(status: RunStatus) -> Verdict {
8343 Verdict {
8344 status,
8345 left_pr: false,
8346 quota_hit: false,
8347 parked: false,
8348 no_viable_candidates: false,
8349 }
8350 }
8351
8352 #[test]
8353 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8354 let mut t = task();
8355 t.attempts = 1;
8356 settle_in(
8357 &mut t,
8358 unstarted_verdict(RunStatus::AlreadyInBase),
8359 "already in main",
8360 1,
8361 phrases("en"),
8362 );
8363 assert_eq!(t.status, TaskStatus::Done);
8364 assert_eq!(t.attempts, 0);
8365 }
8366
8367 #[test]
8368 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8369 let reason = |language: &str| {
8370 let mut t = task();
8371 settle_in(
8372 &mut t,
8373 unstarted_verdict(RunStatus::Judging),
8374 "boom",
8375 1,
8376 phrases(language),
8377 );
8378 t.last_error.or(t.hold_reason).unwrap_or_default()
8379 };
8380 assert!(
8381 reason("en").starts_with("the graph stopped at `"),
8382 "{}",
8383 reason("en")
8384 );
8385 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8386 assert!(reason("日本語").contains("boom"));
8387 assert_eq!(reason("fr"), reason("en"));
8388 }
8389
8390 #[test]
8391 fn describe_follows_the_run_language_and_keeps_the_run_id() {
8392 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8393 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8394 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8395 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8396 assert!(ja.contains("[run "), "{ja}");
8397 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8398 assert!(ended.starts_with("run 終了: "), "{ended}");
8399 let mut de = run_state_in(RunStatus::Failed, "de");
8400 let mut en = run_state_in(RunStatus::Failed, "en");
8401 de.id = "same".to_owned();
8402 en.id = "same".to_owned();
8403 assert_eq!(describe(&de), describe(&en));
8404 }
8405
8406 #[test]
8407 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8408 use crate::handover::Refused;
8409 let cases = [
8410 Refused::Foreign {
8411 branch: "b".into(),
8412 path: "/w/x".into(),
8413 why: "made by hand".into(),
8414 },
8415 Refused::Unsafe {
8416 branch: "b".into(),
8417 path: "/w/x".into(),
8418 why: "its worktree has uncommitted changes (a.rs)".into(),
8419 },
8420 Refused::ReleaseFailed {
8421 branch: "b".into(),
8422 path: "/w/x".into(),
8423 run: "ab12".into(),
8424 },
8425 ];
8426 for r in &cases {
8427 let en = (phrases("en").handover_refused)(r);
8428 assert_eq!(en, r.to_string());
8429 let ja = (phrases("ja").handover_refused)(r);
8430 assert!(
8431 !ja.contains("is checked out") && !ja.contains("try again"),
8432 "{ja}"
8433 );
8434 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8435 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8436 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8437 }
8438 }
8439 assert!(phrases("en").handover_hint.contains("release the task"));
8440 assert!(phrases("ja").handover_hint.contains("解放"));
8441 }
8442
8443 #[test]
8444 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8445 let build = |lang: &str| {
8446 let mut s = run_state_in(RunStatus::Blocked, lang);
8447 s.id = "same".to_owned();
8448 s.config.graph.review_rounds = 3;
8449 let mut r = review_round(3);
8450 r.expected = 3;
8451 r.answered = 1;
8452 s.reviews.push(r);
8453 s.event(
8454 "review",
8455 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8456 );
8457 s
8458 };
8459 let en = describe(&build("en"));
8460 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8461 let ja = describe(&build("ja"));
8462 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8463 assert!(!ja.contains("never answered"), "{ja}");
8464 assert!(ja.contains("[run "), "{ja}");
8465
8466 let mut failed = build("ja");
8469 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8470 command: "cargo test".to_owned(),
8471 code: Some(1),
8472 output_tail: String::new(),
8473 duration_ms: 0,
8474 resource_blocked: false,
8475 });
8476 failed.event("review", "stopped; e2e failed: cargo test");
8477 let ja = describe(&failed);
8478 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8479 assert!(!ja.contains("席のレビュアー"), "{ja}");
8480 }
8481
8482 #[test]
8483 fn refusals_and_recovery_prose_follow_the_language() {
8484 let home = crate::run::test_home();
8485 let t = held_task_with("r1");
8486 let q = action_question(
8487 "r1",
8488 ask::ChoiceAction::Resume {
8489 run: "r1".to_owned(),
8490 },
8491 );
8492 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8493 ActionDecision::Refuse(s) => s,
8494 other => panic!("{other:?}"),
8495 };
8496 assert!(refuse(phrases("en")).contains("could not be read: gone"));
8497 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8498 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8499
8500 let mut held = task();
8501 reclaim(&mut held, None, 2, "ja");
8502 assert!(held.hold_reason.unwrap().contains("保留にしました"));
8503 let mut held = task();
8504 reclaim(&mut held, None, 2, "xx");
8505 assert!(held.hold_reason.unwrap().contains("held for a human"));
8506 }
8507
8508 fn run_state(status: RunStatus) -> RunState {
8509 let mut state = RunState::new(
8510 PathBuf::from("/repo"),
8511 "main".to_owned(),
8512 "abc1234def".to_owned(),
8513 "add retries".to_owned(),
8514 Config::default(),
8515 );
8516 state.status = status;
8517 state
8518 }
8519
8520 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8521 Candidate {
8522 index: 0,
8523 label,
8524 agent: "claude".to_owned(),
8525 branch: format!("magi/x/{label}"),
8526 worktree: PathBuf::from("/repo"),
8527 summary: summary.to_owned(),
8528 stat: String::new(),
8529 files: 0,
8530 commits: usize::from(!empty),
8531 empty,
8532 failed: failed.map(str::to_owned),
8533 verified_noop: None,
8534 duration_ms: 0,
8535 folded: false,
8536 }
8537 }
8538
8539 #[test]
8540 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8541 let mut state = run_state(RunStatus::Blocked);
8542 state.gate = vec![
8543 CommandOutcome {
8544 command: "cargo make check".to_owned(),
8545 code: Some(0),
8546 output_tail: "ok".to_owned(),
8547 duration_ms: 0,
8548 resource_blocked: false,
8549 },
8550 CommandOutcome {
8551 command: "cargo test".to_owned(),
8552 code: Some(101),
8553 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8554 duration_ms: 0,
8555 resource_blocked: false,
8556 },
8557 ];
8558 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8559 assert!(d.contains("cargo test"), "{d}");
8560 assert!(
8561 !d.contains("cargo make check"),
8562 "a passing check is not a diagnostic: {d}"
8563 );
8564 assert!(d.contains("assertion failed"), "{d}");
8565 }
8566
8567 #[test]
8568 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8569 let mut state = run_state(RunStatus::Blocked);
8570 state.event(
8571 "land",
8572 "stopped: the fixer produced no commit while 2 check(s) were failing \
8573 (build, lint); stopping instead of looping on an unchanged tree",
8574 );
8575 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8576 assert!(d.contains("build"), "{d}");
8577 assert!(d.contains("lint"), "{d}");
8578 assert!(d.contains("fixer produced no commit"), "{d}");
8579 }
8580
8581 #[test]
8582 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8583 let state = run_state(RunStatus::VerifiedNoop);
8588 let d = describe(&state);
8589 assert!(
8590 d.contains("agent-verified no-op"),
8591 "expected the display label, not the wire spelling: {d}"
8592 );
8593 assert!(!d.contains("verified_noop"), "{d}");
8594 }
8595
8596 #[test]
8597 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8598 let mut state = run_state(RunStatus::Failed);
8599 state.gate.push(crate::run::CommandOutcome {
8600 command: "cargo test".into(),
8601 code: Some(101),
8602 output_tail: format!(
8603 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8604 " 41: 0x1234 - backtrace frame\n".repeat(10000)
8605 ),
8606 duration_ms: 1,
8607 resource_blocked: false,
8608 });
8609 let d = diagnostic(&state).unwrap();
8610 assert!(d.contains("panicked at widget.rs:12"), "{d}");
8611 assert!(d.contains("assertion failed: widget missing"));
8612 assert!(d.contains("widget log"));
8613 }
8614
8615 #[test]
8616 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8617 let mut state = run_state(RunStatus::Failed);
8623 state.candidates = vec![candidate(
8624 'A',
8625 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8626 true,
8627 None,
8628 )];
8629 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8630 assert!(d.contains("candidate A"), "{d}");
8631 assert!(d.contains("tagged v1.2.3"), "{d}");
8632 }
8633
8634 #[test]
8635 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8636 let mut state = run_state(RunStatus::Failed);
8637 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8638 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8639 assert!(d.contains("candidate A"), "{d}");
8640 assert!(d.contains("agent timed out"), "{d}");
8641 }
8642
8643 #[test]
8644 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8645 let mut state = run_state(RunStatus::Failed);
8648 state.candidates = vec![candidate('A', "did the work", false, None)];
8649 assert!(diagnostic(&state).is_none());
8650 }
8651
8652 #[test]
8653 fn diagnostic_is_bounded_however_much_a_run_printed() {
8654 let mut state = run_state(RunStatus::Blocked);
8655 state.gate = vec![
8656 CommandOutcome {
8657 command: "cargo test".to_owned(),
8658 code: Some(101),
8659 output_tail: "x".repeat(50_000),
8660 duration_ms: 0,
8661 resource_blocked: false,
8662 },
8663 CommandOutcome {
8664 command: "cargo clippy".to_owned(),
8665 code: Some(1),
8666 output_tail: "y".repeat(50_000),
8667 duration_ms: 0,
8668 resource_blocked: false,
8669 },
8670 ];
8671 state.candidates = vec![
8672 candidate('A', &"z".repeat(50_000), true, None),
8673 candidate('B', &"w".repeat(50_000), true, None),
8674 ];
8675 let d = diagnostic(&state).expect("plenty here to diagnose");
8676 assert!(
8677 d.len() <= DIAGNOSTIC_MAX,
8678 "diagnostic grew to {} bytes, unbounded",
8679 d.len()
8680 );
8681 }
8682
8683 #[test]
8684 fn selected_delivery_guards_survive_recovery_failure_accounting() {
8685 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8686 let mut t = task();
8687 let mut state = run_state(status);
8688 t.pr_recovery = Some(crate::pr_recovery::Selection {
8689 url: "url".into(),
8690 branch: format!("magi/task-{}", t.id),
8691 head: "a".repeat(40),
8692 source_head: None,
8693 source_run: None,
8694 source_proof: None,
8695 disposition: Some(crate::pr_recovery::Disposition::Land),
8696 instruction: t.instruction.clone(),
8697 approved_at: Timestamp::now(),
8698 });
8699 state.pr_recovery = t.pr_recovery.clone();
8700 t.start(state.id.clone());
8701 settle_and_diagnose(
8702 &mut t,
8703 Verdict {
8704 status,
8705 left_pr: false,
8706 quota_hit: false,
8707 parked: false,
8708 no_viable_candidates: false,
8709 },
8710 "delivery stopped",
8711 5,
8712 &state,
8713 );
8714 assert_eq!(t.status, TaskStatus::Held);
8715 let reason = t.hold_reason.as_deref().unwrap();
8716 if status == RunStatus::Ready {
8717 assert!(reason.contains("Selected PR delivery is incomplete"));
8718 assert!(t.recovery_budget.is_none());
8719 } else {
8720 assert!(reason.contains("Selected recovery stopped"));
8721 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8722 }
8723 assert!(t.pr_recovery.is_some());
8724 }
8725 }
8726
8727 #[test]
8728 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8729 let mut state = run_state(RunStatus::Voting);
8730 state.base_sync = Some(crate::run::BaseSync {
8731 tip: "base-tip".into(),
8732 behind: 3,
8733 attempts: 4,
8734 conflict: Some("base stopped".into()),
8735 already_in: None,
8736 });
8737 state.record_base_sync_stop("candidate-head");
8738 let mut t = task();
8739 t.start(state.id.clone());
8740 let verdict = Verdict {
8741 status: RunStatus::Blocked,
8742 left_pr: false,
8743 quota_hit: false,
8744 parked: false,
8745 no_viable_candidates: false,
8746 };
8747 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8748 assert_eq!(
8749 t.status,
8750 TaskStatus::Held,
8751 "unspent task attempts cannot start another competition"
8752 );
8753 let at = t.held_at;
8754 let cause = t.hold_notice_cause.clone();
8755 state.begin_pass();
8756 t.release_operator("test-resume", None);
8757 t.start(state.id.clone());
8758 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8759 assert_eq!(t.status, TaskStatus::Held);
8760 assert_eq!(t.held_at, at);
8761 assert_eq!(t.hold_notice_cause, cause);
8762 }
8763
8764 #[test]
8765 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8766 let mut state = run_state(RunStatus::Blocked);
8767 state.gate = vec![CommandOutcome {
8768 command: "cargo test".to_owned(),
8769 code: Some(101),
8770 output_tail: "assertion failed".to_owned(),
8771 duration_ms: 0,
8772 resource_blocked: false,
8773 }];
8774 let verdict = Verdict {
8775 status: RunStatus::Blocked,
8776 left_pr: false,
8777 quota_hit: false,
8778 parked: false,
8779 no_viable_candidates: false,
8780 };
8781
8782 let mut t = task();
8785 t.start("run-1".to_owned());
8786 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8787 assert_eq!(t.status, TaskStatus::Failed);
8788 assert!(t.diagnostic.is_none());
8789
8790 t.start("run-2".to_owned());
8793 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8794 assert_eq!(t.status, TaskStatus::Held);
8795 let d = t.diagnostic.expect("a held task must carry its diagnostic");
8796 assert!(d.contains("cargo test"), "{d}");
8797 }
8798
8799 #[test]
8800 fn a_held_task_names_the_open_question_it_is_waiting_on() {
8801 crate::run::pin_test_home();
8806 let home = crate::run::home();
8807 let state = run_state(RunStatus::VerifiedNoop);
8808 let mut q = ask::Question::new(
8809 state.id.clone(),
8810 "implement".to_owned(),
8811 "impl-A".to_owned(),
8812 "is this really a no-op?".to_owned(),
8813 String::new(),
8814 Vec::new(),
8815 );
8816 Questions::at(home.join("questions")).put(&mut q).unwrap();
8817
8818 let verdict = Verdict {
8819 status: RunStatus::VerifiedNoop,
8820 left_pr: false,
8821 quota_hit: false,
8822 parked: false,
8823 no_viable_candidates: false,
8824 };
8825 let mut t = task();
8826 t.start(state.id.clone());
8827 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8828
8829 assert_eq!(t.status, TaskStatus::Held);
8830 let reason = t.hold_reason.expect("a held task must record why");
8831 assert!(
8832 reason.starts_with("run ended agent-verified no-op"),
8833 "the original settle reason must survive unchanged: {reason}"
8834 );
8835 assert!(
8836 reason.contains(q.short()),
8837 "the open question's id must be named so the notice is actionable: {reason}"
8838 );
8839 }
8840
8841 #[test]
8842 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8843 crate::run::pin_test_home();
8844 let state = run_state(RunStatus::VerifiedNoop);
8845
8846 let verdict = Verdict {
8847 status: RunStatus::VerifiedNoop,
8848 left_pr: false,
8849 quota_hit: false,
8850 parked: false,
8851 no_viable_candidates: false,
8852 };
8853 let mut t = task();
8854 t.start(state.id.clone());
8855 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8856
8857 assert_eq!(t.status, TaskStatus::Held);
8858 assert_eq!(
8859 t.hold_reason.as_deref(),
8860 Some("run ended agent-verified no-op"),
8861 "nothing to append when the question was already answered or never asked"
8862 );
8863 }
8864
8865 #[test]
8866 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8867 crate::run::pin_test_home();
8868 let mut first = run_state(RunStatus::Blocked);
8869 first.id = "20260101-000000-sup1".to_owned();
8870 first.save().unwrap();
8871 let mut second = run_state(RunStatus::Merged);
8872 second.id = "20260101-000000-sup2".to_owned();
8873 second.save().unwrap();
8874
8875 let mut t = task();
8876 t.runs = vec![first.id.clone(), second.id.clone()];
8877 t.status = TaskStatus::Done;
8878
8879 supersede_prior_runs(&t, &crate::run::home());
8880
8881 assert_eq!(
8882 RunState::load(&first.id).unwrap().status,
8883 RunStatus::Superseded,
8884 "the first attempt's Blocked no longer needs anyone's attention"
8885 );
8886 assert_eq!(
8887 RunState::load(&second.id).unwrap().status,
8888 RunStatus::Merged,
8889 "the run that actually succeeded is left exactly as it was"
8890 );
8891 }
8892
8893 #[test]
8894 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8895 crate::run::pin_test_home();
8901 let mut first = run_state(RunStatus::Blocked);
8902 first.id = "20260101-000000-sup9".to_owned();
8903 first.driver_pid = Some(std::process::id());
8906 first.driver_started_at = Some(
8907 crate::proc::process_started_at(std::process::id())
8908 .expect("this test process's own start time must be queryable"),
8909 );
8910 first.save().unwrap();
8911 let mut second = run_state(RunStatus::Merged);
8912 second.id = "20260101-000000-supa".to_owned();
8913 second.save().unwrap();
8914
8915 let mut t = task();
8916 t.runs = vec![first.id.clone(), second.id.clone()];
8917 t.status = TaskStatus::Done;
8918
8919 supersede_prior_runs(&t, &crate::run::home());
8920
8921 assert_eq!(
8922 RunState::load(&first.id).unwrap().status,
8923 RunStatus::Blocked,
8924 "a live driver_pid means something is still actually working this run, \
8925 even though no daemon claims it - rewriting under it would just be \
8926 undone the next time that process saves"
8927 );
8928 }
8929
8930 #[test]
8931 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8932 let dir = tempfile::tempdir().unwrap();
8938 let home = dir.path().to_path_buf();
8939 let queue = Queue::at(dir.path().join("queue"));
8940
8941 let mut first = run_state(RunStatus::Blocked);
8942 first.id = "20260101-000000-supd".to_owned();
8943 first.driver_pid = Some(std::process::id());
8944 first.driver_started_at = Some(
8945 crate::proc::process_started_at(std::process::id())
8946 .expect("this test process's own start time must be queryable"),
8947 );
8948 first.save_under(&home).unwrap();
8949 let mut second = run_state(RunStatus::Merged);
8950 second.id = "20260101-000000-supe".to_owned();
8951 second.save_under(&home).unwrap();
8952
8953 let mut t = task();
8954 t.runs = vec![first.id.clone(), second.id.clone()];
8955 t.status = TaskStatus::Done;
8956 queue.put(&mut t).unwrap();
8957
8958 resweep_superseded_attempts(&queue, &home);
8959 assert_eq!(
8960 RunState::load_under(&first.id, &home).unwrap().status,
8961 RunStatus::Blocked,
8962 "still live on the first pass, so still untouched"
8963 );
8964
8965 let mut stale = RunState::load_under(&first.id, &home).unwrap();
8971 stale.driver_started_at = Some("1".to_owned());
8972 stale.save_under(&home).unwrap();
8973
8974 resweep_superseded_attempts(&queue, &home);
8975 assert_eq!(
8976 RunState::load_under(&first.id, &home).unwrap().status,
8977 RunStatus::Superseded,
8978 "the second pass catches up what the first one correctly skipped"
8979 );
8980 }
8981
8982 #[test]
8983 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8984 crate::run::pin_test_home();
8985 let mut first = run_state(RunStatus::Blocked);
8986 first.id = "20260101-000000-sup3".to_owned();
8987 first.save().unwrap();
8988 let mut second = run_state(RunStatus::Blocked);
8989 second.id = "20260101-000000-sup4".to_owned();
8990 second.save().unwrap();
8991
8992 let mut t = task();
8993 t.runs = vec![first.id.clone(), second.id.clone()];
8994 t.status = TaskStatus::Failed;
8998
8999 supersede_prior_runs(&t, &crate::run::home());
9000
9001 assert_eq!(
9002 RunState::load(&first.id).unwrap().status,
9003 RunStatus::Blocked
9004 );
9005 assert_eq!(
9006 RunState::load(&second.id).unwrap().status,
9007 RunStatus::Blocked
9008 );
9009 }
9010
9011 #[test]
9012 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9013 crate::run::pin_test_home();
9017 let mut first = run_state(RunStatus::Blocked);
9018 first.id = "20260101-000000-sup5".to_owned();
9019 first.save().unwrap();
9020
9021 let mut t = task();
9022 t.runs = vec![first.id.clone()];
9023 t.status = TaskStatus::Done;
9024
9025 supersede_prior_runs(&t, &crate::run::home());
9026
9027 assert_eq!(
9028 RunState::load(&first.id).unwrap().status,
9029 RunStatus::Blocked,
9030 "a single-attempt task has no earlier run to supersede"
9031 );
9032 }
9033
9034 #[test]
9035 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9036 crate::run::pin_test_home();
9043 let mut first = run_state(RunStatus::Blocked);
9044 first.id = "20260101-000000-supb".to_owned();
9045 first.save().unwrap();
9046 let mut second = run_state(RunStatus::Failed);
9047 second.id = "20260101-000000-supc".to_owned();
9048 second.save().unwrap();
9049
9050 let mut t = task();
9051 t.runs = vec![first.id.clone(), second.id.clone()];
9052 t.status = TaskStatus::Done;
9053
9054 supersede_prior_runs(&t, &crate::run::home());
9055
9056 assert_eq!(
9057 RunState::load(&first.id).unwrap().status,
9058 RunStatus::Blocked,
9059 "the task's last attempt never landed, so there is nothing here \
9060 actually superseding it"
9061 );
9062 }
9063
9064 #[test]
9065 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9066 crate::run::pin_test_home();
9070 let mut failed = run_state(RunStatus::Failed);
9071 failed.id = "20260101-000000-sup6".to_owned();
9072 failed.save().unwrap();
9073 let mut noop = run_state(RunStatus::VerifiedNoop);
9074 noop.id = "20260101-000000-sup7".to_owned();
9075 noop.save().unwrap();
9076 let mut winner = run_state(RunStatus::Ready);
9077 winner.id = "20260101-000000-sup8".to_owned();
9078 winner.save().unwrap();
9079
9080 let mut t = task();
9081 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9082 t.status = TaskStatus::Done;
9083
9084 supersede_prior_runs(&t, &crate::run::home());
9085
9086 assert_eq!(
9087 RunState::load(&failed.id).unwrap().status,
9088 RunStatus::Failed
9089 );
9090 assert_eq!(
9091 RunState::load(&noop.id).unwrap().status,
9092 RunStatus::VerifiedNoop
9093 );
9094 }
9095
9096 fn approval_question(run: &str) -> ask::Question {
9097 ask::Question::new(
9098 run.to_owned(),
9099 land::APPROVAL_NODE.to_owned(),
9100 "land".to_owned(),
9101 "merge?".to_owned(),
9102 String::new(),
9103 vec!["merge".to_owned(), "hold".to_owned()],
9104 )
9105 }
9106
9107 #[test]
9108 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9109 crate::run::pin_test_home();
9110 let mut state = run_state(RunStatus::Landing);
9111 state.id = "20260101-000000-fre1".to_owned();
9112 state.parked = true;
9113 state.save().unwrap();
9114 ask::Questions::open()
9115 .put(&mut approval_question(&state.id))
9116 .unwrap();
9117
9118 let mut t = task();
9119 t.runs.push(state.id.clone());
9120 assert_eq!(
9121 land_resume_state(&t),
9122 LandResume::StillWaiting,
9123 "nobody has answered and the timeout has not passed"
9124 );
9125 }
9126
9127 #[test]
9128 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9129 crate::run::pin_test_home();
9130 let mut state = run_state(RunStatus::Gating);
9131 state.id = "20260101-000000-gt01".to_owned();
9132 state.parked = true;
9133 state.config.graph.answer_timeout = 60;
9134 state.github_text = Some(crate::run::GithubTextAsk {
9135 rewrite: None,
9136 fingerprint: "f".into(),
9137 title: true,
9138 body: false,
9139 categories: vec!["title-language".into()],
9140 question: None,
9141 asks: 1,
9142 resolved: false,
9143 chosen_title: None,
9144 choice: None,
9145 });
9146 state.save().unwrap();
9147 let store = ask::Questions::open();
9148 let mut q = ask::Question::new(
9149 state.id.clone(),
9150 crate::github_text::ASK_NODE.to_owned(),
9151 crate::github_text::ASK_SEAT.to_owned(),
9152 "s".into(),
9153 String::new(),
9154 vec!["use fallback".into()],
9155 );
9156 store.put(&mut q).unwrap();
9157 let mut t = task();
9158 t.runs.push(state.id.clone());
9159 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9160 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9161 store.put(&mut q).unwrap();
9162 assert_eq!(land_resume_state(&t), LandResume::Ready);
9163 assert!(!store.get(&q.id).unwrap().status.open());
9164 state.github_text.as_mut().unwrap().resolved = true;
9166 state.save().unwrap();
9167 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9168 }
9169
9170 #[test]
9171 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9172 crate::run::pin_test_home();
9177 let mut state = run_state(RunStatus::Landing);
9178 state.id = "20260101-000000-exp1".to_owned();
9179 state.parked = true;
9180 state.config.graph.answer_timeout = 60;
9181 state.save().unwrap();
9182
9183 let store = ask::Questions::open();
9184 let mut q = approval_question(&state.id);
9185 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9186 store.put(&mut q).unwrap();
9187
9188 let mut t = task();
9189 t.runs.push(state.id.clone());
9190 assert_eq!(
9191 land_resume_state(&t),
9192 LandResume::Ready,
9193 "an expired question must not be waited on forever"
9194 );
9195
9196 let after = store.get(&q.id).unwrap();
9197 assert!(
9198 !after.status.open(),
9199 "the question is abandoned, not silently ignored"
9200 );
9201 assert!(
9202 after.resolution().is_none(),
9203 "an abandoned question is not read as a decision"
9204 );
9205 }
9206
9207 #[test]
9208 fn reclaim_settles_a_running_task_against_its_last_run() {
9209 let mut t = task();
9210 t.start("20260904-000000-4043".to_owned());
9211 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9212 assert_eq!(
9213 t.status,
9214 TaskStatus::Done,
9215 "a run that actually finished must not stay `running` forever"
9216 );
9217 }
9218
9219 #[test]
9220 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9221 let mut t = task();
9222 t.start("20260904-000000-4043".to_owned());
9223 t.last_error = Some("earlier trouble".to_owned());
9224 let mut state = run_state(RunStatus::Judging);
9225 state.parked = true;
9226 reclaim(&mut t, Some(state), 1, "en");
9227 assert_eq!(t.status, TaskStatus::Parked);
9228 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9229 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9230 assert!(t.park_reason.is_some());
9231 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9232 assert!(!t.fresh_start);
9233 assert!(t.status.runnable());
9234 }
9235
9236 #[test]
9237 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9238 let mut t = task();
9239 t.start("20260904-000000-4043".to_owned());
9240 t.last_error = Some("earlier trouble".to_owned());
9241 settle(
9242 &mut t,
9243 Verdict {
9244 status: RunStatus::Judging,
9245 left_pr: false,
9246 quota_hit: false,
9247 parked: true,
9248 no_viable_candidates: false,
9249 },
9250 "parked after `judging`",
9251 1,
9252 );
9253 assert_eq!(t.status, TaskStatus::Parked);
9254 assert_eq!(t.attempts, 0);
9255 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9256 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9257 assert_eq!(t.schema, crate::queue::SCHEMA);
9258 assert!(
9259 crate::notices::task_held(&t).is_none(),
9260 "a park is not news"
9261 );
9262 t.start("20260904-000000-4043".to_owned());
9263 assert_eq!(t.park_reason, None);
9264 }
9265
9266 #[test]
9267 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9268 let mut t = task();
9272 t.start("20260904-000000-4043".to_owned());
9273 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9274 assert_eq!(t.status, TaskStatus::Failed);
9275 assert!(t.status.runnable());
9276 }
9277
9278 #[test]
9279 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9280 let mut t = task();
9281 t.start("20260904-000000-4043".to_owned());
9282 assert_eq!(t.attempts, 1);
9283 let mut run = run_state(RunStatus::Implementing);
9284 run.id = "20260904-000000-4043".to_owned();
9285 run.begin_pass();
9286 let cause = crate::run::ParkCause::Upgrade {
9287 from: "0.121.0".to_owned(),
9288 to: Some("0.121.1".to_owned()),
9289 };
9290 run.end_pass_parked(cause.clone());
9291 run.parked = true;
9292 let verdict = Verdict {
9293 status: run.status,
9294 left_pr: false,
9295 quota_hit: false,
9296 parked: true,
9297 no_viable_candidates: false,
9298 };
9299 let mut orphan = t.clone();
9302 reclaim(&mut orphan, Some(run.clone()), 2, "en");
9303 assert_eq!(orphan.status, TaskStatus::Parked);
9304 assert_eq!(orphan.attempts, 0);
9305 assert_eq!(
9306 orphan.upgrade_resume_key(),
9307 Some((run.passes[0].started_at, orphan.id.as_str()))
9308 );
9309 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9310 assert_eq!(t.attempts, 0);
9311 assert_eq!(t.passes.len(), 1);
9312 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9313 assert_eq!(t.passes[0].parked, Some(cause));
9314 assert_eq!(t.passes[0].pass_index, 0);
9315 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9316 assert!(t.upgrade_resume_key().is_some());
9317
9318 t.start("20260904-000000-4043".to_owned());
9321 run.begin_pass();
9322 run.status = RunStatus::Failed;
9323 let verdict = Verdict {
9324 status: RunStatus::Failed,
9325 left_pr: false,
9326 quota_hit: false,
9327 parked: false,
9328 no_viable_candidates: false,
9329 };
9330 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9331 assert_eq!(t.passes.len(), 2);
9332 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9333 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9334 assert_eq!(t.passes[1].pass_index, 1);
9335 assert_eq!(t.attempts, 1);
9336 }
9337
9338 #[test]
9339 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9340 let mut t = task();
9341 t.start("20260904-000000-4043".to_owned());
9342 reclaim(&mut t, None, 2, "en");
9343 assert_eq!(t.status, TaskStatus::Held);
9344 assert!(
9345 t.last_error
9346 .as_deref()
9347 .is_some_and(|e| e.contains("running")),
9348 "the operator needs to know why this task was held"
9349 );
9350 }
9351
9352 #[test]
9353 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9354 let dir = tempfile::tempdir().unwrap();
9355 let queue = Queue::at(dir.path().to_path_buf());
9356
9357 let mut orphaned = task();
9359 orphaned.id = "20260904-000000-orph".to_owned();
9360 orphaned.status = TaskStatus::Running;
9361 orphaned.attempts = 1;
9362 queue.put(&mut orphaned).unwrap();
9363
9364 let mut alive = task();
9365 alive.id = "20260904-000000-live".to_owned();
9366 alive.status = TaskStatus::Running;
9367 alive.attempts = 1;
9368 queue.put(&mut alive).unwrap();
9369 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9370
9371 let mut queued = task();
9372 queued.id = "20260904-000000-wait".to_owned();
9373 queue.put(&mut queued).unwrap();
9374
9375 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9376 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9377
9378 assert_eq!(
9379 queue.get(&orphaned.id).unwrap().status,
9380 TaskStatus::Held,
9381 "nothing was driving it and there was no run to recover"
9382 );
9383 assert_eq!(
9384 queue.get(&alive.id).unwrap().status,
9385 TaskStatus::Running,
9386 "a live claim must protect the task it belongs to"
9387 );
9388 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9389 }
9390
9391 fn read_run_under(home: &Path, id: &str) -> RunState {
9397 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9398 serde_json::from_str(&body).unwrap()
9399 }
9400
9401 #[test]
9402 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9403 let dir = tempfile::tempdir().unwrap();
9404 let home = dir.path().to_path_buf();
9405 let now = Timestamp::now();
9406 let overrun_seat = || crate::run::ActiveSeat {
9407 node: "implement".to_owned(),
9408 started_at: now - jiff::SignedDuration::new(21_000, 0),
9409 timeout_secs: 3_600,
9410 attempt: 0,
9411 task: None,
9412 command: None,
9413 index: None,
9414 total: None,
9415 };
9416
9417 let mut dead = run_state(RunStatus::Implementing);
9418 dead.id = "20260101-000000-dead".to_owned();
9419 dead.active.insert("impl-A".to_owned(), overrun_seat());
9420 dead.driver_pid = Some(4242);
9423 dead.save_under(&home).unwrap();
9424
9425 let mut alive = run_state(RunStatus::Implementing);
9428 alive.id = "20260101-000000-aliv".to_owned();
9429 alive.active.insert("impl-A".to_owned(), overrun_seat());
9430 alive.save_under(&home).unwrap();
9431 let mut status = Status::new();
9432 status.current = vec![Current {
9433 worker: None,
9434 task: "20260101-000000-task".to_owned(),
9435 run: alive.id.clone(),
9436 }];
9437 write_status_to(&home.join("daemon.json"), &status).unwrap();
9438
9439 let questions = Questions::at(home.join("questions"));
9443 let mut q = ask::Question::new(
9444 dead.id.clone(),
9445 "implement".to_owned(),
9446 "impl-A".to_owned(),
9447 "Which storage backend?".to_owned(),
9448 String::new(),
9449 vec!["SQLite".to_owned(), "Redis".to_owned()],
9450 );
9451 questions.put(&mut q).unwrap();
9452
9453 let abandoned = reclaim_abandoned_runs_with(
9454 &home,
9455 now,
9456 |pid| if pid == 4242 { Some(false) } else { None },
9457 |_| panic!("a query answering Dead outright needs no identity corroboration"),
9458 );
9459 assert_eq!(abandoned, vec![dead.id.clone()]);
9460
9461 let reloaded = read_run_under(&home, &dead.id);
9462 assert_eq!(reloaded.status, RunStatus::Failed);
9463 assert!(reloaded.active.is_empty());
9464 assert!(
9465 !questions.get(&q.id).unwrap().status.open(),
9466 "the failed run's own open question must be settled in the same pass"
9467 );
9468
9469 let still_alive = read_run_under(&home, &alive.id);
9470 assert_eq!(
9471 still_alive.status,
9472 RunStatus::Implementing,
9473 "a live daemon's claim protects it"
9474 );
9475 assert!(!still_alive.active.is_empty());
9476 }
9477
9478 #[test]
9488 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9489 let dir = tempfile::tempdir().unwrap();
9490 let home = dir.path().to_path_buf();
9491 let now = Timestamp::now();
9492
9493 let mut manual = run_state(RunStatus::Reviewing);
9494 manual.id = "20260101-000000-manl".to_owned();
9495 manual.active.insert(
9496 "review-1".to_owned(),
9497 crate::run::ActiveSeat {
9498 node: "review".to_owned(),
9499 started_at: now - jiff::SignedDuration::new(21_000, 0),
9500 timeout_secs: 3_600,
9501 attempt: 0,
9502 task: None,
9503 command: None,
9504 index: None,
9505 total: None,
9506 },
9507 );
9508 manual.driver_pid = Some(4242);
9512 manual.driver_started_at = Some("1790000000".to_owned());
9513 manual.save_under(&home).unwrap();
9514
9515 let abandoned = reclaim_abandoned_runs_with(
9516 &home,
9517 now,
9518 |pid| if pid == 4242 { Some(true) } else { None },
9519 |pid| {
9520 if pid == 4242 {
9521 Some("1790000000".to_owned())
9522 } else {
9523 None
9524 }
9525 },
9526 );
9527 assert!(
9528 abandoned.is_empty(),
9529 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9530 );
9531
9532 let reloaded = read_run_under(&home, &manual.id);
9533 assert_eq!(reloaded.status, RunStatus::Reviewing);
9534 assert!(!reloaded.active.is_empty());
9535 }
9536
9537 #[test]
9538 fn an_already_claimed_task_is_skipped_rather_than_failed() {
9539 let dir = tempfile::tempdir().unwrap();
9540 let queue = Queue::at(dir.path().to_path_buf());
9541 let mut only = task();
9542 queue.put(&mut only).unwrap();
9543
9544 let _elsewhere = queue.claim(&only.id).unwrap();
9545 let candidates = runnable(&queue);
9546 assert_eq!(candidates.len(), 1, "the task is still runnable");
9547 assert!(
9548 queue.claim(&candidates[0].id).is_err(),
9549 "the loop cannot take a claim somebody else holds"
9550 );
9551
9552 let after = queue.get(&only.id).unwrap();
9553 assert_eq!(after.status, TaskStatus::Queued);
9554 assert_eq!(
9555 after.attempts, 0,
9556 "losing the race is not an attempt at the task"
9557 );
9558 assert_eq!(after.last_error, None);
9559 }
9560
9561 #[test]
9562 fn the_status_file_round_trips_and_its_heartbeat_advances() {
9563 let dir = tempfile::tempdir().unwrap();
9564 let path = dir.path().join("daemon.json");
9565
9566 let mut status = Status::new();
9567 status.idle = false;
9568 status.completed = 7;
9569 status.current = vec![Current {
9570 worker: None,
9571 task: "20260902-000000-t111".to_owned(),
9572 run: "20260902-000001-r111".to_owned(),
9573 }];
9574 write_status_to(&path, &status).unwrap();
9575 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9576 assert_eq!(first.schema, SCHEMA);
9577 assert_eq!(first.pid, std::process::id());
9578 assert!(!first.idle);
9579 assert_eq!(first.completed, 7);
9580 assert_eq!(first.current, status.current);
9581 assert!(
9582 !path.with_extension("json.tmp").exists(),
9583 "the temp file is renamed, not left behind"
9584 );
9585
9586 std::thread::sleep(Duration::from_millis(5));
9587 status.updated_at = Timestamp::now();
9588 status.polls = 3;
9589 write_status_to(&path, &status).unwrap();
9590 let second: Status =
9591 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9592 assert!(
9593 second.updated_at > first.updated_at,
9594 "a reader can only detect staleness if the heartbeat moves"
9595 );
9596 assert_eq!(
9597 second.started_at, first.started_at,
9598 "the start time is not a heartbeat"
9599 );
9600 assert_eq!(second.polls, 3);
9601 }
9602
9603 #[test]
9604 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9605 let dir = tempfile::tempdir().unwrap();
9606
9607 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9608
9609 let mut status = Status::new();
9610 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9611 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9612 let stale = read_status(dir.path()).unwrap();
9613 assert!(
9614 !stale.running(Timestamp::now()),
9615 "a minute without a heartbeat is a dead daemon, not a busy one"
9616 );
9617 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9618
9619 status.updated_at = Timestamp::now();
9620 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9621 let fresh = read_status(dir.path()).unwrap();
9622 assert!(fresh.running(Timestamp::now()));
9623 }
9624
9625 #[test]
9626 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9627 let dir = tempfile::tempdir().unwrap();
9628 let now = Timestamp::now();
9629 let mine = "20260903-080619-01c2";
9630
9631 assert!(
9632 !is_working_on(dir.path(), mine, now),
9633 "no status file means nobody is working on anything"
9634 );
9635
9636 let mut status = Status::new();
9637 status.current = vec![Current {
9638 worker: None,
9639 task: "20260903-080340-0167".to_owned(),
9640 run: mine.to_owned(),
9641 }];
9642 status.updated_at = now;
9643 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9644 assert!(is_working_on(dir.path(), mine, now));
9645 assert!(
9646 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9647 "a daemon busy with one run is not working on another"
9648 );
9649
9650 status.updated_at = now - jiff::SignedDuration::from_secs(600);
9653 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9654 assert!(
9655 !is_working_on(dir.path(), mine, now),
9656 "a stale heartbeat is a dead daemon, so its run is a leftover"
9657 );
9658 }
9659
9660 #[test]
9661 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9662 let dir = tempfile::tempdir().unwrap();
9663 let now = Timestamp::now();
9664
9665 assert!(
9666 !is_working_on_short(dir.path(), "01c2", now),
9667 "no status file means nobody is working on anything"
9668 );
9669
9670 let mut status = Status::new();
9671 status.current = vec![Current {
9672 worker: None,
9673 task: "20260903-080340-0167".to_owned(),
9674 run: "20260903-080619-01c2".to_owned(),
9675 }];
9676 status.updated_at = now;
9677 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9678 assert!(
9679 is_working_on_short(dir.path(), "01c2", now),
9680 "the run's short id is the last block of its full id"
9681 );
9682 assert!(
9683 !is_working_on_short(dir.path(), "3cbf", now),
9684 "a daemon busy with one worktree bay is not working on another"
9685 );
9686 }
9687
9688 #[test]
9689 fn a_newer_status_file_still_yields_a_reading() {
9690 let dir = tempfile::tempdir().unwrap();
9691 std::fs::write(
9694 dir.path().join("daemon.json"),
9695 serde_json::json!({
9696 "schema": 2,
9697 "updated_at": Timestamp::now().to_string(),
9698 "idle": true,
9699 "surprise": { "nested": [1, 2, 3] },
9700 })
9701 .to_string(),
9702 )
9703 .unwrap();
9704
9705 let reading = read_status(dir.path()).expect("a forward-compatible read");
9706 assert!(reading.running(Timestamp::now()));
9707 assert!(reading.idle);
9708 assert!(reading.current.is_empty());
9709 }
9710
9711 #[test]
9712 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9713 let dir = tempfile::tempdir().unwrap();
9719 std::fs::write(
9720 dir.path().join("daemon.json"),
9721 serde_json::json!({
9722 "schema": 1,
9723 "pid": 4242,
9724 "updated_at": Timestamp::now().to_string(),
9725 "idle": false,
9726 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9727 "completed": 3,
9728 "polls": 9,
9729 })
9730 .to_string(),
9731 )
9732 .unwrap();
9733
9734 let reading = read_status(dir.path()).expect("an older shape must still parse");
9735 assert!(reading.running(Timestamp::now()));
9736 assert_eq!(
9737 reading.current,
9738 vec![Current {
9739 worker: None,
9740 task: "20260902-140501-aaaa".to_owned(),
9741 run: "20260902-140502-bbbb".to_owned(),
9742 }]
9743 );
9744 }
9745
9746 #[test]
9747 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9748 let dir = tempfile::tempdir().unwrap();
9749 std::fs::write(
9750 dir.path().join("daemon.json"),
9751 serde_json::json!({
9752 "schema": 1,
9753 "updated_at": Timestamp::now().to_string(),
9754 "idle": true,
9755 "current": null,
9756 })
9757 .to_string(),
9758 )
9759 .unwrap();
9760 let with_null = read_status(dir.path()).expect("null must still parse");
9761 assert!(with_null.current.is_empty());
9762
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 })
9770 .to_string(),
9771 )
9772 .unwrap();
9773 let absent = read_status(dir.path()).expect("a missing field must still parse");
9774 assert!(absent.current.is_empty());
9775 }
9776
9777 #[test]
9778 fn a_task_without_a_repository_runs_in_the_daemons_default() {
9779 let fallback = Path::new("/default");
9780 let mut blank = task();
9781 blank.repo = PathBuf::new();
9782 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9783 let mut dot = task();
9784 dot.repo = PathBuf::from(".");
9785 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9786 assert_eq!(
9787 repo_for(&task(), fallback),
9788 PathBuf::from("/repo"),
9789 "a task that names a repository keeps it"
9790 );
9791 }
9792
9793 #[test]
9794 fn task_implementers_edit_inherits_daemon_config_and_merge() {
9795 let dir = tempfile::tempdir().unwrap();
9796 let path = dir.path().join("explicit.toml");
9797 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9798 let opts = Opts {
9799 config: Some(path),
9800 merge: Some("none".into()),
9801 ..Default::default()
9802 };
9803 let mut t = task();
9804 t.set_implementers(
9805 2,
9806 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9807 .unwrap(),
9808 )
9809 .unwrap();
9810 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9811 assert_eq!(cfg.graph.implementers, 2);
9812 assert_eq!(cfg.graph.judges, 1);
9813 assert_eq!(cfg.merge.mode, MergeMode::None);
9814 t.set_implementers(1, &cfg).unwrap();
9815 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9816 apply_task_implementers(&mut cfg, &t);
9817 assert_eq!(cfg.graph.implementers, 1);
9818 assert_eq!(cfg.graph.judges, 1);
9819 assert_eq!(cfg.merge.mode, MergeMode::None);
9820 }
9821
9822 #[test]
9823 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9824 let dir = tempfile::tempdir().unwrap();
9825 let repo = dir.path().join("repo");
9826 std::fs::create_dir(&repo).unwrap();
9827 std::fs::write(
9828 repo.join("magi.toml"),
9829 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9830 )
9831 .unwrap();
9832 let daemon_config = dir.path().join("daemon.toml");
9833 std::fs::write(
9834 &daemon_config,
9835 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9836 )
9837 .unwrap();
9838 let opts = Opts {
9839 config: Some(daemon_config),
9840 merge: Some("pr".into()),
9841 ..Default::default()
9842 };
9843 let q = Queue::at(dir.path().join("queue"));
9844 let validation: Config =
9845 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9846 .unwrap();
9847 for record in ["{}", r#"{"candidates":2}"#] {
9849 let overrides = serde_json::from_str(record).unwrap();
9850 let filing = crate::direct::Filing {
9851 instruction: "work".into(),
9852 title: "direct".into(),
9853 repo: repo.clone(),
9854 source: crate::queue::Source::Human,
9855 solo: false,
9856 overrides,
9857 review_of: None,
9858 sources: Default::default(),
9859 };
9860 let filed =
9861 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9862 let crate::direct::Filed::Standalone {
9863 mut task,
9864 claim: _claim,
9865 } = filed
9866 else {
9867 panic!("local filing")
9868 };
9869 let before = prepare_for(&repo, &opts, &task).unwrap();
9870 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9871 assert_eq!(
9872 before.merge.mode,
9873 MergeMode::None,
9874 "daemon --merge must not leak"
9875 );
9876 for n in [2, 1, 2] {
9877 task.set_implementers(n, &validation).unwrap();
9878 q.put(&mut task).unwrap();
9879 task = q.get(&task.id).unwrap();
9880 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9881 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9882 apply_task_implementers(&mut cfg, &task);
9883 assert_eq!(cfg.graph.implementers, usize::from(n));
9884 assert_eq!(cfg.graph.judges, 2);
9885 assert_eq!(cfg.merge.mode, MergeMode::None);
9886 }
9887 }
9888 }
9889
9890 #[test]
9891 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9892 let cfg: Config =
9893 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9894 .unwrap();
9895 let mut t = task();
9896 t.review_of = Some("review-target".into());
9897 t.hold_manual(Some("retry".into()));
9898 let mut previous = RunState::new(
9899 PathBuf::from("/repo"),
9900 "main".into(),
9901 "abc1234".into(),
9902 "review".into(),
9903 cfg.clone(),
9904 );
9905 previous.config.graph.implementers = 2;
9906 for count in [1, 3] {
9907 t.set_implementers(count, &cfg).unwrap();
9908 t.release();
9909 assert_eq!(t.review_of.as_deref(), Some("review-target"));
9910 for proposed in [
9911 Starter::Resume(previous.id.clone()),
9912 Starter::Review("recovery-target".into()),
9913 ] {
9914 assert_eq!(
9915 starter_with_implementers(&t, Some(&previous), proposed),
9916 Starter::Review("review-target".into())
9917 );
9918 }
9919 let mut configured = cfg.clone();
9920 apply_task_implementers(&mut configured, &t);
9921 assert_eq!(configured.graph.implementers, usize::from(count));
9922 assert_eq!(previous.config.graph.implementers, 2);
9923 }
9924 }
9925
9926 #[test]
9927 fn task_implementers_dispatch_and_resume_agree() {
9928 let mut t = task();
9929 let cfg: crate::config::Config =
9930 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9931 .unwrap();
9932 let mut run = RunState::new(
9933 PathBuf::from("/repo"),
9934 "main".into(),
9935 "abc1234".into(),
9936 "work".into(),
9937 cfg.clone(),
9938 );
9939 run.config.graph.implementers = 2;
9940 for n in [2, 1, 3, 2] {
9941 t.set_implementers(n, &cfg).unwrap();
9942 let mut dispatched = cfg.clone();
9943 apply_task_implementers(&mut dispatched, &t);
9944 assert_eq!(dispatched.graph.implementers, usize::from(n));
9945 assert_eq!(implementers_match(&t, &run), n == 2);
9946 for proposed in [
9947 Starter::Resume(run.id.clone()),
9948 Starter::Review("old-branch".into()),
9949 ] {
9950 let expected = if n == 2 {
9951 proposed.clone()
9952 } else {
9953 Starter::Start
9954 };
9955 assert_eq!(
9956 starter_with_implementers(&t, Some(&run), proposed),
9957 expected
9958 );
9959 }
9960 assert_eq!(
9961 run.config.graph.implementers, 2,
9962 "history must not be rewritten"
9963 );
9964 }
9965 t.solo = false;
9966 t.overrides = None;
9967 assert!(implementers_match(&t, &run));
9968 }
9969
9970 #[test]
9971 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9972 let mut solo_cfg = Config::default();
9978 solo_cfg.graph.implementers = 3;
9979 let mut solo_task = task();
9980 solo_task.solo = true;
9981 apply_task_implementers(&mut solo_cfg, &solo_task);
9982 assert_eq!(solo_cfg.graph.implementers, 1);
9983
9984 let mut plain_cfg = Config::default();
9985 plain_cfg.graph.implementers = 3;
9986 let plain_task = task();
9987 assert!(!plain_task.solo);
9988 apply_task_implementers(&mut plain_cfg, &plain_task);
9989 assert_eq!(
9990 plain_cfg.graph.implementers, 3,
9991 "a task that did not ask to run alone keeps the config's candidates"
9992 );
9993 }
9994
9995 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9996 QuotaLoss {
9997 cause: crate::agent::QuotaCause::UsageLimit,
9998 agent: String::new(),
9999 seat: seat.into(),
10000 node: "judge".into(),
10001 at: at.parse().unwrap(),
10002 reset: reset.map(str::to_string),
10003 }
10004 }
10005
10006 #[test]
10007 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10008 let now = Timestamp::now();
10009 for reset in [None, Some("in 1h")] {
10010 let auth = crate::agent::Quota {
10011 cause: crate::agent::QuotaCause::Authentication,
10012 agent: "alpha".into(),
10013 reset: reset.map(str::to_owned),
10014 };
10015 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10016 assert_eq!(cooldown_until(&[loss], now), None);
10017 }
10018 }
10019
10020 #[test]
10021 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10022 let old: Vec<QuotaLoss> = (1..=4)
10023 .map(|i| {
10024 loss(
10025 &format!("judge-{i}"),
10026 "2026-09-23T05:23:00Z",
10027 Some("2:40pm (Asia/Tokyo)"),
10028 )
10029 })
10030 .collect();
10031 let fresh = losses_this_attempt(&old, &old);
10032 assert!(fresh.is_empty());
10033 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10034 }
10036
10037 #[test]
10038 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10039 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10040 let now = Timestamp::now();
10041 let mut after = old.clone();
10042 after.push(loss("judge-2", &now.to_string(), None));
10043 let fresh = losses_this_attempt(&old, &after);
10044 assert_eq!(fresh, vec![after[1].clone()]);
10045 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10046 assert_eq!(
10047 until,
10048 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10049 );
10050 }
10051
10052 #[test]
10053 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10054 let before = vec![
10057 loss("judge-1", "2026-09-23T05:23:00Z", None),
10058 loss("judge-2", "2026-09-23T05:24:00Z", None),
10059 ];
10060 let after = vec![
10061 loss("judge-2", "2026-09-23T05:24:00Z", None),
10062 loss("judge-1", "2026-09-24T01:00:00Z", None),
10063 ];
10064 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10065 }
10066
10067 #[test]
10068 fn merge_overrides_are_parsed_or_refused() {
10069 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10070 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10071 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10072 assert!(merge_mode("squash").is_err());
10073 }
10074
10075 #[test]
10076 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10077 let now = Timestamp::now();
10078 let fallback = Duration::from_secs(300);
10079 let cap = Duration::from_secs(1800);
10080
10081 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10083
10084 let soon = now + jiff::SignedDuration::from_secs(600);
10086 assert_eq!(
10087 quota_wait(Some(soon), now, fallback, cap),
10088 Duration::from_secs(600)
10089 );
10090
10091 let past = now - jiff::SignedDuration::from_secs(60);
10094 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10095
10096 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10099 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10100 }
10101
10102 #[test]
10103 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10104 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10105
10106 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10107 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10108
10109 let already_past =
10113 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10114 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10115
10116 assert!(
10117 parse_reset_hint("session limit reached", now, now).is_none(),
10118 "free text with no recognised shape is not guessed at"
10119 );
10120 assert!(
10121 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10122 "an unresolvable zone name is not guessed at either"
10123 );
10124 }
10125
10126 #[test]
10127 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10128 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10129
10130 let at = parse_reset_hint(
10131 "You've hit your usage limit. Visit \
10132 https://chatgpt.com/codex/settings/usage to purchase more \
10133 credits or try again at Sep 19th, 2026 5:10 PM.",
10134 now,
10135 now,
10136 )
10137 .expect("the codex reset wording is a recognised shape");
10138 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10139
10140 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10145 .expect("an explicit year needs no rollover");
10146 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10147
10148 assert!(
10149 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10150 "a two-digit year is not the documented shape and is not guessed at"
10151 );
10152 assert!(
10153 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10154 "a four-letter month name is not the documented three-letter abbreviation"
10155 );
10156 assert!(
10157 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10158 "an explicit zone on the dated shape is a format nobody has \
10159 documented, and is refused rather than guessed at as UTC"
10160 );
10161 }
10162
10163 #[test]
10164 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10165 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10166 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10167
10168 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10169 assert_eq!(at.as_second() - recorded.as_second(), 3769);
10170
10171 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10172 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10173
10174 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10175 assert!(
10176 parse_reset_hint(bad, now, recorded).is_none(),
10177 "{bad:?} must not be guessed at"
10178 );
10179 }
10180 }
10181
10182 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10186 let config = dir.join("magi.toml");
10187 std::fs::write(
10188 &config,
10189 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10190 )
10191 .unwrap();
10192 let opts = Opts {
10193 poll: Duration::from_secs(30),
10194 config: Some(config),
10195 repo: dir.join("repo"),
10199 ..Opts::default()
10200 };
10201 let home = dir.join("home");
10210 let stamps = home.join("service-ticks");
10213 std::fs::create_dir_all(&stamps).unwrap();
10214 for service in ["waiter", "deputies", "release-watch"] {
10215 std::fs::write(
10216 stamps.join(service),
10217 Timestamp::now().as_second().to_string(),
10218 )
10219 .unwrap();
10220 }
10221 for operation in [
10222 "conductor",
10223 "maintenance",
10224 "housekeeping",
10225 "disk-pressure",
10226 "cache",
10227 "fetch",
10228 ] {
10229 std::fs::write(
10230 stamps.join(format!("daemon-{operation}")),
10231 serde_json::to_vec(&Timestamp::now()).unwrap(),
10232 )
10233 .unwrap();
10234 }
10235 let worktrees = dir.join("wt");
10236 (
10237 opts,
10238 Queue::at(dir.join("queue")),
10239 home.join("daemon.json"),
10240 home,
10241 worktrees,
10242 )
10243 }
10244
10245 #[test]
10246 fn a_stop_is_idempotent_and_once_set_stays_set() {
10247 let stop = Stop::new();
10248 assert!(!stop.stopped());
10249
10250 stop.stop();
10251 assert!(stop.stopped());
10252 stop.stop();
10253 assert!(stop.stopped(), "a second stop is not a toggle");
10254
10255 let shared = stop.clone();
10256 assert!(
10257 shared.stopped(),
10258 "a clone is the same stop; that is how the loop and its caller share one"
10259 );
10260 }
10261
10262 #[tokio::test]
10263 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10264 for operation in ["conductor", "maintenance", "housekeeping"] {
10265 let dir = tempfile::tempdir().unwrap();
10266 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10267 opts.once = true;
10268 opts.poll = Duration::from_millis(1);
10269 let mut task = task();
10270 task.runs.push("fixture-run".into());
10271 queue.put(&mut task).unwrap();
10272 let claim = queue.claim(&task.id).unwrap();
10273
10274 let directory = home.join("workers/jobs/abcdef");
10277 std::fs::create_dir_all(&directory).unwrap();
10278 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10279 crate::pr_head::try_lock_file(&lease).unwrap();
10280 let mut job = crate::worker::Job {
10281 id: "abcdef".into(),
10282 sequence: 1,
10283 kind: "daemon-service".into(),
10284 key: format!("service:daemon-{operation}"),
10285 payload: serde_json::Value::Null,
10286 generation: "fixture".into(),
10287 version: None,
10288 status: crate::worker::Status::Running,
10289 result: None,
10290 pid: Some(std::process::id()),
10291 created_at: Timestamp::now().as_second() as u64,
10292 finished_at: None,
10293 };
10294 let record = directory.join("job.json");
10295 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10296
10297 let status = Arc::new(Mutex::new(Status::new()));
10298 let stop = Stop::new();
10299 let mut drain = Box::pin(poll(
10300 &opts,
10301 &queue,
10302 &status,
10303 &home,
10304 &worktrees,
10305 &stop,
10306 DispatchLimits {
10307 max_concurrent: 1,
10308 pause_for_interrupts: false,
10309 recovery_cfg: None,
10310 },
10311 ));
10312 std::future::poll_fn(|cx| {
10313 use std::future::Future;
10314 assert!(
10315 drain.as_mut().poll(cx).is_pending(),
10316 "--once must wait for {operation} to release its queue claim"
10317 );
10318 std::task::Poll::Ready(())
10319 })
10320 .await;
10321 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10322
10323 let questions = Questions::at(home.join("questions"));
10326 let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10327 questions.put(&mut q).unwrap();
10328 drop(claim);
10329 let expired =
10333 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10334 for service in [operation, "housekeeping"] {
10335 std::fs::write(
10336 home.join("service-ticks").join(format!("daemon-{service}")),
10337 &expired,
10338 )
10339 .unwrap();
10340 }
10341 job.status = crate::worker::Status::Finished;
10342 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10343 drop(lease);
10344 tokio::time::timeout(Duration::from_secs(2), drain)
10345 .await
10346 .expect("the settled service must allow the drain to finish")
10347 .unwrap();
10348 let after = queue.get(&task.id).unwrap();
10349 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10350 assert!(after.action_applied(&q.id));
10351 for service in [operation, "housekeeping"] {
10352 assert_eq!(
10353 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10354 .unwrap(),
10355 expired,
10356 "the final once rescan must not restart {service}"
10357 );
10358 }
10359 }
10360 }
10361
10362 #[test]
10363 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10364 let stop = Stop::new();
10365 stop.busy.store(1, Ordering::SeqCst);
10366 assert!(
10367 !stop.finishing(),
10368 "a busy loop nobody has asked to stop is just running"
10369 );
10370
10371 stop.stop();
10372 assert!(
10373 stop.finishing(),
10374 "a stop asked for mid-run has not landed until the run is settled"
10375 );
10376
10377 stop.busy.store(0, Ordering::SeqCst);
10378 assert!(
10379 !stop.finishing(),
10380 "once the run is settled the stop has landed and there is nothing to finish"
10381 );
10382 }
10383
10384 #[test]
10385 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10386 let stop = Stop::new();
10387 stop.busy.store(2, Ordering::SeqCst);
10388 stop.stop();
10389 assert!(stop.finishing(), "two runs still in flight");
10390
10391 stop.busy.store(1, Ordering::SeqCst);
10392 assert!(
10393 stop.finishing(),
10394 "one run finished, but a sibling is still working"
10395 );
10396
10397 stop.busy.store(0, Ordering::SeqCst);
10398 assert!(
10399 !stop.finishing(),
10400 "the last run out is what actually lands the stop"
10401 );
10402 }
10403
10404 #[tokio::test]
10405 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10406 let dir = tempfile::tempdir().unwrap();
10407 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10408 let stop = Stop::new();
10409 stop.stop();
10410
10411 let began = std::time::Instant::now();
10412 tokio::time::timeout(
10413 Duration::from_secs(2),
10414 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10415 )
10416 .await
10417 .expect("a stopped loop must return, not sit out its poll interval")
10418 .expect("the loop's own setup and teardown must not fail");
10419 assert!(
10420 began.elapsed() < opts.poll,
10421 "returned only after {:?}, which is a poll interval, not a stop",
10422 began.elapsed()
10423 );
10424 }
10425
10426 #[tokio::test]
10427 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10428 let dir = tempfile::tempdir().unwrap();
10429 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10430 let stop = Stop::new();
10431
10432 let asker = {
10435 let stop = stop.clone();
10436 tokio::spawn(async move {
10437 tokio::time::sleep(Duration::from_millis(20)).await;
10438 stop.stop();
10439 })
10440 };
10441
10442 let began = std::time::Instant::now();
10443 tokio::time::timeout(
10444 Duration::from_secs(2),
10445 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10446 )
10447 .await
10448 .expect("a stop asked for while idle must wake the wait")
10449 .expect("the loop's own setup and teardown must not fail");
10450 asker.await.unwrap();
10451 assert!(
10452 began.elapsed() < opts.poll,
10453 "returned only after {:?}, so the stop waited on the sleep",
10454 began.elapsed()
10455 );
10456 }
10457
10458 #[tokio::test]
10459 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10460 let dir = tempfile::tempdir().unwrap();
10461 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10462 let stop = Stop::new();
10463 stop.stop();
10464
10465 tokio::time::timeout(
10466 Duration::from_secs(2),
10467 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10468 )
10469 .await
10470 .expect("a stopped loop must return")
10471 .expect("the loop's own setup and teardown must not fail");
10472
10473 assert!(
10474 home.is_dir(),
10475 "the loop did publish a status file, so its removal is the teardown and not an absence"
10476 );
10477 assert!(
10478 !status_file.exists(),
10479 "a stopped loop clears its status file"
10480 );
10481 assert!(
10482 read_status(&home).is_none(),
10483 "a reader must see no daemon at all, not a heartbeat that merely stopped"
10484 );
10485 }
10486
10487 #[tokio::test]
10488 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10489 let dir = tempfile::tempdir().unwrap();
10490 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10491
10492 let mut settled = RunState::new(
10493 dir.path().join("repo"),
10494 "main".to_owned(),
10495 "abc1234".to_owned(),
10496 "fixture".to_owned(),
10497 Config::default(),
10498 );
10499 settled.status = RunStatus::Ready;
10500 let run_dir = home.join("runs").join(&settled.id);
10501 std::fs::create_dir_all(&run_dir).unwrap();
10502 std::fs::write(
10503 run_dir.join("run.json"),
10504 serde_json::to_string_pretty(&settled).unwrap(),
10505 )
10506 .unwrap();
10507 let questions = Questions::at(home.join("questions"));
10508 let mut question = ask::Question::new(
10509 settled.id.clone(),
10510 "review".to_owned(),
10511 "reviewer-1".to_owned(),
10512 "Continue?".to_owned(),
10513 String::new(),
10514 Vec::new(),
10515 );
10516 questions.put(&mut question).unwrap();
10517
10518 run_service_worker(
10519 &home,
10520 serde_json::to_value(ServiceWorker {
10521 opts,
10522 queue: queue.root().to_path_buf(),
10523 worktrees_root: worktrees,
10524 operation: "housekeeping".to_owned(),
10525 })
10526 .unwrap(),
10527 )
10528 .await
10529 .unwrap();
10530
10531 assert_eq!(
10532 questions.get(&question.id).unwrap().status,
10533 ask::QuestionStatus::Abandoned,
10534 "the independent housekeeping worker settles ended-run questions"
10535 );
10536 }
10537
10538 #[test]
10539 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10540 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10541
10542 assert!(
10543 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10544 "never checked before: due at once"
10545 );
10546
10547 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10548 assert!(
10549 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10550 "well inside the interval: not due yet"
10551 );
10552
10553 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10554 assert!(
10555 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10556 "exactly at the edge: not yet due, same convention as `clean::due`"
10557 );
10558
10559 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10560 assert!(
10561 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10562 "past the interval: due again"
10563 );
10564 }
10565
10566 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10571 let config = dir.join("magi.toml");
10572 std::fs::write(
10578 &config,
10579 format!(
10580 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10581 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10582 cache_dir.display()
10583 ),
10584 )
10585 .unwrap();
10586 Opts {
10587 config: Some(config),
10588 repo: dir.join("repo"),
10589 ..Opts::default()
10590 }
10591 }
10592
10593 #[tokio::test]
10594 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10595 let dir = tempfile::tempdir().unwrap();
10596 let home = dir.path().join("home");
10597 let cache_dir = dir.path().join("cache");
10598 std::fs::create_dir_all(&cache_dir).unwrap();
10599 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10600 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10601
10602 let running = Stop::new();
10605 let mut last_checked = None;
10606 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10607 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10608 .await;
10609 assert_eq!(
10610 crate::disk::dir_size(&cache_dir),
10611 0,
10612 "over the cap on the first check ever: pruned at once, no idle queue required"
10613 );
10614 assert_eq!(last_checked, Some(t0));
10615
10616 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10618 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10619 maybe_prune_cache_between_runs(
10620 &opts.repo,
10621 &opts,
10622 &home,
10623 &running,
10624 &mut last_checked,
10625 too_soon,
10626 )
10627 .await;
10628 assert_eq!(
10629 crate::disk::dir_size(&cache_dir),
10630 10,
10631 "too soon since the last check: left alone rather than rescanned every call"
10632 );
10633 assert_eq!(
10634 last_checked,
10635 Some(t0),
10636 "an idle check does not reset the clock"
10637 );
10638
10639 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10641 maybe_prune_cache_between_runs(
10642 &opts.repo,
10643 &opts,
10644 &home,
10645 &running,
10646 &mut last_checked,
10647 due_again,
10648 )
10649 .await;
10650 assert_eq!(
10651 crate::disk::dir_size(&cache_dir),
10652 0,
10653 "due again: pruned back under the cap"
10654 );
10655 }
10656
10657 #[tokio::test]
10665 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10666 let dir = tempfile::tempdir().unwrap();
10667 let home = dir.path().join("home");
10668 let cache_dir = dir.path().join("cache");
10669 std::fs::create_dir_all(&cache_dir).unwrap();
10670 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10671 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10672
10673 let stop = Stop::new();
10674 stop.stop();
10675 assert!(
10676 !stop.finishing(),
10677 "no run is in flight at a between-runs boundary, so nothing else \
10678 would tell the operator this stop had not taken effect yet"
10679 );
10680
10681 let mut last_checked = None;
10682 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10683 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10684 .await;
10685 assert_eq!(
10686 crate::disk::dir_size(&cache_dir),
10687 10,
10688 "over its cap, and due for the first check ever, but a stop outranks \
10689 it: the cap is a standing policy the next start measures again"
10690 );
10691 assert_eq!(
10692 last_checked, None,
10693 "a check that never happened must not claim the interval"
10694 );
10695 }
10696
10697 #[tokio::test]
10700 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10701 let dir = tempfile::tempdir().unwrap();
10702 let cache_dir = dir.path().join("cache");
10703 std::fs::create_dir_all(&cache_dir).unwrap();
10704 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10705
10706 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10707 opts.poll = Duration::from_millis(20);
10708 opts.max_attempts = 1_000;
10709
10710 let queue = Queue::at(dir.path().join("queue"));
10711 for i in 0..128 {
10712 let mut task = Task::new(
10713 format!("queued work {i}"),
10714 format!("queued work {i}"),
10715 opts.repo.clone(),
10716 Source::Human,
10717 );
10718 queue.put(&mut task).unwrap();
10719 }
10720
10721 let home = dir.path().join("home");
10722 let worktrees = dir.path().join("wt");
10723 run_service_worker(
10724 &home,
10725 serde_json::to_value(ServiceWorker {
10726 opts,
10727 queue: queue.root().to_path_buf(),
10728 worktrees_root: worktrees,
10729 operation: "cache".to_owned(),
10730 })
10731 .unwrap(),
10732 )
10733 .await
10734 .unwrap();
10735 let after = queue.list();
10736 assert_eq!(after.len(), 128);
10737 assert!(
10738 after
10739 .iter()
10740 .all(|task| task.status.runnable() && task.attempts == 0)
10741 );
10742
10743 assert_eq!(
10744 crate::disk::dir_size(&cache_dir),
10745 0,
10746 "an oversized cache must not be left to grow unboundedly just because the \
10747 queue kept the loop busy the whole time"
10748 );
10749 }
10750
10751 #[test]
10752 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10753 let dir = tempfile::tempdir().unwrap();
10754 let queue = Queue::at(dir.path().join("queue"));
10755 let questions = Questions::at(dir.path().join("questions"));
10756 let mut task = task();
10757 queue.put(&mut task).unwrap();
10758
10759 let mut task_question = ask::Question::new(
10760 task.id.clone(),
10761 crate::conduct::NODE.to_owned(),
10762 "conduct".to_owned(),
10763 "Which backend?".to_owned(),
10764 String::new(),
10765 Vec::new(),
10766 );
10767 questions.put(&mut task_question).unwrap();
10768 task.block(vec![task_question.id.clone()], None);
10769 queue.put(&mut task).unwrap();
10770
10771 let mut run_question = ask::Question::new(
10772 "20260101-000000-run1".to_owned(),
10773 "review".to_owned(),
10774 "reviewer-1".to_owned(),
10775 "Run question".to_owned(),
10776 String::new(),
10777 Vec::new(),
10778 );
10779 questions.put(&mut run_question).unwrap();
10780
10781 let mut coincidental = ask::Question::new(
10786 task.id.clone(),
10787 "review".to_owned(),
10788 "reviewer-1".to_owned(),
10789 "Unrelated review question".to_owned(),
10790 String::new(),
10791 Vec::new(),
10792 );
10793 questions.put(&mut coincidental).unwrap();
10794
10795 reconcile_task_questions(&queue, &questions);
10796 assert!(questions.get(&task_question.id).unwrap().status.open());
10797 assert!(questions.get(&run_question.id).unwrap().status.open());
10798 assert!(questions.get(&coincidental.id).unwrap().status.open());
10799
10800 task.release();
10801 queue.put(&mut task).unwrap();
10802 reconcile_task_questions(&queue, &questions);
10803 assert_eq!(
10804 questions.get(&task_question.id).unwrap().status,
10805 ask::QuestionStatus::Abandoned
10806 );
10807 assert!(
10808 questions.get(&run_question.id).unwrap().status.open(),
10809 "run questions remain the run janitor's responsibility"
10810 );
10811 assert!(
10812 questions.get(&coincidental.id).unwrap().status.open(),
10813 "a non-conductor question must not be abandoned just because its \
10814 run id coincides with a task id"
10815 );
10816 }
10817
10818 #[test]
10819 fn a_freshly_started_running_task_is_never_stalled() {
10820 let dir = tempfile::tempdir().unwrap();
10821 let mut t = task();
10822 t.start("run-1".to_owned());
10823 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10826 }
10827
10828 #[test]
10829 fn a_long_running_task_with_no_live_daemon_is_stalled() {
10830 let dir = tempfile::tempdir().unwrap();
10831 let mut t = task();
10832 t.start("run-1".to_owned());
10833 t.updated_at = Timestamp::now()
10834 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10835 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10836 assert_eq!(
10837 stalled_tasks(
10838 &Queue::at(dir.path().join("q")),
10839 dir.path(),
10840 Timestamp::now()
10841 )
10842 .len(),
10843 0,
10844 "the task was never written to this queue"
10845 );
10846 }
10847
10848 #[test]
10849 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10850 let dir = tempfile::tempdir().unwrap();
10851 let mut t = task();
10852 t.id = "20260903-080340-0167".to_owned();
10853 t.start("20260903-080619-01c2".to_owned());
10854 t.updated_at = Timestamp::now()
10855 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10856
10857 let mut status = Status::new();
10858 status.current = vec![Current {
10859 worker: None,
10860 task: t.id.clone(),
10861 run: "20260903-080619-01c2".to_owned(),
10862 }];
10863 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10864
10865 assert!(
10866 !is_stalled(&t, dir.path(), Timestamp::now()),
10867 "a live daemon's own heartbeat rules out stalled, however long the task has run"
10868 );
10869 }
10870
10871 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10875 let path = queue.path_of(id);
10876 let body = std::fs::read_to_string(&path).unwrap();
10877 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10878 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10879 v["updated_at"] = serde_json::Value::String(old.to_string());
10880 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10881 }
10882
10883 #[test]
10884 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10885 let dir = tempfile::tempdir().unwrap();
10898 let queue = Queue::at(dir.path().join("queue"));
10899 let home = dir.path().join("home");
10900
10901 let mut t = task();
10902 t.id = "20260101-000001-lock".to_owned();
10903 t.start("run-1".to_owned());
10904 queue.put(&mut t).unwrap();
10905 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10906 std::fs::write(
10907 dir.path().join("queue").join(format!("{}.lock", t.id)),
10908 "not a pid",
10909 )
10910 .unwrap();
10911
10912 let now = Timestamp::now();
10913 assert!(
10914 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10915 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10916 and reclaim must leave the task alone"
10917 );
10918 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10919
10920 let stalled = stalled_tasks(&queue, &home, now);
10921 assert_eq!(
10922 stalled.len(),
10923 1,
10924 "reclaim's inability to claim it yet must not hide it from the conductor"
10925 );
10926 assert_eq!(stalled[0].id, t.id);
10927 }
10928
10929 #[test]
10930 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10931 let dir = tempfile::tempdir().unwrap();
10932 crate::run::set_home(dir.path().join("run-home"));
10933 let queue = Queue::at(dir.path().join("queue"));
10934 let home = dir.path().join("home");
10935 let questions = Questions::at(dir.path().join("questions"));
10936
10937 let mut t = task();
10938 t.id = "20260101-000003-dead".to_owned();
10939 t.start("missing-run".to_owned());
10940 queue.put(&mut t).unwrap();
10941 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10942
10943 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10946 assert_eq!(
10947 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10948 [&t.id]
10949 );
10950 assert_eq!(
10951 reclaim_orphaned_running(&queue, 2, &Default::default()),
10952 [t.id.clone()]
10953 );
10954 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10955
10956 crate::conduct::apply(
10959 &queue,
10960 &questions,
10961 &crate::conduct::Verdict {
10962 decisions: vec![crate::conduct::Decision {
10963 id: t.id.clone(),
10964 recovery: Some(crate::conduct::Recovery::Requeue),
10965 ..crate::conduct::Decision::default()
10966 }],
10967 },
10968 )
10969 .unwrap();
10970 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10971 }
10972
10973 #[test]
10974 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10975 let dir = tempfile::tempdir().unwrap();
10976 let queue = Queue::at(dir.path().join("queue"));
10977 let home = dir.path().join("home");
10978
10979 let mut fresh = task();
10980 fresh.id = "20260101-000001-aaaa".to_owned();
10981 fresh.start("run-1".to_owned());
10982 queue.put(&mut fresh).unwrap();
10983
10984 let mut old = task();
10985 old.id = "20260101-000002-bbbb".to_owned();
10986 old.start("run-2".to_owned());
10987 queue.put(&mut old).unwrap();
10988 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10989
10990 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10991 assert_eq!(stalled.len(), 1);
10992 assert_eq!(stalled[0].id, old.id);
10993 }
10994
10995 #[test]
10996 fn queued_and_finished_task_views_partition_by_status() {
10997 let dir = tempfile::tempdir().unwrap();
10998 let queue = Queue::at(dir.path().join("queue"));
10999
11000 let mut queued = task();
11001 queued.id = "20260101-000001-aaaa".to_owned();
11002 queue.put(&mut queued).unwrap();
11003
11004 let mut failed = task();
11005 failed.id = "20260101-000002-bbbb".to_owned();
11006 failed.start("run-1".to_owned());
11007 failed.fail("gate red", 5);
11008 queue.put(&mut failed).unwrap();
11009
11010 let mut held = task();
11011 held.id = "20260101-000003-cccc".to_owned();
11012 held.hold_machine(None);
11013 queue.put(&mut held).unwrap();
11014
11015 let mut running = task();
11016 running.id = "20260101-000004-dddd".to_owned();
11017 running.start("run-2".to_owned());
11018 queue.put(&mut running).unwrap();
11019
11020 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11021 assert_eq!(queued_ids, [queued.id.clone()]);
11022
11023 let mut finished_ids: Vec<String> =
11024 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11025 finished_ids.sort_unstable();
11026 let mut want = vec![failed.id.clone(), held.id.clone()];
11027 want.sort_unstable();
11028 assert_eq!(finished_ids, want);
11029 }
11030
11031 #[test]
11032 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11033 for short in [false, true] {
11034 let dir = tempfile::tempdir().unwrap();
11035 let queue = Queue::at(dir.path().join("queue"));
11036 let questions = ask::Questions::at(dir.path().join("questions"));
11037 let mut running = task();
11038 running.id = "20261013-192213-feb2".into();
11039 running.start("existing-run".into());
11040 queue.put(&mut running).unwrap();
11041 let mut middle = task();
11042 middle.id = "20261013-193611-ca5b".into();
11043 middle.block(
11044 vec![if short {
11045 "feb2".into()
11046 } else {
11047 running.id.clone()
11048 }],
11049 None,
11050 );
11051 queue.put(&mut middle).unwrap();
11052 let mut waiting = task();
11053 waiting.id = "20261013-202849-ee37".into();
11054 waiting.block(
11055 vec![if short {
11056 "ca5b".into()
11057 } else {
11058 middle.id.clone()
11059 }],
11060 Some("wait for implementation".into()),
11061 );
11062 queue.put(&mut waiting).unwrap();
11063 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11064 let inv = crate::blockers::Inventory::load(&queue, &questions);
11065 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11066 assert!(inv.stuck().is_empty());
11067 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11068 assert!(report.quarantined.is_empty());
11069 assert!(report.asked.is_empty());
11070 resolve_blockers(&queue, &questions);
11071 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11072 assert!(questions.list().is_empty());
11073 running.succeed();
11076 queue.put(&mut running).unwrap();
11077 resolve_blockers(&queue, &questions);
11078 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11079 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11080 middle = queue.get(&middle.id).unwrap();
11081 middle.succeed();
11082 queue.put(&mut middle).unwrap();
11083 resolve_blockers(&queue, &questions);
11084 let after = queue.get(&waiting.id).unwrap();
11085 assert_eq!(after.status, TaskStatus::Queued);
11086 assert!(after.blocked_by.is_empty());
11087 assert_eq!(after.instruction, waiting.instruction);
11088 }
11089 }
11090
11091 #[test]
11092 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11093 for future_schema in [false, true] {
11094 let name = "20261013-193611-ca5b";
11095 let mut future = task();
11096 future.id = name.into();
11097 future.schema = crate::queue::SCHEMA + 1;
11098 let contents = if future_schema {
11099 serde_json::to_string(&future).unwrap()
11100 } else {
11101 "corrupt".into()
11102 };
11103 let dir = tempfile::tempdir().unwrap();
11104 let queue = Queue::at(dir.path().join("queue"));
11105 let questions = ask::Questions::at(dir.path().join("questions"));
11106 let mut waiting = task();
11107 waiting.id = "20261013-202849-ee37".into();
11108 waiting.block(vec!["ca5b".into()], None);
11109 queue.put(&mut waiting).unwrap();
11110 std::fs::write(queue.path_of(name), contents).unwrap();
11111 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11112 assert!(
11113 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11114 );
11115 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11116 assert!(report.asked.is_empty());
11117 resolve_blockers(&queue, &questions);
11118 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11119 assert!(questions.list().is_empty());
11120 }
11121 let dir = tempfile::tempdir().unwrap();
11122 let queue = Queue::at(dir.path().join("queue"));
11123 let questions = ask::Questions::at(dir.path().join("questions"));
11124 let mut waiting = task();
11125 waiting.id = "20261013-202849-ee37".into();
11126 waiting.block(vec!["ca5b".into()], None);
11127 queue.put(&mut waiting).unwrap();
11128 let mut done = task();
11129 done.id = "20261013-193611-ca5b".into();
11130 done.succeed();
11131 queue.put(&mut done).unwrap();
11132 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11135 assert!(queue.get("ca5b").is_err());
11136 assert_eq!(
11137 crate::queue::dependency(&queue, &questions, "ca5b"),
11138 crate::queue::Dependency::Ambiguous
11139 );
11140 resolve_blockers(&queue, &questions);
11141 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11142 assert!(report.asked.is_empty());
11143 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11144 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11145 }
11146
11147 #[test]
11148 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11149 for held in [false, true] {
11150 for question in [false, true] {
11151 for reference in ["ca5b", "20261013-193611-ca5b"] {
11152 let dir = tempfile::tempdir().unwrap();
11153 let queue = Queue::at(dir.path().join("queue"));
11154 let questions = ask::Questions::at(dir.path().join("questions"));
11155 let mut prerequisite = task();
11156 prerequisite.id = "20261013-193611-ca5b".into();
11157 prerequisite.start("existing-run".into());
11158 queue.put(&mut prerequisite).unwrap();
11159 let mut waiting = task();
11160 waiting.id = "20261013-202849-ee37".into();
11161 if held {
11162 waiting.hold_machine(Some("waiting for separate consent".into()));
11163 }
11164 queue.put(&mut waiting).unwrap();
11165 let reason = "Deleting saved data requires separate owner consent";
11166 crate::conduct::apply(
11167 &queue,
11168 &questions,
11169 &crate::conduct::Verdict {
11170 decisions: vec![crate::conduct::Decision {
11171 id: waiting.id.clone(),
11172 blocked_by: vec![reference.into()],
11173 question: question.then(|| "May the saved data be deleted?".into()),
11174 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11175 reason: Some(reason.into()),
11176 ..crate::conduct::Decision::default()
11177 }],
11178 },
11179 )
11180 .unwrap();
11181 let before = queue.get(&waiting.id).unwrap();
11182 if question {
11183 assert_eq!(before.status, TaskStatus::Blocked);
11184 let q = questions.get(&before.blocked_by[0]).unwrap();
11185 assert_eq!(q.summary, "May the saved data be deleted?");
11186 assert!(q.status.open());
11187 } else {
11188 assert_eq!(before.status, TaskStatus::Held);
11189 let recorded_reason = before.hold_reason.as_deref().unwrap();
11190 assert!(recorded_reason.starts_with(reason));
11191 if held {
11192 assert!(recorded_reason.contains("waiting for separate consent"));
11193 }
11194 }
11195 prerequisite.succeed();
11196 queue.put(&mut prerequisite).unwrap();
11197 resolve_blockers(&queue, &questions);
11198 let after = queue.get(&waiting.id).unwrap();
11199 assert_eq!(after.status, before.status);
11200 assert_eq!(after.blocked_by, before.blocked_by);
11201 assert_eq!(after.hold_reason, before.hold_reason);
11202 assert_eq!(after.instruction, waiting.instruction);
11203 if question {
11204 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11205 }
11206 assert!(
11207 queue.next_runnable().is_none(),
11208 "dependency completion is not consent"
11209 );
11210 }
11211 }
11212 }
11213 }
11214
11215 #[test]
11216 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11217 let dir = tempfile::tempdir().unwrap();
11218 let queue = Queue::at(dir.path().join("queue"));
11219 let questions = ask::Questions::at(dir.path().join("questions"));
11220
11221 let mut dep = task();
11222 dep.id = "20260101-000001-dep0".to_owned();
11223 dep.succeed();
11224 queue.put(&mut dep).unwrap();
11225
11226 let mut still_going = task();
11227 still_going.id = "20260101-000002-dep1".to_owned();
11228 queue.put(&mut still_going).unwrap();
11229
11230 let mut blocked = task();
11231 blocked.id = "20260101-000003-main".to_owned();
11232 blocked.block(
11233 vec![dep.id.clone(), still_going.id.clone()],
11234 Some("waits on both".to_owned()),
11235 );
11236 queue.put(&mut blocked).unwrap();
11237
11238 resolve_blockers(&queue, &questions);
11239
11240 let after = queue.get(&blocked.id).unwrap();
11241 assert_eq!(
11242 after.status,
11243 TaskStatus::Blocked,
11244 "one dependency is still outstanding"
11245 );
11246 assert_eq!(after.blocked_by, [still_going.id.clone()]);
11247 }
11248
11249 #[test]
11250 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11251 let dir = tempfile::tempdir().unwrap();
11252 let queue = Queue::at(dir.path().join("queue"));
11253 let questions = ask::Questions::at(dir.path().join("questions"));
11254
11255 let mut q = crate::ask::Question::new(
11256 "20260101-000001-main".to_owned(),
11257 crate::conduct::NODE.to_owned(),
11258 "conduct".to_owned(),
11259 "Which backend?".to_owned(),
11260 String::new(),
11261 Vec::new(),
11262 );
11263 questions.put(&mut q).unwrap();
11264 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11265 .unwrap();
11266 questions.put(&mut q).unwrap();
11267
11268 let mut blocked = task();
11269 blocked.id = "20260101-000001-main".to_owned();
11270 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11271 queue.put(&mut blocked).unwrap();
11272
11273 resolve_blockers(&queue, &questions);
11274
11275 let after = queue.get(&blocked.id).unwrap();
11276 assert_eq!(
11277 after.status,
11278 TaskStatus::Queued,
11279 "the only blocker resolved"
11280 );
11281 assert_eq!(after.answers.len(), 1);
11282 assert_eq!(after.answers[0].question, "Which backend?");
11283 assert_eq!(after.answers[0].answer, "SQLite");
11284
11285 let instruction = instruction_for(&after);
11287 assert!(instruction.contains("Which backend?"));
11288 assert!(instruction.contains("SQLite"));
11289 }
11290
11291 #[test]
11292 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11293 let dir = tempfile::tempdir().unwrap();
11294 let queue = Queue::at(dir.path().join("queue"));
11295 let questions = ask::Questions::at(dir.path().join("questions"));
11296
11297 let mut q = crate::ask::Question::new(
11298 "20260101-000001-main".to_owned(),
11299 crate::conduct::NODE.to_owned(),
11300 "conduct".to_owned(),
11301 "Is the setup done?".to_owned(),
11302 String::new(),
11303 Vec::new(),
11304 );
11305 q.abandon("no answer within 60s of asking");
11306 questions.put(&mut q).unwrap();
11307
11308 let mut blocked = task();
11309 blocked.id = "20260101-000001-main".to_owned();
11310 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11311 queue.put(&mut blocked).unwrap();
11312
11313 resolve_blockers(&queue, &questions);
11314
11315 let after = queue.get(&blocked.id).unwrap();
11316 assert_eq!(
11317 after.status,
11318 TaskStatus::Held,
11319 "never left blocked on nothing"
11320 );
11321 assert!(!after.operator_held(), "a machine hold, for triage");
11322 assert!(
11323 after
11324 .hold_reason
11325 .as_deref()
11326 .unwrap_or_default()
11327 .contains("went unanswered")
11328 );
11329 }
11330
11331 #[test]
11332 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11333 let dir = tempfile::tempdir().unwrap();
11339 let queue = Queue::at(dir.path().join("queue"));
11340 let questions = ask::Questions::at(dir.path().join("questions"));
11341
11342 let mut q = crate::ask::Question::new(
11343 "20260101-000001-main".to_owned(),
11344 crate::conduct::NODE.to_owned(),
11345 "conduct".to_owned(),
11346 "How should this be handled?".to_owned(),
11347 String::new(),
11348 Vec::new(),
11349 );
11350 questions.put(&mut q).unwrap();
11351 q.answer(crate::ask::Answer::Text(
11352 "leave it held, a human will look at it later".to_owned(),
11353 ))
11354 .unwrap();
11355 questions.put(&mut q).unwrap();
11356
11357 let mut held = task();
11358 held.id = "20260101-000001-main".to_owned();
11359 held.hold_machine(Some("out of attempts".to_owned()));
11360 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11361 queue.put(&mut held).unwrap();
11362
11363 resolve_blockers(&queue, &questions);
11364
11365 let after = queue.get(&held.id).unwrap();
11366 assert_eq!(after.status, TaskStatus::Held);
11367 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11368 assert_eq!(
11369 after.answers[0].answer,
11370 "leave it held, a human will look at it later"
11371 );
11372 }
11373
11374 #[test]
11375 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11376 let dir = tempfile::tempdir().unwrap();
11377 let queue = Queue::at(dir.path().join("queue"));
11378 let questions = ask::Questions::at(dir.path().join("questions"));
11379 let mut dep = task();
11380 dep.id = "20260101-000001-gone".to_owned();
11381 queue.put(&mut dep).unwrap();
11382 let mut blocked = task();
11383 blocked.id = "20260101-000003-main".to_owned();
11384 blocked.block(vec![dep.id.clone()], None);
11385 queue.put(&mut blocked).unwrap();
11386
11387 let claim = queue.claim(&blocked.id).unwrap();
11389 queue.remove(&dep.id, false, &questions).unwrap();
11390 drop(claim);
11391 resolve_blockers(&queue, &questions);
11392
11393 let after = queue.get(&blocked.id).unwrap();
11394 assert_eq!(after.status, TaskStatus::Queued);
11395 assert!(after.blocked_by.is_empty());
11396 }
11397
11398 #[test]
11399 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11400 let dir = tempfile::tempdir().unwrap();
11406 let queue = Queue::at(dir.path().join("queue"));
11407 let questions = ask::Questions::at(dir.path().join("questions"));
11408
11409 let mut still_going = task();
11410 still_going.id = "20260101-000002-dep1".to_owned();
11411 queue.put(&mut still_going).unwrap();
11412
11413 let mut blocked = task();
11414 blocked.id = "20260101-000003-main".to_owned();
11415 blocked.block(
11416 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11417 Some("waits on both".to_owned()),
11418 );
11419 queue.put(&mut blocked).unwrap();
11420
11421 resolve_blockers(&queue, &questions);
11422
11423 let after = queue.get(&blocked.id).unwrap();
11424 assert_eq!(
11425 after.status,
11426 TaskStatus::Held,
11427 "a missing dependency must not leave the task blocked forever"
11428 );
11429 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11430 assert!(after.blocked_by.is_empty());
11431 let reason = after.hold_reason.as_deref().unwrap_or_default();
11432 assert!(
11433 reason.contains("20260101-000001-gone"),
11434 "the missing id must be named so an operator can tell what happened: {reason}"
11435 );
11436 assert!(
11437 reason.contains(&still_going.id),
11438 "the still-valid dependency must not silently vanish from the record: {reason}"
11439 );
11440 }
11441
11442 #[test]
11443 fn instruction_for_is_unchanged_without_any_answers() {
11444 let t = task();
11445 assert_eq!(instruction_for(&t), t.instruction);
11446 }
11447
11448 #[test]
11449 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11450 let dir = tempfile::tempdir().unwrap();
11451 let q = Queue::at(dir.path().join("queue"));
11452 let src = dir.path().join("shot.png");
11453 std::fs::write(&src, "x").unwrap();
11454 let mut t = task();
11455 q.attach(&mut t, &[src]).unwrap();
11456 let paths = task_attachments(&q, &t).unwrap();
11457 assert_eq!(paths.len(), 1);
11458 assert!(paths[0].is_absolute() && paths[0].is_file());
11459 std::fs::remove_file(&paths[0]).unwrap();
11460 let err = task_attachments(&q, &t).unwrap_err().to_string();
11461 assert!(err.contains("shot.png"), "{err}");
11462 }
11463
11464 #[tokio::test]
11465 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11466 let dir = tempfile::tempdir().unwrap();
11467 let queue_path = dir.path().join("queue");
11468 let queue = Queue::at(queue_path.clone());
11469 let mut t = task();
11470 t.source = Source::Agent {
11471 run: "originating-chat".into(),
11472 node: crate::queue::CHAT_NODE.into(),
11473 };
11474 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11475 stage: "config-fetch",
11476 target: "origin/main".into(),
11477 });
11478 record_config_failure(&mut t, &fetch);
11479 t.hold_machine(Some(format!("{fetch:#}")));
11480 let fetch_key = t.chat_notice_due().unwrap();
11481 t.chat_notices.push(fetch_key.clone());
11482 queue.put(&mut t).unwrap();
11483
11484 let queue = Queue::at(queue_path);
11485 let mut t = queue.get(&t.id).unwrap();
11486 let a = dir.path().join("a.toml");
11487 let b = dir.path().join("b.toml");
11488 for (path, text, new_cause) in [
11489 (&a, "[graph", true),
11490 (&a, "[verify", false),
11491 (&a, "[graph]\nimplementers = 'invalid-type'", true),
11492 (&b, "[graph]\nimplementers = 'invalid-type'", true),
11493 ] {
11494 t.release_operator("test", None);
11495 std::fs::write(path, text).unwrap();
11496 let error = Config::discover_fetched(dir.path(), Some(path))
11497 .await
11498 .unwrap_err();
11499 record_config_failure(&mut t, &error);
11500 t.hold_machine(Some(format!("{error:#}")));
11501 let due = t.chat_notice_due();
11502 assert_eq!(due.is_some(), new_cause, "{error:#}");
11503 if let Some(key) = due {
11504 assert_ne!(key, fetch_key);
11505 t.chat_notices.push(key);
11506 }
11507 }
11508 t.succeed();
11509 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11510 }
11511
11512 #[test]
11513 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11514 let dir = tempfile::tempdir().unwrap();
11515 let queue_path = dir.path().join("queue");
11516 let queue = Queue::at(queue_path.clone());
11517 let mut t = task();
11518 t.source = crate::queue::Source::Agent {
11519 run: "originating-chat".into(),
11520 node: crate::queue::CHAT_NODE.into(),
11521 };
11522 let a = dir.path().join("a.png");
11523 let b = dir.path().join("b.png");
11524 std::fs::write(&a, "a").unwrap();
11525 std::fs::write(&b, "b").unwrap();
11526 queue.attach(&mut t, &[a, b]).unwrap();
11527 let paths = task_attachments(&queue, &t).unwrap();
11528 for path in &paths {
11529 std::fs::remove_file(path).unwrap();
11530 }
11531 let missing = task_attachments(&queue, &t).unwrap_err();
11532 t.attempts += 1;
11533 let reason = missing.to_string();
11534 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11535 let first = t.chat_notice_due().expect("first attachment notice");
11536 t.chat_notices.push(first.clone());
11537 queue.put(&mut t).unwrap();
11538
11539 let queue = Queue::at(queue_path.clone());
11540 let mut t = queue.get(&t.id).unwrap();
11541 assert!(t.chat_notice_due().is_none(), "restart does not replay");
11542 t.release_operator("test", None);
11543 t.attempts += 1;
11544 let missing = task_attachments(&queue, &t).unwrap_err();
11545 t.fail_startup_target(
11546 "startup-attachments",
11547 missing.name,
11548 "same missing attachment with regenerated wording",
11549 1,
11550 );
11551 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11552
11553 std::fs::write(&paths[0], "restored").unwrap();
11554 t.release_operator("test", None);
11555 t.attempts += 1;
11556 let missing = task_attachments(&queue, &t).unwrap_err();
11557 let reason = missing.to_string();
11558 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11559 let second = t
11560 .chat_notice_due()
11561 .expect("different attachment must notify");
11562 assert_ne!(first, second);
11563 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11564 }
11565
11566 #[test]
11567 fn resumed_instruction_is_unchanged_without_any_answers() {
11568 let t = task();
11569 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11570 }
11571
11572 #[test]
11573 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11574 let mut t = task();
11575 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11576 let old = t.instruction.clone();
11580
11581 let refreshed = resumed_instruction(&old, &t);
11582 assert!(refreshed.starts_with(&old), "the original text is kept");
11583 assert!(refreshed.contains("Which backend?"));
11584 assert!(refreshed.contains("SQLite"));
11585 }
11586
11587 #[test]
11588 fn resumed_instruction_keeps_an_original_answers_heading() {
11589 let mut t = task();
11590 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11591 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11592
11593 let refreshed = resumed_instruction(&t.instruction, &t);
11594
11595 assert!(
11596 refreshed.starts_with(&t.instruction),
11597 "an answers heading in the original instruction is not the appended block"
11598 );
11599 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11600 assert!(refreshed.contains("Which backend?"));
11601 assert!(refreshed.contains("SQLite"));
11602
11603 let repeated = resumed_instruction(&refreshed, &t);
11604 assert_eq!(
11605 repeated, refreshed,
11606 "only the final appended block is refreshed"
11607 );
11608 }
11609
11610 #[test]
11611 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11612 let mut t = task();
11613 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11614
11615 let once = resumed_instruction(&t.instruction, &t);
11619 let twice = resumed_instruction(&once, &t);
11620 assert_eq!(once, twice);
11621 assert_eq!(once.matches("Which backend?").count(), 1);
11622
11623 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11625 let refreshed = resumed_instruction(&once, &t);
11626 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11627 assert!(refreshed.contains("Which backend?"));
11628 assert!(refreshed.contains("Which cache?"));
11629 }
11630
11631 #[test]
11632 fn prepare_instruction_covers_all_three_starters() {
11633 let mut t = task();
11634 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11635
11636 assert_eq!(
11639 prepare_instruction(&Starter::Start, None, &t),
11640 Some(instruction_for(&t))
11641 );
11642
11643 let old = t.instruction.clone();
11646 assert_eq!(
11647 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11648 Some(resumed_instruction(&old, &t))
11649 );
11650
11651 assert_eq!(
11655 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11656 None
11657 );
11658 }
11659
11660 #[test]
11661 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11662 assert_eq!(
11663 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11664 Starter::Review("magi/eba2/A".to_owned())
11665 );
11666 }
11667
11668 #[test]
11669 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11670 assert_eq!(
11671 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11672 Starter::Start,
11673 "a vanished review branch must not fall back to resuming the old run either"
11674 );
11675 }
11676
11677 #[test]
11678 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11679 let mut t = task();
11680 t.start("old-run".to_owned());
11681 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11682 t.release();
11683 let branch = t.review_branch.take();
11684 assert_eq!(
11685 choose_starter(branch.as_deref(), true, Some("old-run")),
11686 Starter::Review("magi/eba2/A".to_owned()),
11687 "a review wins over resuming the old run"
11688 );
11689 }
11690
11691 #[test]
11692 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11693 assert_eq!(
11694 choose_starter(None, false, Some("some-run")),
11695 Starter::Resume("some-run".to_owned())
11696 );
11697 assert_eq!(choose_starter(None, false, None), Starter::Start);
11698 }
11699
11700 #[test]
11701 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11702 let mut released = task();
11703 released.start("stalled-run".to_owned());
11704 released.requeue();
11705 let unfinished = (!released.fresh_start)
11706 .then(|| Some("stalled-run".to_owned()))
11707 .flatten();
11708 assert_eq!(
11709 choose_starter(None, false, unfinished.as_deref()),
11710 Starter::Start,
11711 "release keeps run history but must not resume it"
11712 );
11713 assert_eq!(released.runs, ["stalled-run"]);
11714 }
11715
11716 fn stopped_public_run(status: RunStatus) -> RunState {
11717 let mut state = run_state(status);
11718 state.driver_exited = true;
11719 state.config.graph.land = true;
11720 state.config.graph.review_rounds = 1;
11721 state.reviews = vec![review_round(1)];
11722 state.merge = Some(crate::run::MergeOutcome {
11723 mode: MergeMode::Pr,
11724 ok: false,
11725 detail: "landing stopped".into(),
11726 empty: false,
11727 });
11728 state.pr = Some(crate::run::PrRecord {
11729 url: "https://example.test/pull/1".into(),
11730 number: 1,
11731 state: "open".into(),
11732 checks: "red".into(),
11733 round: 1,
11734 rounds: 1,
11735 red_at_merge: Vec::new(),
11736 });
11737 state
11738 }
11739
11740 #[test]
11741 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11742 for status in [RunStatus::Blocked, RunStatus::Gating] {
11743 let home = tempfile::tempdir().unwrap();
11744 let mut state = stopped_public_run(status);
11745 state.save_under(home.path()).unwrap();
11746 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11747 assert!(!exhausted_review_budget(&state));
11748 let mut task = held_task_with(&state.id);
11749 task.release();
11750 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11751 assert_eq!(
11752 choose_starter(None, false, unfinished.as_deref()),
11753 Starter::Resume(state.id.clone())
11754 );
11755 let question = action_question(&state.id, resume_action(&state.id));
11756 assert_eq!(
11757 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11758 state.clone()
11759 )),
11760 ActionDecision::Resume(state.id.clone())
11761 );
11762 assert_eq!(
11764 crate::resume::validate(home.path(), &state.id).unwrap().id,
11765 state.id
11766 );
11767 let queue = Queue::at(home.path().join("queue"));
11768 let mut controlled = Task::new(
11769 "resume land".into(),
11770 state.instruction.clone(),
11771 state.repo.clone(),
11772 Source::Agent {
11773 run: "talk".into(),
11774 node: crate::queue::CHAT_NODE.into(),
11775 },
11776 );
11777 controlled.runs.push(state.id.clone());
11778 controlled.hold_machine(Some("land stopped".into()));
11779 queue.put(&mut controlled).unwrap();
11780 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11781 assert_eq!(resumed.status, TaskStatus::Queued);
11782 assert_eq!(
11783 resumed.resume_override.unwrap().pinned_run,
11784 Some(state.id.clone())
11785 );
11786 assert_eq!(resumed.attempts, 0);
11787 }
11788 }
11789
11790 #[test]
11791 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11792 for review_rounds in [0, 1] {
11793 let home = tempfile::tempdir().unwrap();
11794 let mut state = run_state(RunStatus::Blocked);
11795 state.config.graph.review_rounds = review_rounds;
11796 if review_rounds > 0 {
11797 let mut review = review_round(1);
11798 review.clean = true;
11799 state.reviews = vec![review];
11800 }
11801 state.gate_ran = true;
11802 state.gate = vec![crate::run::CommandOutcome {
11803 command: "verify".into(),
11804 code: Some(1),
11805 output_tail: "gate failed after repair budget exhausted".into(),
11806 duration_ms: 0,
11807 resource_blocked: false,
11808 }];
11809 state.save_under(home.path()).unwrap();
11810 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11811 assert!(exhausted_review_budget(&state));
11812 let mut task = held_task_with(&state.id);
11813 task.release();
11814 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11815 let question = action_question(&state.id, resume_action(&state.id));
11816 assert_ne!(
11817 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11818 state.clone()
11819 )),
11820 ActionDecision::Resume(state.id.clone())
11821 );
11822 let error = crate::resume::validate(home.path(), &state.id)
11823 .unwrap_err()
11824 .to_string();
11825 assert!(!error.contains("review budget exhausted"), "{error}");
11826 assert!(
11827 error.contains(if review_rounds == 0 {
11828 "review is disabled"
11829 } else {
11830 "gate already ran"
11831 }),
11832 "{error}"
11833 );
11834
11835 state.gate_ran = false;
11837 state.gate.clear();
11838 assert!(!exhausted_review_budget(&state));
11839 assert_eq!(
11840 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11841 Some(state.id)
11842 );
11843 }
11844 }
11845
11846 #[test]
11847 fn resource_blocked_verification_resumes_the_same_run() {
11848 for (kind, stage) in [
11849 ("cache", "clean"),
11850 ("coordination", "clean"),
11851 ("cache", "review-e2e"),
11852 ("coordination", "no-reviews"),
11853 ("coordination", "handoff"),
11854 ] {
11855 let home = tempfile::tempdir().unwrap();
11856 let mut state = run_state(RunStatus::Blocked);
11857 state.config.graph.review_rounds = 1;
11858 let mut review = review_round(1);
11859 review.clean = true;
11860 state.reviews = vec![review];
11861 if stage == "review-e2e" {
11862 let review = &mut state.reviews[0];
11863 review.clean = false;
11864 review.blocking = 1;
11865 review.e2e = vec![crate::run::CommandOutcome {
11866 command: "verify".into(),
11867 code: None,
11868 output_tail: "resource wait expired".into(),
11869 duration_ms: 0,
11870 resource_blocked: true,
11871 }];
11872 } else if stage == "no-reviews" {
11873 state.config.graph.review_rounds = 0;
11874 state.reviews.clear();
11875 } else if stage == "handoff" {
11876 let review = &mut state.reviews[0];
11879 review.clean = false;
11880 review.blocking = 1;
11881 review.e2e = vec![crate::run::CommandOutcome {
11882 command: "verify".into(),
11883 code: Some(0),
11884 output_tail: String::new(),
11885 duration_ms: 0,
11886 resource_blocked: false,
11887 }];
11888 }
11889 state.gate_ran = false;
11890 state.resource_block = Some(crate::run::ResourceBlock {
11891 cause: crate::run::ResourceBlockCause::Other,
11892 node: if stage == "review-e2e" {
11893 "review"
11894 } else {
11895 "gate"
11896 }
11897 .into(),
11898 kind: kind.into(),
11899 detail: "resource wait expired".into(),
11900 at: jiff::Timestamp::now(),
11901 });
11902 state.save_under(home.path()).unwrap();
11903 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11904 assert!(!exhausted_review_budget(&state));
11905 let mut task = held_task_with(&state.id);
11906 task.release();
11907 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11908 assert_eq!(
11909 choose_starter(None, false, unfinished.as_deref()),
11910 Starter::Resume(state.id.clone())
11911 );
11912 let question = action_question(&state.id, resume_action(&state.id));
11913 assert_eq!(
11914 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11915 state.clone()
11916 )),
11917 ActionDecision::Resume(state.id.clone())
11918 );
11919 assert_eq!(
11920 crate::resume::validate(home.path(), &state.id).unwrap().id,
11921 state.id
11922 );
11923 let queue = Queue::at(home.path().join("queue"));
11924 let mut controlled = Task::new(
11925 "resume verification".into(),
11926 state.instruction.clone(),
11927 state.repo.clone(),
11928 Source::Agent {
11929 run: "talk".into(),
11930 node: crate::queue::CHAT_NODE.into(),
11931 },
11932 );
11933 controlled.runs.push(state.id.clone());
11934 controlled.hold_machine(Some("verification resource unavailable".into()));
11935 queue.put(&mut controlled).unwrap();
11936 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11937 assert_eq!(resumed.status, TaskStatus::Queued);
11938 assert_eq!(
11939 resumed.resume_override.unwrap().pinned_run,
11940 Some(state.id.clone())
11941 );
11942 assert_eq!(resumed.attempts, 0);
11943
11944 state.config.graph.review_rounds = 1;
11946 let mut unresolved = review_round(1);
11947 unresolved.blocking = 1;
11948 state.reviews = vec![unresolved];
11949 state.resource_block = None;
11950 state.save_under(home.path()).unwrap();
11951 assert!(exhausted_review_budget(&state));
11952 assert!(crate::resume::validate(home.path(), &state.id).is_err());
11953 }
11954 }
11955
11956 #[tokio::test]
11957 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11958 if !crate::standalone_test(
11959 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11960 ) {
11961 return;
11962 }
11963 let home = tempfile::tempdir().unwrap();
11964 let mut owner = stopped_public_run(RunStatus::Blocked);
11965 owner.save_under(home.path()).unwrap();
11966 let history = vec![owner.id.clone()];
11967 let repo = owner.repo.clone();
11968 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11969 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11970 let initial =
11971 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11972 assert!(
11973 initial.is_pending(),
11974 "a busy record must not hold or resume the task"
11975 );
11976 owner.retired_to = Some("20260101-000001-bbbb".into());
11977 owner.save_under(home.path()).unwrap();
11978 drop(lock);
11979 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11980 .await
11981 .expect("ownership lock released")
11982 .expect("read settled owner");
11983 assert!(
11984 result.is_none(),
11985 "the retired owner must not be resumed from a stale read"
11986 );
11987 }
11988
11989 #[tokio::test]
11990 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11991 if !crate::standalone_test(
11992 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11993 ) {
11994 return;
11995 }
11996 let home = tempfile::tempdir().unwrap();
11997 let mut owner = stopped_public_run(RunStatus::Blocked);
11998 let repo = tempfile::tempdir().unwrap();
11999 crate::git::git(repo.path(), &["init"]).await.unwrap();
12000 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12001 owner.id = "20260101-000000-aaaa".into();
12002 owner.save_under(home.path()).unwrap();
12003 let mut successor = run_state(RunStatus::Blocked);
12004 successor.id = "20260101-000001-bbbb".into();
12005 successor.save_under(home.path()).unwrap();
12006 let runs = vec![owner.id.clone(), successor.id.clone()];
12007 assert_eq!(
12008 public_resume_owner(home.path(), &runs, &owner.repo)
12009 .await
12010 .unwrap()
12011 .unwrap()
12012 .id,
12013 owner.id
12014 );
12015 let subdir = owner.repo.join("nested");
12016 std::fs::create_dir(&subdir).unwrap();
12017 assert_eq!(
12018 public_resume_owner(home.path(), &runs, &subdir)
12019 .await
12020 .unwrap()
12021 .unwrap()
12022 .id,
12023 owner.id
12024 );
12025 #[cfg(unix)]
12026 {
12027 let alias = home.path().join("repo-alias");
12028 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12029 assert_eq!(
12030 public_resume_owner(home.path(), &runs, &alias.join("nested"))
12031 .await
12032 .unwrap()
12033 .unwrap()
12034 .id,
12035 owner.id
12036 );
12037 }
12038 let different = tempfile::tempdir().unwrap();
12039 crate::git::git(different.path(), &["init"]).await.unwrap();
12040 assert!(
12041 public_resume_owner(home.path(), &runs, different.path())
12042 .await
12043 .is_err()
12044 );
12045 std::fs::remove_file(
12046 home.path()
12047 .join("runs")
12048 .join(&successor.id)
12049 .join("run.json"),
12050 )
12051 .unwrap();
12052 assert!(
12053 public_resume_owner(home.path(), &runs, &owner.repo)
12054 .await
12055 .is_err()
12056 );
12057 }
12058
12059 #[test]
12060 fn an_ordinary_release_keeps_a_resumable_run_available() {
12061 let mut released = task();
12062 released.start("stalled-run".to_owned());
12063 released.release();
12064 let unfinished = (!released.fresh_start)
12065 .then(|| Some("stalled-run".to_owned()))
12066 .flatten();
12067 assert_eq!(
12068 choose_starter(None, false, unfinished.as_deref()),
12069 Starter::Resume("stalled-run".to_owned()),
12070 "manual release must preserve the normal resume path"
12071 );
12072 }
12073
12074 #[test]
12075 fn resume_refusals_explain_admission_without_changing_task_or_run() {
12076 use crate::handover::{ResumeRefusal, resume_refusal_under};
12077 let home = tempfile::tempdir().unwrap();
12078 let mut exhausted = run_state(RunStatus::Blocked);
12079 exhausted.driver_exited = true;
12080 exhausted.config.graph.review_rounds = 3;
12081 exhausted.reviews = (1..=3).map(review_round).collect();
12082 for refusal in [
12083 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12084 ResumeRefusal::Status(RunStatus::Ready),
12085 ResumeRefusal::Released("20261022-000000-aaaa".into()),
12086 ResumeRefusal::Retired("retirement-successor".into()),
12087 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12088 ] {
12089 let mut state = exhausted.clone();
12090 let expected = match refusal {
12091 ResumeRefusal::Status(_) => {
12092 state.status = RunStatus::Ready;
12093 "status `ready`"
12094 }
12095 ResumeRefusal::Released(ref target) => {
12096 state.released_to = Some(target.clone());
12097 "execution was released"
12098 }
12099 ResumeRefusal::Retired(ref target) => {
12100 state.retired_to = Some(target.clone());
12101 "execution was retired"
12102 }
12103 ResumeRefusal::OwnershipTransferred(ref target) => {
12104 state.pr_taken_over_by = Some(target.clone());
12105 "PR ownership was transferred"
12106 }
12107 _ => "review budget exhausted (3/3 rounds used)",
12108 };
12109 assert_eq!(
12110 resume_refusal_under(&state, Some(home.path())),
12111 Some(refusal.clone())
12112 );
12113 assert_eq!(
12114 refusal.successor(),
12115 state
12116 .released_to
12117 .as_deref()
12118 .or(state.retired_to.as_deref())
12119 .or(state.pr_taken_over_by.as_deref())
12120 );
12121 state.save_under(home.path()).unwrap();
12122 let queue = Queue::at(home.path().join("queue"));
12123 let mut task = Task::new(
12124 "retained implementation".into(),
12125 state.instruction.clone(),
12126 state.repo.clone(),
12127 Source::Agent {
12128 run: "talk".into(),
12129 node: crate::queue::CHAT_NODE.into(),
12130 },
12131 );
12132 task.runs.push(state.id.clone());
12133 task.hold_machine(Some("stopped".into()));
12134 queue.put(&mut task).unwrap();
12135 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12136 let before_run = serde_json::to_value(&state).unwrap();
12137 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12138 .unwrap_err()
12139 .to_string();
12140 assert!(error.contains(expected), "{error}");
12141 assert!(!error.contains("only a stalled or blocked"), "{error}");
12142 if matches!(refusal, ResumeRefusal::Status(_)) {
12143 assert!(
12144 error.contains("is final; there is nothing left to resume"),
12145 "{error}"
12146 );
12147 }
12148 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12149 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12150 assert!(error.contains("review-only successor with a new review budget"));
12151 assert!(error.contains("does not resume this run"));
12152 }
12153 for target in [
12154 &state.released_to,
12155 &state.retired_to,
12156 &state.pr_taken_over_by,
12157 ]
12158 .into_iter()
12159 .flatten()
12160 {
12161 let short = if state.retired_to.as_ref() == Some(target) {
12162 target.as_str()
12163 } else {
12164 crate::run::short_of(target)
12165 };
12166 assert!(
12167 error.contains(&format!("run {short}; inspect `magi show {short}`")),
12168 "{error}"
12169 );
12170 if short != target {
12171 assert!(!error.contains(target), "full successor id leaked: {error}");
12172 }
12173 }
12174 assert_eq!(
12175 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12176 before_task
12177 );
12178 assert_eq!(
12179 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12180 .unwrap(),
12181 before_run
12182 );
12183 let question = action_question(&state.id, resume_action(&state.id));
12184 for phrases in [&PHRASES_EN, &PHRASES_JA] {
12185 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12186 RunState::load_under(id, home.path())
12187 });
12188 let ActionDecision::Refuse(detail) = decision else {
12189 panic!(
12190 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12191 state.id,
12192 home.path().display()
12193 );
12194 };
12195 assert!(detail.contains(expected), "{detail}");
12196 }
12197 }
12198 exhausted.status = RunStatus::Ready;
12200 exhausted.released_to = Some("released".into());
12201 exhausted.retired_to = Some("retired".into());
12202 exhausted.pr_taken_over_by = Some("owner".into());
12203 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12204 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12205 let detail = reason.diagnostic(&exhausted);
12206 for target in ["released", "retired", "owner"] {
12207 assert!(detail.contains(&format!("magi show {target}")));
12208 }
12209 }
12210
12211 #[test]
12212 fn resume_action_ignores_question_checkpoints_in_another_home() {
12213 crate::run::pin_test_home();
12214 let home = tempfile::tempdir().unwrap();
12215 let mut state = run_state(RunStatus::Blocked);
12216 state.id = format!(
12219 "resume-context-{}",
12220 home.path().file_name().unwrap().to_str().unwrap()
12221 );
12222 state.driver_exited = true;
12223 state.config.graph.review_rounds = 1;
12224 state.reviews = vec![review_round(1)];
12225 state.save_under(home.path()).unwrap();
12226 let task = held_task_with(&state.id);
12227 let answer = action_question(&state.id, resume_action(&state.id));
12228 let mut checkpoint = approval_question(&state.id);
12229 let foreign = Questions::open();
12230 foreign.put(&mut checkpoint).unwrap();
12231 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12232 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12233 RunState::load_under(id, home.path())
12234 });
12235 let matching: Vec<_> = foreign
12236 .list()
12237 .into_iter()
12238 .filter(|q| q.run == state.id && q.status.open())
12239 .collect();
12240 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12241 assert!(
12242 matches!(decision, ActionDecision::Refuse(_)),
12243 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12244 state.id,
12245 home.path().display(),
12246 crate::run::test_home().display()
12247 );
12248 assert_eq!(
12249 refusal,
12250 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12251 );
12252 let local = Questions::at(home.path().join("questions"));
12253 for status in [
12254 ask::QuestionStatus::Open,
12255 ask::QuestionStatus::Answered,
12256 ask::QuestionStatus::Abandoned,
12257 ] {
12258 let mut question = checkpoint.clone();
12259 match status {
12260 ask::QuestionStatus::Open => {}
12261 ask::QuestionStatus::Answered => {
12262 question
12263 .answer(ask::Answer::Choice(question.choices[0].clone()))
12264 .unwrap();
12265 }
12266 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12267 }
12268 local.put(&mut question).unwrap();
12269 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12270 RunState::load_under(id, home.path())
12271 });
12272 if status.open() {
12273 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12274 } else {
12275 assert!(
12276 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12277 "status={status:?}, decision={decision:?}"
12278 );
12279 }
12280 }
12281 }
12282
12283 #[test]
12284 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12285 let home = tempfile::tempdir().unwrap();
12286 let mut state = run_state(RunStatus::Stalled);
12287 state.id = format!(
12288 "resume-driver-{}",
12289 home.path().file_name().unwrap().to_str().unwrap()
12290 );
12291 state.driver_claimed = Some(false);
12292 state.save_under(home.path()).unwrap();
12293 let task = held_task_with(&state.id);
12294 let question = action_question(&state.id, resume_action(&state.id));
12295 let decide = || {
12296 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12297 RunState::load_under(id, home.path())
12298 })
12299 };
12300 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12301 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12302 assert_eq!(
12303 decide(),
12304 ActionDecision::Refuse("run already has a live driver".into())
12305 );
12306 drop(lease);
12307 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12308 }
12309
12310 #[test]
12311 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12312 let home = tempfile::tempdir().unwrap();
12313 let mut state = run_state(RunStatus::Blocked);
12314 state.driver_exited = true;
12315 state.config.graph.review_rounds = 1;
12316 state.reviews = vec![review_round(1)];
12317 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12318 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12319 let mut saved = state.clone();
12320 match checkpoint {
12321 "publication" => saved.pr_publication_pending = true,
12322 "approval" => {
12323 saved.land_approval = Some(crate::run::LandApproval {
12324 question: "approval".into(),
12325 head: "head".into(),
12326 })
12327 }
12328 "armed" => saved.land_armed_head = Some("head".into()),
12329 "landing" => saved.status = RunStatus::Landing,
12330 _ => {
12331 let mut question = ask::Question::new(
12332 saved.id.clone(),
12333 "review".into(),
12334 "review-1".into(),
12335 "continue?".into(),
12336 String::new(),
12337 vec!["continue".into()],
12338 );
12339 ask::Questions::at(home.path().join("questions"))
12340 .put(&mut question)
12341 .unwrap();
12342 }
12343 }
12344 saved.save_under(home.path()).unwrap();
12345 assert!(
12346 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12347 "{checkpoint}"
12348 );
12349 assert!(
12350 crate::resume::validate(home.path(), &saved.id).is_ok(),
12351 "{checkpoint}"
12352 );
12353 }
12354 }
12355
12356 #[test]
12357 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12358 let mut state = run_state(RunStatus::Blocked);
12359 state.config.graph.review_rounds = 3;
12360 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12361 assert!(exhausted_review_budget(&state));
12362
12363 state.reviews.pop();
12365 assert!(!exhausted_review_budget(&state));
12366
12367 let mut stalled = run_state(RunStatus::Stalled);
12370 stalled.config.graph.review_rounds = 1;
12371 stalled.reviews = vec![review_round(1)];
12372 assert!(!exhausted_review_budget(&stalled));
12373 }
12374
12375 fn review_round(round: usize) -> crate::run::ReviewRound {
12376 crate::run::ReviewRound {
12377 round,
12378 head: "deadbeef".to_owned(),
12379 verified_head: None,
12380 verified_at: None,
12381 reviews: Vec::new(),
12382 e2e: Vec::new(),
12383 verify_retried: false,
12384 e2e_deferred: false,
12385 e2e_defer_reason: None,
12386 fix: None,
12387 blocking: 0,
12388 answered: 1,
12389 expected: 1,
12390 clean: false,
12391 progressed: true,
12392 vote_split: false,
12393 reconsideration: Vec::new(),
12394 verdict: None,
12395 }
12396 }
12397
12398 #[test]
12399 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12400 let mut run = RunState::new(
12401 PathBuf::from("/repo"),
12402 "main".to_owned(),
12403 "abc1234def".to_owned(),
12404 "add retries".to_owned(),
12405 Config::default(),
12406 );
12407 run.status = RunStatus::Judging;
12408 run.parked = true;
12409 let mut task = Task::new(
12410 "add retries".to_owned(),
12411 "add retries".to_owned(),
12412 PathBuf::from("/repo"),
12413 crate::queue::Source::Human,
12414 );
12415 task.status = TaskStatus::Failed;
12416 task.runs = vec![run.id.clone()];
12417 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12418 assert!(with(&task, &run), "parked after judging is the case");
12419 let mut parked_task = task.clone();
12420 parked_task.status = TaskStatus::Parked;
12421 assert!(with(&parked_task, &run), "the Parked status is the case");
12422
12423 let mut not_parked = run.clone();
12424 not_parked.parked = false;
12425 not_parked.status = RunStatus::Stalled;
12426 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
12427
12428 let mut fresh = task.clone();
12429 fresh.fresh_start = true;
12430 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12431
12432 let mut review = task.clone();
12433 review.review_branch = Some("magi/x/A".to_owned());
12434 assert!(!with(&review, &run), "review is ranked before resume");
12435
12436 let mut held = task.clone();
12437 held.status = TaskStatus::Held;
12438 assert!(!with(&held, &run), "a hold stays visible to the conductor");
12439
12440 let mut released = run.clone();
12441 released.released_to = Some("20260901-000000-new1".to_owned());
12442 assert!(!with(&task, &released), "nothing left to resume into");
12443
12444 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12445 "unreadable"
12446 )));
12447 }
12448
12449 #[test]
12450 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12451 let mut released = RunState::new(
12452 PathBuf::from("/repo"),
12453 "main".to_owned(),
12454 "abc1234def".to_owned(),
12455 "add retries".to_owned(),
12456 Config::default(),
12457 );
12458 released.status = RunStatus::Blocked;
12459 assert_eq!(
12460 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12461 Some(released.id.clone())
12462 );
12463 released.released_to = Some("20260901-000000-new1".to_owned());
12464 assert_eq!(
12465 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12466 None,
12467 "there is nothing left to resume it into"
12468 );
12469 }
12470
12471 #[test]
12472 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12473 let mut exhausted = RunState::new(
12482 PathBuf::from("/repo"),
12483 "main".to_owned(),
12484 "abc1234def".to_owned(),
12485 "add retries".to_owned(),
12486 Config::default(),
12487 );
12488 exhausted.status = RunStatus::Blocked;
12489 exhausted.config.graph.review_rounds = 1;
12490 exhausted.reviews = vec![review_round(1)];
12491
12492 assert_eq!(
12493 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12494 None,
12495 "an exhausted `Blocked` run must not be offered as resumable"
12496 );
12497
12498 let mut has_budget_left = RunState::new(
12501 PathBuf::from("/repo"),
12502 "main".to_owned(),
12503 "abc1234def".to_owned(),
12504 "add retries".to_owned(),
12505 Config::default(),
12506 );
12507 has_budget_left.status = RunStatus::Blocked;
12508 has_budget_left.config.graph.review_rounds = 3;
12509 has_budget_left.reviews = vec![review_round(1)];
12510
12511 assert_eq!(
12512 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12513 Ok(has_budget_left.clone())
12514 }),
12515 Some(has_budget_left.id.clone())
12516 );
12517 }
12518
12519 #[test]
12520 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12521 let mut run = RunState::new(
12522 PathBuf::from("/repo"),
12523 "main".to_owned(),
12524 "abc1234def".to_owned(),
12525 "add retries".to_owned(),
12526 Config::default(),
12527 );
12528 run.status = RunStatus::Blocked;
12529 run.config.graph.review_rounds = 1;
12530 run.reviews = vec![review_round(1)];
12531 run.pr_publication_pending = true;
12532 assert_eq!(
12533 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12534 Some(run.id.clone()),
12535 "a spent review budget must not turn a failed publication into a re-competition"
12536 );
12537 }
12538
12539 #[test]
12540 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12541 let mut task = Task::new(
12542 "recover work".into(),
12543 "recover work".into(),
12544 PathBuf::from("/repo"),
12545 crate::queue::Source::Human,
12546 );
12547 let mut history = std::collections::BTreeMap::new();
12548 for index in 0..8 {
12549 let mut run = run_state(RunStatus::Blocked);
12550 run.id = format!("20260101-000000-{index:04}");
12551 run.base_commit = format!("upstream-{index}");
12552 if index > 0 {
12554 run.candidates.clear();
12555 }
12556 task.runs.extend([run.id.clone(), run.id.clone()]);
12557 history.insert(run.id.clone(), run);
12558 task.requeue();
12559 }
12560 let check = |task: &Task, starter: &Starter, limit| {
12561 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12562 };
12563 assert!(
12564 check(&task, &Starter::Start, 8)
12565 .unwrap()
12566 .contains("8 unretired")
12567 );
12568 assert!(check(&task, &Starter::Start, 9).is_none());
12569 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12570 task.release_operator("owner", None);
12571 assert_eq!(task.attempts, 0);
12572 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12573 assert!(check(&restored, &Starter::Start, 8).is_some());
12574 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12575 assert!(check(&restored, &Starter::Start, 0).is_none());
12576 }
12577
12578 #[test]
12579 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
12580 let tmp = tempfile::tempdir().unwrap();
12581 let mut task = Task::new(
12582 "recover selected PR".into(),
12583 "preserve implementation".into(),
12584 tmp.path().join("repo"),
12585 crate::queue::Source::Human,
12586 );
12587 let mut failed = run_state(RunStatus::Failed);
12588 failed.id = "20260101-000000-fail".into();
12589 failed.candidates.clear();
12590 failed.prep_complete = Some(false);
12591 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
12592 failed.startup = Some(crate::run::Startup {
12593 kind: "pr-recovery".into(),
12594 branch: Some("selected-public-head".into()),
12595 stage: "worktree-setup".into(),
12596 complete: false,
12597 failure: Some("setup modified a tracked file and failed".into()),
12598 });
12599 let worktree = failed.worktree_root().join("under-review");
12602 std::fs::create_dir_all(&worktree).unwrap();
12603 let retained_edit = worktree.join("implementation");
12604 std::fs::write(&retained_edit, "retained setup edit").unwrap();
12605 task.record_startup_failure(crate::run::StartupFailure {
12606 run: failed.id.clone(),
12607 stage: "worktree-setup".into(),
12608 });
12609 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12610 assert!(task.runs.is_empty() && task.passes.is_empty());
12611 assert_eq!(task.attempts, 0);
12612 let starter = Starter::Review("selected-public-head".into());
12613 assert!(
12614 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
12615 .unwrap()
12616 .contains("1 unretired")
12617 );
12618 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
12619 assert!(
12620 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
12621 .unwrap()
12622 .contains("Cannot verify")
12623 );
12624 let mut mixed = task.clone();
12626 mixed.runs.push(failed.id.clone());
12627 mixed
12628 .startup_failures
12629 .push(task.startup_failures[0].clone());
12630 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
12631 failed.retired_to = Some("verified-recovery-owner".into());
12632 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
12633 assert!(
12634 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
12635 panic!("resuming the existing owner must not allocate a new attempt")
12636 })
12637 .is_none()
12638 );
12639 assert_eq!(
12640 std::fs::read_to_string(retained_edit).unwrap(),
12641 "retained setup edit"
12642 );
12643 assert!(task.runs.is_empty() && task.passes.is_empty());
12644 assert_eq!(task.attempts, 0);
12645 }
12646
12647 #[test]
12648 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12649 let mut task = Task::new(
12650 "recover work".into(),
12651 "recover work".into(),
12652 PathBuf::from("/repo"),
12653 crate::queue::Source::Human,
12654 );
12655 let mut run = run_state(RunStatus::Superseded);
12656 run.candidates.clear();
12657 task.runs.push(run.id.clone());
12658 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12659 run.retired_to = Some("authority".into());
12660 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12661 run.retired_to = None;
12662 run.released_to = Some("authority".into());
12663 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12664 assert!(
12665 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12666 .unwrap()
12667 .contains("Cannot verify")
12668 );
12669 assert!(
12671 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12672 panic!("resume must not load historical attempts")
12673 })
12674 .is_none()
12675 );
12676 }
12677
12678 #[test]
12679 fn retired_resume_requires_a_valid_same_repository_authority() {
12680 let mut source = run_state(RunStatus::Blocked);
12681 let mut empty = run_state(RunStatus::Blocked);
12682 empty.retired_to = Some(source.id.clone());
12683 let runs = vec![source.id.clone(), empty.id.clone()];
12684 let resolve = |source: &RunState, empty: &RunState| {
12685 unfinished_run_with(&runs, "fixture", |id| {
12686 if id == source.id {
12687 Ok(source.clone())
12688 } else if id == empty.id {
12689 Ok(empty.clone())
12690 } else {
12691 bail!("unreadable authority")
12692 }
12693 })
12694 };
12695 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12696 assert_eq!(
12697 choose_starter(None, false, resolve(&source, &empty).as_deref()),
12698 Starter::Resume(source.id.clone())
12699 );
12700 source.retired_to = Some(empty.id.clone());
12701 assert!(
12702 resolve(&source, &empty).is_none(),
12703 "cycles do not revive obsolete runs"
12704 );
12705 source.retired_to = None;
12706 source.repo = PathBuf::from("/another-repository");
12707 assert!(resolve(&source, &empty).is_none());
12708 source.repo = empty.repo.clone();
12709 source.released_to = Some("later".into());
12710 assert!(resolve(&source, &empty).is_none());
12711 empty.retired_to = Some("unlisted-run".into());
12712 assert!(resolve(&source, &empty).is_none());
12713 }
12714
12715 #[test]
12716 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12717 let mut older_stalled = RunState::new(
12725 PathBuf::from("/repo"),
12726 "main".to_owned(),
12727 "abc1234def".to_owned(),
12728 "add retries".to_owned(),
12729 Config::default(),
12730 );
12731 older_stalled.status = RunStatus::Stalled;
12732
12733 let mut newest_exhausted = RunState::new(
12734 PathBuf::from("/repo"),
12735 "main".to_owned(),
12736 "abc1234def".to_owned(),
12737 "add retries".to_owned(),
12738 Config::default(),
12739 );
12740 newest_exhausted.status = RunStatus::Blocked;
12741 newest_exhausted.config.graph.review_rounds = 1;
12742 newest_exhausted.reviews = vec![review_round(1)];
12743
12744 assert_eq!(
12745 unfinished_run_with(
12746 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12747 "t",
12748 |_| Ok(newest_exhausted.clone())
12749 ),
12750 None,
12751 "the newest run is exhausted, so nothing here is worth resuming - \
12752 least of all the older, already-superseded run"
12753 );
12754 }
12755
12756 #[test]
12757 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12758 assert_eq!(
12759 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12760 Err(anyhow::anyhow!("fixture is absent"))
12761 }),
12762 None
12763 );
12764 }
12765
12766 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12767 let mut q = ask::Question::new(
12768 run.to_owned(),
12769 "implement".to_owned(),
12770 "impl-A".to_owned(),
12771 "continue?".to_owned(),
12772 String::new(),
12773 vec!["resume で続行する".to_owned(), "other".to_owned()],
12774 );
12775 q.actions.insert("resume で続行する".to_owned(), action);
12776 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12777 .unwrap();
12778 q
12779 }
12780
12781 fn held_task_with(run: &str) -> Task {
12782 let mut t = task();
12783 t.runs = vec![run.to_owned()];
12784 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12785 t
12786 }
12787
12788 fn resume_action(run: &str) -> ask::ChoiceAction {
12789 ask::ChoiceAction::Resume { run: run.into() }
12790 }
12791
12792 #[test]
12793 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12794 let home = crate::run::test_home();
12795 for parked in [false, true] {
12796 let mut t = task();
12797 t.start("A".into());
12798 t.start("B".into());
12799 assert_eq!(t.runs, vec!["A", "B"]);
12800 t.start("A".into());
12801 let mut resumed = run_state(RunStatus::Blocked);
12802 resumed.id = "A".into();
12803 resumed.parked = parked;
12804 resumed.driver_exited = true;
12805 t.hold_machine(Some("resumed run stopped".into()));
12806 let q = action_question("A", resume_action("A"));
12807 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12808 assert_eq!(
12809 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
12810 assert_eq!(id, "A");
12811 Ok(resumed.clone())
12812 }),
12813 ActionDecision::Resume("A".into())
12814 );
12815 assert_eq!(
12816 action_standing(&t, &action_question("B", resume_action("B"))),
12817 ActionStanding::Stale
12818 );
12819 t.release_operator("cli", None);
12820 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12821 assert_eq!(id, "A");
12822 Ok(resumed.clone())
12823 });
12824 assert_eq!(
12825 choose_starter(None, false, unfinished.as_deref()),
12826 Starter::Resume("A".into())
12827 );
12828 assert_eq!(t.runs, vec!["B", "A"]);
12829 }
12830 }
12831
12832 #[test]
12833 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12834 let home = crate::run::test_home();
12835 let mut state = crate::land::tests::repair_state(true, true);
12836 state.status = RunStatus::Landing;
12837 state.parked = true;
12838 state.driver_exited = true;
12839 let mut q = ask::Question::new(
12840 state.id.clone(),
12841 land::APPROVAL_NODE.into(),
12842 "land".into(),
12843 "Merge?".into(),
12844 String::new(),
12845 vec![land::APPROVE.into(), land::HOLD.into()],
12846 );
12847 q.id = state.id.clone();
12848 state.land_approval = Some(crate::run::LandApproval {
12849 question: q.id.clone(),
12850 head: "current-head".into(),
12851 });
12852 assert!(land::upgrade_repair_choice(&mut q, &state));
12853 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12854 let mut task = held_task_with(&state.id);
12855 task.status = TaskStatus::Parked;
12856 assert_eq!(
12857 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12858 ActionDecision::Resume(state.id.clone())
12859 );
12860 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12861 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12862 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12863 assert_eq!(
12864 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12865 ActionDecision::Resume(state.id.clone()),
12866 "a repair answer newer than the manual hold resumes the existing owner"
12867 );
12868 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12869 for answered_at in [q.answered_at, None] {
12870 let mut older = q.clone();
12871 older.answered_at = answered_at;
12872 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
12873 panic!("a later manual hold must prevent dispatch")
12874 });
12875 let ActionDecision::Refuse(reason) = refused else {
12876 panic!("expected an actionable refusal, got {refused:?}");
12877 };
12878 assert!(reason.contains("later operator decision"));
12879 assert!(reason.contains(&format!("magi task release {}", task.id)));
12880 }
12881 task.operator_decided_at = None;
12882 let mut superseded = state.clone();
12883 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12884 assert_eq!(
12885 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
12886 ActionDecision::Stale
12887 );
12888 for case in 1..4 {
12889 let mut changed = state.clone();
12890 match case {
12891 1 => changed.status = RunStatus::Blocked,
12892 2 => changed.released_to = Some("new-owner".into()),
12893 _ => changed.land_approval.as_mut().unwrap().head.clear(),
12894 }
12895 assert!(matches!(
12896 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
12897 ActionDecision::Refuse(_)
12898 ));
12899 }
12900 assert!(matches!(
12901 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
12902 "missing owner"
12903 )),
12904 ActionDecision::Refuse(_)
12905 ));
12906 task.runs.push("replacement".into());
12907 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12908 assert_eq!(
12909 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
12910 "old owner must not load"
12911 )),
12912 ActionDecision::Stale
12913 );
12914 }
12915
12916 #[test]
12917 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12918 let mut state = crate::land::tests::repair_state(true, true);
12919 state.status = RunStatus::Landing;
12920 state.parked = true;
12921 state.driver_exited = true;
12922 let mut q = ask::Question::new(
12923 state.id.clone(),
12924 land::APPROVAL_NODE.into(),
12925 "land".into(),
12926 "Merge?".into(),
12927 String::new(),
12928 vec![land::APPROVE.into(), land::HOLD.into()],
12929 );
12930 q.id = state.id.clone();
12931 state.land_approval = Some(crate::run::LandApproval {
12932 question: q.id.clone(),
12933 head: "current-head".into(),
12934 });
12935 state.save().unwrap();
12936 land::upgrade_repair_choice(&mut q, &state);
12937 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12938 Questions::open().put(&mut q).unwrap();
12939 let tmp = tempfile::tempdir().unwrap();
12940 let queue = Queue::at(tmp.path().join("queue"));
12941 let mut task = held_task_with(&state.id);
12942 task.status = TaskStatus::Parked;
12943 queue.put(&mut task).unwrap();
12944 let empty = Arc::new(tokio::sync::Semaphore::new(0));
12945 let free = Arc::new(tokio::sync::Semaphore::new(1));
12946 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12947 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12948 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12949 assert!(claim.permit.is_some());
12950 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12951 drop(claim);
12952 Questions::open()
12953 .update(&q.id, |q| {
12954 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12955 Ok(())
12956 })
12957 .unwrap();
12958 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12959 assert!(claim.permit.is_none());
12960 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12961 }
12962
12963 #[test]
12964 fn decide_action_resumes_only_the_latest_resumable_run() {
12965 let home = crate::run::test_home();
12966 let t = held_task_with("r1");
12967 let q = action_question("r1", resume_action("r1"));
12968 let load = |s: RunState| move |_: &str| Ok(s);
12969 assert_eq!(
12970 decide_action(
12971 &home,
12972 &t,
12973 &q,
12974 &PHRASES_EN,
12975 load(run_state(RunStatus::Blocked))
12976 ),
12977 ActionDecision::Resume("r1".into())
12978 );
12979 let q_other = action_question("r1", resume_action("r0"));
12981 assert!(matches!(
12982 decide_action(
12983 &home,
12984 &t,
12985 &q_other,
12986 &PHRASES_EN,
12987 load(run_state(RunStatus::Blocked))
12988 ),
12989 ActionDecision::Refuse(_)
12990 ));
12991 assert!(matches!(
12993 decide_action(
12994 &home,
12995 &t,
12996 &q,
12997 &PHRASES_EN,
12998 load(run_state(RunStatus::Ready))
12999 ),
13000 ActionDecision::Refuse(_)
13001 ));
13002 let mut released = run_state(RunStatus::Blocked);
13004 released.released_to = Some("elsewhere".into());
13005 assert!(matches!(
13006 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13007 ActionDecision::Refuse(_)
13008 ));
13009 assert!(matches!(
13011 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13012 ActionDecision::Refuse(_)
13013 ));
13014 }
13015
13016 #[test]
13017 fn decide_action_ignores_a_question_about_an_earlier_run() {
13018 let home = crate::run::test_home();
13019 let mut t = held_task_with("r1");
13020 t.runs.push("r2".to_owned());
13021 let never = |_: &str| -> Result<RunState> { bail!("not read") };
13022 assert_eq!(
13023 decide_action(
13024 &home,
13025 &t,
13026 &action_question("r1", ask::ChoiceAction::Done),
13027 &PHRASES_EN,
13028 never
13029 ),
13030 ActionDecision::Stale
13031 );
13032 }
13033
13034 #[test]
13035 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13036 let home = crate::run::test_home();
13037 let mut t = held_task_with("r1");
13038 let never = |_: &str| -> Result<RunState> { bail!("not read") };
13039 assert_eq!(
13040 decide_action(
13041 &home,
13042 &t,
13043 &action_question("r1", ask::ChoiceAction::Requeue),
13044 &PHRASES_EN,
13045 never
13046 ),
13047 ActionDecision::Requeue
13048 );
13049 let done_q = action_question("r1", ask::ChoiceAction::Done);
13050 assert_eq!(
13051 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13052 ActionDecision::Done
13053 );
13054 t.mark_action_applied(&done_q.id);
13055 assert_eq!(
13056 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13057 ActionDecision::Skip
13058 );
13059
13060 let mut plain = action_question("r1", ask::ChoiceAction::Done);
13062 plain.actions.clear();
13063 assert_eq!(
13064 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13065 ActionDecision::Skip
13066 );
13067 let mut running = held_task_with("r1");
13069 running.status = TaskStatus::Running;
13070 assert_eq!(
13071 decide_action(
13072 &home,
13073 &running,
13074 &action_question("r1", ask::ChoiceAction::Done),
13075 &PHRASES_EN,
13076 never
13077 ),
13078 ActionDecision::Skip
13079 );
13080 }
13081
13082 #[test]
13083 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13084 crate::run::pin_test_home();
13085 for legacy in [false, true] {
13086 let dir = tempfile::tempdir().unwrap();
13087 let queue = Queue::at(dir.path().join("queue"));
13088 let questions = Questions::at(dir.path().join("questions"));
13089 let run = "20260101-000000-hold";
13090 let mut task = held_task_with(run);
13091 task.status = TaskStatus::Parked;
13092 let mut q = ask::Question::new(
13093 run.into(),
13094 land::APPROVAL_NODE.into(),
13095 "land".into(),
13096 "Repair?".into(),
13097 String::new(),
13098 vec![land::REPAIR.into()],
13099 );
13100 q.actions.insert(land::REPAIR.into(), resume_action(run));
13101 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13102 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13104 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13105 questions.put(&mut q).unwrap();
13106 task.hold_manual(Some("Keep this PR paused".into()));
13107 if legacy {
13108 task.hold_source = None;
13109 }
13110 queue.put(&mut task).unwrap();
13111
13112 apply_task_choice_actions(&queue, &questions, dir.path());
13113 let after = queue.get(&task.id).unwrap();
13114 assert!(after.operator_held());
13115 assert_eq!(after.hold_source, task.hold_source);
13116 assert_eq!(after.operator_decided_at, task.operator_decided_at);
13117 assert_eq!(after.runs, task.runs);
13118 assert_eq!(after.instruction, task.instruction);
13119 assert!(after.resume_override.is_none());
13120 assert!(after.action_applied(&q.id));
13121 let reason = after.hold_reason.as_deref().unwrap();
13122 assert!(reason.starts_with("Keep this PR paused"));
13123 assert!(reason.contains("later operator decision"));
13124 assert!(reason.contains(&format!("magi task release {}", task.id)));
13125
13126 for recovery in [
13127 crate::conduct::Recovery::Review,
13128 crate::conduct::Recovery::Requeue,
13129 ] {
13130 crate::conduct::apply(
13131 &queue,
13132 &questions,
13133 &crate::conduct::Verdict {
13134 decisions: vec![crate::conduct::Decision {
13135 id: task.id.clone(),
13136 recovery: Some(recovery),
13137 ..Default::default()
13138 }],
13139 },
13140 )
13141 .unwrap();
13142 }
13143 apply_task_choice_actions(&queue, &questions, dir.path());
13146 let still_held = queue.get(&task.id).unwrap();
13147 assert!(still_held.operator_held());
13148 assert_eq!(still_held.hold_reason, after.hold_reason);
13149 assert_eq!(still_held.runs, task.runs);
13150 assert!(still_held.review_branch.is_none());
13151 assert!(!still_held.fresh_start);
13152 assert!(queue.next_runnable().is_none());
13153 }
13154 }
13155
13156 #[test]
13157 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13158 for held in [false, true] {
13159 for retry in [false, true] {
13160 let dir = tempfile::tempdir().unwrap();
13161 let queue = Queue::at(dir.path().join("queue"));
13162 let questions = Questions::at(dir.path().join("questions"));
13163 let home = dir.path().join("home");
13164 let mut t = task();
13165 if held {
13166 t.hold_machine(Some("driver state unknown".into()));
13167 }
13168 queue.put(&mut t).unwrap();
13169 let verdict = serde_json::from_value(serde_json::json!({
13170 "decisions": [{
13171 "id": t.id,
13172 "question": "Driver state unknown; retry the checks or hold?",
13173 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13174 "actions": {
13175 "daemon: recheck and retry": {"do": "requeue"},
13176 "daemon: hold the task": {"do": "hold"}
13177 }
13178 }]
13179 }))
13180 .unwrap();
13181 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13182 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13183 let mut q = questions.list().pop().unwrap();
13184 let choice = if retry {
13185 "daemon: recheck and retry"
13186 } else {
13187 "daemon: hold the task"
13188 };
13189 assert_eq!(q.actions.len(), 2);
13190 q.answer(ask::Answer::Choice(choice.into())).unwrap();
13191 questions.put(&mut q).unwrap();
13192
13193 questions.beat(&q.id, ask::WaiterKind::Deputy);
13195 for _ in 0..2 {
13196 resolve_blockers(&queue, &questions);
13197 apply_task_choice_actions(&queue, &questions, &home);
13198 let waiting = queue.get(&t.id).unwrap();
13199 assert_eq!(waiting.status, TaskStatus::Blocked);
13200 assert_eq!(waiting.blocked_by, [q.id.clone()]);
13201 assert!(waiting.answers.is_empty());
13202 assert!(!waiting.action_applied(&q.id));
13203 assert!(runnable(&queue).is_empty());
13204 let free = Arc::new(tokio::sync::Semaphore::new(1));
13205 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13206 }
13207 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13208
13209 resolve_blockers(&queue, &questions);
13211 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13212 apply_task_choice_actions(&queue, &questions, &home);
13213 let after = queue.get(&t.id).unwrap();
13214 assert_eq!(
13215 after.status,
13216 if retry {
13217 TaskStatus::Queued
13218 } else {
13219 TaskStatus::Held
13220 }
13221 );
13222 assert!(after.action_applied(&q.id));
13223 assert_eq!(after.operator_held(), !retry);
13224 assert_eq!(after.answers.len(), 1);
13225
13226 let mut changed = after;
13228 if retry {
13229 changed.hold_manual(Some("later hold".into()));
13230 } else {
13231 changed.release_operator("test", None);
13232 }
13233 let expected = changed.status;
13234 queue.put(&mut changed).unwrap();
13235 apply_task_choice_actions(&queue, &questions, &home);
13236 assert_eq!(queue.get(&t.id).unwrap().status, expected);
13237 }
13238 }
13239 }
13240
13241 #[test]
13242 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13243 let dir = tempfile::tempdir().unwrap();
13244 let queue = Queue::at(dir.path().join("queue"));
13245 let questions = Questions::at(dir.path().join("questions"));
13246 let home = dir.path().join("home");
13247 let mut state = run_state(RunStatus::Blocked);
13248 state.id = "20260101-000000-act1".to_owned();
13249 state.save_under(&home).unwrap();
13250
13251 let mut t = held_task_with(&state.id);
13252 queue.put(&mut t).unwrap();
13253 let mut q = action_question(&state.id, resume_action(&state.id));
13254 questions.put(&mut q).unwrap();
13255
13256 apply_task_choice_actions(&queue, &questions, &home);
13257 let after = queue.get(&t.id).unwrap();
13258 assert_eq!(after.status, TaskStatus::Queued);
13259 assert!(!after.fresh_start);
13260 assert!(after.action_applied(&q.id));
13261 let pin = after.resume_override.clone().unwrap();
13262 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13263 assert!(pin.forced);
13264
13265 let mut again = queue.get(&t.id).unwrap();
13267 again.hold_machine(Some("later".into()));
13268 queue.put(&mut again).unwrap();
13269 apply_task_choice_actions(&queue, &questions, &home);
13270 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13271 }
13272
13273 #[test]
13274 fn a_delivered_answer_is_still_acted_on_exactly_once() {
13275 let dir = tempfile::tempdir().unwrap();
13276 let queue = Queue::at(dir.path().join("queue"));
13277 let questions = Questions::at(dir.path().join("questions"));
13278 let home = dir.path().join("home");
13279 let mut state = run_state(RunStatus::Blocked);
13280 state.id = "20260101-000000-act2".to_owned();
13281 state.save_under(&home).unwrap();
13282
13283 let mut t = held_task_with(&state.id);
13284 queue.put(&mut t).unwrap();
13285 let mut q = action_question(&state.id, resume_action(&state.id));
13286 q.answer_delivered = true;
13287 questions.put(&mut q).unwrap();
13288
13289 apply_task_choice_actions(&queue, &questions, &home);
13292 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13293 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13294
13295 let mut again = queue.get(&t.id).unwrap();
13297 again.hold_machine(Some("later".into()));
13298 queue.put(&mut again).unwrap();
13299 apply_task_choice_actions(&queue, &questions, &home);
13300 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13301 }
13302
13303 #[test]
13304 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13305 let dir = tempfile::tempdir().unwrap();
13306 let queue = Queue::at(dir.path().join("queue"));
13307 let questions = Questions::at(dir.path().join("questions"));
13308 let home = dir.path().join("home");
13309 let mut state = run_state(RunStatus::Blocked);
13310 state.id = "20260101-000000-act3".to_owned();
13311 state.save_under(&home).unwrap();
13312 let mut t = held_task_with(&state.id);
13313 queue.put(&mut t).unwrap();
13314 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13315 questions.put(&mut q).unwrap();
13316
13317 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13318 apply_task_choice_actions(&queue, &questions, &home);
13319 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13320
13321 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13322 apply_task_choice_actions(&queue, &questions, &home);
13323 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13324 }
13325
13326 #[test]
13327 fn action_standing_tells_the_reasons_apart() {
13328 let mut t = held_task_with("r1");
13329 let q = action_question("r1", ask::ChoiceAction::Requeue);
13330 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13331 let mut plain = q.clone();
13332 plain.actions.clear();
13333 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13334
13335 t.mark_action_applied(&q.id);
13337 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13338
13339 let mut t = held_task_with("r1");
13341 t.start("r2".to_owned());
13342 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13343 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13345 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13346 t.status = TaskStatus::Blocked;
13347 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13348
13349 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13351 c.node = crate::conduct::NODE.to_owned();
13352 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13353 assert!(!ActionStanding::Busy.daemon_owns());
13354 }
13355
13356 #[test]
13357 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13358 let dir = tempfile::tempdir().unwrap();
13359 let queue = Queue::at(dir.path().join("queue"));
13360 let questions = Questions::at(dir.path().join("questions"));
13361 let home = dir.path().join("home");
13362 let mut state = run_state(RunStatus::Blocked);
13363 state.id = "20260101-000000-act4".to_owned();
13364 state.save_under(&home).unwrap();
13365 let mut t = held_task_with(&state.id);
13366 t.status = TaskStatus::Running;
13367 queue.put(&mut t).unwrap();
13368 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13369 q.cwd = Some(dir.path().display().to_string());
13370 questions.put(&mut q).unwrap();
13371
13372 let running = queue.get(&t.id).unwrap();
13375 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13376 assert!(matches!(
13377 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13378 crate::waiter::Action::Deliver(_)
13379 ));
13380 apply_task_choice_actions(&queue, &questions, &home);
13382 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13383 let mut back = queue.get(&t.id).unwrap();
13384 back.hold_machine(Some("later".into()));
13385 queue.put(&mut back).unwrap();
13386 apply_task_choice_actions(&queue, &questions, &home);
13387 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13388 let mut again = queue.get(&t.id).unwrap();
13389 again.hold_machine(Some("again".into()));
13390 queue.put(&mut again).unwrap();
13391 apply_task_choice_actions(&queue, &questions, &home);
13392 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13393 }
13394}