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.status != RunStatus::Landing || !state.parked {
1980 return LandResume::NotLanding;
1981 }
1982 let store = ask::Questions::open();
1983 let waiting = store
1984 .list()
1985 .into_iter()
1986 .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1987 .max_by(|a, b| a.id.cmp(&b.id));
1988 let Some(mut q) = waiting else {
1989 return LandResume::Ready;
1990 };
1991 if !q.status.open() {
1992 return LandResume::Ready;
1993 }
1994 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2001 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2002 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2003 q.abandon(format!(
2004 "no answer within {}s of asking",
2005 timeout.as_secs().max(1)
2006 ));
2007 if store.put(&mut q).is_ok() {
2010 return LandResume::Ready;
2011 }
2012 }
2013 LandResume::StillWaiting
2014}
2015
2016const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2024
2025const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2037
2038struct InFlightGuard<'a> {
2051 status: &'a Arc<Mutex<Status>>,
2052 stop: &'a Stop,
2053 task_id: &'a str,
2054}
2055
2056impl Drop for InFlightGuard<'_> {
2057 fn drop(&mut self) {
2058 lock(self.status).current.retain(|c| c.task != self.task_id);
2059 self.stop.exit();
2060 }
2061}
2062
2063#[derive(Debug, Clone, PartialEq, Eq)]
2085enum Interrupt {
2086 Idle,
2088 Parking {
2100 parked: Vec<String>,
2101 interrupt_task: String,
2102 },
2103 Running {
2111 parked: Vec<String>,
2112 interrupt_task: String,
2113 },
2114 Resuming { parked: Vec<String> },
2121}
2122
2123fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2144 match state {
2145 Interrupt::Idle => {
2146 if in_flight.len() != 1 {
2158 return Interrupt::Idle;
2159 }
2160 match runnable.iter().find(|t| t.interrupt) {
2161 Some(t) => Interrupt::Parking {
2162 parked: in_flight.to_vec(),
2163 interrupt_task: t.id.clone(),
2164 },
2165 None => Interrupt::Idle,
2166 }
2167 }
2168 Interrupt::Parking {
2169 parked,
2170 interrupt_task,
2171 } => {
2172 if in_flight.iter().any(|id| parked.contains(id)) {
2173 Interrupt::Parking {
2175 parked,
2176 interrupt_task,
2177 }
2178 } else if in_flight.contains(&interrupt_task) {
2179 Interrupt::Running {
2180 parked,
2181 interrupt_task,
2182 }
2183 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2184 Interrupt::Parking {
2188 parked,
2189 interrupt_task,
2190 }
2191 } else {
2192 Interrupt::Resuming { parked }
2197 }
2198 }
2199 Interrupt::Running {
2200 parked,
2201 interrupt_task,
2202 } => {
2203 if in_flight.contains(&interrupt_task) {
2204 Interrupt::Running {
2205 parked,
2206 interrupt_task,
2207 }
2208 } else {
2209 Interrupt::Resuming { parked }
2215 }
2216 }
2217 Interrupt::Resuming { parked } => {
2218 if in_flight.iter().any(|id| parked.contains(id)) {
2219 Interrupt::Idle
2225 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2226 Interrupt::Resuming { parked }
2227 } else {
2228 Interrupt::Idle
2231 }
2232 }
2233 }
2234}
2235
2236fn advance_interrupt_tick(
2242 enabled: bool,
2243 state: Interrupt,
2244 in_flight: &[String],
2245 runnable: &[Task],
2246) -> Interrupt {
2247 if !enabled {
2248 return Interrupt::Idle;
2249 }
2250 advance_interrupt(state, in_flight, runnable)
2251}
2252
2253fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2258 match state {
2259 Interrupt::Idle => candidates,
2260 Interrupt::Parking {
2261 parked,
2262 interrupt_task,
2263 } => {
2264 if in_flight.iter().any(|id| parked.contains(id)) {
2265 Vec::new()
2266 } else {
2267 candidates
2268 .into_iter()
2269 .filter(|t| &t.id == interrupt_task)
2270 .collect()
2271 }
2272 }
2273 Interrupt::Running { .. } => Vec::new(),
2274 Interrupt::Resuming { parked } => candidates
2282 .into_iter()
2283 .find(|t| parked.contains(&t.id))
2284 .into_iter()
2285 .collect(),
2286 }
2287}
2288
2289struct DispatchLimits {
2293 max_concurrent: usize,
2296 pause_for_interrupts: bool,
2298}
2299
2300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2309enum PermitKind {
2310 None,
2315 Urgent,
2322 Ordinary,
2325}
2326
2327fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2330 if priority {
2331 PermitKind::None
2332 } else if urgent {
2333 PermitKind::Urgent
2334 } else {
2335 PermitKind::Ordinary
2336 }
2337}
2338
2339async fn poll(
2358 opts: &Opts,
2359 queue: &Queue,
2360 status: &Arc<Mutex<Status>>,
2361 home: &Path,
2362 worktrees_root: &Path,
2363 stop: &Stop,
2364 limits: DispatchLimits,
2365) -> Result<()> {
2366 let DispatchLimits {
2367 max_concurrent,
2368 pause_for_interrupts,
2369 } = limits;
2370 let mut attempted: Vec<String> = Vec::new();
2375 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2376 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2384 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2390 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2391 let mut conductor = Conductor::new();
2392 let mut cache_last_checked: Option<Timestamp> = None;
2395 let mut interrupt = Interrupt::Idle;
2397 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2403 std::collections::HashMap::new();
2404
2405 while !stop.stopped() {
2406 lock(status).polls += 1;
2407
2408 while let Some(result) = inflight.try_join_next() {
2413 if let Err(e) = result {
2414 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2415 notices::raise(Notice::error(
2416 "loop:attempt",
2417 "A queued attempt ended abnormally; check the task it was running.",
2418 ));
2419 }
2420 }
2421
2422 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2423 if !swept.is_empty() {
2424 tracing::warn!(
2425 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2426 swept.len(),
2427 swept.join(", ")
2428 );
2429 }
2430 let now = Timestamp::now();
2435
2436 if !stop.busy_now() {
2441 maybe_prune_cache_between_runs(
2442 &opts.repo,
2443 opts,
2444 home,
2445 stop,
2446 &mut cache_last_checked,
2447 now,
2448 )
2449 .await;
2450 }
2451
2452 let stalled = stalled_tasks(queue, home, now);
2453 let stalled_ids: std::collections::BTreeSet<_> =
2454 stalled.iter().map(|task| task.id.clone()).collect();
2455 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2456 if !reclaimed.is_empty() {
2457 tracing::warn!(
2458 "reclaimed {} task(s) left `running` by a daemon that never \
2459 recorded the outcome: {}",
2460 reclaimed.len(),
2461 reclaimed.join(", ")
2462 );
2463 }
2464 let abandoned_runs = reclaim_abandoned_runs(home, now);
2465 if !abandoned_runs.is_empty() {
2466 tracing::warn!(
2467 "failed {} run(s) left behind by a killed process, past every \
2468 active seat's own timeout: {}",
2469 abandoned_runs.len(),
2470 abandoned_runs.join(", ")
2471 );
2472 }
2473
2474 let questions = Questions::at(home.join("questions"));
2479
2480 resolve_blockers(queue, &questions);
2483 apply_choice_actions(queue, &questions, home);
2484 reconcile_task_questions(queue, &questions);
2485
2486 let finished: Vec<Task> = finished_tasks(queue)
2492 .into_iter()
2493 .filter(|task| !stalled_ids.contains(&task.id))
2494 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2498 .collect();
2499 let queued = queued_tasks(queue);
2500 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2504 && conductor.worth_a_look(queue, &stalled, &finished)
2505 {
2506 match prepare(&opts.repo, opts) {
2507 Ok(cfg) => {
2508 conductor
2509 .maybe_run(
2510 &cfg,
2511 &opts.repo,
2512 queue,
2513 &questions,
2514 home,
2515 &queued,
2516 &stalled,
2517 &finished,
2518 opts.max_attempts,
2519 )
2520 .await;
2521 }
2522 Err(e) => {
2523 tracing::warn!("conductor: no config: {e:#}");
2524 notices::raise(Notice::warn(
2525 "loop:no-config",
2526 "The loop could not read this repository's config, so held tasks are not being triaged.",
2527 ));
2528 }
2529 }
2530 }
2531
2532 let candidates: Vec<Task> = runnable(queue)
2533 .into_iter()
2534 .filter(|t| !opts.once || !attempted.contains(&t.id))
2535 .collect();
2536
2537 let in_flight: Vec<String> = lock(status)
2542 .current
2543 .iter()
2544 .map(|c| c.task.clone())
2545 .collect();
2546 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2547
2548 interrupt =
2549 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2550 if let Interrupt::Parking {
2551 parked,
2552 interrupt_task,
2553 } = &interrupt
2554 {
2555 let reason = format!(
2556 "task {} asked to run first",
2557 crate::run::short_of(interrupt_task)
2558 );
2559 for id in parked {
2560 if let Some(pause) = interrupt_pauses.get(id) {
2561 pause.park_because(reason.clone());
2562 }
2563 }
2564 }
2565 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2566
2567 let cooling_down =
2568 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2569
2570 let mut started_any = false;
2571 for candidate in candidates {
2572 if stop.stopped() {
2573 break;
2574 }
2575
2576 let resume = land_resume_state(&candidate);
2577 if resume == LandResume::StillWaiting {
2578 continue;
2579 }
2580 let priority = resume == LandResume::Ready;
2581
2582 if !priority && cooling_down {
2583 continue;
2584 }
2585 let permit = match permit_kind(priority, candidate.urgent) {
2586 PermitKind::None => None,
2587 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2588 Ok(p) => Some(p),
2589 Err(_) => continue,
2595 },
2596 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2597 Ok(p) => Some(p),
2598 Err(_) => continue,
2602 },
2603 };
2604
2605 let Ok(claim) = queue.claim(&candidate.id) else {
2610 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2611 continue;
2612 };
2613 let mut task = match queue.get(&candidate.id) {
2616 Ok(t) if t.status.runnable() => t,
2617 Ok(_) => continue,
2618 Err(e) => {
2619 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2620 continue;
2621 }
2622 };
2623 let task_id = task.id.clone();
2624 attempted.push(task_id.clone());
2625 lock(status).idle = false;
2626 stop.enter();
2629 started_any = true;
2630
2631 let run_pause = crate::graph::Pause::new();
2635 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2636
2637 let opts = opts.clone();
2638 let queue = queue.clone();
2639 let status = Arc::clone(status);
2640 let stop = stop.clone();
2641 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2642 inflight.spawn(async move {
2643 let _claim = claim;
2647 let _permit = permit;
2648 let _inflight = InFlightGuard {
2650 status: &status,
2651 stop: &stop,
2652 task_id: &task_id,
2653 };
2654 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2655 lock(&status).completed += 1;
2656 let now = Timestamp::now();
2662 if let Some(until) = cooldown_until("a, now) {
2663 let wait = until.as_second() - now.as_second();
2664 *lock("a_cooldown_until) = Some(until);
2665 let hint = quota
2666 .iter()
2667 .find(|q| q.reset.is_some())
2668 .and_then(|q| q.reset.as_deref());
2669 match hint {
2670 Some(h) => tracing::warn!(
2671 "quota hit; waiting {wait}s before taking another ordinary task \
2672 (CLI reported reset: {h})"
2673 ),
2674 None => tracing::warn!(
2675 "quota hit; waiting {wait}s before taking another ordinary task \
2676 (no reset hint reported)"
2677 ),
2678 }
2679 }
2680 });
2681 }
2682
2683 if started_any {
2684 continue;
2685 }
2686
2687 if stop.busy_now() {
2688 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2693 continue;
2694 }
2695
2696 lock(status).idle = true;
2698 if opts.once {
2699 janitor(&opts.repo, opts, home, worktrees_root).await;
2703 resweep_superseded_attempts(queue, home);
2704 triage_held(queue, home, opts).await;
2705 break;
2706 }
2707 stop.idle(opts.poll).await;
2708 if stop.stopped() {
2709 continue;
2710 }
2711 janitor(&opts.repo, opts, home, worktrees_root).await;
2717 resweep_superseded_attempts(queue, home);
2718 triage_held(queue, home, opts).await;
2719 }
2720
2721 while let Some(result) = inflight.join_next().await {
2726 if let Err(e) = result {
2727 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2728 notices::raise(Notice::error(
2729 "loop:attempt",
2730 "A queued attempt ended abnormally; check the task it was running.",
2731 ));
2732 }
2733 }
2734 Ok(())
2735}
2736
2737async fn attempt(
2743 opts: &Opts,
2744 queue: &Queue,
2745 status: &Arc<Mutex<Status>>,
2746 stop: &Stop,
2747 interrupt_pause: crate::graph::Pause,
2748 task: &mut Task,
2749) -> Vec<QuotaLoss> {
2750 let repo = repo_for(task, &opts.repo);
2751 tracing::info!(
2752 "task {} — {} (repo {})",
2753 task.short(),
2754 task.title,
2755 repo.display()
2756 );
2757
2758 let explicit = match &task.overrides {
2762 Some(o) => o.config.as_deref(),
2763 None => opts.config.as_deref(),
2764 };
2765 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2766 let reason = format!("[config] {e:#}");
2767 task.last_error = Some(reason.clone());
2768 task.hold_machine(Some(reason.clone()));
2769 record(queue, task);
2770 tracing::warn!("holding {}: {reason}", task.short());
2771 return Vec::new();
2772 }
2773 let mut config = match prepare_for(&repo, opts, task) {
2774 Ok(c) => c,
2775 Err(e) => {
2776 task.attempts += 1;
2780 task.fail(format!("config: {e:#}"), opts.max_attempts);
2781 record(queue, task);
2782 return Vec::new();
2783 }
2784 };
2785 apply_solo(&mut config, task);
2786 let p = phrases(&config.graph.language);
2787 let start_failed = p.could_not_start;
2788
2789 if let Some(reason) = disk_gate(&repo, &config) {
2797 task.last_error = Some(reason.clone());
2798 task.hold_machine(Some(reason.clone()));
2799 record(queue, task);
2800 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2801 notices::raise(
2804 Notice::warn(
2805 &format!("disk:{}", repo.display()),
2806 "A task was held for want of free disk space; free some, then release it from the queue.",
2807 )
2808 .link(Link::Task {
2809 id: task.id.clone(),
2810 }),
2811 );
2812 return Vec::new();
2813 }
2814
2815 let unfinished = (!task.fresh_start)
2835 .then(|| unfinished_run(&task.runs, task.short()))
2836 .flatten();
2837 let review_branch = task.review_branch.take();
2843 let branch_exists = match &review_branch {
2844 Some(branch) => crate::git::branch_exists(&repo, branch)
2845 .await
2846 .unwrap_or(false),
2847 None => false,
2848 };
2849 let starter = match (&review_branch, &unfinished, &task.review_of) {
2853 (None, None, Some(branch)) => Starter::Review(branch.clone()),
2854 _ => choose_starter(
2855 review_branch.as_deref(),
2856 branch_exists,
2857 unfinished.as_deref(),
2858 ),
2859 };
2860 let attachments = match task_attachments(queue, task) {
2865 Ok(a) => a,
2866 Err(e) => {
2867 task.attempts += 1;
2868 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2869 record(queue, task);
2870 return Vec::new();
2871 }
2872 };
2873 let started = match &starter {
2874 Starter::Review(branch) => {
2875 tracing::info!(
2876 "task {} reopens `{branch}` as a review-only pass",
2877 task.short()
2878 );
2879 let takeover = crate::handover::Takeover {
2882 earlier: task.earlier_attempts().to_vec(),
2883 home: crate::run::home(),
2884 choice: take_divergence_answer(branch, &config.merge.remote, task),
2885 };
2886 Runner::review_taking_over(
2887 &repo,
2888 branch,
2889 config,
2890 Some(takeover),
2891 crate::run::Origin::queue(&task.id),
2892 )
2893 .await
2894 }
2895 Starter::Resume(id) => {
2896 tracing::info!("resuming run {id} rather than competing again");
2897 Runner::resume(id).map(|mut r| {
2898 if let Some(instruction) =
2899 prepare_instruction(&starter, Some(&r.state.instruction), task)
2900 {
2901 r.state.instruction = instruction;
2902 }
2903 r.state.attachments = attachments.clone();
2904 if let Some(mode) = task
2907 .overrides
2908 .as_ref()
2909 .and_then(|o| o.merge.as_deref())
2910 .and_then(|m| merge_mode(m).ok())
2911 {
2912 r.state.config.merge.mode = mode;
2913 }
2914 r
2915 })
2916 }
2917 Starter::Start => {
2918 if let Some(branch) = &review_branch {
2919 tracing::warn!(
2920 "conductor chose review for task {} but branch `{branch}` no longer \
2921 exists; requeuing as a fresh competition instead",
2922 task.short()
2923 );
2924 }
2925 let instruction = prepare_instruction(&starter, None, task)
2926 .unwrap_or_else(|| task.instruction.clone());
2927 Runner::start_naming(
2928 &repo,
2929 instruction,
2930 &task.title,
2931 config,
2932 crate::run::Origin::queue(&task.id),
2933 )
2934 .await
2935 .map(|mut r| {
2936 r.state.attachments = attachments.clone();
2937 r
2938 })
2939 }
2940 };
2941 let mut runner = match started {
2942 Ok(r) => r,
2943 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2947 let detail = match e.downcast_ref::<crate::handover::Refused>() {
2948 Some(r) => (p.handover_refused)(r),
2949 None => format!("{e:#}"),
2950 };
2951 let reason = format!("{start_failed}{detail}");
2952 task.last_error = Some(reason.clone());
2953 let branch = match &starter {
2956 Starter::Review(branch) => Some(branch.clone()),
2957 _ => None,
2958 };
2959 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
2963 record(queue, task);
2964 tracing::warn!(
2965 "holding {} for a branch it cannot take over: {e:#}",
2966 task.short()
2967 );
2968 return Vec::new();
2969 }
2970 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
2975 let d = e
2976 .downcast_ref::<crate::reconcile::Diverged>()
2977 .expect("checked by the guard");
2978 let mut q = ask::Question::new(
2979 task.id.clone(),
2980 crate::reconcile::NODE.to_owned(),
2981 crate::reconcile::SEAT.to_owned(),
2982 d.summary(),
2983 d.detail(),
2984 d.choices(),
2985 );
2986 match Questions::open().put(&mut q) {
2987 Ok(()) => {
2988 task.last_error = Some(format!("{e:#}"));
2989 task.review_branch = Some(d.branch.clone());
2992 task.block(vec![q.id.clone()], Some(d.summary()));
2993 }
2994 Err(put) => {
2995 tracing::warn!("could not file the divergence question: {put:#}");
2996 task.attempts += 1;
2997 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2998 }
2999 }
3000 record(queue, task);
3001 return Vec::new();
3002 }
3003 Err(e) => {
3004 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3010 && let Starter::Review(branch) = &starter
3011 {
3012 task.review_branch = Some(branch.clone());
3013 task.last_error = Some(format!("{start_failed}{e:#}"));
3014 task.status = crate::queue::TaskStatus::Failed;
3015 record(queue, task);
3016 return Vec::new();
3017 }
3018 task.attempts += 1;
3019 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3020 record(queue, task);
3021 return Vec::new();
3022 }
3023 };
3024 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3027 runner.on_pause(stop.pause());
3029 runner.watch_interrupt(interrupt_pause);
3033
3034 let run = runner.state.id.clone();
3037 task.start(run.clone());
3038 record(queue, task);
3039 lock(status).current.push(Current {
3040 task: task.id.clone(),
3041 run,
3042 });
3043
3044 let quota_before = runner.state.quota.clone();
3047 let result = runner.execute().await;
3048 finish_attempt(
3049 opts.max_attempts,
3050 queue,
3051 task,
3052 &runner.state,
3053 "a_before,
3054 result,
3055 )
3056}
3057
3058pub fn finish_attempt(
3063 max_attempts: usize,
3064 queue: &Queue,
3065 task: &mut Task,
3066 state: &RunState,
3067 quota_before: &[QuotaLoss],
3068 result: Result<()>,
3069) -> Vec<QuotaLoss> {
3070 let detail = match result {
3071 Ok(()) => describe(state),
3072 Err(e) => format!("{e:#}"),
3073 };
3074 let fresh = losses_this_attempt(quota_before, &state.quota);
3075 let verdict = Verdict {
3076 status: state.status,
3077 left_pr: state.pr.is_some(),
3080 quota_hit: !fresh.is_empty(),
3086 parked: state.parked,
3090 no_viable_candidates: state.viable().is_empty(),
3093 };
3094 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3095 if task.status == TaskStatus::Done {
3096 supersede_prior_runs(task, &crate::run::home());
3097 }
3098 record(queue, task);
3099 tracing::info!(
3100 "task {} is {} after run {} ({})",
3101 task.short(),
3102 task.status.as_str(),
3103 state.short(),
3104 label(state.status)
3105 );
3106 fresh
3107}
3108
3109pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3113 if task.status.runnable() {
3114 let why = task.last_error.clone().map_or_else(
3115 || "the run did not finish".to_owned(),
3116 |e| format!("the run did not finish: {e}"),
3117 );
3118 task.hold_manual(Some(format!(
3119 "{why}. It was started by hand, so it is not retried \
3120 automatically; `magi task release` retries it."
3121 )));
3122 record(queue, task);
3123 }
3124}
3125
3126#[must_use]
3130pub fn loop_would_resume(run: &str) -> bool {
3131 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3132}
3133
3134#[must_use]
3144pub fn foreign_loop(
3145 reading: Option<&Reading>,
3146 now: Timestamp,
3147 own_pid: u32,
3148) -> Option<Option<u32>> {
3149 let reading = reading.filter(|r| r.running(now))?;
3150 match reading.pid {
3151 Some(pid) if pid == own_pid => None,
3152 pid => Some(pid),
3153 }
3154}
3155
3156pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3171 let status = Arc::new(Mutex::new(Status::new()));
3172 let stop = Stop::new();
3173 attempt(
3174 opts,
3175 queue,
3176 &status,
3177 &stop,
3178 crate::graph::Pause::new(),
3179 task,
3180 )
3181 .await;
3182 hold_if_runnable(queue, task);
3183}
3184
3185fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3195 after
3196 .iter()
3197 .filter(|q| !before.contains(q))
3198 .cloned()
3199 .collect()
3200}
3201
3202fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3205 if quota.is_empty() {
3206 return None;
3207 }
3208 let with_hint = quota.iter().find(|q| q.reset.is_some());
3209 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3210 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3211 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3212 Some(
3213 now.checked_add(jiff::SignedDuration::from_secs(secs))
3214 .unwrap_or(Timestamp::MAX),
3215 )
3216}
3217
3218fn apply_solo(config: &mut Config, task: &Task) {
3228 if task.solo {
3229 config.graph.implementers = 1;
3230 }
3231}
3232
3233fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3238 let Some(o) = &task.overrides else {
3239 return prepare(repo, opts);
3240 };
3241 let own = Opts {
3245 config: o.config.clone(),
3246 merge: None,
3247 ..opts.clone()
3248 };
3249 let mut config = prepare(repo, &own)?;
3250 o.apply(&mut config);
3251 Ok(config)
3252}
3253
3254fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3256 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3257 if let Some(mode) = &opts.merge {
3258 config.merge.mode = merge_mode(mode)?;
3259 }
3260 Ok(config)
3261}
3262
3263async fn maybe_prune_cache_between_runs(
3294 repo: &Path,
3295 opts: &Opts,
3296 home: &Path,
3297 stop: &Stop,
3298 last_checked: &mut Option<Timestamp>,
3299 now: Timestamp,
3300) {
3301 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3302 return;
3303 }
3304 *last_checked = Some(now);
3305 let cfg = match prepare(repo, opts) {
3306 Ok(cfg) => cfg,
3307 Err(e) => {
3308 tracing::warn!("cache check: no config: {e:#}");
3309 return;
3310 }
3311 };
3312 match clean::prune_cache_if_over_limit(&cfg, home) {
3313 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3314 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3315 pruned.files,
3316 pruned.freed
3317 ),
3318 Ok(_) => {}
3319 Err(e) => {
3320 tracing::warn!("housekeep: prune cache: {e:#}");
3321 notices::raise_in(
3322 home,
3323 Notice::warn(
3324 "housekeep:cache",
3325 "Pruning the shared build cache failed; disk usage may keep growing.",
3326 ),
3327 );
3328 }
3329 }
3330}
3331
3332fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3336 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3337}
3338
3339async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3358 let cfg = match prepare(repo, opts) {
3359 Ok(cfg) => cfg,
3360 Err(e) => {
3361 tracing::warn!("housekeep: no config: {e:#}");
3362 return;
3363 }
3364 };
3365 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3374 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3375 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3380 let mut extra = Vec::new();
3381 if out.unreadable > 0 {
3382 extra.push(format!("{} unreadable", out.unreadable));
3383 }
3384 if out.orphaned_worktrees > 0 {
3385 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3386 }
3387 let detail = if extra.is_empty() {
3388 String::new()
3389 } else {
3390 format!(" ({})", extra.join(", "))
3391 };
3392 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3393 }
3394 if out.external_merges_recorded > 0 {
3395 tracing::info!(
3396 "housekeep: recorded {} run(s) as merged externally",
3397 out.external_merges_recorded
3398 );
3399 }
3400 if out.stale_pr_states_repaired > 0 {
3401 tracing::info!(
3402 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3403 out.stale_pr_states_repaired
3404 );
3405 }
3406 if out.cache_files > 0 {
3407 tracing::info!(
3408 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3409 out.cache_files,
3410 out.cache_freed
3411 );
3412 }
3413 if out.questions_abandoned > 0 {
3414 tracing::info!(
3415 "housekeep: abandoned {} question(s) left open by a finished run",
3416 out.questions_abandoned
3417 );
3418 }
3419}
3420
3421async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3430 let questions = Questions::at(home.join("questions"));
3431 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3432 if report.is_empty() {
3433 return;
3434 }
3435 if !report.quarantined.is_empty() {
3436 tracing::info!(
3437 "triage: held {} blocked task(s) whose blocked-on task or \
3438 question no longer exists: {}",
3439 report.quarantined.len(),
3440 report.quarantined.join(", ")
3441 );
3442 }
3443 if !report.resumed.is_empty() {
3444 tracing::info!(
3445 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3446 report.resumed.len(),
3447 report.resumed.join(", ")
3448 );
3449 }
3450 if !report.asked.is_empty() {
3451 tracing::info!(
3452 "triage: asked about {} held task(s): {}",
3453 report.asked.len(),
3454 report.asked.join(", ")
3455 );
3456 }
3457 if !report.answered.is_empty() {
3458 tracing::info!(
3459 "triage: applied {} operator answer(s): {}",
3460 report.answered.len(),
3461 report.answered.join(", ")
3462 );
3463 }
3464}
3465
3466fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3473 disk_gate_with(repo, config, crate::disk::free_bytes)
3474}
3475
3476fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3480 repo: &Path,
3481 config: &Config,
3482 free_bytes: F,
3483) -> Option<String> {
3484 let min = config.disk.min_free_bytes;
3485 if min == 0 {
3486 return None;
3487 }
3488 match free_bytes(repo) {
3489 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3490 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3491 }
3492}
3493
3494const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3501
3502const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3506
3507fn quota_wait(
3516 reset_at: Option<Timestamp>,
3517 now: Timestamp,
3518 fallback: Duration,
3519 cap: Duration,
3520) -> Duration {
3521 match reset_at {
3522 Some(at) if at > now => {
3523 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3524 Duration::from_secs(secs).min(cap)
3525 }
3526 _ => fallback,
3527 }
3528}
3529
3530fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3544 parse_reset_hint_zoned(text, now)
3545 .or_else(|| parse_reset_hint_dated(text))
3546 .or_else(|| parse_reset_hint_relative(text, recorded))
3547}
3548
3549fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3553 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3554 let mut rest = rest.trim();
3555 if rest.is_empty() {
3556 return None;
3557 }
3558 let mut total: i64 = 0;
3559 let mut matched = false;
3560 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3561 if let Some((digits, tail)) = rest.split_once(unit)
3562 && !digits.is_empty()
3563 && digits.bytes().all(|b| b.is_ascii_digit())
3564 {
3565 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3566 rest = tail;
3567 matched = true;
3568 }
3569 }
3570 if !rest.is_empty() || !matched {
3571 return None;
3572 }
3573 recorded
3574 .checked_add(jiff::SignedDuration::from_secs(total))
3575 .ok()
3576}
3577
3578fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3582 let clock = clock.trim().to_lowercase();
3583 let (digits, pm) = clock
3584 .strip_suffix("am")
3585 .map(|d| (d, false))
3586 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3587 let (h, m) = digits.trim().split_once(':')?;
3588 let mut hour: i8 = h.trim().parse().ok()?;
3589 let minute: i8 = m.trim().parse().ok()?;
3590 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3591 return None;
3592 }
3593 if pm && hour != 12 {
3594 hour += 12;
3595 } else if !pm && hour == 12 {
3596 hour = 0;
3597 }
3598 Some((hour, minute))
3599}
3600
3601fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3606 let open = text.find('(')?;
3607 let close = text.rfind(')')?;
3608 if close <= open {
3609 return None;
3610 }
3611 let zone = text[open + 1..close].trim();
3612 let (hour, minute) = parse_12h_clock(&text[..open])?;
3613 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3614 let candidate = now
3615 .to_zoned(tz)
3616 .with()
3617 .hour(hour)
3618 .minute(minute)
3619 .second(0)
3620 .millisecond(0)
3621 .microsecond(0)
3622 .nanosecond(0)
3623 .build()
3624 .ok()?;
3625 let mut at = candidate.timestamp();
3626 if at <= now {
3627 at += jiff::SignedDuration::from_hours(24);
3628 }
3629 Some(at)
3630}
3631
3632fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3641 let words: Vec<&str> = text.split_whitespace().collect();
3642 if words.len() < 5 {
3643 return None;
3644 }
3645 (0..=words.len() - 5)
3646 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3647}
3648
3649fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3655 if trailing.is_some_and(|next| next.starts_with('(')) {
3656 return None;
3657 }
3658 let month = month_number(window[0])?;
3659 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3660 let day_digits = ["st", "nd", "rd", "th"]
3661 .iter()
3662 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3663 let day: i8 = day_digits.parse().ok()?;
3664 let year_token = window[2];
3665 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3666 return None;
3667 }
3668 let year: i16 = year_token.parse().ok()?;
3669 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3673 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3674 let date = jiff::civil::Date::new(year, month, day).ok()?;
3675 let candidate = date
3676 .at(hour, minute, 0, 0)
3677 .to_zoned(jiff::tz::TimeZone::UTC)
3678 .ok()?;
3679 Some(candidate.timestamp())
3680}
3681
3682fn month_number(name: &str) -> Option<i8> {
3685 const NAMES: [&str; 12] = [
3686 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3687 ];
3688 let lower = name.to_lowercase();
3689 NAMES
3690 .iter()
3691 .position(|n| *n == lower.as_str())
3692 .map(|i| i as i8 + 1)
3693}
3694
3695fn exhausted_review_budget(state: &RunState) -> bool {
3707 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
3708}
3709
3710fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3747 unfinished_run_with(runs, short, RunState::load)
3748}
3749
3750fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3753where
3754 F: FnOnce(&str) -> Result<RunState>,
3755{
3756 let id = runs.last()?;
3757 match load(id) {
3758 Ok(s)
3763 if s.status.resumable()
3764 && !s.released()
3765 && !exhausted_review_budget(&s)
3766 && s.liveness(false) != crate::run::Liveness::Live =>
3767 {
3768 Some(id.clone())
3769 }
3770 Ok(_) => None,
3771 Err(e) => {
3772 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3773 None
3774 }
3775 }
3776}
3777
3778fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3786where
3787 F: FnOnce(&str) -> Result<RunState>,
3788{
3789 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
3791 || task.fresh_start
3792 || task.review_branch.is_some()
3793 {
3794 return false;
3795 }
3796 let Some(id) = task.runs.last() else {
3797 return false;
3798 };
3799 load(id).is_ok_and(|s| {
3800 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3801 })
3802}
3803
3804#[derive(Debug, Clone, PartialEq, Eq)]
3807enum Starter {
3808 Review(String),
3811 Resume(String),
3813 Start,
3815}
3816
3817fn take_divergence_answer(
3821 branch: &str,
3822 remote: &str,
3823 task: &mut Task,
3824) -> Option<crate::reconcile::Choice> {
3825 let summary = crate::reconcile::summary_for(branch, remote);
3826 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3827 (a.question == summary)
3828 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3829 .flatten()
3830 .map(|c| (i, c))
3831 })?;
3832 task.answers.remove(idx);
3833 Some(choice)
3834}
3835
3836fn choose_starter(
3848 review_branch: Option<&str>,
3849 branch_exists: bool,
3850 unfinished: Option<&str>,
3851) -> Starter {
3852 match review_branch {
3853 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3854 Some(_) => Starter::Start,
3855 None => match unfinished {
3856 Some(id) => Starter::Resume(id.to_owned()),
3857 None => Starter::Start,
3858 },
3859 }
3860}
3861
3862fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3865 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3866 return fallback.to_path_buf();
3867 }
3868 task.repo.clone()
3869}
3870
3871const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3875
3876fn answers_block(task: &Task, count: usize) -> String {
3878 let mut s = ANSWERS_HEADER.to_owned();
3879 for a in &task.answers[..count] {
3880 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3881 }
3882 s
3883}
3884
3885fn append_answers(base: &str, task: &Task) -> String {
3888 if task.answers.is_empty() {
3889 return base.to_owned();
3890 }
3891 let mut s = base.to_owned();
3892 s.push_str(&answers_block(task, task.answers.len()));
3893 s
3894}
3895
3896fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3900 for count in (1..=task.answers.len()).rev() {
3901 let block = answers_block(task, count);
3902 if let Some(base) = instruction.strip_suffix(&block) {
3903 return base;
3904 }
3905 }
3906 instruction
3907}
3908
3909fn instruction_for(task: &Task) -> String {
3917 append_answers(&task.instruction, task)
3918}
3919
3920fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3932 append_answers(strip_answers_block(old_instruction, task), task)
3933}
3934
3935fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
3937 let paths = queue.attachment_paths(task);
3938 for (name, path) in task.attachments.iter().zip(&paths) {
3939 if !path.is_file() {
3940 bail!(
3941 "attachment `{name}` is recorded on the task but {} is missing",
3942 path.display()
3943 );
3944 }
3945 }
3946 Ok(paths)
3947}
3948
3949fn prepare_instruction(
3960 starter: &Starter,
3961 old_instruction: Option<&str>,
3962 task: &Task,
3963) -> Option<String> {
3964 match starter {
3965 Starter::Start => Some(instruction_for(task)),
3966 Starter::Resume(_) => Some(resumed_instruction(
3967 old_instruction.expect("a resumed run always has a prior instruction"),
3968 task,
3969 )),
3970 Starter::Review(_) => None,
3971 }
3972}
3973
3974fn record(queue: &Queue, task: &mut Task) {
3978 if let Err(e) = queue.put(task) {
3979 tracing::error!("could not record task {}: {e:#}", task.short());
3980 notices::raise(Notice::error(
3981 "loop:record",
3982 "The loop could not save a task's state; check the disk.",
3983 ));
3984 }
3985}
3986
3987fn runnable(queue: &Queue) -> Vec<Task> {
3993 let mut tasks: Vec<Task> = queue
3994 .list()
3995 .into_iter()
3996 .filter(|t| t.status.runnable())
3997 .collect();
3998 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3999 tasks
4000}
4001
4002fn describe(state: &RunState) -> String {
4016 let p = phrases(&state.config.graph.language);
4017 let mut detail = if state.status == RunStatus::Stalled {
4018 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4019 seats.sort_unstable();
4020 seats.dedup();
4021 if seats.is_empty() {
4022 p.quorum_lost.to_owned()
4023 } else {
4024 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4025 }
4026 } else {
4027 format!("{}{}", p.run_ended, state.status.display_label())
4028 };
4029 if let Some(last) = state.events.last() {
4030 let unanswered = state
4034 .reviews
4035 .last()
4036 .filter(|r| {
4037 state.status == RunStatus::Blocked
4038 && last.node == "review"
4039 && r.incomplete()
4040 && r.blocking == 0
4041 && r.round == state.config.graph.review_rounds
4042 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4043 })
4044 .map(|r| (r.expected - r.answered, r.round));
4045 match unanswered {
4046 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4047 detail.push_str(&format!(
4048 " ({}: {})",
4049 last.node,
4050 (p.reviewers_never_answered)(missing, rounds)
4051 ));
4052 }
4053 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4054 }
4055 }
4056 detail.push_str(&format!(" [run {}]", state.id));
4057 detail
4058}
4059
4060const DIAGNOSTIC_MAX: usize = 4_000;
4066
4067const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4072
4073fn diagnostic(state: &RunState) -> Option<String> {
4087 let mut parts: Vec<String> = Vec::new();
4088
4089 for o in state.gate.iter().filter(|o| !o.ok()) {
4091 parts.push(format!(
4092 "gate `{}` failed ({:?}):\n{}",
4093 o.command,
4094 o.code,
4095 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4096 ));
4097 }
4098
4099 if let Some(last) = state
4102 .events
4103 .iter()
4104 .rev()
4105 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4106 {
4107 parts.push(last.message.clone());
4108 }
4109
4110 if state.viable().is_empty() {
4117 for c in &state.candidates {
4118 if let Some(evidence) = &c.verified_noop {
4119 parts.push(format!(
4120 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4121 c.label
4122 ));
4123 } else if !c.summary.trim().is_empty() {
4124 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4125 } else if let Some(why) = &c.failed {
4126 parts.push(format!("candidate {}: {why}", c.label));
4127 }
4128 }
4129 }
4130
4131 if parts.is_empty() {
4132 return None;
4133 }
4134 Some(crate::run::tail(
4139 &parts.join("\n\n"),
4140 DIAGNOSTIC_MAX.saturating_sub(100),
4141 ))
4142}
4143
4144fn label(status: RunStatus) -> &'static str {
4152 status.as_str()
4153}
4154
4155pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4157 match mode {
4158 "none" => Ok(MergeMode::None),
4159 "local" => Ok(MergeMode::Local),
4160 "pr" => Ok(MergeMode::Pr),
4161 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4162 }
4163}
4164
4165fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4170 mutex
4171 .lock()
4172 .unwrap_or_else(std::sync::PoisonError::into_inner)
4173}
4174
4175#[cfg(test)]
4176mod tests {
4177 use super::*;
4178 use crate::queue::{Source, TaskStatus};
4179 use crate::run::{Candidate, CommandOutcome};
4180 use pretty_assertions::assert_eq;
4181
4182 fn task() -> Task {
4183 Task::new(
4184 "add retries".to_owned(),
4185 "add retries".to_owned(),
4186 PathBuf::from("/repo"),
4187 Source::Human,
4188 )
4189 }
4190
4191 fn interrupt_task(id: &str) -> Task {
4194 let mut t = task();
4195 t.id = id.to_owned();
4196 t.interrupt = true;
4197 t
4198 }
4199
4200 fn task_with_id(id: &str) -> Task {
4202 let mut t = task();
4203 t.id = id.to_owned();
4204 t
4205 }
4206
4207 fn urgent_task(id: &str) -> Task {
4209 let mut t = task();
4210 t.id = id.to_owned();
4211 t.urgent = true;
4212 t
4213 }
4214
4215 #[test]
4220 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4221 assert_eq!(permit_kind(true, false), PermitKind::None);
4222 assert_eq!(permit_kind(true, true), PermitKind::None);
4223 }
4224
4225 #[test]
4230 fn permit_kind_separates_urgent_from_ordinary() {
4231 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4232 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4233 }
4234
4235 #[test]
4242 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4243 let cfg = Config::default();
4244 let repo = Path::new("/any/repo/path");
4245
4246 let reason =
4247 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4248 assert!(reason.contains("1024"), "{reason}");
4249 assert!(
4250 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4251 "{reason}"
4252 );
4253
4254 assert_eq!(
4255 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4256 None,
4257 "exactly at the floor is open"
4258 );
4259 assert_eq!(
4260 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4261 None,
4262 "comfortably above the floor is open"
4263 );
4264 }
4265
4266 #[test]
4267 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4268 let mut cfg = Config::default();
4269 cfg.disk.min_free_bytes = 0;
4270 let repo = Path::new("/any/repo/path");
4271 assert_eq!(
4272 disk_gate_with(repo, &cfg, |_| Ok(0)),
4273 None,
4274 "a zero floor never measures at all"
4275 );
4276 }
4277
4278 #[test]
4279 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
4280 let cfg = Config::default();
4281 let repo = Path::new("/any/repo/path");
4282 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
4283 .expect("a measurement failure must close the gate, not open it");
4284 assert!(reason.contains("could not measure"), "{reason}");
4285 }
4286
4287 #[test]
4288 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
4289 let ordinary = task();
4290 let next = advance_interrupt(
4291 Interrupt::Idle,
4292 std::slice::from_ref(&ordinary.id),
4293 std::slice::from_ref(&ordinary),
4294 );
4295 assert_eq!(next, Interrupt::Idle);
4296 }
4297
4298 #[test]
4299 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
4300 let marked = interrupt_task("marked");
4303 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4304 assert_eq!(next, Interrupt::Idle);
4305 }
4306
4307 #[test]
4308 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
4309 let marked = interrupt_task("marked");
4310 let next = advance_interrupt(
4311 Interrupt::Idle,
4312 &["running".to_owned()],
4313 std::slice::from_ref(&marked),
4314 );
4315 assert_eq!(
4316 next,
4317 Interrupt::Parking {
4318 parked: vec!["running".to_owned()],
4319 interrupt_task: "marked".to_owned(),
4320 }
4321 );
4322 }
4323
4324 #[test]
4333 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
4334 let marked = interrupt_task("marked");
4335
4336 let two = advance_interrupt(
4337 Interrupt::Idle,
4338 &["a".to_owned(), "b".to_owned()],
4339 std::slice::from_ref(&marked),
4340 );
4341 assert_eq!(two, Interrupt::Idle);
4342
4343 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4344 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
4345 }
4346
4347 #[test]
4348 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
4349 let state = Interrupt::Parking {
4350 parked: vec!["running".to_owned()],
4351 interrupt_task: "marked".to_owned(),
4352 };
4353 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
4355 assert_eq!(still_going, state);
4356
4357 let stopped_but_not_yet_dispatched =
4361 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
4362 assert_eq!(stopped_but_not_yet_dispatched, state);
4363
4364 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
4366 assert_eq!(
4367 dispatched,
4368 Interrupt::Running {
4369 parked: vec!["running".to_owned()],
4370 interrupt_task: "marked".to_owned(),
4371 }
4372 );
4373 }
4374
4375 #[test]
4376 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
4377 let state = Interrupt::Running {
4378 parked: vec!["running".to_owned()],
4379 interrupt_task: "marked".to_owned(),
4380 };
4381 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
4382 assert_eq!(still_running, state);
4383
4384 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
4391 assert_eq!(
4392 ended,
4393 Interrupt::Resuming {
4394 parked: vec!["running".to_owned()]
4395 }
4396 );
4397 }
4398
4399 #[test]
4400 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
4401 let state = Interrupt::Resuming {
4402 parked: vec!["running".to_owned()],
4403 };
4404 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
4405 assert_eq!(still_waiting, state);
4406
4407 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
4408 assert_eq!(dispatched, Interrupt::Idle);
4409 }
4410
4411 #[test]
4417 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
4418 {
4419 let state = Interrupt::Parking {
4420 parked: vec!["running".to_owned()],
4421 interrupt_task: "marked".to_owned(),
4422 };
4423 let next = advance_interrupt(state, &[], &[]);
4426 assert_eq!(
4427 next,
4428 Interrupt::Resuming {
4429 parked: vec!["running".to_owned()]
4430 },
4431 "abandoning the interrupt must not abandon the resume it owes"
4432 );
4433 }
4434
4435 #[test]
4438 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
4439 let state = Interrupt::Resuming {
4440 parked: vec!["running".to_owned()],
4441 };
4442 let next = advance_interrupt(state, &[], &[]);
4443 assert_eq!(
4444 next,
4445 Interrupt::Idle,
4446 "nothing is left to wait for; the loop must not stay wedged"
4447 );
4448 }
4449
4450 #[test]
4451 fn disabled_by_config_the_sequence_can_never_leave_idle() {
4452 let marked = interrupt_task("marked");
4453 let next = advance_interrupt_tick(
4454 false,
4455 Interrupt::Idle,
4456 &["running".to_owned()],
4457 std::slice::from_ref(&marked),
4458 );
4459 assert_eq!(
4460 next,
4461 Interrupt::Idle,
4462 "an unmarked, unconfigured daemon must behave exactly as before"
4463 );
4464 }
4465
4466 #[test]
4467 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
4468 let state = Interrupt::Parking {
4469 parked: vec!["running".to_owned()],
4470 interrupt_task: "marked".to_owned(),
4471 };
4472 let candidates = vec![interrupt_task("marked"), task()];
4473 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4474 assert!(
4475 allowed.is_empty(),
4476 "nothing may dispatch - not even the interrupt task itself - \
4477 until the parked run has actually stopped"
4478 );
4479 }
4480
4481 #[test]
4495 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
4496 for state in [
4497 Interrupt::Parking {
4498 parked: vec!["running".to_owned()],
4499 interrupt_task: "marked".to_owned(),
4500 },
4501 Interrupt::Running {
4502 parked: vec!["running".to_owned()],
4503 interrupt_task: "marked".to_owned(),
4504 },
4505 Interrupt::Resuming {
4506 parked: vec!["running".to_owned()],
4507 },
4508 ] {
4509 let candidates = vec![
4510 interrupt_task("marked"),
4511 urgent_task("hot"),
4512 task_with_id("ordinary"),
4513 ];
4514 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4515 assert!(
4516 !allowed.iter().any(|t| t.id == "hot"),
4517 "an urgent candidate must wait out the same gate as anything \
4518 else while the run it would run alongside has not actually \
4519 left flight, for state {state:?}: {allowed:?}"
4520 );
4521 }
4522 }
4523
4524 #[test]
4530 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
4531 let state = Interrupt::Resuming {
4532 parked: vec!["hot".to_owned()],
4533 };
4534 let candidates = vec![urgent_task("hot"), task()];
4535 let allowed = interrupt_gate(&state, &[], candidates);
4536 assert_eq!(
4537 allowed.iter().filter(|t| t.id == "hot").count(),
4538 1,
4539 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
4540 );
4541 }
4542
4543 #[test]
4544 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
4545 let state = Interrupt::Parking {
4546 parked: vec!["running".to_owned()],
4547 interrupt_task: "marked".to_owned(),
4548 };
4549 let other = task();
4550 let candidates = vec![interrupt_task("marked"), other.clone()];
4551 let allowed = interrupt_gate(&state, &[], candidates);
4552 assert_eq!(allowed.len(), 1);
4553 assert_eq!(allowed[0].id, "marked");
4554 }
4555
4556 #[test]
4557 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4558 let state = Interrupt::Running {
4559 parked: vec!["running".to_owned()],
4560 interrupt_task: "marked".to_owned(),
4561 };
4562 let candidates = vec![task(), task()];
4563 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4564 assert!(allowed.is_empty());
4565 }
4566
4567 #[test]
4574 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4575 let state = Interrupt::Resuming {
4576 parked: vec!["a".to_owned(), "c".to_owned()],
4577 };
4578 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4579 let allowed = interrupt_gate(&state, &[], candidates);
4580 assert_eq!(
4581 allowed.len(),
4582 1,
4583 "at most one candidate may be offered while resuming: {allowed:?}"
4584 );
4585 assert_eq!(allowed[0].id, "a");
4586 }
4587
4588 #[test]
4589 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4590 let state = Interrupt::Resuming {
4591 parked: vec!["a".to_owned()],
4592 };
4593 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4594 assert!(allowed.is_empty());
4595 }
4596
4597 #[test]
4603 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4604 let running = task(); let marked = interrupt_task("marked");
4606
4607 let mut state = Interrupt::Idle;
4608 let in_flight = vec![running.id.clone()];
4610 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4611 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4612 assert!(gated.is_empty(), "still waiting on `running` to park");
4613
4614 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4616 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4617 assert_eq!(
4618 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4619 vec!["marked"],
4620 "only the interrupt task may be offered to the dispatcher now"
4621 );
4622
4623 state = advance_interrupt_tick(
4625 true,
4626 state,
4627 &["marked".to_owned()],
4628 std::slice::from_ref(&running),
4629 );
4630 let gated = interrupt_gate(
4631 &state,
4632 &["marked".to_owned()],
4633 vec![marked.clone(), running.clone()],
4634 );
4635 assert!(
4636 gated.is_empty(),
4637 "the parked run must not be offered back while the interrupt \
4638 task is still running"
4639 );
4640
4641 let other = task_with_id("other");
4645 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4646 assert_eq!(
4647 state,
4648 Interrupt::Resuming {
4649 parked: vec![running.id.clone()]
4650 }
4651 );
4652 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4653 assert_eq!(
4654 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4655 vec![running.id.as_str()],
4656 "exactly the parked run resumes - not the unrelated task, even \
4657 though it was offered first"
4658 );
4659
4660 state = advance_interrupt_tick(
4664 true,
4665 state,
4666 std::slice::from_ref(&running.id),
4667 std::slice::from_ref(&other),
4668 );
4669 assert_eq!(state, Interrupt::Idle);
4670 let gated = interrupt_gate(
4671 &state,
4672 std::slice::from_ref(&running.id),
4673 vec![other.clone()],
4674 );
4675 assert_eq!(
4676 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4677 vec![other.id.as_str()],
4678 "ordinary dispatch is unrestricted again"
4679 );
4680 }
4681
4682 #[test]
4683 fn every_run_status_settles_the_task_it_came_from() {
4684 let table = [
4686 (RunStatus::Merged, TaskStatus::Done, 1),
4687 (RunStatus::Ready, TaskStatus::Done, 1),
4688 (RunStatus::Stalled, TaskStatus::Failed, 0),
4689 (RunStatus::Blocked, TaskStatus::Failed, 1),
4690 (RunStatus::Failed, TaskStatus::Failed, 1),
4691 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4692 (RunStatus::Prep, TaskStatus::Failed, 1),
4693 (RunStatus::Implementing, TaskStatus::Failed, 1),
4694 (RunStatus::Judging, TaskStatus::Failed, 1),
4695 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4696 (RunStatus::Voting, TaskStatus::Failed, 1),
4697 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4698 (RunStatus::Gating, TaskStatus::Failed, 1),
4699 ];
4700 for (run, want, attempts) in table {
4701 let mut t = task();
4702 t.start("20260902-000000-aaaa".to_owned());
4703 settle(
4704 &mut t,
4705 Verdict {
4706 status: run,
4707 left_pr: false,
4708 parked: false,
4709 quota_hit: matches!(run, RunStatus::Stalled),
4710 no_viable_candidates: false,
4711 },
4712 "why",
4713 2,
4714 );
4715 assert_eq!(t.status, want, "task status after {}", label(run));
4716 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4717 }
4718 }
4719
4720 #[test]
4721 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4722 let mut stalled = task();
4723 stalled.start("20260902-000000-aaaa".to_owned());
4724 settle(
4725 &mut stalled,
4726 Verdict {
4727 status: RunStatus::Stalled,
4728 left_pr: false,
4729 parked: false,
4730 quota_hit: true,
4731 no_viable_candidates: false,
4732 },
4733 "quota",
4734 1,
4735 );
4736 assert_eq!(stalled.attempts, 0);
4737 assert!(
4738 stalled.status.runnable(),
4739 "a machine problem must leave the task in line"
4740 );
4741
4742 let mut blocked = task();
4743 blocked.start("20260902-000000-aaaa".to_owned());
4744 settle(
4745 &mut blocked,
4746 Verdict {
4747 status: RunStatus::Blocked,
4748 left_pr: false,
4749 parked: false,
4750 quota_hit: false,
4751 no_viable_candidates: false,
4752 },
4753 "findings open",
4754 1,
4755 );
4756 assert_eq!(blocked.attempts, 1);
4757 assert_eq!(
4758 blocked.status,
4759 TaskStatus::Held,
4760 "the last attempt hands the task to a human"
4761 );
4762 }
4763
4764 #[test]
4765 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4766 let mut delivered = task();
4769 delivered.start("20260903-080619-01c2".to_owned());
4770 settle(
4771 &mut delivered,
4772 Verdict {
4773 status: RunStatus::Blocked,
4774 left_pr: true,
4775 parked: false,
4776 quota_hit: false,
4777 no_viable_candidates: false,
4778 },
4779 "no check status",
4780 4,
4781 );
4782 assert_eq!(
4783 delivered.status,
4784 TaskStatus::Held,
4785 "a pull request waiting on CI or a person is not a retryable failure"
4786 );
4787 assert!(
4788 !delivered.status.runnable(),
4789 "the loop must not pick this task up again"
4790 );
4791 assert_eq!(
4792 delivered.last_error.as_deref(),
4793 Some("no check status"),
4794 "the operator needs to be told what the gate was waiting for"
4795 );
4796
4797 let mut empty_handed = task();
4800 empty_handed.start("20260903-080619-01c2".to_owned());
4801 settle(
4802 &mut empty_handed,
4803 Verdict {
4804 status: RunStatus::Blocked,
4805 left_pr: false,
4806 parked: false,
4807 quota_hit: false,
4808 no_viable_candidates: false,
4809 },
4810 "findings open",
4811 4,
4812 );
4813 assert_eq!(empty_handed.status, TaskStatus::Failed);
4814 assert!(empty_handed.status.runnable());
4815 }
4816
4817 #[test]
4818 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4819 let mut noop = task();
4825 noop.start("20260912-131304-391f".to_owned());
4826 settle(
4827 &mut noop,
4828 Verdict {
4829 status: RunStatus::VerifiedNoop,
4830 left_pr: false,
4831 parked: false,
4832 quota_hit: false,
4833 no_viable_candidates: true,
4834 },
4835 "candidate A: already fixed by b32cfc4, on main",
4836 4,
4837 );
4838 assert_eq!(
4839 noop.status,
4840 TaskStatus::Held,
4841 "an unverified claim is a request for a human, not a failure"
4842 );
4843 assert!(
4844 !noop.status.runnable(),
4845 "the loop must not requeue this on the same unverified claim"
4846 );
4847 assert_eq!(noop.attempts, 1);
4852 }
4853
4854 #[test]
4855 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4856 let mut parked = task();
4861 parked.start("20260903-183634-2d98".to_owned());
4862 settle(
4863 &mut parked,
4864 Verdict {
4865 status: RunStatus::Implementing,
4866 left_pr: false,
4867 quota_hit: false,
4868 parked: true,
4869 no_viable_candidates: false,
4870 },
4871 "parked after `implementing`",
4872 2,
4873 );
4874 assert_eq!(parked.attempts, 0, "a park is refunded");
4875 assert!(
4876 parked.status.runnable(),
4877 "and the task stays in line so the next loop resumes its run"
4878 );
4879 assert_eq!(parked.status, TaskStatus::Parked);
4880 assert_eq!(
4881 parked.park_reason.as_deref(),
4882 Some("parked after `implementing`"),
4883 "the card says where it stopped"
4884 );
4885 assert_eq!(parked.last_error, None, "nothing failed");
4886
4887 let mut broken = task();
4891 broken.start("20260903-183634-2d98".to_owned());
4892 settle(
4893 &mut broken,
4894 Verdict {
4895 status: RunStatus::Implementing,
4896 left_pr: false,
4897 quota_hit: false,
4898 parked: false,
4899 no_viable_candidates: false,
4900 },
4901 "returned mid-flight",
4902 2,
4903 );
4904 assert_eq!(broken.attempts, 1);
4905 }
4906
4907 #[test]
4908 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4909 let mut flaky = task();
4914 flaky.start("20260903-123023-e633".to_owned());
4915 settle(
4916 &mut flaky,
4917 Verdict {
4918 status: RunStatus::Stalled,
4919 left_pr: false,
4920 parked: false,
4921 quota_hit: false,
4922 no_viable_candidates: false,
4923 },
4924 "verdict rests on 1 of 3 judges",
4925 2,
4926 );
4927 assert_eq!(
4928 flaky.attempts, 1,
4929 "flakiness spends an attempt, so `max_attempts` still bounds it"
4930 );
4931 assert!(flaky.status.runnable(), "and it is still worth retrying");
4932
4933 let mut limited = task();
4935 limited.start("20260903-123023-e633".to_owned());
4936 settle(
4937 &mut limited,
4938 Verdict {
4939 status: RunStatus::Stalled,
4940 left_pr: false,
4941 parked: false,
4942 quota_hit: true,
4943 no_viable_candidates: false,
4944 },
4945 "judge-2, judge-3 out of quota",
4946 2,
4947 );
4948 assert_eq!(limited.attempts, 0, "a quota window is refunded");
4949 assert!(limited.status.runnable());
4950
4951 let mut worn = task();
4954 for _ in 0..2 {
4955 worn.release();
4956 }
4957 worn.start("20260903-123023-e633".to_owned());
4958 worn.attempts = 2;
4959 settle(
4960 &mut worn,
4961 Verdict {
4962 status: RunStatus::Stalled,
4963 left_pr: false,
4964 parked: false,
4965 quota_hit: false,
4966 no_viable_candidates: false,
4967 },
4968 "no quorum again",
4969 2,
4970 );
4971 assert_eq!(worn.status, TaskStatus::Held);
4972 assert!(!worn.status.runnable());
4973 }
4974
4975 #[test]
4976 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4977 let mut wiped_out = task();
4984 wiped_out.start("20260907-025000-a1b2".to_owned());
4985 settle(
4986 &mut wiped_out,
4987 Verdict {
4988 status: RunStatus::Failed,
4989 left_pr: false,
4990 parked: false,
4991 quota_hit: true,
4992 no_viable_candidates: true,
4993 },
4994 "no candidate produced a change; nothing to judge",
4995 2,
4996 );
4997 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4998 assert!(
4999 wiped_out.status.runnable(),
5000 "a machine problem must leave the task in line"
5001 );
5002
5003 let mut partial_progress = task();
5009 partial_progress.start("20260907-025500-c3d4".to_owned());
5010 settle(
5011 &mut partial_progress,
5012 Verdict {
5013 status: RunStatus::Failed,
5014 left_pr: false,
5015 parked: false,
5016 quota_hit: true,
5017 no_viable_candidates: false,
5018 },
5019 "gate failed on the winning candidate",
5020 2,
5021 );
5022 assert_eq!(
5023 partial_progress.attempts, 1,
5024 "a candidate that actually produced a change spends the attempt \
5025 even though some other seat hit its quota"
5026 );
5027 assert!(partial_progress.status.runnable());
5028 }
5029
5030 #[test]
5031 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5032 let mut t = task();
5038 t.start("20260907-025000-a1b2".to_owned());
5039 let mut state = run_state(RunStatus::Failed);
5040 state.quota.push(QuotaLoss {
5041 seat: "cand-a".to_owned(),
5042 node: "implement".to_owned(),
5043 at: Timestamp::now(),
5044 reset: None,
5045 });
5046 assert!(
5047 state.viable().is_empty(),
5048 "no candidate was added, so nothing is viable"
5049 );
5050 reclaim(&mut t, Some(state), 2, "en");
5051 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5052 assert!(t.status.runnable());
5053 }
5054
5055 #[test]
5056 fn a_held_task_is_never_offered_to_the_loop() {
5057 let dir = tempfile::tempdir().unwrap();
5058 let queue = Queue::at(dir.path().to_path_buf());
5059 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5060 let mut t = task();
5061 t.id = format!("2026090{n}-000000-000{n}");
5062 t.priority = priority;
5063 queue.put(&mut t).unwrap();
5064 }
5065 let mut held = task();
5066 held.id = "20260909-000000-9999".to_owned();
5067 held.priority = 99;
5068 held.hold_machine(None);
5069 queue.put(&mut held).unwrap();
5070
5071 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5072 assert_eq!(order.len(), 3);
5073 assert!(!order.contains(&held.id));
5074 assert_eq!(
5075 order.first().cloned(),
5076 queue.next_runnable().map(|t| t.id),
5077 "the loop's first candidate is exactly what the queue offers"
5078 );
5079 assert_eq!(
5080 order,
5081 vec![
5082 "20260902-000000-0002".to_owned(),
5083 "20260903-000000-0003".to_owned(),
5084 "20260901-000000-0001".to_owned(),
5085 ],
5086 "priority first, then oldest, so nothing starves"
5087 );
5088 }
5089
5090 #[test]
5091 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5092 let dir = tempfile::tempdir().unwrap();
5093 let queue = Queue::at(dir.path().to_path_buf());
5094 let mut old = task();
5095 old.id = "20260101-000000-old0".to_owned();
5096 queue.put(&mut old).unwrap();
5097 let mut fresh = task();
5098 fresh.id = "20260101-000000-new0".to_owned();
5099 queue.put(&mut fresh).unwrap();
5100
5101 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5105 std::thread::sleep(Duration::from_millis(60));
5106 let live = queue.claim(&fresh.id).unwrap();
5107
5108 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5109 assert_eq!(swept, vec![old.id.clone()]);
5110 assert!(
5111 queue.claim(&old.id).is_ok(),
5112 "an unparseable lock older than the threshold is swept"
5113 );
5114 assert!(
5115 queue.claim(&fresh.id).is_err(),
5116 "a live pid protects its lock regardless of age"
5117 );
5118 drop(live);
5119 }
5120
5121 #[test]
5122 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5123 let dir = tempfile::tempdir().unwrap();
5133 let queue = Queue::at(dir.path().to_path_buf());
5134 let mut t = task();
5135 t.id = "20260101-000000-live".to_owned();
5136 queue.put(&mut t).unwrap();
5137
5138 let claim = queue.claim(&t.id).unwrap();
5139 std::thread::sleep(Duration::from_millis(60));
5140
5141 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5142 assert!(
5143 swept.is_empty(),
5144 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5145 );
5146 assert!(
5147 queue.claim(&t.id).is_err(),
5148 "the lock still protects its task"
5149 );
5150 drop(claim);
5151 }
5152
5153 fn injected_dead_pid() -> u32 {
5156 std::process::id().checked_add(1).unwrap_or(1)
5157 }
5158
5159 #[test]
5160 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5161 let dir = tempfile::tempdir().unwrap();
5162 let queue = Queue::at(dir.path().to_path_buf());
5163 let mut t = task();
5164 t.id = "20260101-000000-dead".to_owned();
5165 queue.put(&mut t).unwrap();
5166 let dead_pid = injected_dead_pid();
5167
5168 std::fs::write(
5173 dir.path().join(format!("{}.lock", t.id)),
5174 dead_pid.to_string(),
5175 )
5176 .unwrap();
5177
5178 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5179 pid != dead_pid
5180 });
5181 assert_eq!(
5182 swept,
5183 vec![t.id.clone()],
5184 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5185 );
5186 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5187 }
5188
5189 #[test]
5190 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5191 let dir = tempfile::tempdir().unwrap();
5192 let queue = Queue::at(dir.path().to_path_buf());
5193 let mut t = task();
5194 t.id = "20260101-000000-late".to_owned();
5195 queue.put(&mut t).unwrap();
5196 let dead_pid = injected_dead_pid();
5197
5198 assert!(
5201 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5202 "nothing has claimed the task yet"
5203 );
5204
5205 std::fs::write(
5208 dir.path().join(format!("{}.lock", t.id)),
5209 dead_pid.to_string(),
5210 )
5211 .unwrap();
5212
5213 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5217 pid != dead_pid
5218 });
5219 assert_eq!(swept, vec![t.id.clone()]);
5220 }
5221
5222 #[test]
5223 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5224 crate::run::pin_test_home();
5229 let dir = tempfile::tempdir().unwrap();
5230 let queue = Queue::at(dir.path().to_path_buf());
5231 let mut t = task();
5232 t.id = "20260101-000000-crsh".to_owned();
5233 t.status = TaskStatus::Running;
5234 t.attempts = 1;
5235 t.runs.push("20260904-000000-4043".to_owned());
5239 queue.put(&mut t).unwrap();
5240 let dead_pid = injected_dead_pid();
5241
5242 std::fs::write(
5245 dir.path().join(format!("{}.lock", t.id)),
5246 dead_pid.to_string(),
5247 )
5248 .unwrap();
5249
5250 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5256 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5257
5258 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5259 pid != dead_pid
5260 });
5261 assert_eq!(swept, vec![t.id.clone()]);
5262
5263 let reclaimed = reclaim_orphaned_running(&queue, 2);
5264 assert_eq!(reclaimed, vec![t.id.clone()]);
5265 let after = queue.get(&t.id).unwrap();
5266 assert_eq!(
5267 after.status,
5268 TaskStatus::Held,
5269 "no run.json to recover from, so a human is asked"
5270 );
5271 assert_eq!(
5272 after.runs,
5273 vec!["20260904-000000-4043".to_owned()],
5274 "the crashed run's id is kept as evidence, not discarded"
5275 );
5276 }
5277
5278 #[test]
5279 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
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-unknown".to_owned();
5284 queue.put(&mut t).unwrap();
5285 let dead_pid = injected_dead_pid();
5286 std::fs::write(
5287 dir.path().join(format!("{}.lock", t.id)),
5288 dead_pid.to_string(),
5289 )
5290 .unwrap();
5291
5292 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
5293 assert!(swept.is_empty(), "an unknown pid must keep its lock");
5294 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
5295 }
5296
5297 fn run_state_in(status: RunStatus, language: &str) -> RunState {
5298 let mut s = run_state(status);
5299 s.config.graph.language = language.to_owned();
5300 s
5301 }
5302
5303 fn unstarted_verdict(status: RunStatus) -> Verdict {
5304 Verdict {
5305 status,
5306 left_pr: false,
5307 quota_hit: false,
5308 parked: false,
5309 no_viable_candidates: false,
5310 }
5311 }
5312
5313 #[test]
5314 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
5315 let mut t = task();
5316 t.attempts = 1;
5317 settle_in(
5318 &mut t,
5319 unstarted_verdict(RunStatus::AlreadyInBase),
5320 "already in main",
5321 1,
5322 phrases("en"),
5323 );
5324 assert_eq!(t.status, TaskStatus::Done);
5325 assert_eq!(t.attempts, 0);
5326 }
5327
5328 #[test]
5329 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
5330 let reason = |language: &str| {
5331 let mut t = task();
5332 settle_in(
5333 &mut t,
5334 unstarted_verdict(RunStatus::Judging),
5335 "boom",
5336 1,
5337 phrases(language),
5338 );
5339 t.last_error.or(t.hold_reason).unwrap_or_default()
5340 };
5341 assert!(
5342 reason("en").starts_with("the graph stopped at `"),
5343 "{}",
5344 reason("en")
5345 );
5346 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
5347 assert!(reason("日本語").contains("boom"));
5348 assert_eq!(reason("fr"), reason("en"));
5349 }
5350
5351 #[test]
5352 fn describe_follows_the_run_language_and_keeps_the_run_id() {
5353 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
5354 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
5355 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
5356 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
5357 assert!(ja.contains("[run "), "{ja}");
5358 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
5359 assert!(ended.starts_with("run 終了: "), "{ended}");
5360 let mut de = run_state_in(RunStatus::Failed, "de");
5361 let mut en = run_state_in(RunStatus::Failed, "en");
5362 de.id = "same".to_owned();
5363 en.id = "same".to_owned();
5364 assert_eq!(describe(&de), describe(&en));
5365 }
5366
5367 #[test]
5368 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
5369 use crate::handover::Refused;
5370 let cases = [
5371 Refused::Foreign {
5372 branch: "b".into(),
5373 path: "/w/x".into(),
5374 why: "made by hand".into(),
5375 },
5376 Refused::Unsafe {
5377 branch: "b".into(),
5378 path: "/w/x".into(),
5379 why: "its worktree has uncommitted changes (a.rs)".into(),
5380 },
5381 Refused::ReleaseFailed {
5382 branch: "b".into(),
5383 path: "/w/x".into(),
5384 run: "ab12".into(),
5385 },
5386 ];
5387 for r in &cases {
5388 let en = (phrases("en").handover_refused)(r);
5389 assert_eq!(en, r.to_string());
5390 let ja = (phrases("ja").handover_refused)(r);
5391 assert!(
5392 !ja.contains("is checked out") && !ja.contains("try again"),
5393 "{ja}"
5394 );
5395 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
5396 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
5397 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
5398 }
5399 }
5400 assert!(phrases("en").handover_hint.contains("release the task"));
5401 assert!(phrases("ja").handover_hint.contains("解放"));
5402 }
5403
5404 #[test]
5405 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
5406 let build = |lang: &str| {
5407 let mut s = run_state_in(RunStatus::Blocked, lang);
5408 s.id = "same".to_owned();
5409 s.config.graph.review_rounds = 3;
5410 let mut r = review_round(3);
5411 r.expected = 3;
5412 r.answered = 1;
5413 s.reviews.push(r);
5414 s.event(
5415 "review",
5416 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
5417 );
5418 s
5419 };
5420 let en = describe(&build("en"));
5421 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
5422 let ja = describe(&build("ja"));
5423 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
5424 assert!(!ja.contains("never answered"), "{ja}");
5425 assert!(ja.contains("[run "), "{ja}");
5426
5427 let mut failed = build("ja");
5430 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
5431 command: "cargo test".to_owned(),
5432 code: Some(1),
5433 output_tail: String::new(),
5434 duration_ms: 0,
5435 resource_blocked: false,
5436 });
5437 failed.event("review", "stopped; e2e failed: cargo test");
5438 let ja = describe(&failed);
5439 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
5440 assert!(!ja.contains("席のレビュアー"), "{ja}");
5441 }
5442
5443 #[test]
5444 fn refusals_and_recovery_prose_follow_the_language() {
5445 let t = held_task_with("r1");
5446 let q = action_question(
5447 "r1",
5448 ask::ChoiceAction::Resume {
5449 run: "r1".to_owned(),
5450 },
5451 );
5452 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
5453 ActionDecision::Refuse(s) => s,
5454 other => panic!("{other:?}"),
5455 };
5456 assert!(refuse(phrases("en")).contains("could not be read: gone"));
5457 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
5458 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
5459
5460 let mut held = task();
5461 reclaim(&mut held, None, 2, "ja");
5462 assert!(held.hold_reason.unwrap().contains("保留にしました"));
5463 let mut held = task();
5464 reclaim(&mut held, None, 2, "xx");
5465 assert!(held.hold_reason.unwrap().contains("held for a human"));
5466 }
5467
5468 fn run_state(status: RunStatus) -> RunState {
5469 let mut state = RunState::new(
5470 PathBuf::from("/repo"),
5471 "main".to_owned(),
5472 "abc1234def".to_owned(),
5473 "add retries".to_owned(),
5474 Config::default(),
5475 );
5476 state.status = status;
5477 state
5478 }
5479
5480 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
5481 Candidate {
5482 index: 0,
5483 label,
5484 agent: "claude".to_owned(),
5485 branch: format!("magi/x/{label}"),
5486 worktree: PathBuf::from("/repo"),
5487 summary: summary.to_owned(),
5488 stat: String::new(),
5489 files: 0,
5490 commits: usize::from(!empty),
5491 empty,
5492 failed: failed.map(str::to_owned),
5493 verified_noop: None,
5494 duration_ms: 0,
5495 folded: false,
5496 }
5497 }
5498
5499 #[test]
5500 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
5501 let mut state = run_state(RunStatus::Blocked);
5502 state.gate = vec![
5503 CommandOutcome {
5504 command: "cargo make check".to_owned(),
5505 code: Some(0),
5506 output_tail: "ok".to_owned(),
5507 duration_ms: 0,
5508 resource_blocked: false,
5509 },
5510 CommandOutcome {
5511 command: "cargo test".to_owned(),
5512 code: Some(101),
5513 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
5514 duration_ms: 0,
5515 resource_blocked: false,
5516 },
5517 ];
5518 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
5519 assert!(d.contains("cargo test"), "{d}");
5520 assert!(
5521 !d.contains("cargo make check"),
5522 "a passing check is not a diagnostic: {d}"
5523 );
5524 assert!(d.contains("assertion failed"), "{d}");
5525 }
5526
5527 #[test]
5528 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
5529 let mut state = run_state(RunStatus::Blocked);
5530 state.event(
5531 "land",
5532 "stopped: the fixer produced no commit while 2 check(s) were failing \
5533 (build, lint); stopping instead of looping on an unchanged tree",
5534 );
5535 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
5536 assert!(d.contains("build"), "{d}");
5537 assert!(d.contains("lint"), "{d}");
5538 assert!(d.contains("fixer produced no commit"), "{d}");
5539 }
5540
5541 #[test]
5542 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
5543 let state = run_state(RunStatus::VerifiedNoop);
5548 let d = describe(&state);
5549 assert!(
5550 d.contains("agent-verified no-op"),
5551 "expected the display label, not the wire spelling: {d}"
5552 );
5553 assert!(!d.contains("verified_noop"), "{d}");
5554 }
5555
5556 #[test]
5557 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
5558 let mut state = run_state(RunStatus::Failed);
5564 state.candidates = vec![candidate(
5565 'A',
5566 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
5567 true,
5568 None,
5569 )];
5570 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
5571 assert!(d.contains("candidate A"), "{d}");
5572 assert!(d.contains("tagged v1.2.3"), "{d}");
5573 }
5574
5575 #[test]
5576 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
5577 let mut state = run_state(RunStatus::Failed);
5578 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
5579 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
5580 assert!(d.contains("candidate A"), "{d}");
5581 assert!(d.contains("agent timed out"), "{d}");
5582 }
5583
5584 #[test]
5585 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
5586 let mut state = run_state(RunStatus::Failed);
5589 state.candidates = vec![candidate('A', "did the work", false, None)];
5590 assert!(diagnostic(&state).is_none());
5591 }
5592
5593 #[test]
5594 fn diagnostic_is_bounded_however_much_a_run_printed() {
5595 let mut state = run_state(RunStatus::Blocked);
5596 state.gate = vec![
5597 CommandOutcome {
5598 command: "cargo test".to_owned(),
5599 code: Some(101),
5600 output_tail: "x".repeat(50_000),
5601 duration_ms: 0,
5602 resource_blocked: false,
5603 },
5604 CommandOutcome {
5605 command: "cargo clippy".to_owned(),
5606 code: Some(1),
5607 output_tail: "y".repeat(50_000),
5608 duration_ms: 0,
5609 resource_blocked: false,
5610 },
5611 ];
5612 state.candidates = vec![
5613 candidate('A', &"z".repeat(50_000), true, None),
5614 candidate('B', &"w".repeat(50_000), true, None),
5615 ];
5616 let d = diagnostic(&state).expect("plenty here to diagnose");
5617 assert!(
5618 d.len() <= DIAGNOSTIC_MAX,
5619 "diagnostic grew to {} bytes, unbounded",
5620 d.len()
5621 );
5622 }
5623
5624 #[test]
5625 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
5626 let mut state = run_state(RunStatus::Blocked);
5627 state.gate = vec![CommandOutcome {
5628 command: "cargo test".to_owned(),
5629 code: Some(101),
5630 output_tail: "assertion failed".to_owned(),
5631 duration_ms: 0,
5632 resource_blocked: false,
5633 }];
5634 let verdict = Verdict {
5635 status: RunStatus::Blocked,
5636 left_pr: false,
5637 quota_hit: false,
5638 parked: false,
5639 no_viable_candidates: false,
5640 };
5641
5642 let mut t = task();
5645 t.start("run-1".to_owned());
5646 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5647 assert_eq!(t.status, TaskStatus::Failed);
5648 assert!(t.diagnostic.is_none());
5649
5650 t.start("run-2".to_owned());
5653 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5654 assert_eq!(t.status, TaskStatus::Held);
5655 let d = t.diagnostic.expect("a held task must carry its diagnostic");
5656 assert!(d.contains("cargo test"), "{d}");
5657 }
5658
5659 #[test]
5660 fn a_held_task_names_the_open_question_it_is_waiting_on() {
5661 crate::run::pin_test_home();
5666 let home = crate::run::home();
5667 let state = run_state(RunStatus::VerifiedNoop);
5668 let mut q = ask::Question::new(
5669 state.id.clone(),
5670 "implement".to_owned(),
5671 "impl-A".to_owned(),
5672 "is this really a no-op?".to_owned(),
5673 String::new(),
5674 Vec::new(),
5675 );
5676 Questions::at(home.join("questions")).put(&mut q).unwrap();
5677
5678 let verdict = Verdict {
5679 status: RunStatus::VerifiedNoop,
5680 left_pr: false,
5681 quota_hit: false,
5682 parked: false,
5683 no_viable_candidates: false,
5684 };
5685 let mut t = task();
5686 t.start(state.id.clone());
5687 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5688
5689 assert_eq!(t.status, TaskStatus::Held);
5690 let reason = t.hold_reason.expect("a held task must record why");
5691 assert!(
5692 reason.starts_with("run ended agent-verified no-op"),
5693 "the original settle reason must survive unchanged: {reason}"
5694 );
5695 assert!(
5696 reason.contains(q.short()),
5697 "the open question's id must be named so the notice is actionable: {reason}"
5698 );
5699 }
5700
5701 #[test]
5702 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
5703 crate::run::pin_test_home();
5704 let state = run_state(RunStatus::VerifiedNoop);
5705
5706 let verdict = Verdict {
5707 status: RunStatus::VerifiedNoop,
5708 left_pr: false,
5709 quota_hit: false,
5710 parked: false,
5711 no_viable_candidates: false,
5712 };
5713 let mut t = task();
5714 t.start(state.id.clone());
5715 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5716
5717 assert_eq!(t.status, TaskStatus::Held);
5718 assert_eq!(
5719 t.hold_reason.as_deref(),
5720 Some("run ended agent-verified no-op"),
5721 "nothing to append when the question was already answered or never asked"
5722 );
5723 }
5724
5725 #[test]
5726 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5727 crate::run::pin_test_home();
5728 let mut first = run_state(RunStatus::Blocked);
5729 first.id = "20260101-000000-sup1".to_owned();
5730 first.save().unwrap();
5731 let mut second = run_state(RunStatus::Merged);
5732 second.id = "20260101-000000-sup2".to_owned();
5733 second.save().unwrap();
5734
5735 let mut t = task();
5736 t.runs = vec![first.id.clone(), second.id.clone()];
5737 t.status = TaskStatus::Done;
5738
5739 supersede_prior_runs(&t, &crate::run::home());
5740
5741 assert_eq!(
5742 RunState::load(&first.id).unwrap().status,
5743 RunStatus::Superseded,
5744 "the first attempt's Blocked no longer needs anyone's attention"
5745 );
5746 assert_eq!(
5747 RunState::load(&second.id).unwrap().status,
5748 RunStatus::Merged,
5749 "the run that actually succeeded is left exactly as it was"
5750 );
5751 }
5752
5753 #[test]
5754 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5755 crate::run::pin_test_home();
5761 let mut first = run_state(RunStatus::Blocked);
5762 first.id = "20260101-000000-sup9".to_owned();
5763 first.driver_pid = Some(std::process::id());
5766 first.driver_started_at = Some(
5767 crate::proc::process_started_at(std::process::id())
5768 .expect("this test process's own start time must be queryable"),
5769 );
5770 first.save().unwrap();
5771 let mut second = run_state(RunStatus::Merged);
5772 second.id = "20260101-000000-supa".to_owned();
5773 second.save().unwrap();
5774
5775 let mut t = task();
5776 t.runs = vec![first.id.clone(), second.id.clone()];
5777 t.status = TaskStatus::Done;
5778
5779 supersede_prior_runs(&t, &crate::run::home());
5780
5781 assert_eq!(
5782 RunState::load(&first.id).unwrap().status,
5783 RunStatus::Blocked,
5784 "a live driver_pid means something is still actually working this run, \
5785 even though no daemon claims it - rewriting under it would just be \
5786 undone the next time that process saves"
5787 );
5788 }
5789
5790 #[test]
5791 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5792 let dir = tempfile::tempdir().unwrap();
5798 let home = dir.path().to_path_buf();
5799 let queue = Queue::at(dir.path().join("queue"));
5800
5801 let mut first = run_state(RunStatus::Blocked);
5802 first.id = "20260101-000000-supd".to_owned();
5803 first.driver_pid = Some(std::process::id());
5804 first.driver_started_at = Some(
5805 crate::proc::process_started_at(std::process::id())
5806 .expect("this test process's own start time must be queryable"),
5807 );
5808 first.save_under(&home).unwrap();
5809 let mut second = run_state(RunStatus::Merged);
5810 second.id = "20260101-000000-supe".to_owned();
5811 second.save_under(&home).unwrap();
5812
5813 let mut t = task();
5814 t.runs = vec![first.id.clone(), second.id.clone()];
5815 t.status = TaskStatus::Done;
5816 queue.put(&mut t).unwrap();
5817
5818 resweep_superseded_attempts(&queue, &home);
5819 assert_eq!(
5820 RunState::load_under(&first.id, &home).unwrap().status,
5821 RunStatus::Blocked,
5822 "still live on the first pass, so still untouched"
5823 );
5824
5825 let mut stale = RunState::load_under(&first.id, &home).unwrap();
5831 stale.driver_started_at = Some("1".to_owned());
5832 stale.save_under(&home).unwrap();
5833
5834 resweep_superseded_attempts(&queue, &home);
5835 assert_eq!(
5836 RunState::load_under(&first.id, &home).unwrap().status,
5837 RunStatus::Superseded,
5838 "the second pass catches up what the first one correctly skipped"
5839 );
5840 }
5841
5842 #[test]
5843 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5844 crate::run::pin_test_home();
5845 let mut first = run_state(RunStatus::Blocked);
5846 first.id = "20260101-000000-sup3".to_owned();
5847 first.save().unwrap();
5848 let mut second = run_state(RunStatus::Blocked);
5849 second.id = "20260101-000000-sup4".to_owned();
5850 second.save().unwrap();
5851
5852 let mut t = task();
5853 t.runs = vec![first.id.clone(), second.id.clone()];
5854 t.status = TaskStatus::Failed;
5858
5859 supersede_prior_runs(&t, &crate::run::home());
5860
5861 assert_eq!(
5862 RunState::load(&first.id).unwrap().status,
5863 RunStatus::Blocked
5864 );
5865 assert_eq!(
5866 RunState::load(&second.id).unwrap().status,
5867 RunStatus::Blocked
5868 );
5869 }
5870
5871 #[test]
5872 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5873 crate::run::pin_test_home();
5877 let mut first = run_state(RunStatus::Blocked);
5878 first.id = "20260101-000000-sup5".to_owned();
5879 first.save().unwrap();
5880
5881 let mut t = task();
5882 t.runs = vec![first.id.clone()];
5883 t.status = TaskStatus::Done;
5884
5885 supersede_prior_runs(&t, &crate::run::home());
5886
5887 assert_eq!(
5888 RunState::load(&first.id).unwrap().status,
5889 RunStatus::Blocked,
5890 "a single-attempt task has no earlier run to supersede"
5891 );
5892 }
5893
5894 #[test]
5895 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
5896 crate::run::pin_test_home();
5903 let mut first = run_state(RunStatus::Blocked);
5904 first.id = "20260101-000000-supb".to_owned();
5905 first.save().unwrap();
5906 let mut second = run_state(RunStatus::Failed);
5907 second.id = "20260101-000000-supc".to_owned();
5908 second.save().unwrap();
5909
5910 let mut t = task();
5911 t.runs = vec![first.id.clone(), second.id.clone()];
5912 t.status = TaskStatus::Done;
5913
5914 supersede_prior_runs(&t, &crate::run::home());
5915
5916 assert_eq!(
5917 RunState::load(&first.id).unwrap().status,
5918 RunStatus::Blocked,
5919 "the task's last attempt never landed, so there is nothing here \
5920 actually superseding it"
5921 );
5922 }
5923
5924 #[test]
5925 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
5926 crate::run::pin_test_home();
5930 let mut failed = run_state(RunStatus::Failed);
5931 failed.id = "20260101-000000-sup6".to_owned();
5932 failed.save().unwrap();
5933 let mut noop = run_state(RunStatus::VerifiedNoop);
5934 noop.id = "20260101-000000-sup7".to_owned();
5935 noop.save().unwrap();
5936 let mut winner = run_state(RunStatus::Ready);
5937 winner.id = "20260101-000000-sup8".to_owned();
5938 winner.save().unwrap();
5939
5940 let mut t = task();
5941 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
5942 t.status = TaskStatus::Done;
5943
5944 supersede_prior_runs(&t, &crate::run::home());
5945
5946 assert_eq!(
5947 RunState::load(&failed.id).unwrap().status,
5948 RunStatus::Failed
5949 );
5950 assert_eq!(
5951 RunState::load(&noop.id).unwrap().status,
5952 RunStatus::VerifiedNoop
5953 );
5954 }
5955
5956 fn approval_question(run: &str) -> ask::Question {
5957 ask::Question::new(
5958 run.to_owned(),
5959 land::APPROVAL_NODE.to_owned(),
5960 "land".to_owned(),
5961 "merge?".to_owned(),
5962 String::new(),
5963 vec!["merge".to_owned(), "hold".to_owned()],
5964 )
5965 }
5966
5967 #[test]
5968 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
5969 crate::run::pin_test_home();
5970 let mut state = run_state(RunStatus::Landing);
5971 state.id = "20260101-000000-fre1".to_owned();
5972 state.parked = true;
5973 state.save().unwrap();
5974 ask::Questions::open()
5975 .put(&mut approval_question(&state.id))
5976 .unwrap();
5977
5978 let mut t = task();
5979 t.runs.push(state.id.clone());
5980 assert_eq!(
5981 land_resume_state(&t),
5982 LandResume::StillWaiting,
5983 "nobody has answered and the timeout has not passed"
5984 );
5985 }
5986
5987 #[test]
5988 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
5989 crate::run::pin_test_home();
5994 let mut state = run_state(RunStatus::Landing);
5995 state.id = "20260101-000000-exp1".to_owned();
5996 state.parked = true;
5997 state.config.graph.answer_timeout = 60;
5998 state.save().unwrap();
5999
6000 let store = ask::Questions::open();
6001 let mut q = approval_question(&state.id);
6002 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6003 store.put(&mut q).unwrap();
6004
6005 let mut t = task();
6006 t.runs.push(state.id.clone());
6007 assert_eq!(
6008 land_resume_state(&t),
6009 LandResume::Ready,
6010 "an expired question must not be waited on forever"
6011 );
6012
6013 let after = store.get(&q.id).unwrap();
6014 assert!(
6015 !after.status.open(),
6016 "the question is abandoned, not silently ignored"
6017 );
6018 assert!(
6019 after.resolution().is_none(),
6020 "an abandoned question is not read as a decision"
6021 );
6022 }
6023
6024 #[test]
6025 fn reclaim_settles_a_running_task_against_its_last_run() {
6026 let mut t = task();
6027 t.start("20260904-000000-4043".to_owned());
6028 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6029 assert_eq!(
6030 t.status,
6031 TaskStatus::Done,
6032 "a run that actually finished must not stay `running` forever"
6033 );
6034 }
6035
6036 #[test]
6037 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6038 let mut t = task();
6039 t.start("20260904-000000-4043".to_owned());
6040 t.last_error = Some("earlier trouble".to_owned());
6041 let mut state = run_state(RunStatus::Judging);
6042 state.parked = true;
6043 reclaim(&mut t, Some(state), 1, "en");
6044 assert_eq!(t.status, TaskStatus::Parked);
6045 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6046 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6047 assert!(t.park_reason.is_some());
6048 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6049 assert!(!t.fresh_start);
6050 assert!(t.status.runnable());
6051 }
6052
6053 #[test]
6054 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6055 let mut t = task();
6056 t.start("20260904-000000-4043".to_owned());
6057 t.last_error = Some("earlier trouble".to_owned());
6058 settle(
6059 &mut t,
6060 Verdict {
6061 status: RunStatus::Judging,
6062 left_pr: false,
6063 quota_hit: false,
6064 parked: true,
6065 no_viable_candidates: false,
6066 },
6067 "parked after `judging`",
6068 1,
6069 );
6070 assert_eq!(t.status, TaskStatus::Parked);
6071 assert_eq!(t.attempts, 0);
6072 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6073 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6074 assert_eq!(t.schema, crate::queue::SCHEMA);
6075 assert!(
6076 crate::notices::task_held(&t).is_none(),
6077 "a park is not news"
6078 );
6079 t.start("20260904-000000-4043".to_owned());
6080 assert_eq!(t.park_reason, None);
6081 }
6082
6083 #[test]
6084 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6085 let mut t = task();
6089 t.start("20260904-000000-4043".to_owned());
6090 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6091 assert_eq!(t.status, TaskStatus::Failed);
6092 assert!(t.status.runnable());
6093 }
6094
6095 #[test]
6096 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6097 let mut t = task();
6098 t.start("20260904-000000-4043".to_owned());
6099 reclaim(&mut t, None, 2, "en");
6100 assert_eq!(t.status, TaskStatus::Held);
6101 assert!(
6102 t.last_error
6103 .as_deref()
6104 .is_some_and(|e| e.contains("running")),
6105 "the operator needs to know why this task was held"
6106 );
6107 }
6108
6109 #[test]
6110 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6111 let dir = tempfile::tempdir().unwrap();
6112 let queue = Queue::at(dir.path().to_path_buf());
6113
6114 let mut orphaned = task();
6116 orphaned.id = "20260904-000000-orph".to_owned();
6117 orphaned.status = TaskStatus::Running;
6118 orphaned.attempts = 1;
6119 queue.put(&mut orphaned).unwrap();
6120
6121 let mut alive = task();
6122 alive.id = "20260904-000000-live".to_owned();
6123 alive.status = TaskStatus::Running;
6124 alive.attempts = 1;
6125 queue.put(&mut alive).unwrap();
6126 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6127
6128 let mut queued = task();
6129 queued.id = "20260904-000000-wait".to_owned();
6130 queue.put(&mut queued).unwrap();
6131
6132 let reclaimed = reclaim_orphaned_running(&queue, 2);
6133 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6134
6135 assert_eq!(
6136 queue.get(&orphaned.id).unwrap().status,
6137 TaskStatus::Held,
6138 "nothing was driving it and there was no run to recover"
6139 );
6140 assert_eq!(
6141 queue.get(&alive.id).unwrap().status,
6142 TaskStatus::Running,
6143 "a live claim must protect the task it belongs to"
6144 );
6145 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6146 }
6147
6148 fn read_run_under(home: &Path, id: &str) -> RunState {
6154 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6155 serde_json::from_str(&body).unwrap()
6156 }
6157
6158 #[test]
6159 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6160 let dir = tempfile::tempdir().unwrap();
6161 let home = dir.path().to_path_buf();
6162 let now = Timestamp::now();
6163 let overrun_seat = || crate::run::ActiveSeat {
6164 node: "implement".to_owned(),
6165 started_at: now - jiff::SignedDuration::new(21_000, 0),
6166 timeout_secs: 3_600,
6167 attempt: 0,
6168 task: None,
6169 command: None,
6170 index: None,
6171 total: None,
6172 };
6173
6174 let mut dead = run_state(RunStatus::Implementing);
6175 dead.id = "20260101-000000-dead".to_owned();
6176 dead.active.insert("impl-A".to_owned(), overrun_seat());
6177 dead.driver_pid = Some(4242);
6180 dead.save_under(&home).unwrap();
6181
6182 let mut alive = run_state(RunStatus::Implementing);
6185 alive.id = "20260101-000000-aliv".to_owned();
6186 alive.active.insert("impl-A".to_owned(), overrun_seat());
6187 alive.save_under(&home).unwrap();
6188 let mut status = Status::new();
6189 status.current = vec![Current {
6190 task: "20260101-000000-task".to_owned(),
6191 run: alive.id.clone(),
6192 }];
6193 write_status_to(&home.join("daemon.json"), &status).unwrap();
6194
6195 let questions = Questions::at(home.join("questions"));
6199 let mut q = ask::Question::new(
6200 dead.id.clone(),
6201 "implement".to_owned(),
6202 "impl-A".to_owned(),
6203 "Which storage backend?".to_owned(),
6204 String::new(),
6205 vec!["SQLite".to_owned(), "Redis".to_owned()],
6206 );
6207 questions.put(&mut q).unwrap();
6208
6209 let abandoned = reclaim_abandoned_runs_with(
6210 &home,
6211 now,
6212 |pid| if pid == 4242 { Some(false) } else { None },
6213 |_| panic!("a query answering Dead outright needs no identity corroboration"),
6214 );
6215 assert_eq!(abandoned, vec![dead.id.clone()]);
6216
6217 let reloaded = read_run_under(&home, &dead.id);
6218 assert_eq!(reloaded.status, RunStatus::Failed);
6219 assert!(reloaded.active.is_empty());
6220 assert!(
6221 !questions.get(&q.id).unwrap().status.open(),
6222 "the failed run's own open question must be settled in the same pass"
6223 );
6224
6225 let still_alive = read_run_under(&home, &alive.id);
6226 assert_eq!(
6227 still_alive.status,
6228 RunStatus::Implementing,
6229 "a live daemon's claim protects it"
6230 );
6231 assert!(!still_alive.active.is_empty());
6232 }
6233
6234 #[test]
6244 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
6245 let dir = tempfile::tempdir().unwrap();
6246 let home = dir.path().to_path_buf();
6247 let now = Timestamp::now();
6248
6249 let mut manual = run_state(RunStatus::Reviewing);
6250 manual.id = "20260101-000000-manl".to_owned();
6251 manual.active.insert(
6252 "review-1".to_owned(),
6253 crate::run::ActiveSeat {
6254 node: "review".to_owned(),
6255 started_at: now - jiff::SignedDuration::new(21_000, 0),
6256 timeout_secs: 3_600,
6257 attempt: 0,
6258 task: None,
6259 command: None,
6260 index: None,
6261 total: None,
6262 },
6263 );
6264 manual.driver_pid = Some(4242);
6268 manual.driver_started_at = Some("1790000000".to_owned());
6269 manual.save_under(&home).unwrap();
6270
6271 let abandoned = reclaim_abandoned_runs_with(
6272 &home,
6273 now,
6274 |pid| if pid == 4242 { Some(true) } else { None },
6275 |pid| {
6276 if pid == 4242 {
6277 Some("1790000000".to_owned())
6278 } else {
6279 None
6280 }
6281 },
6282 );
6283 assert!(
6284 abandoned.is_empty(),
6285 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
6286 );
6287
6288 let reloaded = read_run_under(&home, &manual.id);
6289 assert_eq!(reloaded.status, RunStatus::Reviewing);
6290 assert!(!reloaded.active.is_empty());
6291 }
6292
6293 #[test]
6294 fn an_already_claimed_task_is_skipped_rather_than_failed() {
6295 let dir = tempfile::tempdir().unwrap();
6296 let queue = Queue::at(dir.path().to_path_buf());
6297 let mut only = task();
6298 queue.put(&mut only).unwrap();
6299
6300 let _elsewhere = queue.claim(&only.id).unwrap();
6301 let candidates = runnable(&queue);
6302 assert_eq!(candidates.len(), 1, "the task is still runnable");
6303 assert!(
6304 queue.claim(&candidates[0].id).is_err(),
6305 "the loop cannot take a claim somebody else holds"
6306 );
6307
6308 let after = queue.get(&only.id).unwrap();
6309 assert_eq!(after.status, TaskStatus::Queued);
6310 assert_eq!(
6311 after.attempts, 0,
6312 "losing the race is not an attempt at the task"
6313 );
6314 assert_eq!(after.last_error, None);
6315 }
6316
6317 #[test]
6318 fn the_status_file_round_trips_and_its_heartbeat_advances() {
6319 let dir = tempfile::tempdir().unwrap();
6320 let path = dir.path().join("daemon.json");
6321
6322 let mut status = Status::new();
6323 status.idle = false;
6324 status.completed = 7;
6325 status.current = vec![Current {
6326 task: "20260902-000000-t111".to_owned(),
6327 run: "20260902-000001-r111".to_owned(),
6328 }];
6329 write_status_to(&path, &status).unwrap();
6330 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6331 assert_eq!(first.schema, SCHEMA);
6332 assert_eq!(first.pid, std::process::id());
6333 assert!(!first.idle);
6334 assert_eq!(first.completed, 7);
6335 assert_eq!(first.current, status.current);
6336 assert!(
6337 !path.with_extension("json.tmp").exists(),
6338 "the temp file is renamed, not left behind"
6339 );
6340
6341 std::thread::sleep(Duration::from_millis(5));
6342 status.updated_at = Timestamp::now();
6343 status.polls = 3;
6344 write_status_to(&path, &status).unwrap();
6345 let second: Status =
6346 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6347 assert!(
6348 second.updated_at > first.updated_at,
6349 "a reader can only detect staleness if the heartbeat moves"
6350 );
6351 assert_eq!(
6352 second.started_at, first.started_at,
6353 "the start time is not a heartbeat"
6354 );
6355 assert_eq!(second.polls, 3);
6356 }
6357
6358 #[test]
6359 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
6360 let dir = tempfile::tempdir().unwrap();
6361
6362 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
6363
6364 let mut status = Status::new();
6365 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
6366 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6367 let stale = read_status(dir.path()).unwrap();
6368 assert!(
6369 !stale.running(Timestamp::now()),
6370 "a minute without a heartbeat is a dead daemon, not a busy one"
6371 );
6372 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
6373
6374 status.updated_at = Timestamp::now();
6375 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6376 let fresh = read_status(dir.path()).unwrap();
6377 assert!(fresh.running(Timestamp::now()));
6378 }
6379
6380 #[test]
6381 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
6382 let dir = tempfile::tempdir().unwrap();
6383 let now = Timestamp::now();
6384 let mine = "20260903-080619-01c2";
6385
6386 assert!(
6387 !is_working_on(dir.path(), mine, now),
6388 "no status file means nobody is working on anything"
6389 );
6390
6391 let mut status = Status::new();
6392 status.current = vec![Current {
6393 task: "20260903-080340-0167".to_owned(),
6394 run: mine.to_owned(),
6395 }];
6396 status.updated_at = now;
6397 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6398 assert!(is_working_on(dir.path(), mine, now));
6399 assert!(
6400 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
6401 "a daemon busy with one run is not working on another"
6402 );
6403
6404 status.updated_at = now - jiff::SignedDuration::from_secs(600);
6407 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6408 assert!(
6409 !is_working_on(dir.path(), mine, now),
6410 "a stale heartbeat is a dead daemon, so its run is a leftover"
6411 );
6412 }
6413
6414 #[test]
6415 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
6416 let dir = tempfile::tempdir().unwrap();
6417 let now = Timestamp::now();
6418
6419 assert!(
6420 !is_working_on_short(dir.path(), "01c2", now),
6421 "no status file means nobody is working on anything"
6422 );
6423
6424 let mut status = Status::new();
6425 status.current = vec![Current {
6426 task: "20260903-080340-0167".to_owned(),
6427 run: "20260903-080619-01c2".to_owned(),
6428 }];
6429 status.updated_at = now;
6430 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6431 assert!(
6432 is_working_on_short(dir.path(), "01c2", now),
6433 "the run's short id is the last block of its full id"
6434 );
6435 assert!(
6436 !is_working_on_short(dir.path(), "3cbf", now),
6437 "a daemon busy with one worktree bay is not working on another"
6438 );
6439 }
6440
6441 #[test]
6442 fn a_newer_status_file_still_yields_a_reading() {
6443 let dir = tempfile::tempdir().unwrap();
6444 std::fs::write(
6447 dir.path().join("daemon.json"),
6448 serde_json::json!({
6449 "schema": 2,
6450 "updated_at": Timestamp::now().to_string(),
6451 "idle": true,
6452 "surprise": { "nested": [1, 2, 3] },
6453 })
6454 .to_string(),
6455 )
6456 .unwrap();
6457
6458 let reading = read_status(dir.path()).expect("a forward-compatible read");
6459 assert!(reading.running(Timestamp::now()));
6460 assert!(reading.idle);
6461 assert!(reading.current.is_empty());
6462 }
6463
6464 #[test]
6465 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
6466 let dir = tempfile::tempdir().unwrap();
6472 std::fs::write(
6473 dir.path().join("daemon.json"),
6474 serde_json::json!({
6475 "schema": 1,
6476 "pid": 4242,
6477 "updated_at": Timestamp::now().to_string(),
6478 "idle": false,
6479 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
6480 "completed": 3,
6481 "polls": 9,
6482 })
6483 .to_string(),
6484 )
6485 .unwrap();
6486
6487 let reading = read_status(dir.path()).expect("an older shape must still parse");
6488 assert!(reading.running(Timestamp::now()));
6489 assert_eq!(
6490 reading.current,
6491 vec![Current {
6492 task: "20260902-140501-aaaa".to_owned(),
6493 run: "20260902-140502-bbbb".to_owned(),
6494 }]
6495 );
6496 }
6497
6498 #[test]
6499 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
6500 let dir = tempfile::tempdir().unwrap();
6501 std::fs::write(
6502 dir.path().join("daemon.json"),
6503 serde_json::json!({
6504 "schema": 1,
6505 "updated_at": Timestamp::now().to_string(),
6506 "idle": true,
6507 "current": null,
6508 })
6509 .to_string(),
6510 )
6511 .unwrap();
6512 let with_null = read_status(dir.path()).expect("null must still parse");
6513 assert!(with_null.current.is_empty());
6514
6515 std::fs::write(
6516 dir.path().join("daemon.json"),
6517 serde_json::json!({
6518 "schema": 1,
6519 "updated_at": Timestamp::now().to_string(),
6520 "idle": true,
6521 })
6522 .to_string(),
6523 )
6524 .unwrap();
6525 let absent = read_status(dir.path()).expect("a missing field must still parse");
6526 assert!(absent.current.is_empty());
6527 }
6528
6529 #[test]
6530 fn a_task_without_a_repository_runs_in_the_daemons_default() {
6531 let fallback = Path::new("/default");
6532 let mut blank = task();
6533 blank.repo = PathBuf::new();
6534 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
6535 let mut dot = task();
6536 dot.repo = PathBuf::from(".");
6537 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
6538 assert_eq!(
6539 repo_for(&task(), fallback),
6540 PathBuf::from("/repo"),
6541 "a task that names a repository keeps it"
6542 );
6543 }
6544
6545 #[test]
6546 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
6547 let mut solo_cfg = Config::default();
6553 solo_cfg.graph.implementers = 3;
6554 let mut solo_task = task();
6555 solo_task.solo = true;
6556 apply_solo(&mut solo_cfg, &solo_task);
6557 assert_eq!(solo_cfg.graph.implementers, 1);
6558
6559 let mut plain_cfg = Config::default();
6560 plain_cfg.graph.implementers = 3;
6561 let plain_task = task();
6562 assert!(!plain_task.solo);
6563 apply_solo(&mut plain_cfg, &plain_task);
6564 assert_eq!(
6565 plain_cfg.graph.implementers, 3,
6566 "a task that did not ask to run alone keeps the config's candidates"
6567 );
6568 }
6569
6570 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
6571 QuotaLoss {
6572 seat: seat.into(),
6573 node: "judge".into(),
6574 at: at.parse().unwrap(),
6575 reset: reset.map(str::to_string),
6576 }
6577 }
6578
6579 #[test]
6580 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
6581 let old: Vec<QuotaLoss> = (1..=4)
6582 .map(|i| {
6583 loss(
6584 &format!("judge-{i}"),
6585 "2026-09-23T05:23:00Z",
6586 Some("2:40pm (Asia/Tokyo)"),
6587 )
6588 })
6589 .collect();
6590 let fresh = losses_this_attempt(&old, &old);
6591 assert!(fresh.is_empty());
6592 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
6593 }
6595
6596 #[test]
6597 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
6598 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
6599 let now = Timestamp::now();
6600 let mut after = old.clone();
6601 after.push(loss("judge-2", &now.to_string(), None));
6602 let fresh = losses_this_attempt(&old, &after);
6603 assert_eq!(fresh, vec![after[1].clone()]);
6604 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
6605 assert_eq!(
6606 until,
6607 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
6608 );
6609 }
6610
6611 #[test]
6612 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
6613 let before = vec![
6616 loss("judge-1", "2026-09-23T05:23:00Z", None),
6617 loss("judge-2", "2026-09-23T05:24:00Z", None),
6618 ];
6619 let after = vec![
6620 loss("judge-2", "2026-09-23T05:24:00Z", None),
6621 loss("judge-1", "2026-09-24T01:00:00Z", None),
6622 ];
6623 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
6624 }
6625
6626 #[test]
6627 fn merge_overrides_are_parsed_or_refused() {
6628 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
6629 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
6630 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
6631 assert!(merge_mode("squash").is_err());
6632 }
6633
6634 #[test]
6635 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
6636 let now = Timestamp::now();
6637 let fallback = Duration::from_secs(300);
6638 let cap = Duration::from_secs(1800);
6639
6640 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
6642
6643 let soon = now + jiff::SignedDuration::from_secs(600);
6645 assert_eq!(
6646 quota_wait(Some(soon), now, fallback, cap),
6647 Duration::from_secs(600)
6648 );
6649
6650 let past = now - jiff::SignedDuration::from_secs(60);
6653 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
6654
6655 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
6658 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
6659 }
6660
6661 #[test]
6662 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
6663 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6664
6665 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
6666 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
6667
6668 let already_past =
6672 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
6673 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
6674
6675 assert!(
6676 parse_reset_hint("session limit reached", now, now).is_none(),
6677 "free text with no recognised shape is not guessed at"
6678 );
6679 assert!(
6680 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
6681 "an unresolvable zone name is not guessed at either"
6682 );
6683 }
6684
6685 #[test]
6686 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
6687 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6688
6689 let at = parse_reset_hint(
6690 "You've hit your usage limit. Visit \
6691 https://chatgpt.com/codex/settings/usage to purchase more \
6692 credits or try again at Sep 19th, 2026 5:10 PM.",
6693 now,
6694 now,
6695 )
6696 .expect("the codex reset wording is a recognised shape");
6697 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
6698
6699 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
6704 .expect("an explicit year needs no rollover");
6705 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
6706
6707 assert!(
6708 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
6709 "a two-digit year is not the documented shape and is not guessed at"
6710 );
6711 assert!(
6712 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
6713 "a four-letter month name is not the documented three-letter abbreviation"
6714 );
6715 assert!(
6716 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
6717 "an explicit zone on the dated shape is a format nobody has \
6718 documented, and is refused rather than guessed at as UTC"
6719 );
6720 }
6721
6722 #[test]
6723 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
6724 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
6725 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
6726
6727 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
6728 assert_eq!(at.as_second() - recorded.as_second(), 3769);
6729
6730 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
6731 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
6732
6733 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
6734 assert!(
6735 parse_reset_hint(bad, now, recorded).is_none(),
6736 "{bad:?} must not be guessed at"
6737 );
6738 }
6739 }
6740
6741 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
6745 let config = dir.join("magi.toml");
6746 std::fs::write(
6747 &config,
6748 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
6749 )
6750 .unwrap();
6751 let opts = Opts {
6752 poll: Duration::from_secs(30),
6753 config: Some(config),
6754 repo: dir.join("repo"),
6758 ..Opts::default()
6759 };
6760 let home = dir.join("home");
6769 let worktrees = dir.join("wt");
6770 (
6771 opts,
6772 Queue::at(dir.join("queue")),
6773 home.join("daemon.json"),
6774 home,
6775 worktrees,
6776 )
6777 }
6778
6779 #[test]
6780 fn a_stop_is_idempotent_and_once_set_stays_set() {
6781 let stop = Stop::new();
6782 assert!(!stop.stopped());
6783
6784 stop.stop();
6785 assert!(stop.stopped());
6786 stop.stop();
6787 assert!(stop.stopped(), "a second stop is not a toggle");
6788
6789 let shared = stop.clone();
6790 assert!(
6791 shared.stopped(),
6792 "a clone is the same stop; that is how the loop and its caller share one"
6793 );
6794 }
6795
6796 #[test]
6797 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
6798 let stop = Stop::new();
6799 stop.enter();
6800 assert!(
6801 !stop.finishing(),
6802 "a busy loop nobody has asked to stop is just running"
6803 );
6804
6805 stop.stop();
6806 assert!(
6807 stop.finishing(),
6808 "a stop asked for mid-run has not landed until the run is settled"
6809 );
6810
6811 stop.exit();
6812 assert!(
6813 !stop.finishing(),
6814 "once the run is settled the stop has landed and there is nothing to finish"
6815 );
6816 }
6817
6818 #[test]
6819 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6820 let stop = Stop::new();
6821 stop.enter();
6822 stop.enter();
6823 stop.stop();
6824 assert!(stop.finishing(), "two runs still in flight");
6825
6826 stop.exit();
6827 assert!(
6828 stop.finishing(),
6829 "one run finished, but a sibling is still working"
6830 );
6831
6832 stop.exit();
6833 assert!(
6834 !stop.finishing(),
6835 "the last run out is what actually lands the stop"
6836 );
6837 }
6838
6839 #[tokio::test]
6840 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
6841 let dir = tempfile::tempdir().unwrap();
6842 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6843 let stop = Stop::new();
6844 stop.stop();
6845
6846 let began = std::time::Instant::now();
6847 tokio::time::timeout(
6848 Duration::from_secs(2),
6849 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6850 )
6851 .await
6852 .expect("a stopped loop must return, not sit out its poll interval")
6853 .expect("the loop's own setup and teardown must not fail");
6854 assert!(
6855 began.elapsed() < opts.poll,
6856 "returned only after {:?}, which is a poll interval, not a stop",
6857 began.elapsed()
6858 );
6859 }
6860
6861 #[tokio::test]
6862 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
6863 let dir = tempfile::tempdir().unwrap();
6864 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6865 let stop = Stop::new();
6866
6867 let asker = {
6870 let stop = stop.clone();
6871 tokio::spawn(async move {
6872 tokio::time::sleep(Duration::from_millis(20)).await;
6873 stop.stop();
6874 })
6875 };
6876
6877 let began = std::time::Instant::now();
6878 tokio::time::timeout(
6879 Duration::from_secs(2),
6880 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6881 )
6882 .await
6883 .expect("a stop asked for while idle must wake the wait")
6884 .expect("the loop's own setup and teardown must not fail");
6885 asker.await.unwrap();
6886 assert!(
6887 began.elapsed() < opts.poll,
6888 "returned only after {:?}, so the stop waited on the sleep",
6889 began.elapsed()
6890 );
6891 }
6892
6893 #[tokio::test]
6894 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
6895 let dir = tempfile::tempdir().unwrap();
6896 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6897 let stop = Stop::new();
6898 stop.stop();
6899
6900 tokio::time::timeout(
6901 Duration::from_secs(2),
6902 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6903 )
6904 .await
6905 .expect("a stopped loop must return")
6906 .expect("the loop's own setup and teardown must not fail");
6907
6908 assert!(
6909 home.is_dir(),
6910 "the loop did publish a status file, so its removal is the teardown and not an absence"
6911 );
6912 assert!(
6913 !status_file.exists(),
6914 "a stopped loop clears its status file"
6915 );
6916 assert!(
6917 read_status(&home).is_none(),
6918 "a reader must see no daemon at all, not a heartbeat that merely stopped"
6919 );
6920 }
6921
6922 #[tokio::test]
6923 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
6924 let dir = tempfile::tempdir().unwrap();
6925 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6926 opts.once = true;
6927
6928 let mut settled = RunState::new(
6929 dir.path().join("repo"),
6930 "main".to_owned(),
6931 "abc1234".to_owned(),
6932 "fixture".to_owned(),
6933 Config::default(),
6934 );
6935 settled.status = RunStatus::Ready;
6936 let run_dir = home.join("runs").join(&settled.id);
6937 std::fs::create_dir_all(&run_dir).unwrap();
6938 std::fs::write(
6939 run_dir.join("run.json"),
6940 serde_json::to_string_pretty(&settled).unwrap(),
6941 )
6942 .unwrap();
6943 let questions = Questions::at(home.join("questions"));
6944 let mut question = ask::Question::new(
6945 settled.id.clone(),
6946 "review".to_owned(),
6947 "reviewer-1".to_owned(),
6948 "Continue?".to_owned(),
6949 String::new(),
6950 Vec::new(),
6951 );
6952 questions.put(&mut question).unwrap();
6953
6954 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
6955 .await
6956 .unwrap();
6957
6958 assert_eq!(
6959 questions.get(&question.id).unwrap().status,
6960 ask::QuestionStatus::Abandoned,
6961 "an empty --once drain still performs startup question cleanup"
6962 );
6963 }
6964
6965 #[test]
6966 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
6967 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6968
6969 assert!(
6970 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
6971 "never checked before: due at once"
6972 );
6973
6974 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
6975 assert!(
6976 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
6977 "well inside the interval: not due yet"
6978 );
6979
6980 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
6981 assert!(
6982 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
6983 "exactly at the edge: not yet due, same convention as `clean::due`"
6984 );
6985
6986 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6987 assert!(
6988 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
6989 "past the interval: due again"
6990 );
6991 }
6992
6993 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
6998 let config = dir.join("magi.toml");
6999 std::fs::write(
7005 &config,
7006 format!(
7007 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7008 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7009 cache_dir.display()
7010 ),
7011 )
7012 .unwrap();
7013 Opts {
7014 config: Some(config),
7015 repo: dir.join("repo"),
7016 ..Opts::default()
7017 }
7018 }
7019
7020 #[tokio::test]
7021 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
7022 let dir = tempfile::tempdir().unwrap();
7023 let home = dir.path().join("home");
7024 let cache_dir = dir.path().join("cache");
7025 std::fs::create_dir_all(&cache_dir).unwrap();
7026 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7027 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7028
7029 let running = Stop::new();
7032 let mut last_checked = None;
7033 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7034 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
7035 .await;
7036 assert_eq!(
7037 crate::disk::dir_size(&cache_dir),
7038 0,
7039 "over the cap on the first check ever: pruned at once, no idle queue required"
7040 );
7041 assert_eq!(last_checked, Some(t0));
7042
7043 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
7045 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
7046 maybe_prune_cache_between_runs(
7047 &opts.repo,
7048 &opts,
7049 &home,
7050 &running,
7051 &mut last_checked,
7052 too_soon,
7053 )
7054 .await;
7055 assert_eq!(
7056 crate::disk::dir_size(&cache_dir),
7057 10,
7058 "too soon since the last check: left alone rather than rescanned every call"
7059 );
7060 assert_eq!(
7061 last_checked,
7062 Some(t0),
7063 "an idle check does not reset the clock"
7064 );
7065
7066 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7068 maybe_prune_cache_between_runs(
7069 &opts.repo,
7070 &opts,
7071 &home,
7072 &running,
7073 &mut last_checked,
7074 due_again,
7075 )
7076 .await;
7077 assert_eq!(
7078 crate::disk::dir_size(&cache_dir),
7079 0,
7080 "due again: pruned back under the cap"
7081 );
7082 }
7083
7084 #[tokio::test]
7092 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
7093 let dir = tempfile::tempdir().unwrap();
7094 let home = dir.path().join("home");
7095 let cache_dir = dir.path().join("cache");
7096 std::fs::create_dir_all(&cache_dir).unwrap();
7097 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7098 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7099
7100 let stop = Stop::new();
7101 stop.stop();
7102 assert!(
7103 !stop.finishing(),
7104 "no run is in flight at a between-runs boundary, so nothing else \
7105 would tell the operator this stop had not taken effect yet"
7106 );
7107
7108 let mut last_checked = None;
7109 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7110 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
7111 .await;
7112 assert_eq!(
7113 crate::disk::dir_size(&cache_dir),
7114 10,
7115 "over its cap, and due for the first check ever, but a stop outranks \
7116 it: the cap is a standing policy the next start measures again"
7117 );
7118 assert_eq!(
7119 last_checked, None,
7120 "a check that never happened must not claim the interval"
7121 );
7122 }
7123
7124 #[tokio::test]
7138 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
7139 let dir = tempfile::tempdir().unwrap();
7140 let cache_dir = dir.path().join("cache");
7141 std::fs::create_dir_all(&cache_dir).unwrap();
7142 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
7143
7144 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
7145 opts.poll = Duration::from_millis(20);
7146 opts.max_attempts = 1_000;
7147
7148 let queue = Queue::at(dir.path().join("queue"));
7149 let mut t = Task::new(
7150 "x".to_owned(),
7151 "x".to_owned(),
7152 opts.repo.clone(),
7153 Source::Human,
7154 );
7155 queue.put(&mut t).unwrap();
7156
7157 let home = dir.path().join("home");
7158 let worktrees = dir.path().join("wt");
7159 let status_file = home.join("daemon.json");
7160 let stop = Stop::new();
7161 let stopper = {
7162 let stop = stop.clone();
7163 let queue = Queue::at(dir.path().join("queue"));
7164 let id = t.id.clone();
7165 tokio::spawn(async move {
7166 tokio::time::sleep(Duration::from_millis(400)).await;
7170 for _ in 0..200 {
7171 if queue.get(&id).is_ok_and(|t| t.attempts >= 2) {
7172 break;
7173 }
7174 tokio::time::sleep(Duration::from_millis(50)).await;
7175 }
7176 stop.stop();
7177 })
7178 };
7179
7180 tokio::time::timeout(
7181 Duration::from_secs(20),
7182 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7183 )
7184 .await
7185 .expect("the loop must not hang on a queue that keeps producing failing work")
7186 .expect("the loop's own setup and teardown must not fail");
7187 stopper.await.unwrap();
7188
7189 let after = queue.get(&t.id).unwrap();
7190 assert!(
7191 after.attempts >= 2,
7192 "the harness must actually have retried more than once, or this is not \
7193 exercising a busy queue at all (got {} attempt(s))",
7194 after.attempts
7195 );
7196 assert!(
7197 after.status.runnable(),
7198 "still under its attempt budget: the queue never reached a natural idle \
7199 on its own, only the external stop ended the test"
7200 );
7201
7202 assert_eq!(
7203 crate::disk::dir_size(&cache_dir),
7204 0,
7205 "an oversized cache must not be left to grow unboundedly just because the \
7206 queue kept the loop busy the whole time"
7207 );
7208 }
7209
7210 #[test]
7211 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
7212 let dir = tempfile::tempdir().unwrap();
7213 let queue = Queue::at(dir.path().join("queue"));
7214 let questions = Questions::at(dir.path().join("questions"));
7215 let mut task = task();
7216 queue.put(&mut task).unwrap();
7217
7218 let mut task_question = ask::Question::new(
7219 task.id.clone(),
7220 crate::conduct::NODE.to_owned(),
7221 "conduct".to_owned(),
7222 "Which backend?".to_owned(),
7223 String::new(),
7224 Vec::new(),
7225 );
7226 questions.put(&mut task_question).unwrap();
7227 task.block(vec![task_question.id.clone()], None);
7228 queue.put(&mut task).unwrap();
7229
7230 let mut run_question = ask::Question::new(
7231 "20260101-000000-run1".to_owned(),
7232 "review".to_owned(),
7233 "reviewer-1".to_owned(),
7234 "Run question".to_owned(),
7235 String::new(),
7236 Vec::new(),
7237 );
7238 questions.put(&mut run_question).unwrap();
7239
7240 let mut coincidental = ask::Question::new(
7245 task.id.clone(),
7246 "review".to_owned(),
7247 "reviewer-1".to_owned(),
7248 "Unrelated review question".to_owned(),
7249 String::new(),
7250 Vec::new(),
7251 );
7252 questions.put(&mut coincidental).unwrap();
7253
7254 reconcile_task_questions(&queue, &questions);
7255 assert!(questions.get(&task_question.id).unwrap().status.open());
7256 assert!(questions.get(&run_question.id).unwrap().status.open());
7257 assert!(questions.get(&coincidental.id).unwrap().status.open());
7258
7259 task.release();
7260 queue.put(&mut task).unwrap();
7261 reconcile_task_questions(&queue, &questions);
7262 assert_eq!(
7263 questions.get(&task_question.id).unwrap().status,
7264 ask::QuestionStatus::Abandoned
7265 );
7266 assert!(
7267 questions.get(&run_question.id).unwrap().status.open(),
7268 "run questions remain the run janitor's responsibility"
7269 );
7270 assert!(
7271 questions.get(&coincidental.id).unwrap().status.open(),
7272 "a non-conductor question must not be abandoned just because its \
7273 run id coincides with a task id"
7274 );
7275 }
7276
7277 #[test]
7278 fn a_freshly_started_running_task_is_never_stalled() {
7279 let dir = tempfile::tempdir().unwrap();
7280 let mut t = task();
7281 t.start("run-1".to_owned());
7282 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
7285 }
7286
7287 #[test]
7288 fn a_long_running_task_with_no_live_daemon_is_stalled() {
7289 let dir = tempfile::tempdir().unwrap();
7290 let mut t = task();
7291 t.start("run-1".to_owned());
7292 t.updated_at = Timestamp::now()
7293 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7294 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
7295 assert_eq!(
7296 stalled_tasks(
7297 &Queue::at(dir.path().join("q")),
7298 dir.path(),
7299 Timestamp::now()
7300 )
7301 .len(),
7302 0,
7303 "the task was never written to this queue"
7304 );
7305 }
7306
7307 #[test]
7308 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
7309 let dir = tempfile::tempdir().unwrap();
7310 let mut t = task();
7311 t.id = "20260903-080340-0167".to_owned();
7312 t.start("20260903-080619-01c2".to_owned());
7313 t.updated_at = Timestamp::now()
7314 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7315
7316 let mut status = Status::new();
7317 status.current = vec![Current {
7318 task: t.id.clone(),
7319 run: "20260903-080619-01c2".to_owned(),
7320 }];
7321 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7322
7323 assert!(
7324 !is_stalled(&t, dir.path(), Timestamp::now()),
7325 "a live daemon's own heartbeat rules out stalled, however long the task has run"
7326 );
7327 }
7328
7329 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
7333 let path = queue.path_of(id);
7334 let body = std::fs::read_to_string(&path).unwrap();
7335 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
7336 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
7337 v["updated_at"] = serde_json::Value::String(old.to_string());
7338 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
7339 }
7340
7341 #[test]
7342 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
7343 let dir = tempfile::tempdir().unwrap();
7356 let queue = Queue::at(dir.path().join("queue"));
7357 let home = dir.path().join("home");
7358
7359 let mut t = task();
7360 t.id = "20260101-000001-lock".to_owned();
7361 t.start("run-1".to_owned());
7362 queue.put(&mut t).unwrap();
7363 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7364 std::fs::write(
7365 dir.path().join("queue").join(format!("{}.lock", t.id)),
7366 "not a pid",
7367 )
7368 .unwrap();
7369
7370 let now = Timestamp::now();
7371 assert!(
7372 reclaim_orphaned_running(&queue, 2).is_empty(),
7373 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
7374 and reclaim must leave the task alone"
7375 );
7376 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7377
7378 let stalled = stalled_tasks(&queue, &home, now);
7379 assert_eq!(
7380 stalled.len(),
7381 1,
7382 "reclaim's inability to claim it yet must not hide it from the conductor"
7383 );
7384 assert_eq!(stalled[0].id, t.id);
7385 }
7386
7387 #[test]
7388 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
7389 let dir = tempfile::tempdir().unwrap();
7390 crate::run::set_home(dir.path().join("run-home"));
7391 let queue = Queue::at(dir.path().join("queue"));
7392 let home = dir.path().join("home");
7393 let questions = Questions::at(dir.path().join("questions"));
7394
7395 let mut t = task();
7396 t.id = "20260101-000003-dead".to_owned();
7397 t.start("missing-run".to_owned());
7398 queue.put(&mut t).unwrap();
7399 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7400
7401 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7404 assert_eq!(
7405 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
7406 [&t.id]
7407 );
7408 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
7409 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7410
7411 crate::conduct::apply(
7414 &queue,
7415 &questions,
7416 &crate::conduct::Verdict {
7417 decisions: vec![crate::conduct::Decision {
7418 id: t.id.clone(),
7419 recovery: Some(crate::conduct::Recovery::Requeue),
7420 ..crate::conduct::Decision::default()
7421 }],
7422 },
7423 )
7424 .unwrap();
7425 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7426 }
7427
7428 #[test]
7429 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
7430 let dir = tempfile::tempdir().unwrap();
7431 let queue = Queue::at(dir.path().join("queue"));
7432 let home = dir.path().join("home");
7433
7434 let mut fresh = task();
7435 fresh.id = "20260101-000001-aaaa".to_owned();
7436 fresh.start("run-1".to_owned());
7437 queue.put(&mut fresh).unwrap();
7438
7439 let mut old = task();
7440 old.id = "20260101-000002-bbbb".to_owned();
7441 old.start("run-2".to_owned());
7442 queue.put(&mut old).unwrap();
7443 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
7444
7445 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7446 assert_eq!(stalled.len(), 1);
7447 assert_eq!(stalled[0].id, old.id);
7448 }
7449
7450 #[test]
7451 fn queued_and_finished_task_views_partition_by_status() {
7452 let dir = tempfile::tempdir().unwrap();
7453 let queue = Queue::at(dir.path().join("queue"));
7454
7455 let mut queued = task();
7456 queued.id = "20260101-000001-aaaa".to_owned();
7457 queue.put(&mut queued).unwrap();
7458
7459 let mut failed = task();
7460 failed.id = "20260101-000002-bbbb".to_owned();
7461 failed.start("run-1".to_owned());
7462 failed.fail("gate red", 5);
7463 queue.put(&mut failed).unwrap();
7464
7465 let mut held = task();
7466 held.id = "20260101-000003-cccc".to_owned();
7467 held.hold_machine(None);
7468 queue.put(&mut held).unwrap();
7469
7470 let mut running = task();
7471 running.id = "20260101-000004-dddd".to_owned();
7472 running.start("run-2".to_owned());
7473 queue.put(&mut running).unwrap();
7474
7475 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
7476 assert_eq!(queued_ids, [queued.id.clone()]);
7477
7478 let mut finished_ids: Vec<String> =
7479 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
7480 finished_ids.sort_unstable();
7481 let mut want = vec![failed.id.clone(), held.id.clone()];
7482 want.sort_unstable();
7483 assert_eq!(finished_ids, want);
7484 }
7485
7486 #[test]
7487 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
7488 let dir = tempfile::tempdir().unwrap();
7489 let queue = Queue::at(dir.path().join("queue"));
7490 let questions = ask::Questions::at(dir.path().join("questions"));
7491
7492 let mut dep = task();
7493 dep.id = "20260101-000001-dep0".to_owned();
7494 dep.succeed();
7495 queue.put(&mut dep).unwrap();
7496
7497 let mut still_going = task();
7498 still_going.id = "20260101-000002-dep1".to_owned();
7499 queue.put(&mut still_going).unwrap();
7500
7501 let mut blocked = task();
7502 blocked.id = "20260101-000003-main".to_owned();
7503 blocked.block(
7504 vec![dep.id.clone(), still_going.id.clone()],
7505 Some("waits on both".to_owned()),
7506 );
7507 queue.put(&mut blocked).unwrap();
7508
7509 resolve_blockers(&queue, &questions);
7510
7511 let after = queue.get(&blocked.id).unwrap();
7512 assert_eq!(
7513 after.status,
7514 TaskStatus::Blocked,
7515 "one dependency is still outstanding"
7516 );
7517 assert_eq!(after.blocked_by, [still_going.id.clone()]);
7518 }
7519
7520 #[test]
7521 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
7522 let dir = tempfile::tempdir().unwrap();
7523 let queue = Queue::at(dir.path().join("queue"));
7524 let questions = ask::Questions::at(dir.path().join("questions"));
7525
7526 let mut q = crate::ask::Question::new(
7527 "20260101-000001-main".to_owned(),
7528 crate::conduct::NODE.to_owned(),
7529 "conduct".to_owned(),
7530 "Which backend?".to_owned(),
7531 String::new(),
7532 Vec::new(),
7533 );
7534 questions.put(&mut q).unwrap();
7535 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
7536 .unwrap();
7537 questions.put(&mut q).unwrap();
7538
7539 let mut blocked = task();
7540 blocked.id = "20260101-000001-main".to_owned();
7541 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
7542 queue.put(&mut blocked).unwrap();
7543
7544 resolve_blockers(&queue, &questions);
7545
7546 let after = queue.get(&blocked.id).unwrap();
7547 assert_eq!(
7548 after.status,
7549 TaskStatus::Queued,
7550 "the only blocker resolved"
7551 );
7552 assert_eq!(after.answers.len(), 1);
7553 assert_eq!(after.answers[0].question, "Which backend?");
7554 assert_eq!(after.answers[0].answer, "SQLite");
7555
7556 let instruction = instruction_for(&after);
7558 assert!(instruction.contains("Which backend?"));
7559 assert!(instruction.contains("SQLite"));
7560 }
7561
7562 #[test]
7563 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
7564 let dir = tempfile::tempdir().unwrap();
7565 let queue = Queue::at(dir.path().join("queue"));
7566 let questions = ask::Questions::at(dir.path().join("questions"));
7567
7568 let mut q = crate::ask::Question::new(
7569 "20260101-000001-main".to_owned(),
7570 crate::conduct::NODE.to_owned(),
7571 "conduct".to_owned(),
7572 "Is the setup done?".to_owned(),
7573 String::new(),
7574 Vec::new(),
7575 );
7576 q.abandon("no answer within 60s of asking");
7577 questions.put(&mut q).unwrap();
7578
7579 let mut blocked = task();
7580 blocked.id = "20260101-000001-main".to_owned();
7581 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
7582 queue.put(&mut blocked).unwrap();
7583
7584 resolve_blockers(&queue, &questions);
7585
7586 let after = queue.get(&blocked.id).unwrap();
7587 assert_eq!(
7588 after.status,
7589 TaskStatus::Held,
7590 "never left blocked on nothing"
7591 );
7592 assert!(!after.operator_held(), "a machine hold, for triage");
7593 assert!(
7594 after
7595 .hold_reason
7596 .as_deref()
7597 .unwrap_or_default()
7598 .contains("went unanswered")
7599 );
7600 }
7601
7602 #[test]
7603 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
7604 let dir = tempfile::tempdir().unwrap();
7610 let queue = Queue::at(dir.path().join("queue"));
7611 let questions = ask::Questions::at(dir.path().join("questions"));
7612
7613 let mut q = crate::ask::Question::new(
7614 "20260101-000001-main".to_owned(),
7615 crate::conduct::NODE.to_owned(),
7616 "conduct".to_owned(),
7617 "How should this be handled?".to_owned(),
7618 String::new(),
7619 Vec::new(),
7620 );
7621 questions.put(&mut q).unwrap();
7622 q.answer(crate::ask::Answer::Text(
7623 "leave it held, a human will look at it later".to_owned(),
7624 ))
7625 .unwrap();
7626 questions.put(&mut q).unwrap();
7627
7628 let mut held = task();
7629 held.id = "20260101-000001-main".to_owned();
7630 held.hold_machine(Some("out of attempts".to_owned()));
7631 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
7632 queue.put(&mut held).unwrap();
7633
7634 resolve_blockers(&queue, &questions);
7635
7636 let after = queue.get(&held.id).unwrap();
7637 assert_eq!(after.status, TaskStatus::Held);
7638 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
7639 assert_eq!(
7640 after.answers[0].answer,
7641 "leave it held, a human will look at it later"
7642 );
7643 }
7644
7645 #[test]
7646 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
7647 let dir = tempfile::tempdir().unwrap();
7648 let queue = Queue::at(dir.path().join("queue"));
7649 let questions = ask::Questions::at(dir.path().join("questions"));
7650 let mut dep = task();
7651 dep.id = "20260101-000001-gone".to_owned();
7652 queue.put(&mut dep).unwrap();
7653 let mut blocked = task();
7654 blocked.id = "20260101-000003-main".to_owned();
7655 blocked.block(vec![dep.id.clone()], None);
7656 queue.put(&mut blocked).unwrap();
7657
7658 let claim = queue.claim(&blocked.id).unwrap();
7660 queue.remove(&dep.id, false, &questions).unwrap();
7661 drop(claim);
7662 resolve_blockers(&queue, &questions);
7663
7664 let after = queue.get(&blocked.id).unwrap();
7665 assert_eq!(after.status, TaskStatus::Queued);
7666 assert!(after.blocked_by.is_empty());
7667 }
7668
7669 #[test]
7670 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
7671 let dir = tempfile::tempdir().unwrap();
7677 let queue = Queue::at(dir.path().join("queue"));
7678 let questions = ask::Questions::at(dir.path().join("questions"));
7679
7680 let mut still_going = task();
7681 still_going.id = "20260101-000002-dep1".to_owned();
7682 queue.put(&mut still_going).unwrap();
7683
7684 let mut blocked = task();
7685 blocked.id = "20260101-000003-main".to_owned();
7686 blocked.block(
7687 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
7688 Some("waits on both".to_owned()),
7689 );
7690 queue.put(&mut blocked).unwrap();
7691
7692 resolve_blockers(&queue, &questions);
7693
7694 let after = queue.get(&blocked.id).unwrap();
7695 assert_eq!(
7696 after.status,
7697 TaskStatus::Held,
7698 "a missing dependency must not leave the task blocked forever"
7699 );
7700 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
7701 assert!(after.blocked_by.is_empty());
7702 let reason = after.hold_reason.as_deref().unwrap_or_default();
7703 assert!(
7704 reason.contains("20260101-000001-gone"),
7705 "the missing id must be named so an operator can tell what happened: {reason}"
7706 );
7707 assert!(
7708 reason.contains(&still_going.id),
7709 "the still-valid dependency must not silently vanish from the record: {reason}"
7710 );
7711 }
7712
7713 #[test]
7714 fn instruction_for_is_unchanged_without_any_answers() {
7715 let t = task();
7716 assert_eq!(instruction_for(&t), t.instruction);
7717 }
7718
7719 #[test]
7720 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
7721 let dir = tempfile::tempdir().unwrap();
7722 let q = Queue::at(dir.path().join("queue"));
7723 let src = dir.path().join("shot.png");
7724 std::fs::write(&src, "x").unwrap();
7725 let mut t = task();
7726 q.attach(&mut t, &[src]).unwrap();
7727 let paths = task_attachments(&q, &t).unwrap();
7728 assert_eq!(paths.len(), 1);
7729 assert!(paths[0].is_absolute() && paths[0].is_file());
7730 std::fs::remove_file(&paths[0]).unwrap();
7731 let err = task_attachments(&q, &t).unwrap_err().to_string();
7732 assert!(err.contains("shot.png"), "{err}");
7733 }
7734
7735 #[test]
7736 fn resumed_instruction_is_unchanged_without_any_answers() {
7737 let t = task();
7738 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
7739 }
7740
7741 #[test]
7742 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
7743 let mut t = task();
7744 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7745 let old = t.instruction.clone();
7749
7750 let refreshed = resumed_instruction(&old, &t);
7751 assert!(refreshed.starts_with(&old), "the original text is kept");
7752 assert!(refreshed.contains("Which backend?"));
7753 assert!(refreshed.contains("SQLite"));
7754 }
7755
7756 #[test]
7757 fn resumed_instruction_keeps_an_original_answers_heading() {
7758 let mut t = task();
7759 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
7760 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7761
7762 let refreshed = resumed_instruction(&t.instruction, &t);
7763
7764 assert!(
7765 refreshed.starts_with(&t.instruction),
7766 "an answers heading in the original instruction is not the appended block"
7767 );
7768 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
7769 assert!(refreshed.contains("Which backend?"));
7770 assert!(refreshed.contains("SQLite"));
7771
7772 let repeated = resumed_instruction(&refreshed, &t);
7773 assert_eq!(
7774 repeated, refreshed,
7775 "only the final appended block is refreshed"
7776 );
7777 }
7778
7779 #[test]
7780 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
7781 let mut t = task();
7782 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7783
7784 let once = resumed_instruction(&t.instruction, &t);
7788 let twice = resumed_instruction(&once, &t);
7789 assert_eq!(once, twice);
7790 assert_eq!(once.matches("Which backend?").count(), 1);
7791
7792 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
7794 let refreshed = resumed_instruction(&once, &t);
7795 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
7796 assert!(refreshed.contains("Which backend?"));
7797 assert!(refreshed.contains("Which cache?"));
7798 }
7799
7800 #[test]
7801 fn prepare_instruction_covers_all_three_starters() {
7802 let mut t = task();
7803 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7804
7805 assert_eq!(
7808 prepare_instruction(&Starter::Start, None, &t),
7809 Some(instruction_for(&t))
7810 );
7811
7812 let old = t.instruction.clone();
7815 assert_eq!(
7816 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
7817 Some(resumed_instruction(&old, &t))
7818 );
7819
7820 assert_eq!(
7824 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
7825 None
7826 );
7827 }
7828
7829 #[test]
7830 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
7831 assert_eq!(
7832 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
7833 Starter::Review("magi/eba2/A".to_owned())
7834 );
7835 }
7836
7837 #[test]
7838 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
7839 assert_eq!(
7840 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
7841 Starter::Start,
7842 "a vanished review branch must not fall back to resuming the old run either"
7843 );
7844 }
7845
7846 #[test]
7847 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
7848 let mut t = task();
7849 t.start("old-run".to_owned());
7850 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
7851 t.release();
7852 let branch = t.review_branch.take();
7853 assert_eq!(
7854 choose_starter(branch.as_deref(), true, Some("old-run")),
7855 Starter::Review("magi/eba2/A".to_owned()),
7856 "a review wins over resuming the old run"
7857 );
7858 }
7859
7860 #[test]
7861 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
7862 assert_eq!(
7863 choose_starter(None, false, Some("some-run")),
7864 Starter::Resume("some-run".to_owned())
7865 );
7866 assert_eq!(choose_starter(None, false, None), Starter::Start);
7867 }
7868
7869 #[test]
7870 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
7871 let mut released = task();
7872 released.start("stalled-run".to_owned());
7873 released.requeue();
7874 let unfinished = (!released.fresh_start)
7875 .then(|| Some("stalled-run".to_owned()))
7876 .flatten();
7877 assert_eq!(
7878 choose_starter(None, false, unfinished.as_deref()),
7879 Starter::Start,
7880 "release keeps run history but must not resume it"
7881 );
7882 assert_eq!(released.runs, ["stalled-run"]);
7883 }
7884
7885 #[test]
7886 fn an_ordinary_release_keeps_a_resumable_run_available() {
7887 let mut released = task();
7888 released.start("stalled-run".to_owned());
7889 released.release();
7890 let unfinished = (!released.fresh_start)
7891 .then(|| Some("stalled-run".to_owned()))
7892 .flatten();
7893 assert_eq!(
7894 choose_starter(None, false, unfinished.as_deref()),
7895 Starter::Resume("stalled-run".to_owned()),
7896 "manual release must preserve the normal resume path"
7897 );
7898 }
7899
7900 #[test]
7901 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
7902 let mut state = run_state(RunStatus::Blocked);
7903 state.config.graph.review_rounds = 3;
7904 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
7905 assert!(exhausted_review_budget(&state));
7906
7907 state.reviews.pop();
7909 assert!(!exhausted_review_budget(&state));
7910
7911 let mut stalled = run_state(RunStatus::Stalled);
7914 stalled.config.graph.review_rounds = 1;
7915 stalled.reviews = vec![review_round(1)];
7916 assert!(!exhausted_review_budget(&stalled));
7917 }
7918
7919 fn review_round(round: usize) -> crate::run::ReviewRound {
7920 crate::run::ReviewRound {
7921 round,
7922 head: "deadbeef".to_owned(),
7923 verified_head: None,
7924 verified_at: None,
7925 reviews: Vec::new(),
7926 e2e: Vec::new(),
7927 verify_retried: false,
7928 e2e_deferred: false,
7929 e2e_defer_reason: None,
7930 fix: None,
7931 blocking: 0,
7932 answered: 1,
7933 expected: 1,
7934 clean: false,
7935 progressed: true,
7936 vote_split: false,
7937 reconsideration: Vec::new(),
7938 verdict: None,
7939 }
7940 }
7941
7942 #[test]
7943 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
7944 let mut run = RunState::new(
7945 PathBuf::from("/repo"),
7946 "main".to_owned(),
7947 "abc1234def".to_owned(),
7948 "add retries".to_owned(),
7949 Config::default(),
7950 );
7951 run.status = RunStatus::Judging;
7952 run.parked = true;
7953 let mut task = Task::new(
7954 "add retries".to_owned(),
7955 "add retries".to_owned(),
7956 PathBuf::from("/repo"),
7957 crate::queue::Source::Human,
7958 );
7959 task.status = TaskStatus::Failed;
7960 task.runs = vec![run.id.clone()];
7961 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
7962 assert!(with(&task, &run), "parked after judging is the case");
7963 let mut parked_task = task.clone();
7964 parked_task.status = TaskStatus::Parked;
7965 assert!(with(&parked_task, &run), "the Parked status is the case");
7966
7967 let mut not_parked = run.clone();
7968 not_parked.parked = false;
7969 not_parked.status = RunStatus::Stalled;
7970 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
7971
7972 let mut fresh = task.clone();
7973 fresh.fresh_start = true;
7974 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
7975
7976 let mut review = task.clone();
7977 review.review_branch = Some("magi/x/A".to_owned());
7978 assert!(!with(&review, &run), "review is ranked before resume");
7979
7980 let mut held = task.clone();
7981 held.status = TaskStatus::Held;
7982 assert!(!with(&held, &run), "a hold stays visible to the conductor");
7983
7984 let mut released = run.clone();
7985 released.released_to = Some("20260901-000000-new1".to_owned());
7986 assert!(!with(&task, &released), "nothing left to resume into");
7987
7988 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
7989 "unreadable"
7990 )));
7991 }
7992
7993 #[test]
7994 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
7995 let mut released = RunState::new(
7996 PathBuf::from("/repo"),
7997 "main".to_owned(),
7998 "abc1234def".to_owned(),
7999 "add retries".to_owned(),
8000 Config::default(),
8001 );
8002 released.status = RunStatus::Blocked;
8003 assert_eq!(
8004 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8005 Some(released.id.clone())
8006 );
8007 released.released_to = Some("20260901-000000-new1".to_owned());
8008 assert_eq!(
8009 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8010 None,
8011 "there is nothing left to resume it into"
8012 );
8013 }
8014
8015 #[test]
8016 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
8017 let mut exhausted = RunState::new(
8026 PathBuf::from("/repo"),
8027 "main".to_owned(),
8028 "abc1234def".to_owned(),
8029 "add retries".to_owned(),
8030 Config::default(),
8031 );
8032 exhausted.status = RunStatus::Blocked;
8033 exhausted.config.graph.review_rounds = 1;
8034 exhausted.reviews = vec![review_round(1)];
8035
8036 assert_eq!(
8037 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
8038 None,
8039 "an exhausted `Blocked` run must not be offered as resumable"
8040 );
8041
8042 let mut has_budget_left = RunState::new(
8045 PathBuf::from("/repo"),
8046 "main".to_owned(),
8047 "abc1234def".to_owned(),
8048 "add retries".to_owned(),
8049 Config::default(),
8050 );
8051 has_budget_left.status = RunStatus::Blocked;
8052 has_budget_left.config.graph.review_rounds = 3;
8053 has_budget_left.reviews = vec![review_round(1)];
8054
8055 assert_eq!(
8056 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
8057 Ok(has_budget_left.clone())
8058 }),
8059 Some(has_budget_left.id.clone())
8060 );
8061 }
8062
8063 #[test]
8064 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
8065 let mut older_stalled = RunState::new(
8073 PathBuf::from("/repo"),
8074 "main".to_owned(),
8075 "abc1234def".to_owned(),
8076 "add retries".to_owned(),
8077 Config::default(),
8078 );
8079 older_stalled.status = RunStatus::Stalled;
8080
8081 let mut newest_exhausted = RunState::new(
8082 PathBuf::from("/repo"),
8083 "main".to_owned(),
8084 "abc1234def".to_owned(),
8085 "add retries".to_owned(),
8086 Config::default(),
8087 );
8088 newest_exhausted.status = RunStatus::Blocked;
8089 newest_exhausted.config.graph.review_rounds = 1;
8090 newest_exhausted.reviews = vec![review_round(1)];
8091
8092 assert_eq!(
8093 unfinished_run_with(
8094 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
8095 "t",
8096 |_| Ok(newest_exhausted.clone())
8097 ),
8098 None,
8099 "the newest run is exhausted, so nothing here is worth resuming - \
8100 least of all the older, already-superseded run"
8101 );
8102 }
8103
8104 #[test]
8105 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
8106 assert_eq!(
8107 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
8108 Err(anyhow::anyhow!("fixture is absent"))
8109 }),
8110 None
8111 );
8112 }
8113
8114 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
8115 let mut q = ask::Question::new(
8116 run.to_owned(),
8117 "implement".to_owned(),
8118 "impl-A".to_owned(),
8119 "continue?".to_owned(),
8120 String::new(),
8121 vec!["resume で続行する".to_owned(), "other".to_owned()],
8122 );
8123 q.actions.insert("resume で続行する".to_owned(), action);
8124 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
8125 .unwrap();
8126 q
8127 }
8128
8129 fn held_task_with(run: &str) -> Task {
8130 let mut t = task();
8131 t.runs = vec![run.to_owned()];
8132 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
8133 t
8134 }
8135
8136 fn resume_action(run: &str) -> ask::ChoiceAction {
8137 ask::ChoiceAction::Resume { run: run.into() }
8138 }
8139
8140 #[test]
8141 fn decide_action_resumes_only_the_latest_resumable_run() {
8142 let t = held_task_with("r1");
8143 let q = action_question("r1", resume_action("r1"));
8144 let load = |s: RunState| move |_: &str| Ok(s);
8145 assert_eq!(
8146 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
8147 ActionDecision::Resume("r1".into())
8148 );
8149 let q_other = action_question("r1", resume_action("r0"));
8151 assert!(matches!(
8152 decide_action(
8153 &t,
8154 &q_other,
8155 &PHRASES_EN,
8156 load(run_state(RunStatus::Blocked))
8157 ),
8158 ActionDecision::Refuse(_)
8159 ));
8160 assert!(matches!(
8162 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
8163 ActionDecision::Refuse(_)
8164 ));
8165 let mut released = run_state(RunStatus::Blocked);
8167 released.released_to = Some("elsewhere".into());
8168 assert!(matches!(
8169 decide_action(&t, &q, &PHRASES_EN, load(released)),
8170 ActionDecision::Refuse(_)
8171 ));
8172 assert!(matches!(
8174 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
8175 ActionDecision::Refuse(_)
8176 ));
8177 }
8178
8179 #[test]
8180 fn decide_action_ignores_a_question_about_an_earlier_run() {
8181 let mut t = held_task_with("r1");
8182 t.runs.push("r2".to_owned());
8183 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8184 assert_eq!(
8185 decide_action(
8186 &t,
8187 &action_question("r1", ask::ChoiceAction::Done),
8188 &PHRASES_EN,
8189 never
8190 ),
8191 ActionDecision::Stale
8192 );
8193 }
8194
8195 #[test]
8196 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
8197 let mut t = held_task_with("r1");
8198 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8199 assert_eq!(
8200 decide_action(
8201 &t,
8202 &action_question("r1", ask::ChoiceAction::Requeue),
8203 &PHRASES_EN,
8204 never
8205 ),
8206 ActionDecision::Requeue
8207 );
8208 let done_q = action_question("r1", ask::ChoiceAction::Done);
8209 assert_eq!(
8210 decide_action(&t, &done_q, &PHRASES_EN, never),
8211 ActionDecision::Done
8212 );
8213 t.mark_action_applied(&done_q.id);
8214 assert_eq!(
8215 decide_action(&t, &done_q, &PHRASES_EN, never),
8216 ActionDecision::Skip
8217 );
8218
8219 let mut plain = action_question("r1", ask::ChoiceAction::Done);
8221 plain.actions.clear();
8222 assert_eq!(
8223 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
8224 ActionDecision::Skip
8225 );
8226 let mut running = held_task_with("r1");
8228 running.status = TaskStatus::Running;
8229 assert_eq!(
8230 decide_action(
8231 &running,
8232 &action_question("r1", ask::ChoiceAction::Done),
8233 &PHRASES_EN,
8234 never
8235 ),
8236 ActionDecision::Skip
8237 );
8238 }
8239
8240 #[test]
8241 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
8242 let dir = tempfile::tempdir().unwrap();
8243 let queue = Queue::at(dir.path().join("queue"));
8244 let questions = Questions::at(dir.path().join("questions"));
8245 let home = dir.path().join("home");
8246 let mut state = run_state(RunStatus::Blocked);
8247 state.id = "20260101-000000-act1".to_owned();
8248 state.save_under(&home).unwrap();
8249
8250 let mut t = held_task_with(&state.id);
8251 queue.put(&mut t).unwrap();
8252 let mut q = action_question(&state.id, resume_action(&state.id));
8253 questions.put(&mut q).unwrap();
8254
8255 apply_choice_actions(&queue, &questions, &home);
8256 let after = queue.get(&t.id).unwrap();
8257 assert_eq!(after.status, TaskStatus::Queued);
8258 assert!(!after.fresh_start);
8259 assert!(after.action_applied(&q.id));
8260 let pin = after.resume_override.clone().unwrap();
8261 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
8262 assert!(pin.forced);
8263
8264 let mut again = queue.get(&t.id).unwrap();
8266 again.hold_machine(Some("later".into()));
8267 queue.put(&mut again).unwrap();
8268 apply_choice_actions(&queue, &questions, &home);
8269 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8270 }
8271
8272 #[test]
8273 fn a_delivered_answer_is_still_acted_on_exactly_once() {
8274 let dir = tempfile::tempdir().unwrap();
8275 let queue = Queue::at(dir.path().join("queue"));
8276 let questions = Questions::at(dir.path().join("questions"));
8277 let home = dir.path().join("home");
8278 let mut state = run_state(RunStatus::Blocked);
8279 state.id = "20260101-000000-act2".to_owned();
8280 state.save_under(&home).unwrap();
8281
8282 let mut t = held_task_with(&state.id);
8283 queue.put(&mut t).unwrap();
8284 let mut q = action_question(&state.id, resume_action(&state.id));
8285 q.answer_delivered = true;
8286 questions.put(&mut q).unwrap();
8287
8288 apply_choice_actions(&queue, &questions, &home);
8291 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8292 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
8293
8294 let mut again = queue.get(&t.id).unwrap();
8296 again.hold_machine(Some("later".into()));
8297 queue.put(&mut again).unwrap();
8298 apply_choice_actions(&queue, &questions, &home);
8299 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8300 }
8301
8302 #[test]
8303 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
8304 let dir = tempfile::tempdir().unwrap();
8305 let queue = Queue::at(dir.path().join("queue"));
8306 let questions = Questions::at(dir.path().join("questions"));
8307 let home = dir.path().join("home");
8308 let mut state = run_state(RunStatus::Blocked);
8309 state.id = "20260101-000000-act3".to_owned();
8310 state.save_under(&home).unwrap();
8311 let mut t = held_task_with(&state.id);
8312 queue.put(&mut t).unwrap();
8313 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
8314 questions.put(&mut q).unwrap();
8315
8316 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
8317 apply_choice_actions(&queue, &questions, &home);
8318 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8319
8320 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
8321 apply_choice_actions(&queue, &questions, &home);
8322 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8323 }
8324
8325 #[test]
8326 fn action_standing_tells_the_reasons_apart() {
8327 let mut t = held_task_with("r1");
8328 let q = action_question("r1", ask::ChoiceAction::Requeue);
8329 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
8330 let mut plain = q.clone();
8331 plain.actions.clear();
8332 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
8333
8334 t.mark_action_applied(&q.id);
8336 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
8337
8338 let mut t = held_task_with("r1");
8340 t.start("r2".to_owned());
8341 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
8342 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
8344 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8345 t.status = TaskStatus::Blocked;
8346 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8347
8348 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
8350 c.node = crate::conduct::NODE.to_owned();
8351 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
8352 assert!(!ActionStanding::Busy.daemon_owns());
8353 }
8354
8355 #[test]
8356 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
8357 let dir = tempfile::tempdir().unwrap();
8358 let queue = Queue::at(dir.path().join("queue"));
8359 let questions = Questions::at(dir.path().join("questions"));
8360 let home = dir.path().join("home");
8361 let mut state = run_state(RunStatus::Blocked);
8362 state.id = "20260101-000000-act4".to_owned();
8363 state.save_under(&home).unwrap();
8364 let mut t = held_task_with(&state.id);
8365 t.status = TaskStatus::Running;
8366 queue.put(&mut t).unwrap();
8367 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
8368 q.cwd = Some(dir.path().display().to_string());
8369 questions.put(&mut q).unwrap();
8370
8371 let running = queue.get(&t.id).unwrap();
8374 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
8375 assert!(matches!(
8376 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
8377 crate::waiter::Action::Deliver(_)
8378 ));
8379 apply_choice_actions(&queue, &questions, &home);
8381 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8382 let mut back = queue.get(&t.id).unwrap();
8383 back.hold_machine(Some("later".into()));
8384 queue.put(&mut back).unwrap();
8385 apply_choice_actions(&queue, &questions, &home);
8386 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
8387 let mut again = queue.get(&t.id).unwrap();
8388 again.hold_machine(Some("again".into()));
8389 queue.put(&mut again).unwrap();
8390 apply_choice_actions(&queue, &questions, &home);
8391 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8392 }
8393}