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