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, cause: crate::run::ParkCause) {
347 self.pause.park_for(cause);
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 task.operator_decided_at.is_some_and(|at| at > q.asked_at) {
856 return ActionDecision::Stale;
857 }
858 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
861 return ActionDecision::Stale;
862 }
863 match action {
864 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
865 ask::ChoiceAction::Done => ActionDecision::Done,
866 ask::ChoiceAction::Resume { run } => {
867 if task.runs.last() != Some(run) {
868 return ActionDecision::Refuse((p.resume_not_latest)(
869 q.short(),
870 ask::short_id(run),
871 ));
872 }
873 match load(run) {
874 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
875 ActionDecision::Resume(run.clone())
876 }
877 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
878 q.short(),
879 ask::short_id(run),
880 )),
881 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
882 q.short(),
883 ask::short_id(run),
884 &format!("{e:#}"),
885 )),
886 }
887 }
888 }
889}
890
891struct Phrases {
905 graph_stopped: fn(&str, &str) -> String,
907 quorum_lost: &'static str,
908 quota_took_out: &'static str,
910 run_ended: &'static str,
912 waiting_for_answer: &'static str,
914 recovered_running: &'static str,
915 no_run_to_recover: &'static str,
916 could_not_start: &'static str,
917 resume_not_latest: fn(&str, &str) -> String,
918 resume_cannot_progress: fn(&str, &str) -> String,
919 resume_unreadable: fn(&str, &str, &str) -> String,
920 handover_refused: fn(&crate::handover::Refused) -> String,
923 handover_hint: &'static str,
925 reviewers_never_answered: fn(usize, usize) -> String,
928}
929
930const PHRASES_EN: Phrases = Phrases {
931 graph_stopped: |status, detail| {
932 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
933 },
934 quorum_lost: "the judging panel lost its quorum",
935 quota_took_out: "; quota took out ",
936 run_ended: "run ended ",
937 waiting_for_answer: " - waiting for operator answer to question ",
938 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
939 no_run_to_recover: "task was `running` with no live daemon and no readable \
940 run to recover; held for a human to check what happened",
941 could_not_start: "could not start the run: ",
942 resume_not_latest: |q, run| {
943 format!("question {q} asked to resume run {run}, which is not this task's latest run")
944 },
945 resume_cannot_progress: |q, run| {
946 format!("question {q} asked to resume run {run}, which cannot make progress")
947 },
948 resume_unreadable: |q, run, e| {
949 format!("question {q} asked to resume run {run}, which could not be read: {e}")
950 },
951 handover_refused: |r| r.to_string(),
952 handover_hint: " (clean up the other worktree, then release the task from the queue)",
953 reviewers_never_answered: |missing, rounds| {
954 format!(
955 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
956 refusing to call it clean"
957 )
958 },
959};
960
961const PHRASES_JA: Phrases = Phrases {
962 graph_stopped: |status, detail| {
963 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
964 },
965 quorum_lost: "審査パネルが定足数を失いました",
966 quota_took_out: "。クォータで脱落: ",
967 run_ended: "run 終了: ",
968 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
969 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
970 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
971 何が起きたか人が確認するため保留にしました",
972 could_not_start: "run を開始できませんでした: ",
973 resume_not_latest: |q, run| {
974 format!(
975 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
976 )
977 },
978 resume_cannot_progress: |q, run| {
979 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
980 },
981 resume_unreadable: |q, run, e| {
982 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
983 },
984 handover_refused: |r| {
985 use crate::handover::Refused;
986 match r {
987 Refused::Foreign { branch, path, why } => format!(
988 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
989 削除しません。不要なら `git worktree remove` でその worktree を削除して\
990 から、やり直してください(詳細: {why})"
991 ),
992 Refused::Unsafe { branch, path, why } => format!(
993 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
994 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
995 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
996 ),
997 Refused::ReleaseFailed { branch, path, run } => format!(
998 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
999 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1000 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1001 ),
1002 }
1003 },
1004 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1005 reviewers_never_answered: |missing, rounds| {
1006 format!(
1007 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1008 クリーンとは認めません"
1009 )
1010 },
1011};
1012
1013fn phrases(language: &str) -> &'static Phrases {
1014 if crate::lang::is_japanese(language) {
1015 &PHRASES_JA
1016 } else {
1017 &PHRASES_EN
1018 }
1019}
1020
1021fn language_of(task: &Task, fallback: &Path) -> String {
1025 crate::lang::of_repo(&repo_for(task, fallback))
1026}
1027
1028pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1032 if q.node == crate::conduct::NODE {
1033 return tasks.iter().find(|t| t.id == q.run);
1034 }
1035 tasks.iter().find(|t| t.runs.contains(&q.run))
1036}
1037
1038fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1047 let tasks = queue.list();
1048 for q in questions.list() {
1049 if q.chosen_action().is_none() {
1050 continue;
1051 }
1052 let Some(listed) = task_of_question(&tasks, &q) else {
1053 continue;
1054 };
1055 if listed.action_applied(&q.id) {
1056 continue;
1057 }
1058 let Ok(_claim) = queue.claim(&listed.id) else {
1059 continue;
1060 };
1061 let Ok(mut task) = queue.get(&listed.id) else {
1062 continue;
1063 };
1064 let language = language_of(&task, Path::new("."));
1065 let decision = decide_action(&task, &q, phrases(&language), |id| {
1066 RunState::load_under(id, home)
1067 });
1068 let ran = matches!(
1069 decision,
1070 ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1071 );
1072 if ran && asker_may_still_read(questions, &q, home) {
1073 continue;
1082 }
1083 let done = matches!(decision, ActionDecision::Done);
1084 match decision {
1085 ActionDecision::Skip => continue,
1086 ActionDecision::Resume(run) => {
1087 task.release_operator("choice", Some(&q.id));
1088 task.resume_override = Some(crate::queue::OperatorResume {
1089 question_id: q.id.clone(),
1090 at: Timestamp::now(),
1091 conductor_rehold: None,
1092 forced: true,
1093 pinned_run: Some(run),
1094 });
1095 }
1096 ActionDecision::Stale => {}
1097 ActionDecision::Requeue => {
1098 task.release_operator("choice-requeue", Some(&q.id));
1099 task.requeue();
1100 }
1101 ActionDecision::Done => task.succeed(),
1102 ActionDecision::Refuse(why) => {
1103 task.hold_machine(Some(why));
1104 notices::raise(
1105 Notice::warn(
1106 &format!("action:{}", q.id),
1107 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1108 )
1109 .link(Link::Task {
1110 id: task.id.clone(),
1111 }),
1112 );
1113 }
1114 }
1115 task.mark_action_applied(&q.id);
1116 record(queue, &mut task);
1119 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1120 supersede_prior_runs(&task, home);
1121 }
1122 let _ = questions.update(&q.id, |r| {
1125 r.answer_delivered = true;
1126 Ok(())
1127 });
1128 }
1129}
1130
1131fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1135 let now = Timestamp::now();
1136 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1137 return true;
1138 }
1139 q.node != crate::conduct::NODE
1140 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1141 s.seats_active()
1142 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1143 })
1144}
1145
1146fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1157 let tasks = queue.list();
1158 let by_id: std::collections::BTreeMap<&str, &Task> =
1159 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1160 let referenced: std::collections::BTreeSet<&str> = tasks
1161 .iter()
1162 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1163 .collect();
1164
1165 for mut question in questions.list() {
1166 if !question.status.open() || question.node != crate::conduct::NODE {
1167 continue;
1168 }
1169 if referenced.contains(question.id.as_str()) {
1172 continue;
1173 }
1174 let Some(task) = by_id.get(question.run.as_str()) else {
1175 continue;
1176 };
1177 question.abandon(format!(
1178 "task {} no longer waits for this answer",
1179 task.short()
1180 ));
1181 if let Err(e) = questions.put(&mut question) {
1182 tracing::warn!(
1183 "could not retire question {} for task {}: {e:#}",
1184 question.short(),
1185 task.short()
1186 );
1187 }
1188 }
1189}
1190
1191#[derive(Debug, Clone, Copy)]
1198pub struct Verdict {
1199 pub status: RunStatus,
1201 pub left_pr: bool,
1203 pub quota_hit: bool,
1205 pub parked: bool,
1207 pub no_viable_candidates: bool,
1214}
1215
1216pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1273 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1274}
1275
1276fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1278 if verdict.parked {
1284 task.park(detail);
1285 return;
1286 }
1287 match verdict.status {
1288 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1289 RunStatus::AlreadyInBase => task.already_landed(detail),
1290 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1291 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1292 task.stall(detail)
1293 }
1294 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1295 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1296 RunStatus::Blocked => task.fail(detail, max_attempts),
1297 RunStatus::VerifiedNoop => task.handed_off(detail),
1298 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1299 }
1300}
1301
1302pub fn supersede_prior_runs(task: &Task, home: &Path) {
1351 let now = Timestamp::now();
1352 let last_run_succeeded = task
1359 .runs
1360 .last()
1361 .and_then(|id| RunState::load_under(id, home).ok())
1362 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1363 for id in task.superseded_attempts(last_run_succeeded) {
1364 let mut state = match RunState::load_under(id, home) {
1365 Ok(s) => s,
1366 Err(e) => {
1367 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1368 continue;
1369 }
1370 };
1371 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1372 continue;
1373 }
1374 let daemon_claims = is_working_on(home, id, now);
1375 if state.liveness(daemon_claims) == Liveness::Live {
1376 continue;
1377 }
1378 state.status = RunStatus::Superseded;
1379 if let Err(e) = state.save_under(home) {
1380 tracing::warn!("could not mark run {id} superseded: {e:#}");
1381 }
1382 }
1383}
1384
1385fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1407 for task in queue.list() {
1408 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1409 continue;
1410 }
1411 supersede_prior_runs(&task, home);
1412 }
1413}
1414
1415fn settle_and_diagnose(
1422 task: &mut Task,
1423 verdict: Verdict,
1424 detail: &str,
1425 max_attempts: usize,
1426 state: &RunState,
1427) {
1428 let p = phrases(&state.config.graph.language);
1429 let attempts_before = task.attempts;
1430 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1436 task.last_error = Some(detail.to_owned());
1437 task.diagnostic = None;
1438 task.attempts = task.attempts.saturating_sub(1);
1439 task.hold_machine(Some(format!(
1440 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1441 no agent was asked and no attempt was spent",
1442 crate::cache::RESOURCE_HOLD,
1443 block.kind,
1444 block.node
1445 )));
1446 if let Some(pass) = state.passes.last() {
1447 task.record_pass(&state.id, pass.index, attempts_before, None);
1448 }
1449 return;
1450 }
1451 settle_in(task, verdict, detail, max_attempts, p);
1452 if let Some(pass) = state.passes.last() {
1455 let parked = match &pass.end {
1456 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1457 _ => None,
1458 };
1459 task.record_pass(&state.id, pass.index, attempts_before, parked);
1460 }
1461 if task.status == TaskStatus::Held {
1462 task.diagnostic = diagnostic(state);
1463 note_open_question(task, &state.id, p);
1464 }
1465}
1466
1467fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1482 let Some(home) = crate::run::try_home() else {
1483 return;
1484 };
1485 let open = Questions::at(home.join("questions")).open_for(run);
1486 let Some(q) = open.first() else {
1487 return;
1488 };
1489 let base = task.hold_reason.clone().unwrap_or_default();
1490 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1491}
1492
1493fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1504 match last_run {
1505 Some(state) => {
1506 let verdict = Verdict {
1507 status: state.status,
1508 left_pr: state.pr.is_some(),
1509 quota_hit: !state.quota.is_empty(),
1510 parked: state.parked,
1511 no_viable_candidates: state.viable().is_empty(),
1512 };
1513 let detail = format!(
1514 "{}{}",
1515 phrases(&state.config.graph.language).recovered_running,
1516 describe(&state)
1517 );
1518 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1519 }
1520 None => {
1521 let why = phrases(language).no_run_to_recover;
1524 task.last_error = Some(why.to_owned());
1525 task.hold_machine(Some(why.to_owned()));
1528 }
1529 }
1530}
1531
1532fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1554 let mut reclaimed = Vec::new();
1555 for listed in queue.list() {
1556 if listed.status != TaskStatus::Running {
1557 continue;
1558 }
1559 let Ok(_claim) = queue.claim(&listed.id) else {
1560 continue;
1561 };
1562 let Ok(mut task) = queue.get(&listed.id) else {
1566 continue;
1567 };
1568 if task.status != TaskStatus::Running {
1569 continue;
1570 }
1571 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1572 if let Some(state) = &last_run
1582 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1583 {
1584 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1585 }
1586 let language = if last_run.is_none() {
1587 language_of(&task, Path::new("."))
1588 } else {
1589 String::new()
1590 };
1591 reclaim(&mut task, last_run, max_attempts, &language);
1592 if task.status == TaskStatus::Done {
1593 supersede_prior_runs(&task, &crate::run::home());
1594 }
1595 record(queue, &mut task);
1596 reclaimed.push(task.id.clone());
1597 }
1598 reclaimed
1599}
1600
1601fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1633 reclaim_abandoned_runs_with(
1634 home,
1635 now,
1636 crate::proc::pid_status,
1637 crate::proc::process_started_at,
1638 )
1639}
1640
1641fn reclaim_abandoned_runs_with<F, G>(
1647 home: &Path,
1648 now: Timestamp,
1649 query: F,
1650 identity: G,
1651) -> Vec<String>
1652where
1653 F: Fn(u32) -> Option<bool>,
1654 G: Fn(u32) -> Option<String>,
1655{
1656 let mut abandoned = Vec::new();
1657 for entry in std::fs::read_dir(home.join("runs"))
1658 .into_iter()
1659 .flatten()
1660 .flatten()
1661 {
1662 let id = entry.file_name().to_string_lossy().into_owned();
1663 if !crate::run::is_run_id(&id) {
1664 continue;
1665 }
1666 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1674 continue;
1675 };
1676 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1677 continue;
1678 };
1679 if state.status.done() || !state.active_all_overrun(now) {
1680 continue;
1681 }
1682 let daemon_claims = is_working_on(home, &id, now);
1694 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1695 continue;
1696 }
1697 state.abandon("daemon");
1698 if let Err(e) = state.save_under(home) {
1699 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1700 continue;
1701 }
1702 if let Some(notice) = notices::run_ended(&state) {
1705 notices::raise_in(home, notice);
1706 }
1707 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1715 tracing::warn!("abandon questions for {id}: {e:#}");
1716 }
1717 abandoned.push(id);
1718 }
1719 abandoned
1720}
1721
1722pub async fn serve(opts: Opts) -> Result<()> {
1728 serve_until(opts, Stop::new()).await
1729}
1730
1731pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1748 let signal = {
1749 let stop = stop.clone();
1750 tokio::spawn(async move {
1751 if tokio::signal::ctrl_c().await.is_ok() {
1752 stop.stop();
1753 tracing::info!("shutdown requested; a run in flight will be finished first");
1754 }
1755 })
1756 };
1757
1758 let worktrees_root = opts
1759 .worktrees_root
1760 .clone()
1761 .unwrap_or_else(crate::run::default_worktree_root);
1762 let outcome = drive(
1763 &opts,
1764 &Queue::open(),
1765 &status_path(),
1766 &crate::run::home(),
1767 &worktrees_root,
1768 &stop,
1769 )
1770 .await;
1771
1772 signal.abort();
1773 outcome
1774}
1775
1776async fn drive(
1789 opts: &Opts,
1790 queue: &Queue,
1791 status_file: &Path,
1792 home: &Path,
1793 worktrees_root: &Path,
1794 stop: &Stop,
1795) -> Result<()> {
1796 let status = Arc::new(Mutex::new(Status::new()));
1804 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1805 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1806
1807 let daemon_cfg = prepare(&opts.repo, opts)
1813 .map(|c| c.daemon)
1814 .unwrap_or_default();
1815 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1816
1817 let waiter = tokio::spawn(crate::waiter::run(
1822 crate::waiter::Waiter::new(
1823 crate::ask::Questions::at(home.join("questions")),
1824 home.to_path_buf(),
1825 prepare(&opts.repo, opts).ok(),
1826 ),
1827 stop.clone(),
1828 ));
1829
1830 let deputies = tokio::spawn(crate::deputy::run(
1834 crate::deputy::Deputies::new(
1835 crate::ask::Questions::at(home.join("questions")),
1836 home.to_path_buf(),
1837 prepare(&opts.repo, opts).ok(),
1838 opts.repo.clone(),
1839 daemon_cfg.max_deputies,
1840 {
1841 let stop = stop.clone();
1842 Arc::new(move || stop.parking())
1843 },
1844 ),
1845 stop.clone(),
1846 ));
1847
1848 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1851
1852 let release_watch = tokio::spawn(crate::release_watch::run(
1855 crate::release_watch::Watcher::new(
1856 Box::new(crate::release_watch::GhForge),
1857 home.to_path_buf(),
1858 ),
1859 {
1860 let (repo, opts) = (opts.repo.clone(), opts.clone());
1861 move || release_watch_settings(&repo, &opts)
1862 },
1863 stop.clone(),
1864 ));
1865
1866 tracing::info!(
1867 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1868 queue.root().display(),
1869 opts.poll.as_secs(),
1870 opts.max_attempts,
1871 concurrency,
1872 if daemon_cfg.pause_for_interrupts {
1873 ", interrupts enabled"
1874 } else {
1875 ""
1876 }
1877 );
1878
1879 janitor(&opts.repo, opts, home, worktrees_root).await;
1882 resweep_superseded_attempts(queue, home);
1883
1884 let outcome = poll(
1885 opts,
1886 queue,
1887 &status,
1888 home,
1889 worktrees_root,
1890 stop,
1891 DispatchLimits {
1892 max_concurrent: concurrency,
1893 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1894 },
1895 )
1896 .await;
1897
1898 beat.abort();
1899 waiter.abort();
1900 deputies.abort();
1901 fetcher.abort();
1902 release_watch.abort();
1903 clear_status_at(status_file);
1904 outcome
1905}
1906
1907fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
1910 let Ok(cfg) = prepare(repo, opts) else {
1911 return (Vec::new(), 0);
1912 };
1913 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
1914 .into_iter()
1915 .map(|r| r.path)
1916 .collect();
1917 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
1920 let runs = crate::run::home().join("runs");
1921 for id in crate::run::list_ids_in(&runs) {
1922 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
1923 .ok()
1924 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1925 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
1926 known.extend(repo);
1927 }
1928 for k in known {
1929 let k = k.canonicalize().unwrap_or(k);
1930 if k.join(".git").exists() && !paths.contains(&k) {
1931 paths.push(k);
1932 }
1933 }
1934 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
1935 if !paths.contains(&own) {
1936 paths.push(own);
1937 }
1938 (paths, cfg.daemon.release_stall_minutes)
1939}
1940
1941const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
1943
1944async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
1948 while !stop.stopped() {
1949 let (interval, roots) = match prepare(&repo, &opts) {
1950 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
1951 Err(_) => (0, Vec::new()),
1952 };
1953 if interval > 0 && !roots.is_empty() {
1954 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
1955 tracing::debug!("fetch origins: {r:?}");
1956 }
1957 let wait = if interval > 0 { interval } else { 60 };
1959 let mut slept = 0;
1960 while slept < wait && !stop.stopped() {
1961 tokio::time::sleep(Duration::from_secs(1)).await;
1962 slept += 1;
1963 }
1964 }
1965}
1966
1967async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1973 loop {
1974 tokio::time::sleep(HEARTBEAT).await;
1975 let snapshot = {
1976 let mut guard = lock(&status);
1977 guard.updated_at = Timestamp::now();
1978 guard.clone()
1979 };
1980 if let Err(e) = write_status_to(&path, &snapshot) {
1981 tracing::warn!("could not refresh the daemon status file: {e:#}");
1984 }
1985 }
1986}
1987
1988#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1991enum LandResume {
1992 NotLanding,
1995 StillWaiting,
2000 Ready,
2004}
2005
2006fn land_resume_state(task: &Task) -> LandResume {
2010 let Some(run_id) = task.runs.last() else {
2011 return LandResume::NotLanding;
2012 };
2013 let Ok(state) = RunState::load(run_id) else {
2014 return LandResume::NotLanding;
2015 };
2016 if !implementers_match(task, &state) || !state.parked {
2017 return LandResume::NotLanding;
2018 }
2019 let node = if state.status == RunStatus::Landing {
2023 land::APPROVAL_NODE
2024 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2025 crate::github_text::ASK_NODE
2026 } else {
2027 return LandResume::NotLanding;
2028 };
2029 let store = ask::Questions::open();
2030 let waiting = store
2031 .list()
2032 .into_iter()
2033 .filter(|q| &q.run == run_id && q.node == node)
2034 .max_by(|a, b| a.id.cmp(&b.id));
2035 let Some(mut q) = waiting else {
2036 return LandResume::Ready;
2037 };
2038 if !q.status.open() {
2039 return LandResume::Ready;
2040 }
2041 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2048 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2049 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2050 q.abandon(format!(
2051 "no answer within {}s of asking",
2052 timeout.as_secs().max(1)
2053 ));
2054 if store.put(&mut q).is_ok() {
2057 return LandResume::Ready;
2058 }
2059 }
2060 LandResume::StillWaiting
2061}
2062
2063const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2071
2072const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2084
2085struct InFlightGuard<'a> {
2098 status: &'a Arc<Mutex<Status>>,
2099 stop: &'a Stop,
2100 task_id: &'a str,
2101}
2102
2103impl Drop for InFlightGuard<'_> {
2104 fn drop(&mut self) {
2105 lock(self.status).current.retain(|c| c.task != self.task_id);
2106 self.stop.exit();
2107 }
2108}
2109
2110#[derive(Debug, Clone, PartialEq, Eq)]
2132enum Interrupt {
2133 Idle,
2135 Parking {
2147 parked: Vec<String>,
2148 interrupt_task: String,
2149 },
2150 Running {
2158 parked: Vec<String>,
2159 interrupt_task: String,
2160 },
2161 Resuming { parked: Vec<String> },
2168}
2169
2170fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2191 match state {
2192 Interrupt::Idle => {
2193 if in_flight.len() != 1 {
2205 return Interrupt::Idle;
2206 }
2207 match runnable.iter().find(|t| t.interrupt) {
2208 Some(t) => Interrupt::Parking {
2209 parked: in_flight.to_vec(),
2210 interrupt_task: t.id.clone(),
2211 },
2212 None => Interrupt::Idle,
2213 }
2214 }
2215 Interrupt::Parking {
2216 parked,
2217 interrupt_task,
2218 } => {
2219 if in_flight.iter().any(|id| parked.contains(id)) {
2220 Interrupt::Parking {
2222 parked,
2223 interrupt_task,
2224 }
2225 } else if in_flight.contains(&interrupt_task) {
2226 Interrupt::Running {
2227 parked,
2228 interrupt_task,
2229 }
2230 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2231 Interrupt::Parking {
2235 parked,
2236 interrupt_task,
2237 }
2238 } else {
2239 Interrupt::Resuming { parked }
2244 }
2245 }
2246 Interrupt::Running {
2247 parked,
2248 interrupt_task,
2249 } => {
2250 if in_flight.contains(&interrupt_task) {
2251 Interrupt::Running {
2252 parked,
2253 interrupt_task,
2254 }
2255 } else {
2256 Interrupt::Resuming { parked }
2262 }
2263 }
2264 Interrupt::Resuming { parked } => {
2265 if in_flight.iter().any(|id| parked.contains(id)) {
2266 Interrupt::Idle
2272 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2273 Interrupt::Resuming { parked }
2274 } else {
2275 Interrupt::Idle
2278 }
2279 }
2280 }
2281}
2282
2283fn advance_interrupt_tick(
2289 enabled: bool,
2290 state: Interrupt,
2291 in_flight: &[String],
2292 runnable: &[Task],
2293) -> Interrupt {
2294 if !enabled {
2295 return Interrupt::Idle;
2296 }
2297 advance_interrupt(state, in_flight, runnable)
2298}
2299
2300fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2305 match state {
2306 Interrupt::Idle => candidates,
2307 Interrupt::Parking {
2308 parked,
2309 interrupt_task,
2310 } => {
2311 if in_flight.iter().any(|id| parked.contains(id)) {
2312 Vec::new()
2313 } else {
2314 candidates
2315 .into_iter()
2316 .filter(|t| &t.id == interrupt_task)
2317 .collect()
2318 }
2319 }
2320 Interrupt::Running { .. } => Vec::new(),
2321 Interrupt::Resuming { parked } => candidates
2329 .into_iter()
2330 .find(|t| parked.contains(&t.id))
2331 .into_iter()
2332 .collect(),
2333 }
2334}
2335
2336struct DispatchLimits {
2340 max_concurrent: usize,
2343 pause_for_interrupts: bool,
2345}
2346
2347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2356enum PermitKind {
2357 None,
2362 Urgent,
2369 Ordinary,
2372}
2373
2374fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2377 if priority {
2378 PermitKind::None
2379 } else if urgent {
2380 PermitKind::Urgent
2381 } else {
2382 PermitKind::Ordinary
2383 }
2384}
2385
2386struct DispatchClaim {
2387 task: Task,
2388 claim: crate::queue::Claim,
2389 permit: Option<tokio::sync::OwnedSemaphorePermit>,
2390}
2391
2392fn claim_dispatch(
2395 queue: &Queue,
2396 candidate: &Task,
2397 cooling_down: bool,
2398 ordinary: &Arc<tokio::sync::Semaphore>,
2399 urgent: &Arc<tokio::sync::Semaphore>,
2400) -> Option<DispatchClaim> {
2401 let Ok(claim) = queue.claim(&candidate.id) else {
2402 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2403 return None;
2404 };
2405 let task = match queue.get(&candidate.id) {
2406 Ok(t) if t.status.runnable() => t,
2407 Ok(_) => return None,
2408 Err(e) => {
2409 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2410 return None;
2411 }
2412 };
2413 let resume = land_resume_state(&task);
2414 if resume == LandResume::StillWaiting {
2415 return None;
2416 }
2417 let priority = resume == LandResume::Ready;
2418 if !priority && cooling_down {
2419 return None;
2420 }
2421 let permit = match permit_kind(priority, task.urgent) {
2424 PermitKind::None => None,
2425 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
2426 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
2427 };
2428 Some(DispatchClaim {
2429 task,
2430 claim,
2431 permit,
2432 })
2433}
2434
2435async fn poll(
2454 opts: &Opts,
2455 queue: &Queue,
2456 status: &Arc<Mutex<Status>>,
2457 home: &Path,
2458 worktrees_root: &Path,
2459 stop: &Stop,
2460 limits: DispatchLimits,
2461) -> Result<()> {
2462 let DispatchLimits {
2463 max_concurrent,
2464 pause_for_interrupts,
2465 } = limits;
2466 let mut attempted: Vec<String> = Vec::new();
2471 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2472 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2480 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2486 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2487 let mut conductor = Conductor::new();
2488 let mut cache_last_checked: Option<Timestamp> = None;
2491 let mut interrupt = Interrupt::Idle;
2493 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2499 std::collections::HashMap::new();
2500
2501 while !stop.stopped() {
2502 lock(status).polls += 1;
2503
2504 while let Some(result) = inflight.try_join_next() {
2509 if let Err(e) = result {
2510 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2511 notices::raise(Notice::error(
2512 "loop:attempt",
2513 "A queued attempt ended abnormally; check the task it was running.",
2514 ));
2515 }
2516 }
2517
2518 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2519 if !swept.is_empty() {
2520 tracing::warn!(
2521 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2522 swept.len(),
2523 swept.join(", ")
2524 );
2525 }
2526 let now = Timestamp::now();
2531
2532 if !stop.busy_now() {
2537 maybe_prune_cache_between_runs(
2538 &opts.repo,
2539 opts,
2540 home,
2541 stop,
2542 &mut cache_last_checked,
2543 now,
2544 )
2545 .await;
2546 }
2547
2548 let stalled = stalled_tasks(queue, home, now);
2549 let stalled_ids: std::collections::BTreeSet<_> =
2550 stalled.iter().map(|task| task.id.clone()).collect();
2551 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2552 if !reclaimed.is_empty() {
2553 tracing::warn!(
2554 "reclaimed {} task(s) left `running` by a daemon that never \
2555 recorded the outcome: {}",
2556 reclaimed.len(),
2557 reclaimed.join(", ")
2558 );
2559 }
2560 let abandoned_runs = reclaim_abandoned_runs(home, now);
2561 if !abandoned_runs.is_empty() {
2562 tracing::warn!(
2563 "failed {} run(s) left behind by a killed process, past every \
2564 active seat's own timeout: {}",
2565 abandoned_runs.len(),
2566 abandoned_runs.join(", ")
2567 );
2568 }
2569
2570 let questions = Questions::at(home.join("questions"));
2575
2576 resolve_blockers(queue, &questions);
2579 apply_choice_actions(queue, &questions, home);
2580 triage::apply_answers(queue, &questions);
2581 reconcile_task_questions(queue, &questions);
2582 {
2586 let talks = crate::talk::Talks::at(home.join("talks"));
2587 crate::chat_notify::sweep(queue, &talks, home);
2588 crate::chat_watch::sweep(home, &talks);
2589 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2590 }
2591
2592 let finished: Vec<Task> = finished_tasks(queue)
2598 .into_iter()
2599 .filter(|task| !stalled_ids.contains(&task.id))
2600 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2604 .collect();
2605 let queued = queued_tasks(queue);
2606 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2610 && conductor.worth_a_look(queue, &stalled, &finished)
2611 {
2612 match prepare(&opts.repo, opts) {
2613 Ok(cfg) => {
2614 conductor
2615 .maybe_run(
2616 &cfg,
2617 &opts.repo,
2618 queue,
2619 &questions,
2620 home,
2621 &queued,
2622 &stalled,
2623 &finished,
2624 opts.max_attempts,
2625 )
2626 .await;
2627 }
2628 Err(e) => {
2629 tracing::warn!("conductor: no config: {e:#}");
2630 notices::raise(Notice::warn(
2631 "loop:no-config",
2632 "The loop could not read this repository's config, so held tasks are not being triaged.",
2633 ));
2634 }
2635 }
2636 }
2637
2638 let candidates: Vec<Task> = runnable(queue)
2639 .into_iter()
2640 .filter(|t| !opts.once || !attempted.contains(&t.id))
2641 .collect();
2642
2643 let in_flight: Vec<String> = lock(status)
2648 .current
2649 .iter()
2650 .map(|c| c.task.clone())
2651 .collect();
2652 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2653
2654 interrupt =
2655 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2656 if let Interrupt::Parking {
2657 parked,
2658 interrupt_task,
2659 } = &interrupt
2660 {
2661 let reason = format!(
2662 "task {} asked to run first",
2663 crate::run::short_of(interrupt_task)
2664 );
2665 for id in parked {
2666 if let Some(pause) = interrupt_pauses.get(id) {
2667 pause.park_because(reason.clone());
2668 }
2669 }
2670 }
2671 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2672
2673 let cooling_down =
2674 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2675
2676 let mut started_any = false;
2677 for candidate in candidates {
2678 if stop.stopped() {
2679 break;
2680 }
2681
2682 let Some(DispatchClaim {
2683 mut task,
2684 claim,
2685 permit,
2686 }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
2687 else {
2688 continue;
2689 };
2690
2691 let task_id = task.id.clone();
2692 attempted.push(task_id.clone());
2693 lock(status).idle = false;
2694 stop.enter();
2697 started_any = true;
2698
2699 let run_pause = crate::graph::Pause::new();
2703 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2704
2705 let opts = opts.clone();
2706 let queue = queue.clone();
2707 let status = Arc::clone(status);
2708 let stop = stop.clone();
2709 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2710 inflight.spawn(async move {
2711 let _claim = claim;
2715 let _permit = permit;
2716 let _inflight = InFlightGuard {
2718 status: &status,
2719 stop: &stop,
2720 task_id: &task_id,
2721 };
2722 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2723 lock(&status).completed += 1;
2724 let now = Timestamp::now();
2730 if let Some(until) = cooldown_until("a, now) {
2731 let wait = until.as_second() - now.as_second();
2732 *lock("a_cooldown_until) = Some(until);
2733 let hint = quota
2734 .iter()
2735 .find(|q| q.reset.is_some())
2736 .and_then(|q| q.reset.as_deref());
2737 match hint {
2738 Some(h) => tracing::warn!(
2739 "quota hit; waiting {wait}s before taking another ordinary task \
2740 (CLI reported reset: {h})"
2741 ),
2742 None => tracing::warn!(
2743 "quota hit; waiting {wait}s before taking another ordinary task \
2744 (no reset hint reported)"
2745 ),
2746 }
2747 }
2748 });
2749 }
2750
2751 if started_any {
2752 continue;
2753 }
2754
2755 if stop.busy_now() {
2756 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2761 continue;
2762 }
2763
2764 lock(status).idle = true;
2766 if opts.once {
2767 janitor(&opts.repo, opts, home, worktrees_root).await;
2771 resweep_superseded_attempts(queue, home);
2772 triage_held(queue, home, opts).await;
2773 break;
2774 }
2775 stop.idle(opts.poll).await;
2776 if stop.stopped() {
2777 continue;
2778 }
2779 janitor(&opts.repo, opts, home, worktrees_root).await;
2785 resweep_superseded_attempts(queue, home);
2786 triage_held(queue, home, opts).await;
2787 }
2788
2789 while let Some(result) = inflight.join_next().await {
2794 if let Err(e) = result {
2795 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2796 notices::raise(Notice::error(
2797 "loop:attempt",
2798 "A queued attempt ended abnormally; check the task it was running.",
2799 ));
2800 }
2801 }
2802 Ok(())
2803}
2804
2805async fn attempt(
2811 opts: &Opts,
2812 queue: &Queue,
2813 status: &Arc<Mutex<Status>>,
2814 stop: &Stop,
2815 interrupt_pause: crate::graph::Pause,
2816 task: &mut Task,
2817) -> Vec<QuotaLoss> {
2818 let repo = repo_for(task, &opts.repo);
2819 tracing::info!(
2820 "task {} — {} (repo {})",
2821 task.short(),
2822 task.title,
2823 repo.display()
2824 );
2825
2826 let explicit = match &task.overrides {
2830 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
2831 Some(_) => opts.config.as_deref(),
2832 None => opts.config.as_deref(),
2833 };
2834 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2835 let reason = format!("[config] {e:#}");
2836 task.last_error = Some(reason.clone());
2837 task.hold_machine(Some(reason.clone()));
2838 record(queue, task);
2839 tracing::warn!("holding {}: {reason}", task.short());
2840 return Vec::new();
2841 }
2842 let mut config = match prepare_for(&repo, opts, task) {
2843 Ok(c) => c,
2844 Err(e) => {
2845 task.attempts += 1;
2849 task.fail(format!("config: {e:#}"), opts.max_attempts);
2850 record(queue, task);
2851 return Vec::new();
2852 }
2853 };
2854 apply_task_implementers(&mut config, task);
2855 let p = phrases(&config.graph.language);
2856 let start_failed = p.could_not_start;
2857
2858 if let Some(reason) = disk_gate(&repo, &config) {
2866 task.last_error = Some(reason.clone());
2867 task.hold_machine(Some(reason.clone()));
2868 record(queue, task);
2869 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2870 notices::raise(
2873 Notice::warn(
2874 &format!("disk:{}", repo.display()),
2875 "A task was held for want of free disk space; free some, then release it from the queue.",
2876 )
2877 .link(Link::Task {
2878 id: task.id.clone(),
2879 }),
2880 );
2881 return Vec::new();
2882 }
2883
2884 let unfinished = (!task.fresh_start)
2904 .then(|| unfinished_run(&task.runs, task.short()))
2905 .flatten()
2906 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
2907 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
2913 let review_branch = take_review_branch(task, previous.as_ref());
2914 let branch_exists = match &review_branch {
2915 Some(branch) => crate::git::branch_exists(&repo, branch)
2916 .await
2917 .unwrap_or(false),
2918 None => false,
2919 };
2920 let proposed = match (&review_branch, &unfinished, &task.review_of) {
2924 (None, None, Some(branch)) => Starter::Review(branch.clone()),
2925 _ => choose_starter(
2926 review_branch.as_deref(),
2927 branch_exists,
2928 unfinished.as_deref(),
2929 ),
2930 };
2931 let starter = if let Some(selected) = &task.pr_recovery {
2932 if selected.check_task(&task.id, &task.instruction).is_ok() {
2933 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
2934 } else {
2935 Starter::Review(selected.branch.clone())
2936 }
2937 } else {
2938 starter_with_implementers(task, previous.as_ref(), proposed)
2939 };
2940 let attachments = match task_attachments(queue, task) {
2945 Ok(a) => a,
2946 Err(e) => {
2947 task.attempts += 1;
2948 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2949 record(queue, task);
2950 return Vec::new();
2951 }
2952 };
2953 let started = match &starter {
2954 Starter::Review(_) if task.pr_recovery.is_some() => {
2955 let selected = task.pr_recovery.clone().expect("selected recovery");
2956 match selected.check_task(&task.id, &task.instruction) {
2957 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
2958 .await
2959 .map(|mut r| {
2960 r.state.attachments = attachments.clone();
2961 r
2962 }),
2963 Err(e) => Err(e),
2964 }
2965 }
2966 Starter::Review(branch) => {
2967 tracing::info!(
2968 "task {} reopens `{branch}` as a review-only pass",
2969 task.short()
2970 );
2971 let takeover = crate::handover::Takeover {
2974 earlier: task.earlier_attempts().to_vec(),
2975 home: crate::run::home(),
2976 choice: take_divergence_answer(branch, &config.merge.remote, task),
2977 task_instruction: Some(instruction_for(task)),
2978 };
2979 Runner::review_taking_over(
2980 &repo,
2981 branch,
2982 config,
2983 Some(takeover),
2984 crate::run::Origin::queue(&task.id),
2985 )
2986 .await
2987 }
2988 Starter::Resume(id) => {
2989 tracing::info!("resuming run {id} rather than competing again");
2990 Runner::resume(id).and_then(|mut r| {
2991 if r.state.prep_failure.is_some() {
2992 let approval = task
2993 .resumption
2994 .as_ref()
2995 .context("preparation retry requires an explicit task release")?;
2996 r.retry_preparation(approval.at)?;
2997 }
2998 if let Some(instruction) =
2999 prepare_instruction(&starter, Some(&r.state.instruction), task)
3000 {
3001 r.state.instruction = instruction;
3002 }
3003 r.state.attachments = attachments.clone();
3004 if let Some(mode) = task
3007 .overrides
3008 .as_ref()
3009 .and_then(|o| o.merge.as_deref())
3010 .and_then(|m| merge_mode(m).ok())
3011 {
3012 r.state.config.merge.mode = mode;
3013 }
3014 Ok(r)
3015 })
3016 }
3017 Starter::Start => {
3018 if let Some(branch) = &review_branch {
3019 tracing::warn!(
3020 "conductor chose review for task {} but branch `{branch}` no longer \
3021 exists; requeuing as a fresh competition instead",
3022 task.short()
3023 );
3024 }
3025 let instruction = prepare_instruction(&starter, None, task)
3026 .unwrap_or_else(|| task.instruction.clone());
3027 Runner::start_naming(
3028 &repo,
3029 instruction,
3030 &task.title,
3031 config,
3032 crate::run::Origin::queue(&task.id),
3033 )
3034 .await
3035 .map(|mut r| {
3036 r.state.attachments = attachments.clone();
3037 r
3038 })
3039 }
3040 };
3041 let mut runner = match started {
3042 Ok(r) => r,
3043 Err(e) if task.pr_recovery.is_some() => {
3047 task.attempts += 1;
3048 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3049 task.link_run(&partial.run);
3050 task.record_pass(&partial.run, 0, task.attempts, None);
3051 }
3052 task.last_error = Some(format!("{start_failed}{e:#}"));
3053 task.hold_unrequested_retry(Some(format!(
3054 "Selected public-head recovery could not start: {e:#}. Correct the cause and use `magi task recover-pr` with the approved public head; automatic recovery is stopped."
3055 )));
3056 record(queue, task);
3057 return Vec::new();
3058 }
3059 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3060 let detail = match e.downcast_ref::<crate::handover::Refused>() {
3061 Some(r) => (p.handover_refused)(r),
3062 None => format!("{e:#}"),
3063 };
3064 let reason = format!("{start_failed}{detail}");
3065 task.last_error = Some(reason.clone());
3066 let branch = match &starter {
3069 Starter::Review(branch) => Some(branch.clone()),
3070 _ => None,
3071 };
3072 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3076 record(queue, task);
3077 tracing::warn!(
3078 "holding {} for a branch it cannot take over: {e:#}",
3079 task.short()
3080 );
3081 return Vec::new();
3082 }
3083 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3088 let d = e
3089 .downcast_ref::<crate::reconcile::Diverged>()
3090 .expect("checked by the guard");
3091 let mut q = ask::Question::new(
3092 task.id.clone(),
3093 crate::reconcile::NODE.to_owned(),
3094 crate::reconcile::SEAT.to_owned(),
3095 d.summary(),
3096 d.detail(),
3097 d.choices(),
3098 );
3099 match Questions::open().put(&mut q) {
3100 Ok(()) => {
3101 task.last_error = Some(format!("{e:#}"));
3102 task.review_branch = Some(d.branch.clone());
3105 task.review_instruction = Some(task.instruction.clone());
3106 task.block(vec![q.id.clone()], Some(d.summary()));
3107 }
3108 Err(put) => {
3109 tracing::warn!("could not file the divergence question: {put:#}");
3110 task.attempts += 1;
3111 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3112 }
3113 }
3114 record(queue, task);
3115 return Vec::new();
3116 }
3117 Err(e) => {
3118 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3124 && let Starter::Review(branch) = &starter
3125 {
3126 task.review_branch = Some(branch.clone());
3127 task.review_instruction = Some(task.instruction.clone());
3128 task.last_error = Some(format!("{start_failed}{e:#}"));
3129 task.status = crate::queue::TaskStatus::Failed;
3130 record(queue, task);
3131 return Vec::new();
3132 }
3133 task.attempts += 1;
3134 task.last_error = Some(format!("{start_failed}{e:#}"));
3135 task.hold_unrequested_retry(Some(format!(
3136 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3137 )));
3138 record(queue, task);
3139 return Vec::new();
3140 }
3141 };
3142 runner.state.task_instruction = Some(task.instruction.clone());
3143 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3146 if runner.state.origin_chat.is_none() {
3147 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3148 }
3149 runner.on_pause(stop.pause());
3151 runner.watch_interrupt(interrupt_pause);
3155
3156 let run = runner.state.id.clone();
3159 task.start(run.clone());
3160 record(queue, task);
3161 lock(status).current.push(Current {
3162 task: task.id.clone(),
3163 run,
3164 });
3165
3166 let quota_before = runner.state.quota.clone();
3169 runner.state.next_pass_task_entry = true;
3170 let result = runner.execute().await;
3171 finish_attempt(
3172 opts.max_attempts,
3173 queue,
3174 task,
3175 &runner.state,
3176 "a_before,
3177 result,
3178 )
3179}
3180
3181pub fn finish_attempt(
3186 max_attempts: usize,
3187 queue: &Queue,
3188 task: &mut Task,
3189 state: &RunState,
3190 quota_before: &[QuotaLoss],
3191 result: Result<()>,
3192) -> Vec<QuotaLoss> {
3193 let detail = match result {
3194 Ok(()) => describe(state),
3195 Err(e) => format!("{e:#}"),
3196 };
3197 let fresh = losses_this_attempt(quota_before, &state.quota);
3198 let verdict = Verdict {
3199 status: state.status,
3200 left_pr: state.pr.is_some(),
3203 quota_hit: !fresh.is_empty(),
3209 parked: state.parked,
3213 no_viable_candidates: state.viable().is_empty(),
3216 };
3217 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3218 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
3219 task.hold_unrequested_retry(Some(format!(
3220 "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
3221 )));
3222 }
3223 if task.status == TaskStatus::Done {
3224 supersede_prior_runs(task, &crate::run::home());
3225 }
3226 record(queue, task);
3227 tracing::info!(
3228 "task {} is {} after run {} ({})",
3229 task.short(),
3230 task.status.as_str(),
3231 state.short(),
3232 label(state.status)
3233 );
3234 fresh
3235}
3236
3237pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3241 let waits_on_owner = withheld_text_wait(task).is_some();
3246 if task.status.runnable() && !waits_on_owner {
3247 let why = task.last_error.clone().map_or_else(
3248 || "the run did not finish".to_owned(),
3249 |e| format!("the run did not finish: {e}"),
3250 );
3251 task.hold_unrequested_retry(Some(format!(
3252 "{why}. It was started by hand, so it is not retried \
3253 automatically; `magi task release` retries it."
3254 )));
3255 record(queue, task);
3256 }
3257}
3258
3259#[must_use]
3263pub fn loop_would_resume(run: &str) -> bool {
3264 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3265}
3266
3267#[must_use]
3277pub fn foreign_loop(
3278 reading: Option<&Reading>,
3279 now: Timestamp,
3280 own_pid: u32,
3281) -> Option<Option<u32>> {
3282 let reading = reading.filter(|r| r.running(now))?;
3283 match reading.pid {
3284 Some(pid) if pid == own_pid => None,
3285 pid => Some(pid),
3286 }
3287}
3288
3289pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3304 let status = Arc::new(Mutex::new(Status::new()));
3305 let stop = Stop::new();
3306 attempt(
3307 opts,
3308 queue,
3309 &status,
3310 &stop,
3311 crate::graph::Pause::new(),
3312 task,
3313 )
3314 .await;
3315 let mut resumes = 0;
3324 while resumes < MAX_WITHHELD_RESUMES {
3325 let Some(timeout) = withheld_text_wait(task) else {
3326 break;
3327 };
3328 eprintln!(
3329 "waiting for the owner's answer on a withheld pull request text \
3330 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3331 );
3332 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3335 let ready = loop {
3336 match land_resume_state(task) {
3337 LandResume::StillWaiting if std::time::Instant::now() < limit => {
3338 tokio::time::sleep(WITHHELD_POLL).await;
3339 }
3340 LandResume::Ready => break true,
3341 _ => break false,
3342 }
3343 };
3344 if !ready {
3345 break;
3346 }
3347 resumes += 1;
3348 attempt(
3349 opts,
3350 queue,
3351 &status,
3352 &stop,
3353 crate::graph::Pause::new(),
3354 task,
3355 )
3356 .await;
3357 }
3358 hold_if_runnable(queue, task);
3359}
3360
3361const MAX_WITHHELD_RESUMES: u32 = 3;
3364
3365const WITHHELD_POLL: Duration = Duration::from_secs(15);
3367
3368fn withheld_text_wait(task: &Task) -> Option<u64> {
3371 let id = task.runs.last()?;
3372 let s = RunState::load(id).ok()?;
3373 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3374 .then_some(s.config.graph.answer_timeout)
3375}
3376
3377fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3387 after
3388 .iter()
3389 .filter(|q| !before.contains(q))
3390 .cloned()
3391 .collect()
3392}
3393
3394fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3397 if quota.is_empty() {
3398 return None;
3399 }
3400 let with_hint = quota.iter().find(|q| q.reset.is_some());
3401 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3402 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3403 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3404 Some(
3405 now.checked_add(jiff::SignedDuration::from_secs(secs))
3406 .unwrap_or(Timestamp::MAX),
3407 )
3408}
3409
3410fn implementers_match(task: &Task, state: &RunState) -> bool {
3412 task.implementers()
3413 .is_none_or(|n| n == state.config.graph.implementers)
3414}
3415
3416fn starter_with_implementers(
3418 task: &Task,
3419 previous: Option<&RunState>,
3420 proposed: Starter,
3421) -> Starter {
3422 if previous.is_some_and(|s| !implementers_match(task, s)) {
3423 task.review_of
3424 .as_ref()
3425 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3426 } else {
3427 proposed
3428 }
3429}
3430
3431fn apply_task_implementers(config: &mut Config, task: &Task) {
3433 if let Some(n) = task.implementers() {
3434 config.graph.implementers = n;
3435 }
3436}
3437
3438fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3443 let Some(o) = &task.overrides else {
3444 return prepare(repo, opts);
3445 };
3446 let own = Opts {
3450 config: o.config.clone(),
3451 merge: None,
3452 ..opts.clone()
3453 };
3454 let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3455 o.apply(&mut config);
3456 Ok(config)
3457}
3458
3459fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3461 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3462 if let Some(mode) = &opts.merge {
3463 config.merge.mode = merge_mode(mode)?;
3464 }
3465 Ok(config)
3466}
3467
3468async fn maybe_prune_cache_between_runs(
3499 repo: &Path,
3500 opts: &Opts,
3501 home: &Path,
3502 stop: &Stop,
3503 last_checked: &mut Option<Timestamp>,
3504 now: Timestamp,
3505) {
3506 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3507 return;
3508 }
3509 *last_checked = Some(now);
3510 let cfg = match prepare(repo, opts) {
3511 Ok(cfg) => cfg,
3512 Err(e) => {
3513 tracing::warn!("cache check: no config: {e:#}");
3514 return;
3515 }
3516 };
3517 match clean::prune_cache_if_over_limit(&cfg, home) {
3518 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3519 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3520 pruned.files,
3521 pruned.freed
3522 ),
3523 Ok(_) => {}
3524 Err(e) => {
3525 tracing::warn!("housekeep: prune cache: {e:#}");
3526 notices::raise_in(
3527 home,
3528 Notice::warn(
3529 "housekeep:cache",
3530 "Pruning the shared build cache failed; disk usage may keep growing.",
3531 ),
3532 );
3533 }
3534 }
3535}
3536
3537fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3541 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3542}
3543
3544async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3563 let cfg = match prepare(repo, opts) {
3564 Ok(cfg) => cfg,
3565 Err(e) => {
3566 tracing::warn!("housekeep: no config: {e:#}");
3567 return;
3568 }
3569 };
3570 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3579 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3580 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3585 let mut extra = Vec::new();
3586 if out.unreadable > 0 {
3587 extra.push(format!("{} unreadable", out.unreadable));
3588 }
3589 if out.orphaned_worktrees > 0 {
3590 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3591 }
3592 let detail = if extra.is_empty() {
3593 String::new()
3594 } else {
3595 format!(" ({})", extra.join(", "))
3596 };
3597 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3598 }
3599 if out.external_merges_recorded > 0 {
3600 tracing::info!(
3601 "housekeep: recorded {} run(s) as merged externally",
3602 out.external_merges_recorded
3603 );
3604 }
3605 if out.stale_pr_states_repaired > 0 {
3606 tracing::info!(
3607 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3608 out.stale_pr_states_repaired
3609 );
3610 }
3611 if out.cache_files > 0 {
3612 tracing::info!(
3613 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3614 out.cache_files,
3615 out.cache_freed
3616 );
3617 }
3618 if out.questions_abandoned > 0 {
3619 tracing::info!(
3620 "housekeep: abandoned {} question(s) left open by a finished run",
3621 out.questions_abandoned
3622 );
3623 }
3624}
3625
3626async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3635 let questions = Questions::at(home.join("questions"));
3636 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3637 if report.is_empty() {
3638 return;
3639 }
3640 if !report.quarantined.is_empty() {
3641 tracing::info!(
3642 "triage: held {} blocked task(s) whose blocked-on task or \
3643 question no longer exists: {}",
3644 report.quarantined.len(),
3645 report.quarantined.join(", ")
3646 );
3647 }
3648 if !report.resumed.is_empty() {
3649 tracing::info!(
3650 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3651 report.resumed.len(),
3652 report.resumed.join(", ")
3653 );
3654 }
3655 if !report.asked.is_empty() {
3656 tracing::info!(
3657 "triage: asked about {} held task(s): {}",
3658 report.asked.len(),
3659 report.asked.join(", ")
3660 );
3661 }
3662 if !report.answered.is_empty() {
3663 tracing::info!(
3664 "triage: applied {} operator answer(s): {}",
3665 report.answered.len(),
3666 report.answered.join(", ")
3667 );
3668 }
3669}
3670
3671fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3678 disk_gate_with(repo, config, crate::disk::free_bytes)
3679}
3680
3681fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3685 repo: &Path,
3686 config: &Config,
3687 free_bytes: F,
3688) -> Option<String> {
3689 let min = config.disk.min_free_bytes;
3690 if min == 0 {
3691 return None;
3692 }
3693 match free_bytes(repo) {
3694 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3695 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3696 }
3697}
3698
3699const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3706
3707const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3711
3712fn quota_wait(
3721 reset_at: Option<Timestamp>,
3722 now: Timestamp,
3723 fallback: Duration,
3724 cap: Duration,
3725) -> Duration {
3726 match reset_at {
3727 Some(at) if at > now => {
3728 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3729 Duration::from_secs(secs).min(cap)
3730 }
3731 _ => fallback,
3732 }
3733}
3734
3735fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3749 parse_reset_hint_zoned(text, now)
3750 .or_else(|| parse_reset_hint_dated(text))
3751 .or_else(|| parse_reset_hint_relative(text, recorded))
3752}
3753
3754fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3758 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3759 let mut rest = rest.trim();
3760 if rest.is_empty() {
3761 return None;
3762 }
3763 let mut total: i64 = 0;
3764 let mut matched = false;
3765 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3766 if let Some((digits, tail)) = rest.split_once(unit)
3767 && !digits.is_empty()
3768 && digits.bytes().all(|b| b.is_ascii_digit())
3769 {
3770 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3771 rest = tail;
3772 matched = true;
3773 }
3774 }
3775 if !rest.is_empty() || !matched {
3776 return None;
3777 }
3778 recorded
3779 .checked_add(jiff::SignedDuration::from_secs(total))
3780 .ok()
3781}
3782
3783fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3787 let clock = clock.trim().to_lowercase();
3788 let (digits, pm) = clock
3789 .strip_suffix("am")
3790 .map(|d| (d, false))
3791 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3792 let (h, m) = digits.trim().split_once(':')?;
3793 let mut hour: i8 = h.trim().parse().ok()?;
3794 let minute: i8 = m.trim().parse().ok()?;
3795 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3796 return None;
3797 }
3798 if pm && hour != 12 {
3799 hour += 12;
3800 } else if !pm && hour == 12 {
3801 hour = 0;
3802 }
3803 Some((hour, minute))
3804}
3805
3806fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3811 let open = text.find('(')?;
3812 let close = text.rfind(')')?;
3813 if close <= open {
3814 return None;
3815 }
3816 let zone = text[open + 1..close].trim();
3817 let (hour, minute) = parse_12h_clock(&text[..open])?;
3818 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3819 let candidate = now
3820 .to_zoned(tz)
3821 .with()
3822 .hour(hour)
3823 .minute(minute)
3824 .second(0)
3825 .millisecond(0)
3826 .microsecond(0)
3827 .nanosecond(0)
3828 .build()
3829 .ok()?;
3830 let mut at = candidate.timestamp();
3831 if at <= now {
3832 at += jiff::SignedDuration::from_hours(24);
3833 }
3834 Some(at)
3835}
3836
3837fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3846 let words: Vec<&str> = text.split_whitespace().collect();
3847 if words.len() < 5 {
3848 return None;
3849 }
3850 (0..=words.len() - 5)
3851 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3852}
3853
3854fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3860 if trailing.is_some_and(|next| next.starts_with('(')) {
3861 return None;
3862 }
3863 let month = month_number(window[0])?;
3864 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3865 let day_digits = ["st", "nd", "rd", "th"]
3866 .iter()
3867 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3868 let day: i8 = day_digits.parse().ok()?;
3869 let year_token = window[2];
3870 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3871 return None;
3872 }
3873 let year: i16 = year_token.parse().ok()?;
3874 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3878 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3879 let date = jiff::civil::Date::new(year, month, day).ok()?;
3880 let candidate = date
3881 .at(hour, minute, 0, 0)
3882 .to_zoned(jiff::tz::TimeZone::UTC)
3883 .ok()?;
3884 Some(candidate.timestamp())
3885}
3886
3887fn month_number(name: &str) -> Option<i8> {
3890 const NAMES: [&str; 12] = [
3891 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3892 ];
3893 let lower = name.to_lowercase();
3894 NAMES
3895 .iter()
3896 .position(|n| *n == lower.as_str())
3897 .map(|i| i as i8 + 1)
3898}
3899
3900fn exhausted_review_budget(state: &RunState) -> bool {
3912 state.status == RunStatus::Blocked
3915 && !state.pr_publication_pending
3916 && state.reviews.len() >= state.config.graph.review_rounds
3917}
3918
3919fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3956 unfinished_run_with(runs, short, RunState::load)
3957}
3958
3959fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3962where
3963 F: FnOnce(&str) -> Result<RunState>,
3964{
3965 let id = runs.last()?;
3966 match load(id) {
3967 Ok(s)
3972 if s.status.resumable()
3973 && !s.released()
3974 && !exhausted_review_budget(&s)
3975 && s.liveness(false) != crate::run::Liveness::Live =>
3976 {
3977 Some(id.clone())
3978 }
3979 Ok(_) => None,
3980 Err(e) => {
3981 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3982 None
3983 }
3984 }
3985}
3986
3987fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3995where
3996 F: FnOnce(&str) -> Result<RunState>,
3997{
3998 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4000 || task.fresh_start
4001 || task.review_branch.is_some()
4002 {
4003 return false;
4004 }
4005 let Some(id) = task.runs.last() else {
4006 return false;
4007 };
4008 load(id).is_ok_and(|s| {
4009 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4010 })
4011}
4012
4013#[derive(Debug, Clone, PartialEq, Eq)]
4016enum Starter {
4017 Review(String),
4020 Resume(String),
4022 Start,
4024}
4025
4026fn selected_starter(
4028 selected: &crate::pr_recovery::Selection,
4029 previous: Option<&RunState>,
4030 unfinished: Option<&str>,
4031) -> Starter {
4032 if let Some(id) = unfinished
4033 && previous.is_some_and(|r| {
4034 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4035 })
4036 {
4037 Starter::Resume(id.to_owned())
4038 } else {
4039 Starter::Review(selected.branch.clone())
4040 }
4041}
4042
4043fn take_divergence_answer(
4047 branch: &str,
4048 remote: &str,
4049 task: &mut Task,
4050) -> Option<crate::reconcile::Choice> {
4051 let summary = crate::reconcile::summary_for(branch, remote);
4052 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4053 (a.question == summary)
4054 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4055 .flatten()
4056 .map(|c| (i, c))
4057 })?;
4058 task.answers.remove(idx);
4059 Some(choice)
4060}
4061
4062fn choose_starter(
4074 review_branch: Option<&str>,
4075 branch_exists: bool,
4076 unfinished: Option<&str>,
4077) -> Starter {
4078 match review_branch {
4079 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4080 Some(_) => Starter::Start,
4081 None => match unfinished {
4082 Some(id) => Starter::Resume(id.to_owned()),
4083 None => Starter::Start,
4084 },
4085 }
4086}
4087
4088fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4090 let branch = task.review_branch.take();
4091 let instruction = task.review_instruction.take();
4092 branch.filter(|branch| match &instruction {
4093 Some(authored) => *authored == task.instruction,
4094 None => previous.map_or_else(
4097 || task.review_of.as_ref() == Some(branch),
4098 |run| compatible_run_instruction(run, task),
4099 ),
4100 })
4101}
4102
4103fn may_resume_run(run: &RunState, task: &Task) -> bool {
4106 task.resume_override
4107 .as_ref()
4108 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
4109 || compatible_run_instruction(run, task)
4110}
4111
4112pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
4114 if let Some(authored) = &run.task_instruction {
4115 return compatible_instruction(authored, task);
4116 }
4117 if compatible_instruction(&run.instruction, task) {
4118 return true;
4119 }
4120 if run.reviewed_commits.is_some() {
4123 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
4124 return strip_answers_block(authored, task).trim() == task.instruction.trim();
4125 }
4126 if let Some(branch) = &task.review_of {
4127 let canonical = format!(
4128 "Review the branch `{branch}` (review-only: no implementation, no judging)."
4129 );
4130 let generated = format!(
4131 "Review the work already on branch `{branch}`. There is no task statement: what the change claims to do is whatever its commits say.\n\n"
4132 );
4133 return task.instruction == canonical && run.instruction.starts_with(&generated);
4134 }
4135 }
4136 false
4137}
4138
4139pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
4141 strip_answers_block(old, task) == task.instruction
4142}
4143
4144fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4147 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4148 return fallback.to_path_buf();
4149 }
4150 task.repo.clone()
4151}
4152
4153const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4157
4158fn answers_block(task: &Task, count: usize) -> String {
4160 let mut s = ANSWERS_HEADER.to_owned();
4161 for a in &task.answers[..count] {
4162 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4163 }
4164 s
4165}
4166
4167fn resumption_block(r: &crate::queue::Resumption) -> String {
4170 format!(
4171 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
4172 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
4173 r.generation, r.at, r.instruction, r.answers_through,
4174 )
4175}
4176
4177fn append_answers(base: &str, task: &Task) -> String {
4179 let mut s = base.to_owned();
4180 if !task.answers.is_empty() {
4181 s.push_str(&answers_block(task, task.answers.len()));
4182 }
4183 if let Some(r) = &task.resumption {
4184 s.push_str(&resumption_block(r));
4185 }
4186 s
4187}
4188
4189fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4193 let mut instruction = instruction;
4194 for approval in task
4195 .resumption
4196 .iter()
4197 .chain(task.resumption_history.iter().rev())
4198 {
4199 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
4200 instruction = base;
4201 break;
4202 }
4203 }
4204 for count in (1..=task.answers.len()).rev() {
4205 let block = answers_block(task, count);
4206 if let Some(base) = instruction.strip_suffix(&block) {
4207 return base;
4208 }
4209 }
4210 instruction
4211}
4212
4213fn instruction_for(task: &Task) -> String {
4221 append_answers(&task.instruction, task)
4222}
4223
4224fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4236 append_answers(strip_answers_block(old_instruction, task), task)
4237}
4238
4239fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
4241 let paths = queue.attachment_paths(task);
4242 for (name, path) in task.attachments.iter().zip(&paths) {
4243 if !path.is_file() {
4244 bail!(
4245 "attachment `{name}` is recorded on the task but {} is missing",
4246 path.display()
4247 );
4248 }
4249 }
4250 Ok(paths)
4251}
4252
4253fn prepare_instruction(
4264 starter: &Starter,
4265 old_instruction: Option<&str>,
4266 task: &Task,
4267) -> Option<String> {
4268 match starter {
4269 Starter::Start => Some(instruction_for(task)),
4270 Starter::Resume(_) => Some(resumed_instruction(
4271 old_instruction.expect("a resumed run always has a prior instruction"),
4272 task,
4273 )),
4274 Starter::Review(_) => None,
4275 }
4276}
4277
4278fn record(queue: &Queue, task: &mut Task) {
4282 if let Err(e) = queue.put(task) {
4283 tracing::error!("could not record task {}: {e:#}", task.short());
4284 let notice = Notice::error(
4285 "loop:record",
4286 "The loop could not save a task's state; check the disk.",
4287 )
4288 .link(Link::Task {
4289 id: task.id.clone(),
4290 });
4291 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4293 Some(home) => notices::raise_in(home, notice),
4294 None => notices::raise(notice),
4295 }
4296 }
4297}
4298
4299fn runnable(queue: &Queue) -> Vec<Task> {
4305 let mut tasks: Vec<Task> = queue
4306 .list()
4307 .into_iter()
4308 .filter(|t| t.status.runnable())
4309 .collect();
4310 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4311 tasks
4312}
4313
4314fn describe(state: &RunState) -> String {
4328 let p = phrases(&state.config.graph.language);
4329 let mut detail = if state.status == RunStatus::Stalled {
4330 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4331 seats.sort_unstable();
4332 seats.dedup();
4333 if seats.is_empty() {
4334 p.quorum_lost.to_owned()
4335 } else {
4336 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4337 }
4338 } else {
4339 format!("{}{}", p.run_ended, state.status.display_label())
4340 };
4341 if let Some(last) = state.events.last() {
4342 let unanswered = state
4346 .reviews
4347 .last()
4348 .filter(|r| {
4349 state.status == RunStatus::Blocked
4350 && last.node == "review"
4351 && r.incomplete()
4352 && r.blocking == 0
4353 && r.round == state.config.graph.review_rounds
4354 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4355 })
4356 .map(|r| (r.expected - r.answered, r.round));
4357 match unanswered {
4358 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4359 detail.push_str(&format!(
4360 " ({}: {})",
4361 last.node,
4362 (p.reviewers_never_answered)(missing, rounds)
4363 ));
4364 }
4365 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4366 }
4367 }
4368 detail.push_str(&format!(" [run {}]", state.id));
4369 detail
4370}
4371
4372const DIAGNOSTIC_MAX: usize = 4_000;
4378
4379const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4384
4385fn diagnostic(state: &RunState) -> Option<String> {
4399 let mut parts: Vec<String> = Vec::new();
4400
4401 for o in state.gate.iter().filter(|o| !o.ok()) {
4403 parts.push(format!(
4404 "gate `{}` failed ({:?}):\n{}",
4405 o.command,
4406 o.code,
4407 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4408 ));
4409 }
4410
4411 if let Some(last) = state
4414 .events
4415 .iter()
4416 .rev()
4417 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4418 {
4419 parts.push(last.message.clone());
4420 }
4421
4422 if state.viable().is_empty() {
4429 for c in &state.candidates {
4430 if let Some(evidence) = &c.verified_noop {
4431 parts.push(format!(
4432 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4433 c.label
4434 ));
4435 } else if !c.summary.trim().is_empty() {
4436 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4437 } else if let Some(why) = &c.failed {
4438 parts.push(format!("candidate {}: {why}", c.label));
4439 }
4440 }
4441 }
4442
4443 if parts.is_empty() {
4444 return None;
4445 }
4446 Some(crate::run::tail(
4451 &parts.join("\n\n"),
4452 DIAGNOSTIC_MAX.saturating_sub(100),
4453 ))
4454}
4455
4456fn label(status: RunStatus) -> &'static str {
4464 status.as_str()
4465}
4466
4467pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4469 match mode {
4470 "none" => Ok(MergeMode::None),
4471 "local" => Ok(MergeMode::Local),
4472 "pr" => Ok(MergeMode::Pr),
4473 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4474 }
4475}
4476
4477fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4482 mutex
4483 .lock()
4484 .unwrap_or_else(std::sync::PoisonError::into_inner)
4485}
4486
4487#[cfg(test)]
4488mod tests {
4489 use super::*;
4490 use crate::queue::{Source, TaskStatus};
4491 use crate::run::{Candidate, CommandOutcome};
4492 use pretty_assertions::assert_eq;
4493
4494 fn task() -> Task {
4495 Task::new(
4496 "add retries".to_owned(),
4497 "add retries".to_owned(),
4498 PathBuf::from("/repo"),
4499 Source::Human,
4500 )
4501 }
4502
4503 #[test]
4504 fn selected_public_head_overrides_historical_resume_and_pin() {
4505 let mut t = task();
4506 let mut old = run_state(RunStatus::Blocked);
4507 let selection = crate::pr_recovery::Selection {
4508 url: "url".into(),
4509 branch: format!("magi/task-{}", t.id),
4510 head: "a".repeat(40),
4511 instruction: t.instruction.clone(),
4512 approved_at: Timestamp::now(),
4513 };
4514 t.resume_override = Some(crate::queue::OperatorResume {
4515 pinned_run: Some(old.id.clone()),
4516 question_id: "choice".into(),
4517 at: Timestamp::now(),
4518 conductor_rehold: None,
4519 forced: false,
4520 });
4521 assert_eq!(
4522 selected_starter(&selection, Some(&old), Some(&old.id)),
4523 Starter::Review(selection.branch.clone())
4524 );
4525 old.pr_recovery = Some(selection.clone());
4526 assert_eq!(
4527 selected_starter(&selection, Some(&old), Some(&old.id)),
4528 Starter::Review(selection.branch.clone())
4529 );
4530 old.reviewed_commits = Some(vec!["implementation".into()]);
4531 assert_eq!(
4532 selected_starter(&selection, Some(&old), Some(&old.id)),
4533 Starter::Resume(old.id.clone())
4534 );
4535 let mut changed = selection.clone();
4536 changed.head = "b".repeat(40);
4537 assert_eq!(
4538 selected_starter(&changed, Some(&old), Some(&old.id)),
4539 Starter::Review(changed.branch)
4540 );
4541 }
4542
4543 #[test]
4544 fn candidate_transplant_failure_is_one_actionable_hold() {
4545 let dir = tempfile::tempdir().unwrap();
4546 let q = Queue::at(dir.path().join("queue"));
4547 let mut t = task();
4548 let mut state = run_state(RunStatus::Blocked);
4549 state.event("prep", "cannot apply referenced commit: conflict");
4550 state.prep_failure = Some("conflict".into());
4551 t.start(state.id.clone());
4552 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
4553 assert_eq!(t.attempts, 1);
4554 assert_eq!(t.status, TaskStatus::Held);
4555 assert!(t.operator_held());
4556 assert!(!t.status.runnable());
4557 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
4558 }
4559
4560 #[test]
4561 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
4562 for source in ["cli", "web"] {
4563 let mut t = task();
4564 let mut run = run_state(RunStatus::Blocked);
4565 run.instruction = "Run A original criteria".into();
4566 run.task_instruction = Some(run.instruction.clone());
4567 t.start(run.id.clone());
4568 t.release_operator("choice", Some("resume-question"));
4569 t.resume_override = Some(crate::queue::OperatorResume {
4570 question_id: "resume-question".into(),
4571 at: Timestamp::now(),
4572 conductor_rehold: None,
4573 forced: true,
4574 pinned_run: Some(run.id.clone()),
4575 });
4576 t.hold_machine(Some("not enough free space to start a run".into()));
4577 let mut unchanged = t.clone();
4578 unchanged
4579 .edit("title changed".into(), unchanged.instruction.clone())
4580 .unwrap();
4581 unchanged.release_operator(source, None);
4582 assert_eq!(
4583 unchanged
4584 .resume_override
4585 .as_ref()
4586 .unwrap()
4587 .pinned_run
4588 .as_deref(),
4589 Some(run.id.as_str())
4590 );
4591 assert!(!compatible_run_instruction(&run, &unchanged));
4592 assert!(may_resume_run(&run, &unchanged));
4593
4594 t.edit(
4595 "approved recovery".into(),
4596 "Reuse measured PR head B; fix Clippy; review".into(),
4597 )
4598 .unwrap();
4599 assert!(t.resume_override.is_none());
4600 t.release_operator(source, None);
4601 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
4602 assert!(reloaded.resume_override.is_none());
4603 assert!(!may_resume_run(&run, &reloaded));
4604 let unfinished =
4605 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
4606 .filter(|_| may_resume_run(&run, &reloaded));
4607 assert_eq!(
4608 choose_starter(None, false, unfinished.as_deref()),
4609 Starter::Start
4610 );
4611 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
4612 assert_eq!(
4613 reloaded.resumption_history[0].question_id.as_deref(),
4614 Some("resume-question")
4615 );
4616
4617 unchanged.instruction = "Reuse measured PR head B".into();
4620 unchanged.hold_machine(Some("disk hold".into()));
4621 unchanged.release_operator(source, None);
4622 assert!(unchanged.resume_override.is_none());
4623 assert!(!may_resume_run(&run, &unchanged));
4624 }
4625 }
4626
4627 #[test]
4628 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
4629 let mut t = task();
4630 let mut run = run_state(RunStatus::Blocked);
4631 t.review_of = Some("approved-head".into());
4632 t.instruction =
4633 "Review the branch `approved-head` (review-only: no implementation, no judging)."
4634 .into();
4635 run.instruction = "Review the work already on branch `approved-head`. There is no task statement: what the change claims to do is whatever its commits say.\n\nCommit log".into();
4636 run.reviewed_commits = Some(vec!["Commit log".into()]);
4637 t.start(run.id.clone());
4638 t.hold_machine(Some("interrupted review".into()));
4639 t.release_operator("cli", None);
4640 assert!(
4641 compatible_run_instruction(&run, &t),
4642 "legacy explicit review remains resumable"
4643 );
4644 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
4645 .filter(|_| compatible_run_instruction(&run, &t));
4646 assert_eq!(
4647 choose_starter(None, false, unfinished.as_deref()),
4648 Starter::Resume(run.id.clone())
4649 );
4650 run.task_instruction = Some(t.instruction.clone());
4651 assert!(compatible_run_instruction(&run, &t));
4652 let reloaded: RunState =
4653 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
4654 assert!(compatible_run_instruction(&reloaded, &t));
4655 t.edit(
4656 "new approved head".into(),
4657 "Reuse measured PR head B".into(),
4658 )
4659 .unwrap();
4660 assert!(!compatible_run_instruction(&run, &t));
4661
4662 t.review_of = None;
4664 t.instruction = "Fix Clippy on approved head".into();
4665 run.task_instruction = None;
4666 run.instruction = format!(
4667 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
4668 t.instruction
4669 );
4670 assert!(compatible_run_instruction(&run, &t));
4671 t.instruction.push('\n');
4672 assert!(
4673 compatible_run_instruction(&run, &t),
4674 "legacy generated review trimmed the original criteria"
4675 );
4676 t.hold_for_handover(Some("approved-head".into()), "refused".into());
4677 let mut unchanged = t.clone();
4678 assert_eq!(
4679 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
4680 Some("approved-head")
4681 );
4682 t.edit("new plan".into(), "Reuse measured PR head B".into())
4683 .unwrap();
4684 assert!(take_review_branch(&mut t, Some(&run)).is_none());
4685 assert!(!compatible_run_instruction(&run, &t));
4686 t.review_branch = Some("approved-head".into());
4687 t.review_instruction = None;
4688 assert!(
4689 take_review_branch(&mut t, Some(&run)).is_none(),
4690 "legacy retained candidate cannot replace a revised approved head"
4691 );
4692 }
4693
4694 #[test]
4695 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
4696 crate::run::pin_test_home();
4697 let dir = tempfile::tempdir().unwrap();
4698 let queue = Queue::at(dir.path().join("queue"));
4699 for resume in [true, false] {
4700 let state = run_state(RunStatus::Blocked);
4701 let mut t = task();
4702 t.start(state.id.clone());
4703 let action = if resume {
4704 ask::ChoiceAction::Resume {
4705 run: state.id.clone(),
4706 }
4707 } else {
4708 ask::ChoiceAction::Requeue
4709 };
4710 let mut q = action_question(&state.id, action);
4711 q.status = ask::QuestionStatus::Open;
4712 q.answer = None;
4713 q.answered_at = None;
4714 t.fail("run stopped with a question", 3);
4715 hold_if_runnable(&queue, &mut t);
4716 assert!(t.operator_decided_at.is_none());
4717 assert!(t.operator_held());
4718 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
4719 let expected = if resume {
4720 ActionDecision::Resume(state.id.clone())
4721 } else {
4722 ActionDecision::Requeue
4723 };
4724 assert_eq!(
4725 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4726 expected
4727 );
4728 t.hold_manual(Some("later explicit hold".into()));
4729 assert_eq!(
4730 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4731 ActionDecision::Stale
4732 );
4733 }
4734 }
4735
4736 #[test]
4737 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
4738 let mut t = task();
4739 t.answers.push(crate::queue::AnsweredQuestion {
4740 question: "Inspect the remote?".into(),
4741 answer: "Inspect then wait".into(),
4742 });
4743 let old = instruction_for(&t);
4744 assert!(compatible_instruction(&old, &t));
4745 t.instruction = "Reuse approved PR head and review".into();
4746 t.release_operator("cli", None);
4747 assert!(!compatible_instruction(&old, &t));
4748 let approved = instruction_for(&t);
4749 assert!(approved.contains("waiting premises are superseded"));
4750 assert!(compatible_instruction(&approved, &t));
4751 assert_eq!(resumed_instruction(&approved, &t), approved);
4752 t.release_operator("web", None);
4753 assert!(compatible_instruction(&approved, &t));
4754 assert_eq!(t.resumption_history.len(), 1);
4755 t.start("run".into());
4756 assert!(instruction_for(&t).contains("Explicit operator resumption"));
4757 }
4758
4759 #[test]
4763 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
4764 let mut state = RunState::new(
4765 PathBuf::from("/repo"),
4766 "main".to_owned(),
4767 "abc1234".to_owned(),
4768 "task".to_owned(),
4769 Config::default(),
4770 );
4771 state.status = RunStatus::Blocked;
4772 state.resource_block = Some(crate::run::ResourceBlock {
4773 node: "graft".to_owned(),
4774 kind: "shared build cache".to_owned(),
4775 detail: "timed out".to_owned(),
4776 at: jiff::Timestamp::now(),
4777 });
4778 let mut t = task();
4779 t.start("20260902-000000-aaaa".to_owned());
4780 assert_eq!(t.attempts, 1);
4781 let verdict = Verdict {
4782 status: RunStatus::Blocked,
4783 left_pr: false,
4784 quota_hit: false,
4785 parked: false,
4786 no_viable_candidates: false,
4787 };
4788 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
4789 assert_eq!(t.status, TaskStatus::Held);
4790 assert_eq!(t.attempts, 0, "the attempt is refunded");
4791 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
4792 assert!(
4793 !t.operator_held(),
4794 "a machine hold, released without a human"
4795 );
4796
4797 let mut p = task();
4799 p.start("20260902-000000-bbbb".to_owned());
4800 settle_and_diagnose(
4801 &mut p,
4802 Verdict {
4803 parked: true,
4804 ..verdict
4805 },
4806 "parked",
4807 2,
4808 &state,
4809 );
4810 assert_eq!(p.status, TaskStatus::Parked);
4811 }
4812
4813 #[test]
4814 fn record_failure_notice_links_the_task() {
4815 let dir = tempfile::tempdir().unwrap();
4816 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
4819 let queue = Queue::at(dir.path().join("queue"));
4820 let mut t = interrupt_task("rec-fail-1");
4821 record(&queue, &mut t);
4822
4823 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
4824 assert_eq!(found.len(), 1);
4825 assert_eq!(found[0].key, "loop:record");
4826 assert_eq!(
4827 found[0].link,
4828 Some(Link::Task {
4829 id: "rec-fail-1".to_owned()
4830 })
4831 );
4832 }
4833
4834 fn interrupt_task(id: &str) -> Task {
4837 let mut t = task();
4838 t.id = id.to_owned();
4839 t.interrupt = true;
4840 t
4841 }
4842
4843 fn task_with_id(id: &str) -> Task {
4845 let mut t = task();
4846 t.id = id.to_owned();
4847 t
4848 }
4849
4850 fn urgent_task(id: &str) -> Task {
4852 let mut t = task();
4853 t.id = id.to_owned();
4854 t.urgent = true;
4855 t
4856 }
4857
4858 #[test]
4859 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
4860 let dir = tempfile::tempdir().unwrap();
4861 let queue = Queue::at(dir.path().join("queue"));
4862 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
4863 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
4864 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
4865 let mut first = task();
4866 queue.put(&mut first).unwrap();
4867 let stale_plain = queue.get(&first.id).unwrap();
4868 first.set_urgent(true).unwrap();
4869 queue.put(&mut first).unwrap();
4870 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
4871 let mut second = urgent_task("second");
4872 queue.put(&mut second).unwrap();
4873 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
4874 drop(queue.claim(&second.id).unwrap());
4875 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
4876 drop(dispatched);
4877 let stale_urgent = queue.get(&first.id).unwrap();
4878 first.set_urgent(false).unwrap();
4879 queue.put(&mut first).unwrap();
4880 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
4881 assert_eq!(urgent.available_permits(), 1);
4882 drop(queue.claim(&first.id).unwrap());
4883 drop(occupied);
4884 }
4885
4886 #[test]
4887 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
4888 let dir = tempfile::tempdir().unwrap();
4889 let queue = Queue::at(dir.path().join("queue"));
4890 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
4891 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
4892 let mut t = task();
4893 queue.put(&mut t).unwrap();
4894 for enabled in [true, false] {
4895 let stale = queue.get(&t.id).unwrap();
4896 t.set_urgent(enabled).unwrap();
4897 queue.put(&mut t).unwrap();
4898 assert_ne!(stale.urgent, enabled);
4899 let DispatchClaim {
4900 task: fresh,
4901 claim,
4902 permit,
4903 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
4904 assert_eq!(fresh.urgent, enabled);
4905 assert_eq!(ordinary.available_permits(), usize::from(enabled));
4906 assert_eq!(urgent.available_permits(), usize::from(!enabled));
4907 assert!(queue.claim(&t.id).is_err());
4908 assert_eq!(fresh.attempts, stale.attempts);
4909 drop((claim, permit));
4910 assert_eq!(ordinary.available_permits(), 1);
4911 assert_eq!(urgent.available_permits(), 1);
4912 }
4913 t.set_urgent(true).unwrap();
4914 queue.put(&mut t).unwrap();
4915 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
4916 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4917 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
4918 drop(queue.claim(&t.id).unwrap());
4919 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
4920 drop(occupied);
4921 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
4922 drop(queue.claim(&t.id).unwrap());
4923 let held = queue.claim(&t.id).unwrap();
4924 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4925 drop(held);
4926 t.status = TaskStatus::Held;
4927 queue.put(&mut t).unwrap();
4928 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4929 drop(queue.claim(&t.id).unwrap());
4930 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
4931 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4932 drop(queue.claim(&t.id).unwrap());
4933 assert_eq!(urgent.available_permits(), 1);
4934 }
4935
4936 #[test]
4941 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4942 assert_eq!(permit_kind(true, false), PermitKind::None);
4943 assert_eq!(permit_kind(true, true), PermitKind::None);
4944 }
4945
4946 #[test]
4951 fn permit_kind_separates_urgent_from_ordinary() {
4952 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4953 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4954 }
4955
4956 #[test]
4963 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4964 let cfg = Config::default();
4965 let repo = Path::new("/any/repo/path");
4966
4967 let reason =
4968 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4969 assert!(reason.contains("1024"), "{reason}");
4970 assert!(
4971 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4972 "{reason}"
4973 );
4974
4975 assert_eq!(
4976 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4977 None,
4978 "exactly at the floor is open"
4979 );
4980 assert_eq!(
4981 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4982 None,
4983 "comfortably above the floor is open"
4984 );
4985 }
4986
4987 #[test]
4988 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4989 let mut cfg = Config::default();
4990 cfg.disk.min_free_bytes = 0;
4991 let repo = Path::new("/any/repo/path");
4992 assert_eq!(
4993 disk_gate_with(repo, &cfg, |_| Ok(0)),
4994 None,
4995 "a zero floor never measures at all"
4996 );
4997 }
4998
4999 #[test]
5000 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5001 let cfg = Config::default();
5002 let repo = Path::new("/any/repo/path");
5003 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5004 .expect("a measurement failure must close the gate, not open it");
5005 assert!(reason.contains("could not measure"), "{reason}");
5006 }
5007
5008 #[test]
5009 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5010 let ordinary = task();
5011 let next = advance_interrupt(
5012 Interrupt::Idle,
5013 std::slice::from_ref(&ordinary.id),
5014 std::slice::from_ref(&ordinary),
5015 );
5016 assert_eq!(next, Interrupt::Idle);
5017 }
5018
5019 #[test]
5020 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
5021 let marked = interrupt_task("marked");
5024 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5025 assert_eq!(next, Interrupt::Idle);
5026 }
5027
5028 #[test]
5029 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
5030 let marked = interrupt_task("marked");
5031 let next = advance_interrupt(
5032 Interrupt::Idle,
5033 &["running".to_owned()],
5034 std::slice::from_ref(&marked),
5035 );
5036 assert_eq!(
5037 next,
5038 Interrupt::Parking {
5039 parked: vec!["running".to_owned()],
5040 interrupt_task: "marked".to_owned(),
5041 }
5042 );
5043 }
5044
5045 #[test]
5054 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
5055 let marked = interrupt_task("marked");
5056
5057 let two = advance_interrupt(
5058 Interrupt::Idle,
5059 &["a".to_owned(), "b".to_owned()],
5060 std::slice::from_ref(&marked),
5061 );
5062 assert_eq!(two, Interrupt::Idle);
5063
5064 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5065 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
5066 }
5067
5068 #[test]
5069 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
5070 let state = Interrupt::Parking {
5071 parked: vec!["running".to_owned()],
5072 interrupt_task: "marked".to_owned(),
5073 };
5074 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
5076 assert_eq!(still_going, state);
5077
5078 let stopped_but_not_yet_dispatched =
5082 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
5083 assert_eq!(stopped_but_not_yet_dispatched, state);
5084
5085 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
5087 assert_eq!(
5088 dispatched,
5089 Interrupt::Running {
5090 parked: vec!["running".to_owned()],
5091 interrupt_task: "marked".to_owned(),
5092 }
5093 );
5094 }
5095
5096 #[test]
5097 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
5098 let state = Interrupt::Running {
5099 parked: vec!["running".to_owned()],
5100 interrupt_task: "marked".to_owned(),
5101 };
5102 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
5103 assert_eq!(still_running, state);
5104
5105 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
5112 assert_eq!(
5113 ended,
5114 Interrupt::Resuming {
5115 parked: vec!["running".to_owned()]
5116 }
5117 );
5118 }
5119
5120 #[test]
5121 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
5122 let state = Interrupt::Resuming {
5123 parked: vec!["running".to_owned()],
5124 };
5125 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
5126 assert_eq!(still_waiting, state);
5127
5128 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
5129 assert_eq!(dispatched, Interrupt::Idle);
5130 }
5131
5132 #[test]
5138 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
5139 {
5140 let state = Interrupt::Parking {
5141 parked: vec!["running".to_owned()],
5142 interrupt_task: "marked".to_owned(),
5143 };
5144 let next = advance_interrupt(state, &[], &[]);
5147 assert_eq!(
5148 next,
5149 Interrupt::Resuming {
5150 parked: vec!["running".to_owned()]
5151 },
5152 "abandoning the interrupt must not abandon the resume it owes"
5153 );
5154 }
5155
5156 #[test]
5159 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
5160 let state = Interrupt::Resuming {
5161 parked: vec!["running".to_owned()],
5162 };
5163 let next = advance_interrupt(state, &[], &[]);
5164 assert_eq!(
5165 next,
5166 Interrupt::Idle,
5167 "nothing is left to wait for; the loop must not stay wedged"
5168 );
5169 }
5170
5171 #[test]
5172 fn disabled_by_config_the_sequence_can_never_leave_idle() {
5173 let marked = interrupt_task("marked");
5174 let next = advance_interrupt_tick(
5175 false,
5176 Interrupt::Idle,
5177 &["running".to_owned()],
5178 std::slice::from_ref(&marked),
5179 );
5180 assert_eq!(
5181 next,
5182 Interrupt::Idle,
5183 "an unmarked, unconfigured daemon must behave exactly as before"
5184 );
5185 }
5186
5187 #[test]
5188 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
5189 let state = Interrupt::Parking {
5190 parked: vec!["running".to_owned()],
5191 interrupt_task: "marked".to_owned(),
5192 };
5193 let candidates = vec![interrupt_task("marked"), task()];
5194 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5195 assert!(
5196 allowed.is_empty(),
5197 "nothing may dispatch - not even the interrupt task itself - \
5198 until the parked run has actually stopped"
5199 );
5200 }
5201
5202 #[test]
5216 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
5217 for state in [
5218 Interrupt::Parking {
5219 parked: vec!["running".to_owned()],
5220 interrupt_task: "marked".to_owned(),
5221 },
5222 Interrupt::Running {
5223 parked: vec!["running".to_owned()],
5224 interrupt_task: "marked".to_owned(),
5225 },
5226 Interrupt::Resuming {
5227 parked: vec!["running".to_owned()],
5228 },
5229 ] {
5230 let candidates = vec![
5231 interrupt_task("marked"),
5232 urgent_task("hot"),
5233 task_with_id("ordinary"),
5234 ];
5235 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5236 assert!(
5237 !allowed.iter().any(|t| t.id == "hot"),
5238 "an urgent candidate must wait out the same gate as anything \
5239 else while the run it would run alongside has not actually \
5240 left flight, for state {state:?}: {allowed:?}"
5241 );
5242 }
5243 }
5244
5245 #[test]
5251 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
5252 let state = Interrupt::Resuming {
5253 parked: vec!["hot".to_owned()],
5254 };
5255 let candidates = vec![urgent_task("hot"), task()];
5256 let allowed = interrupt_gate(&state, &[], candidates);
5257 assert_eq!(
5258 allowed.iter().filter(|t| t.id == "hot").count(),
5259 1,
5260 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
5261 );
5262 }
5263
5264 #[test]
5265 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
5266 let state = Interrupt::Parking {
5267 parked: vec!["running".to_owned()],
5268 interrupt_task: "marked".to_owned(),
5269 };
5270 let other = task();
5271 let candidates = vec![interrupt_task("marked"), other.clone()];
5272 let allowed = interrupt_gate(&state, &[], candidates);
5273 assert_eq!(allowed.len(), 1);
5274 assert_eq!(allowed[0].id, "marked");
5275 }
5276
5277 #[test]
5278 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
5279 let state = Interrupt::Running {
5280 parked: vec!["running".to_owned()],
5281 interrupt_task: "marked".to_owned(),
5282 };
5283 let candidates = vec![task(), task()];
5284 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
5285 assert!(allowed.is_empty());
5286 }
5287
5288 #[test]
5295 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
5296 let state = Interrupt::Resuming {
5297 parked: vec!["a".to_owned(), "c".to_owned()],
5298 };
5299 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
5300 let allowed = interrupt_gate(&state, &[], candidates);
5301 assert_eq!(
5302 allowed.len(),
5303 1,
5304 "at most one candidate may be offered while resuming: {allowed:?}"
5305 );
5306 assert_eq!(allowed[0].id, "a");
5307 }
5308
5309 #[test]
5310 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
5311 let state = Interrupt::Resuming {
5312 parked: vec!["a".to_owned()],
5313 };
5314 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
5315 assert!(allowed.is_empty());
5316 }
5317
5318 #[test]
5324 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
5325 let running = task(); let marked = interrupt_task("marked");
5327
5328 let mut state = Interrupt::Idle;
5329 let in_flight = vec![running.id.clone()];
5331 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
5332 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
5333 assert!(gated.is_empty(), "still waiting on `running` to park");
5334
5335 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
5337 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
5338 assert_eq!(
5339 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5340 vec!["marked"],
5341 "only the interrupt task may be offered to the dispatcher now"
5342 );
5343
5344 state = advance_interrupt_tick(
5346 true,
5347 state,
5348 &["marked".to_owned()],
5349 std::slice::from_ref(&running),
5350 );
5351 let gated = interrupt_gate(
5352 &state,
5353 &["marked".to_owned()],
5354 vec![marked.clone(), running.clone()],
5355 );
5356 assert!(
5357 gated.is_empty(),
5358 "the parked run must not be offered back while the interrupt \
5359 task is still running"
5360 );
5361
5362 let other = task_with_id("other");
5366 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
5367 assert_eq!(
5368 state,
5369 Interrupt::Resuming {
5370 parked: vec![running.id.clone()]
5371 }
5372 );
5373 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
5374 assert_eq!(
5375 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5376 vec![running.id.as_str()],
5377 "exactly the parked run resumes - not the unrelated task, even \
5378 though it was offered first"
5379 );
5380
5381 state = advance_interrupt_tick(
5385 true,
5386 state,
5387 std::slice::from_ref(&running.id),
5388 std::slice::from_ref(&other),
5389 );
5390 assert_eq!(state, Interrupt::Idle);
5391 let gated = interrupt_gate(
5392 &state,
5393 std::slice::from_ref(&running.id),
5394 vec![other.clone()],
5395 );
5396 assert_eq!(
5397 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5398 vec![other.id.as_str()],
5399 "ordinary dispatch is unrestricted again"
5400 );
5401 }
5402
5403 #[test]
5404 fn every_run_status_settles_the_task_it_came_from() {
5405 let table = [
5407 (RunStatus::Merged, TaskStatus::Done, 1),
5408 (RunStatus::Ready, TaskStatus::Done, 1),
5409 (RunStatus::Stalled, TaskStatus::Failed, 0),
5410 (RunStatus::Blocked, TaskStatus::Failed, 1),
5411 (RunStatus::Failed, TaskStatus::Failed, 1),
5412 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
5413 (RunStatus::Prep, TaskStatus::Failed, 1),
5414 (RunStatus::Implementing, TaskStatus::Failed, 1),
5415 (RunStatus::Judging, TaskStatus::Failed, 1),
5416 (RunStatus::Deliberating, TaskStatus::Failed, 1),
5417 (RunStatus::Voting, TaskStatus::Failed, 1),
5418 (RunStatus::Reviewing, TaskStatus::Failed, 1),
5419 (RunStatus::Gating, TaskStatus::Failed, 1),
5420 ];
5421 for (run, want, attempts) in table {
5422 let mut t = task();
5423 t.start("20260902-000000-aaaa".to_owned());
5424 settle(
5425 &mut t,
5426 Verdict {
5427 status: run,
5428 left_pr: false,
5429 parked: false,
5430 quota_hit: matches!(run, RunStatus::Stalled),
5431 no_viable_candidates: false,
5432 },
5433 "why",
5434 2,
5435 );
5436 assert_eq!(t.status, want, "task status after {}", label(run));
5437 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
5438 }
5439 }
5440
5441 #[test]
5442 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
5443 let mut stalled = task();
5444 stalled.start("20260902-000000-aaaa".to_owned());
5445 settle(
5446 &mut stalled,
5447 Verdict {
5448 status: RunStatus::Stalled,
5449 left_pr: false,
5450 parked: false,
5451 quota_hit: true,
5452 no_viable_candidates: false,
5453 },
5454 "quota",
5455 1,
5456 );
5457 assert_eq!(stalled.attempts, 0);
5458 assert!(
5459 stalled.status.runnable(),
5460 "a machine problem must leave the task in line"
5461 );
5462
5463 let mut blocked = task();
5464 blocked.start("20260902-000000-aaaa".to_owned());
5465 settle(
5466 &mut blocked,
5467 Verdict {
5468 status: RunStatus::Blocked,
5469 left_pr: false,
5470 parked: false,
5471 quota_hit: false,
5472 no_viable_candidates: false,
5473 },
5474 "findings open",
5475 1,
5476 );
5477 assert_eq!(blocked.attempts, 1);
5478 assert_eq!(
5479 blocked.status,
5480 TaskStatus::Held,
5481 "the last attempt hands the task to a human"
5482 );
5483 }
5484
5485 #[test]
5486 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
5487 let mut delivered = task();
5490 delivered.start("20260903-080619-01c2".to_owned());
5491 settle(
5492 &mut delivered,
5493 Verdict {
5494 status: RunStatus::Blocked,
5495 left_pr: true,
5496 parked: false,
5497 quota_hit: false,
5498 no_viable_candidates: false,
5499 },
5500 "no check status",
5501 4,
5502 );
5503 assert_eq!(
5504 delivered.status,
5505 TaskStatus::Held,
5506 "a pull request waiting on CI or a person is not a retryable failure"
5507 );
5508 assert!(
5509 !delivered.status.runnable(),
5510 "the loop must not pick this task up again"
5511 );
5512 assert_eq!(
5513 delivered.last_error.as_deref(),
5514 Some("no check status"),
5515 "the operator needs to be told what the gate was waiting for"
5516 );
5517
5518 let mut empty_handed = task();
5521 empty_handed.start("20260903-080619-01c2".to_owned());
5522 settle(
5523 &mut empty_handed,
5524 Verdict {
5525 status: RunStatus::Blocked,
5526 left_pr: false,
5527 parked: false,
5528 quota_hit: false,
5529 no_viable_candidates: false,
5530 },
5531 "findings open",
5532 4,
5533 );
5534 assert_eq!(empty_handed.status, TaskStatus::Failed);
5535 assert!(empty_handed.status.runnable());
5536 }
5537
5538 #[test]
5539 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
5540 let mut noop = task();
5546 noop.start("20260912-131304-391f".to_owned());
5547 settle(
5548 &mut noop,
5549 Verdict {
5550 status: RunStatus::VerifiedNoop,
5551 left_pr: false,
5552 parked: false,
5553 quota_hit: false,
5554 no_viable_candidates: true,
5555 },
5556 "candidate A: already fixed by b32cfc4, on main",
5557 4,
5558 );
5559 assert_eq!(
5560 noop.status,
5561 TaskStatus::Held,
5562 "an unverified claim is a request for a human, not a failure"
5563 );
5564 assert!(
5565 !noop.status.runnable(),
5566 "the loop must not requeue this on the same unverified claim"
5567 );
5568 assert_eq!(noop.attempts, 1);
5573 }
5574
5575 #[test]
5576 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
5577 let mut parked = task();
5582 parked.start("20260903-183634-2d98".to_owned());
5583 settle(
5584 &mut parked,
5585 Verdict {
5586 status: RunStatus::Implementing,
5587 left_pr: false,
5588 quota_hit: false,
5589 parked: true,
5590 no_viable_candidates: false,
5591 },
5592 "parked after `implementing`",
5593 2,
5594 );
5595 assert_eq!(parked.attempts, 0, "a park is refunded");
5596 assert!(
5597 parked.status.runnable(),
5598 "and the task stays in line so the next loop resumes its run"
5599 );
5600 assert_eq!(parked.status, TaskStatus::Parked);
5601 assert_eq!(
5602 parked.park_reason.as_deref(),
5603 Some("parked after `implementing`"),
5604 "the card says where it stopped"
5605 );
5606 assert_eq!(parked.last_error, None, "nothing failed");
5607
5608 let mut broken = task();
5612 broken.start("20260903-183634-2d98".to_owned());
5613 settle(
5614 &mut broken,
5615 Verdict {
5616 status: RunStatus::Implementing,
5617 left_pr: false,
5618 quota_hit: false,
5619 parked: false,
5620 no_viable_candidates: false,
5621 },
5622 "returned mid-flight",
5623 2,
5624 );
5625 assert_eq!(broken.attempts, 1);
5626 }
5627
5628 #[test]
5629 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
5630 let mut flaky = task();
5635 flaky.start("20260903-123023-e633".to_owned());
5636 settle(
5637 &mut flaky,
5638 Verdict {
5639 status: RunStatus::Stalled,
5640 left_pr: false,
5641 parked: false,
5642 quota_hit: false,
5643 no_viable_candidates: false,
5644 },
5645 "verdict rests on 1 of 3 judges",
5646 2,
5647 );
5648 assert_eq!(
5649 flaky.attempts, 1,
5650 "flakiness spends an attempt, so `max_attempts` still bounds it"
5651 );
5652 assert!(flaky.status.runnable(), "and it is still worth retrying");
5653
5654 let mut limited = task();
5656 limited.start("20260903-123023-e633".to_owned());
5657 settle(
5658 &mut limited,
5659 Verdict {
5660 status: RunStatus::Stalled,
5661 left_pr: false,
5662 parked: false,
5663 quota_hit: true,
5664 no_viable_candidates: false,
5665 },
5666 "judge-2, judge-3 out of quota",
5667 2,
5668 );
5669 assert_eq!(limited.attempts, 0, "a quota window is refunded");
5670 assert!(limited.status.runnable());
5671
5672 let mut worn = task();
5675 for _ in 0..2 {
5676 worn.release();
5677 }
5678 worn.start("20260903-123023-e633".to_owned());
5679 worn.attempts = 2;
5680 settle(
5681 &mut worn,
5682 Verdict {
5683 status: RunStatus::Stalled,
5684 left_pr: false,
5685 parked: false,
5686 quota_hit: false,
5687 no_viable_candidates: false,
5688 },
5689 "no quorum again",
5690 2,
5691 );
5692 assert_eq!(worn.status, TaskStatus::Held);
5693 assert!(!worn.status.runnable());
5694 }
5695
5696 #[test]
5697 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5698 let mut wiped_out = task();
5705 wiped_out.start("20260907-025000-a1b2".to_owned());
5706 settle(
5707 &mut wiped_out,
5708 Verdict {
5709 status: RunStatus::Failed,
5710 left_pr: false,
5711 parked: false,
5712 quota_hit: true,
5713 no_viable_candidates: true,
5714 },
5715 "no candidate produced a change; nothing to judge",
5716 2,
5717 );
5718 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5719 assert!(
5720 wiped_out.status.runnable(),
5721 "a machine problem must leave the task in line"
5722 );
5723
5724 let mut partial_progress = task();
5730 partial_progress.start("20260907-025500-c3d4".to_owned());
5731 settle(
5732 &mut partial_progress,
5733 Verdict {
5734 status: RunStatus::Failed,
5735 left_pr: false,
5736 parked: false,
5737 quota_hit: true,
5738 no_viable_candidates: false,
5739 },
5740 "gate failed on the winning candidate",
5741 2,
5742 );
5743 assert_eq!(
5744 partial_progress.attempts, 1,
5745 "a candidate that actually produced a change spends the attempt \
5746 even though some other seat hit its quota"
5747 );
5748 assert!(partial_progress.status.runnable());
5749 }
5750
5751 #[test]
5752 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5753 let mut t = task();
5759 t.start("20260907-025000-a1b2".to_owned());
5760 let mut state = run_state(RunStatus::Failed);
5761 state.quota.push(QuotaLoss {
5762 seat: "cand-a".to_owned(),
5763 node: "implement".to_owned(),
5764 at: Timestamp::now(),
5765 reset: None,
5766 });
5767 assert!(
5768 state.viable().is_empty(),
5769 "no candidate was added, so nothing is viable"
5770 );
5771 reclaim(&mut t, Some(state), 2, "en");
5772 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5773 assert!(t.status.runnable());
5774 }
5775
5776 #[test]
5777 fn a_held_task_is_never_offered_to_the_loop() {
5778 let dir = tempfile::tempdir().unwrap();
5779 let queue = Queue::at(dir.path().to_path_buf());
5780 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5781 let mut t = task();
5782 t.id = format!("2026090{n}-000000-000{n}");
5783 t.priority = priority;
5784 queue.put(&mut t).unwrap();
5785 }
5786 let mut held = task();
5787 held.id = "20260909-000000-9999".to_owned();
5788 held.priority = 99;
5789 held.hold_machine(None);
5790 queue.put(&mut held).unwrap();
5791
5792 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5793 assert_eq!(order.len(), 3);
5794 assert!(!order.contains(&held.id));
5795 assert_eq!(
5796 order.first().cloned(),
5797 queue.next_runnable().map(|t| t.id),
5798 "the loop's first candidate is exactly what the queue offers"
5799 );
5800 assert_eq!(
5801 order,
5802 vec![
5803 "20260902-000000-0002".to_owned(),
5804 "20260903-000000-0003".to_owned(),
5805 "20260901-000000-0001".to_owned(),
5806 ],
5807 "priority first, then oldest, so nothing starves"
5808 );
5809 }
5810
5811 #[test]
5812 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5813 let dir = tempfile::tempdir().unwrap();
5814 let queue = Queue::at(dir.path().to_path_buf());
5815 let mut old = task();
5816 old.id = "20260101-000000-old0".to_owned();
5817 queue.put(&mut old).unwrap();
5818 let mut fresh = task();
5819 fresh.id = "20260101-000000-new0".to_owned();
5820 queue.put(&mut fresh).unwrap();
5821
5822 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5826 std::thread::sleep(Duration::from_millis(60));
5827 let live = queue.claim(&fresh.id).unwrap();
5828
5829 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5830 assert_eq!(swept, vec![old.id.clone()]);
5831 assert!(
5832 queue.claim(&old.id).is_ok(),
5833 "an unparseable lock older than the threshold is swept"
5834 );
5835 assert!(
5836 queue.claim(&fresh.id).is_err(),
5837 "a live pid protects its lock regardless of age"
5838 );
5839 drop(live);
5840 }
5841
5842 #[test]
5843 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5844 let dir = tempfile::tempdir().unwrap();
5854 let queue = Queue::at(dir.path().to_path_buf());
5855 let mut t = task();
5856 t.id = "20260101-000000-live".to_owned();
5857 queue.put(&mut t).unwrap();
5858
5859 let claim = queue.claim(&t.id).unwrap();
5860 std::thread::sleep(Duration::from_millis(60));
5861
5862 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5863 assert!(
5864 swept.is_empty(),
5865 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5866 );
5867 assert!(
5868 queue.claim(&t.id).is_err(),
5869 "the lock still protects its task"
5870 );
5871 drop(claim);
5872 }
5873
5874 fn injected_dead_pid() -> u32 {
5877 std::process::id().checked_add(1).unwrap_or(1)
5878 }
5879
5880 #[test]
5881 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5882 let dir = tempfile::tempdir().unwrap();
5883 let queue = Queue::at(dir.path().to_path_buf());
5884 let mut t = task();
5885 t.id = "20260101-000000-dead".to_owned();
5886 queue.put(&mut t).unwrap();
5887 let dead_pid = injected_dead_pid();
5888
5889 std::fs::write(
5894 dir.path().join(format!("{}.lock", t.id)),
5895 dead_pid.to_string(),
5896 )
5897 .unwrap();
5898
5899 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5900 pid != dead_pid
5901 });
5902 assert_eq!(
5903 swept,
5904 vec![t.id.clone()],
5905 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5906 );
5907 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5908 }
5909
5910 #[test]
5911 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5912 let dir = tempfile::tempdir().unwrap();
5913 let queue = Queue::at(dir.path().to_path_buf());
5914 let mut t = task();
5915 t.id = "20260101-000000-late".to_owned();
5916 queue.put(&mut t).unwrap();
5917 let dead_pid = injected_dead_pid();
5918
5919 assert!(
5922 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5923 "nothing has claimed the task yet"
5924 );
5925
5926 std::fs::write(
5929 dir.path().join(format!("{}.lock", t.id)),
5930 dead_pid.to_string(),
5931 )
5932 .unwrap();
5933
5934 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5938 pid != dead_pid
5939 });
5940 assert_eq!(swept, vec![t.id.clone()]);
5941 }
5942
5943 #[test]
5944 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5945 crate::run::pin_test_home();
5950 let dir = tempfile::tempdir().unwrap();
5951 let queue = Queue::at(dir.path().to_path_buf());
5952 let mut t = task();
5953 t.id = "20260101-000000-crsh".to_owned();
5954 t.status = TaskStatus::Running;
5955 t.attempts = 1;
5956 t.runs.push("20260904-000000-4043".to_owned());
5960 queue.put(&mut t).unwrap();
5961 let dead_pid = injected_dead_pid();
5962
5963 std::fs::write(
5966 dir.path().join(format!("{}.lock", t.id)),
5967 dead_pid.to_string(),
5968 )
5969 .unwrap();
5970
5971 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5977 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5978
5979 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5980 pid != dead_pid
5981 });
5982 assert_eq!(swept, vec![t.id.clone()]);
5983
5984 let reclaimed = reclaim_orphaned_running(&queue, 2);
5985 assert_eq!(reclaimed, vec![t.id.clone()]);
5986 let after = queue.get(&t.id).unwrap();
5987 assert_eq!(
5988 after.status,
5989 TaskStatus::Held,
5990 "no run.json to recover from, so a human is asked"
5991 );
5992 assert_eq!(
5993 after.runs,
5994 vec!["20260904-000000-4043".to_owned()],
5995 "the crashed run's id is kept as evidence, not discarded"
5996 );
5997 }
5998
5999 #[test]
6000 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6001 let dir = tempfile::tempdir().unwrap();
6002 let queue = Queue::at(dir.path().to_path_buf());
6003 let mut t = task();
6004 t.id = "20260101-000000-unknown".to_owned();
6005 queue.put(&mut t).unwrap();
6006 let dead_pid = injected_dead_pid();
6007 std::fs::write(
6008 dir.path().join(format!("{}.lock", t.id)),
6009 dead_pid.to_string(),
6010 )
6011 .unwrap();
6012
6013 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
6014 assert!(swept.is_empty(), "an unknown pid must keep its lock");
6015 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
6016 }
6017
6018 fn run_state_in(status: RunStatus, language: &str) -> RunState {
6019 let mut s = run_state(status);
6020 s.config.graph.language = language.to_owned();
6021 s
6022 }
6023
6024 fn unstarted_verdict(status: RunStatus) -> Verdict {
6025 Verdict {
6026 status,
6027 left_pr: false,
6028 quota_hit: false,
6029 parked: false,
6030 no_viable_candidates: false,
6031 }
6032 }
6033
6034 #[test]
6035 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
6036 let mut t = task();
6037 t.attempts = 1;
6038 settle_in(
6039 &mut t,
6040 unstarted_verdict(RunStatus::AlreadyInBase),
6041 "already in main",
6042 1,
6043 phrases("en"),
6044 );
6045 assert_eq!(t.status, TaskStatus::Done);
6046 assert_eq!(t.attempts, 0);
6047 }
6048
6049 #[test]
6050 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
6051 let reason = |language: &str| {
6052 let mut t = task();
6053 settle_in(
6054 &mut t,
6055 unstarted_verdict(RunStatus::Judging),
6056 "boom",
6057 1,
6058 phrases(language),
6059 );
6060 t.last_error.or(t.hold_reason).unwrap_or_default()
6061 };
6062 assert!(
6063 reason("en").starts_with("the graph stopped at `"),
6064 "{}",
6065 reason("en")
6066 );
6067 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
6068 assert!(reason("日本語").contains("boom"));
6069 assert_eq!(reason("fr"), reason("en"));
6070 }
6071
6072 #[test]
6073 fn describe_follows_the_run_language_and_keeps_the_run_id() {
6074 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
6075 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
6076 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
6077 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
6078 assert!(ja.contains("[run "), "{ja}");
6079 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
6080 assert!(ended.starts_with("run 終了: "), "{ended}");
6081 let mut de = run_state_in(RunStatus::Failed, "de");
6082 let mut en = run_state_in(RunStatus::Failed, "en");
6083 de.id = "same".to_owned();
6084 en.id = "same".to_owned();
6085 assert_eq!(describe(&de), describe(&en));
6086 }
6087
6088 #[test]
6089 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
6090 use crate::handover::Refused;
6091 let cases = [
6092 Refused::Foreign {
6093 branch: "b".into(),
6094 path: "/w/x".into(),
6095 why: "made by hand".into(),
6096 },
6097 Refused::Unsafe {
6098 branch: "b".into(),
6099 path: "/w/x".into(),
6100 why: "its worktree has uncommitted changes (a.rs)".into(),
6101 },
6102 Refused::ReleaseFailed {
6103 branch: "b".into(),
6104 path: "/w/x".into(),
6105 run: "ab12".into(),
6106 },
6107 ];
6108 for r in &cases {
6109 let en = (phrases("en").handover_refused)(r);
6110 assert_eq!(en, r.to_string());
6111 let ja = (phrases("ja").handover_refused)(r);
6112 assert!(
6113 !ja.contains("is checked out") && !ja.contains("try again"),
6114 "{ja}"
6115 );
6116 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
6117 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
6118 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
6119 }
6120 }
6121 assert!(phrases("en").handover_hint.contains("release the task"));
6122 assert!(phrases("ja").handover_hint.contains("解放"));
6123 }
6124
6125 #[test]
6126 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
6127 let build = |lang: &str| {
6128 let mut s = run_state_in(RunStatus::Blocked, lang);
6129 s.id = "same".to_owned();
6130 s.config.graph.review_rounds = 3;
6131 let mut r = review_round(3);
6132 r.expected = 3;
6133 r.answered = 1;
6134 s.reviews.push(r);
6135 s.event(
6136 "review",
6137 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
6138 );
6139 s
6140 };
6141 let en = describe(&build("en"));
6142 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
6143 let ja = describe(&build("ja"));
6144 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
6145 assert!(!ja.contains("never answered"), "{ja}");
6146 assert!(ja.contains("[run "), "{ja}");
6147
6148 let mut failed = build("ja");
6151 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
6152 command: "cargo test".to_owned(),
6153 code: Some(1),
6154 output_tail: String::new(),
6155 duration_ms: 0,
6156 resource_blocked: false,
6157 });
6158 failed.event("review", "stopped; e2e failed: cargo test");
6159 let ja = describe(&failed);
6160 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
6161 assert!(!ja.contains("席のレビュアー"), "{ja}");
6162 }
6163
6164 #[test]
6165 fn refusals_and_recovery_prose_follow_the_language() {
6166 let t = held_task_with("r1");
6167 let q = action_question(
6168 "r1",
6169 ask::ChoiceAction::Resume {
6170 run: "r1".to_owned(),
6171 },
6172 );
6173 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
6174 ActionDecision::Refuse(s) => s,
6175 other => panic!("{other:?}"),
6176 };
6177 assert!(refuse(phrases("en")).contains("could not be read: gone"));
6178 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
6179 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
6180
6181 let mut held = task();
6182 reclaim(&mut held, None, 2, "ja");
6183 assert!(held.hold_reason.unwrap().contains("保留にしました"));
6184 let mut held = task();
6185 reclaim(&mut held, None, 2, "xx");
6186 assert!(held.hold_reason.unwrap().contains("held for a human"));
6187 }
6188
6189 fn run_state(status: RunStatus) -> RunState {
6190 let mut state = RunState::new(
6191 PathBuf::from("/repo"),
6192 "main".to_owned(),
6193 "abc1234def".to_owned(),
6194 "add retries".to_owned(),
6195 Config::default(),
6196 );
6197 state.status = status;
6198 state
6199 }
6200
6201 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
6202 Candidate {
6203 index: 0,
6204 label,
6205 agent: "claude".to_owned(),
6206 branch: format!("magi/x/{label}"),
6207 worktree: PathBuf::from("/repo"),
6208 summary: summary.to_owned(),
6209 stat: String::new(),
6210 files: 0,
6211 commits: usize::from(!empty),
6212 empty,
6213 failed: failed.map(str::to_owned),
6214 verified_noop: None,
6215 duration_ms: 0,
6216 folded: false,
6217 }
6218 }
6219
6220 #[test]
6221 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
6222 let mut state = run_state(RunStatus::Blocked);
6223 state.gate = vec![
6224 CommandOutcome {
6225 command: "cargo make check".to_owned(),
6226 code: Some(0),
6227 output_tail: "ok".to_owned(),
6228 duration_ms: 0,
6229 resource_blocked: false,
6230 },
6231 CommandOutcome {
6232 command: "cargo test".to_owned(),
6233 code: Some(101),
6234 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
6235 duration_ms: 0,
6236 resource_blocked: false,
6237 },
6238 ];
6239 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
6240 assert!(d.contains("cargo test"), "{d}");
6241 assert!(
6242 !d.contains("cargo make check"),
6243 "a passing check is not a diagnostic: {d}"
6244 );
6245 assert!(d.contains("assertion failed"), "{d}");
6246 }
6247
6248 #[test]
6249 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
6250 let mut state = run_state(RunStatus::Blocked);
6251 state.event(
6252 "land",
6253 "stopped: the fixer produced no commit while 2 check(s) were failing \
6254 (build, lint); stopping instead of looping on an unchanged tree",
6255 );
6256 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
6257 assert!(d.contains("build"), "{d}");
6258 assert!(d.contains("lint"), "{d}");
6259 assert!(d.contains("fixer produced no commit"), "{d}");
6260 }
6261
6262 #[test]
6263 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
6264 let state = run_state(RunStatus::VerifiedNoop);
6269 let d = describe(&state);
6270 assert!(
6271 d.contains("agent-verified no-op"),
6272 "expected the display label, not the wire spelling: {d}"
6273 );
6274 assert!(!d.contains("verified_noop"), "{d}");
6275 }
6276
6277 #[test]
6278 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
6279 let mut state = run_state(RunStatus::Failed);
6285 state.candidates = vec![candidate(
6286 'A',
6287 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
6288 true,
6289 None,
6290 )];
6291 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
6292 assert!(d.contains("candidate A"), "{d}");
6293 assert!(d.contains("tagged v1.2.3"), "{d}");
6294 }
6295
6296 #[test]
6297 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
6298 let mut state = run_state(RunStatus::Failed);
6299 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
6300 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
6301 assert!(d.contains("candidate A"), "{d}");
6302 assert!(d.contains("agent timed out"), "{d}");
6303 }
6304
6305 #[test]
6306 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
6307 let mut state = run_state(RunStatus::Failed);
6310 state.candidates = vec![candidate('A', "did the work", false, None)];
6311 assert!(diagnostic(&state).is_none());
6312 }
6313
6314 #[test]
6315 fn diagnostic_is_bounded_however_much_a_run_printed() {
6316 let mut state = run_state(RunStatus::Blocked);
6317 state.gate = vec![
6318 CommandOutcome {
6319 command: "cargo test".to_owned(),
6320 code: Some(101),
6321 output_tail: "x".repeat(50_000),
6322 duration_ms: 0,
6323 resource_blocked: false,
6324 },
6325 CommandOutcome {
6326 command: "cargo clippy".to_owned(),
6327 code: Some(1),
6328 output_tail: "y".repeat(50_000),
6329 duration_ms: 0,
6330 resource_blocked: false,
6331 },
6332 ];
6333 state.candidates = vec![
6334 candidate('A', &"z".repeat(50_000), true, None),
6335 candidate('B', &"w".repeat(50_000), true, None),
6336 ];
6337 let d = diagnostic(&state).expect("plenty here to diagnose");
6338 assert!(
6339 d.len() <= DIAGNOSTIC_MAX,
6340 "diagnostic grew to {} bytes, unbounded",
6341 d.len()
6342 );
6343 }
6344
6345 #[test]
6346 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
6347 let mut state = run_state(RunStatus::Blocked);
6348 state.gate = vec![CommandOutcome {
6349 command: "cargo test".to_owned(),
6350 code: Some(101),
6351 output_tail: "assertion failed".to_owned(),
6352 duration_ms: 0,
6353 resource_blocked: false,
6354 }];
6355 let verdict = Verdict {
6356 status: RunStatus::Blocked,
6357 left_pr: false,
6358 quota_hit: false,
6359 parked: false,
6360 no_viable_candidates: false,
6361 };
6362
6363 let mut t = task();
6366 t.start("run-1".to_owned());
6367 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6368 assert_eq!(t.status, TaskStatus::Failed);
6369 assert!(t.diagnostic.is_none());
6370
6371 t.start("run-2".to_owned());
6374 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6375 assert_eq!(t.status, TaskStatus::Held);
6376 let d = t.diagnostic.expect("a held task must carry its diagnostic");
6377 assert!(d.contains("cargo test"), "{d}");
6378 }
6379
6380 #[test]
6381 fn a_held_task_names_the_open_question_it_is_waiting_on() {
6382 crate::run::pin_test_home();
6387 let home = crate::run::home();
6388 let state = run_state(RunStatus::VerifiedNoop);
6389 let mut q = ask::Question::new(
6390 state.id.clone(),
6391 "implement".to_owned(),
6392 "impl-A".to_owned(),
6393 "is this really a no-op?".to_owned(),
6394 String::new(),
6395 Vec::new(),
6396 );
6397 Questions::at(home.join("questions")).put(&mut q).unwrap();
6398
6399 let verdict = Verdict {
6400 status: RunStatus::VerifiedNoop,
6401 left_pr: false,
6402 quota_hit: false,
6403 parked: false,
6404 no_viable_candidates: false,
6405 };
6406 let mut t = task();
6407 t.start(state.id.clone());
6408 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6409
6410 assert_eq!(t.status, TaskStatus::Held);
6411 let reason = t.hold_reason.expect("a held task must record why");
6412 assert!(
6413 reason.starts_with("run ended agent-verified no-op"),
6414 "the original settle reason must survive unchanged: {reason}"
6415 );
6416 assert!(
6417 reason.contains(q.short()),
6418 "the open question's id must be named so the notice is actionable: {reason}"
6419 );
6420 }
6421
6422 #[test]
6423 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
6424 crate::run::pin_test_home();
6425 let state = run_state(RunStatus::VerifiedNoop);
6426
6427 let verdict = Verdict {
6428 status: RunStatus::VerifiedNoop,
6429 left_pr: false,
6430 quota_hit: false,
6431 parked: false,
6432 no_viable_candidates: false,
6433 };
6434 let mut t = task();
6435 t.start(state.id.clone());
6436 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6437
6438 assert_eq!(t.status, TaskStatus::Held);
6439 assert_eq!(
6440 t.hold_reason.as_deref(),
6441 Some("run ended agent-verified no-op"),
6442 "nothing to append when the question was already answered or never asked"
6443 );
6444 }
6445
6446 #[test]
6447 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
6448 crate::run::pin_test_home();
6449 let mut first = run_state(RunStatus::Blocked);
6450 first.id = "20260101-000000-sup1".to_owned();
6451 first.save().unwrap();
6452 let mut second = run_state(RunStatus::Merged);
6453 second.id = "20260101-000000-sup2".to_owned();
6454 second.save().unwrap();
6455
6456 let mut t = task();
6457 t.runs = vec![first.id.clone(), second.id.clone()];
6458 t.status = TaskStatus::Done;
6459
6460 supersede_prior_runs(&t, &crate::run::home());
6461
6462 assert_eq!(
6463 RunState::load(&first.id).unwrap().status,
6464 RunStatus::Superseded,
6465 "the first attempt's Blocked no longer needs anyone's attention"
6466 );
6467 assert_eq!(
6468 RunState::load(&second.id).unwrap().status,
6469 RunStatus::Merged,
6470 "the run that actually succeeded is left exactly as it was"
6471 );
6472 }
6473
6474 #[test]
6475 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
6476 crate::run::pin_test_home();
6482 let mut first = run_state(RunStatus::Blocked);
6483 first.id = "20260101-000000-sup9".to_owned();
6484 first.driver_pid = Some(std::process::id());
6487 first.driver_started_at = Some(
6488 crate::proc::process_started_at(std::process::id())
6489 .expect("this test process's own start time must be queryable"),
6490 );
6491 first.save().unwrap();
6492 let mut second = run_state(RunStatus::Merged);
6493 second.id = "20260101-000000-supa".to_owned();
6494 second.save().unwrap();
6495
6496 let mut t = task();
6497 t.runs = vec![first.id.clone(), second.id.clone()];
6498 t.status = TaskStatus::Done;
6499
6500 supersede_prior_runs(&t, &crate::run::home());
6501
6502 assert_eq!(
6503 RunState::load(&first.id).unwrap().status,
6504 RunStatus::Blocked,
6505 "a live driver_pid means something is still actually working this run, \
6506 even though no daemon claims it - rewriting under it would just be \
6507 undone the next time that process saves"
6508 );
6509 }
6510
6511 #[test]
6512 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
6513 let dir = tempfile::tempdir().unwrap();
6519 let home = dir.path().to_path_buf();
6520 let queue = Queue::at(dir.path().join("queue"));
6521
6522 let mut first = run_state(RunStatus::Blocked);
6523 first.id = "20260101-000000-supd".to_owned();
6524 first.driver_pid = Some(std::process::id());
6525 first.driver_started_at = Some(
6526 crate::proc::process_started_at(std::process::id())
6527 .expect("this test process's own start time must be queryable"),
6528 );
6529 first.save_under(&home).unwrap();
6530 let mut second = run_state(RunStatus::Merged);
6531 second.id = "20260101-000000-supe".to_owned();
6532 second.save_under(&home).unwrap();
6533
6534 let mut t = task();
6535 t.runs = vec![first.id.clone(), second.id.clone()];
6536 t.status = TaskStatus::Done;
6537 queue.put(&mut t).unwrap();
6538
6539 resweep_superseded_attempts(&queue, &home);
6540 assert_eq!(
6541 RunState::load_under(&first.id, &home).unwrap().status,
6542 RunStatus::Blocked,
6543 "still live on the first pass, so still untouched"
6544 );
6545
6546 let mut stale = RunState::load_under(&first.id, &home).unwrap();
6552 stale.driver_started_at = Some("1".to_owned());
6553 stale.save_under(&home).unwrap();
6554
6555 resweep_superseded_attempts(&queue, &home);
6556 assert_eq!(
6557 RunState::load_under(&first.id, &home).unwrap().status,
6558 RunStatus::Superseded,
6559 "the second pass catches up what the first one correctly skipped"
6560 );
6561 }
6562
6563 #[test]
6564 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
6565 crate::run::pin_test_home();
6566 let mut first = run_state(RunStatus::Blocked);
6567 first.id = "20260101-000000-sup3".to_owned();
6568 first.save().unwrap();
6569 let mut second = run_state(RunStatus::Blocked);
6570 second.id = "20260101-000000-sup4".to_owned();
6571 second.save().unwrap();
6572
6573 let mut t = task();
6574 t.runs = vec![first.id.clone(), second.id.clone()];
6575 t.status = TaskStatus::Failed;
6579
6580 supersede_prior_runs(&t, &crate::run::home());
6581
6582 assert_eq!(
6583 RunState::load(&first.id).unwrap().status,
6584 RunStatus::Blocked
6585 );
6586 assert_eq!(
6587 RunState::load(&second.id).unwrap().status,
6588 RunStatus::Blocked
6589 );
6590 }
6591
6592 #[test]
6593 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
6594 crate::run::pin_test_home();
6598 let mut first = run_state(RunStatus::Blocked);
6599 first.id = "20260101-000000-sup5".to_owned();
6600 first.save().unwrap();
6601
6602 let mut t = task();
6603 t.runs = vec![first.id.clone()];
6604 t.status = TaskStatus::Done;
6605
6606 supersede_prior_runs(&t, &crate::run::home());
6607
6608 assert_eq!(
6609 RunState::load(&first.id).unwrap().status,
6610 RunStatus::Blocked,
6611 "a single-attempt task has no earlier run to supersede"
6612 );
6613 }
6614
6615 #[test]
6616 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
6617 crate::run::pin_test_home();
6624 let mut first = run_state(RunStatus::Blocked);
6625 first.id = "20260101-000000-supb".to_owned();
6626 first.save().unwrap();
6627 let mut second = run_state(RunStatus::Failed);
6628 second.id = "20260101-000000-supc".to_owned();
6629 second.save().unwrap();
6630
6631 let mut t = task();
6632 t.runs = vec![first.id.clone(), second.id.clone()];
6633 t.status = TaskStatus::Done;
6634
6635 supersede_prior_runs(&t, &crate::run::home());
6636
6637 assert_eq!(
6638 RunState::load(&first.id).unwrap().status,
6639 RunStatus::Blocked,
6640 "the task's last attempt never landed, so there is nothing here \
6641 actually superseding it"
6642 );
6643 }
6644
6645 #[test]
6646 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6647 crate::run::pin_test_home();
6651 let mut failed = run_state(RunStatus::Failed);
6652 failed.id = "20260101-000000-sup6".to_owned();
6653 failed.save().unwrap();
6654 let mut noop = run_state(RunStatus::VerifiedNoop);
6655 noop.id = "20260101-000000-sup7".to_owned();
6656 noop.save().unwrap();
6657 let mut winner = run_state(RunStatus::Ready);
6658 winner.id = "20260101-000000-sup8".to_owned();
6659 winner.save().unwrap();
6660
6661 let mut t = task();
6662 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6663 t.status = TaskStatus::Done;
6664
6665 supersede_prior_runs(&t, &crate::run::home());
6666
6667 assert_eq!(
6668 RunState::load(&failed.id).unwrap().status,
6669 RunStatus::Failed
6670 );
6671 assert_eq!(
6672 RunState::load(&noop.id).unwrap().status,
6673 RunStatus::VerifiedNoop
6674 );
6675 }
6676
6677 fn approval_question(run: &str) -> ask::Question {
6678 ask::Question::new(
6679 run.to_owned(),
6680 land::APPROVAL_NODE.to_owned(),
6681 "land".to_owned(),
6682 "merge?".to_owned(),
6683 String::new(),
6684 vec!["merge".to_owned(), "hold".to_owned()],
6685 )
6686 }
6687
6688 #[test]
6689 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6690 crate::run::pin_test_home();
6691 let mut state = run_state(RunStatus::Landing);
6692 state.id = "20260101-000000-fre1".to_owned();
6693 state.parked = true;
6694 state.save().unwrap();
6695 ask::Questions::open()
6696 .put(&mut approval_question(&state.id))
6697 .unwrap();
6698
6699 let mut t = task();
6700 t.runs.push(state.id.clone());
6701 assert_eq!(
6702 land_resume_state(&t),
6703 LandResume::StillWaiting,
6704 "nobody has answered and the timeout has not passed"
6705 );
6706 }
6707
6708 #[test]
6709 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6710 crate::run::pin_test_home();
6711 let mut state = run_state(RunStatus::Gating);
6712 state.id = "20260101-000000-gt01".to_owned();
6713 state.parked = true;
6714 state.config.graph.answer_timeout = 60;
6715 state.github_text = Some(crate::run::GithubTextAsk {
6716 rewrite: None,
6717 fingerprint: "f".into(),
6718 title: true,
6719 body: false,
6720 categories: vec!["title-language".into()],
6721 question: None,
6722 asks: 1,
6723 resolved: false,
6724 chosen_title: None,
6725 choice: None,
6726 });
6727 state.save().unwrap();
6728 let store = ask::Questions::open();
6729 let mut q = ask::Question::new(
6730 state.id.clone(),
6731 crate::github_text::ASK_NODE.to_owned(),
6732 crate::github_text::ASK_SEAT.to_owned(),
6733 "s".into(),
6734 String::new(),
6735 vec!["use fallback".into()],
6736 );
6737 store.put(&mut q).unwrap();
6738 let mut t = task();
6739 t.runs.push(state.id.clone());
6740 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6741 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6742 store.put(&mut q).unwrap();
6743 assert_eq!(land_resume_state(&t), LandResume::Ready);
6744 assert!(!store.get(&q.id).unwrap().status.open());
6745 state.github_text.as_mut().unwrap().resolved = true;
6747 state.save().unwrap();
6748 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6749 }
6750
6751 #[test]
6752 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6753 crate::run::pin_test_home();
6758 let mut state = run_state(RunStatus::Landing);
6759 state.id = "20260101-000000-exp1".to_owned();
6760 state.parked = true;
6761 state.config.graph.answer_timeout = 60;
6762 state.save().unwrap();
6763
6764 let store = ask::Questions::open();
6765 let mut q = approval_question(&state.id);
6766 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6767 store.put(&mut q).unwrap();
6768
6769 let mut t = task();
6770 t.runs.push(state.id.clone());
6771 assert_eq!(
6772 land_resume_state(&t),
6773 LandResume::Ready,
6774 "an expired question must not be waited on forever"
6775 );
6776
6777 let after = store.get(&q.id).unwrap();
6778 assert!(
6779 !after.status.open(),
6780 "the question is abandoned, not silently ignored"
6781 );
6782 assert!(
6783 after.resolution().is_none(),
6784 "an abandoned question is not read as a decision"
6785 );
6786 }
6787
6788 #[test]
6789 fn reclaim_settles_a_running_task_against_its_last_run() {
6790 let mut t = task();
6791 t.start("20260904-000000-4043".to_owned());
6792 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6793 assert_eq!(
6794 t.status,
6795 TaskStatus::Done,
6796 "a run that actually finished must not stay `running` forever"
6797 );
6798 }
6799
6800 #[test]
6801 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6802 let mut t = task();
6803 t.start("20260904-000000-4043".to_owned());
6804 t.last_error = Some("earlier trouble".to_owned());
6805 let mut state = run_state(RunStatus::Judging);
6806 state.parked = true;
6807 reclaim(&mut t, Some(state), 1, "en");
6808 assert_eq!(t.status, TaskStatus::Parked);
6809 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6810 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6811 assert!(t.park_reason.is_some());
6812 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6813 assert!(!t.fresh_start);
6814 assert!(t.status.runnable());
6815 }
6816
6817 #[test]
6818 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6819 let mut t = task();
6820 t.start("20260904-000000-4043".to_owned());
6821 t.last_error = Some("earlier trouble".to_owned());
6822 settle(
6823 &mut t,
6824 Verdict {
6825 status: RunStatus::Judging,
6826 left_pr: false,
6827 quota_hit: false,
6828 parked: true,
6829 no_viable_candidates: false,
6830 },
6831 "parked after `judging`",
6832 1,
6833 );
6834 assert_eq!(t.status, TaskStatus::Parked);
6835 assert_eq!(t.attempts, 0);
6836 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6837 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6838 assert_eq!(t.schema, crate::queue::SCHEMA);
6839 assert!(
6840 crate::notices::task_held(&t).is_none(),
6841 "a park is not news"
6842 );
6843 t.start("20260904-000000-4043".to_owned());
6844 assert_eq!(t.park_reason, None);
6845 }
6846
6847 #[test]
6848 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6849 let mut t = task();
6853 t.start("20260904-000000-4043".to_owned());
6854 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6855 assert_eq!(t.status, TaskStatus::Failed);
6856 assert!(t.status.runnable());
6857 }
6858
6859 #[test]
6860 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
6861 let mut t = task();
6862 t.start("20260904-000000-4043".to_owned());
6863 assert_eq!(t.attempts, 1);
6864 let mut run = run_state(RunStatus::Implementing);
6865 run.id = "20260904-000000-4043".to_owned();
6866 run.begin_pass();
6867 let cause = crate::run::ParkCause::Upgrade {
6868 from: "0.121.0".to_owned(),
6869 to: Some("0.121.1".to_owned()),
6870 };
6871 run.end_pass_parked(cause.clone());
6872 run.parked = true;
6873 let verdict = Verdict {
6874 status: run.status,
6875 left_pr: false,
6876 quota_hit: false,
6877 parked: true,
6878 no_viable_candidates: false,
6879 };
6880 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
6881 assert_eq!(t.attempts, 0);
6882 assert_eq!(t.passes.len(), 1);
6883 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6884 assert_eq!(t.passes[0].parked, Some(cause));
6885 assert_eq!(t.passes[0].pass_index, 0);
6886
6887 t.start("20260904-000000-4043".to_owned());
6890 run.begin_pass();
6891 run.status = RunStatus::Failed;
6892 let verdict = Verdict {
6893 status: RunStatus::Failed,
6894 left_pr: false,
6895 quota_hit: false,
6896 parked: false,
6897 no_viable_candidates: false,
6898 };
6899 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
6900 assert_eq!(t.passes.len(), 2);
6901 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6902 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
6903 assert_eq!(t.passes[1].pass_index, 1);
6904 assert_eq!(t.attempts, 1);
6905 }
6906
6907 #[test]
6908 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6909 let mut t = task();
6910 t.start("20260904-000000-4043".to_owned());
6911 reclaim(&mut t, None, 2, "en");
6912 assert_eq!(t.status, TaskStatus::Held);
6913 assert!(
6914 t.last_error
6915 .as_deref()
6916 .is_some_and(|e| e.contains("running")),
6917 "the operator needs to know why this task was held"
6918 );
6919 }
6920
6921 #[test]
6922 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6923 let dir = tempfile::tempdir().unwrap();
6924 let queue = Queue::at(dir.path().to_path_buf());
6925
6926 let mut orphaned = task();
6928 orphaned.id = "20260904-000000-orph".to_owned();
6929 orphaned.status = TaskStatus::Running;
6930 orphaned.attempts = 1;
6931 queue.put(&mut orphaned).unwrap();
6932
6933 let mut alive = task();
6934 alive.id = "20260904-000000-live".to_owned();
6935 alive.status = TaskStatus::Running;
6936 alive.attempts = 1;
6937 queue.put(&mut alive).unwrap();
6938 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6939
6940 let mut queued = task();
6941 queued.id = "20260904-000000-wait".to_owned();
6942 queue.put(&mut queued).unwrap();
6943
6944 let reclaimed = reclaim_orphaned_running(&queue, 2);
6945 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6946
6947 assert_eq!(
6948 queue.get(&orphaned.id).unwrap().status,
6949 TaskStatus::Held,
6950 "nothing was driving it and there was no run to recover"
6951 );
6952 assert_eq!(
6953 queue.get(&alive.id).unwrap().status,
6954 TaskStatus::Running,
6955 "a live claim must protect the task it belongs to"
6956 );
6957 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6958 }
6959
6960 fn read_run_under(home: &Path, id: &str) -> RunState {
6966 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6967 serde_json::from_str(&body).unwrap()
6968 }
6969
6970 #[test]
6971 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6972 let dir = tempfile::tempdir().unwrap();
6973 let home = dir.path().to_path_buf();
6974 let now = Timestamp::now();
6975 let overrun_seat = || crate::run::ActiveSeat {
6976 node: "implement".to_owned(),
6977 started_at: now - jiff::SignedDuration::new(21_000, 0),
6978 timeout_secs: 3_600,
6979 attempt: 0,
6980 task: None,
6981 command: None,
6982 index: None,
6983 total: None,
6984 };
6985
6986 let mut dead = run_state(RunStatus::Implementing);
6987 dead.id = "20260101-000000-dead".to_owned();
6988 dead.active.insert("impl-A".to_owned(), overrun_seat());
6989 dead.driver_pid = Some(4242);
6992 dead.save_under(&home).unwrap();
6993
6994 let mut alive = run_state(RunStatus::Implementing);
6997 alive.id = "20260101-000000-aliv".to_owned();
6998 alive.active.insert("impl-A".to_owned(), overrun_seat());
6999 alive.save_under(&home).unwrap();
7000 let mut status = Status::new();
7001 status.current = vec![Current {
7002 task: "20260101-000000-task".to_owned(),
7003 run: alive.id.clone(),
7004 }];
7005 write_status_to(&home.join("daemon.json"), &status).unwrap();
7006
7007 let questions = Questions::at(home.join("questions"));
7011 let mut q = ask::Question::new(
7012 dead.id.clone(),
7013 "implement".to_owned(),
7014 "impl-A".to_owned(),
7015 "Which storage backend?".to_owned(),
7016 String::new(),
7017 vec!["SQLite".to_owned(), "Redis".to_owned()],
7018 );
7019 questions.put(&mut q).unwrap();
7020
7021 let abandoned = reclaim_abandoned_runs_with(
7022 &home,
7023 now,
7024 |pid| if pid == 4242 { Some(false) } else { None },
7025 |_| panic!("a query answering Dead outright needs no identity corroboration"),
7026 );
7027 assert_eq!(abandoned, vec![dead.id.clone()]);
7028
7029 let reloaded = read_run_under(&home, &dead.id);
7030 assert_eq!(reloaded.status, RunStatus::Failed);
7031 assert!(reloaded.active.is_empty());
7032 assert!(
7033 !questions.get(&q.id).unwrap().status.open(),
7034 "the failed run's own open question must be settled in the same pass"
7035 );
7036
7037 let still_alive = read_run_under(&home, &alive.id);
7038 assert_eq!(
7039 still_alive.status,
7040 RunStatus::Implementing,
7041 "a live daemon's claim protects it"
7042 );
7043 assert!(!still_alive.active.is_empty());
7044 }
7045
7046 #[test]
7056 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
7057 let dir = tempfile::tempdir().unwrap();
7058 let home = dir.path().to_path_buf();
7059 let now = Timestamp::now();
7060
7061 let mut manual = run_state(RunStatus::Reviewing);
7062 manual.id = "20260101-000000-manl".to_owned();
7063 manual.active.insert(
7064 "review-1".to_owned(),
7065 crate::run::ActiveSeat {
7066 node: "review".to_owned(),
7067 started_at: now - jiff::SignedDuration::new(21_000, 0),
7068 timeout_secs: 3_600,
7069 attempt: 0,
7070 task: None,
7071 command: None,
7072 index: None,
7073 total: None,
7074 },
7075 );
7076 manual.driver_pid = Some(4242);
7080 manual.driver_started_at = Some("1790000000".to_owned());
7081 manual.save_under(&home).unwrap();
7082
7083 let abandoned = reclaim_abandoned_runs_with(
7084 &home,
7085 now,
7086 |pid| if pid == 4242 { Some(true) } else { None },
7087 |pid| {
7088 if pid == 4242 {
7089 Some("1790000000".to_owned())
7090 } else {
7091 None
7092 }
7093 },
7094 );
7095 assert!(
7096 abandoned.is_empty(),
7097 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
7098 );
7099
7100 let reloaded = read_run_under(&home, &manual.id);
7101 assert_eq!(reloaded.status, RunStatus::Reviewing);
7102 assert!(!reloaded.active.is_empty());
7103 }
7104
7105 #[test]
7106 fn an_already_claimed_task_is_skipped_rather_than_failed() {
7107 let dir = tempfile::tempdir().unwrap();
7108 let queue = Queue::at(dir.path().to_path_buf());
7109 let mut only = task();
7110 queue.put(&mut only).unwrap();
7111
7112 let _elsewhere = queue.claim(&only.id).unwrap();
7113 let candidates = runnable(&queue);
7114 assert_eq!(candidates.len(), 1, "the task is still runnable");
7115 assert!(
7116 queue.claim(&candidates[0].id).is_err(),
7117 "the loop cannot take a claim somebody else holds"
7118 );
7119
7120 let after = queue.get(&only.id).unwrap();
7121 assert_eq!(after.status, TaskStatus::Queued);
7122 assert_eq!(
7123 after.attempts, 0,
7124 "losing the race is not an attempt at the task"
7125 );
7126 assert_eq!(after.last_error, None);
7127 }
7128
7129 #[test]
7130 fn the_status_file_round_trips_and_its_heartbeat_advances() {
7131 let dir = tempfile::tempdir().unwrap();
7132 let path = dir.path().join("daemon.json");
7133
7134 let mut status = Status::new();
7135 status.idle = false;
7136 status.completed = 7;
7137 status.current = vec![Current {
7138 task: "20260902-000000-t111".to_owned(),
7139 run: "20260902-000001-r111".to_owned(),
7140 }];
7141 write_status_to(&path, &status).unwrap();
7142 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7143 assert_eq!(first.schema, SCHEMA);
7144 assert_eq!(first.pid, std::process::id());
7145 assert!(!first.idle);
7146 assert_eq!(first.completed, 7);
7147 assert_eq!(first.current, status.current);
7148 assert!(
7149 !path.with_extension("json.tmp").exists(),
7150 "the temp file is renamed, not left behind"
7151 );
7152
7153 std::thread::sleep(Duration::from_millis(5));
7154 status.updated_at = Timestamp::now();
7155 status.polls = 3;
7156 write_status_to(&path, &status).unwrap();
7157 let second: Status =
7158 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7159 assert!(
7160 second.updated_at > first.updated_at,
7161 "a reader can only detect staleness if the heartbeat moves"
7162 );
7163 assert_eq!(
7164 second.started_at, first.started_at,
7165 "the start time is not a heartbeat"
7166 );
7167 assert_eq!(second.polls, 3);
7168 }
7169
7170 #[test]
7171 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
7172 let dir = tempfile::tempdir().unwrap();
7173
7174 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
7175
7176 let mut status = Status::new();
7177 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
7178 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7179 let stale = read_status(dir.path()).unwrap();
7180 assert!(
7181 !stale.running(Timestamp::now()),
7182 "a minute without a heartbeat is a dead daemon, not a busy one"
7183 );
7184 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
7185
7186 status.updated_at = Timestamp::now();
7187 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7188 let fresh = read_status(dir.path()).unwrap();
7189 assert!(fresh.running(Timestamp::now()));
7190 }
7191
7192 #[test]
7193 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
7194 let dir = tempfile::tempdir().unwrap();
7195 let now = Timestamp::now();
7196 let mine = "20260903-080619-01c2";
7197
7198 assert!(
7199 !is_working_on(dir.path(), mine, now),
7200 "no status file means nobody is working on anything"
7201 );
7202
7203 let mut status = Status::new();
7204 status.current = vec![Current {
7205 task: "20260903-080340-0167".to_owned(),
7206 run: mine.to_owned(),
7207 }];
7208 status.updated_at = now;
7209 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7210 assert!(is_working_on(dir.path(), mine, now));
7211 assert!(
7212 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
7213 "a daemon busy with one run is not working on another"
7214 );
7215
7216 status.updated_at = now - jiff::SignedDuration::from_secs(600);
7219 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7220 assert!(
7221 !is_working_on(dir.path(), mine, now),
7222 "a stale heartbeat is a dead daemon, so its run is a leftover"
7223 );
7224 }
7225
7226 #[test]
7227 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
7228 let dir = tempfile::tempdir().unwrap();
7229 let now = Timestamp::now();
7230
7231 assert!(
7232 !is_working_on_short(dir.path(), "01c2", now),
7233 "no status file means nobody is working on anything"
7234 );
7235
7236 let mut status = Status::new();
7237 status.current = vec![Current {
7238 task: "20260903-080340-0167".to_owned(),
7239 run: "20260903-080619-01c2".to_owned(),
7240 }];
7241 status.updated_at = now;
7242 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7243 assert!(
7244 is_working_on_short(dir.path(), "01c2", now),
7245 "the run's short id is the last block of its full id"
7246 );
7247 assert!(
7248 !is_working_on_short(dir.path(), "3cbf", now),
7249 "a daemon busy with one worktree bay is not working on another"
7250 );
7251 }
7252
7253 #[test]
7254 fn a_newer_status_file_still_yields_a_reading() {
7255 let dir = tempfile::tempdir().unwrap();
7256 std::fs::write(
7259 dir.path().join("daemon.json"),
7260 serde_json::json!({
7261 "schema": 2,
7262 "updated_at": Timestamp::now().to_string(),
7263 "idle": true,
7264 "surprise": { "nested": [1, 2, 3] },
7265 })
7266 .to_string(),
7267 )
7268 .unwrap();
7269
7270 let reading = read_status(dir.path()).expect("a forward-compatible read");
7271 assert!(reading.running(Timestamp::now()));
7272 assert!(reading.idle);
7273 assert!(reading.current.is_empty());
7274 }
7275
7276 #[test]
7277 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
7278 let dir = tempfile::tempdir().unwrap();
7284 std::fs::write(
7285 dir.path().join("daemon.json"),
7286 serde_json::json!({
7287 "schema": 1,
7288 "pid": 4242,
7289 "updated_at": Timestamp::now().to_string(),
7290 "idle": false,
7291 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
7292 "completed": 3,
7293 "polls": 9,
7294 })
7295 .to_string(),
7296 )
7297 .unwrap();
7298
7299 let reading = read_status(dir.path()).expect("an older shape must still parse");
7300 assert!(reading.running(Timestamp::now()));
7301 assert_eq!(
7302 reading.current,
7303 vec![Current {
7304 task: "20260902-140501-aaaa".to_owned(),
7305 run: "20260902-140502-bbbb".to_owned(),
7306 }]
7307 );
7308 }
7309
7310 #[test]
7311 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
7312 let dir = tempfile::tempdir().unwrap();
7313 std::fs::write(
7314 dir.path().join("daemon.json"),
7315 serde_json::json!({
7316 "schema": 1,
7317 "updated_at": Timestamp::now().to_string(),
7318 "idle": true,
7319 "current": null,
7320 })
7321 .to_string(),
7322 )
7323 .unwrap();
7324 let with_null = read_status(dir.path()).expect("null must still parse");
7325 assert!(with_null.current.is_empty());
7326
7327 std::fs::write(
7328 dir.path().join("daemon.json"),
7329 serde_json::json!({
7330 "schema": 1,
7331 "updated_at": Timestamp::now().to_string(),
7332 "idle": true,
7333 })
7334 .to_string(),
7335 )
7336 .unwrap();
7337 let absent = read_status(dir.path()).expect("a missing field must still parse");
7338 assert!(absent.current.is_empty());
7339 }
7340
7341 #[test]
7342 fn a_task_without_a_repository_runs_in_the_daemons_default() {
7343 let fallback = Path::new("/default");
7344 let mut blank = task();
7345 blank.repo = PathBuf::new();
7346 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
7347 let mut dot = task();
7348 dot.repo = PathBuf::from(".");
7349 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
7350 assert_eq!(
7351 repo_for(&task(), fallback),
7352 PathBuf::from("/repo"),
7353 "a task that names a repository keeps it"
7354 );
7355 }
7356
7357 #[test]
7358 fn task_implementers_edit_inherits_daemon_config_and_merge() {
7359 let dir = tempfile::tempdir().unwrap();
7360 let path = dir.path().join("explicit.toml");
7361 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
7362 let opts = Opts {
7363 config: Some(path),
7364 merge: Some("none".into()),
7365 ..Default::default()
7366 };
7367 let mut t = task();
7368 t.set_implementers(
7369 2,
7370 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7371 .unwrap(),
7372 )
7373 .unwrap();
7374 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7375 assert_eq!(cfg.graph.implementers, 2);
7376 assert_eq!(cfg.graph.judges, 1);
7377 assert_eq!(cfg.merge.mode, MergeMode::None);
7378 t.set_implementers(1, &cfg).unwrap();
7379 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7380 apply_task_implementers(&mut cfg, &t);
7381 assert_eq!(cfg.graph.implementers, 1);
7382 assert_eq!(cfg.graph.judges, 1);
7383 assert_eq!(cfg.merge.mode, MergeMode::None);
7384 }
7385
7386 #[test]
7387 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
7388 let dir = tempfile::tempdir().unwrap();
7389 let repo = dir.path().join("repo");
7390 std::fs::create_dir(&repo).unwrap();
7391 std::fs::write(
7392 repo.join("magi.toml"),
7393 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
7394 )
7395 .unwrap();
7396 let daemon_config = dir.path().join("daemon.toml");
7397 std::fs::write(
7398 &daemon_config,
7399 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
7400 )
7401 .unwrap();
7402 let opts = Opts {
7403 config: Some(daemon_config),
7404 merge: Some("pr".into()),
7405 ..Default::default()
7406 };
7407 let q = Queue::at(dir.path().join("queue"));
7408 let validation: Config =
7409 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7410 .unwrap();
7411 for record in ["{}", r#"{"candidates":2}"#] {
7413 let overrides = serde_json::from_str(record).unwrap();
7414 let filing = crate::direct::Filing {
7415 instruction: "work".into(),
7416 title: "direct".into(),
7417 repo: repo.clone(),
7418 source: crate::queue::Source::Human,
7419 solo: false,
7420 overrides,
7421 review_of: None,
7422 };
7423 let filed =
7424 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
7425 let crate::direct::Filed::Standalone {
7426 mut task,
7427 claim: _claim,
7428 } = filed
7429 else {
7430 panic!("local filing")
7431 };
7432 let before = prepare_for(&repo, &opts, &task).unwrap();
7433 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
7434 assert_eq!(
7435 before.merge.mode,
7436 MergeMode::None,
7437 "daemon --merge must not leak"
7438 );
7439 for n in [2, 1, 2] {
7440 task.set_implementers(n, &validation).unwrap();
7441 q.put(&mut task).unwrap();
7442 task = q.get(&task.id).unwrap();
7443 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
7444 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
7445 apply_task_implementers(&mut cfg, &task);
7446 assert_eq!(cfg.graph.implementers, usize::from(n));
7447 assert_eq!(cfg.graph.judges, 2);
7448 assert_eq!(cfg.merge.mode, MergeMode::None);
7449 }
7450 }
7451 }
7452
7453 #[test]
7454 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
7455 let cfg: Config =
7456 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7457 .unwrap();
7458 let mut t = task();
7459 t.review_of = Some("review-target".into());
7460 t.hold_manual(Some("retry".into()));
7461 let mut previous = RunState::new(
7462 PathBuf::from("/repo"),
7463 "main".into(),
7464 "abc1234".into(),
7465 "review".into(),
7466 cfg.clone(),
7467 );
7468 previous.config.graph.implementers = 2;
7469 for count in [1, 3] {
7470 t.set_implementers(count, &cfg).unwrap();
7471 t.release();
7472 assert_eq!(t.review_of.as_deref(), Some("review-target"));
7473 for proposed in [
7474 Starter::Resume(previous.id.clone()),
7475 Starter::Review("recovery-target".into()),
7476 ] {
7477 assert_eq!(
7478 starter_with_implementers(&t, Some(&previous), proposed),
7479 Starter::Review("review-target".into())
7480 );
7481 }
7482 let mut configured = cfg.clone();
7483 apply_task_implementers(&mut configured, &t);
7484 assert_eq!(configured.graph.implementers, usize::from(count));
7485 assert_eq!(previous.config.graph.implementers, 2);
7486 }
7487 }
7488
7489 #[test]
7490 fn task_implementers_dispatch_and_resume_agree() {
7491 let mut t = task();
7492 let cfg: crate::config::Config =
7493 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7494 .unwrap();
7495 let mut run = RunState::new(
7496 PathBuf::from("/repo"),
7497 "main".into(),
7498 "abc1234".into(),
7499 "work".into(),
7500 cfg.clone(),
7501 );
7502 run.config.graph.implementers = 2;
7503 for n in [2, 1, 3, 2] {
7504 t.set_implementers(n, &cfg).unwrap();
7505 let mut dispatched = cfg.clone();
7506 apply_task_implementers(&mut dispatched, &t);
7507 assert_eq!(dispatched.graph.implementers, usize::from(n));
7508 assert_eq!(implementers_match(&t, &run), n == 2);
7509 for proposed in [
7510 Starter::Resume(run.id.clone()),
7511 Starter::Review("old-branch".into()),
7512 ] {
7513 let expected = if n == 2 {
7514 proposed.clone()
7515 } else {
7516 Starter::Start
7517 };
7518 assert_eq!(
7519 starter_with_implementers(&t, Some(&run), proposed),
7520 expected
7521 );
7522 }
7523 assert_eq!(
7524 run.config.graph.implementers, 2,
7525 "history must not be rewritten"
7526 );
7527 }
7528 t.solo = false;
7529 t.overrides = None;
7530 assert!(implementers_match(&t, &run));
7531 }
7532
7533 #[test]
7534 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
7535 let mut solo_cfg = Config::default();
7541 solo_cfg.graph.implementers = 3;
7542 let mut solo_task = task();
7543 solo_task.solo = true;
7544 apply_task_implementers(&mut solo_cfg, &solo_task);
7545 assert_eq!(solo_cfg.graph.implementers, 1);
7546
7547 let mut plain_cfg = Config::default();
7548 plain_cfg.graph.implementers = 3;
7549 let plain_task = task();
7550 assert!(!plain_task.solo);
7551 apply_task_implementers(&mut plain_cfg, &plain_task);
7552 assert_eq!(
7553 plain_cfg.graph.implementers, 3,
7554 "a task that did not ask to run alone keeps the config's candidates"
7555 );
7556 }
7557
7558 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
7559 QuotaLoss {
7560 seat: seat.into(),
7561 node: "judge".into(),
7562 at: at.parse().unwrap(),
7563 reset: reset.map(str::to_string),
7564 }
7565 }
7566
7567 #[test]
7568 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
7569 let old: Vec<QuotaLoss> = (1..=4)
7570 .map(|i| {
7571 loss(
7572 &format!("judge-{i}"),
7573 "2026-09-23T05:23:00Z",
7574 Some("2:40pm (Asia/Tokyo)"),
7575 )
7576 })
7577 .collect();
7578 let fresh = losses_this_attempt(&old, &old);
7579 assert!(fresh.is_empty());
7580 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
7581 }
7583
7584 #[test]
7585 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
7586 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
7587 let now = Timestamp::now();
7588 let mut after = old.clone();
7589 after.push(loss("judge-2", &now.to_string(), None));
7590 let fresh = losses_this_attempt(&old, &after);
7591 assert_eq!(fresh, vec![after[1].clone()]);
7592 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
7593 assert_eq!(
7594 until,
7595 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
7596 );
7597 }
7598
7599 #[test]
7600 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
7601 let before = vec![
7604 loss("judge-1", "2026-09-23T05:23:00Z", None),
7605 loss("judge-2", "2026-09-23T05:24:00Z", None),
7606 ];
7607 let after = vec![
7608 loss("judge-2", "2026-09-23T05:24:00Z", None),
7609 loss("judge-1", "2026-09-24T01:00:00Z", None),
7610 ];
7611 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
7612 }
7613
7614 #[test]
7615 fn merge_overrides_are_parsed_or_refused() {
7616 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
7617 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
7618 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
7619 assert!(merge_mode("squash").is_err());
7620 }
7621
7622 #[test]
7623 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
7624 let now = Timestamp::now();
7625 let fallback = Duration::from_secs(300);
7626 let cap = Duration::from_secs(1800);
7627
7628 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
7630
7631 let soon = now + jiff::SignedDuration::from_secs(600);
7633 assert_eq!(
7634 quota_wait(Some(soon), now, fallback, cap),
7635 Duration::from_secs(600)
7636 );
7637
7638 let past = now - jiff::SignedDuration::from_secs(60);
7641 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
7642
7643 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
7646 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
7647 }
7648
7649 #[test]
7650 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
7651 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7652
7653 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
7654 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
7655
7656 let already_past =
7660 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
7661 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
7662
7663 assert!(
7664 parse_reset_hint("session limit reached", now, now).is_none(),
7665 "free text with no recognised shape is not guessed at"
7666 );
7667 assert!(
7668 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
7669 "an unresolvable zone name is not guessed at either"
7670 );
7671 }
7672
7673 #[test]
7674 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
7675 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7676
7677 let at = parse_reset_hint(
7678 "You've hit your usage limit. Visit \
7679 https://chatgpt.com/codex/settings/usage to purchase more \
7680 credits or try again at Sep 19th, 2026 5:10 PM.",
7681 now,
7682 now,
7683 )
7684 .expect("the codex reset wording is a recognised shape");
7685 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
7686
7687 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
7692 .expect("an explicit year needs no rollover");
7693 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
7694
7695 assert!(
7696 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
7697 "a two-digit year is not the documented shape and is not guessed at"
7698 );
7699 assert!(
7700 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
7701 "a four-letter month name is not the documented three-letter abbreviation"
7702 );
7703 assert!(
7704 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
7705 "an explicit zone on the dated shape is a format nobody has \
7706 documented, and is refused rather than guessed at as UTC"
7707 );
7708 }
7709
7710 #[test]
7711 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
7712 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
7713 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
7714
7715 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
7716 assert_eq!(at.as_second() - recorded.as_second(), 3769);
7717
7718 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
7719 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
7720
7721 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
7722 assert!(
7723 parse_reset_hint(bad, now, recorded).is_none(),
7724 "{bad:?} must not be guessed at"
7725 );
7726 }
7727 }
7728
7729 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
7733 let config = dir.join("magi.toml");
7734 std::fs::write(
7735 &config,
7736 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
7737 )
7738 .unwrap();
7739 let opts = Opts {
7740 poll: Duration::from_secs(30),
7741 config: Some(config),
7742 repo: dir.join("repo"),
7746 ..Opts::default()
7747 };
7748 let home = dir.join("home");
7757 let worktrees = dir.join("wt");
7758 (
7759 opts,
7760 Queue::at(dir.join("queue")),
7761 home.join("daemon.json"),
7762 home,
7763 worktrees,
7764 )
7765 }
7766
7767 #[test]
7768 fn a_stop_is_idempotent_and_once_set_stays_set() {
7769 let stop = Stop::new();
7770 assert!(!stop.stopped());
7771
7772 stop.stop();
7773 assert!(stop.stopped());
7774 stop.stop();
7775 assert!(stop.stopped(), "a second stop is not a toggle");
7776
7777 let shared = stop.clone();
7778 assert!(
7779 shared.stopped(),
7780 "a clone is the same stop; that is how the loop and its caller share one"
7781 );
7782 }
7783
7784 #[test]
7785 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
7786 let stop = Stop::new();
7787 stop.enter();
7788 assert!(
7789 !stop.finishing(),
7790 "a busy loop nobody has asked to stop is just running"
7791 );
7792
7793 stop.stop();
7794 assert!(
7795 stop.finishing(),
7796 "a stop asked for mid-run has not landed until the run is settled"
7797 );
7798
7799 stop.exit();
7800 assert!(
7801 !stop.finishing(),
7802 "once the run is settled the stop has landed and there is nothing to finish"
7803 );
7804 }
7805
7806 #[test]
7807 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
7808 let stop = Stop::new();
7809 stop.enter();
7810 stop.enter();
7811 stop.stop();
7812 assert!(stop.finishing(), "two runs still in flight");
7813
7814 stop.exit();
7815 assert!(
7816 stop.finishing(),
7817 "one run finished, but a sibling is still working"
7818 );
7819
7820 stop.exit();
7821 assert!(
7822 !stop.finishing(),
7823 "the last run out is what actually lands the stop"
7824 );
7825 }
7826
7827 #[tokio::test]
7828 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
7829 let dir = tempfile::tempdir().unwrap();
7830 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7831 let stop = Stop::new();
7832 stop.stop();
7833
7834 let began = std::time::Instant::now();
7835 tokio::time::timeout(
7836 Duration::from_secs(2),
7837 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7838 )
7839 .await
7840 .expect("a stopped loop must return, not sit out its poll interval")
7841 .expect("the loop's own setup and teardown must not fail");
7842 assert!(
7843 began.elapsed() < opts.poll,
7844 "returned only after {:?}, which is a poll interval, not a stop",
7845 began.elapsed()
7846 );
7847 }
7848
7849 #[tokio::test]
7850 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
7851 let dir = tempfile::tempdir().unwrap();
7852 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7853 let stop = Stop::new();
7854
7855 let asker = {
7858 let stop = stop.clone();
7859 tokio::spawn(async move {
7860 tokio::time::sleep(Duration::from_millis(20)).await;
7861 stop.stop();
7862 })
7863 };
7864
7865 let began = std::time::Instant::now();
7866 tokio::time::timeout(
7867 Duration::from_secs(2),
7868 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7869 )
7870 .await
7871 .expect("a stop asked for while idle must wake the wait")
7872 .expect("the loop's own setup and teardown must not fail");
7873 asker.await.unwrap();
7874 assert!(
7875 began.elapsed() < opts.poll,
7876 "returned only after {:?}, so the stop waited on the sleep",
7877 began.elapsed()
7878 );
7879 }
7880
7881 #[tokio::test]
7882 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
7883 let dir = tempfile::tempdir().unwrap();
7884 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7885 let stop = Stop::new();
7886 stop.stop();
7887
7888 tokio::time::timeout(
7889 Duration::from_secs(2),
7890 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7891 )
7892 .await
7893 .expect("a stopped loop must return")
7894 .expect("the loop's own setup and teardown must not fail");
7895
7896 assert!(
7897 home.is_dir(),
7898 "the loop did publish a status file, so its removal is the teardown and not an absence"
7899 );
7900 assert!(
7901 !status_file.exists(),
7902 "a stopped loop clears its status file"
7903 );
7904 assert!(
7905 read_status(&home).is_none(),
7906 "a reader must see no daemon at all, not a heartbeat that merely stopped"
7907 );
7908 }
7909
7910 #[tokio::test]
7911 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
7912 let dir = tempfile::tempdir().unwrap();
7913 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7914 opts.once = true;
7915
7916 let mut settled = RunState::new(
7917 dir.path().join("repo"),
7918 "main".to_owned(),
7919 "abc1234".to_owned(),
7920 "fixture".to_owned(),
7921 Config::default(),
7922 );
7923 settled.status = RunStatus::Ready;
7924 let run_dir = home.join("runs").join(&settled.id);
7925 std::fs::create_dir_all(&run_dir).unwrap();
7926 std::fs::write(
7927 run_dir.join("run.json"),
7928 serde_json::to_string_pretty(&settled).unwrap(),
7929 )
7930 .unwrap();
7931 let questions = Questions::at(home.join("questions"));
7932 let mut question = ask::Question::new(
7933 settled.id.clone(),
7934 "review".to_owned(),
7935 "reviewer-1".to_owned(),
7936 "Continue?".to_owned(),
7937 String::new(),
7938 Vec::new(),
7939 );
7940 questions.put(&mut question).unwrap();
7941
7942 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
7943 .await
7944 .unwrap();
7945
7946 assert_eq!(
7947 questions.get(&question.id).unwrap().status,
7948 ask::QuestionStatus::Abandoned,
7949 "an empty --once drain still performs startup question cleanup"
7950 );
7951 }
7952
7953 #[test]
7954 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
7955 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7956
7957 assert!(
7958 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
7959 "never checked before: due at once"
7960 );
7961
7962 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
7963 assert!(
7964 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
7965 "well inside the interval: not due yet"
7966 );
7967
7968 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
7969 assert!(
7970 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
7971 "exactly at the edge: not yet due, same convention as `clean::due`"
7972 );
7973
7974 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7975 assert!(
7976 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
7977 "past the interval: due again"
7978 );
7979 }
7980
7981 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
7986 let config = dir.join("magi.toml");
7987 std::fs::write(
7993 &config,
7994 format!(
7995 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7996 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7997 cache_dir.display()
7998 ),
7999 )
8000 .unwrap();
8001 Opts {
8002 config: Some(config),
8003 repo: dir.join("repo"),
8004 ..Opts::default()
8005 }
8006 }
8007
8008 #[tokio::test]
8009 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8010 let dir = tempfile::tempdir().unwrap();
8011 let home = dir.path().join("home");
8012 let cache_dir = dir.path().join("cache");
8013 std::fs::create_dir_all(&cache_dir).unwrap();
8014 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8015 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8016
8017 let running = Stop::new();
8020 let mut last_checked = None;
8021 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8022 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
8023 .await;
8024 assert_eq!(
8025 crate::disk::dir_size(&cache_dir),
8026 0,
8027 "over the cap on the first check ever: pruned at once, no idle queue required"
8028 );
8029 assert_eq!(last_checked, Some(t0));
8030
8031 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
8033 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
8034 maybe_prune_cache_between_runs(
8035 &opts.repo,
8036 &opts,
8037 &home,
8038 &running,
8039 &mut last_checked,
8040 too_soon,
8041 )
8042 .await;
8043 assert_eq!(
8044 crate::disk::dir_size(&cache_dir),
8045 10,
8046 "too soon since the last check: left alone rather than rescanned every call"
8047 );
8048 assert_eq!(
8049 last_checked,
8050 Some(t0),
8051 "an idle check does not reset the clock"
8052 );
8053
8054 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8056 maybe_prune_cache_between_runs(
8057 &opts.repo,
8058 &opts,
8059 &home,
8060 &running,
8061 &mut last_checked,
8062 due_again,
8063 )
8064 .await;
8065 assert_eq!(
8066 crate::disk::dir_size(&cache_dir),
8067 0,
8068 "due again: pruned back under the cap"
8069 );
8070 }
8071
8072 #[tokio::test]
8080 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
8081 let dir = tempfile::tempdir().unwrap();
8082 let home = dir.path().join("home");
8083 let cache_dir = dir.path().join("cache");
8084 std::fs::create_dir_all(&cache_dir).unwrap();
8085 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8086 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8087
8088 let stop = Stop::new();
8089 stop.stop();
8090 assert!(
8091 !stop.finishing(),
8092 "no run is in flight at a between-runs boundary, so nothing else \
8093 would tell the operator this stop had not taken effect yet"
8094 );
8095
8096 let mut last_checked = None;
8097 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8098 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
8099 .await;
8100 assert_eq!(
8101 crate::disk::dir_size(&cache_dir),
8102 10,
8103 "over its cap, and due for the first check ever, but a stop outranks \
8104 it: the cap is a standing policy the next start measures again"
8105 );
8106 assert_eq!(
8107 last_checked, None,
8108 "a check that never happened must not claim the interval"
8109 );
8110 }
8111
8112 #[tokio::test]
8123 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
8124 let dir = tempfile::tempdir().unwrap();
8125 let cache_dir = dir.path().join("cache");
8126 std::fs::create_dir_all(&cache_dir).unwrap();
8127 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
8128
8129 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
8130 opts.poll = Duration::from_millis(20);
8131 opts.max_attempts = 1_000;
8132
8133 let queue = Queue::at(dir.path().join("queue"));
8134 for i in 0..128 {
8135 let mut task = Task::new(
8136 format!("queued work {i}"),
8137 format!("queued work {i}"),
8138 opts.repo.clone(),
8139 Source::Human,
8140 );
8141 queue.put(&mut task).unwrap();
8142 }
8143
8144 let home = dir.path().join("home");
8145 let worktrees = dir.path().join("wt");
8146 let status_file = home.join("daemon.json");
8147 let stop = Stop::new();
8148 let stopper = {
8149 let stop = stop.clone();
8150 let queue = Queue::at(dir.path().join("queue"));
8151 tokio::spawn(async move {
8152 for _ in 0..2_000 {
8156 if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
8157 break;
8158 }
8159 tokio::time::sleep(Duration::from_millis(5)).await;
8160 }
8161 stop.stop();
8162 })
8163 };
8164
8165 tokio::time::timeout(
8166 Duration::from_secs(20),
8167 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8168 )
8169 .await
8170 .expect("the loop must not hang on a queue that keeps producing failing work")
8171 .expect("the loop's own setup and teardown must not fail");
8172 stopper.await.unwrap();
8173
8174 let after = queue.list();
8175 let completed = after.iter().filter(|t| t.attempts == 1).count();
8176 assert!(
8177 completed >= 2,
8178 "the harness must have processed multiple tasks to exercise a busy queue \
8179 (got {completed} completed task(s))"
8180 );
8181 assert!(
8182 after.iter().any(|t| t.status.runnable()),
8183 "unprocessed tasks must remain: the external stop, rather than an \
8184 exhausted backlog, must end the test"
8185 );
8186 assert!(
8187 after
8188 .iter()
8189 .filter(|t| t.attempts > 0)
8190 .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
8191 "a busy backlog must not retry a task's unchanged startup failure"
8192 );
8193
8194 assert_eq!(
8195 crate::disk::dir_size(&cache_dir),
8196 0,
8197 "an oversized cache must not be left to grow unboundedly just because the \
8198 queue kept the loop busy the whole time"
8199 );
8200 }
8201
8202 #[test]
8203 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
8204 let dir = tempfile::tempdir().unwrap();
8205 let queue = Queue::at(dir.path().join("queue"));
8206 let questions = Questions::at(dir.path().join("questions"));
8207 let mut task = task();
8208 queue.put(&mut task).unwrap();
8209
8210 let mut task_question = ask::Question::new(
8211 task.id.clone(),
8212 crate::conduct::NODE.to_owned(),
8213 "conduct".to_owned(),
8214 "Which backend?".to_owned(),
8215 String::new(),
8216 Vec::new(),
8217 );
8218 questions.put(&mut task_question).unwrap();
8219 task.block(vec![task_question.id.clone()], None);
8220 queue.put(&mut task).unwrap();
8221
8222 let mut run_question = ask::Question::new(
8223 "20260101-000000-run1".to_owned(),
8224 "review".to_owned(),
8225 "reviewer-1".to_owned(),
8226 "Run question".to_owned(),
8227 String::new(),
8228 Vec::new(),
8229 );
8230 questions.put(&mut run_question).unwrap();
8231
8232 let mut coincidental = ask::Question::new(
8237 task.id.clone(),
8238 "review".to_owned(),
8239 "reviewer-1".to_owned(),
8240 "Unrelated review question".to_owned(),
8241 String::new(),
8242 Vec::new(),
8243 );
8244 questions.put(&mut coincidental).unwrap();
8245
8246 reconcile_task_questions(&queue, &questions);
8247 assert!(questions.get(&task_question.id).unwrap().status.open());
8248 assert!(questions.get(&run_question.id).unwrap().status.open());
8249 assert!(questions.get(&coincidental.id).unwrap().status.open());
8250
8251 task.release();
8252 queue.put(&mut task).unwrap();
8253 reconcile_task_questions(&queue, &questions);
8254 assert_eq!(
8255 questions.get(&task_question.id).unwrap().status,
8256 ask::QuestionStatus::Abandoned
8257 );
8258 assert!(
8259 questions.get(&run_question.id).unwrap().status.open(),
8260 "run questions remain the run janitor's responsibility"
8261 );
8262 assert!(
8263 questions.get(&coincidental.id).unwrap().status.open(),
8264 "a non-conductor question must not be abandoned just because its \
8265 run id coincides with a task id"
8266 );
8267 }
8268
8269 #[test]
8270 fn a_freshly_started_running_task_is_never_stalled() {
8271 let dir = tempfile::tempdir().unwrap();
8272 let mut t = task();
8273 t.start("run-1".to_owned());
8274 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
8277 }
8278
8279 #[test]
8280 fn a_long_running_task_with_no_live_daemon_is_stalled() {
8281 let dir = tempfile::tempdir().unwrap();
8282 let mut t = task();
8283 t.start("run-1".to_owned());
8284 t.updated_at = Timestamp::now()
8285 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8286 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
8287 assert_eq!(
8288 stalled_tasks(
8289 &Queue::at(dir.path().join("q")),
8290 dir.path(),
8291 Timestamp::now()
8292 )
8293 .len(),
8294 0,
8295 "the task was never written to this queue"
8296 );
8297 }
8298
8299 #[test]
8300 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
8301 let dir = tempfile::tempdir().unwrap();
8302 let mut t = task();
8303 t.id = "20260903-080340-0167".to_owned();
8304 t.start("20260903-080619-01c2".to_owned());
8305 t.updated_at = Timestamp::now()
8306 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8307
8308 let mut status = Status::new();
8309 status.current = vec![Current {
8310 task: t.id.clone(),
8311 run: "20260903-080619-01c2".to_owned(),
8312 }];
8313 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8314
8315 assert!(
8316 !is_stalled(&t, dir.path(), Timestamp::now()),
8317 "a live daemon's own heartbeat rules out stalled, however long the task has run"
8318 );
8319 }
8320
8321 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
8325 let path = queue.path_of(id);
8326 let body = std::fs::read_to_string(&path).unwrap();
8327 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
8328 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
8329 v["updated_at"] = serde_json::Value::String(old.to_string());
8330 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
8331 }
8332
8333 #[test]
8334 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
8335 let dir = tempfile::tempdir().unwrap();
8348 let queue = Queue::at(dir.path().join("queue"));
8349 let home = dir.path().join("home");
8350
8351 let mut t = task();
8352 t.id = "20260101-000001-lock".to_owned();
8353 t.start("run-1".to_owned());
8354 queue.put(&mut t).unwrap();
8355 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8356 std::fs::write(
8357 dir.path().join("queue").join(format!("{}.lock", t.id)),
8358 "not a pid",
8359 )
8360 .unwrap();
8361
8362 let now = Timestamp::now();
8363 assert!(
8364 reclaim_orphaned_running(&queue, 2).is_empty(),
8365 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
8366 and reclaim must leave the task alone"
8367 );
8368 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8369
8370 let stalled = stalled_tasks(&queue, &home, now);
8371 assert_eq!(
8372 stalled.len(),
8373 1,
8374 "reclaim's inability to claim it yet must not hide it from the conductor"
8375 );
8376 assert_eq!(stalled[0].id, t.id);
8377 }
8378
8379 #[test]
8380 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
8381 let dir = tempfile::tempdir().unwrap();
8382 crate::run::set_home(dir.path().join("run-home"));
8383 let queue = Queue::at(dir.path().join("queue"));
8384 let home = dir.path().join("home");
8385 let questions = Questions::at(dir.path().join("questions"));
8386
8387 let mut t = task();
8388 t.id = "20260101-000003-dead".to_owned();
8389 t.start("missing-run".to_owned());
8390 queue.put(&mut t).unwrap();
8391 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8392
8393 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8396 assert_eq!(
8397 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
8398 [&t.id]
8399 );
8400 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
8401 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8402
8403 crate::conduct::apply(
8406 &queue,
8407 &questions,
8408 &crate::conduct::Verdict {
8409 decisions: vec![crate::conduct::Decision {
8410 id: t.id.clone(),
8411 recovery: Some(crate::conduct::Recovery::Requeue),
8412 ..crate::conduct::Decision::default()
8413 }],
8414 },
8415 )
8416 .unwrap();
8417 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8418 }
8419
8420 #[test]
8421 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
8422 let dir = tempfile::tempdir().unwrap();
8423 let queue = Queue::at(dir.path().join("queue"));
8424 let home = dir.path().join("home");
8425
8426 let mut fresh = task();
8427 fresh.id = "20260101-000001-aaaa".to_owned();
8428 fresh.start("run-1".to_owned());
8429 queue.put(&mut fresh).unwrap();
8430
8431 let mut old = task();
8432 old.id = "20260101-000002-bbbb".to_owned();
8433 old.start("run-2".to_owned());
8434 queue.put(&mut old).unwrap();
8435 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
8436
8437 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8438 assert_eq!(stalled.len(), 1);
8439 assert_eq!(stalled[0].id, old.id);
8440 }
8441
8442 #[test]
8443 fn queued_and_finished_task_views_partition_by_status() {
8444 let dir = tempfile::tempdir().unwrap();
8445 let queue = Queue::at(dir.path().join("queue"));
8446
8447 let mut queued = task();
8448 queued.id = "20260101-000001-aaaa".to_owned();
8449 queue.put(&mut queued).unwrap();
8450
8451 let mut failed = task();
8452 failed.id = "20260101-000002-bbbb".to_owned();
8453 failed.start("run-1".to_owned());
8454 failed.fail("gate red", 5);
8455 queue.put(&mut failed).unwrap();
8456
8457 let mut held = task();
8458 held.id = "20260101-000003-cccc".to_owned();
8459 held.hold_machine(None);
8460 queue.put(&mut held).unwrap();
8461
8462 let mut running = task();
8463 running.id = "20260101-000004-dddd".to_owned();
8464 running.start("run-2".to_owned());
8465 queue.put(&mut running).unwrap();
8466
8467 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
8468 assert_eq!(queued_ids, [queued.id.clone()]);
8469
8470 let mut finished_ids: Vec<String> =
8471 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
8472 finished_ids.sort_unstable();
8473 let mut want = vec![failed.id.clone(), held.id.clone()];
8474 want.sort_unstable();
8475 assert_eq!(finished_ids, want);
8476 }
8477
8478 #[test]
8479 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
8480 let dir = tempfile::tempdir().unwrap();
8481 let queue = Queue::at(dir.path().join("queue"));
8482 let questions = ask::Questions::at(dir.path().join("questions"));
8483
8484 let mut dep = task();
8485 dep.id = "20260101-000001-dep0".to_owned();
8486 dep.succeed();
8487 queue.put(&mut dep).unwrap();
8488
8489 let mut still_going = task();
8490 still_going.id = "20260101-000002-dep1".to_owned();
8491 queue.put(&mut still_going).unwrap();
8492
8493 let mut blocked = task();
8494 blocked.id = "20260101-000003-main".to_owned();
8495 blocked.block(
8496 vec![dep.id.clone(), still_going.id.clone()],
8497 Some("waits on both".to_owned()),
8498 );
8499 queue.put(&mut blocked).unwrap();
8500
8501 resolve_blockers(&queue, &questions);
8502
8503 let after = queue.get(&blocked.id).unwrap();
8504 assert_eq!(
8505 after.status,
8506 TaskStatus::Blocked,
8507 "one dependency is still outstanding"
8508 );
8509 assert_eq!(after.blocked_by, [still_going.id.clone()]);
8510 }
8511
8512 #[test]
8513 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
8514 let dir = tempfile::tempdir().unwrap();
8515 let queue = Queue::at(dir.path().join("queue"));
8516 let questions = ask::Questions::at(dir.path().join("questions"));
8517
8518 let mut q = crate::ask::Question::new(
8519 "20260101-000001-main".to_owned(),
8520 crate::conduct::NODE.to_owned(),
8521 "conduct".to_owned(),
8522 "Which backend?".to_owned(),
8523 String::new(),
8524 Vec::new(),
8525 );
8526 questions.put(&mut q).unwrap();
8527 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
8528 .unwrap();
8529 questions.put(&mut q).unwrap();
8530
8531 let mut blocked = task();
8532 blocked.id = "20260101-000001-main".to_owned();
8533 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
8534 queue.put(&mut blocked).unwrap();
8535
8536 resolve_blockers(&queue, &questions);
8537
8538 let after = queue.get(&blocked.id).unwrap();
8539 assert_eq!(
8540 after.status,
8541 TaskStatus::Queued,
8542 "the only blocker resolved"
8543 );
8544 assert_eq!(after.answers.len(), 1);
8545 assert_eq!(after.answers[0].question, "Which backend?");
8546 assert_eq!(after.answers[0].answer, "SQLite");
8547
8548 let instruction = instruction_for(&after);
8550 assert!(instruction.contains("Which backend?"));
8551 assert!(instruction.contains("SQLite"));
8552 }
8553
8554 #[test]
8555 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
8556 let dir = tempfile::tempdir().unwrap();
8557 let queue = Queue::at(dir.path().join("queue"));
8558 let questions = ask::Questions::at(dir.path().join("questions"));
8559
8560 let mut q = crate::ask::Question::new(
8561 "20260101-000001-main".to_owned(),
8562 crate::conduct::NODE.to_owned(),
8563 "conduct".to_owned(),
8564 "Is the setup done?".to_owned(),
8565 String::new(),
8566 Vec::new(),
8567 );
8568 q.abandon("no answer within 60s of asking");
8569 questions.put(&mut q).unwrap();
8570
8571 let mut blocked = task();
8572 blocked.id = "20260101-000001-main".to_owned();
8573 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
8574 queue.put(&mut blocked).unwrap();
8575
8576 resolve_blockers(&queue, &questions);
8577
8578 let after = queue.get(&blocked.id).unwrap();
8579 assert_eq!(
8580 after.status,
8581 TaskStatus::Held,
8582 "never left blocked on nothing"
8583 );
8584 assert!(!after.operator_held(), "a machine hold, for triage");
8585 assert!(
8586 after
8587 .hold_reason
8588 .as_deref()
8589 .unwrap_or_default()
8590 .contains("went unanswered")
8591 );
8592 }
8593
8594 #[test]
8595 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
8596 let dir = tempfile::tempdir().unwrap();
8602 let queue = Queue::at(dir.path().join("queue"));
8603 let questions = ask::Questions::at(dir.path().join("questions"));
8604
8605 let mut q = crate::ask::Question::new(
8606 "20260101-000001-main".to_owned(),
8607 crate::conduct::NODE.to_owned(),
8608 "conduct".to_owned(),
8609 "How should this be handled?".to_owned(),
8610 String::new(),
8611 Vec::new(),
8612 );
8613 questions.put(&mut q).unwrap();
8614 q.answer(crate::ask::Answer::Text(
8615 "leave it held, a human will look at it later".to_owned(),
8616 ))
8617 .unwrap();
8618 questions.put(&mut q).unwrap();
8619
8620 let mut held = task();
8621 held.id = "20260101-000001-main".to_owned();
8622 held.hold_machine(Some("out of attempts".to_owned()));
8623 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
8624 queue.put(&mut held).unwrap();
8625
8626 resolve_blockers(&queue, &questions);
8627
8628 let after = queue.get(&held.id).unwrap();
8629 assert_eq!(after.status, TaskStatus::Held);
8630 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
8631 assert_eq!(
8632 after.answers[0].answer,
8633 "leave it held, a human will look at it later"
8634 );
8635 }
8636
8637 #[test]
8638 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
8639 let dir = tempfile::tempdir().unwrap();
8640 let queue = Queue::at(dir.path().join("queue"));
8641 let questions = ask::Questions::at(dir.path().join("questions"));
8642 let mut dep = task();
8643 dep.id = "20260101-000001-gone".to_owned();
8644 queue.put(&mut dep).unwrap();
8645 let mut blocked = task();
8646 blocked.id = "20260101-000003-main".to_owned();
8647 blocked.block(vec![dep.id.clone()], None);
8648 queue.put(&mut blocked).unwrap();
8649
8650 let claim = queue.claim(&blocked.id).unwrap();
8652 queue.remove(&dep.id, false, &questions).unwrap();
8653 drop(claim);
8654 resolve_blockers(&queue, &questions);
8655
8656 let after = queue.get(&blocked.id).unwrap();
8657 assert_eq!(after.status, TaskStatus::Queued);
8658 assert!(after.blocked_by.is_empty());
8659 }
8660
8661 #[test]
8662 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
8663 let dir = tempfile::tempdir().unwrap();
8669 let queue = Queue::at(dir.path().join("queue"));
8670 let questions = ask::Questions::at(dir.path().join("questions"));
8671
8672 let mut still_going = task();
8673 still_going.id = "20260101-000002-dep1".to_owned();
8674 queue.put(&mut still_going).unwrap();
8675
8676 let mut blocked = task();
8677 blocked.id = "20260101-000003-main".to_owned();
8678 blocked.block(
8679 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
8680 Some("waits on both".to_owned()),
8681 );
8682 queue.put(&mut blocked).unwrap();
8683
8684 resolve_blockers(&queue, &questions);
8685
8686 let after = queue.get(&blocked.id).unwrap();
8687 assert_eq!(
8688 after.status,
8689 TaskStatus::Held,
8690 "a missing dependency must not leave the task blocked forever"
8691 );
8692 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
8693 assert!(after.blocked_by.is_empty());
8694 let reason = after.hold_reason.as_deref().unwrap_or_default();
8695 assert!(
8696 reason.contains("20260101-000001-gone"),
8697 "the missing id must be named so an operator can tell what happened: {reason}"
8698 );
8699 assert!(
8700 reason.contains(&still_going.id),
8701 "the still-valid dependency must not silently vanish from the record: {reason}"
8702 );
8703 }
8704
8705 #[test]
8706 fn instruction_for_is_unchanged_without_any_answers() {
8707 let t = task();
8708 assert_eq!(instruction_for(&t), t.instruction);
8709 }
8710
8711 #[test]
8712 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
8713 let dir = tempfile::tempdir().unwrap();
8714 let q = Queue::at(dir.path().join("queue"));
8715 let src = dir.path().join("shot.png");
8716 std::fs::write(&src, "x").unwrap();
8717 let mut t = task();
8718 q.attach(&mut t, &[src]).unwrap();
8719 let paths = task_attachments(&q, &t).unwrap();
8720 assert_eq!(paths.len(), 1);
8721 assert!(paths[0].is_absolute() && paths[0].is_file());
8722 std::fs::remove_file(&paths[0]).unwrap();
8723 let err = task_attachments(&q, &t).unwrap_err().to_string();
8724 assert!(err.contains("shot.png"), "{err}");
8725 }
8726
8727 #[test]
8728 fn resumed_instruction_is_unchanged_without_any_answers() {
8729 let t = task();
8730 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
8731 }
8732
8733 #[test]
8734 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
8735 let mut t = task();
8736 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8737 let old = t.instruction.clone();
8741
8742 let refreshed = resumed_instruction(&old, &t);
8743 assert!(refreshed.starts_with(&old), "the original text is kept");
8744 assert!(refreshed.contains("Which backend?"));
8745 assert!(refreshed.contains("SQLite"));
8746 }
8747
8748 #[test]
8749 fn resumed_instruction_keeps_an_original_answers_heading() {
8750 let mut t = task();
8751 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
8752 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8753
8754 let refreshed = resumed_instruction(&t.instruction, &t);
8755
8756 assert!(
8757 refreshed.starts_with(&t.instruction),
8758 "an answers heading in the original instruction is not the appended block"
8759 );
8760 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
8761 assert!(refreshed.contains("Which backend?"));
8762 assert!(refreshed.contains("SQLite"));
8763
8764 let repeated = resumed_instruction(&refreshed, &t);
8765 assert_eq!(
8766 repeated, refreshed,
8767 "only the final appended block is refreshed"
8768 );
8769 }
8770
8771 #[test]
8772 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
8773 let mut t = task();
8774 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8775
8776 let once = resumed_instruction(&t.instruction, &t);
8780 let twice = resumed_instruction(&once, &t);
8781 assert_eq!(once, twice);
8782 assert_eq!(once.matches("Which backend?").count(), 1);
8783
8784 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
8786 let refreshed = resumed_instruction(&once, &t);
8787 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
8788 assert!(refreshed.contains("Which backend?"));
8789 assert!(refreshed.contains("Which cache?"));
8790 }
8791
8792 #[test]
8793 fn prepare_instruction_covers_all_three_starters() {
8794 let mut t = task();
8795 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8796
8797 assert_eq!(
8800 prepare_instruction(&Starter::Start, None, &t),
8801 Some(instruction_for(&t))
8802 );
8803
8804 let old = t.instruction.clone();
8807 assert_eq!(
8808 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
8809 Some(resumed_instruction(&old, &t))
8810 );
8811
8812 assert_eq!(
8816 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
8817 None
8818 );
8819 }
8820
8821 #[test]
8822 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
8823 assert_eq!(
8824 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
8825 Starter::Review("magi/eba2/A".to_owned())
8826 );
8827 }
8828
8829 #[test]
8830 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
8831 assert_eq!(
8832 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
8833 Starter::Start,
8834 "a vanished review branch must not fall back to resuming the old run either"
8835 );
8836 }
8837
8838 #[test]
8839 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
8840 let mut t = task();
8841 t.start("old-run".to_owned());
8842 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
8843 t.release();
8844 let branch = t.review_branch.take();
8845 assert_eq!(
8846 choose_starter(branch.as_deref(), true, Some("old-run")),
8847 Starter::Review("magi/eba2/A".to_owned()),
8848 "a review wins over resuming the old run"
8849 );
8850 }
8851
8852 #[test]
8853 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
8854 assert_eq!(
8855 choose_starter(None, false, Some("some-run")),
8856 Starter::Resume("some-run".to_owned())
8857 );
8858 assert_eq!(choose_starter(None, false, None), Starter::Start);
8859 }
8860
8861 #[test]
8862 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
8863 let mut released = task();
8864 released.start("stalled-run".to_owned());
8865 released.requeue();
8866 let unfinished = (!released.fresh_start)
8867 .then(|| Some("stalled-run".to_owned()))
8868 .flatten();
8869 assert_eq!(
8870 choose_starter(None, false, unfinished.as_deref()),
8871 Starter::Start,
8872 "release keeps run history but must not resume it"
8873 );
8874 assert_eq!(released.runs, ["stalled-run"]);
8875 }
8876
8877 #[test]
8878 fn an_ordinary_release_keeps_a_resumable_run_available() {
8879 let mut released = task();
8880 released.start("stalled-run".to_owned());
8881 released.release();
8882 let unfinished = (!released.fresh_start)
8883 .then(|| Some("stalled-run".to_owned()))
8884 .flatten();
8885 assert_eq!(
8886 choose_starter(None, false, unfinished.as_deref()),
8887 Starter::Resume("stalled-run".to_owned()),
8888 "manual release must preserve the normal resume path"
8889 );
8890 }
8891
8892 #[test]
8893 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
8894 let mut state = run_state(RunStatus::Blocked);
8895 state.config.graph.review_rounds = 3;
8896 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
8897 assert!(exhausted_review_budget(&state));
8898
8899 state.reviews.pop();
8901 assert!(!exhausted_review_budget(&state));
8902
8903 let mut stalled = run_state(RunStatus::Stalled);
8906 stalled.config.graph.review_rounds = 1;
8907 stalled.reviews = vec![review_round(1)];
8908 assert!(!exhausted_review_budget(&stalled));
8909 }
8910
8911 fn review_round(round: usize) -> crate::run::ReviewRound {
8912 crate::run::ReviewRound {
8913 round,
8914 head: "deadbeef".to_owned(),
8915 verified_head: None,
8916 verified_at: None,
8917 reviews: Vec::new(),
8918 e2e: Vec::new(),
8919 verify_retried: false,
8920 e2e_deferred: false,
8921 e2e_defer_reason: None,
8922 fix: None,
8923 blocking: 0,
8924 answered: 1,
8925 expected: 1,
8926 clean: false,
8927 progressed: true,
8928 vote_split: false,
8929 reconsideration: Vec::new(),
8930 verdict: None,
8931 }
8932 }
8933
8934 #[test]
8935 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
8936 let mut run = RunState::new(
8937 PathBuf::from("/repo"),
8938 "main".to_owned(),
8939 "abc1234def".to_owned(),
8940 "add retries".to_owned(),
8941 Config::default(),
8942 );
8943 run.status = RunStatus::Judging;
8944 run.parked = true;
8945 let mut task = Task::new(
8946 "add retries".to_owned(),
8947 "add retries".to_owned(),
8948 PathBuf::from("/repo"),
8949 crate::queue::Source::Human,
8950 );
8951 task.status = TaskStatus::Failed;
8952 task.runs = vec![run.id.clone()];
8953 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
8954 assert!(with(&task, &run), "parked after judging is the case");
8955 let mut parked_task = task.clone();
8956 parked_task.status = TaskStatus::Parked;
8957 assert!(with(&parked_task, &run), "the Parked status is the case");
8958
8959 let mut not_parked = run.clone();
8960 not_parked.parked = false;
8961 not_parked.status = RunStatus::Stalled;
8962 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
8963
8964 let mut fresh = task.clone();
8965 fresh.fresh_start = true;
8966 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
8967
8968 let mut review = task.clone();
8969 review.review_branch = Some("magi/x/A".to_owned());
8970 assert!(!with(&review, &run), "review is ranked before resume");
8971
8972 let mut held = task.clone();
8973 held.status = TaskStatus::Held;
8974 assert!(!with(&held, &run), "a hold stays visible to the conductor");
8975
8976 let mut released = run.clone();
8977 released.released_to = Some("20260901-000000-new1".to_owned());
8978 assert!(!with(&task, &released), "nothing left to resume into");
8979
8980 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
8981 "unreadable"
8982 )));
8983 }
8984
8985 #[test]
8986 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
8987 let mut released = RunState::new(
8988 PathBuf::from("/repo"),
8989 "main".to_owned(),
8990 "abc1234def".to_owned(),
8991 "add retries".to_owned(),
8992 Config::default(),
8993 );
8994 released.status = RunStatus::Blocked;
8995 assert_eq!(
8996 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8997 Some(released.id.clone())
8998 );
8999 released.released_to = Some("20260901-000000-new1".to_owned());
9000 assert_eq!(
9001 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9002 None,
9003 "there is nothing left to resume it into"
9004 );
9005 }
9006
9007 #[test]
9008 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
9009 let mut exhausted = RunState::new(
9018 PathBuf::from("/repo"),
9019 "main".to_owned(),
9020 "abc1234def".to_owned(),
9021 "add retries".to_owned(),
9022 Config::default(),
9023 );
9024 exhausted.status = RunStatus::Blocked;
9025 exhausted.config.graph.review_rounds = 1;
9026 exhausted.reviews = vec![review_round(1)];
9027
9028 assert_eq!(
9029 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
9030 None,
9031 "an exhausted `Blocked` run must not be offered as resumable"
9032 );
9033
9034 let mut has_budget_left = RunState::new(
9037 PathBuf::from("/repo"),
9038 "main".to_owned(),
9039 "abc1234def".to_owned(),
9040 "add retries".to_owned(),
9041 Config::default(),
9042 );
9043 has_budget_left.status = RunStatus::Blocked;
9044 has_budget_left.config.graph.review_rounds = 3;
9045 has_budget_left.reviews = vec![review_round(1)];
9046
9047 assert_eq!(
9048 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
9049 Ok(has_budget_left.clone())
9050 }),
9051 Some(has_budget_left.id.clone())
9052 );
9053 }
9054
9055 #[test]
9056 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
9057 let mut run = RunState::new(
9058 PathBuf::from("/repo"),
9059 "main".to_owned(),
9060 "abc1234def".to_owned(),
9061 "add retries".to_owned(),
9062 Config::default(),
9063 );
9064 run.status = RunStatus::Blocked;
9065 run.config.graph.review_rounds = 1;
9066 run.reviews = vec![review_round(1)];
9067 run.pr_publication_pending = true;
9068 assert_eq!(
9069 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
9070 Some(run.id.clone()),
9071 "a spent review budget must not turn a failed publication into a re-competition"
9072 );
9073 }
9074
9075 #[test]
9076 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
9077 let mut older_stalled = RunState::new(
9085 PathBuf::from("/repo"),
9086 "main".to_owned(),
9087 "abc1234def".to_owned(),
9088 "add retries".to_owned(),
9089 Config::default(),
9090 );
9091 older_stalled.status = RunStatus::Stalled;
9092
9093 let mut newest_exhausted = RunState::new(
9094 PathBuf::from("/repo"),
9095 "main".to_owned(),
9096 "abc1234def".to_owned(),
9097 "add retries".to_owned(),
9098 Config::default(),
9099 );
9100 newest_exhausted.status = RunStatus::Blocked;
9101 newest_exhausted.config.graph.review_rounds = 1;
9102 newest_exhausted.reviews = vec![review_round(1)];
9103
9104 assert_eq!(
9105 unfinished_run_with(
9106 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
9107 "t",
9108 |_| Ok(newest_exhausted.clone())
9109 ),
9110 None,
9111 "the newest run is exhausted, so nothing here is worth resuming - \
9112 least of all the older, already-superseded run"
9113 );
9114 }
9115
9116 #[test]
9117 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
9118 assert_eq!(
9119 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
9120 Err(anyhow::anyhow!("fixture is absent"))
9121 }),
9122 None
9123 );
9124 }
9125
9126 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
9127 let mut q = ask::Question::new(
9128 run.to_owned(),
9129 "implement".to_owned(),
9130 "impl-A".to_owned(),
9131 "continue?".to_owned(),
9132 String::new(),
9133 vec!["resume で続行する".to_owned(), "other".to_owned()],
9134 );
9135 q.actions.insert("resume で続行する".to_owned(), action);
9136 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
9137 .unwrap();
9138 q
9139 }
9140
9141 fn held_task_with(run: &str) -> Task {
9142 let mut t = task();
9143 t.runs = vec![run.to_owned()];
9144 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
9145 t
9146 }
9147
9148 fn resume_action(run: &str) -> ask::ChoiceAction {
9149 ask::ChoiceAction::Resume { run: run.into() }
9150 }
9151
9152 #[test]
9153 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
9154 for parked in [false, true] {
9155 let mut t = task();
9156 t.start("A".into());
9157 t.start("B".into());
9158 assert_eq!(t.runs, vec!["A", "B"]);
9159 t.start("A".into());
9160 let mut resumed = run_state(RunStatus::Blocked);
9161 resumed.id = "A".into();
9162 resumed.parked = parked;
9163 resumed.driver_exited = true;
9164 t.hold_machine(Some("resumed run stopped".into()));
9165 let q = action_question("A", resume_action("A"));
9166 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
9167 assert_eq!(
9168 decide_action(&t, &q, &PHRASES_EN, |id| {
9169 assert_eq!(id, "A");
9170 Ok(resumed.clone())
9171 }),
9172 ActionDecision::Resume("A".into())
9173 );
9174 assert_eq!(
9175 action_standing(&t, &action_question("B", resume_action("B"))),
9176 ActionStanding::Stale
9177 );
9178 t.release_operator("cli", None);
9179 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
9180 assert_eq!(id, "A");
9181 Ok(resumed.clone())
9182 });
9183 assert_eq!(
9184 choose_starter(None, false, unfinished.as_deref()),
9185 Starter::Resume("A".into())
9186 );
9187 assert_eq!(t.runs, vec!["B", "A"]);
9188 }
9189 }
9190
9191 #[test]
9192 fn decide_action_resumes_only_the_latest_resumable_run() {
9193 let t = held_task_with("r1");
9194 let q = action_question("r1", resume_action("r1"));
9195 let load = |s: RunState| move |_: &str| Ok(s);
9196 assert_eq!(
9197 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
9198 ActionDecision::Resume("r1".into())
9199 );
9200 let q_other = action_question("r1", resume_action("r0"));
9202 assert!(matches!(
9203 decide_action(
9204 &t,
9205 &q_other,
9206 &PHRASES_EN,
9207 load(run_state(RunStatus::Blocked))
9208 ),
9209 ActionDecision::Refuse(_)
9210 ));
9211 assert!(matches!(
9213 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
9214 ActionDecision::Refuse(_)
9215 ));
9216 let mut released = run_state(RunStatus::Blocked);
9218 released.released_to = Some("elsewhere".into());
9219 assert!(matches!(
9220 decide_action(&t, &q, &PHRASES_EN, load(released)),
9221 ActionDecision::Refuse(_)
9222 ));
9223 assert!(matches!(
9225 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
9226 ActionDecision::Refuse(_)
9227 ));
9228 }
9229
9230 #[test]
9231 fn decide_action_ignores_a_question_about_an_earlier_run() {
9232 let mut t = held_task_with("r1");
9233 t.runs.push("r2".to_owned());
9234 let never = |_: &str| -> Result<RunState> { bail!("not read") };
9235 assert_eq!(
9236 decide_action(
9237 &t,
9238 &action_question("r1", ask::ChoiceAction::Done),
9239 &PHRASES_EN,
9240 never
9241 ),
9242 ActionDecision::Stale
9243 );
9244 }
9245
9246 #[test]
9247 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
9248 let mut t = held_task_with("r1");
9249 let never = |_: &str| -> Result<RunState> { bail!("not read") };
9250 assert_eq!(
9251 decide_action(
9252 &t,
9253 &action_question("r1", ask::ChoiceAction::Requeue),
9254 &PHRASES_EN,
9255 never
9256 ),
9257 ActionDecision::Requeue
9258 );
9259 let done_q = action_question("r1", ask::ChoiceAction::Done);
9260 assert_eq!(
9261 decide_action(&t, &done_q, &PHRASES_EN, never),
9262 ActionDecision::Done
9263 );
9264 t.mark_action_applied(&done_q.id);
9265 assert_eq!(
9266 decide_action(&t, &done_q, &PHRASES_EN, never),
9267 ActionDecision::Skip
9268 );
9269
9270 let mut plain = action_question("r1", ask::ChoiceAction::Done);
9272 plain.actions.clear();
9273 assert_eq!(
9274 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
9275 ActionDecision::Skip
9276 );
9277 let mut running = held_task_with("r1");
9279 running.status = TaskStatus::Running;
9280 assert_eq!(
9281 decide_action(
9282 &running,
9283 &action_question("r1", ask::ChoiceAction::Done),
9284 &PHRASES_EN,
9285 never
9286 ),
9287 ActionDecision::Skip
9288 );
9289 }
9290
9291 #[test]
9292 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
9293 let dir = tempfile::tempdir().unwrap();
9294 let queue = Queue::at(dir.path().join("queue"));
9295 let questions = Questions::at(dir.path().join("questions"));
9296 let home = dir.path().join("home");
9297 let mut state = run_state(RunStatus::Blocked);
9298 state.id = "20260101-000000-act1".to_owned();
9299 state.save_under(&home).unwrap();
9300
9301 let mut t = held_task_with(&state.id);
9302 queue.put(&mut t).unwrap();
9303 let mut q = action_question(&state.id, resume_action(&state.id));
9304 questions.put(&mut q).unwrap();
9305
9306 apply_choice_actions(&queue, &questions, &home);
9307 let after = queue.get(&t.id).unwrap();
9308 assert_eq!(after.status, TaskStatus::Queued);
9309 assert!(!after.fresh_start);
9310 assert!(after.action_applied(&q.id));
9311 let pin = after.resume_override.clone().unwrap();
9312 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
9313 assert!(pin.forced);
9314
9315 let mut again = queue.get(&t.id).unwrap();
9317 again.hold_machine(Some("later".into()));
9318 queue.put(&mut again).unwrap();
9319 apply_choice_actions(&queue, &questions, &home);
9320 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9321 }
9322
9323 #[test]
9324 fn a_delivered_answer_is_still_acted_on_exactly_once() {
9325 let dir = tempfile::tempdir().unwrap();
9326 let queue = Queue::at(dir.path().join("queue"));
9327 let questions = Questions::at(dir.path().join("questions"));
9328 let home = dir.path().join("home");
9329 let mut state = run_state(RunStatus::Blocked);
9330 state.id = "20260101-000000-act2".to_owned();
9331 state.save_under(&home).unwrap();
9332
9333 let mut t = held_task_with(&state.id);
9334 queue.put(&mut t).unwrap();
9335 let mut q = action_question(&state.id, resume_action(&state.id));
9336 q.answer_delivered = true;
9337 questions.put(&mut q).unwrap();
9338
9339 apply_choice_actions(&queue, &questions, &home);
9342 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9343 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
9344
9345 let mut again = queue.get(&t.id).unwrap();
9347 again.hold_machine(Some("later".into()));
9348 queue.put(&mut again).unwrap();
9349 apply_choice_actions(&queue, &questions, &home);
9350 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9351 }
9352
9353 #[test]
9354 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
9355 let dir = tempfile::tempdir().unwrap();
9356 let queue = Queue::at(dir.path().join("queue"));
9357 let questions = Questions::at(dir.path().join("questions"));
9358 let home = dir.path().join("home");
9359 let mut state = run_state(RunStatus::Blocked);
9360 state.id = "20260101-000000-act3".to_owned();
9361 state.save_under(&home).unwrap();
9362 let mut t = held_task_with(&state.id);
9363 queue.put(&mut t).unwrap();
9364 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
9365 questions.put(&mut q).unwrap();
9366
9367 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
9368 apply_choice_actions(&queue, &questions, &home);
9369 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9370
9371 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
9372 apply_choice_actions(&queue, &questions, &home);
9373 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9374 }
9375
9376 #[test]
9377 fn action_standing_tells_the_reasons_apart() {
9378 let mut t = held_task_with("r1");
9379 let q = action_question("r1", ask::ChoiceAction::Requeue);
9380 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
9381 let mut plain = q.clone();
9382 plain.actions.clear();
9383 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
9384
9385 t.mark_action_applied(&q.id);
9387 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
9388
9389 let mut t = held_task_with("r1");
9391 t.start("r2".to_owned());
9392 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
9393 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
9395 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
9396 t.status = TaskStatus::Blocked;
9397 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
9398
9399 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
9401 c.node = crate::conduct::NODE.to_owned();
9402 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
9403 assert!(!ActionStanding::Busy.daemon_owns());
9404 }
9405
9406 #[test]
9407 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
9408 let dir = tempfile::tempdir().unwrap();
9409 let queue = Queue::at(dir.path().join("queue"));
9410 let questions = Questions::at(dir.path().join("questions"));
9411 let home = dir.path().join("home");
9412 let mut state = run_state(RunStatus::Blocked);
9413 state.id = "20260101-000000-act4".to_owned();
9414 state.save_under(&home).unwrap();
9415 let mut t = held_task_with(&state.id);
9416 t.status = TaskStatus::Running;
9417 queue.put(&mut t).unwrap();
9418 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
9419 q.cwd = Some(dir.path().display().to_string());
9420 questions.put(&mut q).unwrap();
9421
9422 let running = queue.get(&t.id).unwrap();
9425 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
9426 assert!(matches!(
9427 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
9428 crate::waiter::Action::Deliver(_)
9429 ));
9430 apply_choice_actions(&queue, &questions, &home);
9432 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9433 let mut back = queue.get(&t.id).unwrap();
9434 back.hold_machine(Some("later".into()));
9435 queue.put(&mut back).unwrap();
9436 apply_choice_actions(&queue, &questions, &home);
9437 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
9438 let mut again = queue.get(&t.id).unwrap();
9439 again.hold_machine(Some("again".into()));
9440 queue.put(&mut again).unwrap();
9441 apply_choice_actions(&queue, &questions, &home);
9442 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9443 }
9444}