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(Notice::error(
4058 "loop:record",
4059 "The loop could not save a task's state; check the disk.",
4060 ));
4061 }
4062}
4063
4064fn runnable(queue: &Queue) -> Vec<Task> {
4070 let mut tasks: Vec<Task> = queue
4071 .list()
4072 .into_iter()
4073 .filter(|t| t.status.runnable())
4074 .collect();
4075 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4076 tasks
4077}
4078
4079fn describe(state: &RunState) -> String {
4093 let p = phrases(&state.config.graph.language);
4094 let mut detail = if state.status == RunStatus::Stalled {
4095 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4096 seats.sort_unstable();
4097 seats.dedup();
4098 if seats.is_empty() {
4099 p.quorum_lost.to_owned()
4100 } else {
4101 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4102 }
4103 } else {
4104 format!("{}{}", p.run_ended, state.status.display_label())
4105 };
4106 if let Some(last) = state.events.last() {
4107 let unanswered = state
4111 .reviews
4112 .last()
4113 .filter(|r| {
4114 state.status == RunStatus::Blocked
4115 && last.node == "review"
4116 && r.incomplete()
4117 && r.blocking == 0
4118 && r.round == state.config.graph.review_rounds
4119 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4120 })
4121 .map(|r| (r.expected - r.answered, r.round));
4122 match unanswered {
4123 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4124 detail.push_str(&format!(
4125 " ({}: {})",
4126 last.node,
4127 (p.reviewers_never_answered)(missing, rounds)
4128 ));
4129 }
4130 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4131 }
4132 }
4133 detail.push_str(&format!(" [run {}]", state.id));
4134 detail
4135}
4136
4137const DIAGNOSTIC_MAX: usize = 4_000;
4143
4144const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4149
4150fn diagnostic(state: &RunState) -> Option<String> {
4164 let mut parts: Vec<String> = Vec::new();
4165
4166 for o in state.gate.iter().filter(|o| !o.ok()) {
4168 parts.push(format!(
4169 "gate `{}` failed ({:?}):\n{}",
4170 o.command,
4171 o.code,
4172 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4173 ));
4174 }
4175
4176 if let Some(last) = state
4179 .events
4180 .iter()
4181 .rev()
4182 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4183 {
4184 parts.push(last.message.clone());
4185 }
4186
4187 if state.viable().is_empty() {
4194 for c in &state.candidates {
4195 if let Some(evidence) = &c.verified_noop {
4196 parts.push(format!(
4197 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4198 c.label
4199 ));
4200 } else if !c.summary.trim().is_empty() {
4201 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4202 } else if let Some(why) = &c.failed {
4203 parts.push(format!("candidate {}: {why}", c.label));
4204 }
4205 }
4206 }
4207
4208 if parts.is_empty() {
4209 return None;
4210 }
4211 Some(crate::run::tail(
4216 &parts.join("\n\n"),
4217 DIAGNOSTIC_MAX.saturating_sub(100),
4218 ))
4219}
4220
4221fn label(status: RunStatus) -> &'static str {
4229 status.as_str()
4230}
4231
4232pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4234 match mode {
4235 "none" => Ok(MergeMode::None),
4236 "local" => Ok(MergeMode::Local),
4237 "pr" => Ok(MergeMode::Pr),
4238 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4239 }
4240}
4241
4242fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4247 mutex
4248 .lock()
4249 .unwrap_or_else(std::sync::PoisonError::into_inner)
4250}
4251
4252#[cfg(test)]
4253mod tests {
4254 use super::*;
4255 use crate::queue::{Source, TaskStatus};
4256 use crate::run::{Candidate, CommandOutcome};
4257 use pretty_assertions::assert_eq;
4258
4259 fn task() -> Task {
4260 Task::new(
4261 "add retries".to_owned(),
4262 "add retries".to_owned(),
4263 PathBuf::from("/repo"),
4264 Source::Human,
4265 )
4266 }
4267
4268 fn interrupt_task(id: &str) -> Task {
4271 let mut t = task();
4272 t.id = id.to_owned();
4273 t.interrupt = true;
4274 t
4275 }
4276
4277 fn task_with_id(id: &str) -> Task {
4279 let mut t = task();
4280 t.id = id.to_owned();
4281 t
4282 }
4283
4284 fn urgent_task(id: &str) -> Task {
4286 let mut t = task();
4287 t.id = id.to_owned();
4288 t.urgent = true;
4289 t
4290 }
4291
4292 #[test]
4297 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4298 assert_eq!(permit_kind(true, false), PermitKind::None);
4299 assert_eq!(permit_kind(true, true), PermitKind::None);
4300 }
4301
4302 #[test]
4307 fn permit_kind_separates_urgent_from_ordinary() {
4308 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4309 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4310 }
4311
4312 #[test]
4319 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4320 let cfg = Config::default();
4321 let repo = Path::new("/any/repo/path");
4322
4323 let reason =
4324 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4325 assert!(reason.contains("1024"), "{reason}");
4326 assert!(
4327 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4328 "{reason}"
4329 );
4330
4331 assert_eq!(
4332 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4333 None,
4334 "exactly at the floor is open"
4335 );
4336 assert_eq!(
4337 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4338 None,
4339 "comfortably above the floor is open"
4340 );
4341 }
4342
4343 #[test]
4344 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4345 let mut cfg = Config::default();
4346 cfg.disk.min_free_bytes = 0;
4347 let repo = Path::new("/any/repo/path");
4348 assert_eq!(
4349 disk_gate_with(repo, &cfg, |_| Ok(0)),
4350 None,
4351 "a zero floor never measures at all"
4352 );
4353 }
4354
4355 #[test]
4356 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
4357 let cfg = Config::default();
4358 let repo = Path::new("/any/repo/path");
4359 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
4360 .expect("a measurement failure must close the gate, not open it");
4361 assert!(reason.contains("could not measure"), "{reason}");
4362 }
4363
4364 #[test]
4365 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
4366 let ordinary = task();
4367 let next = advance_interrupt(
4368 Interrupt::Idle,
4369 std::slice::from_ref(&ordinary.id),
4370 std::slice::from_ref(&ordinary),
4371 );
4372 assert_eq!(next, Interrupt::Idle);
4373 }
4374
4375 #[test]
4376 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
4377 let marked = interrupt_task("marked");
4380 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4381 assert_eq!(next, Interrupt::Idle);
4382 }
4383
4384 #[test]
4385 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
4386 let marked = interrupt_task("marked");
4387 let next = advance_interrupt(
4388 Interrupt::Idle,
4389 &["running".to_owned()],
4390 std::slice::from_ref(&marked),
4391 );
4392 assert_eq!(
4393 next,
4394 Interrupt::Parking {
4395 parked: vec!["running".to_owned()],
4396 interrupt_task: "marked".to_owned(),
4397 }
4398 );
4399 }
4400
4401 #[test]
4410 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
4411 let marked = interrupt_task("marked");
4412
4413 let two = advance_interrupt(
4414 Interrupt::Idle,
4415 &["a".to_owned(), "b".to_owned()],
4416 std::slice::from_ref(&marked),
4417 );
4418 assert_eq!(two, Interrupt::Idle);
4419
4420 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4421 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
4422 }
4423
4424 #[test]
4425 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
4426 let state = Interrupt::Parking {
4427 parked: vec!["running".to_owned()],
4428 interrupt_task: "marked".to_owned(),
4429 };
4430 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
4432 assert_eq!(still_going, state);
4433
4434 let stopped_but_not_yet_dispatched =
4438 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
4439 assert_eq!(stopped_but_not_yet_dispatched, state);
4440
4441 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
4443 assert_eq!(
4444 dispatched,
4445 Interrupt::Running {
4446 parked: vec!["running".to_owned()],
4447 interrupt_task: "marked".to_owned(),
4448 }
4449 );
4450 }
4451
4452 #[test]
4453 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
4454 let state = Interrupt::Running {
4455 parked: vec!["running".to_owned()],
4456 interrupt_task: "marked".to_owned(),
4457 };
4458 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
4459 assert_eq!(still_running, state);
4460
4461 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
4468 assert_eq!(
4469 ended,
4470 Interrupt::Resuming {
4471 parked: vec!["running".to_owned()]
4472 }
4473 );
4474 }
4475
4476 #[test]
4477 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
4478 let state = Interrupt::Resuming {
4479 parked: vec!["running".to_owned()],
4480 };
4481 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
4482 assert_eq!(still_waiting, state);
4483
4484 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
4485 assert_eq!(dispatched, Interrupt::Idle);
4486 }
4487
4488 #[test]
4494 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
4495 {
4496 let state = Interrupt::Parking {
4497 parked: vec!["running".to_owned()],
4498 interrupt_task: "marked".to_owned(),
4499 };
4500 let next = advance_interrupt(state, &[], &[]);
4503 assert_eq!(
4504 next,
4505 Interrupt::Resuming {
4506 parked: vec!["running".to_owned()]
4507 },
4508 "abandoning the interrupt must not abandon the resume it owes"
4509 );
4510 }
4511
4512 #[test]
4515 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
4516 let state = Interrupt::Resuming {
4517 parked: vec!["running".to_owned()],
4518 };
4519 let next = advance_interrupt(state, &[], &[]);
4520 assert_eq!(
4521 next,
4522 Interrupt::Idle,
4523 "nothing is left to wait for; the loop must not stay wedged"
4524 );
4525 }
4526
4527 #[test]
4528 fn disabled_by_config_the_sequence_can_never_leave_idle() {
4529 let marked = interrupt_task("marked");
4530 let next = advance_interrupt_tick(
4531 false,
4532 Interrupt::Idle,
4533 &["running".to_owned()],
4534 std::slice::from_ref(&marked),
4535 );
4536 assert_eq!(
4537 next,
4538 Interrupt::Idle,
4539 "an unmarked, unconfigured daemon must behave exactly as before"
4540 );
4541 }
4542
4543 #[test]
4544 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
4545 let state = Interrupt::Parking {
4546 parked: vec!["running".to_owned()],
4547 interrupt_task: "marked".to_owned(),
4548 };
4549 let candidates = vec![interrupt_task("marked"), task()];
4550 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4551 assert!(
4552 allowed.is_empty(),
4553 "nothing may dispatch - not even the interrupt task itself - \
4554 until the parked run has actually stopped"
4555 );
4556 }
4557
4558 #[test]
4572 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
4573 for state in [
4574 Interrupt::Parking {
4575 parked: vec!["running".to_owned()],
4576 interrupt_task: "marked".to_owned(),
4577 },
4578 Interrupt::Running {
4579 parked: vec!["running".to_owned()],
4580 interrupt_task: "marked".to_owned(),
4581 },
4582 Interrupt::Resuming {
4583 parked: vec!["running".to_owned()],
4584 },
4585 ] {
4586 let candidates = vec![
4587 interrupt_task("marked"),
4588 urgent_task("hot"),
4589 task_with_id("ordinary"),
4590 ];
4591 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4592 assert!(
4593 !allowed.iter().any(|t| t.id == "hot"),
4594 "an urgent candidate must wait out the same gate as anything \
4595 else while the run it would run alongside has not actually \
4596 left flight, for state {state:?}: {allowed:?}"
4597 );
4598 }
4599 }
4600
4601 #[test]
4607 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
4608 let state = Interrupt::Resuming {
4609 parked: vec!["hot".to_owned()],
4610 };
4611 let candidates = vec![urgent_task("hot"), task()];
4612 let allowed = interrupt_gate(&state, &[], candidates);
4613 assert_eq!(
4614 allowed.iter().filter(|t| t.id == "hot").count(),
4615 1,
4616 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
4617 );
4618 }
4619
4620 #[test]
4621 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
4622 let state = Interrupt::Parking {
4623 parked: vec!["running".to_owned()],
4624 interrupt_task: "marked".to_owned(),
4625 };
4626 let other = task();
4627 let candidates = vec![interrupt_task("marked"), other.clone()];
4628 let allowed = interrupt_gate(&state, &[], candidates);
4629 assert_eq!(allowed.len(), 1);
4630 assert_eq!(allowed[0].id, "marked");
4631 }
4632
4633 #[test]
4634 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4635 let state = Interrupt::Running {
4636 parked: vec!["running".to_owned()],
4637 interrupt_task: "marked".to_owned(),
4638 };
4639 let candidates = vec![task(), task()];
4640 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4641 assert!(allowed.is_empty());
4642 }
4643
4644 #[test]
4651 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4652 let state = Interrupt::Resuming {
4653 parked: vec!["a".to_owned(), "c".to_owned()],
4654 };
4655 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4656 let allowed = interrupt_gate(&state, &[], candidates);
4657 assert_eq!(
4658 allowed.len(),
4659 1,
4660 "at most one candidate may be offered while resuming: {allowed:?}"
4661 );
4662 assert_eq!(allowed[0].id, "a");
4663 }
4664
4665 #[test]
4666 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4667 let state = Interrupt::Resuming {
4668 parked: vec!["a".to_owned()],
4669 };
4670 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4671 assert!(allowed.is_empty());
4672 }
4673
4674 #[test]
4680 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4681 let running = task(); let marked = interrupt_task("marked");
4683
4684 let mut state = Interrupt::Idle;
4685 let in_flight = vec![running.id.clone()];
4687 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4688 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4689 assert!(gated.is_empty(), "still waiting on `running` to park");
4690
4691 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4693 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4694 assert_eq!(
4695 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4696 vec!["marked"],
4697 "only the interrupt task may be offered to the dispatcher now"
4698 );
4699
4700 state = advance_interrupt_tick(
4702 true,
4703 state,
4704 &["marked".to_owned()],
4705 std::slice::from_ref(&running),
4706 );
4707 let gated = interrupt_gate(
4708 &state,
4709 &["marked".to_owned()],
4710 vec![marked.clone(), running.clone()],
4711 );
4712 assert!(
4713 gated.is_empty(),
4714 "the parked run must not be offered back while the interrupt \
4715 task is still running"
4716 );
4717
4718 let other = task_with_id("other");
4722 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4723 assert_eq!(
4724 state,
4725 Interrupt::Resuming {
4726 parked: vec![running.id.clone()]
4727 }
4728 );
4729 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4730 assert_eq!(
4731 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4732 vec![running.id.as_str()],
4733 "exactly the parked run resumes - not the unrelated task, even \
4734 though it was offered first"
4735 );
4736
4737 state = advance_interrupt_tick(
4741 true,
4742 state,
4743 std::slice::from_ref(&running.id),
4744 std::slice::from_ref(&other),
4745 );
4746 assert_eq!(state, Interrupt::Idle);
4747 let gated = interrupt_gate(
4748 &state,
4749 std::slice::from_ref(&running.id),
4750 vec![other.clone()],
4751 );
4752 assert_eq!(
4753 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4754 vec![other.id.as_str()],
4755 "ordinary dispatch is unrestricted again"
4756 );
4757 }
4758
4759 #[test]
4760 fn every_run_status_settles_the_task_it_came_from() {
4761 let table = [
4763 (RunStatus::Merged, TaskStatus::Done, 1),
4764 (RunStatus::Ready, TaskStatus::Done, 1),
4765 (RunStatus::Stalled, TaskStatus::Failed, 0),
4766 (RunStatus::Blocked, TaskStatus::Failed, 1),
4767 (RunStatus::Failed, TaskStatus::Failed, 1),
4768 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4769 (RunStatus::Prep, TaskStatus::Failed, 1),
4770 (RunStatus::Implementing, TaskStatus::Failed, 1),
4771 (RunStatus::Judging, TaskStatus::Failed, 1),
4772 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4773 (RunStatus::Voting, TaskStatus::Failed, 1),
4774 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4775 (RunStatus::Gating, TaskStatus::Failed, 1),
4776 ];
4777 for (run, want, attempts) in table {
4778 let mut t = task();
4779 t.start("20260902-000000-aaaa".to_owned());
4780 settle(
4781 &mut t,
4782 Verdict {
4783 status: run,
4784 left_pr: false,
4785 parked: false,
4786 quota_hit: matches!(run, RunStatus::Stalled),
4787 no_viable_candidates: false,
4788 },
4789 "why",
4790 2,
4791 );
4792 assert_eq!(t.status, want, "task status after {}", label(run));
4793 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4794 }
4795 }
4796
4797 #[test]
4798 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4799 let mut stalled = task();
4800 stalled.start("20260902-000000-aaaa".to_owned());
4801 settle(
4802 &mut stalled,
4803 Verdict {
4804 status: RunStatus::Stalled,
4805 left_pr: false,
4806 parked: false,
4807 quota_hit: true,
4808 no_viable_candidates: false,
4809 },
4810 "quota",
4811 1,
4812 );
4813 assert_eq!(stalled.attempts, 0);
4814 assert!(
4815 stalled.status.runnable(),
4816 "a machine problem must leave the task in line"
4817 );
4818
4819 let mut blocked = task();
4820 blocked.start("20260902-000000-aaaa".to_owned());
4821 settle(
4822 &mut blocked,
4823 Verdict {
4824 status: RunStatus::Blocked,
4825 left_pr: false,
4826 parked: false,
4827 quota_hit: false,
4828 no_viable_candidates: false,
4829 },
4830 "findings open",
4831 1,
4832 );
4833 assert_eq!(blocked.attempts, 1);
4834 assert_eq!(
4835 blocked.status,
4836 TaskStatus::Held,
4837 "the last attempt hands the task to a human"
4838 );
4839 }
4840
4841 #[test]
4842 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4843 let mut delivered = task();
4846 delivered.start("20260903-080619-01c2".to_owned());
4847 settle(
4848 &mut delivered,
4849 Verdict {
4850 status: RunStatus::Blocked,
4851 left_pr: true,
4852 parked: false,
4853 quota_hit: false,
4854 no_viable_candidates: false,
4855 },
4856 "no check status",
4857 4,
4858 );
4859 assert_eq!(
4860 delivered.status,
4861 TaskStatus::Held,
4862 "a pull request waiting on CI or a person is not a retryable failure"
4863 );
4864 assert!(
4865 !delivered.status.runnable(),
4866 "the loop must not pick this task up again"
4867 );
4868 assert_eq!(
4869 delivered.last_error.as_deref(),
4870 Some("no check status"),
4871 "the operator needs to be told what the gate was waiting for"
4872 );
4873
4874 let mut empty_handed = task();
4877 empty_handed.start("20260903-080619-01c2".to_owned());
4878 settle(
4879 &mut empty_handed,
4880 Verdict {
4881 status: RunStatus::Blocked,
4882 left_pr: false,
4883 parked: false,
4884 quota_hit: false,
4885 no_viable_candidates: false,
4886 },
4887 "findings open",
4888 4,
4889 );
4890 assert_eq!(empty_handed.status, TaskStatus::Failed);
4891 assert!(empty_handed.status.runnable());
4892 }
4893
4894 #[test]
4895 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4896 let mut noop = task();
4902 noop.start("20260912-131304-391f".to_owned());
4903 settle(
4904 &mut noop,
4905 Verdict {
4906 status: RunStatus::VerifiedNoop,
4907 left_pr: false,
4908 parked: false,
4909 quota_hit: false,
4910 no_viable_candidates: true,
4911 },
4912 "candidate A: already fixed by b32cfc4, on main",
4913 4,
4914 );
4915 assert_eq!(
4916 noop.status,
4917 TaskStatus::Held,
4918 "an unverified claim is a request for a human, not a failure"
4919 );
4920 assert!(
4921 !noop.status.runnable(),
4922 "the loop must not requeue this on the same unverified claim"
4923 );
4924 assert_eq!(noop.attempts, 1);
4929 }
4930
4931 #[test]
4932 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4933 let mut parked = task();
4938 parked.start("20260903-183634-2d98".to_owned());
4939 settle(
4940 &mut parked,
4941 Verdict {
4942 status: RunStatus::Implementing,
4943 left_pr: false,
4944 quota_hit: false,
4945 parked: true,
4946 no_viable_candidates: false,
4947 },
4948 "parked after `implementing`",
4949 2,
4950 );
4951 assert_eq!(parked.attempts, 0, "a park is refunded");
4952 assert!(
4953 parked.status.runnable(),
4954 "and the task stays in line so the next loop resumes its run"
4955 );
4956 assert_eq!(parked.status, TaskStatus::Parked);
4957 assert_eq!(
4958 parked.park_reason.as_deref(),
4959 Some("parked after `implementing`"),
4960 "the card says where it stopped"
4961 );
4962 assert_eq!(parked.last_error, None, "nothing failed");
4963
4964 let mut broken = task();
4968 broken.start("20260903-183634-2d98".to_owned());
4969 settle(
4970 &mut broken,
4971 Verdict {
4972 status: RunStatus::Implementing,
4973 left_pr: false,
4974 quota_hit: false,
4975 parked: false,
4976 no_viable_candidates: false,
4977 },
4978 "returned mid-flight",
4979 2,
4980 );
4981 assert_eq!(broken.attempts, 1);
4982 }
4983
4984 #[test]
4985 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4986 let mut flaky = task();
4991 flaky.start("20260903-123023-e633".to_owned());
4992 settle(
4993 &mut flaky,
4994 Verdict {
4995 status: RunStatus::Stalled,
4996 left_pr: false,
4997 parked: false,
4998 quota_hit: false,
4999 no_viable_candidates: false,
5000 },
5001 "verdict rests on 1 of 3 judges",
5002 2,
5003 );
5004 assert_eq!(
5005 flaky.attempts, 1,
5006 "flakiness spends an attempt, so `max_attempts` still bounds it"
5007 );
5008 assert!(flaky.status.runnable(), "and it is still worth retrying");
5009
5010 let mut limited = task();
5012 limited.start("20260903-123023-e633".to_owned());
5013 settle(
5014 &mut limited,
5015 Verdict {
5016 status: RunStatus::Stalled,
5017 left_pr: false,
5018 parked: false,
5019 quota_hit: true,
5020 no_viable_candidates: false,
5021 },
5022 "judge-2, judge-3 out of quota",
5023 2,
5024 );
5025 assert_eq!(limited.attempts, 0, "a quota window is refunded");
5026 assert!(limited.status.runnable());
5027
5028 let mut worn = task();
5031 for _ in 0..2 {
5032 worn.release();
5033 }
5034 worn.start("20260903-123023-e633".to_owned());
5035 worn.attempts = 2;
5036 settle(
5037 &mut worn,
5038 Verdict {
5039 status: RunStatus::Stalled,
5040 left_pr: false,
5041 parked: false,
5042 quota_hit: false,
5043 no_viable_candidates: false,
5044 },
5045 "no quorum again",
5046 2,
5047 );
5048 assert_eq!(worn.status, TaskStatus::Held);
5049 assert!(!worn.status.runnable());
5050 }
5051
5052 #[test]
5053 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5054 let mut wiped_out = task();
5061 wiped_out.start("20260907-025000-a1b2".to_owned());
5062 settle(
5063 &mut wiped_out,
5064 Verdict {
5065 status: RunStatus::Failed,
5066 left_pr: false,
5067 parked: false,
5068 quota_hit: true,
5069 no_viable_candidates: true,
5070 },
5071 "no candidate produced a change; nothing to judge",
5072 2,
5073 );
5074 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5075 assert!(
5076 wiped_out.status.runnable(),
5077 "a machine problem must leave the task in line"
5078 );
5079
5080 let mut partial_progress = task();
5086 partial_progress.start("20260907-025500-c3d4".to_owned());
5087 settle(
5088 &mut partial_progress,
5089 Verdict {
5090 status: RunStatus::Failed,
5091 left_pr: false,
5092 parked: false,
5093 quota_hit: true,
5094 no_viable_candidates: false,
5095 },
5096 "gate failed on the winning candidate",
5097 2,
5098 );
5099 assert_eq!(
5100 partial_progress.attempts, 1,
5101 "a candidate that actually produced a change spends the attempt \
5102 even though some other seat hit its quota"
5103 );
5104 assert!(partial_progress.status.runnable());
5105 }
5106
5107 #[test]
5108 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5109 let mut t = task();
5115 t.start("20260907-025000-a1b2".to_owned());
5116 let mut state = run_state(RunStatus::Failed);
5117 state.quota.push(QuotaLoss {
5118 seat: "cand-a".to_owned(),
5119 node: "implement".to_owned(),
5120 at: Timestamp::now(),
5121 reset: None,
5122 });
5123 assert!(
5124 state.viable().is_empty(),
5125 "no candidate was added, so nothing is viable"
5126 );
5127 reclaim(&mut t, Some(state), 2, "en");
5128 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5129 assert!(t.status.runnable());
5130 }
5131
5132 #[test]
5133 fn a_held_task_is_never_offered_to_the_loop() {
5134 let dir = tempfile::tempdir().unwrap();
5135 let queue = Queue::at(dir.path().to_path_buf());
5136 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5137 let mut t = task();
5138 t.id = format!("2026090{n}-000000-000{n}");
5139 t.priority = priority;
5140 queue.put(&mut t).unwrap();
5141 }
5142 let mut held = task();
5143 held.id = "20260909-000000-9999".to_owned();
5144 held.priority = 99;
5145 held.hold_machine(None);
5146 queue.put(&mut held).unwrap();
5147
5148 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5149 assert_eq!(order.len(), 3);
5150 assert!(!order.contains(&held.id));
5151 assert_eq!(
5152 order.first().cloned(),
5153 queue.next_runnable().map(|t| t.id),
5154 "the loop's first candidate is exactly what the queue offers"
5155 );
5156 assert_eq!(
5157 order,
5158 vec![
5159 "20260902-000000-0002".to_owned(),
5160 "20260903-000000-0003".to_owned(),
5161 "20260901-000000-0001".to_owned(),
5162 ],
5163 "priority first, then oldest, so nothing starves"
5164 );
5165 }
5166
5167 #[test]
5168 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5169 let dir = tempfile::tempdir().unwrap();
5170 let queue = Queue::at(dir.path().to_path_buf());
5171 let mut old = task();
5172 old.id = "20260101-000000-old0".to_owned();
5173 queue.put(&mut old).unwrap();
5174 let mut fresh = task();
5175 fresh.id = "20260101-000000-new0".to_owned();
5176 queue.put(&mut fresh).unwrap();
5177
5178 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5182 std::thread::sleep(Duration::from_millis(60));
5183 let live = queue.claim(&fresh.id).unwrap();
5184
5185 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5186 assert_eq!(swept, vec![old.id.clone()]);
5187 assert!(
5188 queue.claim(&old.id).is_ok(),
5189 "an unparseable lock older than the threshold is swept"
5190 );
5191 assert!(
5192 queue.claim(&fresh.id).is_err(),
5193 "a live pid protects its lock regardless of age"
5194 );
5195 drop(live);
5196 }
5197
5198 #[test]
5199 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5200 let dir = tempfile::tempdir().unwrap();
5210 let queue = Queue::at(dir.path().to_path_buf());
5211 let mut t = task();
5212 t.id = "20260101-000000-live".to_owned();
5213 queue.put(&mut t).unwrap();
5214
5215 let claim = queue.claim(&t.id).unwrap();
5216 std::thread::sleep(Duration::from_millis(60));
5217
5218 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5219 assert!(
5220 swept.is_empty(),
5221 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5222 );
5223 assert!(
5224 queue.claim(&t.id).is_err(),
5225 "the lock still protects its task"
5226 );
5227 drop(claim);
5228 }
5229
5230 fn injected_dead_pid() -> u32 {
5233 std::process::id().checked_add(1).unwrap_or(1)
5234 }
5235
5236 #[test]
5237 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5238 let dir = tempfile::tempdir().unwrap();
5239 let queue = Queue::at(dir.path().to_path_buf());
5240 let mut t = task();
5241 t.id = "20260101-000000-dead".to_owned();
5242 queue.put(&mut t).unwrap();
5243 let dead_pid = injected_dead_pid();
5244
5245 std::fs::write(
5250 dir.path().join(format!("{}.lock", t.id)),
5251 dead_pid.to_string(),
5252 )
5253 .unwrap();
5254
5255 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5256 pid != dead_pid
5257 });
5258 assert_eq!(
5259 swept,
5260 vec![t.id.clone()],
5261 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5262 );
5263 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5264 }
5265
5266 #[test]
5267 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5268 let dir = tempfile::tempdir().unwrap();
5269 let queue = Queue::at(dir.path().to_path_buf());
5270 let mut t = task();
5271 t.id = "20260101-000000-late".to_owned();
5272 queue.put(&mut t).unwrap();
5273 let dead_pid = injected_dead_pid();
5274
5275 assert!(
5278 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5279 "nothing has claimed the task yet"
5280 );
5281
5282 std::fs::write(
5285 dir.path().join(format!("{}.lock", t.id)),
5286 dead_pid.to_string(),
5287 )
5288 .unwrap();
5289
5290 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5294 pid != dead_pid
5295 });
5296 assert_eq!(swept, vec![t.id.clone()]);
5297 }
5298
5299 #[test]
5300 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5301 crate::run::pin_test_home();
5306 let dir = tempfile::tempdir().unwrap();
5307 let queue = Queue::at(dir.path().to_path_buf());
5308 let mut t = task();
5309 t.id = "20260101-000000-crsh".to_owned();
5310 t.status = TaskStatus::Running;
5311 t.attempts = 1;
5312 t.runs.push("20260904-000000-4043".to_owned());
5316 queue.put(&mut t).unwrap();
5317 let dead_pid = injected_dead_pid();
5318
5319 std::fs::write(
5322 dir.path().join(format!("{}.lock", t.id)),
5323 dead_pid.to_string(),
5324 )
5325 .unwrap();
5326
5327 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5333 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5334
5335 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5336 pid != dead_pid
5337 });
5338 assert_eq!(swept, vec![t.id.clone()]);
5339
5340 let reclaimed = reclaim_orphaned_running(&queue, 2);
5341 assert_eq!(reclaimed, vec![t.id.clone()]);
5342 let after = queue.get(&t.id).unwrap();
5343 assert_eq!(
5344 after.status,
5345 TaskStatus::Held,
5346 "no run.json to recover from, so a human is asked"
5347 );
5348 assert_eq!(
5349 after.runs,
5350 vec!["20260904-000000-4043".to_owned()],
5351 "the crashed run's id is kept as evidence, not discarded"
5352 );
5353 }
5354
5355 #[test]
5356 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
5357 let dir = tempfile::tempdir().unwrap();
5358 let queue = Queue::at(dir.path().to_path_buf());
5359 let mut t = task();
5360 t.id = "20260101-000000-unknown".to_owned();
5361 queue.put(&mut t).unwrap();
5362 let dead_pid = injected_dead_pid();
5363 std::fs::write(
5364 dir.path().join(format!("{}.lock", t.id)),
5365 dead_pid.to_string(),
5366 )
5367 .unwrap();
5368
5369 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
5370 assert!(swept.is_empty(), "an unknown pid must keep its lock");
5371 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
5372 }
5373
5374 fn run_state_in(status: RunStatus, language: &str) -> RunState {
5375 let mut s = run_state(status);
5376 s.config.graph.language = language.to_owned();
5377 s
5378 }
5379
5380 fn unstarted_verdict(status: RunStatus) -> Verdict {
5381 Verdict {
5382 status,
5383 left_pr: false,
5384 quota_hit: false,
5385 parked: false,
5386 no_viable_candidates: false,
5387 }
5388 }
5389
5390 #[test]
5391 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
5392 let mut t = task();
5393 t.attempts = 1;
5394 settle_in(
5395 &mut t,
5396 unstarted_verdict(RunStatus::AlreadyInBase),
5397 "already in main",
5398 1,
5399 phrases("en"),
5400 );
5401 assert_eq!(t.status, TaskStatus::Done);
5402 assert_eq!(t.attempts, 0);
5403 }
5404
5405 #[test]
5406 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
5407 let reason = |language: &str| {
5408 let mut t = task();
5409 settle_in(
5410 &mut t,
5411 unstarted_verdict(RunStatus::Judging),
5412 "boom",
5413 1,
5414 phrases(language),
5415 );
5416 t.last_error.or(t.hold_reason).unwrap_or_default()
5417 };
5418 assert!(
5419 reason("en").starts_with("the graph stopped at `"),
5420 "{}",
5421 reason("en")
5422 );
5423 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
5424 assert!(reason("日本語").contains("boom"));
5425 assert_eq!(reason("fr"), reason("en"));
5426 }
5427
5428 #[test]
5429 fn describe_follows_the_run_language_and_keeps_the_run_id() {
5430 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
5431 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
5432 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
5433 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
5434 assert!(ja.contains("[run "), "{ja}");
5435 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
5436 assert!(ended.starts_with("run 終了: "), "{ended}");
5437 let mut de = run_state_in(RunStatus::Failed, "de");
5438 let mut en = run_state_in(RunStatus::Failed, "en");
5439 de.id = "same".to_owned();
5440 en.id = "same".to_owned();
5441 assert_eq!(describe(&de), describe(&en));
5442 }
5443
5444 #[test]
5445 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
5446 use crate::handover::Refused;
5447 let cases = [
5448 Refused::Foreign {
5449 branch: "b".into(),
5450 path: "/w/x".into(),
5451 why: "made by hand".into(),
5452 },
5453 Refused::Unsafe {
5454 branch: "b".into(),
5455 path: "/w/x".into(),
5456 why: "its worktree has uncommitted changes (a.rs)".into(),
5457 },
5458 Refused::ReleaseFailed {
5459 branch: "b".into(),
5460 path: "/w/x".into(),
5461 run: "ab12".into(),
5462 },
5463 ];
5464 for r in &cases {
5465 let en = (phrases("en").handover_refused)(r);
5466 assert_eq!(en, r.to_string());
5467 let ja = (phrases("ja").handover_refused)(r);
5468 assert!(
5469 !ja.contains("is checked out") && !ja.contains("try again"),
5470 "{ja}"
5471 );
5472 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
5473 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
5474 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
5475 }
5476 }
5477 assert!(phrases("en").handover_hint.contains("release the task"));
5478 assert!(phrases("ja").handover_hint.contains("解放"));
5479 }
5480
5481 #[test]
5482 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
5483 let build = |lang: &str| {
5484 let mut s = run_state_in(RunStatus::Blocked, lang);
5485 s.id = "same".to_owned();
5486 s.config.graph.review_rounds = 3;
5487 let mut r = review_round(3);
5488 r.expected = 3;
5489 r.answered = 1;
5490 s.reviews.push(r);
5491 s.event(
5492 "review",
5493 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
5494 );
5495 s
5496 };
5497 let en = describe(&build("en"));
5498 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
5499 let ja = describe(&build("ja"));
5500 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
5501 assert!(!ja.contains("never answered"), "{ja}");
5502 assert!(ja.contains("[run "), "{ja}");
5503
5504 let mut failed = build("ja");
5507 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
5508 command: "cargo test".to_owned(),
5509 code: Some(1),
5510 output_tail: String::new(),
5511 duration_ms: 0,
5512 resource_blocked: false,
5513 });
5514 failed.event("review", "stopped; e2e failed: cargo test");
5515 let ja = describe(&failed);
5516 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
5517 assert!(!ja.contains("席のレビュアー"), "{ja}");
5518 }
5519
5520 #[test]
5521 fn refusals_and_recovery_prose_follow_the_language() {
5522 let t = held_task_with("r1");
5523 let q = action_question(
5524 "r1",
5525 ask::ChoiceAction::Resume {
5526 run: "r1".to_owned(),
5527 },
5528 );
5529 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
5530 ActionDecision::Refuse(s) => s,
5531 other => panic!("{other:?}"),
5532 };
5533 assert!(refuse(phrases("en")).contains("could not be read: gone"));
5534 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
5535 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
5536
5537 let mut held = task();
5538 reclaim(&mut held, None, 2, "ja");
5539 assert!(held.hold_reason.unwrap().contains("保留にしました"));
5540 let mut held = task();
5541 reclaim(&mut held, None, 2, "xx");
5542 assert!(held.hold_reason.unwrap().contains("held for a human"));
5543 }
5544
5545 fn run_state(status: RunStatus) -> RunState {
5546 let mut state = RunState::new(
5547 PathBuf::from("/repo"),
5548 "main".to_owned(),
5549 "abc1234def".to_owned(),
5550 "add retries".to_owned(),
5551 Config::default(),
5552 );
5553 state.status = status;
5554 state
5555 }
5556
5557 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
5558 Candidate {
5559 index: 0,
5560 label,
5561 agent: "claude".to_owned(),
5562 branch: format!("magi/x/{label}"),
5563 worktree: PathBuf::from("/repo"),
5564 summary: summary.to_owned(),
5565 stat: String::new(),
5566 files: 0,
5567 commits: usize::from(!empty),
5568 empty,
5569 failed: failed.map(str::to_owned),
5570 verified_noop: None,
5571 duration_ms: 0,
5572 folded: false,
5573 }
5574 }
5575
5576 #[test]
5577 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
5578 let mut state = run_state(RunStatus::Blocked);
5579 state.gate = vec![
5580 CommandOutcome {
5581 command: "cargo make check".to_owned(),
5582 code: Some(0),
5583 output_tail: "ok".to_owned(),
5584 duration_ms: 0,
5585 resource_blocked: false,
5586 },
5587 CommandOutcome {
5588 command: "cargo test".to_owned(),
5589 code: Some(101),
5590 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
5591 duration_ms: 0,
5592 resource_blocked: false,
5593 },
5594 ];
5595 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
5596 assert!(d.contains("cargo test"), "{d}");
5597 assert!(
5598 !d.contains("cargo make check"),
5599 "a passing check is not a diagnostic: {d}"
5600 );
5601 assert!(d.contains("assertion failed"), "{d}");
5602 }
5603
5604 #[test]
5605 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
5606 let mut state = run_state(RunStatus::Blocked);
5607 state.event(
5608 "land",
5609 "stopped: the fixer produced no commit while 2 check(s) were failing \
5610 (build, lint); stopping instead of looping on an unchanged tree",
5611 );
5612 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
5613 assert!(d.contains("build"), "{d}");
5614 assert!(d.contains("lint"), "{d}");
5615 assert!(d.contains("fixer produced no commit"), "{d}");
5616 }
5617
5618 #[test]
5619 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
5620 let state = run_state(RunStatus::VerifiedNoop);
5625 let d = describe(&state);
5626 assert!(
5627 d.contains("agent-verified no-op"),
5628 "expected the display label, not the wire spelling: {d}"
5629 );
5630 assert!(!d.contains("verified_noop"), "{d}");
5631 }
5632
5633 #[test]
5634 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
5635 let mut state = run_state(RunStatus::Failed);
5641 state.candidates = vec![candidate(
5642 'A',
5643 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
5644 true,
5645 None,
5646 )];
5647 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
5648 assert!(d.contains("candidate A"), "{d}");
5649 assert!(d.contains("tagged v1.2.3"), "{d}");
5650 }
5651
5652 #[test]
5653 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
5654 let mut state = run_state(RunStatus::Failed);
5655 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
5656 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
5657 assert!(d.contains("candidate A"), "{d}");
5658 assert!(d.contains("agent timed out"), "{d}");
5659 }
5660
5661 #[test]
5662 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
5663 let mut state = run_state(RunStatus::Failed);
5666 state.candidates = vec![candidate('A', "did the work", false, None)];
5667 assert!(diagnostic(&state).is_none());
5668 }
5669
5670 #[test]
5671 fn diagnostic_is_bounded_however_much_a_run_printed() {
5672 let mut state = run_state(RunStatus::Blocked);
5673 state.gate = vec![
5674 CommandOutcome {
5675 command: "cargo test".to_owned(),
5676 code: Some(101),
5677 output_tail: "x".repeat(50_000),
5678 duration_ms: 0,
5679 resource_blocked: false,
5680 },
5681 CommandOutcome {
5682 command: "cargo clippy".to_owned(),
5683 code: Some(1),
5684 output_tail: "y".repeat(50_000),
5685 duration_ms: 0,
5686 resource_blocked: false,
5687 },
5688 ];
5689 state.candidates = vec![
5690 candidate('A', &"z".repeat(50_000), true, None),
5691 candidate('B', &"w".repeat(50_000), true, None),
5692 ];
5693 let d = diagnostic(&state).expect("plenty here to diagnose");
5694 assert!(
5695 d.len() <= DIAGNOSTIC_MAX,
5696 "diagnostic grew to {} bytes, unbounded",
5697 d.len()
5698 );
5699 }
5700
5701 #[test]
5702 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
5703 let mut state = run_state(RunStatus::Blocked);
5704 state.gate = vec![CommandOutcome {
5705 command: "cargo test".to_owned(),
5706 code: Some(101),
5707 output_tail: "assertion failed".to_owned(),
5708 duration_ms: 0,
5709 resource_blocked: false,
5710 }];
5711 let verdict = Verdict {
5712 status: RunStatus::Blocked,
5713 left_pr: false,
5714 quota_hit: false,
5715 parked: false,
5716 no_viable_candidates: false,
5717 };
5718
5719 let mut t = task();
5722 t.start("run-1".to_owned());
5723 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5724 assert_eq!(t.status, TaskStatus::Failed);
5725 assert!(t.diagnostic.is_none());
5726
5727 t.start("run-2".to_owned());
5730 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5731 assert_eq!(t.status, TaskStatus::Held);
5732 let d = t.diagnostic.expect("a held task must carry its diagnostic");
5733 assert!(d.contains("cargo test"), "{d}");
5734 }
5735
5736 #[test]
5737 fn a_held_task_names_the_open_question_it_is_waiting_on() {
5738 crate::run::pin_test_home();
5743 let home = crate::run::home();
5744 let state = run_state(RunStatus::VerifiedNoop);
5745 let mut q = ask::Question::new(
5746 state.id.clone(),
5747 "implement".to_owned(),
5748 "impl-A".to_owned(),
5749 "is this really a no-op?".to_owned(),
5750 String::new(),
5751 Vec::new(),
5752 );
5753 Questions::at(home.join("questions")).put(&mut q).unwrap();
5754
5755 let verdict = Verdict {
5756 status: RunStatus::VerifiedNoop,
5757 left_pr: false,
5758 quota_hit: false,
5759 parked: false,
5760 no_viable_candidates: false,
5761 };
5762 let mut t = task();
5763 t.start(state.id.clone());
5764 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5765
5766 assert_eq!(t.status, TaskStatus::Held);
5767 let reason = t.hold_reason.expect("a held task must record why");
5768 assert!(
5769 reason.starts_with("run ended agent-verified no-op"),
5770 "the original settle reason must survive unchanged: {reason}"
5771 );
5772 assert!(
5773 reason.contains(q.short()),
5774 "the open question's id must be named so the notice is actionable: {reason}"
5775 );
5776 }
5777
5778 #[test]
5779 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
5780 crate::run::pin_test_home();
5781 let state = run_state(RunStatus::VerifiedNoop);
5782
5783 let verdict = Verdict {
5784 status: RunStatus::VerifiedNoop,
5785 left_pr: false,
5786 quota_hit: false,
5787 parked: false,
5788 no_viable_candidates: false,
5789 };
5790 let mut t = task();
5791 t.start(state.id.clone());
5792 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5793
5794 assert_eq!(t.status, TaskStatus::Held);
5795 assert_eq!(
5796 t.hold_reason.as_deref(),
5797 Some("run ended agent-verified no-op"),
5798 "nothing to append when the question was already answered or never asked"
5799 );
5800 }
5801
5802 #[test]
5803 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5804 crate::run::pin_test_home();
5805 let mut first = run_state(RunStatus::Blocked);
5806 first.id = "20260101-000000-sup1".to_owned();
5807 first.save().unwrap();
5808 let mut second = run_state(RunStatus::Merged);
5809 second.id = "20260101-000000-sup2".to_owned();
5810 second.save().unwrap();
5811
5812 let mut t = task();
5813 t.runs = vec![first.id.clone(), second.id.clone()];
5814 t.status = TaskStatus::Done;
5815
5816 supersede_prior_runs(&t, &crate::run::home());
5817
5818 assert_eq!(
5819 RunState::load(&first.id).unwrap().status,
5820 RunStatus::Superseded,
5821 "the first attempt's Blocked no longer needs anyone's attention"
5822 );
5823 assert_eq!(
5824 RunState::load(&second.id).unwrap().status,
5825 RunStatus::Merged,
5826 "the run that actually succeeded is left exactly as it was"
5827 );
5828 }
5829
5830 #[test]
5831 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5832 crate::run::pin_test_home();
5838 let mut first = run_state(RunStatus::Blocked);
5839 first.id = "20260101-000000-sup9".to_owned();
5840 first.driver_pid = Some(std::process::id());
5843 first.driver_started_at = Some(
5844 crate::proc::process_started_at(std::process::id())
5845 .expect("this test process's own start time must be queryable"),
5846 );
5847 first.save().unwrap();
5848 let mut second = run_state(RunStatus::Merged);
5849 second.id = "20260101-000000-supa".to_owned();
5850 second.save().unwrap();
5851
5852 let mut t = task();
5853 t.runs = vec![first.id.clone(), second.id.clone()];
5854 t.status = TaskStatus::Done;
5855
5856 supersede_prior_runs(&t, &crate::run::home());
5857
5858 assert_eq!(
5859 RunState::load(&first.id).unwrap().status,
5860 RunStatus::Blocked,
5861 "a live driver_pid means something is still actually working this run, \
5862 even though no daemon claims it - rewriting under it would just be \
5863 undone the next time that process saves"
5864 );
5865 }
5866
5867 #[test]
5868 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5869 let dir = tempfile::tempdir().unwrap();
5875 let home = dir.path().to_path_buf();
5876 let queue = Queue::at(dir.path().join("queue"));
5877
5878 let mut first = run_state(RunStatus::Blocked);
5879 first.id = "20260101-000000-supd".to_owned();
5880 first.driver_pid = Some(std::process::id());
5881 first.driver_started_at = Some(
5882 crate::proc::process_started_at(std::process::id())
5883 .expect("this test process's own start time must be queryable"),
5884 );
5885 first.save_under(&home).unwrap();
5886 let mut second = run_state(RunStatus::Merged);
5887 second.id = "20260101-000000-supe".to_owned();
5888 second.save_under(&home).unwrap();
5889
5890 let mut t = task();
5891 t.runs = vec![first.id.clone(), second.id.clone()];
5892 t.status = TaskStatus::Done;
5893 queue.put(&mut t).unwrap();
5894
5895 resweep_superseded_attempts(&queue, &home);
5896 assert_eq!(
5897 RunState::load_under(&first.id, &home).unwrap().status,
5898 RunStatus::Blocked,
5899 "still live on the first pass, so still untouched"
5900 );
5901
5902 let mut stale = RunState::load_under(&first.id, &home).unwrap();
5908 stale.driver_started_at = Some("1".to_owned());
5909 stale.save_under(&home).unwrap();
5910
5911 resweep_superseded_attempts(&queue, &home);
5912 assert_eq!(
5913 RunState::load_under(&first.id, &home).unwrap().status,
5914 RunStatus::Superseded,
5915 "the second pass catches up what the first one correctly skipped"
5916 );
5917 }
5918
5919 #[test]
5920 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5921 crate::run::pin_test_home();
5922 let mut first = run_state(RunStatus::Blocked);
5923 first.id = "20260101-000000-sup3".to_owned();
5924 first.save().unwrap();
5925 let mut second = run_state(RunStatus::Blocked);
5926 second.id = "20260101-000000-sup4".to_owned();
5927 second.save().unwrap();
5928
5929 let mut t = task();
5930 t.runs = vec![first.id.clone(), second.id.clone()];
5931 t.status = TaskStatus::Failed;
5935
5936 supersede_prior_runs(&t, &crate::run::home());
5937
5938 assert_eq!(
5939 RunState::load(&first.id).unwrap().status,
5940 RunStatus::Blocked
5941 );
5942 assert_eq!(
5943 RunState::load(&second.id).unwrap().status,
5944 RunStatus::Blocked
5945 );
5946 }
5947
5948 #[test]
5949 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5950 crate::run::pin_test_home();
5954 let mut first = run_state(RunStatus::Blocked);
5955 first.id = "20260101-000000-sup5".to_owned();
5956 first.save().unwrap();
5957
5958 let mut t = task();
5959 t.runs = vec![first.id.clone()];
5960 t.status = TaskStatus::Done;
5961
5962 supersede_prior_runs(&t, &crate::run::home());
5963
5964 assert_eq!(
5965 RunState::load(&first.id).unwrap().status,
5966 RunStatus::Blocked,
5967 "a single-attempt task has no earlier run to supersede"
5968 );
5969 }
5970
5971 #[test]
5972 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
5973 crate::run::pin_test_home();
5980 let mut first = run_state(RunStatus::Blocked);
5981 first.id = "20260101-000000-supb".to_owned();
5982 first.save().unwrap();
5983 let mut second = run_state(RunStatus::Failed);
5984 second.id = "20260101-000000-supc".to_owned();
5985 second.save().unwrap();
5986
5987 let mut t = task();
5988 t.runs = vec![first.id.clone(), second.id.clone()];
5989 t.status = TaskStatus::Done;
5990
5991 supersede_prior_runs(&t, &crate::run::home());
5992
5993 assert_eq!(
5994 RunState::load(&first.id).unwrap().status,
5995 RunStatus::Blocked,
5996 "the task's last attempt never landed, so there is nothing here \
5997 actually superseding it"
5998 );
5999 }
6000
6001 #[test]
6002 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6003 crate::run::pin_test_home();
6007 let mut failed = run_state(RunStatus::Failed);
6008 failed.id = "20260101-000000-sup6".to_owned();
6009 failed.save().unwrap();
6010 let mut noop = run_state(RunStatus::VerifiedNoop);
6011 noop.id = "20260101-000000-sup7".to_owned();
6012 noop.save().unwrap();
6013 let mut winner = run_state(RunStatus::Ready);
6014 winner.id = "20260101-000000-sup8".to_owned();
6015 winner.save().unwrap();
6016
6017 let mut t = task();
6018 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6019 t.status = TaskStatus::Done;
6020
6021 supersede_prior_runs(&t, &crate::run::home());
6022
6023 assert_eq!(
6024 RunState::load(&failed.id).unwrap().status,
6025 RunStatus::Failed
6026 );
6027 assert_eq!(
6028 RunState::load(&noop.id).unwrap().status,
6029 RunStatus::VerifiedNoop
6030 );
6031 }
6032
6033 fn approval_question(run: &str) -> ask::Question {
6034 ask::Question::new(
6035 run.to_owned(),
6036 land::APPROVAL_NODE.to_owned(),
6037 "land".to_owned(),
6038 "merge?".to_owned(),
6039 String::new(),
6040 vec!["merge".to_owned(), "hold".to_owned()],
6041 )
6042 }
6043
6044 #[test]
6045 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6046 crate::run::pin_test_home();
6047 let mut state = run_state(RunStatus::Landing);
6048 state.id = "20260101-000000-fre1".to_owned();
6049 state.parked = true;
6050 state.save().unwrap();
6051 ask::Questions::open()
6052 .put(&mut approval_question(&state.id))
6053 .unwrap();
6054
6055 let mut t = task();
6056 t.runs.push(state.id.clone());
6057 assert_eq!(
6058 land_resume_state(&t),
6059 LandResume::StillWaiting,
6060 "nobody has answered and the timeout has not passed"
6061 );
6062 }
6063
6064 #[test]
6065 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6066 crate::run::pin_test_home();
6067 let mut state = run_state(RunStatus::Gating);
6068 state.id = "20260101-000000-gt01".to_owned();
6069 state.parked = true;
6070 state.config.graph.answer_timeout = 60;
6071 state.github_text = Some(crate::run::GithubTextAsk {
6072 fingerprint: "f".into(),
6073 title: true,
6074 body: false,
6075 categories: vec!["title-language".into()],
6076 question: None,
6077 asks: 1,
6078 resolved: false,
6079 chosen_title: None,
6080 });
6081 state.save().unwrap();
6082 let store = ask::Questions::open();
6083 let mut q = ask::Question::new(
6084 state.id.clone(),
6085 crate::github_text::ASK_NODE.to_owned(),
6086 crate::github_text::ASK_SEAT.to_owned(),
6087 "s".into(),
6088 String::new(),
6089 vec!["use fallback".into()],
6090 );
6091 store.put(&mut q).unwrap();
6092 let mut t = task();
6093 t.runs.push(state.id.clone());
6094 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6095 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6096 store.put(&mut q).unwrap();
6097 assert_eq!(land_resume_state(&t), LandResume::Ready);
6098 assert!(!store.get(&q.id).unwrap().status.open());
6099 state.github_text.as_mut().unwrap().resolved = true;
6101 state.save().unwrap();
6102 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6103 }
6104
6105 #[test]
6106 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6107 crate::run::pin_test_home();
6112 let mut state = run_state(RunStatus::Landing);
6113 state.id = "20260101-000000-exp1".to_owned();
6114 state.parked = true;
6115 state.config.graph.answer_timeout = 60;
6116 state.save().unwrap();
6117
6118 let store = ask::Questions::open();
6119 let mut q = approval_question(&state.id);
6120 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6121 store.put(&mut q).unwrap();
6122
6123 let mut t = task();
6124 t.runs.push(state.id.clone());
6125 assert_eq!(
6126 land_resume_state(&t),
6127 LandResume::Ready,
6128 "an expired question must not be waited on forever"
6129 );
6130
6131 let after = store.get(&q.id).unwrap();
6132 assert!(
6133 !after.status.open(),
6134 "the question is abandoned, not silently ignored"
6135 );
6136 assert!(
6137 after.resolution().is_none(),
6138 "an abandoned question is not read as a decision"
6139 );
6140 }
6141
6142 #[test]
6143 fn reclaim_settles_a_running_task_against_its_last_run() {
6144 let mut t = task();
6145 t.start("20260904-000000-4043".to_owned());
6146 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6147 assert_eq!(
6148 t.status,
6149 TaskStatus::Done,
6150 "a run that actually finished must not stay `running` forever"
6151 );
6152 }
6153
6154 #[test]
6155 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6156 let mut t = task();
6157 t.start("20260904-000000-4043".to_owned());
6158 t.last_error = Some("earlier trouble".to_owned());
6159 let mut state = run_state(RunStatus::Judging);
6160 state.parked = true;
6161 reclaim(&mut t, Some(state), 1, "en");
6162 assert_eq!(t.status, TaskStatus::Parked);
6163 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6164 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6165 assert!(t.park_reason.is_some());
6166 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6167 assert!(!t.fresh_start);
6168 assert!(t.status.runnable());
6169 }
6170
6171 #[test]
6172 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6173 let mut t = task();
6174 t.start("20260904-000000-4043".to_owned());
6175 t.last_error = Some("earlier trouble".to_owned());
6176 settle(
6177 &mut t,
6178 Verdict {
6179 status: RunStatus::Judging,
6180 left_pr: false,
6181 quota_hit: false,
6182 parked: true,
6183 no_viable_candidates: false,
6184 },
6185 "parked after `judging`",
6186 1,
6187 );
6188 assert_eq!(t.status, TaskStatus::Parked);
6189 assert_eq!(t.attempts, 0);
6190 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6191 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6192 assert_eq!(t.schema, crate::queue::SCHEMA);
6193 assert!(
6194 crate::notices::task_held(&t).is_none(),
6195 "a park is not news"
6196 );
6197 t.start("20260904-000000-4043".to_owned());
6198 assert_eq!(t.park_reason, None);
6199 }
6200
6201 #[test]
6202 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6203 let mut t = task();
6207 t.start("20260904-000000-4043".to_owned());
6208 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6209 assert_eq!(t.status, TaskStatus::Failed);
6210 assert!(t.status.runnable());
6211 }
6212
6213 #[test]
6214 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6215 let mut t = task();
6216 t.start("20260904-000000-4043".to_owned());
6217 reclaim(&mut t, None, 2, "en");
6218 assert_eq!(t.status, TaskStatus::Held);
6219 assert!(
6220 t.last_error
6221 .as_deref()
6222 .is_some_and(|e| e.contains("running")),
6223 "the operator needs to know why this task was held"
6224 );
6225 }
6226
6227 #[test]
6228 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6229 let dir = tempfile::tempdir().unwrap();
6230 let queue = Queue::at(dir.path().to_path_buf());
6231
6232 let mut orphaned = task();
6234 orphaned.id = "20260904-000000-orph".to_owned();
6235 orphaned.status = TaskStatus::Running;
6236 orphaned.attempts = 1;
6237 queue.put(&mut orphaned).unwrap();
6238
6239 let mut alive = task();
6240 alive.id = "20260904-000000-live".to_owned();
6241 alive.status = TaskStatus::Running;
6242 alive.attempts = 1;
6243 queue.put(&mut alive).unwrap();
6244 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6245
6246 let mut queued = task();
6247 queued.id = "20260904-000000-wait".to_owned();
6248 queue.put(&mut queued).unwrap();
6249
6250 let reclaimed = reclaim_orphaned_running(&queue, 2);
6251 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6252
6253 assert_eq!(
6254 queue.get(&orphaned.id).unwrap().status,
6255 TaskStatus::Held,
6256 "nothing was driving it and there was no run to recover"
6257 );
6258 assert_eq!(
6259 queue.get(&alive.id).unwrap().status,
6260 TaskStatus::Running,
6261 "a live claim must protect the task it belongs to"
6262 );
6263 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6264 }
6265
6266 fn read_run_under(home: &Path, id: &str) -> RunState {
6272 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6273 serde_json::from_str(&body).unwrap()
6274 }
6275
6276 #[test]
6277 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6278 let dir = tempfile::tempdir().unwrap();
6279 let home = dir.path().to_path_buf();
6280 let now = Timestamp::now();
6281 let overrun_seat = || crate::run::ActiveSeat {
6282 node: "implement".to_owned(),
6283 started_at: now - jiff::SignedDuration::new(21_000, 0),
6284 timeout_secs: 3_600,
6285 attempt: 0,
6286 task: None,
6287 command: None,
6288 index: None,
6289 total: None,
6290 };
6291
6292 let mut dead = run_state(RunStatus::Implementing);
6293 dead.id = "20260101-000000-dead".to_owned();
6294 dead.active.insert("impl-A".to_owned(), overrun_seat());
6295 dead.driver_pid = Some(4242);
6298 dead.save_under(&home).unwrap();
6299
6300 let mut alive = run_state(RunStatus::Implementing);
6303 alive.id = "20260101-000000-aliv".to_owned();
6304 alive.active.insert("impl-A".to_owned(), overrun_seat());
6305 alive.save_under(&home).unwrap();
6306 let mut status = Status::new();
6307 status.current = vec![Current {
6308 task: "20260101-000000-task".to_owned(),
6309 run: alive.id.clone(),
6310 }];
6311 write_status_to(&home.join("daemon.json"), &status).unwrap();
6312
6313 let questions = Questions::at(home.join("questions"));
6317 let mut q = ask::Question::new(
6318 dead.id.clone(),
6319 "implement".to_owned(),
6320 "impl-A".to_owned(),
6321 "Which storage backend?".to_owned(),
6322 String::new(),
6323 vec!["SQLite".to_owned(), "Redis".to_owned()],
6324 );
6325 questions.put(&mut q).unwrap();
6326
6327 let abandoned = reclaim_abandoned_runs_with(
6328 &home,
6329 now,
6330 |pid| if pid == 4242 { Some(false) } else { None },
6331 |_| panic!("a query answering Dead outright needs no identity corroboration"),
6332 );
6333 assert_eq!(abandoned, vec![dead.id.clone()]);
6334
6335 let reloaded = read_run_under(&home, &dead.id);
6336 assert_eq!(reloaded.status, RunStatus::Failed);
6337 assert!(reloaded.active.is_empty());
6338 assert!(
6339 !questions.get(&q.id).unwrap().status.open(),
6340 "the failed run's own open question must be settled in the same pass"
6341 );
6342
6343 let still_alive = read_run_under(&home, &alive.id);
6344 assert_eq!(
6345 still_alive.status,
6346 RunStatus::Implementing,
6347 "a live daemon's claim protects it"
6348 );
6349 assert!(!still_alive.active.is_empty());
6350 }
6351
6352 #[test]
6362 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
6363 let dir = tempfile::tempdir().unwrap();
6364 let home = dir.path().to_path_buf();
6365 let now = Timestamp::now();
6366
6367 let mut manual = run_state(RunStatus::Reviewing);
6368 manual.id = "20260101-000000-manl".to_owned();
6369 manual.active.insert(
6370 "review-1".to_owned(),
6371 crate::run::ActiveSeat {
6372 node: "review".to_owned(),
6373 started_at: now - jiff::SignedDuration::new(21_000, 0),
6374 timeout_secs: 3_600,
6375 attempt: 0,
6376 task: None,
6377 command: None,
6378 index: None,
6379 total: None,
6380 },
6381 );
6382 manual.driver_pid = Some(4242);
6386 manual.driver_started_at = Some("1790000000".to_owned());
6387 manual.save_under(&home).unwrap();
6388
6389 let abandoned = reclaim_abandoned_runs_with(
6390 &home,
6391 now,
6392 |pid| if pid == 4242 { Some(true) } else { None },
6393 |pid| {
6394 if pid == 4242 {
6395 Some("1790000000".to_owned())
6396 } else {
6397 None
6398 }
6399 },
6400 );
6401 assert!(
6402 abandoned.is_empty(),
6403 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
6404 );
6405
6406 let reloaded = read_run_under(&home, &manual.id);
6407 assert_eq!(reloaded.status, RunStatus::Reviewing);
6408 assert!(!reloaded.active.is_empty());
6409 }
6410
6411 #[test]
6412 fn an_already_claimed_task_is_skipped_rather_than_failed() {
6413 let dir = tempfile::tempdir().unwrap();
6414 let queue = Queue::at(dir.path().to_path_buf());
6415 let mut only = task();
6416 queue.put(&mut only).unwrap();
6417
6418 let _elsewhere = queue.claim(&only.id).unwrap();
6419 let candidates = runnable(&queue);
6420 assert_eq!(candidates.len(), 1, "the task is still runnable");
6421 assert!(
6422 queue.claim(&candidates[0].id).is_err(),
6423 "the loop cannot take a claim somebody else holds"
6424 );
6425
6426 let after = queue.get(&only.id).unwrap();
6427 assert_eq!(after.status, TaskStatus::Queued);
6428 assert_eq!(
6429 after.attempts, 0,
6430 "losing the race is not an attempt at the task"
6431 );
6432 assert_eq!(after.last_error, None);
6433 }
6434
6435 #[test]
6436 fn the_status_file_round_trips_and_its_heartbeat_advances() {
6437 let dir = tempfile::tempdir().unwrap();
6438 let path = dir.path().join("daemon.json");
6439
6440 let mut status = Status::new();
6441 status.idle = false;
6442 status.completed = 7;
6443 status.current = vec![Current {
6444 task: "20260902-000000-t111".to_owned(),
6445 run: "20260902-000001-r111".to_owned(),
6446 }];
6447 write_status_to(&path, &status).unwrap();
6448 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6449 assert_eq!(first.schema, SCHEMA);
6450 assert_eq!(first.pid, std::process::id());
6451 assert!(!first.idle);
6452 assert_eq!(first.completed, 7);
6453 assert_eq!(first.current, status.current);
6454 assert!(
6455 !path.with_extension("json.tmp").exists(),
6456 "the temp file is renamed, not left behind"
6457 );
6458
6459 std::thread::sleep(Duration::from_millis(5));
6460 status.updated_at = Timestamp::now();
6461 status.polls = 3;
6462 write_status_to(&path, &status).unwrap();
6463 let second: Status =
6464 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6465 assert!(
6466 second.updated_at > first.updated_at,
6467 "a reader can only detect staleness if the heartbeat moves"
6468 );
6469 assert_eq!(
6470 second.started_at, first.started_at,
6471 "the start time is not a heartbeat"
6472 );
6473 assert_eq!(second.polls, 3);
6474 }
6475
6476 #[test]
6477 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
6478 let dir = tempfile::tempdir().unwrap();
6479
6480 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
6481
6482 let mut status = Status::new();
6483 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
6484 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6485 let stale = read_status(dir.path()).unwrap();
6486 assert!(
6487 !stale.running(Timestamp::now()),
6488 "a minute without a heartbeat is a dead daemon, not a busy one"
6489 );
6490 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
6491
6492 status.updated_at = Timestamp::now();
6493 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6494 let fresh = read_status(dir.path()).unwrap();
6495 assert!(fresh.running(Timestamp::now()));
6496 }
6497
6498 #[test]
6499 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
6500 let dir = tempfile::tempdir().unwrap();
6501 let now = Timestamp::now();
6502 let mine = "20260903-080619-01c2";
6503
6504 assert!(
6505 !is_working_on(dir.path(), mine, now),
6506 "no status file means nobody is working on anything"
6507 );
6508
6509 let mut status = Status::new();
6510 status.current = vec![Current {
6511 task: "20260903-080340-0167".to_owned(),
6512 run: mine.to_owned(),
6513 }];
6514 status.updated_at = now;
6515 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6516 assert!(is_working_on(dir.path(), mine, now));
6517 assert!(
6518 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
6519 "a daemon busy with one run is not working on another"
6520 );
6521
6522 status.updated_at = now - jiff::SignedDuration::from_secs(600);
6525 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6526 assert!(
6527 !is_working_on(dir.path(), mine, now),
6528 "a stale heartbeat is a dead daemon, so its run is a leftover"
6529 );
6530 }
6531
6532 #[test]
6533 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
6534 let dir = tempfile::tempdir().unwrap();
6535 let now = Timestamp::now();
6536
6537 assert!(
6538 !is_working_on_short(dir.path(), "01c2", now),
6539 "no status file means nobody is working on anything"
6540 );
6541
6542 let mut status = Status::new();
6543 status.current = vec![Current {
6544 task: "20260903-080340-0167".to_owned(),
6545 run: "20260903-080619-01c2".to_owned(),
6546 }];
6547 status.updated_at = now;
6548 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6549 assert!(
6550 is_working_on_short(dir.path(), "01c2", now),
6551 "the run's short id is the last block of its full id"
6552 );
6553 assert!(
6554 !is_working_on_short(dir.path(), "3cbf", now),
6555 "a daemon busy with one worktree bay is not working on another"
6556 );
6557 }
6558
6559 #[test]
6560 fn a_newer_status_file_still_yields_a_reading() {
6561 let dir = tempfile::tempdir().unwrap();
6562 std::fs::write(
6565 dir.path().join("daemon.json"),
6566 serde_json::json!({
6567 "schema": 2,
6568 "updated_at": Timestamp::now().to_string(),
6569 "idle": true,
6570 "surprise": { "nested": [1, 2, 3] },
6571 })
6572 .to_string(),
6573 )
6574 .unwrap();
6575
6576 let reading = read_status(dir.path()).expect("a forward-compatible read");
6577 assert!(reading.running(Timestamp::now()));
6578 assert!(reading.idle);
6579 assert!(reading.current.is_empty());
6580 }
6581
6582 #[test]
6583 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
6584 let dir = tempfile::tempdir().unwrap();
6590 std::fs::write(
6591 dir.path().join("daemon.json"),
6592 serde_json::json!({
6593 "schema": 1,
6594 "pid": 4242,
6595 "updated_at": Timestamp::now().to_string(),
6596 "idle": false,
6597 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
6598 "completed": 3,
6599 "polls": 9,
6600 })
6601 .to_string(),
6602 )
6603 .unwrap();
6604
6605 let reading = read_status(dir.path()).expect("an older shape must still parse");
6606 assert!(reading.running(Timestamp::now()));
6607 assert_eq!(
6608 reading.current,
6609 vec![Current {
6610 task: "20260902-140501-aaaa".to_owned(),
6611 run: "20260902-140502-bbbb".to_owned(),
6612 }]
6613 );
6614 }
6615
6616 #[test]
6617 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
6618 let dir = tempfile::tempdir().unwrap();
6619 std::fs::write(
6620 dir.path().join("daemon.json"),
6621 serde_json::json!({
6622 "schema": 1,
6623 "updated_at": Timestamp::now().to_string(),
6624 "idle": true,
6625 "current": null,
6626 })
6627 .to_string(),
6628 )
6629 .unwrap();
6630 let with_null = read_status(dir.path()).expect("null must still parse");
6631 assert!(with_null.current.is_empty());
6632
6633 std::fs::write(
6634 dir.path().join("daemon.json"),
6635 serde_json::json!({
6636 "schema": 1,
6637 "updated_at": Timestamp::now().to_string(),
6638 "idle": true,
6639 })
6640 .to_string(),
6641 )
6642 .unwrap();
6643 let absent = read_status(dir.path()).expect("a missing field must still parse");
6644 assert!(absent.current.is_empty());
6645 }
6646
6647 #[test]
6648 fn a_task_without_a_repository_runs_in_the_daemons_default() {
6649 let fallback = Path::new("/default");
6650 let mut blank = task();
6651 blank.repo = PathBuf::new();
6652 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
6653 let mut dot = task();
6654 dot.repo = PathBuf::from(".");
6655 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
6656 assert_eq!(
6657 repo_for(&task(), fallback),
6658 PathBuf::from("/repo"),
6659 "a task that names a repository keeps it"
6660 );
6661 }
6662
6663 #[test]
6664 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
6665 let mut solo_cfg = Config::default();
6671 solo_cfg.graph.implementers = 3;
6672 let mut solo_task = task();
6673 solo_task.solo = true;
6674 apply_solo(&mut solo_cfg, &solo_task);
6675 assert_eq!(solo_cfg.graph.implementers, 1);
6676
6677 let mut plain_cfg = Config::default();
6678 plain_cfg.graph.implementers = 3;
6679 let plain_task = task();
6680 assert!(!plain_task.solo);
6681 apply_solo(&mut plain_cfg, &plain_task);
6682 assert_eq!(
6683 plain_cfg.graph.implementers, 3,
6684 "a task that did not ask to run alone keeps the config's candidates"
6685 );
6686 }
6687
6688 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
6689 QuotaLoss {
6690 seat: seat.into(),
6691 node: "judge".into(),
6692 at: at.parse().unwrap(),
6693 reset: reset.map(str::to_string),
6694 }
6695 }
6696
6697 #[test]
6698 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
6699 let old: Vec<QuotaLoss> = (1..=4)
6700 .map(|i| {
6701 loss(
6702 &format!("judge-{i}"),
6703 "2026-09-23T05:23:00Z",
6704 Some("2:40pm (Asia/Tokyo)"),
6705 )
6706 })
6707 .collect();
6708 let fresh = losses_this_attempt(&old, &old);
6709 assert!(fresh.is_empty());
6710 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
6711 }
6713
6714 #[test]
6715 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
6716 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
6717 let now = Timestamp::now();
6718 let mut after = old.clone();
6719 after.push(loss("judge-2", &now.to_string(), None));
6720 let fresh = losses_this_attempt(&old, &after);
6721 assert_eq!(fresh, vec![after[1].clone()]);
6722 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
6723 assert_eq!(
6724 until,
6725 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
6726 );
6727 }
6728
6729 #[test]
6730 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
6731 let before = vec![
6734 loss("judge-1", "2026-09-23T05:23:00Z", None),
6735 loss("judge-2", "2026-09-23T05:24:00Z", None),
6736 ];
6737 let after = vec![
6738 loss("judge-2", "2026-09-23T05:24:00Z", None),
6739 loss("judge-1", "2026-09-24T01:00:00Z", None),
6740 ];
6741 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
6742 }
6743
6744 #[test]
6745 fn merge_overrides_are_parsed_or_refused() {
6746 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
6747 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
6748 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
6749 assert!(merge_mode("squash").is_err());
6750 }
6751
6752 #[test]
6753 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
6754 let now = Timestamp::now();
6755 let fallback = Duration::from_secs(300);
6756 let cap = Duration::from_secs(1800);
6757
6758 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
6760
6761 let soon = now + jiff::SignedDuration::from_secs(600);
6763 assert_eq!(
6764 quota_wait(Some(soon), now, fallback, cap),
6765 Duration::from_secs(600)
6766 );
6767
6768 let past = now - jiff::SignedDuration::from_secs(60);
6771 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
6772
6773 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
6776 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
6777 }
6778
6779 #[test]
6780 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
6781 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6782
6783 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
6784 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
6785
6786 let already_past =
6790 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
6791 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
6792
6793 assert!(
6794 parse_reset_hint("session limit reached", now, now).is_none(),
6795 "free text with no recognised shape is not guessed at"
6796 );
6797 assert!(
6798 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
6799 "an unresolvable zone name is not guessed at either"
6800 );
6801 }
6802
6803 #[test]
6804 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
6805 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6806
6807 let at = parse_reset_hint(
6808 "You've hit your usage limit. Visit \
6809 https://chatgpt.com/codex/settings/usage to purchase more \
6810 credits or try again at Sep 19th, 2026 5:10 PM.",
6811 now,
6812 now,
6813 )
6814 .expect("the codex reset wording is a recognised shape");
6815 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
6816
6817 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
6822 .expect("an explicit year needs no rollover");
6823 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
6824
6825 assert!(
6826 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
6827 "a two-digit year is not the documented shape and is not guessed at"
6828 );
6829 assert!(
6830 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
6831 "a four-letter month name is not the documented three-letter abbreviation"
6832 );
6833 assert!(
6834 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
6835 "an explicit zone on the dated shape is a format nobody has \
6836 documented, and is refused rather than guessed at as UTC"
6837 );
6838 }
6839
6840 #[test]
6841 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
6842 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
6843 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
6844
6845 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
6846 assert_eq!(at.as_second() - recorded.as_second(), 3769);
6847
6848 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
6849 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
6850
6851 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
6852 assert!(
6853 parse_reset_hint(bad, now, recorded).is_none(),
6854 "{bad:?} must not be guessed at"
6855 );
6856 }
6857 }
6858
6859 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
6863 let config = dir.join("magi.toml");
6864 std::fs::write(
6865 &config,
6866 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
6867 )
6868 .unwrap();
6869 let opts = Opts {
6870 poll: Duration::from_secs(30),
6871 config: Some(config),
6872 repo: dir.join("repo"),
6876 ..Opts::default()
6877 };
6878 let home = dir.join("home");
6887 let worktrees = dir.join("wt");
6888 (
6889 opts,
6890 Queue::at(dir.join("queue")),
6891 home.join("daemon.json"),
6892 home,
6893 worktrees,
6894 )
6895 }
6896
6897 #[test]
6898 fn a_stop_is_idempotent_and_once_set_stays_set() {
6899 let stop = Stop::new();
6900 assert!(!stop.stopped());
6901
6902 stop.stop();
6903 assert!(stop.stopped());
6904 stop.stop();
6905 assert!(stop.stopped(), "a second stop is not a toggle");
6906
6907 let shared = stop.clone();
6908 assert!(
6909 shared.stopped(),
6910 "a clone is the same stop; that is how the loop and its caller share one"
6911 );
6912 }
6913
6914 #[test]
6915 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
6916 let stop = Stop::new();
6917 stop.enter();
6918 assert!(
6919 !stop.finishing(),
6920 "a busy loop nobody has asked to stop is just running"
6921 );
6922
6923 stop.stop();
6924 assert!(
6925 stop.finishing(),
6926 "a stop asked for mid-run has not landed until the run is settled"
6927 );
6928
6929 stop.exit();
6930 assert!(
6931 !stop.finishing(),
6932 "once the run is settled the stop has landed and there is nothing to finish"
6933 );
6934 }
6935
6936 #[test]
6937 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6938 let stop = Stop::new();
6939 stop.enter();
6940 stop.enter();
6941 stop.stop();
6942 assert!(stop.finishing(), "two runs still in flight");
6943
6944 stop.exit();
6945 assert!(
6946 stop.finishing(),
6947 "one run finished, but a sibling is still working"
6948 );
6949
6950 stop.exit();
6951 assert!(
6952 !stop.finishing(),
6953 "the last run out is what actually lands the stop"
6954 );
6955 }
6956
6957 #[tokio::test]
6958 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
6959 let dir = tempfile::tempdir().unwrap();
6960 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6961 let stop = Stop::new();
6962 stop.stop();
6963
6964 let began = std::time::Instant::now();
6965 tokio::time::timeout(
6966 Duration::from_secs(2),
6967 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6968 )
6969 .await
6970 .expect("a stopped loop must return, not sit out its poll interval")
6971 .expect("the loop's own setup and teardown must not fail");
6972 assert!(
6973 began.elapsed() < opts.poll,
6974 "returned only after {:?}, which is a poll interval, not a stop",
6975 began.elapsed()
6976 );
6977 }
6978
6979 #[tokio::test]
6980 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
6981 let dir = tempfile::tempdir().unwrap();
6982 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6983 let stop = Stop::new();
6984
6985 let asker = {
6988 let stop = stop.clone();
6989 tokio::spawn(async move {
6990 tokio::time::sleep(Duration::from_millis(20)).await;
6991 stop.stop();
6992 })
6993 };
6994
6995 let began = std::time::Instant::now();
6996 tokio::time::timeout(
6997 Duration::from_secs(2),
6998 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6999 )
7000 .await
7001 .expect("a stop asked for while idle must wake the wait")
7002 .expect("the loop's own setup and teardown must not fail");
7003 asker.await.unwrap();
7004 assert!(
7005 began.elapsed() < opts.poll,
7006 "returned only after {:?}, so the stop waited on the sleep",
7007 began.elapsed()
7008 );
7009 }
7010
7011 #[tokio::test]
7012 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
7013 let dir = tempfile::tempdir().unwrap();
7014 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7015 let stop = Stop::new();
7016 stop.stop();
7017
7018 tokio::time::timeout(
7019 Duration::from_secs(2),
7020 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7021 )
7022 .await
7023 .expect("a stopped loop must return")
7024 .expect("the loop's own setup and teardown must not fail");
7025
7026 assert!(
7027 home.is_dir(),
7028 "the loop did publish a status file, so its removal is the teardown and not an absence"
7029 );
7030 assert!(
7031 !status_file.exists(),
7032 "a stopped loop clears its status file"
7033 );
7034 assert!(
7035 read_status(&home).is_none(),
7036 "a reader must see no daemon at all, not a heartbeat that merely stopped"
7037 );
7038 }
7039
7040 #[tokio::test]
7041 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
7042 let dir = tempfile::tempdir().unwrap();
7043 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7044 opts.once = true;
7045
7046 let mut settled = RunState::new(
7047 dir.path().join("repo"),
7048 "main".to_owned(),
7049 "abc1234".to_owned(),
7050 "fixture".to_owned(),
7051 Config::default(),
7052 );
7053 settled.status = RunStatus::Ready;
7054 let run_dir = home.join("runs").join(&settled.id);
7055 std::fs::create_dir_all(&run_dir).unwrap();
7056 std::fs::write(
7057 run_dir.join("run.json"),
7058 serde_json::to_string_pretty(&settled).unwrap(),
7059 )
7060 .unwrap();
7061 let questions = Questions::at(home.join("questions"));
7062 let mut question = ask::Question::new(
7063 settled.id.clone(),
7064 "review".to_owned(),
7065 "reviewer-1".to_owned(),
7066 "Continue?".to_owned(),
7067 String::new(),
7068 Vec::new(),
7069 );
7070 questions.put(&mut question).unwrap();
7071
7072 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
7073 .await
7074 .unwrap();
7075
7076 assert_eq!(
7077 questions.get(&question.id).unwrap().status,
7078 ask::QuestionStatus::Abandoned,
7079 "an empty --once drain still performs startup question cleanup"
7080 );
7081 }
7082
7083 #[test]
7084 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
7085 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7086
7087 assert!(
7088 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
7089 "never checked before: due at once"
7090 );
7091
7092 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
7093 assert!(
7094 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
7095 "well inside the interval: not due yet"
7096 );
7097
7098 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
7099 assert!(
7100 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
7101 "exactly at the edge: not yet due, same convention as `clean::due`"
7102 );
7103
7104 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7105 assert!(
7106 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
7107 "past the interval: due again"
7108 );
7109 }
7110
7111 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
7116 let config = dir.join("magi.toml");
7117 std::fs::write(
7123 &config,
7124 format!(
7125 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7126 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7127 cache_dir.display()
7128 ),
7129 )
7130 .unwrap();
7131 Opts {
7132 config: Some(config),
7133 repo: dir.join("repo"),
7134 ..Opts::default()
7135 }
7136 }
7137
7138 #[tokio::test]
7139 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
7140 let dir = tempfile::tempdir().unwrap();
7141 let home = dir.path().join("home");
7142 let cache_dir = dir.path().join("cache");
7143 std::fs::create_dir_all(&cache_dir).unwrap();
7144 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7145 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7146
7147 let running = Stop::new();
7150 let mut last_checked = None;
7151 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7152 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
7153 .await;
7154 assert_eq!(
7155 crate::disk::dir_size(&cache_dir),
7156 0,
7157 "over the cap on the first check ever: pruned at once, no idle queue required"
7158 );
7159 assert_eq!(last_checked, Some(t0));
7160
7161 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
7163 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
7164 maybe_prune_cache_between_runs(
7165 &opts.repo,
7166 &opts,
7167 &home,
7168 &running,
7169 &mut last_checked,
7170 too_soon,
7171 )
7172 .await;
7173 assert_eq!(
7174 crate::disk::dir_size(&cache_dir),
7175 10,
7176 "too soon since the last check: left alone rather than rescanned every call"
7177 );
7178 assert_eq!(
7179 last_checked,
7180 Some(t0),
7181 "an idle check does not reset the clock"
7182 );
7183
7184 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7186 maybe_prune_cache_between_runs(
7187 &opts.repo,
7188 &opts,
7189 &home,
7190 &running,
7191 &mut last_checked,
7192 due_again,
7193 )
7194 .await;
7195 assert_eq!(
7196 crate::disk::dir_size(&cache_dir),
7197 0,
7198 "due again: pruned back under the cap"
7199 );
7200 }
7201
7202 #[tokio::test]
7210 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
7211 let dir = tempfile::tempdir().unwrap();
7212 let home = dir.path().join("home");
7213 let cache_dir = dir.path().join("cache");
7214 std::fs::create_dir_all(&cache_dir).unwrap();
7215 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7216 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7217
7218 let stop = Stop::new();
7219 stop.stop();
7220 assert!(
7221 !stop.finishing(),
7222 "no run is in flight at a between-runs boundary, so nothing else \
7223 would tell the operator this stop had not taken effect yet"
7224 );
7225
7226 let mut last_checked = None;
7227 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7228 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
7229 .await;
7230 assert_eq!(
7231 crate::disk::dir_size(&cache_dir),
7232 10,
7233 "over its cap, and due for the first check ever, but a stop outranks \
7234 it: the cap is a standing policy the next start measures again"
7235 );
7236 assert_eq!(
7237 last_checked, None,
7238 "a check that never happened must not claim the interval"
7239 );
7240 }
7241
7242 #[tokio::test]
7256 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
7257 let dir = tempfile::tempdir().unwrap();
7258 let cache_dir = dir.path().join("cache");
7259 std::fs::create_dir_all(&cache_dir).unwrap();
7260 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
7261
7262 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
7263 opts.poll = Duration::from_millis(20);
7264 opts.max_attempts = 1_000;
7265
7266 let queue = Queue::at(dir.path().join("queue"));
7267 let mut t = Task::new(
7268 "x".to_owned(),
7269 "x".to_owned(),
7270 opts.repo.clone(),
7271 Source::Human,
7272 );
7273 queue.put(&mut t).unwrap();
7274
7275 let home = dir.path().join("home");
7276 let worktrees = dir.path().join("wt");
7277 let status_file = home.join("daemon.json");
7278 let stop = Stop::new();
7279 let stopper = {
7280 let stop = stop.clone();
7281 let queue = Queue::at(dir.path().join("queue"));
7282 let id = t.id.clone();
7283 tokio::spawn(async move {
7284 tokio::time::sleep(Duration::from_millis(400)).await;
7288 for _ in 0..200 {
7289 if queue.get(&id).is_ok_and(|t| t.attempts >= 2) {
7290 break;
7291 }
7292 tokio::time::sleep(Duration::from_millis(50)).await;
7293 }
7294 stop.stop();
7295 })
7296 };
7297
7298 tokio::time::timeout(
7299 Duration::from_secs(20),
7300 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7301 )
7302 .await
7303 .expect("the loop must not hang on a queue that keeps producing failing work")
7304 .expect("the loop's own setup and teardown must not fail");
7305 stopper.await.unwrap();
7306
7307 let after = queue.get(&t.id).unwrap();
7308 assert!(
7309 after.attempts >= 2,
7310 "the harness must actually have retried more than once, or this is not \
7311 exercising a busy queue at all (got {} attempt(s))",
7312 after.attempts
7313 );
7314 assert!(
7315 after.status.runnable(),
7316 "still under its attempt budget: the queue never reached a natural idle \
7317 on its own, only the external stop ended the test"
7318 );
7319
7320 assert_eq!(
7321 crate::disk::dir_size(&cache_dir),
7322 0,
7323 "an oversized cache must not be left to grow unboundedly just because the \
7324 queue kept the loop busy the whole time"
7325 );
7326 }
7327
7328 #[test]
7329 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
7330 let dir = tempfile::tempdir().unwrap();
7331 let queue = Queue::at(dir.path().join("queue"));
7332 let questions = Questions::at(dir.path().join("questions"));
7333 let mut task = task();
7334 queue.put(&mut task).unwrap();
7335
7336 let mut task_question = ask::Question::new(
7337 task.id.clone(),
7338 crate::conduct::NODE.to_owned(),
7339 "conduct".to_owned(),
7340 "Which backend?".to_owned(),
7341 String::new(),
7342 Vec::new(),
7343 );
7344 questions.put(&mut task_question).unwrap();
7345 task.block(vec![task_question.id.clone()], None);
7346 queue.put(&mut task).unwrap();
7347
7348 let mut run_question = ask::Question::new(
7349 "20260101-000000-run1".to_owned(),
7350 "review".to_owned(),
7351 "reviewer-1".to_owned(),
7352 "Run question".to_owned(),
7353 String::new(),
7354 Vec::new(),
7355 );
7356 questions.put(&mut run_question).unwrap();
7357
7358 let mut coincidental = ask::Question::new(
7363 task.id.clone(),
7364 "review".to_owned(),
7365 "reviewer-1".to_owned(),
7366 "Unrelated review question".to_owned(),
7367 String::new(),
7368 Vec::new(),
7369 );
7370 questions.put(&mut coincidental).unwrap();
7371
7372 reconcile_task_questions(&queue, &questions);
7373 assert!(questions.get(&task_question.id).unwrap().status.open());
7374 assert!(questions.get(&run_question.id).unwrap().status.open());
7375 assert!(questions.get(&coincidental.id).unwrap().status.open());
7376
7377 task.release();
7378 queue.put(&mut task).unwrap();
7379 reconcile_task_questions(&queue, &questions);
7380 assert_eq!(
7381 questions.get(&task_question.id).unwrap().status,
7382 ask::QuestionStatus::Abandoned
7383 );
7384 assert!(
7385 questions.get(&run_question.id).unwrap().status.open(),
7386 "run questions remain the run janitor's responsibility"
7387 );
7388 assert!(
7389 questions.get(&coincidental.id).unwrap().status.open(),
7390 "a non-conductor question must not be abandoned just because its \
7391 run id coincides with a task id"
7392 );
7393 }
7394
7395 #[test]
7396 fn a_freshly_started_running_task_is_never_stalled() {
7397 let dir = tempfile::tempdir().unwrap();
7398 let mut t = task();
7399 t.start("run-1".to_owned());
7400 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
7403 }
7404
7405 #[test]
7406 fn a_long_running_task_with_no_live_daemon_is_stalled() {
7407 let dir = tempfile::tempdir().unwrap();
7408 let mut t = task();
7409 t.start("run-1".to_owned());
7410 t.updated_at = Timestamp::now()
7411 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7412 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
7413 assert_eq!(
7414 stalled_tasks(
7415 &Queue::at(dir.path().join("q")),
7416 dir.path(),
7417 Timestamp::now()
7418 )
7419 .len(),
7420 0,
7421 "the task was never written to this queue"
7422 );
7423 }
7424
7425 #[test]
7426 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
7427 let dir = tempfile::tempdir().unwrap();
7428 let mut t = task();
7429 t.id = "20260903-080340-0167".to_owned();
7430 t.start("20260903-080619-01c2".to_owned());
7431 t.updated_at = Timestamp::now()
7432 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7433
7434 let mut status = Status::new();
7435 status.current = vec![Current {
7436 task: t.id.clone(),
7437 run: "20260903-080619-01c2".to_owned(),
7438 }];
7439 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7440
7441 assert!(
7442 !is_stalled(&t, dir.path(), Timestamp::now()),
7443 "a live daemon's own heartbeat rules out stalled, however long the task has run"
7444 );
7445 }
7446
7447 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
7451 let path = queue.path_of(id);
7452 let body = std::fs::read_to_string(&path).unwrap();
7453 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
7454 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
7455 v["updated_at"] = serde_json::Value::String(old.to_string());
7456 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
7457 }
7458
7459 #[test]
7460 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
7461 let dir = tempfile::tempdir().unwrap();
7474 let queue = Queue::at(dir.path().join("queue"));
7475 let home = dir.path().join("home");
7476
7477 let mut t = task();
7478 t.id = "20260101-000001-lock".to_owned();
7479 t.start("run-1".to_owned());
7480 queue.put(&mut t).unwrap();
7481 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7482 std::fs::write(
7483 dir.path().join("queue").join(format!("{}.lock", t.id)),
7484 "not a pid",
7485 )
7486 .unwrap();
7487
7488 let now = Timestamp::now();
7489 assert!(
7490 reclaim_orphaned_running(&queue, 2).is_empty(),
7491 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
7492 and reclaim must leave the task alone"
7493 );
7494 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7495
7496 let stalled = stalled_tasks(&queue, &home, now);
7497 assert_eq!(
7498 stalled.len(),
7499 1,
7500 "reclaim's inability to claim it yet must not hide it from the conductor"
7501 );
7502 assert_eq!(stalled[0].id, t.id);
7503 }
7504
7505 #[test]
7506 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
7507 let dir = tempfile::tempdir().unwrap();
7508 crate::run::set_home(dir.path().join("run-home"));
7509 let queue = Queue::at(dir.path().join("queue"));
7510 let home = dir.path().join("home");
7511 let questions = Questions::at(dir.path().join("questions"));
7512
7513 let mut t = task();
7514 t.id = "20260101-000003-dead".to_owned();
7515 t.start("missing-run".to_owned());
7516 queue.put(&mut t).unwrap();
7517 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7518
7519 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7522 assert_eq!(
7523 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
7524 [&t.id]
7525 );
7526 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
7527 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7528
7529 crate::conduct::apply(
7532 &queue,
7533 &questions,
7534 &crate::conduct::Verdict {
7535 decisions: vec![crate::conduct::Decision {
7536 id: t.id.clone(),
7537 recovery: Some(crate::conduct::Recovery::Requeue),
7538 ..crate::conduct::Decision::default()
7539 }],
7540 },
7541 )
7542 .unwrap();
7543 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7544 }
7545
7546 #[test]
7547 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
7548 let dir = tempfile::tempdir().unwrap();
7549 let queue = Queue::at(dir.path().join("queue"));
7550 let home = dir.path().join("home");
7551
7552 let mut fresh = task();
7553 fresh.id = "20260101-000001-aaaa".to_owned();
7554 fresh.start("run-1".to_owned());
7555 queue.put(&mut fresh).unwrap();
7556
7557 let mut old = task();
7558 old.id = "20260101-000002-bbbb".to_owned();
7559 old.start("run-2".to_owned());
7560 queue.put(&mut old).unwrap();
7561 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
7562
7563 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7564 assert_eq!(stalled.len(), 1);
7565 assert_eq!(stalled[0].id, old.id);
7566 }
7567
7568 #[test]
7569 fn queued_and_finished_task_views_partition_by_status() {
7570 let dir = tempfile::tempdir().unwrap();
7571 let queue = Queue::at(dir.path().join("queue"));
7572
7573 let mut queued = task();
7574 queued.id = "20260101-000001-aaaa".to_owned();
7575 queue.put(&mut queued).unwrap();
7576
7577 let mut failed = task();
7578 failed.id = "20260101-000002-bbbb".to_owned();
7579 failed.start("run-1".to_owned());
7580 failed.fail("gate red", 5);
7581 queue.put(&mut failed).unwrap();
7582
7583 let mut held = task();
7584 held.id = "20260101-000003-cccc".to_owned();
7585 held.hold_machine(None);
7586 queue.put(&mut held).unwrap();
7587
7588 let mut running = task();
7589 running.id = "20260101-000004-dddd".to_owned();
7590 running.start("run-2".to_owned());
7591 queue.put(&mut running).unwrap();
7592
7593 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
7594 assert_eq!(queued_ids, [queued.id.clone()]);
7595
7596 let mut finished_ids: Vec<String> =
7597 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
7598 finished_ids.sort_unstable();
7599 let mut want = vec![failed.id.clone(), held.id.clone()];
7600 want.sort_unstable();
7601 assert_eq!(finished_ids, want);
7602 }
7603
7604 #[test]
7605 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
7606 let dir = tempfile::tempdir().unwrap();
7607 let queue = Queue::at(dir.path().join("queue"));
7608 let questions = ask::Questions::at(dir.path().join("questions"));
7609
7610 let mut dep = task();
7611 dep.id = "20260101-000001-dep0".to_owned();
7612 dep.succeed();
7613 queue.put(&mut dep).unwrap();
7614
7615 let mut still_going = task();
7616 still_going.id = "20260101-000002-dep1".to_owned();
7617 queue.put(&mut still_going).unwrap();
7618
7619 let mut blocked = task();
7620 blocked.id = "20260101-000003-main".to_owned();
7621 blocked.block(
7622 vec![dep.id.clone(), still_going.id.clone()],
7623 Some("waits on both".to_owned()),
7624 );
7625 queue.put(&mut blocked).unwrap();
7626
7627 resolve_blockers(&queue, &questions);
7628
7629 let after = queue.get(&blocked.id).unwrap();
7630 assert_eq!(
7631 after.status,
7632 TaskStatus::Blocked,
7633 "one dependency is still outstanding"
7634 );
7635 assert_eq!(after.blocked_by, [still_going.id.clone()]);
7636 }
7637
7638 #[test]
7639 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
7640 let dir = tempfile::tempdir().unwrap();
7641 let queue = Queue::at(dir.path().join("queue"));
7642 let questions = ask::Questions::at(dir.path().join("questions"));
7643
7644 let mut q = crate::ask::Question::new(
7645 "20260101-000001-main".to_owned(),
7646 crate::conduct::NODE.to_owned(),
7647 "conduct".to_owned(),
7648 "Which backend?".to_owned(),
7649 String::new(),
7650 Vec::new(),
7651 );
7652 questions.put(&mut q).unwrap();
7653 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
7654 .unwrap();
7655 questions.put(&mut q).unwrap();
7656
7657 let mut blocked = task();
7658 blocked.id = "20260101-000001-main".to_owned();
7659 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
7660 queue.put(&mut blocked).unwrap();
7661
7662 resolve_blockers(&queue, &questions);
7663
7664 let after = queue.get(&blocked.id).unwrap();
7665 assert_eq!(
7666 after.status,
7667 TaskStatus::Queued,
7668 "the only blocker resolved"
7669 );
7670 assert_eq!(after.answers.len(), 1);
7671 assert_eq!(after.answers[0].question, "Which backend?");
7672 assert_eq!(after.answers[0].answer, "SQLite");
7673
7674 let instruction = instruction_for(&after);
7676 assert!(instruction.contains("Which backend?"));
7677 assert!(instruction.contains("SQLite"));
7678 }
7679
7680 #[test]
7681 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
7682 let dir = tempfile::tempdir().unwrap();
7683 let queue = Queue::at(dir.path().join("queue"));
7684 let questions = ask::Questions::at(dir.path().join("questions"));
7685
7686 let mut q = crate::ask::Question::new(
7687 "20260101-000001-main".to_owned(),
7688 crate::conduct::NODE.to_owned(),
7689 "conduct".to_owned(),
7690 "Is the setup done?".to_owned(),
7691 String::new(),
7692 Vec::new(),
7693 );
7694 q.abandon("no answer within 60s of asking");
7695 questions.put(&mut q).unwrap();
7696
7697 let mut blocked = task();
7698 blocked.id = "20260101-000001-main".to_owned();
7699 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
7700 queue.put(&mut blocked).unwrap();
7701
7702 resolve_blockers(&queue, &questions);
7703
7704 let after = queue.get(&blocked.id).unwrap();
7705 assert_eq!(
7706 after.status,
7707 TaskStatus::Held,
7708 "never left blocked on nothing"
7709 );
7710 assert!(!after.operator_held(), "a machine hold, for triage");
7711 assert!(
7712 after
7713 .hold_reason
7714 .as_deref()
7715 .unwrap_or_default()
7716 .contains("went unanswered")
7717 );
7718 }
7719
7720 #[test]
7721 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
7722 let dir = tempfile::tempdir().unwrap();
7728 let queue = Queue::at(dir.path().join("queue"));
7729 let questions = ask::Questions::at(dir.path().join("questions"));
7730
7731 let mut q = crate::ask::Question::new(
7732 "20260101-000001-main".to_owned(),
7733 crate::conduct::NODE.to_owned(),
7734 "conduct".to_owned(),
7735 "How should this be handled?".to_owned(),
7736 String::new(),
7737 Vec::new(),
7738 );
7739 questions.put(&mut q).unwrap();
7740 q.answer(crate::ask::Answer::Text(
7741 "leave it held, a human will look at it later".to_owned(),
7742 ))
7743 .unwrap();
7744 questions.put(&mut q).unwrap();
7745
7746 let mut held = task();
7747 held.id = "20260101-000001-main".to_owned();
7748 held.hold_machine(Some("out of attempts".to_owned()));
7749 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
7750 queue.put(&mut held).unwrap();
7751
7752 resolve_blockers(&queue, &questions);
7753
7754 let after = queue.get(&held.id).unwrap();
7755 assert_eq!(after.status, TaskStatus::Held);
7756 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
7757 assert_eq!(
7758 after.answers[0].answer,
7759 "leave it held, a human will look at it later"
7760 );
7761 }
7762
7763 #[test]
7764 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
7765 let dir = tempfile::tempdir().unwrap();
7766 let queue = Queue::at(dir.path().join("queue"));
7767 let questions = ask::Questions::at(dir.path().join("questions"));
7768 let mut dep = task();
7769 dep.id = "20260101-000001-gone".to_owned();
7770 queue.put(&mut dep).unwrap();
7771 let mut blocked = task();
7772 blocked.id = "20260101-000003-main".to_owned();
7773 blocked.block(vec![dep.id.clone()], None);
7774 queue.put(&mut blocked).unwrap();
7775
7776 let claim = queue.claim(&blocked.id).unwrap();
7778 queue.remove(&dep.id, false, &questions).unwrap();
7779 drop(claim);
7780 resolve_blockers(&queue, &questions);
7781
7782 let after = queue.get(&blocked.id).unwrap();
7783 assert_eq!(after.status, TaskStatus::Queued);
7784 assert!(after.blocked_by.is_empty());
7785 }
7786
7787 #[test]
7788 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
7789 let dir = tempfile::tempdir().unwrap();
7795 let queue = Queue::at(dir.path().join("queue"));
7796 let questions = ask::Questions::at(dir.path().join("questions"));
7797
7798 let mut still_going = task();
7799 still_going.id = "20260101-000002-dep1".to_owned();
7800 queue.put(&mut still_going).unwrap();
7801
7802 let mut blocked = task();
7803 blocked.id = "20260101-000003-main".to_owned();
7804 blocked.block(
7805 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
7806 Some("waits on both".to_owned()),
7807 );
7808 queue.put(&mut blocked).unwrap();
7809
7810 resolve_blockers(&queue, &questions);
7811
7812 let after = queue.get(&blocked.id).unwrap();
7813 assert_eq!(
7814 after.status,
7815 TaskStatus::Held,
7816 "a missing dependency must not leave the task blocked forever"
7817 );
7818 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
7819 assert!(after.blocked_by.is_empty());
7820 let reason = after.hold_reason.as_deref().unwrap_or_default();
7821 assert!(
7822 reason.contains("20260101-000001-gone"),
7823 "the missing id must be named so an operator can tell what happened: {reason}"
7824 );
7825 assert!(
7826 reason.contains(&still_going.id),
7827 "the still-valid dependency must not silently vanish from the record: {reason}"
7828 );
7829 }
7830
7831 #[test]
7832 fn instruction_for_is_unchanged_without_any_answers() {
7833 let t = task();
7834 assert_eq!(instruction_for(&t), t.instruction);
7835 }
7836
7837 #[test]
7838 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
7839 let dir = tempfile::tempdir().unwrap();
7840 let q = Queue::at(dir.path().join("queue"));
7841 let src = dir.path().join("shot.png");
7842 std::fs::write(&src, "x").unwrap();
7843 let mut t = task();
7844 q.attach(&mut t, &[src]).unwrap();
7845 let paths = task_attachments(&q, &t).unwrap();
7846 assert_eq!(paths.len(), 1);
7847 assert!(paths[0].is_absolute() && paths[0].is_file());
7848 std::fs::remove_file(&paths[0]).unwrap();
7849 let err = task_attachments(&q, &t).unwrap_err().to_string();
7850 assert!(err.contains("shot.png"), "{err}");
7851 }
7852
7853 #[test]
7854 fn resumed_instruction_is_unchanged_without_any_answers() {
7855 let t = task();
7856 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
7857 }
7858
7859 #[test]
7860 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
7861 let mut t = task();
7862 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7863 let old = t.instruction.clone();
7867
7868 let refreshed = resumed_instruction(&old, &t);
7869 assert!(refreshed.starts_with(&old), "the original text is kept");
7870 assert!(refreshed.contains("Which backend?"));
7871 assert!(refreshed.contains("SQLite"));
7872 }
7873
7874 #[test]
7875 fn resumed_instruction_keeps_an_original_answers_heading() {
7876 let mut t = task();
7877 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
7878 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7879
7880 let refreshed = resumed_instruction(&t.instruction, &t);
7881
7882 assert!(
7883 refreshed.starts_with(&t.instruction),
7884 "an answers heading in the original instruction is not the appended block"
7885 );
7886 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
7887 assert!(refreshed.contains("Which backend?"));
7888 assert!(refreshed.contains("SQLite"));
7889
7890 let repeated = resumed_instruction(&refreshed, &t);
7891 assert_eq!(
7892 repeated, refreshed,
7893 "only the final appended block is refreshed"
7894 );
7895 }
7896
7897 #[test]
7898 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
7899 let mut t = task();
7900 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7901
7902 let once = resumed_instruction(&t.instruction, &t);
7906 let twice = resumed_instruction(&once, &t);
7907 assert_eq!(once, twice);
7908 assert_eq!(once.matches("Which backend?").count(), 1);
7909
7910 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
7912 let refreshed = resumed_instruction(&once, &t);
7913 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
7914 assert!(refreshed.contains("Which backend?"));
7915 assert!(refreshed.contains("Which cache?"));
7916 }
7917
7918 #[test]
7919 fn prepare_instruction_covers_all_three_starters() {
7920 let mut t = task();
7921 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7922
7923 assert_eq!(
7926 prepare_instruction(&Starter::Start, None, &t),
7927 Some(instruction_for(&t))
7928 );
7929
7930 let old = t.instruction.clone();
7933 assert_eq!(
7934 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
7935 Some(resumed_instruction(&old, &t))
7936 );
7937
7938 assert_eq!(
7942 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
7943 None
7944 );
7945 }
7946
7947 #[test]
7948 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
7949 assert_eq!(
7950 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
7951 Starter::Review("magi/eba2/A".to_owned())
7952 );
7953 }
7954
7955 #[test]
7956 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
7957 assert_eq!(
7958 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
7959 Starter::Start,
7960 "a vanished review branch must not fall back to resuming the old run either"
7961 );
7962 }
7963
7964 #[test]
7965 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
7966 let mut t = task();
7967 t.start("old-run".to_owned());
7968 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
7969 t.release();
7970 let branch = t.review_branch.take();
7971 assert_eq!(
7972 choose_starter(branch.as_deref(), true, Some("old-run")),
7973 Starter::Review("magi/eba2/A".to_owned()),
7974 "a review wins over resuming the old run"
7975 );
7976 }
7977
7978 #[test]
7979 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
7980 assert_eq!(
7981 choose_starter(None, false, Some("some-run")),
7982 Starter::Resume("some-run".to_owned())
7983 );
7984 assert_eq!(choose_starter(None, false, None), Starter::Start);
7985 }
7986
7987 #[test]
7988 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
7989 let mut released = task();
7990 released.start("stalled-run".to_owned());
7991 released.requeue();
7992 let unfinished = (!released.fresh_start)
7993 .then(|| Some("stalled-run".to_owned()))
7994 .flatten();
7995 assert_eq!(
7996 choose_starter(None, false, unfinished.as_deref()),
7997 Starter::Start,
7998 "release keeps run history but must not resume it"
7999 );
8000 assert_eq!(released.runs, ["stalled-run"]);
8001 }
8002
8003 #[test]
8004 fn an_ordinary_release_keeps_a_resumable_run_available() {
8005 let mut released = task();
8006 released.start("stalled-run".to_owned());
8007 released.release();
8008 let unfinished = (!released.fresh_start)
8009 .then(|| Some("stalled-run".to_owned()))
8010 .flatten();
8011 assert_eq!(
8012 choose_starter(None, false, unfinished.as_deref()),
8013 Starter::Resume("stalled-run".to_owned()),
8014 "manual release must preserve the normal resume path"
8015 );
8016 }
8017
8018 #[test]
8019 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
8020 let mut state = run_state(RunStatus::Blocked);
8021 state.config.graph.review_rounds = 3;
8022 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
8023 assert!(exhausted_review_budget(&state));
8024
8025 state.reviews.pop();
8027 assert!(!exhausted_review_budget(&state));
8028
8029 let mut stalled = run_state(RunStatus::Stalled);
8032 stalled.config.graph.review_rounds = 1;
8033 stalled.reviews = vec![review_round(1)];
8034 assert!(!exhausted_review_budget(&stalled));
8035 }
8036
8037 fn review_round(round: usize) -> crate::run::ReviewRound {
8038 crate::run::ReviewRound {
8039 round,
8040 head: "deadbeef".to_owned(),
8041 verified_head: None,
8042 verified_at: None,
8043 reviews: Vec::new(),
8044 e2e: Vec::new(),
8045 verify_retried: false,
8046 e2e_deferred: false,
8047 e2e_defer_reason: None,
8048 fix: None,
8049 blocking: 0,
8050 answered: 1,
8051 expected: 1,
8052 clean: false,
8053 progressed: true,
8054 vote_split: false,
8055 reconsideration: Vec::new(),
8056 verdict: None,
8057 }
8058 }
8059
8060 #[test]
8061 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
8062 let mut run = RunState::new(
8063 PathBuf::from("/repo"),
8064 "main".to_owned(),
8065 "abc1234def".to_owned(),
8066 "add retries".to_owned(),
8067 Config::default(),
8068 );
8069 run.status = RunStatus::Judging;
8070 run.parked = true;
8071 let mut task = Task::new(
8072 "add retries".to_owned(),
8073 "add retries".to_owned(),
8074 PathBuf::from("/repo"),
8075 crate::queue::Source::Human,
8076 );
8077 task.status = TaskStatus::Failed;
8078 task.runs = vec![run.id.clone()];
8079 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
8080 assert!(with(&task, &run), "parked after judging is the case");
8081 let mut parked_task = task.clone();
8082 parked_task.status = TaskStatus::Parked;
8083 assert!(with(&parked_task, &run), "the Parked status is the case");
8084
8085 let mut not_parked = run.clone();
8086 not_parked.parked = false;
8087 not_parked.status = RunStatus::Stalled;
8088 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
8089
8090 let mut fresh = task.clone();
8091 fresh.fresh_start = true;
8092 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
8093
8094 let mut review = task.clone();
8095 review.review_branch = Some("magi/x/A".to_owned());
8096 assert!(!with(&review, &run), "review is ranked before resume");
8097
8098 let mut held = task.clone();
8099 held.status = TaskStatus::Held;
8100 assert!(!with(&held, &run), "a hold stays visible to the conductor");
8101
8102 let mut released = run.clone();
8103 released.released_to = Some("20260901-000000-new1".to_owned());
8104 assert!(!with(&task, &released), "nothing left to resume into");
8105
8106 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
8107 "unreadable"
8108 )));
8109 }
8110
8111 #[test]
8112 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
8113 let mut released = RunState::new(
8114 PathBuf::from("/repo"),
8115 "main".to_owned(),
8116 "abc1234def".to_owned(),
8117 "add retries".to_owned(),
8118 Config::default(),
8119 );
8120 released.status = RunStatus::Blocked;
8121 assert_eq!(
8122 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8123 Some(released.id.clone())
8124 );
8125 released.released_to = Some("20260901-000000-new1".to_owned());
8126 assert_eq!(
8127 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8128 None,
8129 "there is nothing left to resume it into"
8130 );
8131 }
8132
8133 #[test]
8134 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
8135 let mut exhausted = RunState::new(
8144 PathBuf::from("/repo"),
8145 "main".to_owned(),
8146 "abc1234def".to_owned(),
8147 "add retries".to_owned(),
8148 Config::default(),
8149 );
8150 exhausted.status = RunStatus::Blocked;
8151 exhausted.config.graph.review_rounds = 1;
8152 exhausted.reviews = vec![review_round(1)];
8153
8154 assert_eq!(
8155 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
8156 None,
8157 "an exhausted `Blocked` run must not be offered as resumable"
8158 );
8159
8160 let mut has_budget_left = RunState::new(
8163 PathBuf::from("/repo"),
8164 "main".to_owned(),
8165 "abc1234def".to_owned(),
8166 "add retries".to_owned(),
8167 Config::default(),
8168 );
8169 has_budget_left.status = RunStatus::Blocked;
8170 has_budget_left.config.graph.review_rounds = 3;
8171 has_budget_left.reviews = vec![review_round(1)];
8172
8173 assert_eq!(
8174 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
8175 Ok(has_budget_left.clone())
8176 }),
8177 Some(has_budget_left.id.clone())
8178 );
8179 }
8180
8181 #[test]
8182 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
8183 let mut older_stalled = RunState::new(
8191 PathBuf::from("/repo"),
8192 "main".to_owned(),
8193 "abc1234def".to_owned(),
8194 "add retries".to_owned(),
8195 Config::default(),
8196 );
8197 older_stalled.status = RunStatus::Stalled;
8198
8199 let mut newest_exhausted = RunState::new(
8200 PathBuf::from("/repo"),
8201 "main".to_owned(),
8202 "abc1234def".to_owned(),
8203 "add retries".to_owned(),
8204 Config::default(),
8205 );
8206 newest_exhausted.status = RunStatus::Blocked;
8207 newest_exhausted.config.graph.review_rounds = 1;
8208 newest_exhausted.reviews = vec![review_round(1)];
8209
8210 assert_eq!(
8211 unfinished_run_with(
8212 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
8213 "t",
8214 |_| Ok(newest_exhausted.clone())
8215 ),
8216 None,
8217 "the newest run is exhausted, so nothing here is worth resuming - \
8218 least of all the older, already-superseded run"
8219 );
8220 }
8221
8222 #[test]
8223 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
8224 assert_eq!(
8225 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
8226 Err(anyhow::anyhow!("fixture is absent"))
8227 }),
8228 None
8229 );
8230 }
8231
8232 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
8233 let mut q = ask::Question::new(
8234 run.to_owned(),
8235 "implement".to_owned(),
8236 "impl-A".to_owned(),
8237 "continue?".to_owned(),
8238 String::new(),
8239 vec!["resume で続行する".to_owned(), "other".to_owned()],
8240 );
8241 q.actions.insert("resume で続行する".to_owned(), action);
8242 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
8243 .unwrap();
8244 q
8245 }
8246
8247 fn held_task_with(run: &str) -> Task {
8248 let mut t = task();
8249 t.runs = vec![run.to_owned()];
8250 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
8251 t
8252 }
8253
8254 fn resume_action(run: &str) -> ask::ChoiceAction {
8255 ask::ChoiceAction::Resume { run: run.into() }
8256 }
8257
8258 #[test]
8259 fn decide_action_resumes_only_the_latest_resumable_run() {
8260 let t = held_task_with("r1");
8261 let q = action_question("r1", resume_action("r1"));
8262 let load = |s: RunState| move |_: &str| Ok(s);
8263 assert_eq!(
8264 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
8265 ActionDecision::Resume("r1".into())
8266 );
8267 let q_other = action_question("r1", resume_action("r0"));
8269 assert!(matches!(
8270 decide_action(
8271 &t,
8272 &q_other,
8273 &PHRASES_EN,
8274 load(run_state(RunStatus::Blocked))
8275 ),
8276 ActionDecision::Refuse(_)
8277 ));
8278 assert!(matches!(
8280 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
8281 ActionDecision::Refuse(_)
8282 ));
8283 let mut released = run_state(RunStatus::Blocked);
8285 released.released_to = Some("elsewhere".into());
8286 assert!(matches!(
8287 decide_action(&t, &q, &PHRASES_EN, load(released)),
8288 ActionDecision::Refuse(_)
8289 ));
8290 assert!(matches!(
8292 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
8293 ActionDecision::Refuse(_)
8294 ));
8295 }
8296
8297 #[test]
8298 fn decide_action_ignores_a_question_about_an_earlier_run() {
8299 let mut t = held_task_with("r1");
8300 t.runs.push("r2".to_owned());
8301 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8302 assert_eq!(
8303 decide_action(
8304 &t,
8305 &action_question("r1", ask::ChoiceAction::Done),
8306 &PHRASES_EN,
8307 never
8308 ),
8309 ActionDecision::Stale
8310 );
8311 }
8312
8313 #[test]
8314 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
8315 let mut t = held_task_with("r1");
8316 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8317 assert_eq!(
8318 decide_action(
8319 &t,
8320 &action_question("r1", ask::ChoiceAction::Requeue),
8321 &PHRASES_EN,
8322 never
8323 ),
8324 ActionDecision::Requeue
8325 );
8326 let done_q = action_question("r1", ask::ChoiceAction::Done);
8327 assert_eq!(
8328 decide_action(&t, &done_q, &PHRASES_EN, never),
8329 ActionDecision::Done
8330 );
8331 t.mark_action_applied(&done_q.id);
8332 assert_eq!(
8333 decide_action(&t, &done_q, &PHRASES_EN, never),
8334 ActionDecision::Skip
8335 );
8336
8337 let mut plain = action_question("r1", ask::ChoiceAction::Done);
8339 plain.actions.clear();
8340 assert_eq!(
8341 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
8342 ActionDecision::Skip
8343 );
8344 let mut running = held_task_with("r1");
8346 running.status = TaskStatus::Running;
8347 assert_eq!(
8348 decide_action(
8349 &running,
8350 &action_question("r1", ask::ChoiceAction::Done),
8351 &PHRASES_EN,
8352 never
8353 ),
8354 ActionDecision::Skip
8355 );
8356 }
8357
8358 #[test]
8359 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
8360 let dir = tempfile::tempdir().unwrap();
8361 let queue = Queue::at(dir.path().join("queue"));
8362 let questions = Questions::at(dir.path().join("questions"));
8363 let home = dir.path().join("home");
8364 let mut state = run_state(RunStatus::Blocked);
8365 state.id = "20260101-000000-act1".to_owned();
8366 state.save_under(&home).unwrap();
8367
8368 let mut t = held_task_with(&state.id);
8369 queue.put(&mut t).unwrap();
8370 let mut q = action_question(&state.id, resume_action(&state.id));
8371 questions.put(&mut q).unwrap();
8372
8373 apply_choice_actions(&queue, &questions, &home);
8374 let after = queue.get(&t.id).unwrap();
8375 assert_eq!(after.status, TaskStatus::Queued);
8376 assert!(!after.fresh_start);
8377 assert!(after.action_applied(&q.id));
8378 let pin = after.resume_override.clone().unwrap();
8379 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
8380 assert!(pin.forced);
8381
8382 let mut again = queue.get(&t.id).unwrap();
8384 again.hold_machine(Some("later".into()));
8385 queue.put(&mut again).unwrap();
8386 apply_choice_actions(&queue, &questions, &home);
8387 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8388 }
8389
8390 #[test]
8391 fn a_delivered_answer_is_still_acted_on_exactly_once() {
8392 let dir = tempfile::tempdir().unwrap();
8393 let queue = Queue::at(dir.path().join("queue"));
8394 let questions = Questions::at(dir.path().join("questions"));
8395 let home = dir.path().join("home");
8396 let mut state = run_state(RunStatus::Blocked);
8397 state.id = "20260101-000000-act2".to_owned();
8398 state.save_under(&home).unwrap();
8399
8400 let mut t = held_task_with(&state.id);
8401 queue.put(&mut t).unwrap();
8402 let mut q = action_question(&state.id, resume_action(&state.id));
8403 q.answer_delivered = true;
8404 questions.put(&mut q).unwrap();
8405
8406 apply_choice_actions(&queue, &questions, &home);
8409 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8410 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
8411
8412 let mut again = queue.get(&t.id).unwrap();
8414 again.hold_machine(Some("later".into()));
8415 queue.put(&mut again).unwrap();
8416 apply_choice_actions(&queue, &questions, &home);
8417 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8418 }
8419
8420 #[test]
8421 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
8422 let dir = tempfile::tempdir().unwrap();
8423 let queue = Queue::at(dir.path().join("queue"));
8424 let questions = Questions::at(dir.path().join("questions"));
8425 let home = dir.path().join("home");
8426 let mut state = run_state(RunStatus::Blocked);
8427 state.id = "20260101-000000-act3".to_owned();
8428 state.save_under(&home).unwrap();
8429 let mut t = held_task_with(&state.id);
8430 queue.put(&mut t).unwrap();
8431 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
8432 questions.put(&mut q).unwrap();
8433
8434 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
8435 apply_choice_actions(&queue, &questions, &home);
8436 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8437
8438 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
8439 apply_choice_actions(&queue, &questions, &home);
8440 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8441 }
8442
8443 #[test]
8444 fn action_standing_tells_the_reasons_apart() {
8445 let mut t = held_task_with("r1");
8446 let q = action_question("r1", ask::ChoiceAction::Requeue);
8447 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
8448 let mut plain = q.clone();
8449 plain.actions.clear();
8450 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
8451
8452 t.mark_action_applied(&q.id);
8454 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
8455
8456 let mut t = held_task_with("r1");
8458 t.start("r2".to_owned());
8459 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
8460 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
8462 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8463 t.status = TaskStatus::Blocked;
8464 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8465
8466 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
8468 c.node = crate::conduct::NODE.to_owned();
8469 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
8470 assert!(!ActionStanding::Busy.daemon_owns());
8471 }
8472
8473 #[test]
8474 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
8475 let dir = tempfile::tempdir().unwrap();
8476 let queue = Queue::at(dir.path().join("queue"));
8477 let questions = Questions::at(dir.path().join("questions"));
8478 let home = dir.path().join("home");
8479 let mut state = run_state(RunStatus::Blocked);
8480 state.id = "20260101-000000-act4".to_owned();
8481 state.save_under(&home).unwrap();
8482 let mut t = held_task_with(&state.id);
8483 t.status = TaskStatus::Running;
8484 queue.put(&mut t).unwrap();
8485 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
8486 q.cwd = Some(dir.path().display().to_string());
8487 questions.put(&mut q).unwrap();
8488
8489 let running = queue.get(&t.id).unwrap();
8492 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
8493 assert!(matches!(
8494 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
8495 crate::waiter::Action::Deliver(_)
8496 ));
8497 apply_choice_actions(&queue, &questions, &home);
8499 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8500 let mut back = queue.get(&t.id).unwrap();
8501 back.hold_machine(Some("later".into()));
8502 queue.put(&mut back).unwrap();
8503 apply_choice_actions(&queue, &questions, &home);
8504 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
8505 let mut again = queue.get(&t.id).unwrap();
8506 again.hold_machine(Some("again".into()));
8507 queue.put(&mut again).unwrap();
8508 apply_choice_actions(&queue, &questions, &home);
8509 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8510 }
8511}