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 {
2499 let talks = crate::talk::Talks::at(home.join("talks"));
2500 crate::chat_notify::sweep(queue, &talks, home);
2501 crate::chat_watch::sweep(home, &talks);
2502 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2503 }
2504
2505 let finished: Vec<Task> = finished_tasks(queue)
2511 .into_iter()
2512 .filter(|task| !stalled_ids.contains(&task.id))
2513 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2517 .collect();
2518 let queued = queued_tasks(queue);
2519 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2523 && conductor.worth_a_look(queue, &stalled, &finished)
2524 {
2525 match prepare(&opts.repo, opts) {
2526 Ok(cfg) => {
2527 conductor
2528 .maybe_run(
2529 &cfg,
2530 &opts.repo,
2531 queue,
2532 &questions,
2533 home,
2534 &queued,
2535 &stalled,
2536 &finished,
2537 opts.max_attempts,
2538 )
2539 .await;
2540 }
2541 Err(e) => {
2542 tracing::warn!("conductor: no config: {e:#}");
2543 notices::raise(Notice::warn(
2544 "loop:no-config",
2545 "The loop could not read this repository's config, so held tasks are not being triaged.",
2546 ));
2547 }
2548 }
2549 }
2550
2551 let candidates: Vec<Task> = runnable(queue)
2552 .into_iter()
2553 .filter(|t| !opts.once || !attempted.contains(&t.id))
2554 .collect();
2555
2556 let in_flight: Vec<String> = lock(status)
2561 .current
2562 .iter()
2563 .map(|c| c.task.clone())
2564 .collect();
2565 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2566
2567 interrupt =
2568 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2569 if let Interrupt::Parking {
2570 parked,
2571 interrupt_task,
2572 } = &interrupt
2573 {
2574 let reason = format!(
2575 "task {} asked to run first",
2576 crate::run::short_of(interrupt_task)
2577 );
2578 for id in parked {
2579 if let Some(pause) = interrupt_pauses.get(id) {
2580 pause.park_because(reason.clone());
2581 }
2582 }
2583 }
2584 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2585
2586 let cooling_down =
2587 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2588
2589 let mut started_any = false;
2590 for candidate in candidates {
2591 if stop.stopped() {
2592 break;
2593 }
2594
2595 let resume = land_resume_state(&candidate);
2596 if resume == LandResume::StillWaiting {
2597 continue;
2598 }
2599 let priority = resume == LandResume::Ready;
2600
2601 if !priority && cooling_down {
2602 continue;
2603 }
2604 let permit = match permit_kind(priority, candidate.urgent) {
2605 PermitKind::None => None,
2606 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2607 Ok(p) => Some(p),
2608 Err(_) => continue,
2614 },
2615 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2616 Ok(p) => Some(p),
2617 Err(_) => continue,
2621 },
2622 };
2623
2624 let Ok(claim) = queue.claim(&candidate.id) else {
2629 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2630 continue;
2631 };
2632 let mut task = match queue.get(&candidate.id) {
2635 Ok(t) if t.status.runnable() => t,
2636 Ok(_) => continue,
2637 Err(e) => {
2638 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2639 continue;
2640 }
2641 };
2642 let task_id = task.id.clone();
2643 attempted.push(task_id.clone());
2644 lock(status).idle = false;
2645 stop.enter();
2648 started_any = true;
2649
2650 let run_pause = crate::graph::Pause::new();
2654 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2655
2656 let opts = opts.clone();
2657 let queue = queue.clone();
2658 let status = Arc::clone(status);
2659 let stop = stop.clone();
2660 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2661 inflight.spawn(async move {
2662 let _claim = claim;
2666 let _permit = permit;
2667 let _inflight = InFlightGuard {
2669 status: &status,
2670 stop: &stop,
2671 task_id: &task_id,
2672 };
2673 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2674 lock(&status).completed += 1;
2675 let now = Timestamp::now();
2681 if let Some(until) = cooldown_until("a, now) {
2682 let wait = until.as_second() - now.as_second();
2683 *lock("a_cooldown_until) = Some(until);
2684 let hint = quota
2685 .iter()
2686 .find(|q| q.reset.is_some())
2687 .and_then(|q| q.reset.as_deref());
2688 match hint {
2689 Some(h) => tracing::warn!(
2690 "quota hit; waiting {wait}s before taking another ordinary task \
2691 (CLI reported reset: {h})"
2692 ),
2693 None => tracing::warn!(
2694 "quota hit; waiting {wait}s before taking another ordinary task \
2695 (no reset hint reported)"
2696 ),
2697 }
2698 }
2699 });
2700 }
2701
2702 if started_any {
2703 continue;
2704 }
2705
2706 if stop.busy_now() {
2707 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2712 continue;
2713 }
2714
2715 lock(status).idle = true;
2717 if opts.once {
2718 janitor(&opts.repo, opts, home, worktrees_root).await;
2722 resweep_superseded_attempts(queue, home);
2723 triage_held(queue, home, opts).await;
2724 break;
2725 }
2726 stop.idle(opts.poll).await;
2727 if stop.stopped() {
2728 continue;
2729 }
2730 janitor(&opts.repo, opts, home, worktrees_root).await;
2736 resweep_superseded_attempts(queue, home);
2737 triage_held(queue, home, opts).await;
2738 }
2739
2740 while let Some(result) = inflight.join_next().await {
2745 if let Err(e) = result {
2746 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2747 notices::raise(Notice::error(
2748 "loop:attempt",
2749 "A queued attempt ended abnormally; check the task it was running.",
2750 ));
2751 }
2752 }
2753 Ok(())
2754}
2755
2756async fn attempt(
2762 opts: &Opts,
2763 queue: &Queue,
2764 status: &Arc<Mutex<Status>>,
2765 stop: &Stop,
2766 interrupt_pause: crate::graph::Pause,
2767 task: &mut Task,
2768) -> Vec<QuotaLoss> {
2769 let repo = repo_for(task, &opts.repo);
2770 tracing::info!(
2771 "task {} — {} (repo {})",
2772 task.short(),
2773 task.title,
2774 repo.display()
2775 );
2776
2777 let explicit = match &task.overrides {
2781 Some(o) => o.config.as_deref(),
2782 None => opts.config.as_deref(),
2783 };
2784 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2785 let reason = format!("[config] {e:#}");
2786 task.last_error = Some(reason.clone());
2787 task.hold_machine(Some(reason.clone()));
2788 record(queue, task);
2789 tracing::warn!("holding {}: {reason}", task.short());
2790 return Vec::new();
2791 }
2792 let mut config = match prepare_for(&repo, opts, task) {
2793 Ok(c) => c,
2794 Err(e) => {
2795 task.attempts += 1;
2799 task.fail(format!("config: {e:#}"), opts.max_attempts);
2800 record(queue, task);
2801 return Vec::new();
2802 }
2803 };
2804 apply_solo(&mut config, task);
2805 let p = phrases(&config.graph.language);
2806 let start_failed = p.could_not_start;
2807
2808 if let Some(reason) = disk_gate(&repo, &config) {
2816 task.last_error = Some(reason.clone());
2817 task.hold_machine(Some(reason.clone()));
2818 record(queue, task);
2819 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2820 notices::raise(
2823 Notice::warn(
2824 &format!("disk:{}", repo.display()),
2825 "A task was held for want of free disk space; free some, then release it from the queue.",
2826 )
2827 .link(Link::Task {
2828 id: task.id.clone(),
2829 }),
2830 );
2831 return Vec::new();
2832 }
2833
2834 let unfinished = (!task.fresh_start)
2854 .then(|| unfinished_run(&task.runs, task.short()))
2855 .flatten();
2856 let review_branch = task.review_branch.take();
2862 let branch_exists = match &review_branch {
2863 Some(branch) => crate::git::branch_exists(&repo, branch)
2864 .await
2865 .unwrap_or(false),
2866 None => false,
2867 };
2868 let starter = match (&review_branch, &unfinished, &task.review_of) {
2872 (None, None, Some(branch)) => Starter::Review(branch.clone()),
2873 _ => choose_starter(
2874 review_branch.as_deref(),
2875 branch_exists,
2876 unfinished.as_deref(),
2877 ),
2878 };
2879 let attachments = match task_attachments(queue, task) {
2884 Ok(a) => a,
2885 Err(e) => {
2886 task.attempts += 1;
2887 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2888 record(queue, task);
2889 return Vec::new();
2890 }
2891 };
2892 let started = match &starter {
2893 Starter::Review(branch) => {
2894 tracing::info!(
2895 "task {} reopens `{branch}` as a review-only pass",
2896 task.short()
2897 );
2898 let takeover = crate::handover::Takeover {
2901 earlier: task.earlier_attempts().to_vec(),
2902 home: crate::run::home(),
2903 choice: take_divergence_answer(branch, &config.merge.remote, task),
2904 };
2905 Runner::review_taking_over(
2906 &repo,
2907 branch,
2908 config,
2909 Some(takeover),
2910 crate::run::Origin::queue(&task.id),
2911 )
2912 .await
2913 }
2914 Starter::Resume(id) => {
2915 tracing::info!("resuming run {id} rather than competing again");
2916 Runner::resume(id).map(|mut r| {
2917 if let Some(instruction) =
2918 prepare_instruction(&starter, Some(&r.state.instruction), task)
2919 {
2920 r.state.instruction = instruction;
2921 }
2922 r.state.attachments = attachments.clone();
2923 if let Some(mode) = task
2926 .overrides
2927 .as_ref()
2928 .and_then(|o| o.merge.as_deref())
2929 .and_then(|m| merge_mode(m).ok())
2930 {
2931 r.state.config.merge.mode = mode;
2932 }
2933 r
2934 })
2935 }
2936 Starter::Start => {
2937 if let Some(branch) = &review_branch {
2938 tracing::warn!(
2939 "conductor chose review for task {} but branch `{branch}` no longer \
2940 exists; requeuing as a fresh competition instead",
2941 task.short()
2942 );
2943 }
2944 let instruction = prepare_instruction(&starter, None, task)
2945 .unwrap_or_else(|| task.instruction.clone());
2946 Runner::start_naming(
2947 &repo,
2948 instruction,
2949 &task.title,
2950 config,
2951 crate::run::Origin::queue(&task.id),
2952 )
2953 .await
2954 .map(|mut r| {
2955 r.state.attachments = attachments.clone();
2956 r
2957 })
2958 }
2959 };
2960 let mut runner = match started {
2961 Ok(r) => r,
2962 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2966 let detail = match e.downcast_ref::<crate::handover::Refused>() {
2967 Some(r) => (p.handover_refused)(r),
2968 None => format!("{e:#}"),
2969 };
2970 let reason = format!("{start_failed}{detail}");
2971 task.last_error = Some(reason.clone());
2972 let branch = match &starter {
2975 Starter::Review(branch) => Some(branch.clone()),
2976 _ => None,
2977 };
2978 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
2982 record(queue, task);
2983 tracing::warn!(
2984 "holding {} for a branch it cannot take over: {e:#}",
2985 task.short()
2986 );
2987 return Vec::new();
2988 }
2989 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
2994 let d = e
2995 .downcast_ref::<crate::reconcile::Diverged>()
2996 .expect("checked by the guard");
2997 let mut q = ask::Question::new(
2998 task.id.clone(),
2999 crate::reconcile::NODE.to_owned(),
3000 crate::reconcile::SEAT.to_owned(),
3001 d.summary(),
3002 d.detail(),
3003 d.choices(),
3004 );
3005 match Questions::open().put(&mut q) {
3006 Ok(()) => {
3007 task.last_error = Some(format!("{e:#}"));
3008 task.review_branch = Some(d.branch.clone());
3011 task.block(vec![q.id.clone()], Some(d.summary()));
3012 }
3013 Err(put) => {
3014 tracing::warn!("could not file the divergence question: {put:#}");
3015 task.attempts += 1;
3016 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3017 }
3018 }
3019 record(queue, task);
3020 return Vec::new();
3021 }
3022 Err(e) => {
3023 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3029 && let Starter::Review(branch) = &starter
3030 {
3031 task.review_branch = Some(branch.clone());
3032 task.last_error = Some(format!("{start_failed}{e:#}"));
3033 task.status = crate::queue::TaskStatus::Failed;
3034 record(queue, task);
3035 return Vec::new();
3036 }
3037 task.attempts += 1;
3038 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3039 record(queue, task);
3040 return Vec::new();
3041 }
3042 };
3043 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3046 if runner.state.origin_chat.is_none() {
3047 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3048 }
3049 runner.on_pause(stop.pause());
3051 runner.watch_interrupt(interrupt_pause);
3055
3056 let run = runner.state.id.clone();
3059 task.start(run.clone());
3060 record(queue, task);
3061 lock(status).current.push(Current {
3062 task: task.id.clone(),
3063 run,
3064 });
3065
3066 let quota_before = runner.state.quota.clone();
3069 let result = runner.execute().await;
3070 finish_attempt(
3071 opts.max_attempts,
3072 queue,
3073 task,
3074 &runner.state,
3075 "a_before,
3076 result,
3077 )
3078}
3079
3080pub fn finish_attempt(
3085 max_attempts: usize,
3086 queue: &Queue,
3087 task: &mut Task,
3088 state: &RunState,
3089 quota_before: &[QuotaLoss],
3090 result: Result<()>,
3091) -> Vec<QuotaLoss> {
3092 let detail = match result {
3093 Ok(()) => describe(state),
3094 Err(e) => format!("{e:#}"),
3095 };
3096 let fresh = losses_this_attempt(quota_before, &state.quota);
3097 let verdict = Verdict {
3098 status: state.status,
3099 left_pr: state.pr.is_some(),
3102 quota_hit: !fresh.is_empty(),
3108 parked: state.parked,
3112 no_viable_candidates: state.viable().is_empty(),
3115 };
3116 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3117 if task.status == TaskStatus::Done {
3118 supersede_prior_runs(task, &crate::run::home());
3119 }
3120 record(queue, task);
3121 tracing::info!(
3122 "task {} is {} after run {} ({})",
3123 task.short(),
3124 task.status.as_str(),
3125 state.short(),
3126 label(state.status)
3127 );
3128 fresh
3129}
3130
3131pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3135 let waits_on_owner = withheld_text_wait(task).is_some();
3140 if task.status.runnable() && !waits_on_owner {
3141 let why = task.last_error.clone().map_or_else(
3142 || "the run did not finish".to_owned(),
3143 |e| format!("the run did not finish: {e}"),
3144 );
3145 task.hold_manual(Some(format!(
3146 "{why}. It was started by hand, so it is not retried \
3147 automatically; `magi task release` retries it."
3148 )));
3149 record(queue, task);
3150 }
3151}
3152
3153#[must_use]
3157pub fn loop_would_resume(run: &str) -> bool {
3158 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3159}
3160
3161#[must_use]
3171pub fn foreign_loop(
3172 reading: Option<&Reading>,
3173 now: Timestamp,
3174 own_pid: u32,
3175) -> Option<Option<u32>> {
3176 let reading = reading.filter(|r| r.running(now))?;
3177 match reading.pid {
3178 Some(pid) if pid == own_pid => None,
3179 pid => Some(pid),
3180 }
3181}
3182
3183pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3198 let status = Arc::new(Mutex::new(Status::new()));
3199 let stop = Stop::new();
3200 attempt(
3201 opts,
3202 queue,
3203 &status,
3204 &stop,
3205 crate::graph::Pause::new(),
3206 task,
3207 )
3208 .await;
3209 let mut resumes = 0;
3218 while resumes < MAX_WITHHELD_RESUMES {
3219 let Some(timeout) = withheld_text_wait(task) else {
3220 break;
3221 };
3222 eprintln!(
3223 "waiting for the owner's answer on a withheld pull request text \
3224 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3225 );
3226 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3229 let ready = loop {
3230 match land_resume_state(task) {
3231 LandResume::StillWaiting if std::time::Instant::now() < limit => {
3232 tokio::time::sleep(WITHHELD_POLL).await;
3233 }
3234 LandResume::Ready => break true,
3235 _ => break false,
3236 }
3237 };
3238 if !ready {
3239 break;
3240 }
3241 resumes += 1;
3242 attempt(
3243 opts,
3244 queue,
3245 &status,
3246 &stop,
3247 crate::graph::Pause::new(),
3248 task,
3249 )
3250 .await;
3251 }
3252 hold_if_runnable(queue, task);
3253}
3254
3255const MAX_WITHHELD_RESUMES: u32 = 3;
3258
3259const WITHHELD_POLL: Duration = Duration::from_secs(15);
3261
3262fn withheld_text_wait(task: &Task) -> Option<u64> {
3265 let id = task.runs.last()?;
3266 let s = RunState::load(id).ok()?;
3267 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3268 .then_some(s.config.graph.answer_timeout)
3269}
3270
3271fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3281 after
3282 .iter()
3283 .filter(|q| !before.contains(q))
3284 .cloned()
3285 .collect()
3286}
3287
3288fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3291 if quota.is_empty() {
3292 return None;
3293 }
3294 let with_hint = quota.iter().find(|q| q.reset.is_some());
3295 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3296 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3297 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3298 Some(
3299 now.checked_add(jiff::SignedDuration::from_secs(secs))
3300 .unwrap_or(Timestamp::MAX),
3301 )
3302}
3303
3304fn apply_solo(config: &mut Config, task: &Task) {
3314 if task.solo {
3315 config.graph.implementers = 1;
3316 }
3317}
3318
3319fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3324 let Some(o) = &task.overrides else {
3325 return prepare(repo, opts);
3326 };
3327 let own = Opts {
3331 config: o.config.clone(),
3332 merge: None,
3333 ..opts.clone()
3334 };
3335 let mut config = prepare(repo, &own)?;
3336 o.apply(&mut config);
3337 Ok(config)
3338}
3339
3340fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3342 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3343 if let Some(mode) = &opts.merge {
3344 config.merge.mode = merge_mode(mode)?;
3345 }
3346 Ok(config)
3347}
3348
3349async fn maybe_prune_cache_between_runs(
3380 repo: &Path,
3381 opts: &Opts,
3382 home: &Path,
3383 stop: &Stop,
3384 last_checked: &mut Option<Timestamp>,
3385 now: Timestamp,
3386) {
3387 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3388 return;
3389 }
3390 *last_checked = Some(now);
3391 let cfg = match prepare(repo, opts) {
3392 Ok(cfg) => cfg,
3393 Err(e) => {
3394 tracing::warn!("cache check: no config: {e:#}");
3395 return;
3396 }
3397 };
3398 match clean::prune_cache_if_over_limit(&cfg, home) {
3399 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3400 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3401 pruned.files,
3402 pruned.freed
3403 ),
3404 Ok(_) => {}
3405 Err(e) => {
3406 tracing::warn!("housekeep: prune cache: {e:#}");
3407 notices::raise_in(
3408 home,
3409 Notice::warn(
3410 "housekeep:cache",
3411 "Pruning the shared build cache failed; disk usage may keep growing.",
3412 ),
3413 );
3414 }
3415 }
3416}
3417
3418fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3422 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3423}
3424
3425async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3444 let cfg = match prepare(repo, opts) {
3445 Ok(cfg) => cfg,
3446 Err(e) => {
3447 tracing::warn!("housekeep: no config: {e:#}");
3448 return;
3449 }
3450 };
3451 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3460 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3461 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3466 let mut extra = Vec::new();
3467 if out.unreadable > 0 {
3468 extra.push(format!("{} unreadable", out.unreadable));
3469 }
3470 if out.orphaned_worktrees > 0 {
3471 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3472 }
3473 let detail = if extra.is_empty() {
3474 String::new()
3475 } else {
3476 format!(" ({})", extra.join(", "))
3477 };
3478 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3479 }
3480 if out.external_merges_recorded > 0 {
3481 tracing::info!(
3482 "housekeep: recorded {} run(s) as merged externally",
3483 out.external_merges_recorded
3484 );
3485 }
3486 if out.stale_pr_states_repaired > 0 {
3487 tracing::info!(
3488 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3489 out.stale_pr_states_repaired
3490 );
3491 }
3492 if out.cache_files > 0 {
3493 tracing::info!(
3494 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3495 out.cache_files,
3496 out.cache_freed
3497 );
3498 }
3499 if out.questions_abandoned > 0 {
3500 tracing::info!(
3501 "housekeep: abandoned {} question(s) left open by a finished run",
3502 out.questions_abandoned
3503 );
3504 }
3505}
3506
3507async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3516 let questions = Questions::at(home.join("questions"));
3517 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3518 if report.is_empty() {
3519 return;
3520 }
3521 if !report.quarantined.is_empty() {
3522 tracing::info!(
3523 "triage: held {} blocked task(s) whose blocked-on task or \
3524 question no longer exists: {}",
3525 report.quarantined.len(),
3526 report.quarantined.join(", ")
3527 );
3528 }
3529 if !report.resumed.is_empty() {
3530 tracing::info!(
3531 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3532 report.resumed.len(),
3533 report.resumed.join(", ")
3534 );
3535 }
3536 if !report.asked.is_empty() {
3537 tracing::info!(
3538 "triage: asked about {} held task(s): {}",
3539 report.asked.len(),
3540 report.asked.join(", ")
3541 );
3542 }
3543 if !report.answered.is_empty() {
3544 tracing::info!(
3545 "triage: applied {} operator answer(s): {}",
3546 report.answered.len(),
3547 report.answered.join(", ")
3548 );
3549 }
3550}
3551
3552fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3559 disk_gate_with(repo, config, crate::disk::free_bytes)
3560}
3561
3562fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3566 repo: &Path,
3567 config: &Config,
3568 free_bytes: F,
3569) -> Option<String> {
3570 let min = config.disk.min_free_bytes;
3571 if min == 0 {
3572 return None;
3573 }
3574 match free_bytes(repo) {
3575 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3576 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3577 }
3578}
3579
3580const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3587
3588const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3592
3593fn quota_wait(
3602 reset_at: Option<Timestamp>,
3603 now: Timestamp,
3604 fallback: Duration,
3605 cap: Duration,
3606) -> Duration {
3607 match reset_at {
3608 Some(at) if at > now => {
3609 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3610 Duration::from_secs(secs).min(cap)
3611 }
3612 _ => fallback,
3613 }
3614}
3615
3616fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3630 parse_reset_hint_zoned(text, now)
3631 .or_else(|| parse_reset_hint_dated(text))
3632 .or_else(|| parse_reset_hint_relative(text, recorded))
3633}
3634
3635fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3639 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3640 let mut rest = rest.trim();
3641 if rest.is_empty() {
3642 return None;
3643 }
3644 let mut total: i64 = 0;
3645 let mut matched = false;
3646 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3647 if let Some((digits, tail)) = rest.split_once(unit)
3648 && !digits.is_empty()
3649 && digits.bytes().all(|b| b.is_ascii_digit())
3650 {
3651 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3652 rest = tail;
3653 matched = true;
3654 }
3655 }
3656 if !rest.is_empty() || !matched {
3657 return None;
3658 }
3659 recorded
3660 .checked_add(jiff::SignedDuration::from_secs(total))
3661 .ok()
3662}
3663
3664fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3668 let clock = clock.trim().to_lowercase();
3669 let (digits, pm) = clock
3670 .strip_suffix("am")
3671 .map(|d| (d, false))
3672 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3673 let (h, m) = digits.trim().split_once(':')?;
3674 let mut hour: i8 = h.trim().parse().ok()?;
3675 let minute: i8 = m.trim().parse().ok()?;
3676 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3677 return None;
3678 }
3679 if pm && hour != 12 {
3680 hour += 12;
3681 } else if !pm && hour == 12 {
3682 hour = 0;
3683 }
3684 Some((hour, minute))
3685}
3686
3687fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3692 let open = text.find('(')?;
3693 let close = text.rfind(')')?;
3694 if close <= open {
3695 return None;
3696 }
3697 let zone = text[open + 1..close].trim();
3698 let (hour, minute) = parse_12h_clock(&text[..open])?;
3699 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3700 let candidate = now
3701 .to_zoned(tz)
3702 .with()
3703 .hour(hour)
3704 .minute(minute)
3705 .second(0)
3706 .millisecond(0)
3707 .microsecond(0)
3708 .nanosecond(0)
3709 .build()
3710 .ok()?;
3711 let mut at = candidate.timestamp();
3712 if at <= now {
3713 at += jiff::SignedDuration::from_hours(24);
3714 }
3715 Some(at)
3716}
3717
3718fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3727 let words: Vec<&str> = text.split_whitespace().collect();
3728 if words.len() < 5 {
3729 return None;
3730 }
3731 (0..=words.len() - 5)
3732 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3733}
3734
3735fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3741 if trailing.is_some_and(|next| next.starts_with('(')) {
3742 return None;
3743 }
3744 let month = month_number(window[0])?;
3745 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3746 let day_digits = ["st", "nd", "rd", "th"]
3747 .iter()
3748 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3749 let day: i8 = day_digits.parse().ok()?;
3750 let year_token = window[2];
3751 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3752 return None;
3753 }
3754 let year: i16 = year_token.parse().ok()?;
3755 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3759 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3760 let date = jiff::civil::Date::new(year, month, day).ok()?;
3761 let candidate = date
3762 .at(hour, minute, 0, 0)
3763 .to_zoned(jiff::tz::TimeZone::UTC)
3764 .ok()?;
3765 Some(candidate.timestamp())
3766}
3767
3768fn month_number(name: &str) -> Option<i8> {
3771 const NAMES: [&str; 12] = [
3772 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3773 ];
3774 let lower = name.to_lowercase();
3775 NAMES
3776 .iter()
3777 .position(|n| *n == lower.as_str())
3778 .map(|i| i as i8 + 1)
3779}
3780
3781fn exhausted_review_budget(state: &RunState) -> bool {
3793 state.status == RunStatus::Blocked
3796 && !state.pr_publication_pending
3797 && state.reviews.len() >= state.config.graph.review_rounds
3798}
3799
3800fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3837 unfinished_run_with(runs, short, RunState::load)
3838}
3839
3840fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3843where
3844 F: FnOnce(&str) -> Result<RunState>,
3845{
3846 let id = runs.last()?;
3847 match load(id) {
3848 Ok(s)
3853 if s.status.resumable()
3854 && !s.released()
3855 && !exhausted_review_budget(&s)
3856 && s.liveness(false) != crate::run::Liveness::Live =>
3857 {
3858 Some(id.clone())
3859 }
3860 Ok(_) => None,
3861 Err(e) => {
3862 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3863 None
3864 }
3865 }
3866}
3867
3868fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3876where
3877 F: FnOnce(&str) -> Result<RunState>,
3878{
3879 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
3881 || task.fresh_start
3882 || task.review_branch.is_some()
3883 {
3884 return false;
3885 }
3886 let Some(id) = task.runs.last() else {
3887 return false;
3888 };
3889 load(id).is_ok_and(|s| {
3890 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3891 })
3892}
3893
3894#[derive(Debug, Clone, PartialEq, Eq)]
3897enum Starter {
3898 Review(String),
3901 Resume(String),
3903 Start,
3905}
3906
3907fn take_divergence_answer(
3911 branch: &str,
3912 remote: &str,
3913 task: &mut Task,
3914) -> Option<crate::reconcile::Choice> {
3915 let summary = crate::reconcile::summary_for(branch, remote);
3916 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3917 (a.question == summary)
3918 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3919 .flatten()
3920 .map(|c| (i, c))
3921 })?;
3922 task.answers.remove(idx);
3923 Some(choice)
3924}
3925
3926fn choose_starter(
3938 review_branch: Option<&str>,
3939 branch_exists: bool,
3940 unfinished: Option<&str>,
3941) -> Starter {
3942 match review_branch {
3943 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3944 Some(_) => Starter::Start,
3945 None => match unfinished {
3946 Some(id) => Starter::Resume(id.to_owned()),
3947 None => Starter::Start,
3948 },
3949 }
3950}
3951
3952fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3955 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3956 return fallback.to_path_buf();
3957 }
3958 task.repo.clone()
3959}
3960
3961const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3965
3966fn answers_block(task: &Task, count: usize) -> String {
3968 let mut s = ANSWERS_HEADER.to_owned();
3969 for a in &task.answers[..count] {
3970 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3971 }
3972 s
3973}
3974
3975fn append_answers(base: &str, task: &Task) -> String {
3978 if task.answers.is_empty() {
3979 return base.to_owned();
3980 }
3981 let mut s = base.to_owned();
3982 s.push_str(&answers_block(task, task.answers.len()));
3983 s
3984}
3985
3986fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3990 for count in (1..=task.answers.len()).rev() {
3991 let block = answers_block(task, count);
3992 if let Some(base) = instruction.strip_suffix(&block) {
3993 return base;
3994 }
3995 }
3996 instruction
3997}
3998
3999fn instruction_for(task: &Task) -> String {
4007 append_answers(&task.instruction, task)
4008}
4009
4010fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4022 append_answers(strip_answers_block(old_instruction, task), task)
4023}
4024
4025fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
4027 let paths = queue.attachment_paths(task);
4028 for (name, path) in task.attachments.iter().zip(&paths) {
4029 if !path.is_file() {
4030 bail!(
4031 "attachment `{name}` is recorded on the task but {} is missing",
4032 path.display()
4033 );
4034 }
4035 }
4036 Ok(paths)
4037}
4038
4039fn prepare_instruction(
4050 starter: &Starter,
4051 old_instruction: Option<&str>,
4052 task: &Task,
4053) -> Option<String> {
4054 match starter {
4055 Starter::Start => Some(instruction_for(task)),
4056 Starter::Resume(_) => Some(resumed_instruction(
4057 old_instruction.expect("a resumed run always has a prior instruction"),
4058 task,
4059 )),
4060 Starter::Review(_) => None,
4061 }
4062}
4063
4064fn record(queue: &Queue, task: &mut Task) {
4068 if let Err(e) = queue.put(task) {
4069 tracing::error!("could not record task {}: {e:#}", task.short());
4070 let notice = Notice::error(
4071 "loop:record",
4072 "The loop could not save a task's state; check the disk.",
4073 )
4074 .link(Link::Task {
4075 id: task.id.clone(),
4076 });
4077 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4079 Some(home) => notices::raise_in(home, notice),
4080 None => notices::raise(notice),
4081 }
4082 }
4083}
4084
4085fn runnable(queue: &Queue) -> Vec<Task> {
4091 let mut tasks: Vec<Task> = queue
4092 .list()
4093 .into_iter()
4094 .filter(|t| t.status.runnable())
4095 .collect();
4096 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4097 tasks
4098}
4099
4100fn describe(state: &RunState) -> String {
4114 let p = phrases(&state.config.graph.language);
4115 let mut detail = if state.status == RunStatus::Stalled {
4116 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4117 seats.sort_unstable();
4118 seats.dedup();
4119 if seats.is_empty() {
4120 p.quorum_lost.to_owned()
4121 } else {
4122 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4123 }
4124 } else {
4125 format!("{}{}", p.run_ended, state.status.display_label())
4126 };
4127 if let Some(last) = state.events.last() {
4128 let unanswered = state
4132 .reviews
4133 .last()
4134 .filter(|r| {
4135 state.status == RunStatus::Blocked
4136 && last.node == "review"
4137 && r.incomplete()
4138 && r.blocking == 0
4139 && r.round == state.config.graph.review_rounds
4140 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4141 })
4142 .map(|r| (r.expected - r.answered, r.round));
4143 match unanswered {
4144 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4145 detail.push_str(&format!(
4146 " ({}: {})",
4147 last.node,
4148 (p.reviewers_never_answered)(missing, rounds)
4149 ));
4150 }
4151 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4152 }
4153 }
4154 detail.push_str(&format!(" [run {}]", state.id));
4155 detail
4156}
4157
4158const DIAGNOSTIC_MAX: usize = 4_000;
4164
4165const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4170
4171fn diagnostic(state: &RunState) -> Option<String> {
4185 let mut parts: Vec<String> = Vec::new();
4186
4187 for o in state.gate.iter().filter(|o| !o.ok()) {
4189 parts.push(format!(
4190 "gate `{}` failed ({:?}):\n{}",
4191 o.command,
4192 o.code,
4193 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4194 ));
4195 }
4196
4197 if let Some(last) = state
4200 .events
4201 .iter()
4202 .rev()
4203 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4204 {
4205 parts.push(last.message.clone());
4206 }
4207
4208 if state.viable().is_empty() {
4215 for c in &state.candidates {
4216 if let Some(evidence) = &c.verified_noop {
4217 parts.push(format!(
4218 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4219 c.label
4220 ));
4221 } else if !c.summary.trim().is_empty() {
4222 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4223 } else if let Some(why) = &c.failed {
4224 parts.push(format!("candidate {}: {why}", c.label));
4225 }
4226 }
4227 }
4228
4229 if parts.is_empty() {
4230 return None;
4231 }
4232 Some(crate::run::tail(
4237 &parts.join("\n\n"),
4238 DIAGNOSTIC_MAX.saturating_sub(100),
4239 ))
4240}
4241
4242fn label(status: RunStatus) -> &'static str {
4250 status.as_str()
4251}
4252
4253pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4255 match mode {
4256 "none" => Ok(MergeMode::None),
4257 "local" => Ok(MergeMode::Local),
4258 "pr" => Ok(MergeMode::Pr),
4259 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4260 }
4261}
4262
4263fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4268 mutex
4269 .lock()
4270 .unwrap_or_else(std::sync::PoisonError::into_inner)
4271}
4272
4273#[cfg(test)]
4274mod tests {
4275 use super::*;
4276 use crate::queue::{Source, TaskStatus};
4277 use crate::run::{Candidate, CommandOutcome};
4278 use pretty_assertions::assert_eq;
4279
4280 fn task() -> Task {
4281 Task::new(
4282 "add retries".to_owned(),
4283 "add retries".to_owned(),
4284 PathBuf::from("/repo"),
4285 Source::Human,
4286 )
4287 }
4288
4289 #[test]
4290 fn record_failure_notice_links_the_task() {
4291 let dir = tempfile::tempdir().unwrap();
4292 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
4295 let queue = Queue::at(dir.path().join("queue"));
4296 let mut t = interrupt_task("rec-fail-1");
4297 record(&queue, &mut t);
4298
4299 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
4300 assert_eq!(found.len(), 1);
4301 assert_eq!(found[0].key, "loop:record");
4302 assert_eq!(
4303 found[0].link,
4304 Some(Link::Task {
4305 id: "rec-fail-1".to_owned()
4306 })
4307 );
4308 }
4309
4310 fn interrupt_task(id: &str) -> Task {
4313 let mut t = task();
4314 t.id = id.to_owned();
4315 t.interrupt = true;
4316 t
4317 }
4318
4319 fn task_with_id(id: &str) -> Task {
4321 let mut t = task();
4322 t.id = id.to_owned();
4323 t
4324 }
4325
4326 fn urgent_task(id: &str) -> Task {
4328 let mut t = task();
4329 t.id = id.to_owned();
4330 t.urgent = true;
4331 t
4332 }
4333
4334 #[test]
4339 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4340 assert_eq!(permit_kind(true, false), PermitKind::None);
4341 assert_eq!(permit_kind(true, true), PermitKind::None);
4342 }
4343
4344 #[test]
4349 fn permit_kind_separates_urgent_from_ordinary() {
4350 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4351 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4352 }
4353
4354 #[test]
4361 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4362 let cfg = Config::default();
4363 let repo = Path::new("/any/repo/path");
4364
4365 let reason =
4366 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4367 assert!(reason.contains("1024"), "{reason}");
4368 assert!(
4369 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4370 "{reason}"
4371 );
4372
4373 assert_eq!(
4374 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4375 None,
4376 "exactly at the floor is open"
4377 );
4378 assert_eq!(
4379 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4380 None,
4381 "comfortably above the floor is open"
4382 );
4383 }
4384
4385 #[test]
4386 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4387 let mut cfg = Config::default();
4388 cfg.disk.min_free_bytes = 0;
4389 let repo = Path::new("/any/repo/path");
4390 assert_eq!(
4391 disk_gate_with(repo, &cfg, |_| Ok(0)),
4392 None,
4393 "a zero floor never measures at all"
4394 );
4395 }
4396
4397 #[test]
4398 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
4399 let cfg = Config::default();
4400 let repo = Path::new("/any/repo/path");
4401 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
4402 .expect("a measurement failure must close the gate, not open it");
4403 assert!(reason.contains("could not measure"), "{reason}");
4404 }
4405
4406 #[test]
4407 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
4408 let ordinary = task();
4409 let next = advance_interrupt(
4410 Interrupt::Idle,
4411 std::slice::from_ref(&ordinary.id),
4412 std::slice::from_ref(&ordinary),
4413 );
4414 assert_eq!(next, Interrupt::Idle);
4415 }
4416
4417 #[test]
4418 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
4419 let marked = interrupt_task("marked");
4422 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4423 assert_eq!(next, Interrupt::Idle);
4424 }
4425
4426 #[test]
4427 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
4428 let marked = interrupt_task("marked");
4429 let next = advance_interrupt(
4430 Interrupt::Idle,
4431 &["running".to_owned()],
4432 std::slice::from_ref(&marked),
4433 );
4434 assert_eq!(
4435 next,
4436 Interrupt::Parking {
4437 parked: vec!["running".to_owned()],
4438 interrupt_task: "marked".to_owned(),
4439 }
4440 );
4441 }
4442
4443 #[test]
4452 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
4453 let marked = interrupt_task("marked");
4454
4455 let two = advance_interrupt(
4456 Interrupt::Idle,
4457 &["a".to_owned(), "b".to_owned()],
4458 std::slice::from_ref(&marked),
4459 );
4460 assert_eq!(two, Interrupt::Idle);
4461
4462 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4463 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
4464 }
4465
4466 #[test]
4467 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
4468 let state = Interrupt::Parking {
4469 parked: vec!["running".to_owned()],
4470 interrupt_task: "marked".to_owned(),
4471 };
4472 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
4474 assert_eq!(still_going, state);
4475
4476 let stopped_but_not_yet_dispatched =
4480 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
4481 assert_eq!(stopped_but_not_yet_dispatched, state);
4482
4483 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
4485 assert_eq!(
4486 dispatched,
4487 Interrupt::Running {
4488 parked: vec!["running".to_owned()],
4489 interrupt_task: "marked".to_owned(),
4490 }
4491 );
4492 }
4493
4494 #[test]
4495 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
4496 let state = Interrupt::Running {
4497 parked: vec!["running".to_owned()],
4498 interrupt_task: "marked".to_owned(),
4499 };
4500 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
4501 assert_eq!(still_running, state);
4502
4503 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
4510 assert_eq!(
4511 ended,
4512 Interrupt::Resuming {
4513 parked: vec!["running".to_owned()]
4514 }
4515 );
4516 }
4517
4518 #[test]
4519 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
4520 let state = Interrupt::Resuming {
4521 parked: vec!["running".to_owned()],
4522 };
4523 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
4524 assert_eq!(still_waiting, state);
4525
4526 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
4527 assert_eq!(dispatched, Interrupt::Idle);
4528 }
4529
4530 #[test]
4536 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
4537 {
4538 let state = Interrupt::Parking {
4539 parked: vec!["running".to_owned()],
4540 interrupt_task: "marked".to_owned(),
4541 };
4542 let next = advance_interrupt(state, &[], &[]);
4545 assert_eq!(
4546 next,
4547 Interrupt::Resuming {
4548 parked: vec!["running".to_owned()]
4549 },
4550 "abandoning the interrupt must not abandon the resume it owes"
4551 );
4552 }
4553
4554 #[test]
4557 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
4558 let state = Interrupt::Resuming {
4559 parked: vec!["running".to_owned()],
4560 };
4561 let next = advance_interrupt(state, &[], &[]);
4562 assert_eq!(
4563 next,
4564 Interrupt::Idle,
4565 "nothing is left to wait for; the loop must not stay wedged"
4566 );
4567 }
4568
4569 #[test]
4570 fn disabled_by_config_the_sequence_can_never_leave_idle() {
4571 let marked = interrupt_task("marked");
4572 let next = advance_interrupt_tick(
4573 false,
4574 Interrupt::Idle,
4575 &["running".to_owned()],
4576 std::slice::from_ref(&marked),
4577 );
4578 assert_eq!(
4579 next,
4580 Interrupt::Idle,
4581 "an unmarked, unconfigured daemon must behave exactly as before"
4582 );
4583 }
4584
4585 #[test]
4586 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
4587 let state = Interrupt::Parking {
4588 parked: vec!["running".to_owned()],
4589 interrupt_task: "marked".to_owned(),
4590 };
4591 let candidates = vec![interrupt_task("marked"), task()];
4592 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4593 assert!(
4594 allowed.is_empty(),
4595 "nothing may dispatch - not even the interrupt task itself - \
4596 until the parked run has actually stopped"
4597 );
4598 }
4599
4600 #[test]
4614 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
4615 for state in [
4616 Interrupt::Parking {
4617 parked: vec!["running".to_owned()],
4618 interrupt_task: "marked".to_owned(),
4619 },
4620 Interrupt::Running {
4621 parked: vec!["running".to_owned()],
4622 interrupt_task: "marked".to_owned(),
4623 },
4624 Interrupt::Resuming {
4625 parked: vec!["running".to_owned()],
4626 },
4627 ] {
4628 let candidates = vec![
4629 interrupt_task("marked"),
4630 urgent_task("hot"),
4631 task_with_id("ordinary"),
4632 ];
4633 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4634 assert!(
4635 !allowed.iter().any(|t| t.id == "hot"),
4636 "an urgent candidate must wait out the same gate as anything \
4637 else while the run it would run alongside has not actually \
4638 left flight, for state {state:?}: {allowed:?}"
4639 );
4640 }
4641 }
4642
4643 #[test]
4649 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
4650 let state = Interrupt::Resuming {
4651 parked: vec!["hot".to_owned()],
4652 };
4653 let candidates = vec![urgent_task("hot"), task()];
4654 let allowed = interrupt_gate(&state, &[], candidates);
4655 assert_eq!(
4656 allowed.iter().filter(|t| t.id == "hot").count(),
4657 1,
4658 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
4659 );
4660 }
4661
4662 #[test]
4663 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
4664 let state = Interrupt::Parking {
4665 parked: vec!["running".to_owned()],
4666 interrupt_task: "marked".to_owned(),
4667 };
4668 let other = task();
4669 let candidates = vec![interrupt_task("marked"), other.clone()];
4670 let allowed = interrupt_gate(&state, &[], candidates);
4671 assert_eq!(allowed.len(), 1);
4672 assert_eq!(allowed[0].id, "marked");
4673 }
4674
4675 #[test]
4676 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4677 let state = Interrupt::Running {
4678 parked: vec!["running".to_owned()],
4679 interrupt_task: "marked".to_owned(),
4680 };
4681 let candidates = vec![task(), task()];
4682 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4683 assert!(allowed.is_empty());
4684 }
4685
4686 #[test]
4693 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4694 let state = Interrupt::Resuming {
4695 parked: vec!["a".to_owned(), "c".to_owned()],
4696 };
4697 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4698 let allowed = interrupt_gate(&state, &[], candidates);
4699 assert_eq!(
4700 allowed.len(),
4701 1,
4702 "at most one candidate may be offered while resuming: {allowed:?}"
4703 );
4704 assert_eq!(allowed[0].id, "a");
4705 }
4706
4707 #[test]
4708 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4709 let state = Interrupt::Resuming {
4710 parked: vec!["a".to_owned()],
4711 };
4712 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4713 assert!(allowed.is_empty());
4714 }
4715
4716 #[test]
4722 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4723 let running = task(); let marked = interrupt_task("marked");
4725
4726 let mut state = Interrupt::Idle;
4727 let in_flight = vec![running.id.clone()];
4729 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4730 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4731 assert!(gated.is_empty(), "still waiting on `running` to park");
4732
4733 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4735 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4736 assert_eq!(
4737 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4738 vec!["marked"],
4739 "only the interrupt task may be offered to the dispatcher now"
4740 );
4741
4742 state = advance_interrupt_tick(
4744 true,
4745 state,
4746 &["marked".to_owned()],
4747 std::slice::from_ref(&running),
4748 );
4749 let gated = interrupt_gate(
4750 &state,
4751 &["marked".to_owned()],
4752 vec![marked.clone(), running.clone()],
4753 );
4754 assert!(
4755 gated.is_empty(),
4756 "the parked run must not be offered back while the interrupt \
4757 task is still running"
4758 );
4759
4760 let other = task_with_id("other");
4764 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4765 assert_eq!(
4766 state,
4767 Interrupt::Resuming {
4768 parked: vec![running.id.clone()]
4769 }
4770 );
4771 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4772 assert_eq!(
4773 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4774 vec![running.id.as_str()],
4775 "exactly the parked run resumes - not the unrelated task, even \
4776 though it was offered first"
4777 );
4778
4779 state = advance_interrupt_tick(
4783 true,
4784 state,
4785 std::slice::from_ref(&running.id),
4786 std::slice::from_ref(&other),
4787 );
4788 assert_eq!(state, Interrupt::Idle);
4789 let gated = interrupt_gate(
4790 &state,
4791 std::slice::from_ref(&running.id),
4792 vec![other.clone()],
4793 );
4794 assert_eq!(
4795 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4796 vec![other.id.as_str()],
4797 "ordinary dispatch is unrestricted again"
4798 );
4799 }
4800
4801 #[test]
4802 fn every_run_status_settles_the_task_it_came_from() {
4803 let table = [
4805 (RunStatus::Merged, TaskStatus::Done, 1),
4806 (RunStatus::Ready, TaskStatus::Done, 1),
4807 (RunStatus::Stalled, TaskStatus::Failed, 0),
4808 (RunStatus::Blocked, TaskStatus::Failed, 1),
4809 (RunStatus::Failed, TaskStatus::Failed, 1),
4810 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4811 (RunStatus::Prep, TaskStatus::Failed, 1),
4812 (RunStatus::Implementing, TaskStatus::Failed, 1),
4813 (RunStatus::Judging, TaskStatus::Failed, 1),
4814 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4815 (RunStatus::Voting, TaskStatus::Failed, 1),
4816 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4817 (RunStatus::Gating, TaskStatus::Failed, 1),
4818 ];
4819 for (run, want, attempts) in table {
4820 let mut t = task();
4821 t.start("20260902-000000-aaaa".to_owned());
4822 settle(
4823 &mut t,
4824 Verdict {
4825 status: run,
4826 left_pr: false,
4827 parked: false,
4828 quota_hit: matches!(run, RunStatus::Stalled),
4829 no_viable_candidates: false,
4830 },
4831 "why",
4832 2,
4833 );
4834 assert_eq!(t.status, want, "task status after {}", label(run));
4835 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4836 }
4837 }
4838
4839 #[test]
4840 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4841 let mut stalled = task();
4842 stalled.start("20260902-000000-aaaa".to_owned());
4843 settle(
4844 &mut stalled,
4845 Verdict {
4846 status: RunStatus::Stalled,
4847 left_pr: false,
4848 parked: false,
4849 quota_hit: true,
4850 no_viable_candidates: false,
4851 },
4852 "quota",
4853 1,
4854 );
4855 assert_eq!(stalled.attempts, 0);
4856 assert!(
4857 stalled.status.runnable(),
4858 "a machine problem must leave the task in line"
4859 );
4860
4861 let mut blocked = task();
4862 blocked.start("20260902-000000-aaaa".to_owned());
4863 settle(
4864 &mut blocked,
4865 Verdict {
4866 status: RunStatus::Blocked,
4867 left_pr: false,
4868 parked: false,
4869 quota_hit: false,
4870 no_viable_candidates: false,
4871 },
4872 "findings open",
4873 1,
4874 );
4875 assert_eq!(blocked.attempts, 1);
4876 assert_eq!(
4877 blocked.status,
4878 TaskStatus::Held,
4879 "the last attempt hands the task to a human"
4880 );
4881 }
4882
4883 #[test]
4884 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4885 let mut delivered = task();
4888 delivered.start("20260903-080619-01c2".to_owned());
4889 settle(
4890 &mut delivered,
4891 Verdict {
4892 status: RunStatus::Blocked,
4893 left_pr: true,
4894 parked: false,
4895 quota_hit: false,
4896 no_viable_candidates: false,
4897 },
4898 "no check status",
4899 4,
4900 );
4901 assert_eq!(
4902 delivered.status,
4903 TaskStatus::Held,
4904 "a pull request waiting on CI or a person is not a retryable failure"
4905 );
4906 assert!(
4907 !delivered.status.runnable(),
4908 "the loop must not pick this task up again"
4909 );
4910 assert_eq!(
4911 delivered.last_error.as_deref(),
4912 Some("no check status"),
4913 "the operator needs to be told what the gate was waiting for"
4914 );
4915
4916 let mut empty_handed = task();
4919 empty_handed.start("20260903-080619-01c2".to_owned());
4920 settle(
4921 &mut empty_handed,
4922 Verdict {
4923 status: RunStatus::Blocked,
4924 left_pr: false,
4925 parked: false,
4926 quota_hit: false,
4927 no_viable_candidates: false,
4928 },
4929 "findings open",
4930 4,
4931 );
4932 assert_eq!(empty_handed.status, TaskStatus::Failed);
4933 assert!(empty_handed.status.runnable());
4934 }
4935
4936 #[test]
4937 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4938 let mut noop = task();
4944 noop.start("20260912-131304-391f".to_owned());
4945 settle(
4946 &mut noop,
4947 Verdict {
4948 status: RunStatus::VerifiedNoop,
4949 left_pr: false,
4950 parked: false,
4951 quota_hit: false,
4952 no_viable_candidates: true,
4953 },
4954 "candidate A: already fixed by b32cfc4, on main",
4955 4,
4956 );
4957 assert_eq!(
4958 noop.status,
4959 TaskStatus::Held,
4960 "an unverified claim is a request for a human, not a failure"
4961 );
4962 assert!(
4963 !noop.status.runnable(),
4964 "the loop must not requeue this on the same unverified claim"
4965 );
4966 assert_eq!(noop.attempts, 1);
4971 }
4972
4973 #[test]
4974 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4975 let mut parked = task();
4980 parked.start("20260903-183634-2d98".to_owned());
4981 settle(
4982 &mut parked,
4983 Verdict {
4984 status: RunStatus::Implementing,
4985 left_pr: false,
4986 quota_hit: false,
4987 parked: true,
4988 no_viable_candidates: false,
4989 },
4990 "parked after `implementing`",
4991 2,
4992 );
4993 assert_eq!(parked.attempts, 0, "a park is refunded");
4994 assert!(
4995 parked.status.runnable(),
4996 "and the task stays in line so the next loop resumes its run"
4997 );
4998 assert_eq!(parked.status, TaskStatus::Parked);
4999 assert_eq!(
5000 parked.park_reason.as_deref(),
5001 Some("parked after `implementing`"),
5002 "the card says where it stopped"
5003 );
5004 assert_eq!(parked.last_error, None, "nothing failed");
5005
5006 let mut broken = task();
5010 broken.start("20260903-183634-2d98".to_owned());
5011 settle(
5012 &mut broken,
5013 Verdict {
5014 status: RunStatus::Implementing,
5015 left_pr: false,
5016 quota_hit: false,
5017 parked: false,
5018 no_viable_candidates: false,
5019 },
5020 "returned mid-flight",
5021 2,
5022 );
5023 assert_eq!(broken.attempts, 1);
5024 }
5025
5026 #[test]
5027 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
5028 let mut flaky = task();
5033 flaky.start("20260903-123023-e633".to_owned());
5034 settle(
5035 &mut flaky,
5036 Verdict {
5037 status: RunStatus::Stalled,
5038 left_pr: false,
5039 parked: false,
5040 quota_hit: false,
5041 no_viable_candidates: false,
5042 },
5043 "verdict rests on 1 of 3 judges",
5044 2,
5045 );
5046 assert_eq!(
5047 flaky.attempts, 1,
5048 "flakiness spends an attempt, so `max_attempts` still bounds it"
5049 );
5050 assert!(flaky.status.runnable(), "and it is still worth retrying");
5051
5052 let mut limited = task();
5054 limited.start("20260903-123023-e633".to_owned());
5055 settle(
5056 &mut limited,
5057 Verdict {
5058 status: RunStatus::Stalled,
5059 left_pr: false,
5060 parked: false,
5061 quota_hit: true,
5062 no_viable_candidates: false,
5063 },
5064 "judge-2, judge-3 out of quota",
5065 2,
5066 );
5067 assert_eq!(limited.attempts, 0, "a quota window is refunded");
5068 assert!(limited.status.runnable());
5069
5070 let mut worn = task();
5073 for _ in 0..2 {
5074 worn.release();
5075 }
5076 worn.start("20260903-123023-e633".to_owned());
5077 worn.attempts = 2;
5078 settle(
5079 &mut worn,
5080 Verdict {
5081 status: RunStatus::Stalled,
5082 left_pr: false,
5083 parked: false,
5084 quota_hit: false,
5085 no_viable_candidates: false,
5086 },
5087 "no quorum again",
5088 2,
5089 );
5090 assert_eq!(worn.status, TaskStatus::Held);
5091 assert!(!worn.status.runnable());
5092 }
5093
5094 #[test]
5095 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5096 let mut wiped_out = task();
5103 wiped_out.start("20260907-025000-a1b2".to_owned());
5104 settle(
5105 &mut wiped_out,
5106 Verdict {
5107 status: RunStatus::Failed,
5108 left_pr: false,
5109 parked: false,
5110 quota_hit: true,
5111 no_viable_candidates: true,
5112 },
5113 "no candidate produced a change; nothing to judge",
5114 2,
5115 );
5116 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5117 assert!(
5118 wiped_out.status.runnable(),
5119 "a machine problem must leave the task in line"
5120 );
5121
5122 let mut partial_progress = task();
5128 partial_progress.start("20260907-025500-c3d4".to_owned());
5129 settle(
5130 &mut partial_progress,
5131 Verdict {
5132 status: RunStatus::Failed,
5133 left_pr: false,
5134 parked: false,
5135 quota_hit: true,
5136 no_viable_candidates: false,
5137 },
5138 "gate failed on the winning candidate",
5139 2,
5140 );
5141 assert_eq!(
5142 partial_progress.attempts, 1,
5143 "a candidate that actually produced a change spends the attempt \
5144 even though some other seat hit its quota"
5145 );
5146 assert!(partial_progress.status.runnable());
5147 }
5148
5149 #[test]
5150 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5151 let mut t = task();
5157 t.start("20260907-025000-a1b2".to_owned());
5158 let mut state = run_state(RunStatus::Failed);
5159 state.quota.push(QuotaLoss {
5160 seat: "cand-a".to_owned(),
5161 node: "implement".to_owned(),
5162 at: Timestamp::now(),
5163 reset: None,
5164 });
5165 assert!(
5166 state.viable().is_empty(),
5167 "no candidate was added, so nothing is viable"
5168 );
5169 reclaim(&mut t, Some(state), 2, "en");
5170 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5171 assert!(t.status.runnable());
5172 }
5173
5174 #[test]
5175 fn a_held_task_is_never_offered_to_the_loop() {
5176 let dir = tempfile::tempdir().unwrap();
5177 let queue = Queue::at(dir.path().to_path_buf());
5178 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5179 let mut t = task();
5180 t.id = format!("2026090{n}-000000-000{n}");
5181 t.priority = priority;
5182 queue.put(&mut t).unwrap();
5183 }
5184 let mut held = task();
5185 held.id = "20260909-000000-9999".to_owned();
5186 held.priority = 99;
5187 held.hold_machine(None);
5188 queue.put(&mut held).unwrap();
5189
5190 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5191 assert_eq!(order.len(), 3);
5192 assert!(!order.contains(&held.id));
5193 assert_eq!(
5194 order.first().cloned(),
5195 queue.next_runnable().map(|t| t.id),
5196 "the loop's first candidate is exactly what the queue offers"
5197 );
5198 assert_eq!(
5199 order,
5200 vec![
5201 "20260902-000000-0002".to_owned(),
5202 "20260903-000000-0003".to_owned(),
5203 "20260901-000000-0001".to_owned(),
5204 ],
5205 "priority first, then oldest, so nothing starves"
5206 );
5207 }
5208
5209 #[test]
5210 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5211 let dir = tempfile::tempdir().unwrap();
5212 let queue = Queue::at(dir.path().to_path_buf());
5213 let mut old = task();
5214 old.id = "20260101-000000-old0".to_owned();
5215 queue.put(&mut old).unwrap();
5216 let mut fresh = task();
5217 fresh.id = "20260101-000000-new0".to_owned();
5218 queue.put(&mut fresh).unwrap();
5219
5220 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5224 std::thread::sleep(Duration::from_millis(60));
5225 let live = queue.claim(&fresh.id).unwrap();
5226
5227 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5228 assert_eq!(swept, vec![old.id.clone()]);
5229 assert!(
5230 queue.claim(&old.id).is_ok(),
5231 "an unparseable lock older than the threshold is swept"
5232 );
5233 assert!(
5234 queue.claim(&fresh.id).is_err(),
5235 "a live pid protects its lock regardless of age"
5236 );
5237 drop(live);
5238 }
5239
5240 #[test]
5241 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5242 let dir = tempfile::tempdir().unwrap();
5252 let queue = Queue::at(dir.path().to_path_buf());
5253 let mut t = task();
5254 t.id = "20260101-000000-live".to_owned();
5255 queue.put(&mut t).unwrap();
5256
5257 let claim = queue.claim(&t.id).unwrap();
5258 std::thread::sleep(Duration::from_millis(60));
5259
5260 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5261 assert!(
5262 swept.is_empty(),
5263 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5264 );
5265 assert!(
5266 queue.claim(&t.id).is_err(),
5267 "the lock still protects its task"
5268 );
5269 drop(claim);
5270 }
5271
5272 fn injected_dead_pid() -> u32 {
5275 std::process::id().checked_add(1).unwrap_or(1)
5276 }
5277
5278 #[test]
5279 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5280 let dir = tempfile::tempdir().unwrap();
5281 let queue = Queue::at(dir.path().to_path_buf());
5282 let mut t = task();
5283 t.id = "20260101-000000-dead".to_owned();
5284 queue.put(&mut t).unwrap();
5285 let dead_pid = injected_dead_pid();
5286
5287 std::fs::write(
5292 dir.path().join(format!("{}.lock", t.id)),
5293 dead_pid.to_string(),
5294 )
5295 .unwrap();
5296
5297 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5298 pid != dead_pid
5299 });
5300 assert_eq!(
5301 swept,
5302 vec![t.id.clone()],
5303 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5304 );
5305 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5306 }
5307
5308 #[test]
5309 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5310 let dir = tempfile::tempdir().unwrap();
5311 let queue = Queue::at(dir.path().to_path_buf());
5312 let mut t = task();
5313 t.id = "20260101-000000-late".to_owned();
5314 queue.put(&mut t).unwrap();
5315 let dead_pid = injected_dead_pid();
5316
5317 assert!(
5320 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5321 "nothing has claimed the task yet"
5322 );
5323
5324 std::fs::write(
5327 dir.path().join(format!("{}.lock", t.id)),
5328 dead_pid.to_string(),
5329 )
5330 .unwrap();
5331
5332 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
5341 #[test]
5342 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5343 crate::run::pin_test_home();
5348 let dir = tempfile::tempdir().unwrap();
5349 let queue = Queue::at(dir.path().to_path_buf());
5350 let mut t = task();
5351 t.id = "20260101-000000-crsh".to_owned();
5352 t.status = TaskStatus::Running;
5353 t.attempts = 1;
5354 t.runs.push("20260904-000000-4043".to_owned());
5358 queue.put(&mut t).unwrap();
5359 let dead_pid = injected_dead_pid();
5360
5361 std::fs::write(
5364 dir.path().join(format!("{}.lock", t.id)),
5365 dead_pid.to_string(),
5366 )
5367 .unwrap();
5368
5369 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5375 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5376
5377 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5378 pid != dead_pid
5379 });
5380 assert_eq!(swept, vec![t.id.clone()]);
5381
5382 let reclaimed = reclaim_orphaned_running(&queue, 2);
5383 assert_eq!(reclaimed, vec![t.id.clone()]);
5384 let after = queue.get(&t.id).unwrap();
5385 assert_eq!(
5386 after.status,
5387 TaskStatus::Held,
5388 "no run.json to recover from, so a human is asked"
5389 );
5390 assert_eq!(
5391 after.runs,
5392 vec!["20260904-000000-4043".to_owned()],
5393 "the crashed run's id is kept as evidence, not discarded"
5394 );
5395 }
5396
5397 #[test]
5398 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
5399 let dir = tempfile::tempdir().unwrap();
5400 let queue = Queue::at(dir.path().to_path_buf());
5401 let mut t = task();
5402 t.id = "20260101-000000-unknown".to_owned();
5403 queue.put(&mut t).unwrap();
5404 let dead_pid = injected_dead_pid();
5405 std::fs::write(
5406 dir.path().join(format!("{}.lock", t.id)),
5407 dead_pid.to_string(),
5408 )
5409 .unwrap();
5410
5411 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
5412 assert!(swept.is_empty(), "an unknown pid must keep its lock");
5413 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
5414 }
5415
5416 fn run_state_in(status: RunStatus, language: &str) -> RunState {
5417 let mut s = run_state(status);
5418 s.config.graph.language = language.to_owned();
5419 s
5420 }
5421
5422 fn unstarted_verdict(status: RunStatus) -> Verdict {
5423 Verdict {
5424 status,
5425 left_pr: false,
5426 quota_hit: false,
5427 parked: false,
5428 no_viable_candidates: false,
5429 }
5430 }
5431
5432 #[test]
5433 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
5434 let mut t = task();
5435 t.attempts = 1;
5436 settle_in(
5437 &mut t,
5438 unstarted_verdict(RunStatus::AlreadyInBase),
5439 "already in main",
5440 1,
5441 phrases("en"),
5442 );
5443 assert_eq!(t.status, TaskStatus::Done);
5444 assert_eq!(t.attempts, 0);
5445 }
5446
5447 #[test]
5448 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
5449 let reason = |language: &str| {
5450 let mut t = task();
5451 settle_in(
5452 &mut t,
5453 unstarted_verdict(RunStatus::Judging),
5454 "boom",
5455 1,
5456 phrases(language),
5457 );
5458 t.last_error.or(t.hold_reason).unwrap_or_default()
5459 };
5460 assert!(
5461 reason("en").starts_with("the graph stopped at `"),
5462 "{}",
5463 reason("en")
5464 );
5465 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
5466 assert!(reason("日本語").contains("boom"));
5467 assert_eq!(reason("fr"), reason("en"));
5468 }
5469
5470 #[test]
5471 fn describe_follows_the_run_language_and_keeps_the_run_id() {
5472 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
5473 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
5474 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
5475 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
5476 assert!(ja.contains("[run "), "{ja}");
5477 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
5478 assert!(ended.starts_with("run 終了: "), "{ended}");
5479 let mut de = run_state_in(RunStatus::Failed, "de");
5480 let mut en = run_state_in(RunStatus::Failed, "en");
5481 de.id = "same".to_owned();
5482 en.id = "same".to_owned();
5483 assert_eq!(describe(&de), describe(&en));
5484 }
5485
5486 #[test]
5487 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
5488 use crate::handover::Refused;
5489 let cases = [
5490 Refused::Foreign {
5491 branch: "b".into(),
5492 path: "/w/x".into(),
5493 why: "made by hand".into(),
5494 },
5495 Refused::Unsafe {
5496 branch: "b".into(),
5497 path: "/w/x".into(),
5498 why: "its worktree has uncommitted changes (a.rs)".into(),
5499 },
5500 Refused::ReleaseFailed {
5501 branch: "b".into(),
5502 path: "/w/x".into(),
5503 run: "ab12".into(),
5504 },
5505 ];
5506 for r in &cases {
5507 let en = (phrases("en").handover_refused)(r);
5508 assert_eq!(en, r.to_string());
5509 let ja = (phrases("ja").handover_refused)(r);
5510 assert!(
5511 !ja.contains("is checked out") && !ja.contains("try again"),
5512 "{ja}"
5513 );
5514 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
5515 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
5516 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
5517 }
5518 }
5519 assert!(phrases("en").handover_hint.contains("release the task"));
5520 assert!(phrases("ja").handover_hint.contains("解放"));
5521 }
5522
5523 #[test]
5524 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
5525 let build = |lang: &str| {
5526 let mut s = run_state_in(RunStatus::Blocked, lang);
5527 s.id = "same".to_owned();
5528 s.config.graph.review_rounds = 3;
5529 let mut r = review_round(3);
5530 r.expected = 3;
5531 r.answered = 1;
5532 s.reviews.push(r);
5533 s.event(
5534 "review",
5535 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
5536 );
5537 s
5538 };
5539 let en = describe(&build("en"));
5540 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
5541 let ja = describe(&build("ja"));
5542 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
5543 assert!(!ja.contains("never answered"), "{ja}");
5544 assert!(ja.contains("[run "), "{ja}");
5545
5546 let mut failed = build("ja");
5549 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
5550 command: "cargo test".to_owned(),
5551 code: Some(1),
5552 output_tail: String::new(),
5553 duration_ms: 0,
5554 resource_blocked: false,
5555 });
5556 failed.event("review", "stopped; e2e failed: cargo test");
5557 let ja = describe(&failed);
5558 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
5559 assert!(!ja.contains("席のレビュアー"), "{ja}");
5560 }
5561
5562 #[test]
5563 fn refusals_and_recovery_prose_follow_the_language() {
5564 let t = held_task_with("r1");
5565 let q = action_question(
5566 "r1",
5567 ask::ChoiceAction::Resume {
5568 run: "r1".to_owned(),
5569 },
5570 );
5571 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
5572 ActionDecision::Refuse(s) => s,
5573 other => panic!("{other:?}"),
5574 };
5575 assert!(refuse(phrases("en")).contains("could not be read: gone"));
5576 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
5577 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
5578
5579 let mut held = task();
5580 reclaim(&mut held, None, 2, "ja");
5581 assert!(held.hold_reason.unwrap().contains("保留にしました"));
5582 let mut held = task();
5583 reclaim(&mut held, None, 2, "xx");
5584 assert!(held.hold_reason.unwrap().contains("held for a human"));
5585 }
5586
5587 fn run_state(status: RunStatus) -> RunState {
5588 let mut state = RunState::new(
5589 PathBuf::from("/repo"),
5590 "main".to_owned(),
5591 "abc1234def".to_owned(),
5592 "add retries".to_owned(),
5593 Config::default(),
5594 );
5595 state.status = status;
5596 state
5597 }
5598
5599 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
5600 Candidate {
5601 index: 0,
5602 label,
5603 agent: "claude".to_owned(),
5604 branch: format!("magi/x/{label}"),
5605 worktree: PathBuf::from("/repo"),
5606 summary: summary.to_owned(),
5607 stat: String::new(),
5608 files: 0,
5609 commits: usize::from(!empty),
5610 empty,
5611 failed: failed.map(str::to_owned),
5612 verified_noop: None,
5613 duration_ms: 0,
5614 folded: false,
5615 }
5616 }
5617
5618 #[test]
5619 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
5620 let mut state = run_state(RunStatus::Blocked);
5621 state.gate = vec![
5622 CommandOutcome {
5623 command: "cargo make check".to_owned(),
5624 code: Some(0),
5625 output_tail: "ok".to_owned(),
5626 duration_ms: 0,
5627 resource_blocked: false,
5628 },
5629 CommandOutcome {
5630 command: "cargo test".to_owned(),
5631 code: Some(101),
5632 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
5633 duration_ms: 0,
5634 resource_blocked: false,
5635 },
5636 ];
5637 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
5638 assert!(d.contains("cargo test"), "{d}");
5639 assert!(
5640 !d.contains("cargo make check"),
5641 "a passing check is not a diagnostic: {d}"
5642 );
5643 assert!(d.contains("assertion failed"), "{d}");
5644 }
5645
5646 #[test]
5647 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
5648 let mut state = run_state(RunStatus::Blocked);
5649 state.event(
5650 "land",
5651 "stopped: the fixer produced no commit while 2 check(s) were failing \
5652 (build, lint); stopping instead of looping on an unchanged tree",
5653 );
5654 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
5655 assert!(d.contains("build"), "{d}");
5656 assert!(d.contains("lint"), "{d}");
5657 assert!(d.contains("fixer produced no commit"), "{d}");
5658 }
5659
5660 #[test]
5661 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
5662 let state = run_state(RunStatus::VerifiedNoop);
5667 let d = describe(&state);
5668 assert!(
5669 d.contains("agent-verified no-op"),
5670 "expected the display label, not the wire spelling: {d}"
5671 );
5672 assert!(!d.contains("verified_noop"), "{d}");
5673 }
5674
5675 #[test]
5676 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
5677 let mut state = run_state(RunStatus::Failed);
5683 state.candidates = vec![candidate(
5684 'A',
5685 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
5686 true,
5687 None,
5688 )];
5689 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
5690 assert!(d.contains("candidate A"), "{d}");
5691 assert!(d.contains("tagged v1.2.3"), "{d}");
5692 }
5693
5694 #[test]
5695 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
5696 let mut state = run_state(RunStatus::Failed);
5697 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
5698 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
5699 assert!(d.contains("candidate A"), "{d}");
5700 assert!(d.contains("agent timed out"), "{d}");
5701 }
5702
5703 #[test]
5704 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
5705 let mut state = run_state(RunStatus::Failed);
5708 state.candidates = vec![candidate('A', "did the work", false, None)];
5709 assert!(diagnostic(&state).is_none());
5710 }
5711
5712 #[test]
5713 fn diagnostic_is_bounded_however_much_a_run_printed() {
5714 let mut state = run_state(RunStatus::Blocked);
5715 state.gate = vec![
5716 CommandOutcome {
5717 command: "cargo test".to_owned(),
5718 code: Some(101),
5719 output_tail: "x".repeat(50_000),
5720 duration_ms: 0,
5721 resource_blocked: false,
5722 },
5723 CommandOutcome {
5724 command: "cargo clippy".to_owned(),
5725 code: Some(1),
5726 output_tail: "y".repeat(50_000),
5727 duration_ms: 0,
5728 resource_blocked: false,
5729 },
5730 ];
5731 state.candidates = vec![
5732 candidate('A', &"z".repeat(50_000), true, None),
5733 candidate('B', &"w".repeat(50_000), true, None),
5734 ];
5735 let d = diagnostic(&state).expect("plenty here to diagnose");
5736 assert!(
5737 d.len() <= DIAGNOSTIC_MAX,
5738 "diagnostic grew to {} bytes, unbounded",
5739 d.len()
5740 );
5741 }
5742
5743 #[test]
5744 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
5745 let mut state = run_state(RunStatus::Blocked);
5746 state.gate = vec![CommandOutcome {
5747 command: "cargo test".to_owned(),
5748 code: Some(101),
5749 output_tail: "assertion failed".to_owned(),
5750 duration_ms: 0,
5751 resource_blocked: false,
5752 }];
5753 let verdict = Verdict {
5754 status: RunStatus::Blocked,
5755 left_pr: false,
5756 quota_hit: false,
5757 parked: false,
5758 no_viable_candidates: false,
5759 };
5760
5761 let mut t = task();
5764 t.start("run-1".to_owned());
5765 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5766 assert_eq!(t.status, TaskStatus::Failed);
5767 assert!(t.diagnostic.is_none());
5768
5769 t.start("run-2".to_owned());
5772 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5773 assert_eq!(t.status, TaskStatus::Held);
5774 let d = t.diagnostic.expect("a held task must carry its diagnostic");
5775 assert!(d.contains("cargo test"), "{d}");
5776 }
5777
5778 #[test]
5779 fn a_held_task_names_the_open_question_it_is_waiting_on() {
5780 crate::run::pin_test_home();
5785 let home = crate::run::home();
5786 let state = run_state(RunStatus::VerifiedNoop);
5787 let mut q = ask::Question::new(
5788 state.id.clone(),
5789 "implement".to_owned(),
5790 "impl-A".to_owned(),
5791 "is this really a no-op?".to_owned(),
5792 String::new(),
5793 Vec::new(),
5794 );
5795 Questions::at(home.join("questions")).put(&mut q).unwrap();
5796
5797 let verdict = Verdict {
5798 status: RunStatus::VerifiedNoop,
5799 left_pr: false,
5800 quota_hit: false,
5801 parked: false,
5802 no_viable_candidates: false,
5803 };
5804 let mut t = task();
5805 t.start(state.id.clone());
5806 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5807
5808 assert_eq!(t.status, TaskStatus::Held);
5809 let reason = t.hold_reason.expect("a held task must record why");
5810 assert!(
5811 reason.starts_with("run ended agent-verified no-op"),
5812 "the original settle reason must survive unchanged: {reason}"
5813 );
5814 assert!(
5815 reason.contains(q.short()),
5816 "the open question's id must be named so the notice is actionable: {reason}"
5817 );
5818 }
5819
5820 #[test]
5821 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
5822 crate::run::pin_test_home();
5823 let state = run_state(RunStatus::VerifiedNoop);
5824
5825 let verdict = Verdict {
5826 status: RunStatus::VerifiedNoop,
5827 left_pr: false,
5828 quota_hit: false,
5829 parked: false,
5830 no_viable_candidates: false,
5831 };
5832 let mut t = task();
5833 t.start(state.id.clone());
5834 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5835
5836 assert_eq!(t.status, TaskStatus::Held);
5837 assert_eq!(
5838 t.hold_reason.as_deref(),
5839 Some("run ended agent-verified no-op"),
5840 "nothing to append when the question was already answered or never asked"
5841 );
5842 }
5843
5844 #[test]
5845 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5846 crate::run::pin_test_home();
5847 let mut first = run_state(RunStatus::Blocked);
5848 first.id = "20260101-000000-sup1".to_owned();
5849 first.save().unwrap();
5850 let mut second = run_state(RunStatus::Merged);
5851 second.id = "20260101-000000-sup2".to_owned();
5852 second.save().unwrap();
5853
5854 let mut t = task();
5855 t.runs = vec![first.id.clone(), second.id.clone()];
5856 t.status = TaskStatus::Done;
5857
5858 supersede_prior_runs(&t, &crate::run::home());
5859
5860 assert_eq!(
5861 RunState::load(&first.id).unwrap().status,
5862 RunStatus::Superseded,
5863 "the first attempt's Blocked no longer needs anyone's attention"
5864 );
5865 assert_eq!(
5866 RunState::load(&second.id).unwrap().status,
5867 RunStatus::Merged,
5868 "the run that actually succeeded is left exactly as it was"
5869 );
5870 }
5871
5872 #[test]
5873 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5874 crate::run::pin_test_home();
5880 let mut first = run_state(RunStatus::Blocked);
5881 first.id = "20260101-000000-sup9".to_owned();
5882 first.driver_pid = Some(std::process::id());
5885 first.driver_started_at = Some(
5886 crate::proc::process_started_at(std::process::id())
5887 .expect("this test process's own start time must be queryable"),
5888 );
5889 first.save().unwrap();
5890 let mut second = run_state(RunStatus::Merged);
5891 second.id = "20260101-000000-supa".to_owned();
5892 second.save().unwrap();
5893
5894 let mut t = task();
5895 t.runs = vec![first.id.clone(), second.id.clone()];
5896 t.status = TaskStatus::Done;
5897
5898 supersede_prior_runs(&t, &crate::run::home());
5899
5900 assert_eq!(
5901 RunState::load(&first.id).unwrap().status,
5902 RunStatus::Blocked,
5903 "a live driver_pid means something is still actually working this run, \
5904 even though no daemon claims it - rewriting under it would just be \
5905 undone the next time that process saves"
5906 );
5907 }
5908
5909 #[test]
5910 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5911 let dir = tempfile::tempdir().unwrap();
5917 let home = dir.path().to_path_buf();
5918 let queue = Queue::at(dir.path().join("queue"));
5919
5920 let mut first = run_state(RunStatus::Blocked);
5921 first.id = "20260101-000000-supd".to_owned();
5922 first.driver_pid = Some(std::process::id());
5923 first.driver_started_at = Some(
5924 crate::proc::process_started_at(std::process::id())
5925 .expect("this test process's own start time must be queryable"),
5926 );
5927 first.save_under(&home).unwrap();
5928 let mut second = run_state(RunStatus::Merged);
5929 second.id = "20260101-000000-supe".to_owned();
5930 second.save_under(&home).unwrap();
5931
5932 let mut t = task();
5933 t.runs = vec![first.id.clone(), second.id.clone()];
5934 t.status = TaskStatus::Done;
5935 queue.put(&mut t).unwrap();
5936
5937 resweep_superseded_attempts(&queue, &home);
5938 assert_eq!(
5939 RunState::load_under(&first.id, &home).unwrap().status,
5940 RunStatus::Blocked,
5941 "still live on the first pass, so still untouched"
5942 );
5943
5944 let mut stale = RunState::load_under(&first.id, &home).unwrap();
5950 stale.driver_started_at = Some("1".to_owned());
5951 stale.save_under(&home).unwrap();
5952
5953 resweep_superseded_attempts(&queue, &home);
5954 assert_eq!(
5955 RunState::load_under(&first.id, &home).unwrap().status,
5956 RunStatus::Superseded,
5957 "the second pass catches up what the first one correctly skipped"
5958 );
5959 }
5960
5961 #[test]
5962 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5963 crate::run::pin_test_home();
5964 let mut first = run_state(RunStatus::Blocked);
5965 first.id = "20260101-000000-sup3".to_owned();
5966 first.save().unwrap();
5967 let mut second = run_state(RunStatus::Blocked);
5968 second.id = "20260101-000000-sup4".to_owned();
5969 second.save().unwrap();
5970
5971 let mut t = task();
5972 t.runs = vec![first.id.clone(), second.id.clone()];
5973 t.status = TaskStatus::Failed;
5977
5978 supersede_prior_runs(&t, &crate::run::home());
5979
5980 assert_eq!(
5981 RunState::load(&first.id).unwrap().status,
5982 RunStatus::Blocked
5983 );
5984 assert_eq!(
5985 RunState::load(&second.id).unwrap().status,
5986 RunStatus::Blocked
5987 );
5988 }
5989
5990 #[test]
5991 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5992 crate::run::pin_test_home();
5996 let mut first = run_state(RunStatus::Blocked);
5997 first.id = "20260101-000000-sup5".to_owned();
5998 first.save().unwrap();
5999
6000 let mut t = task();
6001 t.runs = vec![first.id.clone()];
6002 t.status = TaskStatus::Done;
6003
6004 supersede_prior_runs(&t, &crate::run::home());
6005
6006 assert_eq!(
6007 RunState::load(&first.id).unwrap().status,
6008 RunStatus::Blocked,
6009 "a single-attempt task has no earlier run to supersede"
6010 );
6011 }
6012
6013 #[test]
6014 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
6015 crate::run::pin_test_home();
6022 let mut first = run_state(RunStatus::Blocked);
6023 first.id = "20260101-000000-supb".to_owned();
6024 first.save().unwrap();
6025 let mut second = run_state(RunStatus::Failed);
6026 second.id = "20260101-000000-supc".to_owned();
6027 second.save().unwrap();
6028
6029 let mut t = task();
6030 t.runs = vec![first.id.clone(), second.id.clone()];
6031 t.status = TaskStatus::Done;
6032
6033 supersede_prior_runs(&t, &crate::run::home());
6034
6035 assert_eq!(
6036 RunState::load(&first.id).unwrap().status,
6037 RunStatus::Blocked,
6038 "the task's last attempt never landed, so there is nothing here \
6039 actually superseding it"
6040 );
6041 }
6042
6043 #[test]
6044 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6045 crate::run::pin_test_home();
6049 let mut failed = run_state(RunStatus::Failed);
6050 failed.id = "20260101-000000-sup6".to_owned();
6051 failed.save().unwrap();
6052 let mut noop = run_state(RunStatus::VerifiedNoop);
6053 noop.id = "20260101-000000-sup7".to_owned();
6054 noop.save().unwrap();
6055 let mut winner = run_state(RunStatus::Ready);
6056 winner.id = "20260101-000000-sup8".to_owned();
6057 winner.save().unwrap();
6058
6059 let mut t = task();
6060 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6061 t.status = TaskStatus::Done;
6062
6063 supersede_prior_runs(&t, &crate::run::home());
6064
6065 assert_eq!(
6066 RunState::load(&failed.id).unwrap().status,
6067 RunStatus::Failed
6068 );
6069 assert_eq!(
6070 RunState::load(&noop.id).unwrap().status,
6071 RunStatus::VerifiedNoop
6072 );
6073 }
6074
6075 fn approval_question(run: &str) -> ask::Question {
6076 ask::Question::new(
6077 run.to_owned(),
6078 land::APPROVAL_NODE.to_owned(),
6079 "land".to_owned(),
6080 "merge?".to_owned(),
6081 String::new(),
6082 vec!["merge".to_owned(), "hold".to_owned()],
6083 )
6084 }
6085
6086 #[test]
6087 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6088 crate::run::pin_test_home();
6089 let mut state = run_state(RunStatus::Landing);
6090 state.id = "20260101-000000-fre1".to_owned();
6091 state.parked = true;
6092 state.save().unwrap();
6093 ask::Questions::open()
6094 .put(&mut approval_question(&state.id))
6095 .unwrap();
6096
6097 let mut t = task();
6098 t.runs.push(state.id.clone());
6099 assert_eq!(
6100 land_resume_state(&t),
6101 LandResume::StillWaiting,
6102 "nobody has answered and the timeout has not passed"
6103 );
6104 }
6105
6106 #[test]
6107 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6108 crate::run::pin_test_home();
6109 let mut state = run_state(RunStatus::Gating);
6110 state.id = "20260101-000000-gt01".to_owned();
6111 state.parked = true;
6112 state.config.graph.answer_timeout = 60;
6113 state.github_text = Some(crate::run::GithubTextAsk {
6114 fingerprint: "f".into(),
6115 title: true,
6116 body: false,
6117 categories: vec!["title-language".into()],
6118 question: None,
6119 asks: 1,
6120 resolved: false,
6121 chosen_title: None,
6122 choice: None,
6123 });
6124 state.save().unwrap();
6125 let store = ask::Questions::open();
6126 let mut q = ask::Question::new(
6127 state.id.clone(),
6128 crate::github_text::ASK_NODE.to_owned(),
6129 crate::github_text::ASK_SEAT.to_owned(),
6130 "s".into(),
6131 String::new(),
6132 vec!["use fallback".into()],
6133 );
6134 store.put(&mut q).unwrap();
6135 let mut t = task();
6136 t.runs.push(state.id.clone());
6137 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6138 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6139 store.put(&mut q).unwrap();
6140 assert_eq!(land_resume_state(&t), LandResume::Ready);
6141 assert!(!store.get(&q.id).unwrap().status.open());
6142 state.github_text.as_mut().unwrap().resolved = true;
6144 state.save().unwrap();
6145 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6146 }
6147
6148 #[test]
6149 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6150 crate::run::pin_test_home();
6155 let mut state = run_state(RunStatus::Landing);
6156 state.id = "20260101-000000-exp1".to_owned();
6157 state.parked = true;
6158 state.config.graph.answer_timeout = 60;
6159 state.save().unwrap();
6160
6161 let store = ask::Questions::open();
6162 let mut q = approval_question(&state.id);
6163 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6164 store.put(&mut q).unwrap();
6165
6166 let mut t = task();
6167 t.runs.push(state.id.clone());
6168 assert_eq!(
6169 land_resume_state(&t),
6170 LandResume::Ready,
6171 "an expired question must not be waited on forever"
6172 );
6173
6174 let after = store.get(&q.id).unwrap();
6175 assert!(
6176 !after.status.open(),
6177 "the question is abandoned, not silently ignored"
6178 );
6179 assert!(
6180 after.resolution().is_none(),
6181 "an abandoned question is not read as a decision"
6182 );
6183 }
6184
6185 #[test]
6186 fn reclaim_settles_a_running_task_against_its_last_run() {
6187 let mut t = task();
6188 t.start("20260904-000000-4043".to_owned());
6189 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6190 assert_eq!(
6191 t.status,
6192 TaskStatus::Done,
6193 "a run that actually finished must not stay `running` forever"
6194 );
6195 }
6196
6197 #[test]
6198 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6199 let mut t = task();
6200 t.start("20260904-000000-4043".to_owned());
6201 t.last_error = Some("earlier trouble".to_owned());
6202 let mut state = run_state(RunStatus::Judging);
6203 state.parked = true;
6204 reclaim(&mut t, Some(state), 1, "en");
6205 assert_eq!(t.status, TaskStatus::Parked);
6206 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6207 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6208 assert!(t.park_reason.is_some());
6209 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6210 assert!(!t.fresh_start);
6211 assert!(t.status.runnable());
6212 }
6213
6214 #[test]
6215 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6216 let mut t = task();
6217 t.start("20260904-000000-4043".to_owned());
6218 t.last_error = Some("earlier trouble".to_owned());
6219 settle(
6220 &mut t,
6221 Verdict {
6222 status: RunStatus::Judging,
6223 left_pr: false,
6224 quota_hit: false,
6225 parked: true,
6226 no_viable_candidates: false,
6227 },
6228 "parked after `judging`",
6229 1,
6230 );
6231 assert_eq!(t.status, TaskStatus::Parked);
6232 assert_eq!(t.attempts, 0);
6233 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6234 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6235 assert_eq!(t.schema, crate::queue::SCHEMA);
6236 assert!(
6237 crate::notices::task_held(&t).is_none(),
6238 "a park is not news"
6239 );
6240 t.start("20260904-000000-4043".to_owned());
6241 assert_eq!(t.park_reason, None);
6242 }
6243
6244 #[test]
6245 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6246 let mut t = task();
6250 t.start("20260904-000000-4043".to_owned());
6251 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6252 assert_eq!(t.status, TaskStatus::Failed);
6253 assert!(t.status.runnable());
6254 }
6255
6256 #[test]
6257 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6258 let mut t = task();
6259 t.start("20260904-000000-4043".to_owned());
6260 reclaim(&mut t, None, 2, "en");
6261 assert_eq!(t.status, TaskStatus::Held);
6262 assert!(
6263 t.last_error
6264 .as_deref()
6265 .is_some_and(|e| e.contains("running")),
6266 "the operator needs to know why this task was held"
6267 );
6268 }
6269
6270 #[test]
6271 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6272 let dir = tempfile::tempdir().unwrap();
6273 let queue = Queue::at(dir.path().to_path_buf());
6274
6275 let mut orphaned = task();
6277 orphaned.id = "20260904-000000-orph".to_owned();
6278 orphaned.status = TaskStatus::Running;
6279 orphaned.attempts = 1;
6280 queue.put(&mut orphaned).unwrap();
6281
6282 let mut alive = task();
6283 alive.id = "20260904-000000-live".to_owned();
6284 alive.status = TaskStatus::Running;
6285 alive.attempts = 1;
6286 queue.put(&mut alive).unwrap();
6287 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6288
6289 let mut queued = task();
6290 queued.id = "20260904-000000-wait".to_owned();
6291 queue.put(&mut queued).unwrap();
6292
6293 let reclaimed = reclaim_orphaned_running(&queue, 2);
6294 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6295
6296 assert_eq!(
6297 queue.get(&orphaned.id).unwrap().status,
6298 TaskStatus::Held,
6299 "nothing was driving it and there was no run to recover"
6300 );
6301 assert_eq!(
6302 queue.get(&alive.id).unwrap().status,
6303 TaskStatus::Running,
6304 "a live claim must protect the task it belongs to"
6305 );
6306 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6307 }
6308
6309 fn read_run_under(home: &Path, id: &str) -> RunState {
6315 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6316 serde_json::from_str(&body).unwrap()
6317 }
6318
6319 #[test]
6320 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6321 let dir = tempfile::tempdir().unwrap();
6322 let home = dir.path().to_path_buf();
6323 let now = Timestamp::now();
6324 let overrun_seat = || crate::run::ActiveSeat {
6325 node: "implement".to_owned(),
6326 started_at: now - jiff::SignedDuration::new(21_000, 0),
6327 timeout_secs: 3_600,
6328 attempt: 0,
6329 task: None,
6330 command: None,
6331 index: None,
6332 total: None,
6333 };
6334
6335 let mut dead = run_state(RunStatus::Implementing);
6336 dead.id = "20260101-000000-dead".to_owned();
6337 dead.active.insert("impl-A".to_owned(), overrun_seat());
6338 dead.driver_pid = Some(4242);
6341 dead.save_under(&home).unwrap();
6342
6343 let mut alive = run_state(RunStatus::Implementing);
6346 alive.id = "20260101-000000-aliv".to_owned();
6347 alive.active.insert("impl-A".to_owned(), overrun_seat());
6348 alive.save_under(&home).unwrap();
6349 let mut status = Status::new();
6350 status.current = vec![Current {
6351 task: "20260101-000000-task".to_owned(),
6352 run: alive.id.clone(),
6353 }];
6354 write_status_to(&home.join("daemon.json"), &status).unwrap();
6355
6356 let questions = Questions::at(home.join("questions"));
6360 let mut q = ask::Question::new(
6361 dead.id.clone(),
6362 "implement".to_owned(),
6363 "impl-A".to_owned(),
6364 "Which storage backend?".to_owned(),
6365 String::new(),
6366 vec!["SQLite".to_owned(), "Redis".to_owned()],
6367 );
6368 questions.put(&mut q).unwrap();
6369
6370 let abandoned = reclaim_abandoned_runs_with(
6371 &home,
6372 now,
6373 |pid| if pid == 4242 { Some(false) } else { None },
6374 |_| panic!("a query answering Dead outright needs no identity corroboration"),
6375 );
6376 assert_eq!(abandoned, vec![dead.id.clone()]);
6377
6378 let reloaded = read_run_under(&home, &dead.id);
6379 assert_eq!(reloaded.status, RunStatus::Failed);
6380 assert!(reloaded.active.is_empty());
6381 assert!(
6382 !questions.get(&q.id).unwrap().status.open(),
6383 "the failed run's own open question must be settled in the same pass"
6384 );
6385
6386 let still_alive = read_run_under(&home, &alive.id);
6387 assert_eq!(
6388 still_alive.status,
6389 RunStatus::Implementing,
6390 "a live daemon's claim protects it"
6391 );
6392 assert!(!still_alive.active.is_empty());
6393 }
6394
6395 #[test]
6405 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
6406 let dir = tempfile::tempdir().unwrap();
6407 let home = dir.path().to_path_buf();
6408 let now = Timestamp::now();
6409
6410 let mut manual = run_state(RunStatus::Reviewing);
6411 manual.id = "20260101-000000-manl".to_owned();
6412 manual.active.insert(
6413 "review-1".to_owned(),
6414 crate::run::ActiveSeat {
6415 node: "review".to_owned(),
6416 started_at: now - jiff::SignedDuration::new(21_000, 0),
6417 timeout_secs: 3_600,
6418 attempt: 0,
6419 task: None,
6420 command: None,
6421 index: None,
6422 total: None,
6423 },
6424 );
6425 manual.driver_pid = Some(4242);
6429 manual.driver_started_at = Some("1790000000".to_owned());
6430 manual.save_under(&home).unwrap();
6431
6432 let abandoned = reclaim_abandoned_runs_with(
6433 &home,
6434 now,
6435 |pid| if pid == 4242 { Some(true) } else { None },
6436 |pid| {
6437 if pid == 4242 {
6438 Some("1790000000".to_owned())
6439 } else {
6440 None
6441 }
6442 },
6443 );
6444 assert!(
6445 abandoned.is_empty(),
6446 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
6447 );
6448
6449 let reloaded = read_run_under(&home, &manual.id);
6450 assert_eq!(reloaded.status, RunStatus::Reviewing);
6451 assert!(!reloaded.active.is_empty());
6452 }
6453
6454 #[test]
6455 fn an_already_claimed_task_is_skipped_rather_than_failed() {
6456 let dir = tempfile::tempdir().unwrap();
6457 let queue = Queue::at(dir.path().to_path_buf());
6458 let mut only = task();
6459 queue.put(&mut only).unwrap();
6460
6461 let _elsewhere = queue.claim(&only.id).unwrap();
6462 let candidates = runnable(&queue);
6463 assert_eq!(candidates.len(), 1, "the task is still runnable");
6464 assert!(
6465 queue.claim(&candidates[0].id).is_err(),
6466 "the loop cannot take a claim somebody else holds"
6467 );
6468
6469 let after = queue.get(&only.id).unwrap();
6470 assert_eq!(after.status, TaskStatus::Queued);
6471 assert_eq!(
6472 after.attempts, 0,
6473 "losing the race is not an attempt at the task"
6474 );
6475 assert_eq!(after.last_error, None);
6476 }
6477
6478 #[test]
6479 fn the_status_file_round_trips_and_its_heartbeat_advances() {
6480 let dir = tempfile::tempdir().unwrap();
6481 let path = dir.path().join("daemon.json");
6482
6483 let mut status = Status::new();
6484 status.idle = false;
6485 status.completed = 7;
6486 status.current = vec![Current {
6487 task: "20260902-000000-t111".to_owned(),
6488 run: "20260902-000001-r111".to_owned(),
6489 }];
6490 write_status_to(&path, &status).unwrap();
6491 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6492 assert_eq!(first.schema, SCHEMA);
6493 assert_eq!(first.pid, std::process::id());
6494 assert!(!first.idle);
6495 assert_eq!(first.completed, 7);
6496 assert_eq!(first.current, status.current);
6497 assert!(
6498 !path.with_extension("json.tmp").exists(),
6499 "the temp file is renamed, not left behind"
6500 );
6501
6502 std::thread::sleep(Duration::from_millis(5));
6503 status.updated_at = Timestamp::now();
6504 status.polls = 3;
6505 write_status_to(&path, &status).unwrap();
6506 let second: Status =
6507 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6508 assert!(
6509 second.updated_at > first.updated_at,
6510 "a reader can only detect staleness if the heartbeat moves"
6511 );
6512 assert_eq!(
6513 second.started_at, first.started_at,
6514 "the start time is not a heartbeat"
6515 );
6516 assert_eq!(second.polls, 3);
6517 }
6518
6519 #[test]
6520 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
6521 let dir = tempfile::tempdir().unwrap();
6522
6523 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
6524
6525 let mut status = Status::new();
6526 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
6527 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6528 let stale = read_status(dir.path()).unwrap();
6529 assert!(
6530 !stale.running(Timestamp::now()),
6531 "a minute without a heartbeat is a dead daemon, not a busy one"
6532 );
6533 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
6534
6535 status.updated_at = Timestamp::now();
6536 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6537 let fresh = read_status(dir.path()).unwrap();
6538 assert!(fresh.running(Timestamp::now()));
6539 }
6540
6541 #[test]
6542 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
6543 let dir = tempfile::tempdir().unwrap();
6544 let now = Timestamp::now();
6545 let mine = "20260903-080619-01c2";
6546
6547 assert!(
6548 !is_working_on(dir.path(), mine, now),
6549 "no status file means nobody is working on anything"
6550 );
6551
6552 let mut status = Status::new();
6553 status.current = vec![Current {
6554 task: "20260903-080340-0167".to_owned(),
6555 run: mine.to_owned(),
6556 }];
6557 status.updated_at = now;
6558 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6559 assert!(is_working_on(dir.path(), mine, now));
6560 assert!(
6561 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
6562 "a daemon busy with one run is not working on another"
6563 );
6564
6565 status.updated_at = now - jiff::SignedDuration::from_secs(600);
6568 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6569 assert!(
6570 !is_working_on(dir.path(), mine, now),
6571 "a stale heartbeat is a dead daemon, so its run is a leftover"
6572 );
6573 }
6574
6575 #[test]
6576 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
6577 let dir = tempfile::tempdir().unwrap();
6578 let now = Timestamp::now();
6579
6580 assert!(
6581 !is_working_on_short(dir.path(), "01c2", now),
6582 "no status file means nobody is working on anything"
6583 );
6584
6585 let mut status = Status::new();
6586 status.current = vec![Current {
6587 task: "20260903-080340-0167".to_owned(),
6588 run: "20260903-080619-01c2".to_owned(),
6589 }];
6590 status.updated_at = now;
6591 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6592 assert!(
6593 is_working_on_short(dir.path(), "01c2", now),
6594 "the run's short id is the last block of its full id"
6595 );
6596 assert!(
6597 !is_working_on_short(dir.path(), "3cbf", now),
6598 "a daemon busy with one worktree bay is not working on another"
6599 );
6600 }
6601
6602 #[test]
6603 fn a_newer_status_file_still_yields_a_reading() {
6604 let dir = tempfile::tempdir().unwrap();
6605 std::fs::write(
6608 dir.path().join("daemon.json"),
6609 serde_json::json!({
6610 "schema": 2,
6611 "updated_at": Timestamp::now().to_string(),
6612 "idle": true,
6613 "surprise": { "nested": [1, 2, 3] },
6614 })
6615 .to_string(),
6616 )
6617 .unwrap();
6618
6619 let reading = read_status(dir.path()).expect("a forward-compatible read");
6620 assert!(reading.running(Timestamp::now()));
6621 assert!(reading.idle);
6622 assert!(reading.current.is_empty());
6623 }
6624
6625 #[test]
6626 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
6627 let dir = tempfile::tempdir().unwrap();
6633 std::fs::write(
6634 dir.path().join("daemon.json"),
6635 serde_json::json!({
6636 "schema": 1,
6637 "pid": 4242,
6638 "updated_at": Timestamp::now().to_string(),
6639 "idle": false,
6640 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
6641 "completed": 3,
6642 "polls": 9,
6643 })
6644 .to_string(),
6645 )
6646 .unwrap();
6647
6648 let reading = read_status(dir.path()).expect("an older shape must still parse");
6649 assert!(reading.running(Timestamp::now()));
6650 assert_eq!(
6651 reading.current,
6652 vec![Current {
6653 task: "20260902-140501-aaaa".to_owned(),
6654 run: "20260902-140502-bbbb".to_owned(),
6655 }]
6656 );
6657 }
6658
6659 #[test]
6660 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
6661 let dir = tempfile::tempdir().unwrap();
6662 std::fs::write(
6663 dir.path().join("daemon.json"),
6664 serde_json::json!({
6665 "schema": 1,
6666 "updated_at": Timestamp::now().to_string(),
6667 "idle": true,
6668 "current": null,
6669 })
6670 .to_string(),
6671 )
6672 .unwrap();
6673 let with_null = read_status(dir.path()).expect("null must still parse");
6674 assert!(with_null.current.is_empty());
6675
6676 std::fs::write(
6677 dir.path().join("daemon.json"),
6678 serde_json::json!({
6679 "schema": 1,
6680 "updated_at": Timestamp::now().to_string(),
6681 "idle": true,
6682 })
6683 .to_string(),
6684 )
6685 .unwrap();
6686 let absent = read_status(dir.path()).expect("a missing field must still parse");
6687 assert!(absent.current.is_empty());
6688 }
6689
6690 #[test]
6691 fn a_task_without_a_repository_runs_in_the_daemons_default() {
6692 let fallback = Path::new("/default");
6693 let mut blank = task();
6694 blank.repo = PathBuf::new();
6695 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
6696 let mut dot = task();
6697 dot.repo = PathBuf::from(".");
6698 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
6699 assert_eq!(
6700 repo_for(&task(), fallback),
6701 PathBuf::from("/repo"),
6702 "a task that names a repository keeps it"
6703 );
6704 }
6705
6706 #[test]
6707 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
6708 let mut solo_cfg = Config::default();
6714 solo_cfg.graph.implementers = 3;
6715 let mut solo_task = task();
6716 solo_task.solo = true;
6717 apply_solo(&mut solo_cfg, &solo_task);
6718 assert_eq!(solo_cfg.graph.implementers, 1);
6719
6720 let mut plain_cfg = Config::default();
6721 plain_cfg.graph.implementers = 3;
6722 let plain_task = task();
6723 assert!(!plain_task.solo);
6724 apply_solo(&mut plain_cfg, &plain_task);
6725 assert_eq!(
6726 plain_cfg.graph.implementers, 3,
6727 "a task that did not ask to run alone keeps the config's candidates"
6728 );
6729 }
6730
6731 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
6732 QuotaLoss {
6733 seat: seat.into(),
6734 node: "judge".into(),
6735 at: at.parse().unwrap(),
6736 reset: reset.map(str::to_string),
6737 }
6738 }
6739
6740 #[test]
6741 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
6742 let old: Vec<QuotaLoss> = (1..=4)
6743 .map(|i| {
6744 loss(
6745 &format!("judge-{i}"),
6746 "2026-09-23T05:23:00Z",
6747 Some("2:40pm (Asia/Tokyo)"),
6748 )
6749 })
6750 .collect();
6751 let fresh = losses_this_attempt(&old, &old);
6752 assert!(fresh.is_empty());
6753 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
6754 }
6756
6757 #[test]
6758 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
6759 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
6760 let now = Timestamp::now();
6761 let mut after = old.clone();
6762 after.push(loss("judge-2", &now.to_string(), None));
6763 let fresh = losses_this_attempt(&old, &after);
6764 assert_eq!(fresh, vec![after[1].clone()]);
6765 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
6766 assert_eq!(
6767 until,
6768 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
6769 );
6770 }
6771
6772 #[test]
6773 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
6774 let before = vec![
6777 loss("judge-1", "2026-09-23T05:23:00Z", None),
6778 loss("judge-2", "2026-09-23T05:24:00Z", None),
6779 ];
6780 let after = vec![
6781 loss("judge-2", "2026-09-23T05:24:00Z", None),
6782 loss("judge-1", "2026-09-24T01:00:00Z", None),
6783 ];
6784 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
6785 }
6786
6787 #[test]
6788 fn merge_overrides_are_parsed_or_refused() {
6789 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
6790 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
6791 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
6792 assert!(merge_mode("squash").is_err());
6793 }
6794
6795 #[test]
6796 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
6797 let now = Timestamp::now();
6798 let fallback = Duration::from_secs(300);
6799 let cap = Duration::from_secs(1800);
6800
6801 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
6803
6804 let soon = now + jiff::SignedDuration::from_secs(600);
6806 assert_eq!(
6807 quota_wait(Some(soon), now, fallback, cap),
6808 Duration::from_secs(600)
6809 );
6810
6811 let past = now - jiff::SignedDuration::from_secs(60);
6814 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
6815
6816 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
6819 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
6820 }
6821
6822 #[test]
6823 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
6824 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6825
6826 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
6827 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
6828
6829 let already_past =
6833 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
6834 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
6835
6836 assert!(
6837 parse_reset_hint("session limit reached", now, now).is_none(),
6838 "free text with no recognised shape is not guessed at"
6839 );
6840 assert!(
6841 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
6842 "an unresolvable zone name is not guessed at either"
6843 );
6844 }
6845
6846 #[test]
6847 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
6848 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6849
6850 let at = parse_reset_hint(
6851 "You've hit your usage limit. Visit \
6852 https://chatgpt.com/codex/settings/usage to purchase more \
6853 credits or try again at Sep 19th, 2026 5:10 PM.",
6854 now,
6855 now,
6856 )
6857 .expect("the codex reset wording is a recognised shape");
6858 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
6859
6860 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
6865 .expect("an explicit year needs no rollover");
6866 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
6867
6868 assert!(
6869 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
6870 "a two-digit year is not the documented shape and is not guessed at"
6871 );
6872 assert!(
6873 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
6874 "a four-letter month name is not the documented three-letter abbreviation"
6875 );
6876 assert!(
6877 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
6878 "an explicit zone on the dated shape is a format nobody has \
6879 documented, and is refused rather than guessed at as UTC"
6880 );
6881 }
6882
6883 #[test]
6884 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
6885 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
6886 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
6887
6888 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
6889 assert_eq!(at.as_second() - recorded.as_second(), 3769);
6890
6891 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
6892 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
6893
6894 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
6895 assert!(
6896 parse_reset_hint(bad, now, recorded).is_none(),
6897 "{bad:?} must not be guessed at"
6898 );
6899 }
6900 }
6901
6902 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
6906 let config = dir.join("magi.toml");
6907 std::fs::write(
6908 &config,
6909 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
6910 )
6911 .unwrap();
6912 let opts = Opts {
6913 poll: Duration::from_secs(30),
6914 config: Some(config),
6915 repo: dir.join("repo"),
6919 ..Opts::default()
6920 };
6921 let home = dir.join("home");
6930 let worktrees = dir.join("wt");
6931 (
6932 opts,
6933 Queue::at(dir.join("queue")),
6934 home.join("daemon.json"),
6935 home,
6936 worktrees,
6937 )
6938 }
6939
6940 #[test]
6941 fn a_stop_is_idempotent_and_once_set_stays_set() {
6942 let stop = Stop::new();
6943 assert!(!stop.stopped());
6944
6945 stop.stop();
6946 assert!(stop.stopped());
6947 stop.stop();
6948 assert!(stop.stopped(), "a second stop is not a toggle");
6949
6950 let shared = stop.clone();
6951 assert!(
6952 shared.stopped(),
6953 "a clone is the same stop; that is how the loop and its caller share one"
6954 );
6955 }
6956
6957 #[test]
6958 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
6959 let stop = Stop::new();
6960 stop.enter();
6961 assert!(
6962 !stop.finishing(),
6963 "a busy loop nobody has asked to stop is just running"
6964 );
6965
6966 stop.stop();
6967 assert!(
6968 stop.finishing(),
6969 "a stop asked for mid-run has not landed until the run is settled"
6970 );
6971
6972 stop.exit();
6973 assert!(
6974 !stop.finishing(),
6975 "once the run is settled the stop has landed and there is nothing to finish"
6976 );
6977 }
6978
6979 #[test]
6980 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6981 let stop = Stop::new();
6982 stop.enter();
6983 stop.enter();
6984 stop.stop();
6985 assert!(stop.finishing(), "two runs still in flight");
6986
6987 stop.exit();
6988 assert!(
6989 stop.finishing(),
6990 "one run finished, but a sibling is still working"
6991 );
6992
6993 stop.exit();
6994 assert!(
6995 !stop.finishing(),
6996 "the last run out is what actually lands the stop"
6997 );
6998 }
6999
7000 #[tokio::test]
7001 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
7002 let dir = tempfile::tempdir().unwrap();
7003 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7004 let stop = Stop::new();
7005 stop.stop();
7006
7007 let began = std::time::Instant::now();
7008 tokio::time::timeout(
7009 Duration::from_secs(2),
7010 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7011 )
7012 .await
7013 .expect("a stopped loop must return, not sit out its poll interval")
7014 .expect("the loop's own setup and teardown must not fail");
7015 assert!(
7016 began.elapsed() < opts.poll,
7017 "returned only after {:?}, which is a poll interval, not a stop",
7018 began.elapsed()
7019 );
7020 }
7021
7022 #[tokio::test]
7023 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
7024 let dir = tempfile::tempdir().unwrap();
7025 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7026 let stop = Stop::new();
7027
7028 let asker = {
7031 let stop = stop.clone();
7032 tokio::spawn(async move {
7033 tokio::time::sleep(Duration::from_millis(20)).await;
7034 stop.stop();
7035 })
7036 };
7037
7038 let began = std::time::Instant::now();
7039 tokio::time::timeout(
7040 Duration::from_secs(2),
7041 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7042 )
7043 .await
7044 .expect("a stop asked for while idle must wake the wait")
7045 .expect("the loop's own setup and teardown must not fail");
7046 asker.await.unwrap();
7047 assert!(
7048 began.elapsed() < opts.poll,
7049 "returned only after {:?}, so the stop waited on the sleep",
7050 began.elapsed()
7051 );
7052 }
7053
7054 #[tokio::test]
7055 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
7056 let dir = tempfile::tempdir().unwrap();
7057 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7058 let stop = Stop::new();
7059 stop.stop();
7060
7061 tokio::time::timeout(
7062 Duration::from_secs(2),
7063 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7064 )
7065 .await
7066 .expect("a stopped loop must return")
7067 .expect("the loop's own setup and teardown must not fail");
7068
7069 assert!(
7070 home.is_dir(),
7071 "the loop did publish a status file, so its removal is the teardown and not an absence"
7072 );
7073 assert!(
7074 !status_file.exists(),
7075 "a stopped loop clears its status file"
7076 );
7077 assert!(
7078 read_status(&home).is_none(),
7079 "a reader must see no daemon at all, not a heartbeat that merely stopped"
7080 );
7081 }
7082
7083 #[tokio::test]
7084 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
7085 let dir = tempfile::tempdir().unwrap();
7086 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7087 opts.once = true;
7088
7089 let mut settled = RunState::new(
7090 dir.path().join("repo"),
7091 "main".to_owned(),
7092 "abc1234".to_owned(),
7093 "fixture".to_owned(),
7094 Config::default(),
7095 );
7096 settled.status = RunStatus::Ready;
7097 let run_dir = home.join("runs").join(&settled.id);
7098 std::fs::create_dir_all(&run_dir).unwrap();
7099 std::fs::write(
7100 run_dir.join("run.json"),
7101 serde_json::to_string_pretty(&settled).unwrap(),
7102 )
7103 .unwrap();
7104 let questions = Questions::at(home.join("questions"));
7105 let mut question = ask::Question::new(
7106 settled.id.clone(),
7107 "review".to_owned(),
7108 "reviewer-1".to_owned(),
7109 "Continue?".to_owned(),
7110 String::new(),
7111 Vec::new(),
7112 );
7113 questions.put(&mut question).unwrap();
7114
7115 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
7116 .await
7117 .unwrap();
7118
7119 assert_eq!(
7120 questions.get(&question.id).unwrap().status,
7121 ask::QuestionStatus::Abandoned,
7122 "an empty --once drain still performs startup question cleanup"
7123 );
7124 }
7125
7126 #[test]
7127 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
7128 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7129
7130 assert!(
7131 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
7132 "never checked before: due at once"
7133 );
7134
7135 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
7136 assert!(
7137 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
7138 "well inside the interval: not due yet"
7139 );
7140
7141 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
7142 assert!(
7143 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
7144 "exactly at the edge: not yet due, same convention as `clean::due`"
7145 );
7146
7147 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7148 assert!(
7149 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
7150 "past the interval: due again"
7151 );
7152 }
7153
7154 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
7159 let config = dir.join("magi.toml");
7160 std::fs::write(
7166 &config,
7167 format!(
7168 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7169 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7170 cache_dir.display()
7171 ),
7172 )
7173 .unwrap();
7174 Opts {
7175 config: Some(config),
7176 repo: dir.join("repo"),
7177 ..Opts::default()
7178 }
7179 }
7180
7181 #[tokio::test]
7182 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
7183 let dir = tempfile::tempdir().unwrap();
7184 let home = dir.path().join("home");
7185 let cache_dir = dir.path().join("cache");
7186 std::fs::create_dir_all(&cache_dir).unwrap();
7187 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7188 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7189
7190 let running = Stop::new();
7193 let mut last_checked = None;
7194 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7195 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
7196 .await;
7197 assert_eq!(
7198 crate::disk::dir_size(&cache_dir),
7199 0,
7200 "over the cap on the first check ever: pruned at once, no idle queue required"
7201 );
7202 assert_eq!(last_checked, Some(t0));
7203
7204 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
7206 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
7207 maybe_prune_cache_between_runs(
7208 &opts.repo,
7209 &opts,
7210 &home,
7211 &running,
7212 &mut last_checked,
7213 too_soon,
7214 )
7215 .await;
7216 assert_eq!(
7217 crate::disk::dir_size(&cache_dir),
7218 10,
7219 "too soon since the last check: left alone rather than rescanned every call"
7220 );
7221 assert_eq!(
7222 last_checked,
7223 Some(t0),
7224 "an idle check does not reset the clock"
7225 );
7226
7227 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7229 maybe_prune_cache_between_runs(
7230 &opts.repo,
7231 &opts,
7232 &home,
7233 &running,
7234 &mut last_checked,
7235 due_again,
7236 )
7237 .await;
7238 assert_eq!(
7239 crate::disk::dir_size(&cache_dir),
7240 0,
7241 "due again: pruned back under the cap"
7242 );
7243 }
7244
7245 #[tokio::test]
7253 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
7254 let dir = tempfile::tempdir().unwrap();
7255 let home = dir.path().join("home");
7256 let cache_dir = dir.path().join("cache");
7257 std::fs::create_dir_all(&cache_dir).unwrap();
7258 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7259 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7260
7261 let stop = Stop::new();
7262 stop.stop();
7263 assert!(
7264 !stop.finishing(),
7265 "no run is in flight at a between-runs boundary, so nothing else \
7266 would tell the operator this stop had not taken effect yet"
7267 );
7268
7269 let mut last_checked = None;
7270 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7271 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
7272 .await;
7273 assert_eq!(
7274 crate::disk::dir_size(&cache_dir),
7275 10,
7276 "over its cap, and due for the first check ever, but a stop outranks \
7277 it: the cap is a standing policy the next start measures again"
7278 );
7279 assert_eq!(
7280 last_checked, None,
7281 "a check that never happened must not claim the interval"
7282 );
7283 }
7284
7285 #[tokio::test]
7299 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
7300 let dir = tempfile::tempdir().unwrap();
7301 let cache_dir = dir.path().join("cache");
7302 std::fs::create_dir_all(&cache_dir).unwrap();
7303 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
7304
7305 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
7306 opts.poll = Duration::from_millis(20);
7307 opts.max_attempts = 1_000;
7308
7309 let queue = Queue::at(dir.path().join("queue"));
7310 let mut t = Task::new(
7311 "x".to_owned(),
7312 "x".to_owned(),
7313 opts.repo.clone(),
7314 Source::Human,
7315 );
7316 queue.put(&mut t).unwrap();
7317
7318 let home = dir.path().join("home");
7319 let worktrees = dir.path().join("wt");
7320 let status_file = home.join("daemon.json");
7321 let stop = Stop::new();
7322 let stopper = {
7323 let stop = stop.clone();
7324 let queue = Queue::at(dir.path().join("queue"));
7325 let id = t.id.clone();
7326 tokio::spawn(async move {
7327 tokio::time::sleep(Duration::from_millis(400)).await;
7331 for _ in 0..200 {
7332 if queue.get(&id).is_ok_and(|t| t.attempts >= 2) {
7333 break;
7334 }
7335 tokio::time::sleep(Duration::from_millis(50)).await;
7336 }
7337 stop.stop();
7338 })
7339 };
7340
7341 tokio::time::timeout(
7342 Duration::from_secs(20),
7343 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7344 )
7345 .await
7346 .expect("the loop must not hang on a queue that keeps producing failing work")
7347 .expect("the loop's own setup and teardown must not fail");
7348 stopper.await.unwrap();
7349
7350 let after = queue.get(&t.id).unwrap();
7351 assert!(
7352 after.attempts >= 2,
7353 "the harness must actually have retried more than once, or this is not \
7354 exercising a busy queue at all (got {} attempt(s))",
7355 after.attempts
7356 );
7357 assert!(
7358 after.status.runnable(),
7359 "still under its attempt budget: the queue never reached a natural idle \
7360 on its own, only the external stop ended the test"
7361 );
7362
7363 assert_eq!(
7364 crate::disk::dir_size(&cache_dir),
7365 0,
7366 "an oversized cache must not be left to grow unboundedly just because the \
7367 queue kept the loop busy the whole time"
7368 );
7369 }
7370
7371 #[test]
7372 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
7373 let dir = tempfile::tempdir().unwrap();
7374 let queue = Queue::at(dir.path().join("queue"));
7375 let questions = Questions::at(dir.path().join("questions"));
7376 let mut task = task();
7377 queue.put(&mut task).unwrap();
7378
7379 let mut task_question = ask::Question::new(
7380 task.id.clone(),
7381 crate::conduct::NODE.to_owned(),
7382 "conduct".to_owned(),
7383 "Which backend?".to_owned(),
7384 String::new(),
7385 Vec::new(),
7386 );
7387 questions.put(&mut task_question).unwrap();
7388 task.block(vec![task_question.id.clone()], None);
7389 queue.put(&mut task).unwrap();
7390
7391 let mut run_question = ask::Question::new(
7392 "20260101-000000-run1".to_owned(),
7393 "review".to_owned(),
7394 "reviewer-1".to_owned(),
7395 "Run question".to_owned(),
7396 String::new(),
7397 Vec::new(),
7398 );
7399 questions.put(&mut run_question).unwrap();
7400
7401 let mut coincidental = ask::Question::new(
7406 task.id.clone(),
7407 "review".to_owned(),
7408 "reviewer-1".to_owned(),
7409 "Unrelated review question".to_owned(),
7410 String::new(),
7411 Vec::new(),
7412 );
7413 questions.put(&mut coincidental).unwrap();
7414
7415 reconcile_task_questions(&queue, &questions);
7416 assert!(questions.get(&task_question.id).unwrap().status.open());
7417 assert!(questions.get(&run_question.id).unwrap().status.open());
7418 assert!(questions.get(&coincidental.id).unwrap().status.open());
7419
7420 task.release();
7421 queue.put(&mut task).unwrap();
7422 reconcile_task_questions(&queue, &questions);
7423 assert_eq!(
7424 questions.get(&task_question.id).unwrap().status,
7425 ask::QuestionStatus::Abandoned
7426 );
7427 assert!(
7428 questions.get(&run_question.id).unwrap().status.open(),
7429 "run questions remain the run janitor's responsibility"
7430 );
7431 assert!(
7432 questions.get(&coincidental.id).unwrap().status.open(),
7433 "a non-conductor question must not be abandoned just because its \
7434 run id coincides with a task id"
7435 );
7436 }
7437
7438 #[test]
7439 fn a_freshly_started_running_task_is_never_stalled() {
7440 let dir = tempfile::tempdir().unwrap();
7441 let mut t = task();
7442 t.start("run-1".to_owned());
7443 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
7446 }
7447
7448 #[test]
7449 fn a_long_running_task_with_no_live_daemon_is_stalled() {
7450 let dir = tempfile::tempdir().unwrap();
7451 let mut t = task();
7452 t.start("run-1".to_owned());
7453 t.updated_at = Timestamp::now()
7454 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7455 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
7456 assert_eq!(
7457 stalled_tasks(
7458 &Queue::at(dir.path().join("q")),
7459 dir.path(),
7460 Timestamp::now()
7461 )
7462 .len(),
7463 0,
7464 "the task was never written to this queue"
7465 );
7466 }
7467
7468 #[test]
7469 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
7470 let dir = tempfile::tempdir().unwrap();
7471 let mut t = task();
7472 t.id = "20260903-080340-0167".to_owned();
7473 t.start("20260903-080619-01c2".to_owned());
7474 t.updated_at = Timestamp::now()
7475 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7476
7477 let mut status = Status::new();
7478 status.current = vec![Current {
7479 task: t.id.clone(),
7480 run: "20260903-080619-01c2".to_owned(),
7481 }];
7482 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7483
7484 assert!(
7485 !is_stalled(&t, dir.path(), Timestamp::now()),
7486 "a live daemon's own heartbeat rules out stalled, however long the task has run"
7487 );
7488 }
7489
7490 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
7494 let path = queue.path_of(id);
7495 let body = std::fs::read_to_string(&path).unwrap();
7496 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
7497 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
7498 v["updated_at"] = serde_json::Value::String(old.to_string());
7499 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
7500 }
7501
7502 #[test]
7503 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
7504 let dir = tempfile::tempdir().unwrap();
7517 let queue = Queue::at(dir.path().join("queue"));
7518 let home = dir.path().join("home");
7519
7520 let mut t = task();
7521 t.id = "20260101-000001-lock".to_owned();
7522 t.start("run-1".to_owned());
7523 queue.put(&mut t).unwrap();
7524 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7525 std::fs::write(
7526 dir.path().join("queue").join(format!("{}.lock", t.id)),
7527 "not a pid",
7528 )
7529 .unwrap();
7530
7531 let now = Timestamp::now();
7532 assert!(
7533 reclaim_orphaned_running(&queue, 2).is_empty(),
7534 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
7535 and reclaim must leave the task alone"
7536 );
7537 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7538
7539 let stalled = stalled_tasks(&queue, &home, now);
7540 assert_eq!(
7541 stalled.len(),
7542 1,
7543 "reclaim's inability to claim it yet must not hide it from the conductor"
7544 );
7545 assert_eq!(stalled[0].id, t.id);
7546 }
7547
7548 #[test]
7549 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
7550 let dir = tempfile::tempdir().unwrap();
7551 crate::run::set_home(dir.path().join("run-home"));
7552 let queue = Queue::at(dir.path().join("queue"));
7553 let home = dir.path().join("home");
7554 let questions = Questions::at(dir.path().join("questions"));
7555
7556 let mut t = task();
7557 t.id = "20260101-000003-dead".to_owned();
7558 t.start("missing-run".to_owned());
7559 queue.put(&mut t).unwrap();
7560 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7561
7562 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7565 assert_eq!(
7566 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
7567 [&t.id]
7568 );
7569 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
7570 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7571
7572 crate::conduct::apply(
7575 &queue,
7576 &questions,
7577 &crate::conduct::Verdict {
7578 decisions: vec![crate::conduct::Decision {
7579 id: t.id.clone(),
7580 recovery: Some(crate::conduct::Recovery::Requeue),
7581 ..crate::conduct::Decision::default()
7582 }],
7583 },
7584 )
7585 .unwrap();
7586 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7587 }
7588
7589 #[test]
7590 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
7591 let dir = tempfile::tempdir().unwrap();
7592 let queue = Queue::at(dir.path().join("queue"));
7593 let home = dir.path().join("home");
7594
7595 let mut fresh = task();
7596 fresh.id = "20260101-000001-aaaa".to_owned();
7597 fresh.start("run-1".to_owned());
7598 queue.put(&mut fresh).unwrap();
7599
7600 let mut old = task();
7601 old.id = "20260101-000002-bbbb".to_owned();
7602 old.start("run-2".to_owned());
7603 queue.put(&mut old).unwrap();
7604 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
7605
7606 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7607 assert_eq!(stalled.len(), 1);
7608 assert_eq!(stalled[0].id, old.id);
7609 }
7610
7611 #[test]
7612 fn queued_and_finished_task_views_partition_by_status() {
7613 let dir = tempfile::tempdir().unwrap();
7614 let queue = Queue::at(dir.path().join("queue"));
7615
7616 let mut queued = task();
7617 queued.id = "20260101-000001-aaaa".to_owned();
7618 queue.put(&mut queued).unwrap();
7619
7620 let mut failed = task();
7621 failed.id = "20260101-000002-bbbb".to_owned();
7622 failed.start("run-1".to_owned());
7623 failed.fail("gate red", 5);
7624 queue.put(&mut failed).unwrap();
7625
7626 let mut held = task();
7627 held.id = "20260101-000003-cccc".to_owned();
7628 held.hold_machine(None);
7629 queue.put(&mut held).unwrap();
7630
7631 let mut running = task();
7632 running.id = "20260101-000004-dddd".to_owned();
7633 running.start("run-2".to_owned());
7634 queue.put(&mut running).unwrap();
7635
7636 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
7637 assert_eq!(queued_ids, [queued.id.clone()]);
7638
7639 let mut finished_ids: Vec<String> =
7640 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
7641 finished_ids.sort_unstable();
7642 let mut want = vec![failed.id.clone(), held.id.clone()];
7643 want.sort_unstable();
7644 assert_eq!(finished_ids, want);
7645 }
7646
7647 #[test]
7648 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
7649 let dir = tempfile::tempdir().unwrap();
7650 let queue = Queue::at(dir.path().join("queue"));
7651 let questions = ask::Questions::at(dir.path().join("questions"));
7652
7653 let mut dep = task();
7654 dep.id = "20260101-000001-dep0".to_owned();
7655 dep.succeed();
7656 queue.put(&mut dep).unwrap();
7657
7658 let mut still_going = task();
7659 still_going.id = "20260101-000002-dep1".to_owned();
7660 queue.put(&mut still_going).unwrap();
7661
7662 let mut blocked = task();
7663 blocked.id = "20260101-000003-main".to_owned();
7664 blocked.block(
7665 vec![dep.id.clone(), still_going.id.clone()],
7666 Some("waits on both".to_owned()),
7667 );
7668 queue.put(&mut blocked).unwrap();
7669
7670 resolve_blockers(&queue, &questions);
7671
7672 let after = queue.get(&blocked.id).unwrap();
7673 assert_eq!(
7674 after.status,
7675 TaskStatus::Blocked,
7676 "one dependency is still outstanding"
7677 );
7678 assert_eq!(after.blocked_by, [still_going.id.clone()]);
7679 }
7680
7681 #[test]
7682 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
7683 let dir = tempfile::tempdir().unwrap();
7684 let queue = Queue::at(dir.path().join("queue"));
7685 let questions = ask::Questions::at(dir.path().join("questions"));
7686
7687 let mut q = crate::ask::Question::new(
7688 "20260101-000001-main".to_owned(),
7689 crate::conduct::NODE.to_owned(),
7690 "conduct".to_owned(),
7691 "Which backend?".to_owned(),
7692 String::new(),
7693 Vec::new(),
7694 );
7695 questions.put(&mut q).unwrap();
7696 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
7697 .unwrap();
7698 questions.put(&mut q).unwrap();
7699
7700 let mut blocked = task();
7701 blocked.id = "20260101-000001-main".to_owned();
7702 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
7703 queue.put(&mut blocked).unwrap();
7704
7705 resolve_blockers(&queue, &questions);
7706
7707 let after = queue.get(&blocked.id).unwrap();
7708 assert_eq!(
7709 after.status,
7710 TaskStatus::Queued,
7711 "the only blocker resolved"
7712 );
7713 assert_eq!(after.answers.len(), 1);
7714 assert_eq!(after.answers[0].question, "Which backend?");
7715 assert_eq!(after.answers[0].answer, "SQLite");
7716
7717 let instruction = instruction_for(&after);
7719 assert!(instruction.contains("Which backend?"));
7720 assert!(instruction.contains("SQLite"));
7721 }
7722
7723 #[test]
7724 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
7725 let dir = tempfile::tempdir().unwrap();
7726 let queue = Queue::at(dir.path().join("queue"));
7727 let questions = ask::Questions::at(dir.path().join("questions"));
7728
7729 let mut q = crate::ask::Question::new(
7730 "20260101-000001-main".to_owned(),
7731 crate::conduct::NODE.to_owned(),
7732 "conduct".to_owned(),
7733 "Is the setup done?".to_owned(),
7734 String::new(),
7735 Vec::new(),
7736 );
7737 q.abandon("no answer within 60s of asking");
7738 questions.put(&mut q).unwrap();
7739
7740 let mut blocked = task();
7741 blocked.id = "20260101-000001-main".to_owned();
7742 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
7743 queue.put(&mut blocked).unwrap();
7744
7745 resolve_blockers(&queue, &questions);
7746
7747 let after = queue.get(&blocked.id).unwrap();
7748 assert_eq!(
7749 after.status,
7750 TaskStatus::Held,
7751 "never left blocked on nothing"
7752 );
7753 assert!(!after.operator_held(), "a machine hold, for triage");
7754 assert!(
7755 after
7756 .hold_reason
7757 .as_deref()
7758 .unwrap_or_default()
7759 .contains("went unanswered")
7760 );
7761 }
7762
7763 #[test]
7764 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
7765 let dir = tempfile::tempdir().unwrap();
7771 let queue = Queue::at(dir.path().join("queue"));
7772 let questions = ask::Questions::at(dir.path().join("questions"));
7773
7774 let mut q = crate::ask::Question::new(
7775 "20260101-000001-main".to_owned(),
7776 crate::conduct::NODE.to_owned(),
7777 "conduct".to_owned(),
7778 "How should this be handled?".to_owned(),
7779 String::new(),
7780 Vec::new(),
7781 );
7782 questions.put(&mut q).unwrap();
7783 q.answer(crate::ask::Answer::Text(
7784 "leave it held, a human will look at it later".to_owned(),
7785 ))
7786 .unwrap();
7787 questions.put(&mut q).unwrap();
7788
7789 let mut held = task();
7790 held.id = "20260101-000001-main".to_owned();
7791 held.hold_machine(Some("out of attempts".to_owned()));
7792 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
7793 queue.put(&mut held).unwrap();
7794
7795 resolve_blockers(&queue, &questions);
7796
7797 let after = queue.get(&held.id).unwrap();
7798 assert_eq!(after.status, TaskStatus::Held);
7799 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
7800 assert_eq!(
7801 after.answers[0].answer,
7802 "leave it held, a human will look at it later"
7803 );
7804 }
7805
7806 #[test]
7807 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
7808 let dir = tempfile::tempdir().unwrap();
7809 let queue = Queue::at(dir.path().join("queue"));
7810 let questions = ask::Questions::at(dir.path().join("questions"));
7811 let mut dep = task();
7812 dep.id = "20260101-000001-gone".to_owned();
7813 queue.put(&mut dep).unwrap();
7814 let mut blocked = task();
7815 blocked.id = "20260101-000003-main".to_owned();
7816 blocked.block(vec![dep.id.clone()], None);
7817 queue.put(&mut blocked).unwrap();
7818
7819 let claim = queue.claim(&blocked.id).unwrap();
7821 queue.remove(&dep.id, false, &questions).unwrap();
7822 drop(claim);
7823 resolve_blockers(&queue, &questions);
7824
7825 let after = queue.get(&blocked.id).unwrap();
7826 assert_eq!(after.status, TaskStatus::Queued);
7827 assert!(after.blocked_by.is_empty());
7828 }
7829
7830 #[test]
7831 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
7832 let dir = tempfile::tempdir().unwrap();
7838 let queue = Queue::at(dir.path().join("queue"));
7839 let questions = ask::Questions::at(dir.path().join("questions"));
7840
7841 let mut still_going = task();
7842 still_going.id = "20260101-000002-dep1".to_owned();
7843 queue.put(&mut still_going).unwrap();
7844
7845 let mut blocked = task();
7846 blocked.id = "20260101-000003-main".to_owned();
7847 blocked.block(
7848 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
7849 Some("waits on both".to_owned()),
7850 );
7851 queue.put(&mut blocked).unwrap();
7852
7853 resolve_blockers(&queue, &questions);
7854
7855 let after = queue.get(&blocked.id).unwrap();
7856 assert_eq!(
7857 after.status,
7858 TaskStatus::Held,
7859 "a missing dependency must not leave the task blocked forever"
7860 );
7861 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
7862 assert!(after.blocked_by.is_empty());
7863 let reason = after.hold_reason.as_deref().unwrap_or_default();
7864 assert!(
7865 reason.contains("20260101-000001-gone"),
7866 "the missing id must be named so an operator can tell what happened: {reason}"
7867 );
7868 assert!(
7869 reason.contains(&still_going.id),
7870 "the still-valid dependency must not silently vanish from the record: {reason}"
7871 );
7872 }
7873
7874 #[test]
7875 fn instruction_for_is_unchanged_without_any_answers() {
7876 let t = task();
7877 assert_eq!(instruction_for(&t), t.instruction);
7878 }
7879
7880 #[test]
7881 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
7882 let dir = tempfile::tempdir().unwrap();
7883 let q = Queue::at(dir.path().join("queue"));
7884 let src = dir.path().join("shot.png");
7885 std::fs::write(&src, "x").unwrap();
7886 let mut t = task();
7887 q.attach(&mut t, &[src]).unwrap();
7888 let paths = task_attachments(&q, &t).unwrap();
7889 assert_eq!(paths.len(), 1);
7890 assert!(paths[0].is_absolute() && paths[0].is_file());
7891 std::fs::remove_file(&paths[0]).unwrap();
7892 let err = task_attachments(&q, &t).unwrap_err().to_string();
7893 assert!(err.contains("shot.png"), "{err}");
7894 }
7895
7896 #[test]
7897 fn resumed_instruction_is_unchanged_without_any_answers() {
7898 let t = task();
7899 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
7900 }
7901
7902 #[test]
7903 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
7904 let mut t = task();
7905 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7906 let old = t.instruction.clone();
7910
7911 let refreshed = resumed_instruction(&old, &t);
7912 assert!(refreshed.starts_with(&old), "the original text is kept");
7913 assert!(refreshed.contains("Which backend?"));
7914 assert!(refreshed.contains("SQLite"));
7915 }
7916
7917 #[test]
7918 fn resumed_instruction_keeps_an_original_answers_heading() {
7919 let mut t = task();
7920 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
7921 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7922
7923 let refreshed = resumed_instruction(&t.instruction, &t);
7924
7925 assert!(
7926 refreshed.starts_with(&t.instruction),
7927 "an answers heading in the original instruction is not the appended block"
7928 );
7929 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
7930 assert!(refreshed.contains("Which backend?"));
7931 assert!(refreshed.contains("SQLite"));
7932
7933 let repeated = resumed_instruction(&refreshed, &t);
7934 assert_eq!(
7935 repeated, refreshed,
7936 "only the final appended block is refreshed"
7937 );
7938 }
7939
7940 #[test]
7941 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
7942 let mut t = task();
7943 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7944
7945 let once = resumed_instruction(&t.instruction, &t);
7949 let twice = resumed_instruction(&once, &t);
7950 assert_eq!(once, twice);
7951 assert_eq!(once.matches("Which backend?").count(), 1);
7952
7953 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
7955 let refreshed = resumed_instruction(&once, &t);
7956 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
7957 assert!(refreshed.contains("Which backend?"));
7958 assert!(refreshed.contains("Which cache?"));
7959 }
7960
7961 #[test]
7962 fn prepare_instruction_covers_all_three_starters() {
7963 let mut t = task();
7964 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7965
7966 assert_eq!(
7969 prepare_instruction(&Starter::Start, None, &t),
7970 Some(instruction_for(&t))
7971 );
7972
7973 let old = t.instruction.clone();
7976 assert_eq!(
7977 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
7978 Some(resumed_instruction(&old, &t))
7979 );
7980
7981 assert_eq!(
7985 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
7986 None
7987 );
7988 }
7989
7990 #[test]
7991 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
7992 assert_eq!(
7993 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
7994 Starter::Review("magi/eba2/A".to_owned())
7995 );
7996 }
7997
7998 #[test]
7999 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
8000 assert_eq!(
8001 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
8002 Starter::Start,
8003 "a vanished review branch must not fall back to resuming the old run either"
8004 );
8005 }
8006
8007 #[test]
8008 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
8009 let mut t = task();
8010 t.start("old-run".to_owned());
8011 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
8012 t.release();
8013 let branch = t.review_branch.take();
8014 assert_eq!(
8015 choose_starter(branch.as_deref(), true, Some("old-run")),
8016 Starter::Review("magi/eba2/A".to_owned()),
8017 "a review wins over resuming the old run"
8018 );
8019 }
8020
8021 #[test]
8022 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
8023 assert_eq!(
8024 choose_starter(None, false, Some("some-run")),
8025 Starter::Resume("some-run".to_owned())
8026 );
8027 assert_eq!(choose_starter(None, false, None), Starter::Start);
8028 }
8029
8030 #[test]
8031 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
8032 let mut released = task();
8033 released.start("stalled-run".to_owned());
8034 released.requeue();
8035 let unfinished = (!released.fresh_start)
8036 .then(|| Some("stalled-run".to_owned()))
8037 .flatten();
8038 assert_eq!(
8039 choose_starter(None, false, unfinished.as_deref()),
8040 Starter::Start,
8041 "release keeps run history but must not resume it"
8042 );
8043 assert_eq!(released.runs, ["stalled-run"]);
8044 }
8045
8046 #[test]
8047 fn an_ordinary_release_keeps_a_resumable_run_available() {
8048 let mut released = task();
8049 released.start("stalled-run".to_owned());
8050 released.release();
8051 let unfinished = (!released.fresh_start)
8052 .then(|| Some("stalled-run".to_owned()))
8053 .flatten();
8054 assert_eq!(
8055 choose_starter(None, false, unfinished.as_deref()),
8056 Starter::Resume("stalled-run".to_owned()),
8057 "manual release must preserve the normal resume path"
8058 );
8059 }
8060
8061 #[test]
8062 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
8063 let mut state = run_state(RunStatus::Blocked);
8064 state.config.graph.review_rounds = 3;
8065 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
8066 assert!(exhausted_review_budget(&state));
8067
8068 state.reviews.pop();
8070 assert!(!exhausted_review_budget(&state));
8071
8072 let mut stalled = run_state(RunStatus::Stalled);
8075 stalled.config.graph.review_rounds = 1;
8076 stalled.reviews = vec![review_round(1)];
8077 assert!(!exhausted_review_budget(&stalled));
8078 }
8079
8080 fn review_round(round: usize) -> crate::run::ReviewRound {
8081 crate::run::ReviewRound {
8082 round,
8083 head: "deadbeef".to_owned(),
8084 verified_head: None,
8085 verified_at: None,
8086 reviews: Vec::new(),
8087 e2e: Vec::new(),
8088 verify_retried: false,
8089 e2e_deferred: false,
8090 e2e_defer_reason: None,
8091 fix: None,
8092 blocking: 0,
8093 answered: 1,
8094 expected: 1,
8095 clean: false,
8096 progressed: true,
8097 vote_split: false,
8098 reconsideration: Vec::new(),
8099 verdict: None,
8100 }
8101 }
8102
8103 #[test]
8104 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
8105 let mut run = RunState::new(
8106 PathBuf::from("/repo"),
8107 "main".to_owned(),
8108 "abc1234def".to_owned(),
8109 "add retries".to_owned(),
8110 Config::default(),
8111 );
8112 run.status = RunStatus::Judging;
8113 run.parked = true;
8114 let mut task = Task::new(
8115 "add retries".to_owned(),
8116 "add retries".to_owned(),
8117 PathBuf::from("/repo"),
8118 crate::queue::Source::Human,
8119 );
8120 task.status = TaskStatus::Failed;
8121 task.runs = vec![run.id.clone()];
8122 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
8123 assert!(with(&task, &run), "parked after judging is the case");
8124 let mut parked_task = task.clone();
8125 parked_task.status = TaskStatus::Parked;
8126 assert!(with(&parked_task, &run), "the Parked status is the case");
8127
8128 let mut not_parked = run.clone();
8129 not_parked.parked = false;
8130 not_parked.status = RunStatus::Stalled;
8131 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
8132
8133 let mut fresh = task.clone();
8134 fresh.fresh_start = true;
8135 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
8136
8137 let mut review = task.clone();
8138 review.review_branch = Some("magi/x/A".to_owned());
8139 assert!(!with(&review, &run), "review is ranked before resume");
8140
8141 let mut held = task.clone();
8142 held.status = TaskStatus::Held;
8143 assert!(!with(&held, &run), "a hold stays visible to the conductor");
8144
8145 let mut released = run.clone();
8146 released.released_to = Some("20260901-000000-new1".to_owned());
8147 assert!(!with(&task, &released), "nothing left to resume into");
8148
8149 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
8150 "unreadable"
8151 )));
8152 }
8153
8154 #[test]
8155 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
8156 let mut released = RunState::new(
8157 PathBuf::from("/repo"),
8158 "main".to_owned(),
8159 "abc1234def".to_owned(),
8160 "add retries".to_owned(),
8161 Config::default(),
8162 );
8163 released.status = RunStatus::Blocked;
8164 assert_eq!(
8165 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8166 Some(released.id.clone())
8167 );
8168 released.released_to = Some("20260901-000000-new1".to_owned());
8169 assert_eq!(
8170 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8171 None,
8172 "there is nothing left to resume it into"
8173 );
8174 }
8175
8176 #[test]
8177 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
8178 let mut exhausted = RunState::new(
8187 PathBuf::from("/repo"),
8188 "main".to_owned(),
8189 "abc1234def".to_owned(),
8190 "add retries".to_owned(),
8191 Config::default(),
8192 );
8193 exhausted.status = RunStatus::Blocked;
8194 exhausted.config.graph.review_rounds = 1;
8195 exhausted.reviews = vec![review_round(1)];
8196
8197 assert_eq!(
8198 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
8199 None,
8200 "an exhausted `Blocked` run must not be offered as resumable"
8201 );
8202
8203 let mut has_budget_left = RunState::new(
8206 PathBuf::from("/repo"),
8207 "main".to_owned(),
8208 "abc1234def".to_owned(),
8209 "add retries".to_owned(),
8210 Config::default(),
8211 );
8212 has_budget_left.status = RunStatus::Blocked;
8213 has_budget_left.config.graph.review_rounds = 3;
8214 has_budget_left.reviews = vec![review_round(1)];
8215
8216 assert_eq!(
8217 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
8218 Ok(has_budget_left.clone())
8219 }),
8220 Some(has_budget_left.id.clone())
8221 );
8222 }
8223
8224 #[test]
8225 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
8226 let mut run = RunState::new(
8227 PathBuf::from("/repo"),
8228 "main".to_owned(),
8229 "abc1234def".to_owned(),
8230 "add retries".to_owned(),
8231 Config::default(),
8232 );
8233 run.status = RunStatus::Blocked;
8234 run.config.graph.review_rounds = 1;
8235 run.reviews = vec![review_round(1)];
8236 run.pr_publication_pending = true;
8237 assert_eq!(
8238 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
8239 Some(run.id.clone()),
8240 "a spent review budget must not turn a failed publication into a re-competition"
8241 );
8242 }
8243
8244 #[test]
8245 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
8246 let mut older_stalled = RunState::new(
8254 PathBuf::from("/repo"),
8255 "main".to_owned(),
8256 "abc1234def".to_owned(),
8257 "add retries".to_owned(),
8258 Config::default(),
8259 );
8260 older_stalled.status = RunStatus::Stalled;
8261
8262 let mut newest_exhausted = RunState::new(
8263 PathBuf::from("/repo"),
8264 "main".to_owned(),
8265 "abc1234def".to_owned(),
8266 "add retries".to_owned(),
8267 Config::default(),
8268 );
8269 newest_exhausted.status = RunStatus::Blocked;
8270 newest_exhausted.config.graph.review_rounds = 1;
8271 newest_exhausted.reviews = vec![review_round(1)];
8272
8273 assert_eq!(
8274 unfinished_run_with(
8275 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
8276 "t",
8277 |_| Ok(newest_exhausted.clone())
8278 ),
8279 None,
8280 "the newest run is exhausted, so nothing here is worth resuming - \
8281 least of all the older, already-superseded run"
8282 );
8283 }
8284
8285 #[test]
8286 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
8287 assert_eq!(
8288 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
8289 Err(anyhow::anyhow!("fixture is absent"))
8290 }),
8291 None
8292 );
8293 }
8294
8295 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
8296 let mut q = ask::Question::new(
8297 run.to_owned(),
8298 "implement".to_owned(),
8299 "impl-A".to_owned(),
8300 "continue?".to_owned(),
8301 String::new(),
8302 vec!["resume で続行する".to_owned(), "other".to_owned()],
8303 );
8304 q.actions.insert("resume で続行する".to_owned(), action);
8305 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
8306 .unwrap();
8307 q
8308 }
8309
8310 fn held_task_with(run: &str) -> Task {
8311 let mut t = task();
8312 t.runs = vec![run.to_owned()];
8313 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
8314 t
8315 }
8316
8317 fn resume_action(run: &str) -> ask::ChoiceAction {
8318 ask::ChoiceAction::Resume { run: run.into() }
8319 }
8320
8321 #[test]
8322 fn decide_action_resumes_only_the_latest_resumable_run() {
8323 let t = held_task_with("r1");
8324 let q = action_question("r1", resume_action("r1"));
8325 let load = |s: RunState| move |_: &str| Ok(s);
8326 assert_eq!(
8327 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
8328 ActionDecision::Resume("r1".into())
8329 );
8330 let q_other = action_question("r1", resume_action("r0"));
8332 assert!(matches!(
8333 decide_action(
8334 &t,
8335 &q_other,
8336 &PHRASES_EN,
8337 load(run_state(RunStatus::Blocked))
8338 ),
8339 ActionDecision::Refuse(_)
8340 ));
8341 assert!(matches!(
8343 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
8344 ActionDecision::Refuse(_)
8345 ));
8346 let mut released = run_state(RunStatus::Blocked);
8348 released.released_to = Some("elsewhere".into());
8349 assert!(matches!(
8350 decide_action(&t, &q, &PHRASES_EN, load(released)),
8351 ActionDecision::Refuse(_)
8352 ));
8353 assert!(matches!(
8355 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
8356 ActionDecision::Refuse(_)
8357 ));
8358 }
8359
8360 #[test]
8361 fn decide_action_ignores_a_question_about_an_earlier_run() {
8362 let mut t = held_task_with("r1");
8363 t.runs.push("r2".to_owned());
8364 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8365 assert_eq!(
8366 decide_action(
8367 &t,
8368 &action_question("r1", ask::ChoiceAction::Done),
8369 &PHRASES_EN,
8370 never
8371 ),
8372 ActionDecision::Stale
8373 );
8374 }
8375
8376 #[test]
8377 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
8378 let mut t = held_task_with("r1");
8379 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8380 assert_eq!(
8381 decide_action(
8382 &t,
8383 &action_question("r1", ask::ChoiceAction::Requeue),
8384 &PHRASES_EN,
8385 never
8386 ),
8387 ActionDecision::Requeue
8388 );
8389 let done_q = action_question("r1", ask::ChoiceAction::Done);
8390 assert_eq!(
8391 decide_action(&t, &done_q, &PHRASES_EN, never),
8392 ActionDecision::Done
8393 );
8394 t.mark_action_applied(&done_q.id);
8395 assert_eq!(
8396 decide_action(&t, &done_q, &PHRASES_EN, never),
8397 ActionDecision::Skip
8398 );
8399
8400 let mut plain = action_question("r1", ask::ChoiceAction::Done);
8402 plain.actions.clear();
8403 assert_eq!(
8404 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
8405 ActionDecision::Skip
8406 );
8407 let mut running = held_task_with("r1");
8409 running.status = TaskStatus::Running;
8410 assert_eq!(
8411 decide_action(
8412 &running,
8413 &action_question("r1", ask::ChoiceAction::Done),
8414 &PHRASES_EN,
8415 never
8416 ),
8417 ActionDecision::Skip
8418 );
8419 }
8420
8421 #[test]
8422 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
8423 let dir = tempfile::tempdir().unwrap();
8424 let queue = Queue::at(dir.path().join("queue"));
8425 let questions = Questions::at(dir.path().join("questions"));
8426 let home = dir.path().join("home");
8427 let mut state = run_state(RunStatus::Blocked);
8428 state.id = "20260101-000000-act1".to_owned();
8429 state.save_under(&home).unwrap();
8430
8431 let mut t = held_task_with(&state.id);
8432 queue.put(&mut t).unwrap();
8433 let mut q = action_question(&state.id, resume_action(&state.id));
8434 questions.put(&mut q).unwrap();
8435
8436 apply_choice_actions(&queue, &questions, &home);
8437 let after = queue.get(&t.id).unwrap();
8438 assert_eq!(after.status, TaskStatus::Queued);
8439 assert!(!after.fresh_start);
8440 assert!(after.action_applied(&q.id));
8441 let pin = after.resume_override.clone().unwrap();
8442 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
8443 assert!(pin.forced);
8444
8445 let mut again = queue.get(&t.id).unwrap();
8447 again.hold_machine(Some("later".into()));
8448 queue.put(&mut again).unwrap();
8449 apply_choice_actions(&queue, &questions, &home);
8450 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8451 }
8452
8453 #[test]
8454 fn a_delivered_answer_is_still_acted_on_exactly_once() {
8455 let dir = tempfile::tempdir().unwrap();
8456 let queue = Queue::at(dir.path().join("queue"));
8457 let questions = Questions::at(dir.path().join("questions"));
8458 let home = dir.path().join("home");
8459 let mut state = run_state(RunStatus::Blocked);
8460 state.id = "20260101-000000-act2".to_owned();
8461 state.save_under(&home).unwrap();
8462
8463 let mut t = held_task_with(&state.id);
8464 queue.put(&mut t).unwrap();
8465 let mut q = action_question(&state.id, resume_action(&state.id));
8466 q.answer_delivered = true;
8467 questions.put(&mut q).unwrap();
8468
8469 apply_choice_actions(&queue, &questions, &home);
8472 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8473 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
8474
8475 let mut again = queue.get(&t.id).unwrap();
8477 again.hold_machine(Some("later".into()));
8478 queue.put(&mut again).unwrap();
8479 apply_choice_actions(&queue, &questions, &home);
8480 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8481 }
8482
8483 #[test]
8484 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
8485 let dir = tempfile::tempdir().unwrap();
8486 let queue = Queue::at(dir.path().join("queue"));
8487 let questions = Questions::at(dir.path().join("questions"));
8488 let home = dir.path().join("home");
8489 let mut state = run_state(RunStatus::Blocked);
8490 state.id = "20260101-000000-act3".to_owned();
8491 state.save_under(&home).unwrap();
8492 let mut t = held_task_with(&state.id);
8493 queue.put(&mut t).unwrap();
8494 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
8495 questions.put(&mut q).unwrap();
8496
8497 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
8498 apply_choice_actions(&queue, &questions, &home);
8499 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8500
8501 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
8502 apply_choice_actions(&queue, &questions, &home);
8503 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8504 }
8505
8506 #[test]
8507 fn action_standing_tells_the_reasons_apart() {
8508 let mut t = held_task_with("r1");
8509 let q = action_question("r1", ask::ChoiceAction::Requeue);
8510 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
8511 let mut plain = q.clone();
8512 plain.actions.clear();
8513 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
8514
8515 t.mark_action_applied(&q.id);
8517 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
8518
8519 let mut t = held_task_with("r1");
8521 t.start("r2".to_owned());
8522 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
8523 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
8525 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8526 t.status = TaskStatus::Blocked;
8527 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8528
8529 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
8531 c.node = crate::conduct::NODE.to_owned();
8532 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
8533 assert!(!ActionStanding::Busy.daemon_owns());
8534 }
8535
8536 #[test]
8537 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
8538 let dir = tempfile::tempdir().unwrap();
8539 let queue = Queue::at(dir.path().join("queue"));
8540 let questions = Questions::at(dir.path().join("questions"));
8541 let home = dir.path().join("home");
8542 let mut state = run_state(RunStatus::Blocked);
8543 state.id = "20260101-000000-act4".to_owned();
8544 state.save_under(&home).unwrap();
8545 let mut t = held_task_with(&state.id);
8546 t.status = TaskStatus::Running;
8547 queue.put(&mut t).unwrap();
8548 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
8549 q.cwd = Some(dir.path().display().to_string());
8550 questions.put(&mut q).unwrap();
8551
8552 let running = queue.get(&t.id).unwrap();
8555 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
8556 assert!(matches!(
8557 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
8558 crate::waiter::Action::Deliver(_)
8559 ));
8560 apply_choice_actions(&queue, &questions, &home);
8562 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8563 let mut back = queue.get(&t.id).unwrap();
8564 back.hold_machine(Some("later".into()));
8565 queue.put(&mut back).unwrap();
8566 apply_choice_actions(&queue, &questions, &home);
8567 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
8568 let mut again = queue.get(&t.id).unwrap();
8569 again.hold_machine(Some("again".into()));
8570 queue.put(&mut again).unwrap();
8571 apply_choice_actions(&queue, &questions, &home);
8572 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8573 }
8574}