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