1use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71pub const SCHEMA: u32 = 1;
73
74pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79pub const STALE_SECS: i64 = 30;
88
89pub const POLL: Duration = Duration::from_secs(5);
91
92pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 pub task: String,
123 pub run: String,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 pub schema: u32,
137 pub pid: u32,
139 pub started_at: Timestamp,
141 pub updated_at: Timestamp,
143 pub idle: bool,
145 pub current: Vec<Current>,
151 pub completed: usize,
153 pub polls: u64,
155}
156
157impl Status {
158 #[must_use]
160 pub fn new() -> Self {
161 let now = Timestamp::now();
162 Self {
163 schema: SCHEMA,
164 pid: std::process::id(),
165 started_at: now,
166 updated_at: now,
167 idle: true,
168 current: Vec::new(),
169 completed: 0,
170 polls: 0,
171 }
172 }
173}
174
175impl Default for Status {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180
181#[derive(Debug, Clone)]
183pub struct Opts {
184 pub repo: PathBuf,
186 pub config: Option<PathBuf>,
188 pub poll: Duration,
190 pub max_attempts: usize,
192 pub once: bool,
194 pub merge: Option<String>,
196 pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208 fn default() -> Self {
209 Self {
210 repo: PathBuf::from("."),
211 config: None,
212 poll: POLL,
213 max_attempts: 2,
214 once: false,
215 merge: None,
216 worktrees_root: None,
217 }
218 }
219}
220
221fn max_concurrent(n: usize) -> usize {
226 n.max(1)
227}
228
229#[must_use]
231pub fn status_path() -> PathBuf {
232 crate::run::home().join("daemon.json")
233}
234
235pub fn write_status(status: &Status) -> Result<()> {
237 write_status_to(&status_path(), status)
238}
239
240pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247 }
248 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249 let tmp = path.with_extension("json.tmp");
250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252 Ok(())
253}
254
255pub fn clear_status() {
258 clear_status_at(&status_path());
259}
260
261fn clear_status_at(path: &Path) {
265 let _ = std::fs::remove_file(path);
266}
267
268#[derive(Debug, Clone, Default)]
281pub struct Stop {
282 stopped: Arc<AtomicBool>,
286 busy: Arc<std::sync::atomic::AtomicUsize>,
292 wake: Arc<Notify>,
296 pause: crate::graph::Pause,
299}
300
301impl Stop {
302 #[must_use]
304 pub fn new() -> Self {
305 Self::default()
306 }
307
308 pub fn stop(&self) {
311 self.stopped.store(true, Ordering::SeqCst);
312 self.wake.notify_one();
316 }
317
318 #[must_use]
320 pub fn stopped(&self) -> bool {
321 self.stopped.load(Ordering::SeqCst)
322 }
323
324 #[must_use]
332 pub fn finishing(&self) -> bool {
333 self.stopped() && self.busy_now()
334 }
335
336 pub fn park(&self) {
347 self.pause.park();
348 self.stop();
349 }
350
351 #[must_use]
353 pub fn parking(&self) -> bool {
354 self.pause.parked()
355 }
356
357 #[must_use]
359 pub fn pause(&self) -> crate::graph::Pause {
360 self.pause.clone()
361 }
362
363 #[must_use]
369 pub fn busy_now(&self) -> bool {
370 self.busy.load(Ordering::SeqCst) > 0
371 }
372
373 fn enter(&self) {
375 self.busy.fetch_add(1, Ordering::SeqCst);
376 }
377
378 fn exit(&self) {
381 self.busy.fetch_sub(1, Ordering::SeqCst);
382 }
383
384 async fn idle(&self, poll: Duration) {
386 tokio::select! {
387 () = tokio::time::sleep(poll) => {}
388 () = self.wake.notified() => {}
389 }
390 }
391}
392
393#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402 pub schema: u32,
404 pub pid: Option<u32>,
406 pub started_at: Option<Timestamp>,
408 pub updated_at: Option<Timestamp>,
410 pub idle: bool,
412 #[serde(deserialize_with = "de_current")]
424 pub current: Vec<Current>,
425 pub completed: u64,
427 pub polls: u64,
429}
430
431fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435 D: serde::Deserializer<'de>,
436{
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum Shape {
440 Many(Vec<Current>),
441 One(Current),
442 }
443 Ok(
444 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445 Shape::Many(v) => v,
446 Shape::One(c) => vec![c],
447 }),
448 )
449}
450
451impl Reading {
452 #[must_use]
455 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456 self.updated_at
457 .map(|at| (now.as_second() - at.as_second()).max(0))
458 }
459
460 #[must_use]
464 pub fn running(&self, now: Timestamp) -> bool {
465 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466 }
467}
468
469#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478 serde_json::from_str(&body).ok()
479}
480
481#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494 read_status(home)
495 .filter(|reading| reading.running(now))
496 .map(|reading| reading.current)
497 .unwrap_or_default()
498}
499
500#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503 current_work(home, now).iter().any(|c| c.run == run)
504}
505
506#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517 current_work(home, now)
518 .iter()
519 .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525 current_work(home, now).iter().any(|c| c.task == task)
526}
527
528pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580 F: Fn(u32) -> bool,
581{
582 let this_process = std::process::id();
583 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584 .into_iter()
585 .flatten()
586 .flatten()
587 .map(|e| e.path())
588 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589 .filter(|p| {
590 match std::fs::read_to_string(p)
591 .ok()
592 .and_then(|body| body.trim().parse::<u32>().ok())
593 {
594 Some(pid) if pid == this_process => false,
598 Some(pid) => !pid_alive(pid),
599 None => p
600 .metadata()
601 .and_then(|m| m.modified())
602 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603 .is_ok_and(|age| age >= older_than),
604 }
605 })
606 .filter(|p| std::fs::remove_file(p).is_ok())
607 .filter_map(|p| {
608 p.file_stem()
609 .and_then(|s| s.to_str())
610 .map(std::borrow::ToOwned::to_owned)
611 })
612 .collect();
613 swept.sort_unstable();
614 swept
615}
616
617fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622 task.status == TaskStatus::Running
623 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624 && !is_working_on_task(home, &task.id, now)
625}
626
627fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630 queue
631 .list()
632 .into_iter()
633 .filter(|t| is_stalled(t, home, now))
634 .collect()
635}
636
637fn queued_tasks(queue: &Queue) -> Vec<Task> {
643 queue
644 .list()
645 .into_iter()
646 .filter(|t| t.status == TaskStatus::Queued)
647 .collect()
648}
649
650fn finished_tasks(queue: &Queue) -> Vec<Task> {
653 queue
654 .list()
655 .into_iter()
656 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657 .collect()
658}
659
660fn resolve_blockers(queue: &Queue, questions: &Questions) {
677 for listed in queue.list() {
678 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679 continue;
680 }
681 let Ok(_claim) = queue.claim(&listed.id) else {
682 continue;
683 };
684 let Ok(mut task) = queue.get(&listed.id) else {
685 continue;
686 };
687 if task.status != TaskStatus::Blocked {
688 continue;
689 }
690 let deleted = queue.apply_deleted_blockers(&mut task);
694 if !deleted.is_empty() {
695 record(queue, &mut task);
696 for id in &deleted {
697 queue.note_dependency_deleted(&task, id);
698 }
699 if task.status != TaskStatus::Blocked {
700 continue;
701 }
702 }
703 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
704 if !missing.is_empty() {
705 let language = language_of(&task, Path::new("."));
706 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
707 &task.blocked_by,
708 &missing,
709 &language,
710 )));
711 record(queue, &mut task);
712 continue;
713 }
714 if let Some(q) = task.blocked_by.iter().find_map(|id| {
717 questions.get(id).ok().filter(|q| {
718 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
719 })
720 }) {
721 let language = language_of(&task, Path::new("."));
722 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
723 record(queue, &mut task);
724 continue;
725 }
726 let mut changed = false;
727 for id in task.blocked_by.clone() {
728 if let Ok(dep) = queue.get(&id) {
729 if dep.status == TaskStatus::Done {
730 task.unblock(&id);
731 changed = true;
732 }
733 continue;
734 }
735 if let Ok(q) = questions.get(&id)
736 && q.status == ask::QuestionStatus::Answered
737 {
738 let answer = match &q.answer {
739 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
740 None => String::new(),
741 };
742 task.record_answer(q.summary.clone(), answer);
743 task.unblock(&id);
744 changed = true;
745 }
746 }
747 if changed {
748 record(queue, &mut task);
749 }
750 }
751}
752
753fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
755 if crate::lang::is_japanese(language) {
756 format!(
757 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
758 q.short(),
759 q.summary
760 )
761 } else {
762 format!(
763 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
764 q.short(),
765 q.summary
766 )
767 }
768}
769
770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
773pub(crate) enum ActionStanding {
774 NoAction,
776 Pending,
778 Applied,
781 Stale,
783 Busy,
785}
786
787impl ActionStanding {
788 pub(crate) fn daemon_owns(self) -> bool {
790 matches!(self, Self::Pending | Self::Applied | Self::Stale)
791 }
792}
793
794pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
798 if q.chosen_action().is_none() {
799 ActionStanding::NoAction
800 } else if task.action_applied(&q.id) {
801 ActionStanding::Applied
802 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
803 ActionStanding::Stale
804 } else if matches!(
805 task.status,
806 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
807 ) {
808 ActionStanding::Busy
809 } else {
810 ActionStanding::Pending
811 }
812}
813
814#[derive(Debug, Clone, PartialEq, Eq)]
816enum ActionDecision {
817 Skip,
819 Resume(String),
821 Requeue,
823 Done,
825 Stale,
828 Refuse(String),
831}
832
833fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
841where
842 F: FnOnce(&str) -> Result<RunState>,
843{
844 let Some(action) = q.chosen_action() else {
845 return ActionDecision::Skip;
846 };
847 if task.action_applied(&q.id)
848 || matches!(
849 task.status,
850 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
851 )
852 {
853 return ActionDecision::Skip;
854 }
855 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
858 return ActionDecision::Stale;
859 }
860 match action {
861 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
862 ask::ChoiceAction::Done => ActionDecision::Done,
863 ask::ChoiceAction::Resume { run } => {
864 if task.runs.last() != Some(run) {
865 return ActionDecision::Refuse((p.resume_not_latest)(
866 q.short(),
867 ask::short_id(run),
868 ));
869 }
870 match load(run) {
871 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
872 ActionDecision::Resume(run.clone())
873 }
874 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
875 q.short(),
876 ask::short_id(run),
877 )),
878 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
879 q.short(),
880 ask::short_id(run),
881 &format!("{e:#}"),
882 )),
883 }
884 }
885 }
886}
887
888struct Phrases {
902 graph_stopped: fn(&str, &str) -> String,
904 quorum_lost: &'static str,
905 quota_took_out: &'static str,
907 run_ended: &'static str,
909 waiting_for_answer: &'static str,
911 recovered_running: &'static str,
912 no_run_to_recover: &'static str,
913 could_not_start: &'static str,
914 resume_not_latest: fn(&str, &str) -> String,
915 resume_cannot_progress: fn(&str, &str) -> String,
916 resume_unreadable: fn(&str, &str, &str) -> String,
917 handover_refused: fn(&crate::handover::Refused) -> String,
920 handover_hint: &'static str,
922 reviewers_never_answered: fn(usize, usize) -> String,
925}
926
927const PHRASES_EN: Phrases = Phrases {
928 graph_stopped: |status, detail| {
929 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
930 },
931 quorum_lost: "the judging panel lost its quorum",
932 quota_took_out: "; quota took out ",
933 run_ended: "run ended ",
934 waiting_for_answer: " - waiting for operator answer to question ",
935 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
936 no_run_to_recover: "task was `running` with no live daemon and no readable \
937 run to recover; held for a human to check what happened",
938 could_not_start: "could not start the run: ",
939 resume_not_latest: |q, run| {
940 format!("question {q} asked to resume run {run}, which is not this task's latest run")
941 },
942 resume_cannot_progress: |q, run| {
943 format!("question {q} asked to resume run {run}, which cannot make progress")
944 },
945 resume_unreadable: |q, run, e| {
946 format!("question {q} asked to resume run {run}, which could not be read: {e}")
947 },
948 handover_refused: |r| r.to_string(),
949 handover_hint: " (clean up the other worktree, then release the task from the queue)",
950 reviewers_never_answered: |missing, rounds| {
951 format!(
952 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
953 refusing to call it clean"
954 )
955 },
956};
957
958const PHRASES_JA: Phrases = Phrases {
959 graph_stopped: |status, detail| {
960 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
961 },
962 quorum_lost: "審査パネルが定足数を失いました",
963 quota_took_out: "。クォータで脱落: ",
964 run_ended: "run 終了: ",
965 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
966 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
967 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
968 何が起きたか人が確認するため保留にしました",
969 could_not_start: "run を開始できませんでした: ",
970 resume_not_latest: |q, run| {
971 format!(
972 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
973 )
974 },
975 resume_cannot_progress: |q, run| {
976 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
977 },
978 resume_unreadable: |q, run, e| {
979 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
980 },
981 handover_refused: |r| {
982 use crate::handover::Refused;
983 match r {
984 Refused::Foreign { branch, path, why } => format!(
985 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
986 削除しません。不要なら `git worktree remove` でその worktree を削除して\
987 から、やり直してください(詳細: {why})"
988 ),
989 Refused::Unsafe { branch, path, why } => format!(
990 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
991 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
992 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
993 ),
994 Refused::ReleaseFailed { branch, path, run } => format!(
995 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
996 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
997 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
998 ),
999 }
1000 },
1001 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1002 reviewers_never_answered: |missing, rounds| {
1003 format!(
1004 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1005 クリーンとは認めません"
1006 )
1007 },
1008};
1009
1010fn phrases(language: &str) -> &'static Phrases {
1011 if crate::lang::is_japanese(language) {
1012 &PHRASES_JA
1013 } else {
1014 &PHRASES_EN
1015 }
1016}
1017
1018fn language_of(task: &Task, fallback: &Path) -> String {
1022 crate::lang::of_repo(&repo_for(task, fallback))
1023}
1024
1025pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1029 if q.node == crate::conduct::NODE {
1030 return tasks.iter().find(|t| t.id == q.run);
1031 }
1032 tasks.iter().find(|t| t.runs.contains(&q.run))
1033}
1034
1035fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1044 let tasks = queue.list();
1045 for q in questions.list() {
1046 if q.chosen_action().is_none() {
1047 continue;
1048 }
1049 let Some(listed) = task_of_question(&tasks, &q) else {
1050 continue;
1051 };
1052 if listed.action_applied(&q.id) {
1053 continue;
1054 }
1055 let Ok(_claim) = queue.claim(&listed.id) else {
1056 continue;
1057 };
1058 let Ok(mut task) = queue.get(&listed.id) else {
1059 continue;
1060 };
1061 let language = language_of(&task, Path::new("."));
1062 let decision = decide_action(&task, &q, phrases(&language), |id| {
1063 RunState::load_under(id, home)
1064 });
1065 let ran = matches!(
1066 decision,
1067 ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1068 );
1069 if ran && asker_may_still_read(questions, &q, home) {
1070 continue;
1079 }
1080 let done = matches!(decision, ActionDecision::Done);
1081 match decision {
1082 ActionDecision::Skip => continue,
1083 ActionDecision::Resume(run) => {
1084 task.release();
1085 task.resume_override = Some(crate::queue::OperatorResume {
1086 question_id: q.id.clone(),
1087 at: Timestamp::now(),
1088 conductor_rehold: None,
1089 forced: true,
1090 pinned_run: Some(run),
1091 });
1092 }
1093 ActionDecision::Stale => {}
1094 ActionDecision::Requeue => task.requeue(),
1095 ActionDecision::Done => task.succeed(),
1096 ActionDecision::Refuse(why) => {
1097 task.hold_machine(Some(why));
1098 notices::raise(
1099 Notice::warn(
1100 &format!("action:{}", q.id),
1101 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1102 )
1103 .link(Link::Task {
1104 id: task.id.clone(),
1105 }),
1106 );
1107 }
1108 }
1109 task.mark_action_applied(&q.id);
1110 record(queue, &mut task);
1113 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1114 supersede_prior_runs(&task, home);
1115 }
1116 let _ = questions.update(&q.id, |r| {
1119 r.answer_delivered = true;
1120 Ok(())
1121 });
1122 }
1123}
1124
1125fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1129 let now = Timestamp::now();
1130 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1131 return true;
1132 }
1133 q.node != crate::conduct::NODE
1134 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1135 s.seats_active()
1136 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1137 })
1138}
1139
1140fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1151 let tasks = queue.list();
1152 let by_id: std::collections::BTreeMap<&str, &Task> =
1153 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1154 let referenced: std::collections::BTreeSet<&str> = tasks
1155 .iter()
1156 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1157 .collect();
1158
1159 for mut question in questions.list() {
1160 if !question.status.open() || question.node != crate::conduct::NODE {
1161 continue;
1162 }
1163 if referenced.contains(question.id.as_str()) {
1166 continue;
1167 }
1168 let Some(task) = by_id.get(question.run.as_str()) else {
1169 continue;
1170 };
1171 question.abandon(format!(
1172 "task {} no longer waits for this answer",
1173 task.short()
1174 ));
1175 if let Err(e) = questions.put(&mut question) {
1176 tracing::warn!(
1177 "could not retire question {} for task {}: {e:#}",
1178 question.short(),
1179 task.short()
1180 );
1181 }
1182 }
1183}
1184
1185#[derive(Debug, Clone, Copy)]
1192pub struct Verdict {
1193 pub status: RunStatus,
1195 pub left_pr: bool,
1197 pub quota_hit: bool,
1199 pub parked: bool,
1201 pub no_viable_candidates: bool,
1208}
1209
1210pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1267 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1268}
1269
1270fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1272 if verdict.parked {
1278 task.park(detail);
1279 return;
1280 }
1281 match verdict.status {
1282 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1283 RunStatus::AlreadyInBase => task.already_landed(detail),
1284 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1285 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1286 task.stall(detail)
1287 }
1288 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1289 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1290 RunStatus::Blocked => task.fail(detail, max_attempts),
1291 RunStatus::VerifiedNoop => task.handed_off(detail),
1292 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1293 }
1294}
1295
1296pub fn supersede_prior_runs(task: &Task, home: &Path) {
1345 let now = Timestamp::now();
1346 let last_run_succeeded = task
1353 .runs
1354 .last()
1355 .and_then(|id| RunState::load_under(id, home).ok())
1356 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1357 for id in task.superseded_attempts(last_run_succeeded) {
1358 let mut state = match RunState::load_under(id, home) {
1359 Ok(s) => s,
1360 Err(e) => {
1361 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1362 continue;
1363 }
1364 };
1365 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1366 continue;
1367 }
1368 let daemon_claims = is_working_on(home, id, now);
1369 if state.liveness(daemon_claims) == Liveness::Live {
1370 continue;
1371 }
1372 state.status = RunStatus::Superseded;
1373 if let Err(e) = state.save_under(home) {
1374 tracing::warn!("could not mark run {id} superseded: {e:#}");
1375 }
1376 }
1377}
1378
1379fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1401 for task in queue.list() {
1402 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1403 continue;
1404 }
1405 supersede_prior_runs(&task, home);
1406 }
1407}
1408
1409fn settle_and_diagnose(
1416 task: &mut Task,
1417 verdict: Verdict,
1418 detail: &str,
1419 max_attempts: usize,
1420 state: &RunState,
1421) {
1422 let p = phrases(&state.config.graph.language);
1423 settle_in(task, verdict, detail, max_attempts, p);
1424 if task.status == TaskStatus::Held {
1425 task.diagnostic = diagnostic(state);
1426 note_open_question(task, &state.id, p);
1427 }
1428}
1429
1430fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1445 let Some(home) = crate::run::try_home() else {
1446 return;
1447 };
1448 let open = Questions::at(home.join("questions")).open_for(run);
1449 let Some(q) = open.first() else {
1450 return;
1451 };
1452 let base = task.hold_reason.clone().unwrap_or_default();
1453 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1454}
1455
1456fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1467 match last_run {
1468 Some(state) => {
1469 let verdict = Verdict {
1470 status: state.status,
1471 left_pr: state.pr.is_some(),
1472 quota_hit: !state.quota.is_empty(),
1473 parked: state.parked,
1474 no_viable_candidates: state.viable().is_empty(),
1475 };
1476 let detail = format!(
1477 "{}{}",
1478 phrases(&state.config.graph.language).recovered_running,
1479 describe(&state)
1480 );
1481 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1482 }
1483 None => {
1484 let why = phrases(language).no_run_to_recover;
1487 task.last_error = Some(why.to_owned());
1488 task.hold_machine(Some(why.to_owned()));
1491 }
1492 }
1493}
1494
1495fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1517 let mut reclaimed = Vec::new();
1518 for listed in queue.list() {
1519 if listed.status != TaskStatus::Running {
1520 continue;
1521 }
1522 let Ok(_claim) = queue.claim(&listed.id) else {
1523 continue;
1524 };
1525 let Ok(mut task) = queue.get(&listed.id) else {
1529 continue;
1530 };
1531 if task.status != TaskStatus::Running {
1532 continue;
1533 }
1534 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1535 if let Some(state) = &last_run
1545 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1546 {
1547 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1548 }
1549 let language = if last_run.is_none() {
1550 language_of(&task, Path::new("."))
1551 } else {
1552 String::new()
1553 };
1554 reclaim(&mut task, last_run, max_attempts, &language);
1555 if task.status == TaskStatus::Done {
1556 supersede_prior_runs(&task, &crate::run::home());
1557 }
1558 record(queue, &mut task);
1559 reclaimed.push(task.id.clone());
1560 }
1561 reclaimed
1562}
1563
1564fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1596 reclaim_abandoned_runs_with(
1597 home,
1598 now,
1599 crate::proc::pid_status,
1600 crate::proc::process_started_at,
1601 )
1602}
1603
1604fn reclaim_abandoned_runs_with<F, G>(
1610 home: &Path,
1611 now: Timestamp,
1612 query: F,
1613 identity: G,
1614) -> Vec<String>
1615where
1616 F: Fn(u32) -> Option<bool>,
1617 G: Fn(u32) -> Option<String>,
1618{
1619 let mut abandoned = Vec::new();
1620 for entry in std::fs::read_dir(home.join("runs"))
1621 .into_iter()
1622 .flatten()
1623 .flatten()
1624 {
1625 let id = entry.file_name().to_string_lossy().into_owned();
1626 if !crate::run::is_run_id(&id) {
1627 continue;
1628 }
1629 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1637 continue;
1638 };
1639 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1640 continue;
1641 };
1642 if state.status.done() || !state.active_all_overrun(now) {
1643 continue;
1644 }
1645 let daemon_claims = is_working_on(home, &id, now);
1657 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1658 continue;
1659 }
1660 state.abandon("daemon");
1661 if let Err(e) = state.save_under(home) {
1662 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1663 continue;
1664 }
1665 if let Some(notice) = notices::run_ended(&state) {
1668 notices::raise_in(home, notice);
1669 }
1670 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1678 tracing::warn!("abandon questions for {id}: {e:#}");
1679 }
1680 abandoned.push(id);
1681 }
1682 abandoned
1683}
1684
1685pub async fn serve(opts: Opts) -> Result<()> {
1691 serve_until(opts, Stop::new()).await
1692}
1693
1694pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1711 let signal = {
1712 let stop = stop.clone();
1713 tokio::spawn(async move {
1714 if tokio::signal::ctrl_c().await.is_ok() {
1715 stop.stop();
1716 tracing::info!("shutdown requested; a run in flight will be finished first");
1717 }
1718 })
1719 };
1720
1721 let worktrees_root = opts
1722 .worktrees_root
1723 .clone()
1724 .unwrap_or_else(crate::run::default_worktree_root);
1725 let outcome = drive(
1726 &opts,
1727 &Queue::open(),
1728 &status_path(),
1729 &crate::run::home(),
1730 &worktrees_root,
1731 &stop,
1732 )
1733 .await;
1734
1735 signal.abort();
1736 outcome
1737}
1738
1739async fn drive(
1752 opts: &Opts,
1753 queue: &Queue,
1754 status_file: &Path,
1755 home: &Path,
1756 worktrees_root: &Path,
1757 stop: &Stop,
1758) -> Result<()> {
1759 let status = Arc::new(Mutex::new(Status::new()));
1767 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1768 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1769
1770 let daemon_cfg = prepare(&opts.repo, opts)
1776 .map(|c| c.daemon)
1777 .unwrap_or_default();
1778 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1779
1780 let waiter = tokio::spawn(crate::waiter::run(
1785 crate::waiter::Waiter::new(
1786 crate::ask::Questions::at(home.join("questions")),
1787 home.to_path_buf(),
1788 prepare(&opts.repo, opts).ok(),
1789 ),
1790 stop.clone(),
1791 ));
1792
1793 let deputies = tokio::spawn(crate::deputy::run(
1797 crate::deputy::Deputies::new(
1798 crate::ask::Questions::at(home.join("questions")),
1799 home.to_path_buf(),
1800 prepare(&opts.repo, opts).ok(),
1801 opts.repo.clone(),
1802 daemon_cfg.max_deputies,
1803 {
1804 let stop = stop.clone();
1805 Arc::new(move || stop.parking())
1806 },
1807 ),
1808 stop.clone(),
1809 ));
1810
1811 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1814
1815 let release_watch = tokio::spawn(crate::release_watch::run(
1818 crate::release_watch::Watcher::new(
1819 Box::new(crate::release_watch::GhForge),
1820 home.to_path_buf(),
1821 ),
1822 {
1823 let (repo, opts) = (opts.repo.clone(), opts.clone());
1824 move || release_watch_settings(&repo, &opts)
1825 },
1826 stop.clone(),
1827 ));
1828
1829 tracing::info!(
1830 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1831 queue.root().display(),
1832 opts.poll.as_secs(),
1833 opts.max_attempts,
1834 concurrency,
1835 if daemon_cfg.pause_for_interrupts {
1836 ", interrupts enabled"
1837 } else {
1838 ""
1839 }
1840 );
1841
1842 janitor(&opts.repo, opts, home, worktrees_root).await;
1845 resweep_superseded_attempts(queue, home);
1846
1847 let outcome = poll(
1848 opts,
1849 queue,
1850 &status,
1851 home,
1852 worktrees_root,
1853 stop,
1854 DispatchLimits {
1855 max_concurrent: concurrency,
1856 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1857 },
1858 )
1859 .await;
1860
1861 beat.abort();
1862 waiter.abort();
1863 deputies.abort();
1864 fetcher.abort();
1865 release_watch.abort();
1866 clear_status_at(status_file);
1867 outcome
1868}
1869
1870fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
1873 let Ok(cfg) = prepare(repo, opts) else {
1874 return (Vec::new(), 0);
1875 };
1876 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
1877 .into_iter()
1878 .map(|r| r.path)
1879 .collect();
1880 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
1883 let runs = crate::run::home().join("runs");
1884 for id in crate::run::list_ids_in(&runs) {
1885 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
1886 .ok()
1887 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1888 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
1889 known.extend(repo);
1890 }
1891 for k in known {
1892 let k = k.canonicalize().unwrap_or(k);
1893 if k.join(".git").exists() && !paths.contains(&k) {
1894 paths.push(k);
1895 }
1896 }
1897 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
1898 if !paths.contains(&own) {
1899 paths.push(own);
1900 }
1901 (paths, cfg.daemon.release_stall_minutes)
1902}
1903
1904const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
1906
1907async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
1911 while !stop.stopped() {
1912 let (interval, roots) = match prepare(&repo, &opts) {
1913 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
1914 Err(_) => (0, Vec::new()),
1915 };
1916 if interval > 0 && !roots.is_empty() {
1917 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
1918 tracing::debug!("fetch origins: {r:?}");
1919 }
1920 let wait = if interval > 0 { interval } else { 60 };
1922 let mut slept = 0;
1923 while slept < wait && !stop.stopped() {
1924 tokio::time::sleep(Duration::from_secs(1)).await;
1925 slept += 1;
1926 }
1927 }
1928}
1929
1930async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1936 loop {
1937 tokio::time::sleep(HEARTBEAT).await;
1938 let snapshot = {
1939 let mut guard = lock(&status);
1940 guard.updated_at = Timestamp::now();
1941 guard.clone()
1942 };
1943 if let Err(e) = write_status_to(&path, &snapshot) {
1944 tracing::warn!("could not refresh the daemon status file: {e:#}");
1947 }
1948 }
1949}
1950
1951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1954enum LandResume {
1955 NotLanding,
1958 StillWaiting,
1963 Ready,
1967}
1968
1969fn land_resume_state(task: &Task) -> LandResume {
1973 let Some(run_id) = task.runs.last() else {
1974 return LandResume::NotLanding;
1975 };
1976 let Ok(state) = RunState::load(run_id) else {
1977 return LandResume::NotLanding;
1978 };
1979 if !state.parked {
1980 return LandResume::NotLanding;
1981 }
1982 let node = if state.status == RunStatus::Landing {
1986 land::APPROVAL_NODE
1987 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
1988 crate::github_text::ASK_NODE
1989 } else {
1990 return LandResume::NotLanding;
1991 };
1992 let store = ask::Questions::open();
1993 let waiting = store
1994 .list()
1995 .into_iter()
1996 .filter(|q| &q.run == run_id && q.node == node)
1997 .max_by(|a, b| a.id.cmp(&b.id));
1998 let Some(mut q) = waiting else {
1999 return LandResume::Ready;
2000 };
2001 if !q.status.open() {
2002 return LandResume::Ready;
2003 }
2004 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2011 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2012 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2013 q.abandon(format!(
2014 "no answer within {}s of asking",
2015 timeout.as_secs().max(1)
2016 ));
2017 if store.put(&mut q).is_ok() {
2020 return LandResume::Ready;
2021 }
2022 }
2023 LandResume::StillWaiting
2024}
2025
2026const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2034
2035const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2047
2048struct InFlightGuard<'a> {
2061 status: &'a Arc<Mutex<Status>>,
2062 stop: &'a Stop,
2063 task_id: &'a str,
2064}
2065
2066impl Drop for InFlightGuard<'_> {
2067 fn drop(&mut self) {
2068 lock(self.status).current.retain(|c| c.task != self.task_id);
2069 self.stop.exit();
2070 }
2071}
2072
2073#[derive(Debug, Clone, PartialEq, Eq)]
2095enum Interrupt {
2096 Idle,
2098 Parking {
2110 parked: Vec<String>,
2111 interrupt_task: String,
2112 },
2113 Running {
2121 parked: Vec<String>,
2122 interrupt_task: String,
2123 },
2124 Resuming { parked: Vec<String> },
2131}
2132
2133fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2154 match state {
2155 Interrupt::Idle => {
2156 if in_flight.len() != 1 {
2168 return Interrupt::Idle;
2169 }
2170 match runnable.iter().find(|t| t.interrupt) {
2171 Some(t) => Interrupt::Parking {
2172 parked: in_flight.to_vec(),
2173 interrupt_task: t.id.clone(),
2174 },
2175 None => Interrupt::Idle,
2176 }
2177 }
2178 Interrupt::Parking {
2179 parked,
2180 interrupt_task,
2181 } => {
2182 if in_flight.iter().any(|id| parked.contains(id)) {
2183 Interrupt::Parking {
2185 parked,
2186 interrupt_task,
2187 }
2188 } else if in_flight.contains(&interrupt_task) {
2189 Interrupt::Running {
2190 parked,
2191 interrupt_task,
2192 }
2193 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2194 Interrupt::Parking {
2198 parked,
2199 interrupt_task,
2200 }
2201 } else {
2202 Interrupt::Resuming { parked }
2207 }
2208 }
2209 Interrupt::Running {
2210 parked,
2211 interrupt_task,
2212 } => {
2213 if in_flight.contains(&interrupt_task) {
2214 Interrupt::Running {
2215 parked,
2216 interrupt_task,
2217 }
2218 } else {
2219 Interrupt::Resuming { parked }
2225 }
2226 }
2227 Interrupt::Resuming { parked } => {
2228 if in_flight.iter().any(|id| parked.contains(id)) {
2229 Interrupt::Idle
2235 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2236 Interrupt::Resuming { parked }
2237 } else {
2238 Interrupt::Idle
2241 }
2242 }
2243 }
2244}
2245
2246fn advance_interrupt_tick(
2252 enabled: bool,
2253 state: Interrupt,
2254 in_flight: &[String],
2255 runnable: &[Task],
2256) -> Interrupt {
2257 if !enabled {
2258 return Interrupt::Idle;
2259 }
2260 advance_interrupt(state, in_flight, runnable)
2261}
2262
2263fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2268 match state {
2269 Interrupt::Idle => candidates,
2270 Interrupt::Parking {
2271 parked,
2272 interrupt_task,
2273 } => {
2274 if in_flight.iter().any(|id| parked.contains(id)) {
2275 Vec::new()
2276 } else {
2277 candidates
2278 .into_iter()
2279 .filter(|t| &t.id == interrupt_task)
2280 .collect()
2281 }
2282 }
2283 Interrupt::Running { .. } => Vec::new(),
2284 Interrupt::Resuming { parked } => candidates
2292 .into_iter()
2293 .find(|t| parked.contains(&t.id))
2294 .into_iter()
2295 .collect(),
2296 }
2297}
2298
2299struct DispatchLimits {
2303 max_concurrent: usize,
2306 pause_for_interrupts: bool,
2308}
2309
2310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2319enum PermitKind {
2320 None,
2325 Urgent,
2332 Ordinary,
2335}
2336
2337fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2340 if priority {
2341 PermitKind::None
2342 } else if urgent {
2343 PermitKind::Urgent
2344 } else {
2345 PermitKind::Ordinary
2346 }
2347}
2348
2349async fn poll(
2368 opts: &Opts,
2369 queue: &Queue,
2370 status: &Arc<Mutex<Status>>,
2371 home: &Path,
2372 worktrees_root: &Path,
2373 stop: &Stop,
2374 limits: DispatchLimits,
2375) -> Result<()> {
2376 let DispatchLimits {
2377 max_concurrent,
2378 pause_for_interrupts,
2379 } = limits;
2380 let mut attempted: Vec<String> = Vec::new();
2385 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2386 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2394 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2400 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2401 let mut conductor = Conductor::new();
2402 let mut cache_last_checked: Option<Timestamp> = None;
2405 let mut interrupt = Interrupt::Idle;
2407 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2413 std::collections::HashMap::new();
2414
2415 while !stop.stopped() {
2416 lock(status).polls += 1;
2417
2418 while let Some(result) = inflight.try_join_next() {
2423 if let Err(e) = result {
2424 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2425 notices::raise(Notice::error(
2426 "loop:attempt",
2427 "A queued attempt ended abnormally; check the task it was running.",
2428 ));
2429 }
2430 }
2431
2432 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2433 if !swept.is_empty() {
2434 tracing::warn!(
2435 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2436 swept.len(),
2437 swept.join(", ")
2438 );
2439 }
2440 let now = Timestamp::now();
2445
2446 if !stop.busy_now() {
2451 maybe_prune_cache_between_runs(
2452 &opts.repo,
2453 opts,
2454 home,
2455 stop,
2456 &mut cache_last_checked,
2457 now,
2458 )
2459 .await;
2460 }
2461
2462 let stalled = stalled_tasks(queue, home, now);
2463 let stalled_ids: std::collections::BTreeSet<_> =
2464 stalled.iter().map(|task| task.id.clone()).collect();
2465 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2466 if !reclaimed.is_empty() {
2467 tracing::warn!(
2468 "reclaimed {} task(s) left `running` by a daemon that never \
2469 recorded the outcome: {}",
2470 reclaimed.len(),
2471 reclaimed.join(", ")
2472 );
2473 }
2474 let abandoned_runs = reclaim_abandoned_runs(home, now);
2475 if !abandoned_runs.is_empty() {
2476 tracing::warn!(
2477 "failed {} run(s) left behind by a killed process, past every \
2478 active seat's own timeout: {}",
2479 abandoned_runs.len(),
2480 abandoned_runs.join(", ")
2481 );
2482 }
2483
2484 let questions = Questions::at(home.join("questions"));
2489
2490 resolve_blockers(queue, &questions);
2493 apply_choice_actions(queue, &questions, home);
2494 reconcile_task_questions(queue, &questions);
2495
2496 let finished: Vec<Task> = finished_tasks(queue)
2502 .into_iter()
2503 .filter(|task| !stalled_ids.contains(&task.id))
2504 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2508 .collect();
2509 let queued = queued_tasks(queue);
2510 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2514 && conductor.worth_a_look(queue, &stalled, &finished)
2515 {
2516 match prepare(&opts.repo, opts) {
2517 Ok(cfg) => {
2518 conductor
2519 .maybe_run(
2520 &cfg,
2521 &opts.repo,
2522 queue,
2523 &questions,
2524 home,
2525 &queued,
2526 &stalled,
2527 &finished,
2528 opts.max_attempts,
2529 )
2530 .await;
2531 }
2532 Err(e) => {
2533 tracing::warn!("conductor: no config: {e:#}");
2534 notices::raise(Notice::warn(
2535 "loop:no-config",
2536 "The loop could not read this repository's config, so held tasks are not being triaged.",
2537 ));
2538 }
2539 }
2540 }
2541
2542 let candidates: Vec<Task> = runnable(queue)
2543 .into_iter()
2544 .filter(|t| !opts.once || !attempted.contains(&t.id))
2545 .collect();
2546
2547 let in_flight: Vec<String> = lock(status)
2552 .current
2553 .iter()
2554 .map(|c| c.task.clone())
2555 .collect();
2556 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2557
2558 interrupt =
2559 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2560 if let Interrupt::Parking {
2561 parked,
2562 interrupt_task,
2563 } = &interrupt
2564 {
2565 let reason = format!(
2566 "task {} asked to run first",
2567 crate::run::short_of(interrupt_task)
2568 );
2569 for id in parked {
2570 if let Some(pause) = interrupt_pauses.get(id) {
2571 pause.park_because(reason.clone());
2572 }
2573 }
2574 }
2575 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2576
2577 let cooling_down =
2578 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2579
2580 let mut started_any = false;
2581 for candidate in candidates {
2582 if stop.stopped() {
2583 break;
2584 }
2585
2586 let resume = land_resume_state(&candidate);
2587 if resume == LandResume::StillWaiting {
2588 continue;
2589 }
2590 let priority = resume == LandResume::Ready;
2591
2592 if !priority && cooling_down {
2593 continue;
2594 }
2595 let permit = match permit_kind(priority, candidate.urgent) {
2596 PermitKind::None => None,
2597 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2598 Ok(p) => Some(p),
2599 Err(_) => continue,
2605 },
2606 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2607 Ok(p) => Some(p),
2608 Err(_) => continue,
2612 },
2613 };
2614
2615 let Ok(claim) = queue.claim(&candidate.id) else {
2620 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2621 continue;
2622 };
2623 let mut task = match queue.get(&candidate.id) {
2626 Ok(t) if t.status.runnable() => t,
2627 Ok(_) => continue,
2628 Err(e) => {
2629 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2630 continue;
2631 }
2632 };
2633 let task_id = task.id.clone();
2634 attempted.push(task_id.clone());
2635 lock(status).idle = false;
2636 stop.enter();
2639 started_any = true;
2640
2641 let run_pause = crate::graph::Pause::new();
2645 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2646
2647 let opts = opts.clone();
2648 let queue = queue.clone();
2649 let status = Arc::clone(status);
2650 let stop = stop.clone();
2651 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2652 inflight.spawn(async move {
2653 let _claim = claim;
2657 let _permit = permit;
2658 let _inflight = InFlightGuard {
2660 status: &status,
2661 stop: &stop,
2662 task_id: &task_id,
2663 };
2664 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2665 lock(&status).completed += 1;
2666 let now = Timestamp::now();
2672 if let Some(until) = cooldown_until("a, now) {
2673 let wait = until.as_second() - now.as_second();
2674 *lock("a_cooldown_until) = Some(until);
2675 let hint = quota
2676 .iter()
2677 .find(|q| q.reset.is_some())
2678 .and_then(|q| q.reset.as_deref());
2679 match hint {
2680 Some(h) => tracing::warn!(
2681 "quota hit; waiting {wait}s before taking another ordinary task \
2682 (CLI reported reset: {h})"
2683 ),
2684 None => tracing::warn!(
2685 "quota hit; waiting {wait}s before taking another ordinary task \
2686 (no reset hint reported)"
2687 ),
2688 }
2689 }
2690 });
2691 }
2692
2693 if started_any {
2694 continue;
2695 }
2696
2697 if stop.busy_now() {
2698 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2703 continue;
2704 }
2705
2706 lock(status).idle = true;
2708 if opts.once {
2709 janitor(&opts.repo, opts, home, worktrees_root).await;
2713 resweep_superseded_attempts(queue, home);
2714 triage_held(queue, home, opts).await;
2715 break;
2716 }
2717 stop.idle(opts.poll).await;
2718 if stop.stopped() {
2719 continue;
2720 }
2721 janitor(&opts.repo, opts, home, worktrees_root).await;
2727 resweep_superseded_attempts(queue, home);
2728 triage_held(queue, home, opts).await;
2729 }
2730
2731 while let Some(result) = inflight.join_next().await {
2736 if let Err(e) = result {
2737 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2738 notices::raise(Notice::error(
2739 "loop:attempt",
2740 "A queued attempt ended abnormally; check the task it was running.",
2741 ));
2742 }
2743 }
2744 Ok(())
2745}
2746
2747async fn attempt(
2753 opts: &Opts,
2754 queue: &Queue,
2755 status: &Arc<Mutex<Status>>,
2756 stop: &Stop,
2757 interrupt_pause: crate::graph::Pause,
2758 task: &mut Task,
2759) -> Vec<QuotaLoss> {
2760 let repo = repo_for(task, &opts.repo);
2761 tracing::info!(
2762 "task {} — {} (repo {})",
2763 task.short(),
2764 task.title,
2765 repo.display()
2766 );
2767
2768 let explicit = match &task.overrides {
2772 Some(o) => o.config.as_deref(),
2773 None => opts.config.as_deref(),
2774 };
2775 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2776 let reason = format!("[config] {e:#}");
2777 task.last_error = Some(reason.clone());
2778 task.hold_machine(Some(reason.clone()));
2779 record(queue, task);
2780 tracing::warn!("holding {}: {reason}", task.short());
2781 return Vec::new();
2782 }
2783 let mut config = match prepare_for(&repo, opts, task) {
2784 Ok(c) => c,
2785 Err(e) => {
2786 task.attempts += 1;
2790 task.fail(format!("config: {e:#}"), opts.max_attempts);
2791 record(queue, task);
2792 return Vec::new();
2793 }
2794 };
2795 apply_solo(&mut config, task);
2796 let p = phrases(&config.graph.language);
2797 let start_failed = p.could_not_start;
2798
2799 if let Some(reason) = disk_gate(&repo, &config) {
2807 task.last_error = Some(reason.clone());
2808 task.hold_machine(Some(reason.clone()));
2809 record(queue, task);
2810 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2811 notices::raise(
2814 Notice::warn(
2815 &format!("disk:{}", repo.display()),
2816 "A task was held for want of free disk space; free some, then release it from the queue.",
2817 )
2818 .link(Link::Task {
2819 id: task.id.clone(),
2820 }),
2821 );
2822 return Vec::new();
2823 }
2824
2825 let unfinished = (!task.fresh_start)
2845 .then(|| unfinished_run(&task.runs, task.short()))
2846 .flatten();
2847 let review_branch = task.review_branch.take();
2853 let branch_exists = match &review_branch {
2854 Some(branch) => crate::git::branch_exists(&repo, branch)
2855 .await
2856 .unwrap_or(false),
2857 None => false,
2858 };
2859 let starter = match (&review_branch, &unfinished, &task.review_of) {
2863 (None, None, Some(branch)) => Starter::Review(branch.clone()),
2864 _ => choose_starter(
2865 review_branch.as_deref(),
2866 branch_exists,
2867 unfinished.as_deref(),
2868 ),
2869 };
2870 let attachments = match task_attachments(queue, task) {
2875 Ok(a) => a,
2876 Err(e) => {
2877 task.attempts += 1;
2878 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2879 record(queue, task);
2880 return Vec::new();
2881 }
2882 };
2883 let started = match &starter {
2884 Starter::Review(branch) => {
2885 tracing::info!(
2886 "task {} reopens `{branch}` as a review-only pass",
2887 task.short()
2888 );
2889 let takeover = crate::handover::Takeover {
2892 earlier: task.earlier_attempts().to_vec(),
2893 home: crate::run::home(),
2894 choice: take_divergence_answer(branch, &config.merge.remote, task),
2895 };
2896 Runner::review_taking_over(
2897 &repo,
2898 branch,
2899 config,
2900 Some(takeover),
2901 crate::run::Origin::queue(&task.id),
2902 )
2903 .await
2904 }
2905 Starter::Resume(id) => {
2906 tracing::info!("resuming run {id} rather than competing again");
2907 Runner::resume(id).map(|mut r| {
2908 if let Some(instruction) =
2909 prepare_instruction(&starter, Some(&r.state.instruction), task)
2910 {
2911 r.state.instruction = instruction;
2912 }
2913 r.state.attachments = attachments.clone();
2914 if let Some(mode) = task
2917 .overrides
2918 .as_ref()
2919 .and_then(|o| o.merge.as_deref())
2920 .and_then(|m| merge_mode(m).ok())
2921 {
2922 r.state.config.merge.mode = mode;
2923 }
2924 r
2925 })
2926 }
2927 Starter::Start => {
2928 if let Some(branch) = &review_branch {
2929 tracing::warn!(
2930 "conductor chose review for task {} but branch `{branch}` no longer \
2931 exists; requeuing as a fresh competition instead",
2932 task.short()
2933 );
2934 }
2935 let instruction = prepare_instruction(&starter, None, task)
2936 .unwrap_or_else(|| task.instruction.clone());
2937 Runner::start_naming(
2938 &repo,
2939 instruction,
2940 &task.title,
2941 config,
2942 crate::run::Origin::queue(&task.id),
2943 )
2944 .await
2945 .map(|mut r| {
2946 r.state.attachments = attachments.clone();
2947 r
2948 })
2949 }
2950 };
2951 let mut runner = match started {
2952 Ok(r) => r,
2953 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2957 let detail = match e.downcast_ref::<crate::handover::Refused>() {
2958 Some(r) => (p.handover_refused)(r),
2959 None => format!("{e:#}"),
2960 };
2961 let reason = format!("{start_failed}{detail}");
2962 task.last_error = Some(reason.clone());
2963 let branch = match &starter {
2966 Starter::Review(branch) => Some(branch.clone()),
2967 _ => None,
2968 };
2969 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
2973 record(queue, task);
2974 tracing::warn!(
2975 "holding {} for a branch it cannot take over: {e:#}",
2976 task.short()
2977 );
2978 return Vec::new();
2979 }
2980 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
2985 let d = e
2986 .downcast_ref::<crate::reconcile::Diverged>()
2987 .expect("checked by the guard");
2988 let mut q = ask::Question::new(
2989 task.id.clone(),
2990 crate::reconcile::NODE.to_owned(),
2991 crate::reconcile::SEAT.to_owned(),
2992 d.summary(),
2993 d.detail(),
2994 d.choices(),
2995 );
2996 match Questions::open().put(&mut q) {
2997 Ok(()) => {
2998 task.last_error = Some(format!("{e:#}"));
2999 task.review_branch = Some(d.branch.clone());
3002 task.block(vec![q.id.clone()], Some(d.summary()));
3003 }
3004 Err(put) => {
3005 tracing::warn!("could not file the divergence question: {put:#}");
3006 task.attempts += 1;
3007 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3008 }
3009 }
3010 record(queue, task);
3011 return Vec::new();
3012 }
3013 Err(e) => {
3014 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3020 && let Starter::Review(branch) = &starter
3021 {
3022 task.review_branch = Some(branch.clone());
3023 task.last_error = Some(format!("{start_failed}{e:#}"));
3024 task.status = crate::queue::TaskStatus::Failed;
3025 record(queue, task);
3026 return Vec::new();
3027 }
3028 task.attempts += 1;
3029 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3030 record(queue, task);
3031 return Vec::new();
3032 }
3033 };
3034 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3037 if runner.state.origin_chat.is_none() {
3038 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3039 }
3040 runner.on_pause(stop.pause());
3042 runner.watch_interrupt(interrupt_pause);
3046
3047 let run = runner.state.id.clone();
3050 task.start(run.clone());
3051 record(queue, task);
3052 lock(status).current.push(Current {
3053 task: task.id.clone(),
3054 run,
3055 });
3056
3057 let quota_before = runner.state.quota.clone();
3060 let result = runner.execute().await;
3061 finish_attempt(
3062 opts.max_attempts,
3063 queue,
3064 task,
3065 &runner.state,
3066 "a_before,
3067 result,
3068 )
3069}
3070
3071pub fn finish_attempt(
3076 max_attempts: usize,
3077 queue: &Queue,
3078 task: &mut Task,
3079 state: &RunState,
3080 quota_before: &[QuotaLoss],
3081 result: Result<()>,
3082) -> Vec<QuotaLoss> {
3083 let detail = match result {
3084 Ok(()) => describe(state),
3085 Err(e) => format!("{e:#}"),
3086 };
3087 let fresh = losses_this_attempt(quota_before, &state.quota);
3088 let verdict = Verdict {
3089 status: state.status,
3090 left_pr: state.pr.is_some(),
3093 quota_hit: !fresh.is_empty(),
3099 parked: state.parked,
3103 no_viable_candidates: state.viable().is_empty(),
3106 };
3107 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3108 if task.status == TaskStatus::Done {
3109 supersede_prior_runs(task, &crate::run::home());
3110 }
3111 record(queue, task);
3112 tracing::info!(
3113 "task {} is {} after run {} ({})",
3114 task.short(),
3115 task.status.as_str(),
3116 state.short(),
3117 label(state.status)
3118 );
3119 fresh
3120}
3121
3122pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3126 let waits_on_owner = withheld_text_wait(task).is_some();
3131 if task.status.runnable() && !waits_on_owner {
3132 let why = task.last_error.clone().map_or_else(
3133 || "the run did not finish".to_owned(),
3134 |e| format!("the run did not finish: {e}"),
3135 );
3136 task.hold_manual(Some(format!(
3137 "{why}. It was started by hand, so it is not retried \
3138 automatically; `magi task release` retries it."
3139 )));
3140 record(queue, task);
3141 }
3142}
3143
3144#[must_use]
3148pub fn loop_would_resume(run: &str) -> bool {
3149 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3150}
3151
3152#[must_use]
3162pub fn foreign_loop(
3163 reading: Option<&Reading>,
3164 now: Timestamp,
3165 own_pid: u32,
3166) -> Option<Option<u32>> {
3167 let reading = reading.filter(|r| r.running(now))?;
3168 match reading.pid {
3169 Some(pid) if pid == own_pid => None,
3170 pid => Some(pid),
3171 }
3172}
3173
3174pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3189 let status = Arc::new(Mutex::new(Status::new()));
3190 let stop = Stop::new();
3191 attempt(
3192 opts,
3193 queue,
3194 &status,
3195 &stop,
3196 crate::graph::Pause::new(),
3197 task,
3198 )
3199 .await;
3200 let mut resumes = 0;
3209 while resumes < MAX_WITHHELD_RESUMES {
3210 let Some(timeout) = withheld_text_wait(task) else {
3211 break;
3212 };
3213 eprintln!(
3214 "waiting for the owner's answer on a withheld pull request text \
3215 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3216 );
3217 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3220 let ready = loop {
3221 match land_resume_state(task) {
3222 LandResume::StillWaiting if std::time::Instant::now() < limit => {
3223 tokio::time::sleep(WITHHELD_POLL).await;
3224 }
3225 LandResume::Ready => break true,
3226 _ => break false,
3227 }
3228 };
3229 if !ready {
3230 break;
3231 }
3232 resumes += 1;
3233 attempt(
3234 opts,
3235 queue,
3236 &status,
3237 &stop,
3238 crate::graph::Pause::new(),
3239 task,
3240 )
3241 .await;
3242 }
3243 hold_if_runnable(queue, task);
3244}
3245
3246const MAX_WITHHELD_RESUMES: u32 = 3;
3249
3250const WITHHELD_POLL: Duration = Duration::from_secs(15);
3252
3253fn withheld_text_wait(task: &Task) -> Option<u64> {
3256 let id = task.runs.last()?;
3257 let s = RunState::load(id).ok()?;
3258 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3259 .then_some(s.config.graph.answer_timeout)
3260}
3261
3262fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3272 after
3273 .iter()
3274 .filter(|q| !before.contains(q))
3275 .cloned()
3276 .collect()
3277}
3278
3279fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3282 if quota.is_empty() {
3283 return None;
3284 }
3285 let with_hint = quota.iter().find(|q| q.reset.is_some());
3286 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3287 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3288 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3289 Some(
3290 now.checked_add(jiff::SignedDuration::from_secs(secs))
3291 .unwrap_or(Timestamp::MAX),
3292 )
3293}
3294
3295fn apply_solo(config: &mut Config, task: &Task) {
3305 if task.solo {
3306 config.graph.implementers = 1;
3307 }
3308}
3309
3310fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3315 let Some(o) = &task.overrides else {
3316 return prepare(repo, opts);
3317 };
3318 let own = Opts {
3322 config: o.config.clone(),
3323 merge: None,
3324 ..opts.clone()
3325 };
3326 let mut config = prepare(repo, &own)?;
3327 o.apply(&mut config);
3328 Ok(config)
3329}
3330
3331fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3333 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3334 if let Some(mode) = &opts.merge {
3335 config.merge.mode = merge_mode(mode)?;
3336 }
3337 Ok(config)
3338}
3339
3340async fn maybe_prune_cache_between_runs(
3371 repo: &Path,
3372 opts: &Opts,
3373 home: &Path,
3374 stop: &Stop,
3375 last_checked: &mut Option<Timestamp>,
3376 now: Timestamp,
3377) {
3378 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3379 return;
3380 }
3381 *last_checked = Some(now);
3382 let cfg = match prepare(repo, opts) {
3383 Ok(cfg) => cfg,
3384 Err(e) => {
3385 tracing::warn!("cache check: no config: {e:#}");
3386 return;
3387 }
3388 };
3389 match clean::prune_cache_if_over_limit(&cfg, home) {
3390 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3391 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3392 pruned.files,
3393 pruned.freed
3394 ),
3395 Ok(_) => {}
3396 Err(e) => {
3397 tracing::warn!("housekeep: prune cache: {e:#}");
3398 notices::raise_in(
3399 home,
3400 Notice::warn(
3401 "housekeep:cache",
3402 "Pruning the shared build cache failed; disk usage may keep growing.",
3403 ),
3404 );
3405 }
3406 }
3407}
3408
3409fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3413 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3414}
3415
3416async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3435 let cfg = match prepare(repo, opts) {
3436 Ok(cfg) => cfg,
3437 Err(e) => {
3438 tracing::warn!("housekeep: no config: {e:#}");
3439 return;
3440 }
3441 };
3442 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3451 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3452 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3457 let mut extra = Vec::new();
3458 if out.unreadable > 0 {
3459 extra.push(format!("{} unreadable", out.unreadable));
3460 }
3461 if out.orphaned_worktrees > 0 {
3462 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3463 }
3464 let detail = if extra.is_empty() {
3465 String::new()
3466 } else {
3467 format!(" ({})", extra.join(", "))
3468 };
3469 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3470 }
3471 if out.external_merges_recorded > 0 {
3472 tracing::info!(
3473 "housekeep: recorded {} run(s) as merged externally",
3474 out.external_merges_recorded
3475 );
3476 }
3477 if out.stale_pr_states_repaired > 0 {
3478 tracing::info!(
3479 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3480 out.stale_pr_states_repaired
3481 );
3482 }
3483 if out.cache_files > 0 {
3484 tracing::info!(
3485 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3486 out.cache_files,
3487 out.cache_freed
3488 );
3489 }
3490 if out.questions_abandoned > 0 {
3491 tracing::info!(
3492 "housekeep: abandoned {} question(s) left open by a finished run",
3493 out.questions_abandoned
3494 );
3495 }
3496}
3497
3498async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3507 let questions = Questions::at(home.join("questions"));
3508 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3509 if report.is_empty() {
3510 return;
3511 }
3512 if !report.quarantined.is_empty() {
3513 tracing::info!(
3514 "triage: held {} blocked task(s) whose blocked-on task or \
3515 question no longer exists: {}",
3516 report.quarantined.len(),
3517 report.quarantined.join(", ")
3518 );
3519 }
3520 if !report.resumed.is_empty() {
3521 tracing::info!(
3522 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3523 report.resumed.len(),
3524 report.resumed.join(", ")
3525 );
3526 }
3527 if !report.asked.is_empty() {
3528 tracing::info!(
3529 "triage: asked about {} held task(s): {}",
3530 report.asked.len(),
3531 report.asked.join(", ")
3532 );
3533 }
3534 if !report.answered.is_empty() {
3535 tracing::info!(
3536 "triage: applied {} operator answer(s): {}",
3537 report.answered.len(),
3538 report.answered.join(", ")
3539 );
3540 }
3541}
3542
3543fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3550 disk_gate_with(repo, config, crate::disk::free_bytes)
3551}
3552
3553fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3557 repo: &Path,
3558 config: &Config,
3559 free_bytes: F,
3560) -> Option<String> {
3561 let min = config.disk.min_free_bytes;
3562 if min == 0 {
3563 return None;
3564 }
3565 match free_bytes(repo) {
3566 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3567 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3568 }
3569}
3570
3571const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3578
3579const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3583
3584fn quota_wait(
3593 reset_at: Option<Timestamp>,
3594 now: Timestamp,
3595 fallback: Duration,
3596 cap: Duration,
3597) -> Duration {
3598 match reset_at {
3599 Some(at) if at > now => {
3600 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3601 Duration::from_secs(secs).min(cap)
3602 }
3603 _ => fallback,
3604 }
3605}
3606
3607fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3621 parse_reset_hint_zoned(text, now)
3622 .or_else(|| parse_reset_hint_dated(text))
3623 .or_else(|| parse_reset_hint_relative(text, recorded))
3624}
3625
3626fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3630 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3631 let mut rest = rest.trim();
3632 if rest.is_empty() {
3633 return None;
3634 }
3635 let mut total: i64 = 0;
3636 let mut matched = false;
3637 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3638 if let Some((digits, tail)) = rest.split_once(unit)
3639 && !digits.is_empty()
3640 && digits.bytes().all(|b| b.is_ascii_digit())
3641 {
3642 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3643 rest = tail;
3644 matched = true;
3645 }
3646 }
3647 if !rest.is_empty() || !matched {
3648 return None;
3649 }
3650 recorded
3651 .checked_add(jiff::SignedDuration::from_secs(total))
3652 .ok()
3653}
3654
3655fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3659 let clock = clock.trim().to_lowercase();
3660 let (digits, pm) = clock
3661 .strip_suffix("am")
3662 .map(|d| (d, false))
3663 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3664 let (h, m) = digits.trim().split_once(':')?;
3665 let mut hour: i8 = h.trim().parse().ok()?;
3666 let minute: i8 = m.trim().parse().ok()?;
3667 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3668 return None;
3669 }
3670 if pm && hour != 12 {
3671 hour += 12;
3672 } else if !pm && hour == 12 {
3673 hour = 0;
3674 }
3675 Some((hour, minute))
3676}
3677
3678fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3683 let open = text.find('(')?;
3684 let close = text.rfind(')')?;
3685 if close <= open {
3686 return None;
3687 }
3688 let zone = text[open + 1..close].trim();
3689 let (hour, minute) = parse_12h_clock(&text[..open])?;
3690 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3691 let candidate = now
3692 .to_zoned(tz)
3693 .with()
3694 .hour(hour)
3695 .minute(minute)
3696 .second(0)
3697 .millisecond(0)
3698 .microsecond(0)
3699 .nanosecond(0)
3700 .build()
3701 .ok()?;
3702 let mut at = candidate.timestamp();
3703 if at <= now {
3704 at += jiff::SignedDuration::from_hours(24);
3705 }
3706 Some(at)
3707}
3708
3709fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3718 let words: Vec<&str> = text.split_whitespace().collect();
3719 if words.len() < 5 {
3720 return None;
3721 }
3722 (0..=words.len() - 5)
3723 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3724}
3725
3726fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3732 if trailing.is_some_and(|next| next.starts_with('(')) {
3733 return None;
3734 }
3735 let month = month_number(window[0])?;
3736 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3737 let day_digits = ["st", "nd", "rd", "th"]
3738 .iter()
3739 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3740 let day: i8 = day_digits.parse().ok()?;
3741 let year_token = window[2];
3742 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3743 return None;
3744 }
3745 let year: i16 = year_token.parse().ok()?;
3746 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3750 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3751 let date = jiff::civil::Date::new(year, month, day).ok()?;
3752 let candidate = date
3753 .at(hour, minute, 0, 0)
3754 .to_zoned(jiff::tz::TimeZone::UTC)
3755 .ok()?;
3756 Some(candidate.timestamp())
3757}
3758
3759fn month_number(name: &str) -> Option<i8> {
3762 const NAMES: [&str; 12] = [
3763 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3764 ];
3765 let lower = name.to_lowercase();
3766 NAMES
3767 .iter()
3768 .position(|n| *n == lower.as_str())
3769 .map(|i| i as i8 + 1)
3770}
3771
3772fn exhausted_review_budget(state: &RunState) -> bool {
3784 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
3785}
3786
3787fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3824 unfinished_run_with(runs, short, RunState::load)
3825}
3826
3827fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3830where
3831 F: FnOnce(&str) -> Result<RunState>,
3832{
3833 let id = runs.last()?;
3834 match load(id) {
3835 Ok(s)
3840 if s.status.resumable()
3841 && !s.released()
3842 && !exhausted_review_budget(&s)
3843 && s.liveness(false) != crate::run::Liveness::Live =>
3844 {
3845 Some(id.clone())
3846 }
3847 Ok(_) => None,
3848 Err(e) => {
3849 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3850 None
3851 }
3852 }
3853}
3854
3855fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3863where
3864 F: FnOnce(&str) -> Result<RunState>,
3865{
3866 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
3868 || task.fresh_start
3869 || task.review_branch.is_some()
3870 {
3871 return false;
3872 }
3873 let Some(id) = task.runs.last() else {
3874 return false;
3875 };
3876 load(id).is_ok_and(|s| {
3877 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3878 })
3879}
3880
3881#[derive(Debug, Clone, PartialEq, Eq)]
3884enum Starter {
3885 Review(String),
3888 Resume(String),
3890 Start,
3892}
3893
3894fn take_divergence_answer(
3898 branch: &str,
3899 remote: &str,
3900 task: &mut Task,
3901) -> Option<crate::reconcile::Choice> {
3902 let summary = crate::reconcile::summary_for(branch, remote);
3903 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3904 (a.question == summary)
3905 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3906 .flatten()
3907 .map(|c| (i, c))
3908 })?;
3909 task.answers.remove(idx);
3910 Some(choice)
3911}
3912
3913fn choose_starter(
3925 review_branch: Option<&str>,
3926 branch_exists: bool,
3927 unfinished: Option<&str>,
3928) -> Starter {
3929 match review_branch {
3930 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3931 Some(_) => Starter::Start,
3932 None => match unfinished {
3933 Some(id) => Starter::Resume(id.to_owned()),
3934 None => Starter::Start,
3935 },
3936 }
3937}
3938
3939fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3942 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3943 return fallback.to_path_buf();
3944 }
3945 task.repo.clone()
3946}
3947
3948const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3952
3953fn answers_block(task: &Task, count: usize) -> String {
3955 let mut s = ANSWERS_HEADER.to_owned();
3956 for a in &task.answers[..count] {
3957 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3958 }
3959 s
3960}
3961
3962fn append_answers(base: &str, task: &Task) -> String {
3965 if task.answers.is_empty() {
3966 return base.to_owned();
3967 }
3968 let mut s = base.to_owned();
3969 s.push_str(&answers_block(task, task.answers.len()));
3970 s
3971}
3972
3973fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3977 for count in (1..=task.answers.len()).rev() {
3978 let block = answers_block(task, count);
3979 if let Some(base) = instruction.strip_suffix(&block) {
3980 return base;
3981 }
3982 }
3983 instruction
3984}
3985
3986fn instruction_for(task: &Task) -> String {
3994 append_answers(&task.instruction, task)
3995}
3996
3997fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4009 append_answers(strip_answers_block(old_instruction, task), task)
4010}
4011
4012fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
4014 let paths = queue.attachment_paths(task);
4015 for (name, path) in task.attachments.iter().zip(&paths) {
4016 if !path.is_file() {
4017 bail!(
4018 "attachment `{name}` is recorded on the task but {} is missing",
4019 path.display()
4020 );
4021 }
4022 }
4023 Ok(paths)
4024}
4025
4026fn prepare_instruction(
4037 starter: &Starter,
4038 old_instruction: Option<&str>,
4039 task: &Task,
4040) -> Option<String> {
4041 match starter {
4042 Starter::Start => Some(instruction_for(task)),
4043 Starter::Resume(_) => Some(resumed_instruction(
4044 old_instruction.expect("a resumed run always has a prior instruction"),
4045 task,
4046 )),
4047 Starter::Review(_) => None,
4048 }
4049}
4050
4051fn record(queue: &Queue, task: &mut Task) {
4055 if let Err(e) = queue.put(task) {
4056 tracing::error!("could not record task {}: {e:#}", task.short());
4057 notices::raise(
4058 Notice::error(
4059 "loop:record",
4060 "The loop could not save a task's state; check the disk.",
4061 )
4062 .link(Link::Task {
4063 id: task.id.clone(),
4064 }),
4065 );
4066 }
4067}
4068
4069fn runnable(queue: &Queue) -> Vec<Task> {
4075 let mut tasks: Vec<Task> = queue
4076 .list()
4077 .into_iter()
4078 .filter(|t| t.status.runnable())
4079 .collect();
4080 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4081 tasks
4082}
4083
4084fn describe(state: &RunState) -> String {
4098 let p = phrases(&state.config.graph.language);
4099 let mut detail = if state.status == RunStatus::Stalled {
4100 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4101 seats.sort_unstable();
4102 seats.dedup();
4103 if seats.is_empty() {
4104 p.quorum_lost.to_owned()
4105 } else {
4106 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4107 }
4108 } else {
4109 format!("{}{}", p.run_ended, state.status.display_label())
4110 };
4111 if let Some(last) = state.events.last() {
4112 let unanswered = state
4116 .reviews
4117 .last()
4118 .filter(|r| {
4119 state.status == RunStatus::Blocked
4120 && last.node == "review"
4121 && r.incomplete()
4122 && r.blocking == 0
4123 && r.round == state.config.graph.review_rounds
4124 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4125 })
4126 .map(|r| (r.expected - r.answered, r.round));
4127 match unanswered {
4128 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4129 detail.push_str(&format!(
4130 " ({}: {})",
4131 last.node,
4132 (p.reviewers_never_answered)(missing, rounds)
4133 ));
4134 }
4135 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4136 }
4137 }
4138 detail.push_str(&format!(" [run {}]", state.id));
4139 detail
4140}
4141
4142const DIAGNOSTIC_MAX: usize = 4_000;
4148
4149const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4154
4155fn diagnostic(state: &RunState) -> Option<String> {
4169 let mut parts: Vec<String> = Vec::new();
4170
4171 for o in state.gate.iter().filter(|o| !o.ok()) {
4173 parts.push(format!(
4174 "gate `{}` failed ({:?}):\n{}",
4175 o.command,
4176 o.code,
4177 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4178 ));
4179 }
4180
4181 if let Some(last) = state
4184 .events
4185 .iter()
4186 .rev()
4187 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4188 {
4189 parts.push(last.message.clone());
4190 }
4191
4192 if state.viable().is_empty() {
4199 for c in &state.candidates {
4200 if let Some(evidence) = &c.verified_noop {
4201 parts.push(format!(
4202 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4203 c.label
4204 ));
4205 } else if !c.summary.trim().is_empty() {
4206 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4207 } else if let Some(why) = &c.failed {
4208 parts.push(format!("candidate {}: {why}", c.label));
4209 }
4210 }
4211 }
4212
4213 if parts.is_empty() {
4214 return None;
4215 }
4216 Some(crate::run::tail(
4221 &parts.join("\n\n"),
4222 DIAGNOSTIC_MAX.saturating_sub(100),
4223 ))
4224}
4225
4226fn label(status: RunStatus) -> &'static str {
4234 status.as_str()
4235}
4236
4237pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4239 match mode {
4240 "none" => Ok(MergeMode::None),
4241 "local" => Ok(MergeMode::Local),
4242 "pr" => Ok(MergeMode::Pr),
4243 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4244 }
4245}
4246
4247fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4252 mutex
4253 .lock()
4254 .unwrap_or_else(std::sync::PoisonError::into_inner)
4255}
4256
4257#[cfg(test)]
4258mod tests {
4259 use super::*;
4260 use crate::queue::{Source, TaskStatus};
4261 use crate::run::{Candidate, CommandOutcome};
4262 use pretty_assertions::assert_eq;
4263
4264 fn task() -> Task {
4265 Task::new(
4266 "add retries".to_owned(),
4267 "add retries".to_owned(),
4268 PathBuf::from("/repo"),
4269 Source::Human,
4270 )
4271 }
4272
4273 fn interrupt_task(id: &str) -> Task {
4276 let mut t = task();
4277 t.id = id.to_owned();
4278 t.interrupt = true;
4279 t
4280 }
4281
4282 fn task_with_id(id: &str) -> Task {
4284 let mut t = task();
4285 t.id = id.to_owned();
4286 t
4287 }
4288
4289 fn urgent_task(id: &str) -> Task {
4291 let mut t = task();
4292 t.id = id.to_owned();
4293 t.urgent = true;
4294 t
4295 }
4296
4297 #[test]
4302 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4303 assert_eq!(permit_kind(true, false), PermitKind::None);
4304 assert_eq!(permit_kind(true, true), PermitKind::None);
4305 }
4306
4307 #[test]
4312 fn permit_kind_separates_urgent_from_ordinary() {
4313 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4314 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4315 }
4316
4317 #[test]
4324 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4325 let cfg = Config::default();
4326 let repo = Path::new("/any/repo/path");
4327
4328 let reason =
4329 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4330 assert!(reason.contains("1024"), "{reason}");
4331 assert!(
4332 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4333 "{reason}"
4334 );
4335
4336 assert_eq!(
4337 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4338 None,
4339 "exactly at the floor is open"
4340 );
4341 assert_eq!(
4342 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4343 None,
4344 "comfortably above the floor is open"
4345 );
4346 }
4347
4348 #[test]
4349 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4350 let mut cfg = Config::default();
4351 cfg.disk.min_free_bytes = 0;
4352 let repo = Path::new("/any/repo/path");
4353 assert_eq!(
4354 disk_gate_with(repo, &cfg, |_| Ok(0)),
4355 None,
4356 "a zero floor never measures at all"
4357 );
4358 }
4359
4360 #[test]
4361 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
4362 let cfg = Config::default();
4363 let repo = Path::new("/any/repo/path");
4364 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
4365 .expect("a measurement failure must close the gate, not open it");
4366 assert!(reason.contains("could not measure"), "{reason}");
4367 }
4368
4369 #[test]
4370 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
4371 let ordinary = task();
4372 let next = advance_interrupt(
4373 Interrupt::Idle,
4374 std::slice::from_ref(&ordinary.id),
4375 std::slice::from_ref(&ordinary),
4376 );
4377 assert_eq!(next, Interrupt::Idle);
4378 }
4379
4380 #[test]
4381 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
4382 let marked = interrupt_task("marked");
4385 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4386 assert_eq!(next, Interrupt::Idle);
4387 }
4388
4389 #[test]
4390 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
4391 let marked = interrupt_task("marked");
4392 let next = advance_interrupt(
4393 Interrupt::Idle,
4394 &["running".to_owned()],
4395 std::slice::from_ref(&marked),
4396 );
4397 assert_eq!(
4398 next,
4399 Interrupt::Parking {
4400 parked: vec!["running".to_owned()],
4401 interrupt_task: "marked".to_owned(),
4402 }
4403 );
4404 }
4405
4406 #[test]
4415 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
4416 let marked = interrupt_task("marked");
4417
4418 let two = advance_interrupt(
4419 Interrupt::Idle,
4420 &["a".to_owned(), "b".to_owned()],
4421 std::slice::from_ref(&marked),
4422 );
4423 assert_eq!(two, Interrupt::Idle);
4424
4425 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4426 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
4427 }
4428
4429 #[test]
4430 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
4431 let state = Interrupt::Parking {
4432 parked: vec!["running".to_owned()],
4433 interrupt_task: "marked".to_owned(),
4434 };
4435 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
4437 assert_eq!(still_going, state);
4438
4439 let stopped_but_not_yet_dispatched =
4443 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
4444 assert_eq!(stopped_but_not_yet_dispatched, state);
4445
4446 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
4448 assert_eq!(
4449 dispatched,
4450 Interrupt::Running {
4451 parked: vec!["running".to_owned()],
4452 interrupt_task: "marked".to_owned(),
4453 }
4454 );
4455 }
4456
4457 #[test]
4458 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
4459 let state = Interrupt::Running {
4460 parked: vec!["running".to_owned()],
4461 interrupt_task: "marked".to_owned(),
4462 };
4463 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
4464 assert_eq!(still_running, state);
4465
4466 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
4473 assert_eq!(
4474 ended,
4475 Interrupt::Resuming {
4476 parked: vec!["running".to_owned()]
4477 }
4478 );
4479 }
4480
4481 #[test]
4482 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
4483 let state = Interrupt::Resuming {
4484 parked: vec!["running".to_owned()],
4485 };
4486 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
4487 assert_eq!(still_waiting, state);
4488
4489 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
4490 assert_eq!(dispatched, Interrupt::Idle);
4491 }
4492
4493 #[test]
4499 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
4500 {
4501 let state = Interrupt::Parking {
4502 parked: vec!["running".to_owned()],
4503 interrupt_task: "marked".to_owned(),
4504 };
4505 let next = advance_interrupt(state, &[], &[]);
4508 assert_eq!(
4509 next,
4510 Interrupt::Resuming {
4511 parked: vec!["running".to_owned()]
4512 },
4513 "abandoning the interrupt must not abandon the resume it owes"
4514 );
4515 }
4516
4517 #[test]
4520 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
4521 let state = Interrupt::Resuming {
4522 parked: vec!["running".to_owned()],
4523 };
4524 let next = advance_interrupt(state, &[], &[]);
4525 assert_eq!(
4526 next,
4527 Interrupt::Idle,
4528 "nothing is left to wait for; the loop must not stay wedged"
4529 );
4530 }
4531
4532 #[test]
4533 fn disabled_by_config_the_sequence_can_never_leave_idle() {
4534 let marked = interrupt_task("marked");
4535 let next = advance_interrupt_tick(
4536 false,
4537 Interrupt::Idle,
4538 &["running".to_owned()],
4539 std::slice::from_ref(&marked),
4540 );
4541 assert_eq!(
4542 next,
4543 Interrupt::Idle,
4544 "an unmarked, unconfigured daemon must behave exactly as before"
4545 );
4546 }
4547
4548 #[test]
4549 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
4550 let state = Interrupt::Parking {
4551 parked: vec!["running".to_owned()],
4552 interrupt_task: "marked".to_owned(),
4553 };
4554 let candidates = vec![interrupt_task("marked"), task()];
4555 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4556 assert!(
4557 allowed.is_empty(),
4558 "nothing may dispatch - not even the interrupt task itself - \
4559 until the parked run has actually stopped"
4560 );
4561 }
4562
4563 #[test]
4577 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
4578 for state in [
4579 Interrupt::Parking {
4580 parked: vec!["running".to_owned()],
4581 interrupt_task: "marked".to_owned(),
4582 },
4583 Interrupt::Running {
4584 parked: vec!["running".to_owned()],
4585 interrupt_task: "marked".to_owned(),
4586 },
4587 Interrupt::Resuming {
4588 parked: vec!["running".to_owned()],
4589 },
4590 ] {
4591 let candidates = vec![
4592 interrupt_task("marked"),
4593 urgent_task("hot"),
4594 task_with_id("ordinary"),
4595 ];
4596 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4597 assert!(
4598 !allowed.iter().any(|t| t.id == "hot"),
4599 "an urgent candidate must wait out the same gate as anything \
4600 else while the run it would run alongside has not actually \
4601 left flight, for state {state:?}: {allowed:?}"
4602 );
4603 }
4604 }
4605
4606 #[test]
4612 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
4613 let state = Interrupt::Resuming {
4614 parked: vec!["hot".to_owned()],
4615 };
4616 let candidates = vec![urgent_task("hot"), task()];
4617 let allowed = interrupt_gate(&state, &[], candidates);
4618 assert_eq!(
4619 allowed.iter().filter(|t| t.id == "hot").count(),
4620 1,
4621 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
4622 );
4623 }
4624
4625 #[test]
4626 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
4627 let state = Interrupt::Parking {
4628 parked: vec!["running".to_owned()],
4629 interrupt_task: "marked".to_owned(),
4630 };
4631 let other = task();
4632 let candidates = vec![interrupt_task("marked"), other.clone()];
4633 let allowed = interrupt_gate(&state, &[], candidates);
4634 assert_eq!(allowed.len(), 1);
4635 assert_eq!(allowed[0].id, "marked");
4636 }
4637
4638 #[test]
4639 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4640 let state = Interrupt::Running {
4641 parked: vec!["running".to_owned()],
4642 interrupt_task: "marked".to_owned(),
4643 };
4644 let candidates = vec![task(), task()];
4645 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4646 assert!(allowed.is_empty());
4647 }
4648
4649 #[test]
4656 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4657 let state = Interrupt::Resuming {
4658 parked: vec!["a".to_owned(), "c".to_owned()],
4659 };
4660 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4661 let allowed = interrupt_gate(&state, &[], candidates);
4662 assert_eq!(
4663 allowed.len(),
4664 1,
4665 "at most one candidate may be offered while resuming: {allowed:?}"
4666 );
4667 assert_eq!(allowed[0].id, "a");
4668 }
4669
4670 #[test]
4671 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4672 let state = Interrupt::Resuming {
4673 parked: vec!["a".to_owned()],
4674 };
4675 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4676 assert!(allowed.is_empty());
4677 }
4678
4679 #[test]
4685 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4686 let running = task(); let marked = interrupt_task("marked");
4688
4689 let mut state = Interrupt::Idle;
4690 let in_flight = vec![running.id.clone()];
4692 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4693 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4694 assert!(gated.is_empty(), "still waiting on `running` to park");
4695
4696 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4698 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4699 assert_eq!(
4700 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4701 vec!["marked"],
4702 "only the interrupt task may be offered to the dispatcher now"
4703 );
4704
4705 state = advance_interrupt_tick(
4707 true,
4708 state,
4709 &["marked".to_owned()],
4710 std::slice::from_ref(&running),
4711 );
4712 let gated = interrupt_gate(
4713 &state,
4714 &["marked".to_owned()],
4715 vec![marked.clone(), running.clone()],
4716 );
4717 assert!(
4718 gated.is_empty(),
4719 "the parked run must not be offered back while the interrupt \
4720 task is still running"
4721 );
4722
4723 let other = task_with_id("other");
4727 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4728 assert_eq!(
4729 state,
4730 Interrupt::Resuming {
4731 parked: vec![running.id.clone()]
4732 }
4733 );
4734 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4735 assert_eq!(
4736 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4737 vec![running.id.as_str()],
4738 "exactly the parked run resumes - not the unrelated task, even \
4739 though it was offered first"
4740 );
4741
4742 state = advance_interrupt_tick(
4746 true,
4747 state,
4748 std::slice::from_ref(&running.id),
4749 std::slice::from_ref(&other),
4750 );
4751 assert_eq!(state, Interrupt::Idle);
4752 let gated = interrupt_gate(
4753 &state,
4754 std::slice::from_ref(&running.id),
4755 vec![other.clone()],
4756 );
4757 assert_eq!(
4758 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4759 vec![other.id.as_str()],
4760 "ordinary dispatch is unrestricted again"
4761 );
4762 }
4763
4764 #[test]
4765 fn every_run_status_settles_the_task_it_came_from() {
4766 let table = [
4768 (RunStatus::Merged, TaskStatus::Done, 1),
4769 (RunStatus::Ready, TaskStatus::Done, 1),
4770 (RunStatus::Stalled, TaskStatus::Failed, 0),
4771 (RunStatus::Blocked, TaskStatus::Failed, 1),
4772 (RunStatus::Failed, TaskStatus::Failed, 1),
4773 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4774 (RunStatus::Prep, TaskStatus::Failed, 1),
4775 (RunStatus::Implementing, TaskStatus::Failed, 1),
4776 (RunStatus::Judging, TaskStatus::Failed, 1),
4777 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4778 (RunStatus::Voting, TaskStatus::Failed, 1),
4779 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4780 (RunStatus::Gating, TaskStatus::Failed, 1),
4781 ];
4782 for (run, want, attempts) in table {
4783 let mut t = task();
4784 t.start("20260902-000000-aaaa".to_owned());
4785 settle(
4786 &mut t,
4787 Verdict {
4788 status: run,
4789 left_pr: false,
4790 parked: false,
4791 quota_hit: matches!(run, RunStatus::Stalled),
4792 no_viable_candidates: false,
4793 },
4794 "why",
4795 2,
4796 );
4797 assert_eq!(t.status, want, "task status after {}", label(run));
4798 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4799 }
4800 }
4801
4802 #[test]
4803 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4804 let mut stalled = task();
4805 stalled.start("20260902-000000-aaaa".to_owned());
4806 settle(
4807 &mut stalled,
4808 Verdict {
4809 status: RunStatus::Stalled,
4810 left_pr: false,
4811 parked: false,
4812 quota_hit: true,
4813 no_viable_candidates: false,
4814 },
4815 "quota",
4816 1,
4817 );
4818 assert_eq!(stalled.attempts, 0);
4819 assert!(
4820 stalled.status.runnable(),
4821 "a machine problem must leave the task in line"
4822 );
4823
4824 let mut blocked = task();
4825 blocked.start("20260902-000000-aaaa".to_owned());
4826 settle(
4827 &mut blocked,
4828 Verdict {
4829 status: RunStatus::Blocked,
4830 left_pr: false,
4831 parked: false,
4832 quota_hit: false,
4833 no_viable_candidates: false,
4834 },
4835 "findings open",
4836 1,
4837 );
4838 assert_eq!(blocked.attempts, 1);
4839 assert_eq!(
4840 blocked.status,
4841 TaskStatus::Held,
4842 "the last attempt hands the task to a human"
4843 );
4844 }
4845
4846 #[test]
4847 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4848 let mut delivered = task();
4851 delivered.start("20260903-080619-01c2".to_owned());
4852 settle(
4853 &mut delivered,
4854 Verdict {
4855 status: RunStatus::Blocked,
4856 left_pr: true,
4857 parked: false,
4858 quota_hit: false,
4859 no_viable_candidates: false,
4860 },
4861 "no check status",
4862 4,
4863 );
4864 assert_eq!(
4865 delivered.status,
4866 TaskStatus::Held,
4867 "a pull request waiting on CI or a person is not a retryable failure"
4868 );
4869 assert!(
4870 !delivered.status.runnable(),
4871 "the loop must not pick this task up again"
4872 );
4873 assert_eq!(
4874 delivered.last_error.as_deref(),
4875 Some("no check status"),
4876 "the operator needs to be told what the gate was waiting for"
4877 );
4878
4879 let mut empty_handed = task();
4882 empty_handed.start("20260903-080619-01c2".to_owned());
4883 settle(
4884 &mut empty_handed,
4885 Verdict {
4886 status: RunStatus::Blocked,
4887 left_pr: false,
4888 parked: false,
4889 quota_hit: false,
4890 no_viable_candidates: false,
4891 },
4892 "findings open",
4893 4,
4894 );
4895 assert_eq!(empty_handed.status, TaskStatus::Failed);
4896 assert!(empty_handed.status.runnable());
4897 }
4898
4899 #[test]
4900 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4901 let mut noop = task();
4907 noop.start("20260912-131304-391f".to_owned());
4908 settle(
4909 &mut noop,
4910 Verdict {
4911 status: RunStatus::VerifiedNoop,
4912 left_pr: false,
4913 parked: false,
4914 quota_hit: false,
4915 no_viable_candidates: true,
4916 },
4917 "candidate A: already fixed by b32cfc4, on main",
4918 4,
4919 );
4920 assert_eq!(
4921 noop.status,
4922 TaskStatus::Held,
4923 "an unverified claim is a request for a human, not a failure"
4924 );
4925 assert!(
4926 !noop.status.runnable(),
4927 "the loop must not requeue this on the same unverified claim"
4928 );
4929 assert_eq!(noop.attempts, 1);
4934 }
4935
4936 #[test]
4937 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4938 let mut parked = task();
4943 parked.start("20260903-183634-2d98".to_owned());
4944 settle(
4945 &mut parked,
4946 Verdict {
4947 status: RunStatus::Implementing,
4948 left_pr: false,
4949 quota_hit: false,
4950 parked: true,
4951 no_viable_candidates: false,
4952 },
4953 "parked after `implementing`",
4954 2,
4955 );
4956 assert_eq!(parked.attempts, 0, "a park is refunded");
4957 assert!(
4958 parked.status.runnable(),
4959 "and the task stays in line so the next loop resumes its run"
4960 );
4961 assert_eq!(parked.status, TaskStatus::Parked);
4962 assert_eq!(
4963 parked.park_reason.as_deref(),
4964 Some("parked after `implementing`"),
4965 "the card says where it stopped"
4966 );
4967 assert_eq!(parked.last_error, None, "nothing failed");
4968
4969 let mut broken = task();
4973 broken.start("20260903-183634-2d98".to_owned());
4974 settle(
4975 &mut broken,
4976 Verdict {
4977 status: RunStatus::Implementing,
4978 left_pr: false,
4979 quota_hit: false,
4980 parked: false,
4981 no_viable_candidates: false,
4982 },
4983 "returned mid-flight",
4984 2,
4985 );
4986 assert_eq!(broken.attempts, 1);
4987 }
4988
4989 #[test]
4990 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4991 let mut flaky = task();
4996 flaky.start("20260903-123023-e633".to_owned());
4997 settle(
4998 &mut flaky,
4999 Verdict {
5000 status: RunStatus::Stalled,
5001 left_pr: false,
5002 parked: false,
5003 quota_hit: false,
5004 no_viable_candidates: false,
5005 },
5006 "verdict rests on 1 of 3 judges",
5007 2,
5008 );
5009 assert_eq!(
5010 flaky.attempts, 1,
5011 "flakiness spends an attempt, so `max_attempts` still bounds it"
5012 );
5013 assert!(flaky.status.runnable(), "and it is still worth retrying");
5014
5015 let mut limited = task();
5017 limited.start("20260903-123023-e633".to_owned());
5018 settle(
5019 &mut limited,
5020 Verdict {
5021 status: RunStatus::Stalled,
5022 left_pr: false,
5023 parked: false,
5024 quota_hit: true,
5025 no_viable_candidates: false,
5026 },
5027 "judge-2, judge-3 out of quota",
5028 2,
5029 );
5030 assert_eq!(limited.attempts, 0, "a quota window is refunded");
5031 assert!(limited.status.runnable());
5032
5033 let mut worn = task();
5036 for _ in 0..2 {
5037 worn.release();
5038 }
5039 worn.start("20260903-123023-e633".to_owned());
5040 worn.attempts = 2;
5041 settle(
5042 &mut worn,
5043 Verdict {
5044 status: RunStatus::Stalled,
5045 left_pr: false,
5046 parked: false,
5047 quota_hit: false,
5048 no_viable_candidates: false,
5049 },
5050 "no quorum again",
5051 2,
5052 );
5053 assert_eq!(worn.status, TaskStatus::Held);
5054 assert!(!worn.status.runnable());
5055 }
5056
5057 #[test]
5058 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5059 let mut wiped_out = task();
5066 wiped_out.start("20260907-025000-a1b2".to_owned());
5067 settle(
5068 &mut wiped_out,
5069 Verdict {
5070 status: RunStatus::Failed,
5071 left_pr: false,
5072 parked: false,
5073 quota_hit: true,
5074 no_viable_candidates: true,
5075 },
5076 "no candidate produced a change; nothing to judge",
5077 2,
5078 );
5079 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5080 assert!(
5081 wiped_out.status.runnable(),
5082 "a machine problem must leave the task in line"
5083 );
5084
5085 let mut partial_progress = task();
5091 partial_progress.start("20260907-025500-c3d4".to_owned());
5092 settle(
5093 &mut partial_progress,
5094 Verdict {
5095 status: RunStatus::Failed,
5096 left_pr: false,
5097 parked: false,
5098 quota_hit: true,
5099 no_viable_candidates: false,
5100 },
5101 "gate failed on the winning candidate",
5102 2,
5103 );
5104 assert_eq!(
5105 partial_progress.attempts, 1,
5106 "a candidate that actually produced a change spends the attempt \
5107 even though some other seat hit its quota"
5108 );
5109 assert!(partial_progress.status.runnable());
5110 }
5111
5112 #[test]
5113 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5114 let mut t = task();
5120 t.start("20260907-025000-a1b2".to_owned());
5121 let mut state = run_state(RunStatus::Failed);
5122 state.quota.push(QuotaLoss {
5123 seat: "cand-a".to_owned(),
5124 node: "implement".to_owned(),
5125 at: Timestamp::now(),
5126 reset: None,
5127 });
5128 assert!(
5129 state.viable().is_empty(),
5130 "no candidate was added, so nothing is viable"
5131 );
5132 reclaim(&mut t, Some(state), 2, "en");
5133 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5134 assert!(t.status.runnable());
5135 }
5136
5137 #[test]
5138 fn a_held_task_is_never_offered_to_the_loop() {
5139 let dir = tempfile::tempdir().unwrap();
5140 let queue = Queue::at(dir.path().to_path_buf());
5141 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5142 let mut t = task();
5143 t.id = format!("2026090{n}-000000-000{n}");
5144 t.priority = priority;
5145 queue.put(&mut t).unwrap();
5146 }
5147 let mut held = task();
5148 held.id = "20260909-000000-9999".to_owned();
5149 held.priority = 99;
5150 held.hold_machine(None);
5151 queue.put(&mut held).unwrap();
5152
5153 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5154 assert_eq!(order.len(), 3);
5155 assert!(!order.contains(&held.id));
5156 assert_eq!(
5157 order.first().cloned(),
5158 queue.next_runnable().map(|t| t.id),
5159 "the loop's first candidate is exactly what the queue offers"
5160 );
5161 assert_eq!(
5162 order,
5163 vec![
5164 "20260902-000000-0002".to_owned(),
5165 "20260903-000000-0003".to_owned(),
5166 "20260901-000000-0001".to_owned(),
5167 ],
5168 "priority first, then oldest, so nothing starves"
5169 );
5170 }
5171
5172 #[test]
5173 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5174 let dir = tempfile::tempdir().unwrap();
5175 let queue = Queue::at(dir.path().to_path_buf());
5176 let mut old = task();
5177 old.id = "20260101-000000-old0".to_owned();
5178 queue.put(&mut old).unwrap();
5179 let mut fresh = task();
5180 fresh.id = "20260101-000000-new0".to_owned();
5181 queue.put(&mut fresh).unwrap();
5182
5183 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5187 std::thread::sleep(Duration::from_millis(60));
5188 let live = queue.claim(&fresh.id).unwrap();
5189
5190 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5191 assert_eq!(swept, vec![old.id.clone()]);
5192 assert!(
5193 queue.claim(&old.id).is_ok(),
5194 "an unparseable lock older than the threshold is swept"
5195 );
5196 assert!(
5197 queue.claim(&fresh.id).is_err(),
5198 "a live pid protects its lock regardless of age"
5199 );
5200 drop(live);
5201 }
5202
5203 #[test]
5204 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5205 let dir = tempfile::tempdir().unwrap();
5215 let queue = Queue::at(dir.path().to_path_buf());
5216 let mut t = task();
5217 t.id = "20260101-000000-live".to_owned();
5218 queue.put(&mut t).unwrap();
5219
5220 let claim = queue.claim(&t.id).unwrap();
5221 std::thread::sleep(Duration::from_millis(60));
5222
5223 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5224 assert!(
5225 swept.is_empty(),
5226 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5227 );
5228 assert!(
5229 queue.claim(&t.id).is_err(),
5230 "the lock still protects its task"
5231 );
5232 drop(claim);
5233 }
5234
5235 fn injected_dead_pid() -> u32 {
5238 std::process::id().checked_add(1).unwrap_or(1)
5239 }
5240
5241 #[test]
5242 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5243 let dir = tempfile::tempdir().unwrap();
5244 let queue = Queue::at(dir.path().to_path_buf());
5245 let mut t = task();
5246 t.id = "20260101-000000-dead".to_owned();
5247 queue.put(&mut t).unwrap();
5248 let dead_pid = injected_dead_pid();
5249
5250 std::fs::write(
5255 dir.path().join(format!("{}.lock", t.id)),
5256 dead_pid.to_string(),
5257 )
5258 .unwrap();
5259
5260 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5261 pid != dead_pid
5262 });
5263 assert_eq!(
5264 swept,
5265 vec![t.id.clone()],
5266 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5267 );
5268 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5269 }
5270
5271 #[test]
5272 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5273 let dir = tempfile::tempdir().unwrap();
5274 let queue = Queue::at(dir.path().to_path_buf());
5275 let mut t = task();
5276 t.id = "20260101-000000-late".to_owned();
5277 queue.put(&mut t).unwrap();
5278 let dead_pid = injected_dead_pid();
5279
5280 assert!(
5283 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5284 "nothing has claimed the task yet"
5285 );
5286
5287 std::fs::write(
5290 dir.path().join(format!("{}.lock", t.id)),
5291 dead_pid.to_string(),
5292 )
5293 .unwrap();
5294
5295 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5299 pid != dead_pid
5300 });
5301 assert_eq!(swept, vec![t.id.clone()]);
5302 }
5303
5304 #[test]
5305 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5306 crate::run::pin_test_home();
5311 let dir = tempfile::tempdir().unwrap();
5312 let queue = Queue::at(dir.path().to_path_buf());
5313 let mut t = task();
5314 t.id = "20260101-000000-crsh".to_owned();
5315 t.status = TaskStatus::Running;
5316 t.attempts = 1;
5317 t.runs.push("20260904-000000-4043".to_owned());
5321 queue.put(&mut t).unwrap();
5322 let dead_pid = injected_dead_pid();
5323
5324 std::fs::write(
5327 dir.path().join(format!("{}.lock", t.id)),
5328 dead_pid.to_string(),
5329 )
5330 .unwrap();
5331
5332 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5338 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5339
5340 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5341 pid != dead_pid
5342 });
5343 assert_eq!(swept, vec![t.id.clone()]);
5344
5345 let reclaimed = reclaim_orphaned_running(&queue, 2);
5346 assert_eq!(reclaimed, vec![t.id.clone()]);
5347 let after = queue.get(&t.id).unwrap();
5348 assert_eq!(
5349 after.status,
5350 TaskStatus::Held,
5351 "no run.json to recover from, so a human is asked"
5352 );
5353 assert_eq!(
5354 after.runs,
5355 vec!["20260904-000000-4043".to_owned()],
5356 "the crashed run's id is kept as evidence, not discarded"
5357 );
5358 }
5359
5360 #[test]
5361 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
5362 let dir = tempfile::tempdir().unwrap();
5363 let queue = Queue::at(dir.path().to_path_buf());
5364 let mut t = task();
5365 t.id = "20260101-000000-unknown".to_owned();
5366 queue.put(&mut t).unwrap();
5367 let dead_pid = injected_dead_pid();
5368 std::fs::write(
5369 dir.path().join(format!("{}.lock", t.id)),
5370 dead_pid.to_string(),
5371 )
5372 .unwrap();
5373
5374 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
5375 assert!(swept.is_empty(), "an unknown pid must keep its lock");
5376 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
5377 }
5378
5379 fn run_state_in(status: RunStatus, language: &str) -> RunState {
5380 let mut s = run_state(status);
5381 s.config.graph.language = language.to_owned();
5382 s
5383 }
5384
5385 fn unstarted_verdict(status: RunStatus) -> Verdict {
5386 Verdict {
5387 status,
5388 left_pr: false,
5389 quota_hit: false,
5390 parked: false,
5391 no_viable_candidates: false,
5392 }
5393 }
5394
5395 #[test]
5396 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
5397 let mut t = task();
5398 t.attempts = 1;
5399 settle_in(
5400 &mut t,
5401 unstarted_verdict(RunStatus::AlreadyInBase),
5402 "already in main",
5403 1,
5404 phrases("en"),
5405 );
5406 assert_eq!(t.status, TaskStatus::Done);
5407 assert_eq!(t.attempts, 0);
5408 }
5409
5410 #[test]
5411 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
5412 let reason = |language: &str| {
5413 let mut t = task();
5414 settle_in(
5415 &mut t,
5416 unstarted_verdict(RunStatus::Judging),
5417 "boom",
5418 1,
5419 phrases(language),
5420 );
5421 t.last_error.or(t.hold_reason).unwrap_or_default()
5422 };
5423 assert!(
5424 reason("en").starts_with("the graph stopped at `"),
5425 "{}",
5426 reason("en")
5427 );
5428 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
5429 assert!(reason("日本語").contains("boom"));
5430 assert_eq!(reason("fr"), reason("en"));
5431 }
5432
5433 #[test]
5434 fn describe_follows_the_run_language_and_keeps_the_run_id() {
5435 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
5436 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
5437 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
5438 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
5439 assert!(ja.contains("[run "), "{ja}");
5440 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
5441 assert!(ended.starts_with("run 終了: "), "{ended}");
5442 let mut de = run_state_in(RunStatus::Failed, "de");
5443 let mut en = run_state_in(RunStatus::Failed, "en");
5444 de.id = "same".to_owned();
5445 en.id = "same".to_owned();
5446 assert_eq!(describe(&de), describe(&en));
5447 }
5448
5449 #[test]
5450 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
5451 use crate::handover::Refused;
5452 let cases = [
5453 Refused::Foreign {
5454 branch: "b".into(),
5455 path: "/w/x".into(),
5456 why: "made by hand".into(),
5457 },
5458 Refused::Unsafe {
5459 branch: "b".into(),
5460 path: "/w/x".into(),
5461 why: "its worktree has uncommitted changes (a.rs)".into(),
5462 },
5463 Refused::ReleaseFailed {
5464 branch: "b".into(),
5465 path: "/w/x".into(),
5466 run: "ab12".into(),
5467 },
5468 ];
5469 for r in &cases {
5470 let en = (phrases("en").handover_refused)(r);
5471 assert_eq!(en, r.to_string());
5472 let ja = (phrases("ja").handover_refused)(r);
5473 assert!(
5474 !ja.contains("is checked out") && !ja.contains("try again"),
5475 "{ja}"
5476 );
5477 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
5478 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
5479 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
5480 }
5481 }
5482 assert!(phrases("en").handover_hint.contains("release the task"));
5483 assert!(phrases("ja").handover_hint.contains("解放"));
5484 }
5485
5486 #[test]
5487 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
5488 let build = |lang: &str| {
5489 let mut s = run_state_in(RunStatus::Blocked, lang);
5490 s.id = "same".to_owned();
5491 s.config.graph.review_rounds = 3;
5492 let mut r = review_round(3);
5493 r.expected = 3;
5494 r.answered = 1;
5495 s.reviews.push(r);
5496 s.event(
5497 "review",
5498 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
5499 );
5500 s
5501 };
5502 let en = describe(&build("en"));
5503 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
5504 let ja = describe(&build("ja"));
5505 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
5506 assert!(!ja.contains("never answered"), "{ja}");
5507 assert!(ja.contains("[run "), "{ja}");
5508
5509 let mut failed = build("ja");
5512 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
5513 command: "cargo test".to_owned(),
5514 code: Some(1),
5515 output_tail: String::new(),
5516 duration_ms: 0,
5517 resource_blocked: false,
5518 });
5519 failed.event("review", "stopped; e2e failed: cargo test");
5520 let ja = describe(&failed);
5521 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
5522 assert!(!ja.contains("席のレビュアー"), "{ja}");
5523 }
5524
5525 #[test]
5526 fn refusals_and_recovery_prose_follow_the_language() {
5527 let t = held_task_with("r1");
5528 let q = action_question(
5529 "r1",
5530 ask::ChoiceAction::Resume {
5531 run: "r1".to_owned(),
5532 },
5533 );
5534 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
5535 ActionDecision::Refuse(s) => s,
5536 other => panic!("{other:?}"),
5537 };
5538 assert!(refuse(phrases("en")).contains("could not be read: gone"));
5539 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
5540 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
5541
5542 let mut held = task();
5543 reclaim(&mut held, None, 2, "ja");
5544 assert!(held.hold_reason.unwrap().contains("保留にしました"));
5545 let mut held = task();
5546 reclaim(&mut held, None, 2, "xx");
5547 assert!(held.hold_reason.unwrap().contains("held for a human"));
5548 }
5549
5550 fn run_state(status: RunStatus) -> RunState {
5551 let mut state = RunState::new(
5552 PathBuf::from("/repo"),
5553 "main".to_owned(),
5554 "abc1234def".to_owned(),
5555 "add retries".to_owned(),
5556 Config::default(),
5557 );
5558 state.status = status;
5559 state
5560 }
5561
5562 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
5563 Candidate {
5564 index: 0,
5565 label,
5566 agent: "claude".to_owned(),
5567 branch: format!("magi/x/{label}"),
5568 worktree: PathBuf::from("/repo"),
5569 summary: summary.to_owned(),
5570 stat: String::new(),
5571 files: 0,
5572 commits: usize::from(!empty),
5573 empty,
5574 failed: failed.map(str::to_owned),
5575 verified_noop: None,
5576 duration_ms: 0,
5577 folded: false,
5578 }
5579 }
5580
5581 #[test]
5582 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
5583 let mut state = run_state(RunStatus::Blocked);
5584 state.gate = vec![
5585 CommandOutcome {
5586 command: "cargo make check".to_owned(),
5587 code: Some(0),
5588 output_tail: "ok".to_owned(),
5589 duration_ms: 0,
5590 resource_blocked: false,
5591 },
5592 CommandOutcome {
5593 command: "cargo test".to_owned(),
5594 code: Some(101),
5595 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
5596 duration_ms: 0,
5597 resource_blocked: false,
5598 },
5599 ];
5600 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
5601 assert!(d.contains("cargo test"), "{d}");
5602 assert!(
5603 !d.contains("cargo make check"),
5604 "a passing check is not a diagnostic: {d}"
5605 );
5606 assert!(d.contains("assertion failed"), "{d}");
5607 }
5608
5609 #[test]
5610 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
5611 let mut state = run_state(RunStatus::Blocked);
5612 state.event(
5613 "land",
5614 "stopped: the fixer produced no commit while 2 check(s) were failing \
5615 (build, lint); stopping instead of looping on an unchanged tree",
5616 );
5617 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
5618 assert!(d.contains("build"), "{d}");
5619 assert!(d.contains("lint"), "{d}");
5620 assert!(d.contains("fixer produced no commit"), "{d}");
5621 }
5622
5623 #[test]
5624 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
5625 let state = run_state(RunStatus::VerifiedNoop);
5630 let d = describe(&state);
5631 assert!(
5632 d.contains("agent-verified no-op"),
5633 "expected the display label, not the wire spelling: {d}"
5634 );
5635 assert!(!d.contains("verified_noop"), "{d}");
5636 }
5637
5638 #[test]
5639 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
5640 let mut state = run_state(RunStatus::Failed);
5646 state.candidates = vec![candidate(
5647 'A',
5648 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
5649 true,
5650 None,
5651 )];
5652 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
5653 assert!(d.contains("candidate A"), "{d}");
5654 assert!(d.contains("tagged v1.2.3"), "{d}");
5655 }
5656
5657 #[test]
5658 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
5659 let mut state = run_state(RunStatus::Failed);
5660 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
5661 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
5662 assert!(d.contains("candidate A"), "{d}");
5663 assert!(d.contains("agent timed out"), "{d}");
5664 }
5665
5666 #[test]
5667 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
5668 let mut state = run_state(RunStatus::Failed);
5671 state.candidates = vec![candidate('A', "did the work", false, None)];
5672 assert!(diagnostic(&state).is_none());
5673 }
5674
5675 #[test]
5676 fn diagnostic_is_bounded_however_much_a_run_printed() {
5677 let mut state = run_state(RunStatus::Blocked);
5678 state.gate = vec![
5679 CommandOutcome {
5680 command: "cargo test".to_owned(),
5681 code: Some(101),
5682 output_tail: "x".repeat(50_000),
5683 duration_ms: 0,
5684 resource_blocked: false,
5685 },
5686 CommandOutcome {
5687 command: "cargo clippy".to_owned(),
5688 code: Some(1),
5689 output_tail: "y".repeat(50_000),
5690 duration_ms: 0,
5691 resource_blocked: false,
5692 },
5693 ];
5694 state.candidates = vec![
5695 candidate('A', &"z".repeat(50_000), true, None),
5696 candidate('B', &"w".repeat(50_000), true, None),
5697 ];
5698 let d = diagnostic(&state).expect("plenty here to diagnose");
5699 assert!(
5700 d.len() <= DIAGNOSTIC_MAX,
5701 "diagnostic grew to {} bytes, unbounded",
5702 d.len()
5703 );
5704 }
5705
5706 #[test]
5707 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
5708 let mut state = run_state(RunStatus::Blocked);
5709 state.gate = vec![CommandOutcome {
5710 command: "cargo test".to_owned(),
5711 code: Some(101),
5712 output_tail: "assertion failed".to_owned(),
5713 duration_ms: 0,
5714 resource_blocked: false,
5715 }];
5716 let verdict = Verdict {
5717 status: RunStatus::Blocked,
5718 left_pr: false,
5719 quota_hit: false,
5720 parked: false,
5721 no_viable_candidates: false,
5722 };
5723
5724 let mut t = task();
5727 t.start("run-1".to_owned());
5728 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5729 assert_eq!(t.status, TaskStatus::Failed);
5730 assert!(t.diagnostic.is_none());
5731
5732 t.start("run-2".to_owned());
5735 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5736 assert_eq!(t.status, TaskStatus::Held);
5737 let d = t.diagnostic.expect("a held task must carry its diagnostic");
5738 assert!(d.contains("cargo test"), "{d}");
5739 }
5740
5741 #[test]
5742 fn a_held_task_names_the_open_question_it_is_waiting_on() {
5743 crate::run::pin_test_home();
5748 let home = crate::run::home();
5749 let state = run_state(RunStatus::VerifiedNoop);
5750 let mut q = ask::Question::new(
5751 state.id.clone(),
5752 "implement".to_owned(),
5753 "impl-A".to_owned(),
5754 "is this really a no-op?".to_owned(),
5755 String::new(),
5756 Vec::new(),
5757 );
5758 Questions::at(home.join("questions")).put(&mut q).unwrap();
5759
5760 let verdict = Verdict {
5761 status: RunStatus::VerifiedNoop,
5762 left_pr: false,
5763 quota_hit: false,
5764 parked: false,
5765 no_viable_candidates: false,
5766 };
5767 let mut t = task();
5768 t.start(state.id.clone());
5769 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5770
5771 assert_eq!(t.status, TaskStatus::Held);
5772 let reason = t.hold_reason.expect("a held task must record why");
5773 assert!(
5774 reason.starts_with("run ended agent-verified no-op"),
5775 "the original settle reason must survive unchanged: {reason}"
5776 );
5777 assert!(
5778 reason.contains(q.short()),
5779 "the open question's id must be named so the notice is actionable: {reason}"
5780 );
5781 }
5782
5783 #[test]
5784 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
5785 crate::run::pin_test_home();
5786 let state = run_state(RunStatus::VerifiedNoop);
5787
5788 let verdict = Verdict {
5789 status: RunStatus::VerifiedNoop,
5790 left_pr: false,
5791 quota_hit: false,
5792 parked: false,
5793 no_viable_candidates: false,
5794 };
5795 let mut t = task();
5796 t.start(state.id.clone());
5797 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5798
5799 assert_eq!(t.status, TaskStatus::Held);
5800 assert_eq!(
5801 t.hold_reason.as_deref(),
5802 Some("run ended agent-verified no-op"),
5803 "nothing to append when the question was already answered or never asked"
5804 );
5805 }
5806
5807 #[test]
5808 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5809 crate::run::pin_test_home();
5810 let mut first = run_state(RunStatus::Blocked);
5811 first.id = "20260101-000000-sup1".to_owned();
5812 first.save().unwrap();
5813 let mut second = run_state(RunStatus::Merged);
5814 second.id = "20260101-000000-sup2".to_owned();
5815 second.save().unwrap();
5816
5817 let mut t = task();
5818 t.runs = vec![first.id.clone(), second.id.clone()];
5819 t.status = TaskStatus::Done;
5820
5821 supersede_prior_runs(&t, &crate::run::home());
5822
5823 assert_eq!(
5824 RunState::load(&first.id).unwrap().status,
5825 RunStatus::Superseded,
5826 "the first attempt's Blocked no longer needs anyone's attention"
5827 );
5828 assert_eq!(
5829 RunState::load(&second.id).unwrap().status,
5830 RunStatus::Merged,
5831 "the run that actually succeeded is left exactly as it was"
5832 );
5833 }
5834
5835 #[test]
5836 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5837 crate::run::pin_test_home();
5843 let mut first = run_state(RunStatus::Blocked);
5844 first.id = "20260101-000000-sup9".to_owned();
5845 first.driver_pid = Some(std::process::id());
5848 first.driver_started_at = Some(
5849 crate::proc::process_started_at(std::process::id())
5850 .expect("this test process's own start time must be queryable"),
5851 );
5852 first.save().unwrap();
5853 let mut second = run_state(RunStatus::Merged);
5854 second.id = "20260101-000000-supa".to_owned();
5855 second.save().unwrap();
5856
5857 let mut t = task();
5858 t.runs = vec![first.id.clone(), second.id.clone()];
5859 t.status = TaskStatus::Done;
5860
5861 supersede_prior_runs(&t, &crate::run::home());
5862
5863 assert_eq!(
5864 RunState::load(&first.id).unwrap().status,
5865 RunStatus::Blocked,
5866 "a live driver_pid means something is still actually working this run, \
5867 even though no daemon claims it - rewriting under it would just be \
5868 undone the next time that process saves"
5869 );
5870 }
5871
5872 #[test]
5873 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5874 let dir = tempfile::tempdir().unwrap();
5880 let home = dir.path().to_path_buf();
5881 let queue = Queue::at(dir.path().join("queue"));
5882
5883 let mut first = run_state(RunStatus::Blocked);
5884 first.id = "20260101-000000-supd".to_owned();
5885 first.driver_pid = Some(std::process::id());
5886 first.driver_started_at = Some(
5887 crate::proc::process_started_at(std::process::id())
5888 .expect("this test process's own start time must be queryable"),
5889 );
5890 first.save_under(&home).unwrap();
5891 let mut second = run_state(RunStatus::Merged);
5892 second.id = "20260101-000000-supe".to_owned();
5893 second.save_under(&home).unwrap();
5894
5895 let mut t = task();
5896 t.runs = vec![first.id.clone(), second.id.clone()];
5897 t.status = TaskStatus::Done;
5898 queue.put(&mut t).unwrap();
5899
5900 resweep_superseded_attempts(&queue, &home);
5901 assert_eq!(
5902 RunState::load_under(&first.id, &home).unwrap().status,
5903 RunStatus::Blocked,
5904 "still live on the first pass, so still untouched"
5905 );
5906
5907 let mut stale = RunState::load_under(&first.id, &home).unwrap();
5913 stale.driver_started_at = Some("1".to_owned());
5914 stale.save_under(&home).unwrap();
5915
5916 resweep_superseded_attempts(&queue, &home);
5917 assert_eq!(
5918 RunState::load_under(&first.id, &home).unwrap().status,
5919 RunStatus::Superseded,
5920 "the second pass catches up what the first one correctly skipped"
5921 );
5922 }
5923
5924 #[test]
5925 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5926 crate::run::pin_test_home();
5927 let mut first = run_state(RunStatus::Blocked);
5928 first.id = "20260101-000000-sup3".to_owned();
5929 first.save().unwrap();
5930 let mut second = run_state(RunStatus::Blocked);
5931 second.id = "20260101-000000-sup4".to_owned();
5932 second.save().unwrap();
5933
5934 let mut t = task();
5935 t.runs = vec![first.id.clone(), second.id.clone()];
5936 t.status = TaskStatus::Failed;
5940
5941 supersede_prior_runs(&t, &crate::run::home());
5942
5943 assert_eq!(
5944 RunState::load(&first.id).unwrap().status,
5945 RunStatus::Blocked
5946 );
5947 assert_eq!(
5948 RunState::load(&second.id).unwrap().status,
5949 RunStatus::Blocked
5950 );
5951 }
5952
5953 #[test]
5954 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5955 crate::run::pin_test_home();
5959 let mut first = run_state(RunStatus::Blocked);
5960 first.id = "20260101-000000-sup5".to_owned();
5961 first.save().unwrap();
5962
5963 let mut t = task();
5964 t.runs = vec![first.id.clone()];
5965 t.status = TaskStatus::Done;
5966
5967 supersede_prior_runs(&t, &crate::run::home());
5968
5969 assert_eq!(
5970 RunState::load(&first.id).unwrap().status,
5971 RunStatus::Blocked,
5972 "a single-attempt task has no earlier run to supersede"
5973 );
5974 }
5975
5976 #[test]
5977 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
5978 crate::run::pin_test_home();
5985 let mut first = run_state(RunStatus::Blocked);
5986 first.id = "20260101-000000-supb".to_owned();
5987 first.save().unwrap();
5988 let mut second = run_state(RunStatus::Failed);
5989 second.id = "20260101-000000-supc".to_owned();
5990 second.save().unwrap();
5991
5992 let mut t = task();
5993 t.runs = vec![first.id.clone(), second.id.clone()];
5994 t.status = TaskStatus::Done;
5995
5996 supersede_prior_runs(&t, &crate::run::home());
5997
5998 assert_eq!(
5999 RunState::load(&first.id).unwrap().status,
6000 RunStatus::Blocked,
6001 "the task's last attempt never landed, so there is nothing here \
6002 actually superseding it"
6003 );
6004 }
6005
6006 #[test]
6007 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6008 crate::run::pin_test_home();
6012 let mut failed = run_state(RunStatus::Failed);
6013 failed.id = "20260101-000000-sup6".to_owned();
6014 failed.save().unwrap();
6015 let mut noop = run_state(RunStatus::VerifiedNoop);
6016 noop.id = "20260101-000000-sup7".to_owned();
6017 noop.save().unwrap();
6018 let mut winner = run_state(RunStatus::Ready);
6019 winner.id = "20260101-000000-sup8".to_owned();
6020 winner.save().unwrap();
6021
6022 let mut t = task();
6023 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6024 t.status = TaskStatus::Done;
6025
6026 supersede_prior_runs(&t, &crate::run::home());
6027
6028 assert_eq!(
6029 RunState::load(&failed.id).unwrap().status,
6030 RunStatus::Failed
6031 );
6032 assert_eq!(
6033 RunState::load(&noop.id).unwrap().status,
6034 RunStatus::VerifiedNoop
6035 );
6036 }
6037
6038 fn approval_question(run: &str) -> ask::Question {
6039 ask::Question::new(
6040 run.to_owned(),
6041 land::APPROVAL_NODE.to_owned(),
6042 "land".to_owned(),
6043 "merge?".to_owned(),
6044 String::new(),
6045 vec!["merge".to_owned(), "hold".to_owned()],
6046 )
6047 }
6048
6049 #[test]
6050 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6051 crate::run::pin_test_home();
6052 let mut state = run_state(RunStatus::Landing);
6053 state.id = "20260101-000000-fre1".to_owned();
6054 state.parked = true;
6055 state.save().unwrap();
6056 ask::Questions::open()
6057 .put(&mut approval_question(&state.id))
6058 .unwrap();
6059
6060 let mut t = task();
6061 t.runs.push(state.id.clone());
6062 assert_eq!(
6063 land_resume_state(&t),
6064 LandResume::StillWaiting,
6065 "nobody has answered and the timeout has not passed"
6066 );
6067 }
6068
6069 #[test]
6070 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6071 crate::run::pin_test_home();
6072 let mut state = run_state(RunStatus::Gating);
6073 state.id = "20260101-000000-gt01".to_owned();
6074 state.parked = true;
6075 state.config.graph.answer_timeout = 60;
6076 state.github_text = Some(crate::run::GithubTextAsk {
6077 fingerprint: "f".into(),
6078 title: true,
6079 body: false,
6080 categories: vec!["title-language".into()],
6081 question: None,
6082 asks: 1,
6083 resolved: false,
6084 chosen_title: None,
6085 });
6086 state.save().unwrap();
6087 let store = ask::Questions::open();
6088 let mut q = ask::Question::new(
6089 state.id.clone(),
6090 crate::github_text::ASK_NODE.to_owned(),
6091 crate::github_text::ASK_SEAT.to_owned(),
6092 "s".into(),
6093 String::new(),
6094 vec!["use fallback".into()],
6095 );
6096 store.put(&mut q).unwrap();
6097 let mut t = task();
6098 t.runs.push(state.id.clone());
6099 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6100 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6101 store.put(&mut q).unwrap();
6102 assert_eq!(land_resume_state(&t), LandResume::Ready);
6103 assert!(!store.get(&q.id).unwrap().status.open());
6104 state.github_text.as_mut().unwrap().resolved = true;
6106 state.save().unwrap();
6107 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6108 }
6109
6110 #[test]
6111 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6112 crate::run::pin_test_home();
6117 let mut state = run_state(RunStatus::Landing);
6118 state.id = "20260101-000000-exp1".to_owned();
6119 state.parked = true;
6120 state.config.graph.answer_timeout = 60;
6121 state.save().unwrap();
6122
6123 let store = ask::Questions::open();
6124 let mut q = approval_question(&state.id);
6125 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6126 store.put(&mut q).unwrap();
6127
6128 let mut t = task();
6129 t.runs.push(state.id.clone());
6130 assert_eq!(
6131 land_resume_state(&t),
6132 LandResume::Ready,
6133 "an expired question must not be waited on forever"
6134 );
6135
6136 let after = store.get(&q.id).unwrap();
6137 assert!(
6138 !after.status.open(),
6139 "the question is abandoned, not silently ignored"
6140 );
6141 assert!(
6142 after.resolution().is_none(),
6143 "an abandoned question is not read as a decision"
6144 );
6145 }
6146
6147 #[test]
6148 fn reclaim_settles_a_running_task_against_its_last_run() {
6149 let mut t = task();
6150 t.start("20260904-000000-4043".to_owned());
6151 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6152 assert_eq!(
6153 t.status,
6154 TaskStatus::Done,
6155 "a run that actually finished must not stay `running` forever"
6156 );
6157 }
6158
6159 #[test]
6160 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6161 let mut t = task();
6162 t.start("20260904-000000-4043".to_owned());
6163 t.last_error = Some("earlier trouble".to_owned());
6164 let mut state = run_state(RunStatus::Judging);
6165 state.parked = true;
6166 reclaim(&mut t, Some(state), 1, "en");
6167 assert_eq!(t.status, TaskStatus::Parked);
6168 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6169 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6170 assert!(t.park_reason.is_some());
6171 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6172 assert!(!t.fresh_start);
6173 assert!(t.status.runnable());
6174 }
6175
6176 #[test]
6177 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6178 let mut t = task();
6179 t.start("20260904-000000-4043".to_owned());
6180 t.last_error = Some("earlier trouble".to_owned());
6181 settle(
6182 &mut t,
6183 Verdict {
6184 status: RunStatus::Judging,
6185 left_pr: false,
6186 quota_hit: false,
6187 parked: true,
6188 no_viable_candidates: false,
6189 },
6190 "parked after `judging`",
6191 1,
6192 );
6193 assert_eq!(t.status, TaskStatus::Parked);
6194 assert_eq!(t.attempts, 0);
6195 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6196 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6197 assert_eq!(t.schema, crate::queue::SCHEMA);
6198 assert!(
6199 crate::notices::task_held(&t).is_none(),
6200 "a park is not news"
6201 );
6202 t.start("20260904-000000-4043".to_owned());
6203 assert_eq!(t.park_reason, None);
6204 }
6205
6206 #[test]
6207 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6208 let mut t = task();
6212 t.start("20260904-000000-4043".to_owned());
6213 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6214 assert_eq!(t.status, TaskStatus::Failed);
6215 assert!(t.status.runnable());
6216 }
6217
6218 #[test]
6219 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6220 let mut t = task();
6221 t.start("20260904-000000-4043".to_owned());
6222 reclaim(&mut t, None, 2, "en");
6223 assert_eq!(t.status, TaskStatus::Held);
6224 assert!(
6225 t.last_error
6226 .as_deref()
6227 .is_some_and(|e| e.contains("running")),
6228 "the operator needs to know why this task was held"
6229 );
6230 }
6231
6232 #[test]
6233 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6234 let dir = tempfile::tempdir().unwrap();
6235 let queue = Queue::at(dir.path().to_path_buf());
6236
6237 let mut orphaned = task();
6239 orphaned.id = "20260904-000000-orph".to_owned();
6240 orphaned.status = TaskStatus::Running;
6241 orphaned.attempts = 1;
6242 queue.put(&mut orphaned).unwrap();
6243
6244 let mut alive = task();
6245 alive.id = "20260904-000000-live".to_owned();
6246 alive.status = TaskStatus::Running;
6247 alive.attempts = 1;
6248 queue.put(&mut alive).unwrap();
6249 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6250
6251 let mut queued = task();
6252 queued.id = "20260904-000000-wait".to_owned();
6253 queue.put(&mut queued).unwrap();
6254
6255 let reclaimed = reclaim_orphaned_running(&queue, 2);
6256 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6257
6258 assert_eq!(
6259 queue.get(&orphaned.id).unwrap().status,
6260 TaskStatus::Held,
6261 "nothing was driving it and there was no run to recover"
6262 );
6263 assert_eq!(
6264 queue.get(&alive.id).unwrap().status,
6265 TaskStatus::Running,
6266 "a live claim must protect the task it belongs to"
6267 );
6268 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6269 }
6270
6271 fn read_run_under(home: &Path, id: &str) -> RunState {
6277 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6278 serde_json::from_str(&body).unwrap()
6279 }
6280
6281 #[test]
6282 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6283 let dir = tempfile::tempdir().unwrap();
6284 let home = dir.path().to_path_buf();
6285 let now = Timestamp::now();
6286 let overrun_seat = || crate::run::ActiveSeat {
6287 node: "implement".to_owned(),
6288 started_at: now - jiff::SignedDuration::new(21_000, 0),
6289 timeout_secs: 3_600,
6290 attempt: 0,
6291 task: None,
6292 command: None,
6293 index: None,
6294 total: None,
6295 };
6296
6297 let mut dead = run_state(RunStatus::Implementing);
6298 dead.id = "20260101-000000-dead".to_owned();
6299 dead.active.insert("impl-A".to_owned(), overrun_seat());
6300 dead.driver_pid = Some(4242);
6303 dead.save_under(&home).unwrap();
6304
6305 let mut alive = run_state(RunStatus::Implementing);
6308 alive.id = "20260101-000000-aliv".to_owned();
6309 alive.active.insert("impl-A".to_owned(), overrun_seat());
6310 alive.save_under(&home).unwrap();
6311 let mut status = Status::new();
6312 status.current = vec![Current {
6313 task: "20260101-000000-task".to_owned(),
6314 run: alive.id.clone(),
6315 }];
6316 write_status_to(&home.join("daemon.json"), &status).unwrap();
6317
6318 let questions = Questions::at(home.join("questions"));
6322 let mut q = ask::Question::new(
6323 dead.id.clone(),
6324 "implement".to_owned(),
6325 "impl-A".to_owned(),
6326 "Which storage backend?".to_owned(),
6327 String::new(),
6328 vec!["SQLite".to_owned(), "Redis".to_owned()],
6329 );
6330 questions.put(&mut q).unwrap();
6331
6332 let abandoned = reclaim_abandoned_runs_with(
6333 &home,
6334 now,
6335 |pid| if pid == 4242 { Some(false) } else { None },
6336 |_| panic!("a query answering Dead outright needs no identity corroboration"),
6337 );
6338 assert_eq!(abandoned, vec![dead.id.clone()]);
6339
6340 let reloaded = read_run_under(&home, &dead.id);
6341 assert_eq!(reloaded.status, RunStatus::Failed);
6342 assert!(reloaded.active.is_empty());
6343 assert!(
6344 !questions.get(&q.id).unwrap().status.open(),
6345 "the failed run's own open question must be settled in the same pass"
6346 );
6347
6348 let still_alive = read_run_under(&home, &alive.id);
6349 assert_eq!(
6350 still_alive.status,
6351 RunStatus::Implementing,
6352 "a live daemon's claim protects it"
6353 );
6354 assert!(!still_alive.active.is_empty());
6355 }
6356
6357 #[test]
6367 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
6368 let dir = tempfile::tempdir().unwrap();
6369 let home = dir.path().to_path_buf();
6370 let now = Timestamp::now();
6371
6372 let mut manual = run_state(RunStatus::Reviewing);
6373 manual.id = "20260101-000000-manl".to_owned();
6374 manual.active.insert(
6375 "review-1".to_owned(),
6376 crate::run::ActiveSeat {
6377 node: "review".to_owned(),
6378 started_at: now - jiff::SignedDuration::new(21_000, 0),
6379 timeout_secs: 3_600,
6380 attempt: 0,
6381 task: None,
6382 command: None,
6383 index: None,
6384 total: None,
6385 },
6386 );
6387 manual.driver_pid = Some(4242);
6391 manual.driver_started_at = Some("1790000000".to_owned());
6392 manual.save_under(&home).unwrap();
6393
6394 let abandoned = reclaim_abandoned_runs_with(
6395 &home,
6396 now,
6397 |pid| if pid == 4242 { Some(true) } else { None },
6398 |pid| {
6399 if pid == 4242 {
6400 Some("1790000000".to_owned())
6401 } else {
6402 None
6403 }
6404 },
6405 );
6406 assert!(
6407 abandoned.is_empty(),
6408 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
6409 );
6410
6411 let reloaded = read_run_under(&home, &manual.id);
6412 assert_eq!(reloaded.status, RunStatus::Reviewing);
6413 assert!(!reloaded.active.is_empty());
6414 }
6415
6416 #[test]
6417 fn an_already_claimed_task_is_skipped_rather_than_failed() {
6418 let dir = tempfile::tempdir().unwrap();
6419 let queue = Queue::at(dir.path().to_path_buf());
6420 let mut only = task();
6421 queue.put(&mut only).unwrap();
6422
6423 let _elsewhere = queue.claim(&only.id).unwrap();
6424 let candidates = runnable(&queue);
6425 assert_eq!(candidates.len(), 1, "the task is still runnable");
6426 assert!(
6427 queue.claim(&candidates[0].id).is_err(),
6428 "the loop cannot take a claim somebody else holds"
6429 );
6430
6431 let after = queue.get(&only.id).unwrap();
6432 assert_eq!(after.status, TaskStatus::Queued);
6433 assert_eq!(
6434 after.attempts, 0,
6435 "losing the race is not an attempt at the task"
6436 );
6437 assert_eq!(after.last_error, None);
6438 }
6439
6440 #[test]
6441 fn the_status_file_round_trips_and_its_heartbeat_advances() {
6442 let dir = tempfile::tempdir().unwrap();
6443 let path = dir.path().join("daemon.json");
6444
6445 let mut status = Status::new();
6446 status.idle = false;
6447 status.completed = 7;
6448 status.current = vec![Current {
6449 task: "20260902-000000-t111".to_owned(),
6450 run: "20260902-000001-r111".to_owned(),
6451 }];
6452 write_status_to(&path, &status).unwrap();
6453 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6454 assert_eq!(first.schema, SCHEMA);
6455 assert_eq!(first.pid, std::process::id());
6456 assert!(!first.idle);
6457 assert_eq!(first.completed, 7);
6458 assert_eq!(first.current, status.current);
6459 assert!(
6460 !path.with_extension("json.tmp").exists(),
6461 "the temp file is renamed, not left behind"
6462 );
6463
6464 std::thread::sleep(Duration::from_millis(5));
6465 status.updated_at = Timestamp::now();
6466 status.polls = 3;
6467 write_status_to(&path, &status).unwrap();
6468 let second: Status =
6469 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6470 assert!(
6471 second.updated_at > first.updated_at,
6472 "a reader can only detect staleness if the heartbeat moves"
6473 );
6474 assert_eq!(
6475 second.started_at, first.started_at,
6476 "the start time is not a heartbeat"
6477 );
6478 assert_eq!(second.polls, 3);
6479 }
6480
6481 #[test]
6482 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
6483 let dir = tempfile::tempdir().unwrap();
6484
6485 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
6486
6487 let mut status = Status::new();
6488 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
6489 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6490 let stale = read_status(dir.path()).unwrap();
6491 assert!(
6492 !stale.running(Timestamp::now()),
6493 "a minute without a heartbeat is a dead daemon, not a busy one"
6494 );
6495 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
6496
6497 status.updated_at = Timestamp::now();
6498 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6499 let fresh = read_status(dir.path()).unwrap();
6500 assert!(fresh.running(Timestamp::now()));
6501 }
6502
6503 #[test]
6504 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
6505 let dir = tempfile::tempdir().unwrap();
6506 let now = Timestamp::now();
6507 let mine = "20260903-080619-01c2";
6508
6509 assert!(
6510 !is_working_on(dir.path(), mine, now),
6511 "no status file means nobody is working on anything"
6512 );
6513
6514 let mut status = Status::new();
6515 status.current = vec![Current {
6516 task: "20260903-080340-0167".to_owned(),
6517 run: mine.to_owned(),
6518 }];
6519 status.updated_at = now;
6520 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6521 assert!(is_working_on(dir.path(), mine, now));
6522 assert!(
6523 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
6524 "a daemon busy with one run is not working on another"
6525 );
6526
6527 status.updated_at = now - jiff::SignedDuration::from_secs(600);
6530 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6531 assert!(
6532 !is_working_on(dir.path(), mine, now),
6533 "a stale heartbeat is a dead daemon, so its run is a leftover"
6534 );
6535 }
6536
6537 #[test]
6538 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
6539 let dir = tempfile::tempdir().unwrap();
6540 let now = Timestamp::now();
6541
6542 assert!(
6543 !is_working_on_short(dir.path(), "01c2", now),
6544 "no status file means nobody is working on anything"
6545 );
6546
6547 let mut status = Status::new();
6548 status.current = vec![Current {
6549 task: "20260903-080340-0167".to_owned(),
6550 run: "20260903-080619-01c2".to_owned(),
6551 }];
6552 status.updated_at = now;
6553 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6554 assert!(
6555 is_working_on_short(dir.path(), "01c2", now),
6556 "the run's short id is the last block of its full id"
6557 );
6558 assert!(
6559 !is_working_on_short(dir.path(), "3cbf", now),
6560 "a daemon busy with one worktree bay is not working on another"
6561 );
6562 }
6563
6564 #[test]
6565 fn a_newer_status_file_still_yields_a_reading() {
6566 let dir = tempfile::tempdir().unwrap();
6567 std::fs::write(
6570 dir.path().join("daemon.json"),
6571 serde_json::json!({
6572 "schema": 2,
6573 "updated_at": Timestamp::now().to_string(),
6574 "idle": true,
6575 "surprise": { "nested": [1, 2, 3] },
6576 })
6577 .to_string(),
6578 )
6579 .unwrap();
6580
6581 let reading = read_status(dir.path()).expect("a forward-compatible read");
6582 assert!(reading.running(Timestamp::now()));
6583 assert!(reading.idle);
6584 assert!(reading.current.is_empty());
6585 }
6586
6587 #[test]
6588 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
6589 let dir = tempfile::tempdir().unwrap();
6595 std::fs::write(
6596 dir.path().join("daemon.json"),
6597 serde_json::json!({
6598 "schema": 1,
6599 "pid": 4242,
6600 "updated_at": Timestamp::now().to_string(),
6601 "idle": false,
6602 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
6603 "completed": 3,
6604 "polls": 9,
6605 })
6606 .to_string(),
6607 )
6608 .unwrap();
6609
6610 let reading = read_status(dir.path()).expect("an older shape must still parse");
6611 assert!(reading.running(Timestamp::now()));
6612 assert_eq!(
6613 reading.current,
6614 vec![Current {
6615 task: "20260902-140501-aaaa".to_owned(),
6616 run: "20260902-140502-bbbb".to_owned(),
6617 }]
6618 );
6619 }
6620
6621 #[test]
6622 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
6623 let dir = tempfile::tempdir().unwrap();
6624 std::fs::write(
6625 dir.path().join("daemon.json"),
6626 serde_json::json!({
6627 "schema": 1,
6628 "updated_at": Timestamp::now().to_string(),
6629 "idle": true,
6630 "current": null,
6631 })
6632 .to_string(),
6633 )
6634 .unwrap();
6635 let with_null = read_status(dir.path()).expect("null must still parse");
6636 assert!(with_null.current.is_empty());
6637
6638 std::fs::write(
6639 dir.path().join("daemon.json"),
6640 serde_json::json!({
6641 "schema": 1,
6642 "updated_at": Timestamp::now().to_string(),
6643 "idle": true,
6644 })
6645 .to_string(),
6646 )
6647 .unwrap();
6648 let absent = read_status(dir.path()).expect("a missing field must still parse");
6649 assert!(absent.current.is_empty());
6650 }
6651
6652 #[test]
6653 fn a_task_without_a_repository_runs_in_the_daemons_default() {
6654 let fallback = Path::new("/default");
6655 let mut blank = task();
6656 blank.repo = PathBuf::new();
6657 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
6658 let mut dot = task();
6659 dot.repo = PathBuf::from(".");
6660 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
6661 assert_eq!(
6662 repo_for(&task(), fallback),
6663 PathBuf::from("/repo"),
6664 "a task that names a repository keeps it"
6665 );
6666 }
6667
6668 #[test]
6669 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
6670 let mut solo_cfg = Config::default();
6676 solo_cfg.graph.implementers = 3;
6677 let mut solo_task = task();
6678 solo_task.solo = true;
6679 apply_solo(&mut solo_cfg, &solo_task);
6680 assert_eq!(solo_cfg.graph.implementers, 1);
6681
6682 let mut plain_cfg = Config::default();
6683 plain_cfg.graph.implementers = 3;
6684 let plain_task = task();
6685 assert!(!plain_task.solo);
6686 apply_solo(&mut plain_cfg, &plain_task);
6687 assert_eq!(
6688 plain_cfg.graph.implementers, 3,
6689 "a task that did not ask to run alone keeps the config's candidates"
6690 );
6691 }
6692
6693 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
6694 QuotaLoss {
6695 seat: seat.into(),
6696 node: "judge".into(),
6697 at: at.parse().unwrap(),
6698 reset: reset.map(str::to_string),
6699 }
6700 }
6701
6702 #[test]
6703 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
6704 let old: Vec<QuotaLoss> = (1..=4)
6705 .map(|i| {
6706 loss(
6707 &format!("judge-{i}"),
6708 "2026-09-23T05:23:00Z",
6709 Some("2:40pm (Asia/Tokyo)"),
6710 )
6711 })
6712 .collect();
6713 let fresh = losses_this_attempt(&old, &old);
6714 assert!(fresh.is_empty());
6715 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
6716 }
6718
6719 #[test]
6720 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
6721 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
6722 let now = Timestamp::now();
6723 let mut after = old.clone();
6724 after.push(loss("judge-2", &now.to_string(), None));
6725 let fresh = losses_this_attempt(&old, &after);
6726 assert_eq!(fresh, vec![after[1].clone()]);
6727 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
6728 assert_eq!(
6729 until,
6730 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
6731 );
6732 }
6733
6734 #[test]
6735 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
6736 let before = vec![
6739 loss("judge-1", "2026-09-23T05:23:00Z", None),
6740 loss("judge-2", "2026-09-23T05:24:00Z", None),
6741 ];
6742 let after = vec![
6743 loss("judge-2", "2026-09-23T05:24:00Z", None),
6744 loss("judge-1", "2026-09-24T01:00:00Z", None),
6745 ];
6746 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
6747 }
6748
6749 #[test]
6750 fn merge_overrides_are_parsed_or_refused() {
6751 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
6752 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
6753 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
6754 assert!(merge_mode("squash").is_err());
6755 }
6756
6757 #[test]
6758 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
6759 let now = Timestamp::now();
6760 let fallback = Duration::from_secs(300);
6761 let cap = Duration::from_secs(1800);
6762
6763 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
6765
6766 let soon = now + jiff::SignedDuration::from_secs(600);
6768 assert_eq!(
6769 quota_wait(Some(soon), now, fallback, cap),
6770 Duration::from_secs(600)
6771 );
6772
6773 let past = now - jiff::SignedDuration::from_secs(60);
6776 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
6777
6778 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
6781 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
6782 }
6783
6784 #[test]
6785 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
6786 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6787
6788 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
6789 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
6790
6791 let already_past =
6795 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
6796 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
6797
6798 assert!(
6799 parse_reset_hint("session limit reached", now, now).is_none(),
6800 "free text with no recognised shape is not guessed at"
6801 );
6802 assert!(
6803 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
6804 "an unresolvable zone name is not guessed at either"
6805 );
6806 }
6807
6808 #[test]
6809 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
6810 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6811
6812 let at = parse_reset_hint(
6813 "You've hit your usage limit. Visit \
6814 https://chatgpt.com/codex/settings/usage to purchase more \
6815 credits or try again at Sep 19th, 2026 5:10 PM.",
6816 now,
6817 now,
6818 )
6819 .expect("the codex reset wording is a recognised shape");
6820 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
6821
6822 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
6827 .expect("an explicit year needs no rollover");
6828 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
6829
6830 assert!(
6831 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
6832 "a two-digit year is not the documented shape and is not guessed at"
6833 );
6834 assert!(
6835 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
6836 "a four-letter month name is not the documented three-letter abbreviation"
6837 );
6838 assert!(
6839 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
6840 "an explicit zone on the dated shape is a format nobody has \
6841 documented, and is refused rather than guessed at as UTC"
6842 );
6843 }
6844
6845 #[test]
6846 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
6847 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
6848 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
6849
6850 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
6851 assert_eq!(at.as_second() - recorded.as_second(), 3769);
6852
6853 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
6854 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
6855
6856 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
6857 assert!(
6858 parse_reset_hint(bad, now, recorded).is_none(),
6859 "{bad:?} must not be guessed at"
6860 );
6861 }
6862 }
6863
6864 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
6868 let config = dir.join("magi.toml");
6869 std::fs::write(
6870 &config,
6871 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
6872 )
6873 .unwrap();
6874 let opts = Opts {
6875 poll: Duration::from_secs(30),
6876 config: Some(config),
6877 repo: dir.join("repo"),
6881 ..Opts::default()
6882 };
6883 let home = dir.join("home");
6892 let worktrees = dir.join("wt");
6893 (
6894 opts,
6895 Queue::at(dir.join("queue")),
6896 home.join("daemon.json"),
6897 home,
6898 worktrees,
6899 )
6900 }
6901
6902 #[test]
6903 fn a_stop_is_idempotent_and_once_set_stays_set() {
6904 let stop = Stop::new();
6905 assert!(!stop.stopped());
6906
6907 stop.stop();
6908 assert!(stop.stopped());
6909 stop.stop();
6910 assert!(stop.stopped(), "a second stop is not a toggle");
6911
6912 let shared = stop.clone();
6913 assert!(
6914 shared.stopped(),
6915 "a clone is the same stop; that is how the loop and its caller share one"
6916 );
6917 }
6918
6919 #[test]
6920 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
6921 let stop = Stop::new();
6922 stop.enter();
6923 assert!(
6924 !stop.finishing(),
6925 "a busy loop nobody has asked to stop is just running"
6926 );
6927
6928 stop.stop();
6929 assert!(
6930 stop.finishing(),
6931 "a stop asked for mid-run has not landed until the run is settled"
6932 );
6933
6934 stop.exit();
6935 assert!(
6936 !stop.finishing(),
6937 "once the run is settled the stop has landed and there is nothing to finish"
6938 );
6939 }
6940
6941 #[test]
6942 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6943 let stop = Stop::new();
6944 stop.enter();
6945 stop.enter();
6946 stop.stop();
6947 assert!(stop.finishing(), "two runs still in flight");
6948
6949 stop.exit();
6950 assert!(
6951 stop.finishing(),
6952 "one run finished, but a sibling is still working"
6953 );
6954
6955 stop.exit();
6956 assert!(
6957 !stop.finishing(),
6958 "the last run out is what actually lands the stop"
6959 );
6960 }
6961
6962 #[tokio::test]
6963 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
6964 let dir = tempfile::tempdir().unwrap();
6965 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6966 let stop = Stop::new();
6967 stop.stop();
6968
6969 let began = std::time::Instant::now();
6970 tokio::time::timeout(
6971 Duration::from_secs(2),
6972 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6973 )
6974 .await
6975 .expect("a stopped loop must return, not sit out its poll interval")
6976 .expect("the loop's own setup and teardown must not fail");
6977 assert!(
6978 began.elapsed() < opts.poll,
6979 "returned only after {:?}, which is a poll interval, not a stop",
6980 began.elapsed()
6981 );
6982 }
6983
6984 #[tokio::test]
6985 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
6986 let dir = tempfile::tempdir().unwrap();
6987 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6988 let stop = Stop::new();
6989
6990 let asker = {
6993 let stop = stop.clone();
6994 tokio::spawn(async move {
6995 tokio::time::sleep(Duration::from_millis(20)).await;
6996 stop.stop();
6997 })
6998 };
6999
7000 let began = std::time::Instant::now();
7001 tokio::time::timeout(
7002 Duration::from_secs(2),
7003 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7004 )
7005 .await
7006 .expect("a stop asked for while idle must wake the wait")
7007 .expect("the loop's own setup and teardown must not fail");
7008 asker.await.unwrap();
7009 assert!(
7010 began.elapsed() < opts.poll,
7011 "returned only after {:?}, so the stop waited on the sleep",
7012 began.elapsed()
7013 );
7014 }
7015
7016 #[tokio::test]
7017 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
7018 let dir = tempfile::tempdir().unwrap();
7019 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7020 let stop = Stop::new();
7021 stop.stop();
7022
7023 tokio::time::timeout(
7024 Duration::from_secs(2),
7025 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7026 )
7027 .await
7028 .expect("a stopped loop must return")
7029 .expect("the loop's own setup and teardown must not fail");
7030
7031 assert!(
7032 home.is_dir(),
7033 "the loop did publish a status file, so its removal is the teardown and not an absence"
7034 );
7035 assert!(
7036 !status_file.exists(),
7037 "a stopped loop clears its status file"
7038 );
7039 assert!(
7040 read_status(&home).is_none(),
7041 "a reader must see no daemon at all, not a heartbeat that merely stopped"
7042 );
7043 }
7044
7045 #[tokio::test]
7046 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
7047 let dir = tempfile::tempdir().unwrap();
7048 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7049 opts.once = true;
7050
7051 let mut settled = RunState::new(
7052 dir.path().join("repo"),
7053 "main".to_owned(),
7054 "abc1234".to_owned(),
7055 "fixture".to_owned(),
7056 Config::default(),
7057 );
7058 settled.status = RunStatus::Ready;
7059 let run_dir = home.join("runs").join(&settled.id);
7060 std::fs::create_dir_all(&run_dir).unwrap();
7061 std::fs::write(
7062 run_dir.join("run.json"),
7063 serde_json::to_string_pretty(&settled).unwrap(),
7064 )
7065 .unwrap();
7066 let questions = Questions::at(home.join("questions"));
7067 let mut question = ask::Question::new(
7068 settled.id.clone(),
7069 "review".to_owned(),
7070 "reviewer-1".to_owned(),
7071 "Continue?".to_owned(),
7072 String::new(),
7073 Vec::new(),
7074 );
7075 questions.put(&mut question).unwrap();
7076
7077 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
7078 .await
7079 .unwrap();
7080
7081 assert_eq!(
7082 questions.get(&question.id).unwrap().status,
7083 ask::QuestionStatus::Abandoned,
7084 "an empty --once drain still performs startup question cleanup"
7085 );
7086 }
7087
7088 #[test]
7089 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
7090 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7091
7092 assert!(
7093 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
7094 "never checked before: due at once"
7095 );
7096
7097 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
7098 assert!(
7099 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
7100 "well inside the interval: not due yet"
7101 );
7102
7103 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
7104 assert!(
7105 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
7106 "exactly at the edge: not yet due, same convention as `clean::due`"
7107 );
7108
7109 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7110 assert!(
7111 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
7112 "past the interval: due again"
7113 );
7114 }
7115
7116 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
7121 let config = dir.join("magi.toml");
7122 std::fs::write(
7128 &config,
7129 format!(
7130 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7131 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7132 cache_dir.display()
7133 ),
7134 )
7135 .unwrap();
7136 Opts {
7137 config: Some(config),
7138 repo: dir.join("repo"),
7139 ..Opts::default()
7140 }
7141 }
7142
7143 #[tokio::test]
7144 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
7145 let dir = tempfile::tempdir().unwrap();
7146 let home = dir.path().join("home");
7147 let cache_dir = dir.path().join("cache");
7148 std::fs::create_dir_all(&cache_dir).unwrap();
7149 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7150 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7151
7152 let running = Stop::new();
7155 let mut last_checked = None;
7156 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7157 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
7158 .await;
7159 assert_eq!(
7160 crate::disk::dir_size(&cache_dir),
7161 0,
7162 "over the cap on the first check ever: pruned at once, no idle queue required"
7163 );
7164 assert_eq!(last_checked, Some(t0));
7165
7166 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
7168 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
7169 maybe_prune_cache_between_runs(
7170 &opts.repo,
7171 &opts,
7172 &home,
7173 &running,
7174 &mut last_checked,
7175 too_soon,
7176 )
7177 .await;
7178 assert_eq!(
7179 crate::disk::dir_size(&cache_dir),
7180 10,
7181 "too soon since the last check: left alone rather than rescanned every call"
7182 );
7183 assert_eq!(
7184 last_checked,
7185 Some(t0),
7186 "an idle check does not reset the clock"
7187 );
7188
7189 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7191 maybe_prune_cache_between_runs(
7192 &opts.repo,
7193 &opts,
7194 &home,
7195 &running,
7196 &mut last_checked,
7197 due_again,
7198 )
7199 .await;
7200 assert_eq!(
7201 crate::disk::dir_size(&cache_dir),
7202 0,
7203 "due again: pruned back under the cap"
7204 );
7205 }
7206
7207 #[tokio::test]
7215 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
7216 let dir = tempfile::tempdir().unwrap();
7217 let home = dir.path().join("home");
7218 let cache_dir = dir.path().join("cache");
7219 std::fs::create_dir_all(&cache_dir).unwrap();
7220 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7221 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7222
7223 let stop = Stop::new();
7224 stop.stop();
7225 assert!(
7226 !stop.finishing(),
7227 "no run is in flight at a between-runs boundary, so nothing else \
7228 would tell the operator this stop had not taken effect yet"
7229 );
7230
7231 let mut last_checked = None;
7232 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7233 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
7234 .await;
7235 assert_eq!(
7236 crate::disk::dir_size(&cache_dir),
7237 10,
7238 "over its cap, and due for the first check ever, but a stop outranks \
7239 it: the cap is a standing policy the next start measures again"
7240 );
7241 assert_eq!(
7242 last_checked, None,
7243 "a check that never happened must not claim the interval"
7244 );
7245 }
7246
7247 #[tokio::test]
7261 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
7262 let dir = tempfile::tempdir().unwrap();
7263 let cache_dir = dir.path().join("cache");
7264 std::fs::create_dir_all(&cache_dir).unwrap();
7265 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
7266
7267 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
7268 opts.poll = Duration::from_millis(20);
7269 opts.max_attempts = 1_000;
7270
7271 let queue = Queue::at(dir.path().join("queue"));
7272 let mut t = Task::new(
7273 "x".to_owned(),
7274 "x".to_owned(),
7275 opts.repo.clone(),
7276 Source::Human,
7277 );
7278 queue.put(&mut t).unwrap();
7279
7280 let home = dir.path().join("home");
7281 let worktrees = dir.path().join("wt");
7282 let status_file = home.join("daemon.json");
7283 let stop = Stop::new();
7284 let stopper = {
7285 let stop = stop.clone();
7286 let queue = Queue::at(dir.path().join("queue"));
7287 let id = t.id.clone();
7288 tokio::spawn(async move {
7289 tokio::time::sleep(Duration::from_millis(400)).await;
7293 for _ in 0..200 {
7294 if queue.get(&id).is_ok_and(|t| t.attempts >= 2) {
7295 break;
7296 }
7297 tokio::time::sleep(Duration::from_millis(50)).await;
7298 }
7299 stop.stop();
7300 })
7301 };
7302
7303 tokio::time::timeout(
7304 Duration::from_secs(20),
7305 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7306 )
7307 .await
7308 .expect("the loop must not hang on a queue that keeps producing failing work")
7309 .expect("the loop's own setup and teardown must not fail");
7310 stopper.await.unwrap();
7311
7312 let after = queue.get(&t.id).unwrap();
7313 assert!(
7314 after.attempts >= 2,
7315 "the harness must actually have retried more than once, or this is not \
7316 exercising a busy queue at all (got {} attempt(s))",
7317 after.attempts
7318 );
7319 assert!(
7320 after.status.runnable(),
7321 "still under its attempt budget: the queue never reached a natural idle \
7322 on its own, only the external stop ended the test"
7323 );
7324
7325 assert_eq!(
7326 crate::disk::dir_size(&cache_dir),
7327 0,
7328 "an oversized cache must not be left to grow unboundedly just because the \
7329 queue kept the loop busy the whole time"
7330 );
7331 }
7332
7333 #[test]
7334 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
7335 let dir = tempfile::tempdir().unwrap();
7336 let queue = Queue::at(dir.path().join("queue"));
7337 let questions = Questions::at(dir.path().join("questions"));
7338 let mut task = task();
7339 queue.put(&mut task).unwrap();
7340
7341 let mut task_question = ask::Question::new(
7342 task.id.clone(),
7343 crate::conduct::NODE.to_owned(),
7344 "conduct".to_owned(),
7345 "Which backend?".to_owned(),
7346 String::new(),
7347 Vec::new(),
7348 );
7349 questions.put(&mut task_question).unwrap();
7350 task.block(vec![task_question.id.clone()], None);
7351 queue.put(&mut task).unwrap();
7352
7353 let mut run_question = ask::Question::new(
7354 "20260101-000000-run1".to_owned(),
7355 "review".to_owned(),
7356 "reviewer-1".to_owned(),
7357 "Run question".to_owned(),
7358 String::new(),
7359 Vec::new(),
7360 );
7361 questions.put(&mut run_question).unwrap();
7362
7363 let mut coincidental = ask::Question::new(
7368 task.id.clone(),
7369 "review".to_owned(),
7370 "reviewer-1".to_owned(),
7371 "Unrelated review question".to_owned(),
7372 String::new(),
7373 Vec::new(),
7374 );
7375 questions.put(&mut coincidental).unwrap();
7376
7377 reconcile_task_questions(&queue, &questions);
7378 assert!(questions.get(&task_question.id).unwrap().status.open());
7379 assert!(questions.get(&run_question.id).unwrap().status.open());
7380 assert!(questions.get(&coincidental.id).unwrap().status.open());
7381
7382 task.release();
7383 queue.put(&mut task).unwrap();
7384 reconcile_task_questions(&queue, &questions);
7385 assert_eq!(
7386 questions.get(&task_question.id).unwrap().status,
7387 ask::QuestionStatus::Abandoned
7388 );
7389 assert!(
7390 questions.get(&run_question.id).unwrap().status.open(),
7391 "run questions remain the run janitor's responsibility"
7392 );
7393 assert!(
7394 questions.get(&coincidental.id).unwrap().status.open(),
7395 "a non-conductor question must not be abandoned just because its \
7396 run id coincides with a task id"
7397 );
7398 }
7399
7400 #[test]
7401 fn a_freshly_started_running_task_is_never_stalled() {
7402 let dir = tempfile::tempdir().unwrap();
7403 let mut t = task();
7404 t.start("run-1".to_owned());
7405 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
7408 }
7409
7410 #[test]
7411 fn a_long_running_task_with_no_live_daemon_is_stalled() {
7412 let dir = tempfile::tempdir().unwrap();
7413 let mut t = task();
7414 t.start("run-1".to_owned());
7415 t.updated_at = Timestamp::now()
7416 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7417 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
7418 assert_eq!(
7419 stalled_tasks(
7420 &Queue::at(dir.path().join("q")),
7421 dir.path(),
7422 Timestamp::now()
7423 )
7424 .len(),
7425 0,
7426 "the task was never written to this queue"
7427 );
7428 }
7429
7430 #[test]
7431 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
7432 let dir = tempfile::tempdir().unwrap();
7433 let mut t = task();
7434 t.id = "20260903-080340-0167".to_owned();
7435 t.start("20260903-080619-01c2".to_owned());
7436 t.updated_at = Timestamp::now()
7437 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7438
7439 let mut status = Status::new();
7440 status.current = vec![Current {
7441 task: t.id.clone(),
7442 run: "20260903-080619-01c2".to_owned(),
7443 }];
7444 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7445
7446 assert!(
7447 !is_stalled(&t, dir.path(), Timestamp::now()),
7448 "a live daemon's own heartbeat rules out stalled, however long the task has run"
7449 );
7450 }
7451
7452 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
7456 let path = queue.path_of(id);
7457 let body = std::fs::read_to_string(&path).unwrap();
7458 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
7459 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
7460 v["updated_at"] = serde_json::Value::String(old.to_string());
7461 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
7462 }
7463
7464 #[test]
7465 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
7466 let dir = tempfile::tempdir().unwrap();
7479 let queue = Queue::at(dir.path().join("queue"));
7480 let home = dir.path().join("home");
7481
7482 let mut t = task();
7483 t.id = "20260101-000001-lock".to_owned();
7484 t.start("run-1".to_owned());
7485 queue.put(&mut t).unwrap();
7486 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7487 std::fs::write(
7488 dir.path().join("queue").join(format!("{}.lock", t.id)),
7489 "not a pid",
7490 )
7491 .unwrap();
7492
7493 let now = Timestamp::now();
7494 assert!(
7495 reclaim_orphaned_running(&queue, 2).is_empty(),
7496 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
7497 and reclaim must leave the task alone"
7498 );
7499 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7500
7501 let stalled = stalled_tasks(&queue, &home, now);
7502 assert_eq!(
7503 stalled.len(),
7504 1,
7505 "reclaim's inability to claim it yet must not hide it from the conductor"
7506 );
7507 assert_eq!(stalled[0].id, t.id);
7508 }
7509
7510 #[test]
7511 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
7512 let dir = tempfile::tempdir().unwrap();
7513 crate::run::set_home(dir.path().join("run-home"));
7514 let queue = Queue::at(dir.path().join("queue"));
7515 let home = dir.path().join("home");
7516 let questions = Questions::at(dir.path().join("questions"));
7517
7518 let mut t = task();
7519 t.id = "20260101-000003-dead".to_owned();
7520 t.start("missing-run".to_owned());
7521 queue.put(&mut t).unwrap();
7522 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7523
7524 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7527 assert_eq!(
7528 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
7529 [&t.id]
7530 );
7531 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
7532 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7533
7534 crate::conduct::apply(
7537 &queue,
7538 &questions,
7539 &crate::conduct::Verdict {
7540 decisions: vec![crate::conduct::Decision {
7541 id: t.id.clone(),
7542 recovery: Some(crate::conduct::Recovery::Requeue),
7543 ..crate::conduct::Decision::default()
7544 }],
7545 },
7546 )
7547 .unwrap();
7548 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7549 }
7550
7551 #[test]
7552 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
7553 let dir = tempfile::tempdir().unwrap();
7554 let queue = Queue::at(dir.path().join("queue"));
7555 let home = dir.path().join("home");
7556
7557 let mut fresh = task();
7558 fresh.id = "20260101-000001-aaaa".to_owned();
7559 fresh.start("run-1".to_owned());
7560 queue.put(&mut fresh).unwrap();
7561
7562 let mut old = task();
7563 old.id = "20260101-000002-bbbb".to_owned();
7564 old.start("run-2".to_owned());
7565 queue.put(&mut old).unwrap();
7566 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
7567
7568 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7569 assert_eq!(stalled.len(), 1);
7570 assert_eq!(stalled[0].id, old.id);
7571 }
7572
7573 #[test]
7574 fn queued_and_finished_task_views_partition_by_status() {
7575 let dir = tempfile::tempdir().unwrap();
7576 let queue = Queue::at(dir.path().join("queue"));
7577
7578 let mut queued = task();
7579 queued.id = "20260101-000001-aaaa".to_owned();
7580 queue.put(&mut queued).unwrap();
7581
7582 let mut failed = task();
7583 failed.id = "20260101-000002-bbbb".to_owned();
7584 failed.start("run-1".to_owned());
7585 failed.fail("gate red", 5);
7586 queue.put(&mut failed).unwrap();
7587
7588 let mut held = task();
7589 held.id = "20260101-000003-cccc".to_owned();
7590 held.hold_machine(None);
7591 queue.put(&mut held).unwrap();
7592
7593 let mut running = task();
7594 running.id = "20260101-000004-dddd".to_owned();
7595 running.start("run-2".to_owned());
7596 queue.put(&mut running).unwrap();
7597
7598 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
7599 assert_eq!(queued_ids, [queued.id.clone()]);
7600
7601 let mut finished_ids: Vec<String> =
7602 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
7603 finished_ids.sort_unstable();
7604 let mut want = vec![failed.id.clone(), held.id.clone()];
7605 want.sort_unstable();
7606 assert_eq!(finished_ids, want);
7607 }
7608
7609 #[test]
7610 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
7611 let dir = tempfile::tempdir().unwrap();
7612 let queue = Queue::at(dir.path().join("queue"));
7613 let questions = ask::Questions::at(dir.path().join("questions"));
7614
7615 let mut dep = task();
7616 dep.id = "20260101-000001-dep0".to_owned();
7617 dep.succeed();
7618 queue.put(&mut dep).unwrap();
7619
7620 let mut still_going = task();
7621 still_going.id = "20260101-000002-dep1".to_owned();
7622 queue.put(&mut still_going).unwrap();
7623
7624 let mut blocked = task();
7625 blocked.id = "20260101-000003-main".to_owned();
7626 blocked.block(
7627 vec![dep.id.clone(), still_going.id.clone()],
7628 Some("waits on both".to_owned()),
7629 );
7630 queue.put(&mut blocked).unwrap();
7631
7632 resolve_blockers(&queue, &questions);
7633
7634 let after = queue.get(&blocked.id).unwrap();
7635 assert_eq!(
7636 after.status,
7637 TaskStatus::Blocked,
7638 "one dependency is still outstanding"
7639 );
7640 assert_eq!(after.blocked_by, [still_going.id.clone()]);
7641 }
7642
7643 #[test]
7644 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
7645 let dir = tempfile::tempdir().unwrap();
7646 let queue = Queue::at(dir.path().join("queue"));
7647 let questions = ask::Questions::at(dir.path().join("questions"));
7648
7649 let mut q = crate::ask::Question::new(
7650 "20260101-000001-main".to_owned(),
7651 crate::conduct::NODE.to_owned(),
7652 "conduct".to_owned(),
7653 "Which backend?".to_owned(),
7654 String::new(),
7655 Vec::new(),
7656 );
7657 questions.put(&mut q).unwrap();
7658 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
7659 .unwrap();
7660 questions.put(&mut q).unwrap();
7661
7662 let mut blocked = task();
7663 blocked.id = "20260101-000001-main".to_owned();
7664 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
7665 queue.put(&mut blocked).unwrap();
7666
7667 resolve_blockers(&queue, &questions);
7668
7669 let after = queue.get(&blocked.id).unwrap();
7670 assert_eq!(
7671 after.status,
7672 TaskStatus::Queued,
7673 "the only blocker resolved"
7674 );
7675 assert_eq!(after.answers.len(), 1);
7676 assert_eq!(after.answers[0].question, "Which backend?");
7677 assert_eq!(after.answers[0].answer, "SQLite");
7678
7679 let instruction = instruction_for(&after);
7681 assert!(instruction.contains("Which backend?"));
7682 assert!(instruction.contains("SQLite"));
7683 }
7684
7685 #[test]
7686 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
7687 let dir = tempfile::tempdir().unwrap();
7688 let queue = Queue::at(dir.path().join("queue"));
7689 let questions = ask::Questions::at(dir.path().join("questions"));
7690
7691 let mut q = crate::ask::Question::new(
7692 "20260101-000001-main".to_owned(),
7693 crate::conduct::NODE.to_owned(),
7694 "conduct".to_owned(),
7695 "Is the setup done?".to_owned(),
7696 String::new(),
7697 Vec::new(),
7698 );
7699 q.abandon("no answer within 60s of asking");
7700 questions.put(&mut q).unwrap();
7701
7702 let mut blocked = task();
7703 blocked.id = "20260101-000001-main".to_owned();
7704 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
7705 queue.put(&mut blocked).unwrap();
7706
7707 resolve_blockers(&queue, &questions);
7708
7709 let after = queue.get(&blocked.id).unwrap();
7710 assert_eq!(
7711 after.status,
7712 TaskStatus::Held,
7713 "never left blocked on nothing"
7714 );
7715 assert!(!after.operator_held(), "a machine hold, for triage");
7716 assert!(
7717 after
7718 .hold_reason
7719 .as_deref()
7720 .unwrap_or_default()
7721 .contains("went unanswered")
7722 );
7723 }
7724
7725 #[test]
7726 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
7727 let dir = tempfile::tempdir().unwrap();
7733 let queue = Queue::at(dir.path().join("queue"));
7734 let questions = ask::Questions::at(dir.path().join("questions"));
7735
7736 let mut q = crate::ask::Question::new(
7737 "20260101-000001-main".to_owned(),
7738 crate::conduct::NODE.to_owned(),
7739 "conduct".to_owned(),
7740 "How should this be handled?".to_owned(),
7741 String::new(),
7742 Vec::new(),
7743 );
7744 questions.put(&mut q).unwrap();
7745 q.answer(crate::ask::Answer::Text(
7746 "leave it held, a human will look at it later".to_owned(),
7747 ))
7748 .unwrap();
7749 questions.put(&mut q).unwrap();
7750
7751 let mut held = task();
7752 held.id = "20260101-000001-main".to_owned();
7753 held.hold_machine(Some("out of attempts".to_owned()));
7754 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
7755 queue.put(&mut held).unwrap();
7756
7757 resolve_blockers(&queue, &questions);
7758
7759 let after = queue.get(&held.id).unwrap();
7760 assert_eq!(after.status, TaskStatus::Held);
7761 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
7762 assert_eq!(
7763 after.answers[0].answer,
7764 "leave it held, a human will look at it later"
7765 );
7766 }
7767
7768 #[test]
7769 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
7770 let dir = tempfile::tempdir().unwrap();
7771 let queue = Queue::at(dir.path().join("queue"));
7772 let questions = ask::Questions::at(dir.path().join("questions"));
7773 let mut dep = task();
7774 dep.id = "20260101-000001-gone".to_owned();
7775 queue.put(&mut dep).unwrap();
7776 let mut blocked = task();
7777 blocked.id = "20260101-000003-main".to_owned();
7778 blocked.block(vec![dep.id.clone()], None);
7779 queue.put(&mut blocked).unwrap();
7780
7781 let claim = queue.claim(&blocked.id).unwrap();
7783 queue.remove(&dep.id, false, &questions).unwrap();
7784 drop(claim);
7785 resolve_blockers(&queue, &questions);
7786
7787 let after = queue.get(&blocked.id).unwrap();
7788 assert_eq!(after.status, TaskStatus::Queued);
7789 assert!(after.blocked_by.is_empty());
7790 }
7791
7792 #[test]
7793 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
7794 let dir = tempfile::tempdir().unwrap();
7800 let queue = Queue::at(dir.path().join("queue"));
7801 let questions = ask::Questions::at(dir.path().join("questions"));
7802
7803 let mut still_going = task();
7804 still_going.id = "20260101-000002-dep1".to_owned();
7805 queue.put(&mut still_going).unwrap();
7806
7807 let mut blocked = task();
7808 blocked.id = "20260101-000003-main".to_owned();
7809 blocked.block(
7810 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
7811 Some("waits on both".to_owned()),
7812 );
7813 queue.put(&mut blocked).unwrap();
7814
7815 resolve_blockers(&queue, &questions);
7816
7817 let after = queue.get(&blocked.id).unwrap();
7818 assert_eq!(
7819 after.status,
7820 TaskStatus::Held,
7821 "a missing dependency must not leave the task blocked forever"
7822 );
7823 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
7824 assert!(after.blocked_by.is_empty());
7825 let reason = after.hold_reason.as_deref().unwrap_or_default();
7826 assert!(
7827 reason.contains("20260101-000001-gone"),
7828 "the missing id must be named so an operator can tell what happened: {reason}"
7829 );
7830 assert!(
7831 reason.contains(&still_going.id),
7832 "the still-valid dependency must not silently vanish from the record: {reason}"
7833 );
7834 }
7835
7836 #[test]
7837 fn instruction_for_is_unchanged_without_any_answers() {
7838 let t = task();
7839 assert_eq!(instruction_for(&t), t.instruction);
7840 }
7841
7842 #[test]
7843 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
7844 let dir = tempfile::tempdir().unwrap();
7845 let q = Queue::at(dir.path().join("queue"));
7846 let src = dir.path().join("shot.png");
7847 std::fs::write(&src, "x").unwrap();
7848 let mut t = task();
7849 q.attach(&mut t, &[src]).unwrap();
7850 let paths = task_attachments(&q, &t).unwrap();
7851 assert_eq!(paths.len(), 1);
7852 assert!(paths[0].is_absolute() && paths[0].is_file());
7853 std::fs::remove_file(&paths[0]).unwrap();
7854 let err = task_attachments(&q, &t).unwrap_err().to_string();
7855 assert!(err.contains("shot.png"), "{err}");
7856 }
7857
7858 #[test]
7859 fn resumed_instruction_is_unchanged_without_any_answers() {
7860 let t = task();
7861 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
7862 }
7863
7864 #[test]
7865 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
7866 let mut t = task();
7867 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7868 let old = t.instruction.clone();
7872
7873 let refreshed = resumed_instruction(&old, &t);
7874 assert!(refreshed.starts_with(&old), "the original text is kept");
7875 assert!(refreshed.contains("Which backend?"));
7876 assert!(refreshed.contains("SQLite"));
7877 }
7878
7879 #[test]
7880 fn resumed_instruction_keeps_an_original_answers_heading() {
7881 let mut t = task();
7882 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
7883 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7884
7885 let refreshed = resumed_instruction(&t.instruction, &t);
7886
7887 assert!(
7888 refreshed.starts_with(&t.instruction),
7889 "an answers heading in the original instruction is not the appended block"
7890 );
7891 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
7892 assert!(refreshed.contains("Which backend?"));
7893 assert!(refreshed.contains("SQLite"));
7894
7895 let repeated = resumed_instruction(&refreshed, &t);
7896 assert_eq!(
7897 repeated, refreshed,
7898 "only the final appended block is refreshed"
7899 );
7900 }
7901
7902 #[test]
7903 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
7904 let mut t = task();
7905 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7906
7907 let once = resumed_instruction(&t.instruction, &t);
7911 let twice = resumed_instruction(&once, &t);
7912 assert_eq!(once, twice);
7913 assert_eq!(once.matches("Which backend?").count(), 1);
7914
7915 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
7917 let refreshed = resumed_instruction(&once, &t);
7918 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
7919 assert!(refreshed.contains("Which backend?"));
7920 assert!(refreshed.contains("Which cache?"));
7921 }
7922
7923 #[test]
7924 fn prepare_instruction_covers_all_three_starters() {
7925 let mut t = task();
7926 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7927
7928 assert_eq!(
7931 prepare_instruction(&Starter::Start, None, &t),
7932 Some(instruction_for(&t))
7933 );
7934
7935 let old = t.instruction.clone();
7938 assert_eq!(
7939 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
7940 Some(resumed_instruction(&old, &t))
7941 );
7942
7943 assert_eq!(
7947 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
7948 None
7949 );
7950 }
7951
7952 #[test]
7953 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
7954 assert_eq!(
7955 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
7956 Starter::Review("magi/eba2/A".to_owned())
7957 );
7958 }
7959
7960 #[test]
7961 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
7962 assert_eq!(
7963 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
7964 Starter::Start,
7965 "a vanished review branch must not fall back to resuming the old run either"
7966 );
7967 }
7968
7969 #[test]
7970 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
7971 let mut t = task();
7972 t.start("old-run".to_owned());
7973 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
7974 t.release();
7975 let branch = t.review_branch.take();
7976 assert_eq!(
7977 choose_starter(branch.as_deref(), true, Some("old-run")),
7978 Starter::Review("magi/eba2/A".to_owned()),
7979 "a review wins over resuming the old run"
7980 );
7981 }
7982
7983 #[test]
7984 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
7985 assert_eq!(
7986 choose_starter(None, false, Some("some-run")),
7987 Starter::Resume("some-run".to_owned())
7988 );
7989 assert_eq!(choose_starter(None, false, None), Starter::Start);
7990 }
7991
7992 #[test]
7993 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
7994 let mut released = task();
7995 released.start("stalled-run".to_owned());
7996 released.requeue();
7997 let unfinished = (!released.fresh_start)
7998 .then(|| Some("stalled-run".to_owned()))
7999 .flatten();
8000 assert_eq!(
8001 choose_starter(None, false, unfinished.as_deref()),
8002 Starter::Start,
8003 "release keeps run history but must not resume it"
8004 );
8005 assert_eq!(released.runs, ["stalled-run"]);
8006 }
8007
8008 #[test]
8009 fn an_ordinary_release_keeps_a_resumable_run_available() {
8010 let mut released = task();
8011 released.start("stalled-run".to_owned());
8012 released.release();
8013 let unfinished = (!released.fresh_start)
8014 .then(|| Some("stalled-run".to_owned()))
8015 .flatten();
8016 assert_eq!(
8017 choose_starter(None, false, unfinished.as_deref()),
8018 Starter::Resume("stalled-run".to_owned()),
8019 "manual release must preserve the normal resume path"
8020 );
8021 }
8022
8023 #[test]
8024 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
8025 let mut state = run_state(RunStatus::Blocked);
8026 state.config.graph.review_rounds = 3;
8027 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
8028 assert!(exhausted_review_budget(&state));
8029
8030 state.reviews.pop();
8032 assert!(!exhausted_review_budget(&state));
8033
8034 let mut stalled = run_state(RunStatus::Stalled);
8037 stalled.config.graph.review_rounds = 1;
8038 stalled.reviews = vec![review_round(1)];
8039 assert!(!exhausted_review_budget(&stalled));
8040 }
8041
8042 fn review_round(round: usize) -> crate::run::ReviewRound {
8043 crate::run::ReviewRound {
8044 round,
8045 head: "deadbeef".to_owned(),
8046 verified_head: None,
8047 verified_at: None,
8048 reviews: Vec::new(),
8049 e2e: Vec::new(),
8050 verify_retried: false,
8051 e2e_deferred: false,
8052 e2e_defer_reason: None,
8053 fix: None,
8054 blocking: 0,
8055 answered: 1,
8056 expected: 1,
8057 clean: false,
8058 progressed: true,
8059 vote_split: false,
8060 reconsideration: Vec::new(),
8061 verdict: None,
8062 }
8063 }
8064
8065 #[test]
8066 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
8067 let mut run = RunState::new(
8068 PathBuf::from("/repo"),
8069 "main".to_owned(),
8070 "abc1234def".to_owned(),
8071 "add retries".to_owned(),
8072 Config::default(),
8073 );
8074 run.status = RunStatus::Judging;
8075 run.parked = true;
8076 let mut task = Task::new(
8077 "add retries".to_owned(),
8078 "add retries".to_owned(),
8079 PathBuf::from("/repo"),
8080 crate::queue::Source::Human,
8081 );
8082 task.status = TaskStatus::Failed;
8083 task.runs = vec![run.id.clone()];
8084 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
8085 assert!(with(&task, &run), "parked after judging is the case");
8086 let mut parked_task = task.clone();
8087 parked_task.status = TaskStatus::Parked;
8088 assert!(with(&parked_task, &run), "the Parked status is the case");
8089
8090 let mut not_parked = run.clone();
8091 not_parked.parked = false;
8092 not_parked.status = RunStatus::Stalled;
8093 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
8094
8095 let mut fresh = task.clone();
8096 fresh.fresh_start = true;
8097 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
8098
8099 let mut review = task.clone();
8100 review.review_branch = Some("magi/x/A".to_owned());
8101 assert!(!with(&review, &run), "review is ranked before resume");
8102
8103 let mut held = task.clone();
8104 held.status = TaskStatus::Held;
8105 assert!(!with(&held, &run), "a hold stays visible to the conductor");
8106
8107 let mut released = run.clone();
8108 released.released_to = Some("20260901-000000-new1".to_owned());
8109 assert!(!with(&task, &released), "nothing left to resume into");
8110
8111 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
8112 "unreadable"
8113 )));
8114 }
8115
8116 #[test]
8117 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
8118 let mut released = RunState::new(
8119 PathBuf::from("/repo"),
8120 "main".to_owned(),
8121 "abc1234def".to_owned(),
8122 "add retries".to_owned(),
8123 Config::default(),
8124 );
8125 released.status = RunStatus::Blocked;
8126 assert_eq!(
8127 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8128 Some(released.id.clone())
8129 );
8130 released.released_to = Some("20260901-000000-new1".to_owned());
8131 assert_eq!(
8132 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8133 None,
8134 "there is nothing left to resume it into"
8135 );
8136 }
8137
8138 #[test]
8139 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
8140 let mut exhausted = RunState::new(
8149 PathBuf::from("/repo"),
8150 "main".to_owned(),
8151 "abc1234def".to_owned(),
8152 "add retries".to_owned(),
8153 Config::default(),
8154 );
8155 exhausted.status = RunStatus::Blocked;
8156 exhausted.config.graph.review_rounds = 1;
8157 exhausted.reviews = vec![review_round(1)];
8158
8159 assert_eq!(
8160 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
8161 None,
8162 "an exhausted `Blocked` run must not be offered as resumable"
8163 );
8164
8165 let mut has_budget_left = RunState::new(
8168 PathBuf::from("/repo"),
8169 "main".to_owned(),
8170 "abc1234def".to_owned(),
8171 "add retries".to_owned(),
8172 Config::default(),
8173 );
8174 has_budget_left.status = RunStatus::Blocked;
8175 has_budget_left.config.graph.review_rounds = 3;
8176 has_budget_left.reviews = vec![review_round(1)];
8177
8178 assert_eq!(
8179 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
8180 Ok(has_budget_left.clone())
8181 }),
8182 Some(has_budget_left.id.clone())
8183 );
8184 }
8185
8186 #[test]
8187 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
8188 let mut older_stalled = RunState::new(
8196 PathBuf::from("/repo"),
8197 "main".to_owned(),
8198 "abc1234def".to_owned(),
8199 "add retries".to_owned(),
8200 Config::default(),
8201 );
8202 older_stalled.status = RunStatus::Stalled;
8203
8204 let mut newest_exhausted = RunState::new(
8205 PathBuf::from("/repo"),
8206 "main".to_owned(),
8207 "abc1234def".to_owned(),
8208 "add retries".to_owned(),
8209 Config::default(),
8210 );
8211 newest_exhausted.status = RunStatus::Blocked;
8212 newest_exhausted.config.graph.review_rounds = 1;
8213 newest_exhausted.reviews = vec![review_round(1)];
8214
8215 assert_eq!(
8216 unfinished_run_with(
8217 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
8218 "t",
8219 |_| Ok(newest_exhausted.clone())
8220 ),
8221 None,
8222 "the newest run is exhausted, so nothing here is worth resuming - \
8223 least of all the older, already-superseded run"
8224 );
8225 }
8226
8227 #[test]
8228 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
8229 assert_eq!(
8230 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
8231 Err(anyhow::anyhow!("fixture is absent"))
8232 }),
8233 None
8234 );
8235 }
8236
8237 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
8238 let mut q = ask::Question::new(
8239 run.to_owned(),
8240 "implement".to_owned(),
8241 "impl-A".to_owned(),
8242 "continue?".to_owned(),
8243 String::new(),
8244 vec!["resume で続行する".to_owned(), "other".to_owned()],
8245 );
8246 q.actions.insert("resume で続行する".to_owned(), action);
8247 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
8248 .unwrap();
8249 q
8250 }
8251
8252 fn held_task_with(run: &str) -> Task {
8253 let mut t = task();
8254 t.runs = vec![run.to_owned()];
8255 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
8256 t
8257 }
8258
8259 fn resume_action(run: &str) -> ask::ChoiceAction {
8260 ask::ChoiceAction::Resume { run: run.into() }
8261 }
8262
8263 #[test]
8264 fn decide_action_resumes_only_the_latest_resumable_run() {
8265 let t = held_task_with("r1");
8266 let q = action_question("r1", resume_action("r1"));
8267 let load = |s: RunState| move |_: &str| Ok(s);
8268 assert_eq!(
8269 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
8270 ActionDecision::Resume("r1".into())
8271 );
8272 let q_other = action_question("r1", resume_action("r0"));
8274 assert!(matches!(
8275 decide_action(
8276 &t,
8277 &q_other,
8278 &PHRASES_EN,
8279 load(run_state(RunStatus::Blocked))
8280 ),
8281 ActionDecision::Refuse(_)
8282 ));
8283 assert!(matches!(
8285 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
8286 ActionDecision::Refuse(_)
8287 ));
8288 let mut released = run_state(RunStatus::Blocked);
8290 released.released_to = Some("elsewhere".into());
8291 assert!(matches!(
8292 decide_action(&t, &q, &PHRASES_EN, load(released)),
8293 ActionDecision::Refuse(_)
8294 ));
8295 assert!(matches!(
8297 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
8298 ActionDecision::Refuse(_)
8299 ));
8300 }
8301
8302 #[test]
8303 fn decide_action_ignores_a_question_about_an_earlier_run() {
8304 let mut t = held_task_with("r1");
8305 t.runs.push("r2".to_owned());
8306 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8307 assert_eq!(
8308 decide_action(
8309 &t,
8310 &action_question("r1", ask::ChoiceAction::Done),
8311 &PHRASES_EN,
8312 never
8313 ),
8314 ActionDecision::Stale
8315 );
8316 }
8317
8318 #[test]
8319 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
8320 let mut t = held_task_with("r1");
8321 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8322 assert_eq!(
8323 decide_action(
8324 &t,
8325 &action_question("r1", ask::ChoiceAction::Requeue),
8326 &PHRASES_EN,
8327 never
8328 ),
8329 ActionDecision::Requeue
8330 );
8331 let done_q = action_question("r1", ask::ChoiceAction::Done);
8332 assert_eq!(
8333 decide_action(&t, &done_q, &PHRASES_EN, never),
8334 ActionDecision::Done
8335 );
8336 t.mark_action_applied(&done_q.id);
8337 assert_eq!(
8338 decide_action(&t, &done_q, &PHRASES_EN, never),
8339 ActionDecision::Skip
8340 );
8341
8342 let mut plain = action_question("r1", ask::ChoiceAction::Done);
8344 plain.actions.clear();
8345 assert_eq!(
8346 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
8347 ActionDecision::Skip
8348 );
8349 let mut running = held_task_with("r1");
8351 running.status = TaskStatus::Running;
8352 assert_eq!(
8353 decide_action(
8354 &running,
8355 &action_question("r1", ask::ChoiceAction::Done),
8356 &PHRASES_EN,
8357 never
8358 ),
8359 ActionDecision::Skip
8360 );
8361 }
8362
8363 #[test]
8364 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
8365 let dir = tempfile::tempdir().unwrap();
8366 let queue = Queue::at(dir.path().join("queue"));
8367 let questions = Questions::at(dir.path().join("questions"));
8368 let home = dir.path().join("home");
8369 let mut state = run_state(RunStatus::Blocked);
8370 state.id = "20260101-000000-act1".to_owned();
8371 state.save_under(&home).unwrap();
8372
8373 let mut t = held_task_with(&state.id);
8374 queue.put(&mut t).unwrap();
8375 let mut q = action_question(&state.id, resume_action(&state.id));
8376 questions.put(&mut q).unwrap();
8377
8378 apply_choice_actions(&queue, &questions, &home);
8379 let after = queue.get(&t.id).unwrap();
8380 assert_eq!(after.status, TaskStatus::Queued);
8381 assert!(!after.fresh_start);
8382 assert!(after.action_applied(&q.id));
8383 let pin = after.resume_override.clone().unwrap();
8384 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
8385 assert!(pin.forced);
8386
8387 let mut again = queue.get(&t.id).unwrap();
8389 again.hold_machine(Some("later".into()));
8390 queue.put(&mut again).unwrap();
8391 apply_choice_actions(&queue, &questions, &home);
8392 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8393 }
8394
8395 #[test]
8396 fn a_delivered_answer_is_still_acted_on_exactly_once() {
8397 let dir = tempfile::tempdir().unwrap();
8398 let queue = Queue::at(dir.path().join("queue"));
8399 let questions = Questions::at(dir.path().join("questions"));
8400 let home = dir.path().join("home");
8401 let mut state = run_state(RunStatus::Blocked);
8402 state.id = "20260101-000000-act2".to_owned();
8403 state.save_under(&home).unwrap();
8404
8405 let mut t = held_task_with(&state.id);
8406 queue.put(&mut t).unwrap();
8407 let mut q = action_question(&state.id, resume_action(&state.id));
8408 q.answer_delivered = true;
8409 questions.put(&mut q).unwrap();
8410
8411 apply_choice_actions(&queue, &questions, &home);
8414 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8415 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
8416
8417 let mut again = queue.get(&t.id).unwrap();
8419 again.hold_machine(Some("later".into()));
8420 queue.put(&mut again).unwrap();
8421 apply_choice_actions(&queue, &questions, &home);
8422 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8423 }
8424
8425 #[test]
8426 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
8427 let dir = tempfile::tempdir().unwrap();
8428 let queue = Queue::at(dir.path().join("queue"));
8429 let questions = Questions::at(dir.path().join("questions"));
8430 let home = dir.path().join("home");
8431 let mut state = run_state(RunStatus::Blocked);
8432 state.id = "20260101-000000-act3".to_owned();
8433 state.save_under(&home).unwrap();
8434 let mut t = held_task_with(&state.id);
8435 queue.put(&mut t).unwrap();
8436 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
8437 questions.put(&mut q).unwrap();
8438
8439 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
8440 apply_choice_actions(&queue, &questions, &home);
8441 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8442
8443 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
8444 apply_choice_actions(&queue, &questions, &home);
8445 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8446 }
8447
8448 #[test]
8449 fn action_standing_tells_the_reasons_apart() {
8450 let mut t = held_task_with("r1");
8451 let q = action_question("r1", ask::ChoiceAction::Requeue);
8452 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
8453 let mut plain = q.clone();
8454 plain.actions.clear();
8455 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
8456
8457 t.mark_action_applied(&q.id);
8459 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
8460
8461 let mut t = held_task_with("r1");
8463 t.start("r2".to_owned());
8464 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
8465 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
8467 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8468 t.status = TaskStatus::Blocked;
8469 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8470
8471 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
8473 c.node = crate::conduct::NODE.to_owned();
8474 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
8475 assert!(!ActionStanding::Busy.daemon_owns());
8476 }
8477
8478 #[test]
8479 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
8480 let dir = tempfile::tempdir().unwrap();
8481 let queue = Queue::at(dir.path().join("queue"));
8482 let questions = Questions::at(dir.path().join("questions"));
8483 let home = dir.path().join("home");
8484 let mut state = run_state(RunStatus::Blocked);
8485 state.id = "20260101-000000-act4".to_owned();
8486 state.save_under(&home).unwrap();
8487 let mut t = held_task_with(&state.id);
8488 t.status = TaskStatus::Running;
8489 queue.put(&mut t).unwrap();
8490 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
8491 q.cwd = Some(dir.path().display().to_string());
8492 questions.put(&mut q).unwrap();
8493
8494 let running = queue.get(&t.id).unwrap();
8497 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
8498 assert!(matches!(
8499 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
8500 crate::waiter::Action::Deliver(_)
8501 ));
8502 apply_choice_actions(&queue, &questions, &home);
8504 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8505 let mut back = queue.get(&t.id).unwrap();
8506 back.hold_machine(Some("later".into()));
8507 queue.put(&mut back).unwrap();
8508 apply_choice_actions(&queue, &questions, &home);
8509 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
8510 let mut again = queue.get(&t.id).unwrap();
8511 again.hold_machine(Some("again".into()));
8512 queue.put(&mut again).unwrap();
8513 apply_choice_actions(&queue, &questions, &home);
8514 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8515 }
8516}