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