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 q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
858 return ActionDecision::Stale;
859 }
860 match action {
861 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
862 ask::ChoiceAction::Done => ActionDecision::Done,
863 ask::ChoiceAction::Resume { run } => {
864 if task.runs.last() != Some(run) {
865 return ActionDecision::Refuse((p.resume_not_latest)(
866 q.short(),
867 ask::short_id(run),
868 ));
869 }
870 match load(run) {
871 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
872 ActionDecision::Resume(run.clone())
873 }
874 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
875 q.short(),
876 ask::short_id(run),
877 )),
878 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
879 q.short(),
880 ask::short_id(run),
881 &format!("{e:#}"),
882 )),
883 }
884 }
885 }
886}
887
888struct Phrases {
902 graph_stopped: fn(&str, &str) -> String,
904 quorum_lost: &'static str,
905 quota_took_out: &'static str,
907 run_ended: &'static str,
909 waiting_for_answer: &'static str,
911 recovered_running: &'static str,
912 no_run_to_recover: &'static str,
913 could_not_start: &'static str,
914 resume_not_latest: fn(&str, &str) -> String,
915 resume_cannot_progress: fn(&str, &str) -> String,
916 resume_unreadable: fn(&str, &str, &str) -> String,
917 handover_refused: fn(&crate::handover::Refused) -> String,
920 handover_hint: &'static str,
922 reviewers_never_answered: fn(usize, usize) -> String,
925}
926
927const PHRASES_EN: Phrases = Phrases {
928 graph_stopped: |status, detail| {
929 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
930 },
931 quorum_lost: "the judging panel lost its quorum",
932 quota_took_out: "; quota took out ",
933 run_ended: "run ended ",
934 waiting_for_answer: " - waiting for operator answer to question ",
935 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
936 no_run_to_recover: "task was `running` with no live daemon and no readable \
937 run to recover; held for a human to check what happened",
938 could_not_start: "could not start the run: ",
939 resume_not_latest: |q, run| {
940 format!("question {q} asked to resume run {run}, which is not this task's latest run")
941 },
942 resume_cannot_progress: |q, run| {
943 format!("question {q} asked to resume run {run}, which cannot make progress")
944 },
945 resume_unreadable: |q, run, e| {
946 format!("question {q} asked to resume run {run}, which could not be read: {e}")
947 },
948 handover_refused: |r| r.to_string(),
949 handover_hint: " (clean up the other worktree, then release the task from the queue)",
950 reviewers_never_answered: |missing, rounds| {
951 format!(
952 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
953 refusing to call it clean"
954 )
955 },
956};
957
958const PHRASES_JA: Phrases = Phrases {
959 graph_stopped: |status, detail| {
960 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
961 },
962 quorum_lost: "審査パネルが定足数を失いました",
963 quota_took_out: "。クォータで脱落: ",
964 run_ended: "run 終了: ",
965 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
966 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
967 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
968 何が起きたか人が確認するため保留にしました",
969 could_not_start: "run を開始できませんでした: ",
970 resume_not_latest: |q, run| {
971 format!(
972 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
973 )
974 },
975 resume_cannot_progress: |q, run| {
976 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
977 },
978 resume_unreadable: |q, run, e| {
979 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
980 },
981 handover_refused: |r| {
982 use crate::handover::Refused;
983 match r {
984 Refused::Foreign { branch, path, why } => format!(
985 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
986 削除しません。不要なら `git worktree remove` でその worktree を削除して\
987 から、やり直してください(詳細: {why})"
988 ),
989 Refused::Unsafe { branch, path, why } => format!(
990 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
991 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
992 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
993 ),
994 Refused::ReleaseFailed { branch, path, run } => format!(
995 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
996 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
997 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
998 ),
999 }
1000 },
1001 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1002 reviewers_never_answered: |missing, rounds| {
1003 format!(
1004 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1005 クリーンとは認めません"
1006 )
1007 },
1008};
1009
1010fn phrases(language: &str) -> &'static Phrases {
1011 if crate::lang::is_japanese(language) {
1012 &PHRASES_JA
1013 } else {
1014 &PHRASES_EN
1015 }
1016}
1017
1018fn language_of(task: &Task, fallback: &Path) -> String {
1022 crate::lang::of_repo(&repo_for(task, fallback))
1023}
1024
1025pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1029 if q.node == crate::conduct::NODE {
1030 return tasks.iter().find(|t| t.id == q.run);
1031 }
1032 tasks.iter().find(|t| t.runs.contains(&q.run))
1033}
1034
1035fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1044 let tasks = queue.list();
1045 for q in questions.list() {
1046 if q.chosen_action().is_none() {
1047 continue;
1048 }
1049 let Some(listed) = task_of_question(&tasks, &q) else {
1050 continue;
1051 };
1052 if listed.action_applied(&q.id) {
1053 continue;
1054 }
1055 let Ok(_claim) = queue.claim(&listed.id) else {
1056 continue;
1057 };
1058 let Ok(mut task) = queue.get(&listed.id) else {
1059 continue;
1060 };
1061 let language = language_of(&task, Path::new("."));
1062 let decision = decide_action(&task, &q, phrases(&language), |id| {
1063 RunState::load_under(id, home)
1064 });
1065 let ran = matches!(
1066 decision,
1067 ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1068 );
1069 if ran && asker_may_still_read(questions, &q, home) {
1070 continue;
1079 }
1080 let done = matches!(decision, ActionDecision::Done);
1081 match decision {
1082 ActionDecision::Skip => continue,
1083 ActionDecision::Resume(run) => {
1084 task.release();
1085 task.resume_override = Some(crate::queue::OperatorResume {
1086 question_id: q.id.clone(),
1087 at: Timestamp::now(),
1088 conductor_rehold: None,
1089 forced: true,
1090 pinned_run: Some(run),
1091 });
1092 }
1093 ActionDecision::Stale => {}
1094 ActionDecision::Requeue => task.requeue(),
1095 ActionDecision::Done => task.succeed(),
1096 ActionDecision::Refuse(why) => {
1097 task.hold_machine(Some(why));
1098 notices::raise(
1099 Notice::warn(
1100 &format!("action:{}", q.id),
1101 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1102 )
1103 .link(Link::Task {
1104 id: task.id.clone(),
1105 }),
1106 );
1107 }
1108 }
1109 task.mark_action_applied(&q.id);
1110 record(queue, &mut task);
1113 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1114 supersede_prior_runs(&task, home);
1115 }
1116 let _ = questions.update(&q.id, |r| {
1119 r.answer_delivered = true;
1120 Ok(())
1121 });
1122 }
1123}
1124
1125fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1129 let now = Timestamp::now();
1130 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1131 return true;
1132 }
1133 q.node != crate::conduct::NODE
1134 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1135 s.seats_active()
1136 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1137 })
1138}
1139
1140fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1151 let tasks = queue.list();
1152 let by_id: std::collections::BTreeMap<&str, &Task> =
1153 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1154 let referenced: std::collections::BTreeSet<&str> = tasks
1155 .iter()
1156 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1157 .collect();
1158
1159 for mut question in questions.list() {
1160 if !question.status.open() || question.node != crate::conduct::NODE {
1161 continue;
1162 }
1163 if referenced.contains(question.id.as_str()) {
1166 continue;
1167 }
1168 let Some(task) = by_id.get(question.run.as_str()) else {
1169 continue;
1170 };
1171 question.abandon(format!(
1172 "task {} no longer waits for this answer",
1173 task.short()
1174 ));
1175 if let Err(e) = questions.put(&mut question) {
1176 tracing::warn!(
1177 "could not retire question {} for task {}: {e:#}",
1178 question.short(),
1179 task.short()
1180 );
1181 }
1182 }
1183}
1184
1185#[derive(Debug, Clone, Copy)]
1192pub struct Verdict {
1193 pub status: RunStatus,
1195 pub left_pr: bool,
1197 pub quota_hit: bool,
1199 pub parked: bool,
1201 pub no_viable_candidates: bool,
1208}
1209
1210pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1267 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1268}
1269
1270fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1272 if verdict.parked {
1278 task.park(detail);
1279 return;
1280 }
1281 match verdict.status {
1282 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1283 RunStatus::AlreadyInBase => task.already_landed(detail),
1284 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1285 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1286 task.stall(detail)
1287 }
1288 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1289 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1290 RunStatus::Blocked => task.fail(detail, max_attempts),
1291 RunStatus::VerifiedNoop => task.handed_off(detail),
1292 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1293 }
1294}
1295
1296pub fn supersede_prior_runs(task: &Task, home: &Path) {
1345 let now = Timestamp::now();
1346 let last_run_succeeded = task
1353 .runs
1354 .last()
1355 .and_then(|id| RunState::load_under(id, home).ok())
1356 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1357 for id in task.superseded_attempts(last_run_succeeded) {
1358 let mut state = match RunState::load_under(id, home) {
1359 Ok(s) => s,
1360 Err(e) => {
1361 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1362 continue;
1363 }
1364 };
1365 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1366 continue;
1367 }
1368 let daemon_claims = is_working_on(home, id, now);
1369 if state.liveness(daemon_claims) == Liveness::Live {
1370 continue;
1371 }
1372 state.status = RunStatus::Superseded;
1373 if let Err(e) = state.save_under(home) {
1374 tracing::warn!("could not mark run {id} superseded: {e:#}");
1375 }
1376 }
1377}
1378
1379fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1401 for task in queue.list() {
1402 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1403 continue;
1404 }
1405 supersede_prior_runs(&task, home);
1406 }
1407}
1408
1409fn settle_and_diagnose(
1416 task: &mut Task,
1417 verdict: Verdict,
1418 detail: &str,
1419 max_attempts: usize,
1420 state: &RunState,
1421) {
1422 let p = phrases(&state.config.graph.language);
1423 let attempts_before = task.attempts;
1424 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1430 task.last_error = Some(detail.to_owned());
1431 task.diagnostic = None;
1432 task.attempts = task.attempts.saturating_sub(1);
1433 task.hold_machine(Some(format!(
1434 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1435 no agent was asked and no attempt was spent",
1436 crate::cache::RESOURCE_HOLD,
1437 block.kind,
1438 block.node
1439 )));
1440 if let Some(pass) = state.passes.last() {
1441 task.record_pass(&state.id, pass.index, attempts_before, None);
1442 }
1443 return;
1444 }
1445 settle_in(task, verdict, detail, max_attempts, p);
1446 if let Some(pass) = state.passes.last() {
1449 let parked = match &pass.end {
1450 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1451 _ => None,
1452 };
1453 task.record_pass(&state.id, pass.index, attempts_before, parked);
1454 }
1455 if task.status == TaskStatus::Held {
1456 task.diagnostic = diagnostic(state);
1457 note_open_question(task, &state.id, p);
1458 }
1459}
1460
1461fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1476 let Some(home) = crate::run::try_home() else {
1477 return;
1478 };
1479 let open = Questions::at(home.join("questions")).open_for(run);
1480 let Some(q) = open.first() else {
1481 return;
1482 };
1483 let base = task.hold_reason.clone().unwrap_or_default();
1484 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1485}
1486
1487fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1498 match last_run {
1499 Some(state) => {
1500 let verdict = Verdict {
1501 status: state.status,
1502 left_pr: state.pr.is_some(),
1503 quota_hit: !state.quota.is_empty(),
1504 parked: state.parked,
1505 no_viable_candidates: state.viable().is_empty(),
1506 };
1507 let detail = format!(
1508 "{}{}",
1509 phrases(&state.config.graph.language).recovered_running,
1510 describe(&state)
1511 );
1512 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1513 }
1514 None => {
1515 let why = phrases(language).no_run_to_recover;
1518 task.last_error = Some(why.to_owned());
1519 task.hold_machine(Some(why.to_owned()));
1522 }
1523 }
1524}
1525
1526fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1548 let mut reclaimed = Vec::new();
1549 for listed in queue.list() {
1550 if listed.status != TaskStatus::Running {
1551 continue;
1552 }
1553 let Ok(_claim) = queue.claim(&listed.id) else {
1554 continue;
1555 };
1556 let Ok(mut task) = queue.get(&listed.id) else {
1560 continue;
1561 };
1562 if task.status != TaskStatus::Running {
1563 continue;
1564 }
1565 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1566 if let Some(state) = &last_run
1576 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1577 {
1578 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1579 }
1580 let language = if last_run.is_none() {
1581 language_of(&task, Path::new("."))
1582 } else {
1583 String::new()
1584 };
1585 reclaim(&mut task, last_run, max_attempts, &language);
1586 if task.status == TaskStatus::Done {
1587 supersede_prior_runs(&task, &crate::run::home());
1588 }
1589 record(queue, &mut task);
1590 reclaimed.push(task.id.clone());
1591 }
1592 reclaimed
1593}
1594
1595fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1627 reclaim_abandoned_runs_with(
1628 home,
1629 now,
1630 crate::proc::pid_status,
1631 crate::proc::process_started_at,
1632 )
1633}
1634
1635fn reclaim_abandoned_runs_with<F, G>(
1641 home: &Path,
1642 now: Timestamp,
1643 query: F,
1644 identity: G,
1645) -> Vec<String>
1646where
1647 F: Fn(u32) -> Option<bool>,
1648 G: Fn(u32) -> Option<String>,
1649{
1650 let mut abandoned = Vec::new();
1651 for entry in std::fs::read_dir(home.join("runs"))
1652 .into_iter()
1653 .flatten()
1654 .flatten()
1655 {
1656 let id = entry.file_name().to_string_lossy().into_owned();
1657 if !crate::run::is_run_id(&id) {
1658 continue;
1659 }
1660 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1668 continue;
1669 };
1670 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1671 continue;
1672 };
1673 if state.status.done() || !state.active_all_overrun(now) {
1674 continue;
1675 }
1676 let daemon_claims = is_working_on(home, &id, now);
1688 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1689 continue;
1690 }
1691 state.abandon("daemon");
1692 if let Err(e) = state.save_under(home) {
1693 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1694 continue;
1695 }
1696 if let Some(notice) = notices::run_ended(&state) {
1699 notices::raise_in(home, notice);
1700 }
1701 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1709 tracing::warn!("abandon questions for {id}: {e:#}");
1710 }
1711 abandoned.push(id);
1712 }
1713 abandoned
1714}
1715
1716pub async fn serve(opts: Opts) -> Result<()> {
1722 serve_until(opts, Stop::new()).await
1723}
1724
1725pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1742 let signal = {
1743 let stop = stop.clone();
1744 tokio::spawn(async move {
1745 if tokio::signal::ctrl_c().await.is_ok() {
1746 stop.stop();
1747 tracing::info!("shutdown requested; a run in flight will be finished first");
1748 }
1749 })
1750 };
1751
1752 let worktrees_root = opts
1753 .worktrees_root
1754 .clone()
1755 .unwrap_or_else(crate::run::default_worktree_root);
1756 let outcome = drive(
1757 &opts,
1758 &Queue::open(),
1759 &status_path(),
1760 &crate::run::home(),
1761 &worktrees_root,
1762 &stop,
1763 )
1764 .await;
1765
1766 signal.abort();
1767 outcome
1768}
1769
1770async fn drive(
1783 opts: &Opts,
1784 queue: &Queue,
1785 status_file: &Path,
1786 home: &Path,
1787 worktrees_root: &Path,
1788 stop: &Stop,
1789) -> Result<()> {
1790 let status = Arc::new(Mutex::new(Status::new()));
1798 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1799 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1800
1801 let daemon_cfg = prepare(&opts.repo, opts)
1807 .map(|c| c.daemon)
1808 .unwrap_or_default();
1809 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1810
1811 let waiter = tokio::spawn(crate::waiter::run(
1816 crate::waiter::Waiter::new(
1817 crate::ask::Questions::at(home.join("questions")),
1818 home.to_path_buf(),
1819 prepare(&opts.repo, opts).ok(),
1820 ),
1821 stop.clone(),
1822 ));
1823
1824 let deputies = tokio::spawn(crate::deputy::run(
1828 crate::deputy::Deputies::new(
1829 crate::ask::Questions::at(home.join("questions")),
1830 home.to_path_buf(),
1831 prepare(&opts.repo, opts).ok(),
1832 opts.repo.clone(),
1833 daemon_cfg.max_deputies,
1834 {
1835 let stop = stop.clone();
1836 Arc::new(move || stop.parking())
1837 },
1838 ),
1839 stop.clone(),
1840 ));
1841
1842 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1845
1846 let release_watch = tokio::spawn(crate::release_watch::run(
1849 crate::release_watch::Watcher::new(
1850 Box::new(crate::release_watch::GhForge),
1851 home.to_path_buf(),
1852 ),
1853 {
1854 let (repo, opts) = (opts.repo.clone(), opts.clone());
1855 move || release_watch_settings(&repo, &opts)
1856 },
1857 stop.clone(),
1858 ));
1859
1860 tracing::info!(
1861 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1862 queue.root().display(),
1863 opts.poll.as_secs(),
1864 opts.max_attempts,
1865 concurrency,
1866 if daemon_cfg.pause_for_interrupts {
1867 ", interrupts enabled"
1868 } else {
1869 ""
1870 }
1871 );
1872
1873 janitor(&opts.repo, opts, home, worktrees_root).await;
1876 resweep_superseded_attempts(queue, home);
1877
1878 let outcome = poll(
1879 opts,
1880 queue,
1881 &status,
1882 home,
1883 worktrees_root,
1884 stop,
1885 DispatchLimits {
1886 max_concurrent: concurrency,
1887 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1888 },
1889 )
1890 .await;
1891
1892 beat.abort();
1893 waiter.abort();
1894 deputies.abort();
1895 fetcher.abort();
1896 release_watch.abort();
1897 clear_status_at(status_file);
1898 outcome
1899}
1900
1901fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
1904 let Ok(cfg) = prepare(repo, opts) else {
1905 return (Vec::new(), 0);
1906 };
1907 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
1908 .into_iter()
1909 .map(|r| r.path)
1910 .collect();
1911 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
1914 let runs = crate::run::home().join("runs");
1915 for id in crate::run::list_ids_in(&runs) {
1916 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
1917 .ok()
1918 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1919 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
1920 known.extend(repo);
1921 }
1922 for k in known {
1923 let k = k.canonicalize().unwrap_or(k);
1924 if k.join(".git").exists() && !paths.contains(&k) {
1925 paths.push(k);
1926 }
1927 }
1928 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
1929 if !paths.contains(&own) {
1930 paths.push(own);
1931 }
1932 (paths, cfg.daemon.release_stall_minutes)
1933}
1934
1935const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
1937
1938async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
1942 while !stop.stopped() {
1943 let (interval, roots) = match prepare(&repo, &opts) {
1944 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
1945 Err(_) => (0, Vec::new()),
1946 };
1947 if interval > 0 && !roots.is_empty() {
1948 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
1949 tracing::debug!("fetch origins: {r:?}");
1950 }
1951 let wait = if interval > 0 { interval } else { 60 };
1953 let mut slept = 0;
1954 while slept < wait && !stop.stopped() {
1955 tokio::time::sleep(Duration::from_secs(1)).await;
1956 slept += 1;
1957 }
1958 }
1959}
1960
1961async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1967 loop {
1968 tokio::time::sleep(HEARTBEAT).await;
1969 let snapshot = {
1970 let mut guard = lock(&status);
1971 guard.updated_at = Timestamp::now();
1972 guard.clone()
1973 };
1974 if let Err(e) = write_status_to(&path, &snapshot) {
1975 tracing::warn!("could not refresh the daemon status file: {e:#}");
1978 }
1979 }
1980}
1981
1982#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1985enum LandResume {
1986 NotLanding,
1989 StillWaiting,
1994 Ready,
1998}
1999
2000fn land_resume_state(task: &Task) -> LandResume {
2004 let Some(run_id) = task.runs.last() else {
2005 return LandResume::NotLanding;
2006 };
2007 let Ok(state) = RunState::load(run_id) else {
2008 return LandResume::NotLanding;
2009 };
2010 if !implementers_match(task, &state) || !state.parked {
2011 return LandResume::NotLanding;
2012 }
2013 let node = if state.status == RunStatus::Landing {
2017 land::APPROVAL_NODE
2018 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2019 crate::github_text::ASK_NODE
2020 } else {
2021 return LandResume::NotLanding;
2022 };
2023 let store = ask::Questions::open();
2024 let waiting = store
2025 .list()
2026 .into_iter()
2027 .filter(|q| &q.run == run_id && q.node == node)
2028 .max_by(|a, b| a.id.cmp(&b.id));
2029 let Some(mut q) = waiting else {
2030 return LandResume::Ready;
2031 };
2032 if !q.status.open() {
2033 return LandResume::Ready;
2034 }
2035 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2042 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2043 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2044 q.abandon(format!(
2045 "no answer within {}s of asking",
2046 timeout.as_secs().max(1)
2047 ));
2048 if store.put(&mut q).is_ok() {
2051 return LandResume::Ready;
2052 }
2053 }
2054 LandResume::StillWaiting
2055}
2056
2057const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2065
2066const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2078
2079struct InFlightGuard<'a> {
2092 status: &'a Arc<Mutex<Status>>,
2093 stop: &'a Stop,
2094 task_id: &'a str,
2095}
2096
2097impl Drop for InFlightGuard<'_> {
2098 fn drop(&mut self) {
2099 lock(self.status).current.retain(|c| c.task != self.task_id);
2100 self.stop.exit();
2101 }
2102}
2103
2104#[derive(Debug, Clone, PartialEq, Eq)]
2126enum Interrupt {
2127 Idle,
2129 Parking {
2141 parked: Vec<String>,
2142 interrupt_task: String,
2143 },
2144 Running {
2152 parked: Vec<String>,
2153 interrupt_task: String,
2154 },
2155 Resuming { parked: Vec<String> },
2162}
2163
2164fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2185 match state {
2186 Interrupt::Idle => {
2187 if in_flight.len() != 1 {
2199 return Interrupt::Idle;
2200 }
2201 match runnable.iter().find(|t| t.interrupt) {
2202 Some(t) => Interrupt::Parking {
2203 parked: in_flight.to_vec(),
2204 interrupt_task: t.id.clone(),
2205 },
2206 None => Interrupt::Idle,
2207 }
2208 }
2209 Interrupt::Parking {
2210 parked,
2211 interrupt_task,
2212 } => {
2213 if in_flight.iter().any(|id| parked.contains(id)) {
2214 Interrupt::Parking {
2216 parked,
2217 interrupt_task,
2218 }
2219 } else if in_flight.contains(&interrupt_task) {
2220 Interrupt::Running {
2221 parked,
2222 interrupt_task,
2223 }
2224 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2225 Interrupt::Parking {
2229 parked,
2230 interrupt_task,
2231 }
2232 } else {
2233 Interrupt::Resuming { parked }
2238 }
2239 }
2240 Interrupt::Running {
2241 parked,
2242 interrupt_task,
2243 } => {
2244 if in_flight.contains(&interrupt_task) {
2245 Interrupt::Running {
2246 parked,
2247 interrupt_task,
2248 }
2249 } else {
2250 Interrupt::Resuming { parked }
2256 }
2257 }
2258 Interrupt::Resuming { parked } => {
2259 if in_flight.iter().any(|id| parked.contains(id)) {
2260 Interrupt::Idle
2266 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2267 Interrupt::Resuming { parked }
2268 } else {
2269 Interrupt::Idle
2272 }
2273 }
2274 }
2275}
2276
2277fn advance_interrupt_tick(
2283 enabled: bool,
2284 state: Interrupt,
2285 in_flight: &[String],
2286 runnable: &[Task],
2287) -> Interrupt {
2288 if !enabled {
2289 return Interrupt::Idle;
2290 }
2291 advance_interrupt(state, in_flight, runnable)
2292}
2293
2294fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2299 match state {
2300 Interrupt::Idle => candidates,
2301 Interrupt::Parking {
2302 parked,
2303 interrupt_task,
2304 } => {
2305 if in_flight.iter().any(|id| parked.contains(id)) {
2306 Vec::new()
2307 } else {
2308 candidates
2309 .into_iter()
2310 .filter(|t| &t.id == interrupt_task)
2311 .collect()
2312 }
2313 }
2314 Interrupt::Running { .. } => Vec::new(),
2315 Interrupt::Resuming { parked } => candidates
2323 .into_iter()
2324 .find(|t| parked.contains(&t.id))
2325 .into_iter()
2326 .collect(),
2327 }
2328}
2329
2330struct DispatchLimits {
2334 max_concurrent: usize,
2337 pause_for_interrupts: bool,
2339}
2340
2341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2350enum PermitKind {
2351 None,
2356 Urgent,
2363 Ordinary,
2366}
2367
2368fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2371 if priority {
2372 PermitKind::None
2373 } else if urgent {
2374 PermitKind::Urgent
2375 } else {
2376 PermitKind::Ordinary
2377 }
2378}
2379
2380async fn poll(
2399 opts: &Opts,
2400 queue: &Queue,
2401 status: &Arc<Mutex<Status>>,
2402 home: &Path,
2403 worktrees_root: &Path,
2404 stop: &Stop,
2405 limits: DispatchLimits,
2406) -> Result<()> {
2407 let DispatchLimits {
2408 max_concurrent,
2409 pause_for_interrupts,
2410 } = limits;
2411 let mut attempted: Vec<String> = Vec::new();
2416 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2417 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2425 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2431 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2432 let mut conductor = Conductor::new();
2433 let mut cache_last_checked: Option<Timestamp> = None;
2436 let mut interrupt = Interrupt::Idle;
2438 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2444 std::collections::HashMap::new();
2445
2446 while !stop.stopped() {
2447 lock(status).polls += 1;
2448
2449 while let Some(result) = inflight.try_join_next() {
2454 if let Err(e) = result {
2455 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2456 notices::raise(Notice::error(
2457 "loop:attempt",
2458 "A queued attempt ended abnormally; check the task it was running.",
2459 ));
2460 }
2461 }
2462
2463 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2464 if !swept.is_empty() {
2465 tracing::warn!(
2466 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2467 swept.len(),
2468 swept.join(", ")
2469 );
2470 }
2471 let now = Timestamp::now();
2476
2477 if !stop.busy_now() {
2482 maybe_prune_cache_between_runs(
2483 &opts.repo,
2484 opts,
2485 home,
2486 stop,
2487 &mut cache_last_checked,
2488 now,
2489 )
2490 .await;
2491 }
2492
2493 let stalled = stalled_tasks(queue, home, now);
2494 let stalled_ids: std::collections::BTreeSet<_> =
2495 stalled.iter().map(|task| task.id.clone()).collect();
2496 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2497 if !reclaimed.is_empty() {
2498 tracing::warn!(
2499 "reclaimed {} task(s) left `running` by a daemon that never \
2500 recorded the outcome: {}",
2501 reclaimed.len(),
2502 reclaimed.join(", ")
2503 );
2504 }
2505 let abandoned_runs = reclaim_abandoned_runs(home, now);
2506 if !abandoned_runs.is_empty() {
2507 tracing::warn!(
2508 "failed {} run(s) left behind by a killed process, past every \
2509 active seat's own timeout: {}",
2510 abandoned_runs.len(),
2511 abandoned_runs.join(", ")
2512 );
2513 }
2514
2515 let questions = Questions::at(home.join("questions"));
2520
2521 resolve_blockers(queue, &questions);
2524 apply_choice_actions(queue, &questions, home);
2525 reconcile_task_questions(queue, &questions);
2526 {
2530 let talks = crate::talk::Talks::at(home.join("talks"));
2531 crate::chat_notify::sweep(queue, &talks, home);
2532 crate::chat_watch::sweep(home, &talks);
2533 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2534 }
2535
2536 let finished: Vec<Task> = finished_tasks(queue)
2542 .into_iter()
2543 .filter(|task| !stalled_ids.contains(&task.id))
2544 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2548 .collect();
2549 let queued = queued_tasks(queue);
2550 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2554 && conductor.worth_a_look(queue, &stalled, &finished)
2555 {
2556 match prepare(&opts.repo, opts) {
2557 Ok(cfg) => {
2558 conductor
2559 .maybe_run(
2560 &cfg,
2561 &opts.repo,
2562 queue,
2563 &questions,
2564 home,
2565 &queued,
2566 &stalled,
2567 &finished,
2568 opts.max_attempts,
2569 )
2570 .await;
2571 }
2572 Err(e) => {
2573 tracing::warn!("conductor: no config: {e:#}");
2574 notices::raise(Notice::warn(
2575 "loop:no-config",
2576 "The loop could not read this repository's config, so held tasks are not being triaged.",
2577 ));
2578 }
2579 }
2580 }
2581
2582 let candidates: Vec<Task> = runnable(queue)
2583 .into_iter()
2584 .filter(|t| !opts.once || !attempted.contains(&t.id))
2585 .collect();
2586
2587 let in_flight: Vec<String> = lock(status)
2592 .current
2593 .iter()
2594 .map(|c| c.task.clone())
2595 .collect();
2596 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2597
2598 interrupt =
2599 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2600 if let Interrupt::Parking {
2601 parked,
2602 interrupt_task,
2603 } = &interrupt
2604 {
2605 let reason = format!(
2606 "task {} asked to run first",
2607 crate::run::short_of(interrupt_task)
2608 );
2609 for id in parked {
2610 if let Some(pause) = interrupt_pauses.get(id) {
2611 pause.park_because(reason.clone());
2612 }
2613 }
2614 }
2615 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2616
2617 let cooling_down =
2618 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2619
2620 let mut started_any = false;
2621 for candidate in candidates {
2622 if stop.stopped() {
2623 break;
2624 }
2625
2626 let resume = land_resume_state(&candidate);
2627 if resume == LandResume::StillWaiting {
2628 continue;
2629 }
2630 let priority = resume == LandResume::Ready;
2631
2632 if !priority && cooling_down {
2633 continue;
2634 }
2635 let permit = match permit_kind(priority, candidate.urgent) {
2636 PermitKind::None => None,
2637 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2638 Ok(p) => Some(p),
2639 Err(_) => continue,
2645 },
2646 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2647 Ok(p) => Some(p),
2648 Err(_) => continue,
2652 },
2653 };
2654
2655 let Ok(claim) = queue.claim(&candidate.id) else {
2660 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2661 continue;
2662 };
2663 let mut task = match queue.get(&candidate.id) {
2666 Ok(t) if t.status.runnable() => t,
2667 Ok(_) => continue,
2668 Err(e) => {
2669 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2670 continue;
2671 }
2672 };
2673 let task_id = task.id.clone();
2674 attempted.push(task_id.clone());
2675 lock(status).idle = false;
2676 stop.enter();
2679 started_any = true;
2680
2681 let run_pause = crate::graph::Pause::new();
2685 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2686
2687 let opts = opts.clone();
2688 let queue = queue.clone();
2689 let status = Arc::clone(status);
2690 let stop = stop.clone();
2691 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2692 inflight.spawn(async move {
2693 let _claim = claim;
2697 let _permit = permit;
2698 let _inflight = InFlightGuard {
2700 status: &status,
2701 stop: &stop,
2702 task_id: &task_id,
2703 };
2704 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2705 lock(&status).completed += 1;
2706 let now = Timestamp::now();
2712 if let Some(until) = cooldown_until("a, now) {
2713 let wait = until.as_second() - now.as_second();
2714 *lock("a_cooldown_until) = Some(until);
2715 let hint = quota
2716 .iter()
2717 .find(|q| q.reset.is_some())
2718 .and_then(|q| q.reset.as_deref());
2719 match hint {
2720 Some(h) => tracing::warn!(
2721 "quota hit; waiting {wait}s before taking another ordinary task \
2722 (CLI reported reset: {h})"
2723 ),
2724 None => tracing::warn!(
2725 "quota hit; waiting {wait}s before taking another ordinary task \
2726 (no reset hint reported)"
2727 ),
2728 }
2729 }
2730 });
2731 }
2732
2733 if started_any {
2734 continue;
2735 }
2736
2737 if stop.busy_now() {
2738 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2743 continue;
2744 }
2745
2746 lock(status).idle = true;
2748 if opts.once {
2749 janitor(&opts.repo, opts, home, worktrees_root).await;
2753 resweep_superseded_attempts(queue, home);
2754 triage_held(queue, home, opts).await;
2755 break;
2756 }
2757 stop.idle(opts.poll).await;
2758 if stop.stopped() {
2759 continue;
2760 }
2761 janitor(&opts.repo, opts, home, worktrees_root).await;
2767 resweep_superseded_attempts(queue, home);
2768 triage_held(queue, home, opts).await;
2769 }
2770
2771 while let Some(result) = inflight.join_next().await {
2776 if let Err(e) = result {
2777 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2778 notices::raise(Notice::error(
2779 "loop:attempt",
2780 "A queued attempt ended abnormally; check the task it was running.",
2781 ));
2782 }
2783 }
2784 Ok(())
2785}
2786
2787async fn attempt(
2793 opts: &Opts,
2794 queue: &Queue,
2795 status: &Arc<Mutex<Status>>,
2796 stop: &Stop,
2797 interrupt_pause: crate::graph::Pause,
2798 task: &mut Task,
2799) -> Vec<QuotaLoss> {
2800 let repo = repo_for(task, &opts.repo);
2801 tracing::info!(
2802 "task {} — {} (repo {})",
2803 task.short(),
2804 task.title,
2805 repo.display()
2806 );
2807
2808 let explicit = match &task.overrides {
2812 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
2813 Some(_) => opts.config.as_deref(),
2814 None => opts.config.as_deref(),
2815 };
2816 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2817 let reason = format!("[config] {e:#}");
2818 task.last_error = Some(reason.clone());
2819 task.hold_machine(Some(reason.clone()));
2820 record(queue, task);
2821 tracing::warn!("holding {}: {reason}", task.short());
2822 return Vec::new();
2823 }
2824 let mut config = match prepare_for(&repo, opts, task) {
2825 Ok(c) => c,
2826 Err(e) => {
2827 task.attempts += 1;
2831 task.fail(format!("config: {e:#}"), opts.max_attempts);
2832 record(queue, task);
2833 return Vec::new();
2834 }
2835 };
2836 apply_task_implementers(&mut config, task);
2837 let p = phrases(&config.graph.language);
2838 let start_failed = p.could_not_start;
2839
2840 if let Some(reason) = disk_gate(&repo, &config) {
2848 task.last_error = Some(reason.clone());
2849 task.hold_machine(Some(reason.clone()));
2850 record(queue, task);
2851 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2852 notices::raise(
2855 Notice::warn(
2856 &format!("disk:{}", repo.display()),
2857 "A task was held for want of free disk space; free some, then release it from the queue.",
2858 )
2859 .link(Link::Task {
2860 id: task.id.clone(),
2861 }),
2862 );
2863 return Vec::new();
2864 }
2865
2866 let unfinished = (!task.fresh_start)
2886 .then(|| unfinished_run(&task.runs, task.short()))
2887 .flatten();
2888 let review_branch = task.review_branch.take();
2894 let branch_exists = match &review_branch {
2895 Some(branch) => crate::git::branch_exists(&repo, branch)
2896 .await
2897 .unwrap_or(false),
2898 None => false,
2899 };
2900 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
2904 let proposed = match (&review_branch, &unfinished, &task.review_of) {
2905 (None, None, Some(branch)) => Starter::Review(branch.clone()),
2906 _ => choose_starter(
2907 review_branch.as_deref(),
2908 branch_exists,
2909 unfinished.as_deref(),
2910 ),
2911 };
2912 let starter = starter_with_implementers(task, previous.as_ref(), proposed);
2913 let attachments = match task_attachments(queue, task) {
2918 Ok(a) => a,
2919 Err(e) => {
2920 task.attempts += 1;
2921 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2922 record(queue, task);
2923 return Vec::new();
2924 }
2925 };
2926 let started = match &starter {
2927 Starter::Review(branch) => {
2928 tracing::info!(
2929 "task {} reopens `{branch}` as a review-only pass",
2930 task.short()
2931 );
2932 let takeover = crate::handover::Takeover {
2935 earlier: task.earlier_attempts().to_vec(),
2936 home: crate::run::home(),
2937 choice: take_divergence_answer(branch, &config.merge.remote, task),
2938 task_instruction: Some(instruction_for(task)),
2939 };
2940 Runner::review_taking_over(
2941 &repo,
2942 branch,
2943 config,
2944 Some(takeover),
2945 crate::run::Origin::queue(&task.id),
2946 )
2947 .await
2948 }
2949 Starter::Resume(id) => {
2950 tracing::info!("resuming run {id} rather than competing again");
2951 Runner::resume(id).map(|mut r| {
2952 if let Some(instruction) =
2953 prepare_instruction(&starter, Some(&r.state.instruction), task)
2954 {
2955 r.state.instruction = instruction;
2956 }
2957 r.state.attachments = attachments.clone();
2958 if let Some(mode) = task
2961 .overrides
2962 .as_ref()
2963 .and_then(|o| o.merge.as_deref())
2964 .and_then(|m| merge_mode(m).ok())
2965 {
2966 r.state.config.merge.mode = mode;
2967 }
2968 r
2969 })
2970 }
2971 Starter::Start => {
2972 if let Some(branch) = &review_branch {
2973 tracing::warn!(
2974 "conductor chose review for task {} but branch `{branch}` no longer \
2975 exists; requeuing as a fresh competition instead",
2976 task.short()
2977 );
2978 }
2979 let instruction = prepare_instruction(&starter, None, task)
2980 .unwrap_or_else(|| task.instruction.clone());
2981 Runner::start_naming(
2982 &repo,
2983 instruction,
2984 &task.title,
2985 config,
2986 crate::run::Origin::queue(&task.id),
2987 )
2988 .await
2989 .map(|mut r| {
2990 r.state.attachments = attachments.clone();
2991 r
2992 })
2993 }
2994 };
2995 let mut runner = match started {
2996 Ok(r) => r,
2997 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3001 let detail = match e.downcast_ref::<crate::handover::Refused>() {
3002 Some(r) => (p.handover_refused)(r),
3003 None => format!("{e:#}"),
3004 };
3005 let reason = format!("{start_failed}{detail}");
3006 task.last_error = Some(reason.clone());
3007 let branch = match &starter {
3010 Starter::Review(branch) => Some(branch.clone()),
3011 _ => None,
3012 };
3013 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3017 record(queue, task);
3018 tracing::warn!(
3019 "holding {} for a branch it cannot take over: {e:#}",
3020 task.short()
3021 );
3022 return Vec::new();
3023 }
3024 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3029 let d = e
3030 .downcast_ref::<crate::reconcile::Diverged>()
3031 .expect("checked by the guard");
3032 let mut q = ask::Question::new(
3033 task.id.clone(),
3034 crate::reconcile::NODE.to_owned(),
3035 crate::reconcile::SEAT.to_owned(),
3036 d.summary(),
3037 d.detail(),
3038 d.choices(),
3039 );
3040 match Questions::open().put(&mut q) {
3041 Ok(()) => {
3042 task.last_error = Some(format!("{e:#}"));
3043 task.review_branch = Some(d.branch.clone());
3046 task.block(vec![q.id.clone()], Some(d.summary()));
3047 }
3048 Err(put) => {
3049 tracing::warn!("could not file the divergence question: {put:#}");
3050 task.attempts += 1;
3051 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3052 }
3053 }
3054 record(queue, task);
3055 return Vec::new();
3056 }
3057 Err(e) => {
3058 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3064 && let Starter::Review(branch) = &starter
3065 {
3066 task.review_branch = Some(branch.clone());
3067 task.last_error = Some(format!("{start_failed}{e:#}"));
3068 task.status = crate::queue::TaskStatus::Failed;
3069 record(queue, task);
3070 return Vec::new();
3071 }
3072 task.attempts += 1;
3073 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3074 record(queue, task);
3075 return Vec::new();
3076 }
3077 };
3078 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3081 if runner.state.origin_chat.is_none() {
3082 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3083 }
3084 runner.on_pause(stop.pause());
3086 runner.watch_interrupt(interrupt_pause);
3090
3091 let run = runner.state.id.clone();
3094 task.start(run.clone());
3095 record(queue, task);
3096 lock(status).current.push(Current {
3097 task: task.id.clone(),
3098 run,
3099 });
3100
3101 let quota_before = runner.state.quota.clone();
3104 runner.state.next_pass_task_entry = true;
3105 let result = runner.execute().await;
3106 finish_attempt(
3107 opts.max_attempts,
3108 queue,
3109 task,
3110 &runner.state,
3111 "a_before,
3112 result,
3113 )
3114}
3115
3116pub fn finish_attempt(
3121 max_attempts: usize,
3122 queue: &Queue,
3123 task: &mut Task,
3124 state: &RunState,
3125 quota_before: &[QuotaLoss],
3126 result: Result<()>,
3127) -> Vec<QuotaLoss> {
3128 let detail = match result {
3129 Ok(()) => describe(state),
3130 Err(e) => format!("{e:#}"),
3131 };
3132 let fresh = losses_this_attempt(quota_before, &state.quota);
3133 let verdict = Verdict {
3134 status: state.status,
3135 left_pr: state.pr.is_some(),
3138 quota_hit: !fresh.is_empty(),
3144 parked: state.parked,
3148 no_viable_candidates: state.viable().is_empty(),
3151 };
3152 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3153 if task.status == TaskStatus::Done {
3154 supersede_prior_runs(task, &crate::run::home());
3155 }
3156 record(queue, task);
3157 tracing::info!(
3158 "task {} is {} after run {} ({})",
3159 task.short(),
3160 task.status.as_str(),
3161 state.short(),
3162 label(state.status)
3163 );
3164 fresh
3165}
3166
3167pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3171 let waits_on_owner = withheld_text_wait(task).is_some();
3176 if task.status.runnable() && !waits_on_owner {
3177 let why = task.last_error.clone().map_or_else(
3178 || "the run did not finish".to_owned(),
3179 |e| format!("the run did not finish: {e}"),
3180 );
3181 task.hold_manual(Some(format!(
3182 "{why}. It was started by hand, so it is not retried \
3183 automatically; `magi task release` retries it."
3184 )));
3185 record(queue, task);
3186 }
3187}
3188
3189#[must_use]
3193pub fn loop_would_resume(run: &str) -> bool {
3194 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3195}
3196
3197#[must_use]
3207pub fn foreign_loop(
3208 reading: Option<&Reading>,
3209 now: Timestamp,
3210 own_pid: u32,
3211) -> Option<Option<u32>> {
3212 let reading = reading.filter(|r| r.running(now))?;
3213 match reading.pid {
3214 Some(pid) if pid == own_pid => None,
3215 pid => Some(pid),
3216 }
3217}
3218
3219pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3234 let status = Arc::new(Mutex::new(Status::new()));
3235 let stop = Stop::new();
3236 attempt(
3237 opts,
3238 queue,
3239 &status,
3240 &stop,
3241 crate::graph::Pause::new(),
3242 task,
3243 )
3244 .await;
3245 let mut resumes = 0;
3254 while resumes < MAX_WITHHELD_RESUMES {
3255 let Some(timeout) = withheld_text_wait(task) else {
3256 break;
3257 };
3258 eprintln!(
3259 "waiting for the owner's answer on a withheld pull request text \
3260 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3261 );
3262 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3265 let ready = loop {
3266 match land_resume_state(task) {
3267 LandResume::StillWaiting if std::time::Instant::now() < limit => {
3268 tokio::time::sleep(WITHHELD_POLL).await;
3269 }
3270 LandResume::Ready => break true,
3271 _ => break false,
3272 }
3273 };
3274 if !ready {
3275 break;
3276 }
3277 resumes += 1;
3278 attempt(
3279 opts,
3280 queue,
3281 &status,
3282 &stop,
3283 crate::graph::Pause::new(),
3284 task,
3285 )
3286 .await;
3287 }
3288 hold_if_runnable(queue, task);
3289}
3290
3291const MAX_WITHHELD_RESUMES: u32 = 3;
3294
3295const WITHHELD_POLL: Duration = Duration::from_secs(15);
3297
3298fn withheld_text_wait(task: &Task) -> Option<u64> {
3301 let id = task.runs.last()?;
3302 let s = RunState::load(id).ok()?;
3303 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3304 .then_some(s.config.graph.answer_timeout)
3305}
3306
3307fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3317 after
3318 .iter()
3319 .filter(|q| !before.contains(q))
3320 .cloned()
3321 .collect()
3322}
3323
3324fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3327 if quota.is_empty() {
3328 return None;
3329 }
3330 let with_hint = quota.iter().find(|q| q.reset.is_some());
3331 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3332 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3333 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3334 Some(
3335 now.checked_add(jiff::SignedDuration::from_secs(secs))
3336 .unwrap_or(Timestamp::MAX),
3337 )
3338}
3339
3340fn implementers_match(task: &Task, state: &RunState) -> bool {
3342 task.implementers()
3343 .is_none_or(|n| n == state.config.graph.implementers)
3344}
3345
3346fn starter_with_implementers(
3348 task: &Task,
3349 previous: Option<&RunState>,
3350 proposed: Starter,
3351) -> Starter {
3352 if previous.is_some_and(|s| !implementers_match(task, s)) {
3353 task.review_of
3354 .as_ref()
3355 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3356 } else {
3357 proposed
3358 }
3359}
3360
3361fn apply_task_implementers(config: &mut Config, task: &Task) {
3363 if let Some(n) = task.implementers() {
3364 config.graph.implementers = n;
3365 }
3366}
3367
3368fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3373 let Some(o) = &task.overrides else {
3374 return prepare(repo, opts);
3375 };
3376 let own = Opts {
3380 config: o.config.clone(),
3381 merge: None,
3382 ..opts.clone()
3383 };
3384 let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3385 o.apply(&mut config);
3386 Ok(config)
3387}
3388
3389fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3391 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3392 if let Some(mode) = &opts.merge {
3393 config.merge.mode = merge_mode(mode)?;
3394 }
3395 Ok(config)
3396}
3397
3398async fn maybe_prune_cache_between_runs(
3429 repo: &Path,
3430 opts: &Opts,
3431 home: &Path,
3432 stop: &Stop,
3433 last_checked: &mut Option<Timestamp>,
3434 now: Timestamp,
3435) {
3436 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3437 return;
3438 }
3439 *last_checked = Some(now);
3440 let cfg = match prepare(repo, opts) {
3441 Ok(cfg) => cfg,
3442 Err(e) => {
3443 tracing::warn!("cache check: no config: {e:#}");
3444 return;
3445 }
3446 };
3447 match clean::prune_cache_if_over_limit(&cfg, home) {
3448 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3449 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3450 pruned.files,
3451 pruned.freed
3452 ),
3453 Ok(_) => {}
3454 Err(e) => {
3455 tracing::warn!("housekeep: prune cache: {e:#}");
3456 notices::raise_in(
3457 home,
3458 Notice::warn(
3459 "housekeep:cache",
3460 "Pruning the shared build cache failed; disk usage may keep growing.",
3461 ),
3462 );
3463 }
3464 }
3465}
3466
3467fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3471 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3472}
3473
3474async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3493 let cfg = match prepare(repo, opts) {
3494 Ok(cfg) => cfg,
3495 Err(e) => {
3496 tracing::warn!("housekeep: no config: {e:#}");
3497 return;
3498 }
3499 };
3500 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3509 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3510 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3515 let mut extra = Vec::new();
3516 if out.unreadable > 0 {
3517 extra.push(format!("{} unreadable", out.unreadable));
3518 }
3519 if out.orphaned_worktrees > 0 {
3520 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3521 }
3522 let detail = if extra.is_empty() {
3523 String::new()
3524 } else {
3525 format!(" ({})", extra.join(", "))
3526 };
3527 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3528 }
3529 if out.external_merges_recorded > 0 {
3530 tracing::info!(
3531 "housekeep: recorded {} run(s) as merged externally",
3532 out.external_merges_recorded
3533 );
3534 }
3535 if out.stale_pr_states_repaired > 0 {
3536 tracing::info!(
3537 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3538 out.stale_pr_states_repaired
3539 );
3540 }
3541 if out.cache_files > 0 {
3542 tracing::info!(
3543 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3544 out.cache_files,
3545 out.cache_freed
3546 );
3547 }
3548 if out.questions_abandoned > 0 {
3549 tracing::info!(
3550 "housekeep: abandoned {} question(s) left open by a finished run",
3551 out.questions_abandoned
3552 );
3553 }
3554}
3555
3556async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3565 let questions = Questions::at(home.join("questions"));
3566 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3567 if report.is_empty() {
3568 return;
3569 }
3570 if !report.quarantined.is_empty() {
3571 tracing::info!(
3572 "triage: held {} blocked task(s) whose blocked-on task or \
3573 question no longer exists: {}",
3574 report.quarantined.len(),
3575 report.quarantined.join(", ")
3576 );
3577 }
3578 if !report.resumed.is_empty() {
3579 tracing::info!(
3580 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3581 report.resumed.len(),
3582 report.resumed.join(", ")
3583 );
3584 }
3585 if !report.asked.is_empty() {
3586 tracing::info!(
3587 "triage: asked about {} held task(s): {}",
3588 report.asked.len(),
3589 report.asked.join(", ")
3590 );
3591 }
3592 if !report.answered.is_empty() {
3593 tracing::info!(
3594 "triage: applied {} operator answer(s): {}",
3595 report.answered.len(),
3596 report.answered.join(", ")
3597 );
3598 }
3599}
3600
3601fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3608 disk_gate_with(repo, config, crate::disk::free_bytes)
3609}
3610
3611fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3615 repo: &Path,
3616 config: &Config,
3617 free_bytes: F,
3618) -> Option<String> {
3619 let min = config.disk.min_free_bytes;
3620 if min == 0 {
3621 return None;
3622 }
3623 match free_bytes(repo) {
3624 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3625 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3626 }
3627}
3628
3629const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3636
3637const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3641
3642fn quota_wait(
3651 reset_at: Option<Timestamp>,
3652 now: Timestamp,
3653 fallback: Duration,
3654 cap: Duration,
3655) -> Duration {
3656 match reset_at {
3657 Some(at) if at > now => {
3658 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3659 Duration::from_secs(secs).min(cap)
3660 }
3661 _ => fallback,
3662 }
3663}
3664
3665fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3679 parse_reset_hint_zoned(text, now)
3680 .or_else(|| parse_reset_hint_dated(text))
3681 .or_else(|| parse_reset_hint_relative(text, recorded))
3682}
3683
3684fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3688 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3689 let mut rest = rest.trim();
3690 if rest.is_empty() {
3691 return None;
3692 }
3693 let mut total: i64 = 0;
3694 let mut matched = false;
3695 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3696 if let Some((digits, tail)) = rest.split_once(unit)
3697 && !digits.is_empty()
3698 && digits.bytes().all(|b| b.is_ascii_digit())
3699 {
3700 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3701 rest = tail;
3702 matched = true;
3703 }
3704 }
3705 if !rest.is_empty() || !matched {
3706 return None;
3707 }
3708 recorded
3709 .checked_add(jiff::SignedDuration::from_secs(total))
3710 .ok()
3711}
3712
3713fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3717 let clock = clock.trim().to_lowercase();
3718 let (digits, pm) = clock
3719 .strip_suffix("am")
3720 .map(|d| (d, false))
3721 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3722 let (h, m) = digits.trim().split_once(':')?;
3723 let mut hour: i8 = h.trim().parse().ok()?;
3724 let minute: i8 = m.trim().parse().ok()?;
3725 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3726 return None;
3727 }
3728 if pm && hour != 12 {
3729 hour += 12;
3730 } else if !pm && hour == 12 {
3731 hour = 0;
3732 }
3733 Some((hour, minute))
3734}
3735
3736fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3741 let open = text.find('(')?;
3742 let close = text.rfind(')')?;
3743 if close <= open {
3744 return None;
3745 }
3746 let zone = text[open + 1..close].trim();
3747 let (hour, minute) = parse_12h_clock(&text[..open])?;
3748 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3749 let candidate = now
3750 .to_zoned(tz)
3751 .with()
3752 .hour(hour)
3753 .minute(minute)
3754 .second(0)
3755 .millisecond(0)
3756 .microsecond(0)
3757 .nanosecond(0)
3758 .build()
3759 .ok()?;
3760 let mut at = candidate.timestamp();
3761 if at <= now {
3762 at += jiff::SignedDuration::from_hours(24);
3763 }
3764 Some(at)
3765}
3766
3767fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3776 let words: Vec<&str> = text.split_whitespace().collect();
3777 if words.len() < 5 {
3778 return None;
3779 }
3780 (0..=words.len() - 5)
3781 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3782}
3783
3784fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3790 if trailing.is_some_and(|next| next.starts_with('(')) {
3791 return None;
3792 }
3793 let month = month_number(window[0])?;
3794 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3795 let day_digits = ["st", "nd", "rd", "th"]
3796 .iter()
3797 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3798 let day: i8 = day_digits.parse().ok()?;
3799 let year_token = window[2];
3800 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3801 return None;
3802 }
3803 let year: i16 = year_token.parse().ok()?;
3804 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3808 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3809 let date = jiff::civil::Date::new(year, month, day).ok()?;
3810 let candidate = date
3811 .at(hour, minute, 0, 0)
3812 .to_zoned(jiff::tz::TimeZone::UTC)
3813 .ok()?;
3814 Some(candidate.timestamp())
3815}
3816
3817fn month_number(name: &str) -> Option<i8> {
3820 const NAMES: [&str; 12] = [
3821 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3822 ];
3823 let lower = name.to_lowercase();
3824 NAMES
3825 .iter()
3826 .position(|n| *n == lower.as_str())
3827 .map(|i| i as i8 + 1)
3828}
3829
3830fn exhausted_review_budget(state: &RunState) -> bool {
3842 state.status == RunStatus::Blocked
3845 && !state.pr_publication_pending
3846 && state.reviews.len() >= state.config.graph.review_rounds
3847}
3848
3849fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3886 unfinished_run_with(runs, short, RunState::load)
3887}
3888
3889fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3892where
3893 F: FnOnce(&str) -> Result<RunState>,
3894{
3895 let id = runs.last()?;
3896 match load(id) {
3897 Ok(s)
3902 if s.status.resumable()
3903 && !s.released()
3904 && !exhausted_review_budget(&s)
3905 && s.liveness(false) != crate::run::Liveness::Live =>
3906 {
3907 Some(id.clone())
3908 }
3909 Ok(_) => None,
3910 Err(e) => {
3911 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3912 None
3913 }
3914 }
3915}
3916
3917fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3925where
3926 F: FnOnce(&str) -> Result<RunState>,
3927{
3928 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
3930 || task.fresh_start
3931 || task.review_branch.is_some()
3932 {
3933 return false;
3934 }
3935 let Some(id) = task.runs.last() else {
3936 return false;
3937 };
3938 load(id).is_ok_and(|s| {
3939 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3940 })
3941}
3942
3943#[derive(Debug, Clone, PartialEq, Eq)]
3946enum Starter {
3947 Review(String),
3950 Resume(String),
3952 Start,
3954}
3955
3956fn take_divergence_answer(
3960 branch: &str,
3961 remote: &str,
3962 task: &mut Task,
3963) -> Option<crate::reconcile::Choice> {
3964 let summary = crate::reconcile::summary_for(branch, remote);
3965 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3966 (a.question == summary)
3967 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3968 .flatten()
3969 .map(|c| (i, c))
3970 })?;
3971 task.answers.remove(idx);
3972 Some(choice)
3973}
3974
3975fn choose_starter(
3987 review_branch: Option<&str>,
3988 branch_exists: bool,
3989 unfinished: Option<&str>,
3990) -> Starter {
3991 match review_branch {
3992 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3993 Some(_) => Starter::Start,
3994 None => match unfinished {
3995 Some(id) => Starter::Resume(id.to_owned()),
3996 None => Starter::Start,
3997 },
3998 }
3999}
4000
4001fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4004 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4005 return fallback.to_path_buf();
4006 }
4007 task.repo.clone()
4008}
4009
4010const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4014
4015fn answers_block(task: &Task, count: usize) -> String {
4017 let mut s = ANSWERS_HEADER.to_owned();
4018 for a in &task.answers[..count] {
4019 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4020 }
4021 s
4022}
4023
4024fn append_answers(base: &str, task: &Task) -> String {
4027 if task.answers.is_empty() {
4028 return base.to_owned();
4029 }
4030 let mut s = base.to_owned();
4031 s.push_str(&answers_block(task, task.answers.len()));
4032 s
4033}
4034
4035fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4039 for count in (1..=task.answers.len()).rev() {
4040 let block = answers_block(task, count);
4041 if let Some(base) = instruction.strip_suffix(&block) {
4042 return base;
4043 }
4044 }
4045 instruction
4046}
4047
4048fn instruction_for(task: &Task) -> String {
4056 append_answers(&task.instruction, task)
4057}
4058
4059fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4071 append_answers(strip_answers_block(old_instruction, task), task)
4072}
4073
4074fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
4076 let paths = queue.attachment_paths(task);
4077 for (name, path) in task.attachments.iter().zip(&paths) {
4078 if !path.is_file() {
4079 bail!(
4080 "attachment `{name}` is recorded on the task but {} is missing",
4081 path.display()
4082 );
4083 }
4084 }
4085 Ok(paths)
4086}
4087
4088fn prepare_instruction(
4099 starter: &Starter,
4100 old_instruction: Option<&str>,
4101 task: &Task,
4102) -> Option<String> {
4103 match starter {
4104 Starter::Start => Some(instruction_for(task)),
4105 Starter::Resume(_) => Some(resumed_instruction(
4106 old_instruction.expect("a resumed run always has a prior instruction"),
4107 task,
4108 )),
4109 Starter::Review(_) => None,
4110 }
4111}
4112
4113fn record(queue: &Queue, task: &mut Task) {
4117 if let Err(e) = queue.put(task) {
4118 tracing::error!("could not record task {}: {e:#}", task.short());
4119 let notice = Notice::error(
4120 "loop:record",
4121 "The loop could not save a task's state; check the disk.",
4122 )
4123 .link(Link::Task {
4124 id: task.id.clone(),
4125 });
4126 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4128 Some(home) => notices::raise_in(home, notice),
4129 None => notices::raise(notice),
4130 }
4131 }
4132}
4133
4134fn runnable(queue: &Queue) -> Vec<Task> {
4140 let mut tasks: Vec<Task> = queue
4141 .list()
4142 .into_iter()
4143 .filter(|t| t.status.runnable())
4144 .collect();
4145 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4146 tasks
4147}
4148
4149fn describe(state: &RunState) -> String {
4163 let p = phrases(&state.config.graph.language);
4164 let mut detail = if state.status == RunStatus::Stalled {
4165 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4166 seats.sort_unstable();
4167 seats.dedup();
4168 if seats.is_empty() {
4169 p.quorum_lost.to_owned()
4170 } else {
4171 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4172 }
4173 } else {
4174 format!("{}{}", p.run_ended, state.status.display_label())
4175 };
4176 if let Some(last) = state.events.last() {
4177 let unanswered = state
4181 .reviews
4182 .last()
4183 .filter(|r| {
4184 state.status == RunStatus::Blocked
4185 && last.node == "review"
4186 && r.incomplete()
4187 && r.blocking == 0
4188 && r.round == state.config.graph.review_rounds
4189 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4190 })
4191 .map(|r| (r.expected - r.answered, r.round));
4192 match unanswered {
4193 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4194 detail.push_str(&format!(
4195 " ({}: {})",
4196 last.node,
4197 (p.reviewers_never_answered)(missing, rounds)
4198 ));
4199 }
4200 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4201 }
4202 }
4203 detail.push_str(&format!(" [run {}]", state.id));
4204 detail
4205}
4206
4207const DIAGNOSTIC_MAX: usize = 4_000;
4213
4214const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4219
4220fn diagnostic(state: &RunState) -> Option<String> {
4234 let mut parts: Vec<String> = Vec::new();
4235
4236 for o in state.gate.iter().filter(|o| !o.ok()) {
4238 parts.push(format!(
4239 "gate `{}` failed ({:?}):\n{}",
4240 o.command,
4241 o.code,
4242 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4243 ));
4244 }
4245
4246 if let Some(last) = state
4249 .events
4250 .iter()
4251 .rev()
4252 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4253 {
4254 parts.push(last.message.clone());
4255 }
4256
4257 if state.viable().is_empty() {
4264 for c in &state.candidates {
4265 if let Some(evidence) = &c.verified_noop {
4266 parts.push(format!(
4267 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4268 c.label
4269 ));
4270 } else if !c.summary.trim().is_empty() {
4271 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4272 } else if let Some(why) = &c.failed {
4273 parts.push(format!("candidate {}: {why}", c.label));
4274 }
4275 }
4276 }
4277
4278 if parts.is_empty() {
4279 return None;
4280 }
4281 Some(crate::run::tail(
4286 &parts.join("\n\n"),
4287 DIAGNOSTIC_MAX.saturating_sub(100),
4288 ))
4289}
4290
4291fn label(status: RunStatus) -> &'static str {
4299 status.as_str()
4300}
4301
4302pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4304 match mode {
4305 "none" => Ok(MergeMode::None),
4306 "local" => Ok(MergeMode::Local),
4307 "pr" => Ok(MergeMode::Pr),
4308 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4309 }
4310}
4311
4312fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4317 mutex
4318 .lock()
4319 .unwrap_or_else(std::sync::PoisonError::into_inner)
4320}
4321
4322#[cfg(test)]
4323mod tests {
4324 use super::*;
4325 use crate::queue::{Source, TaskStatus};
4326 use crate::run::{Candidate, CommandOutcome};
4327 use pretty_assertions::assert_eq;
4328
4329 fn task() -> Task {
4330 Task::new(
4331 "add retries".to_owned(),
4332 "add retries".to_owned(),
4333 PathBuf::from("/repo"),
4334 Source::Human,
4335 )
4336 }
4337
4338 #[test]
4342 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
4343 let mut state = RunState::new(
4344 PathBuf::from("/repo"),
4345 "main".to_owned(),
4346 "abc1234".to_owned(),
4347 "task".to_owned(),
4348 Config::default(),
4349 );
4350 state.status = RunStatus::Blocked;
4351 state.resource_block = Some(crate::run::ResourceBlock {
4352 node: "graft".to_owned(),
4353 kind: "shared build cache".to_owned(),
4354 detail: "timed out".to_owned(),
4355 at: jiff::Timestamp::now(),
4356 });
4357 let mut t = task();
4358 t.start("20260902-000000-aaaa".to_owned());
4359 assert_eq!(t.attempts, 1);
4360 let verdict = Verdict {
4361 status: RunStatus::Blocked,
4362 left_pr: false,
4363 quota_hit: false,
4364 parked: false,
4365 no_viable_candidates: false,
4366 };
4367 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
4368 assert_eq!(t.status, TaskStatus::Held);
4369 assert_eq!(t.attempts, 0, "the attempt is refunded");
4370 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
4371 assert!(
4372 !t.operator_held(),
4373 "a machine hold, released without a human"
4374 );
4375
4376 let mut p = task();
4378 p.start("20260902-000000-bbbb".to_owned());
4379 settle_and_diagnose(
4380 &mut p,
4381 Verdict {
4382 parked: true,
4383 ..verdict
4384 },
4385 "parked",
4386 2,
4387 &state,
4388 );
4389 assert_eq!(p.status, TaskStatus::Parked);
4390 }
4391
4392 #[test]
4393 fn record_failure_notice_links_the_task() {
4394 let dir = tempfile::tempdir().unwrap();
4395 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
4398 let queue = Queue::at(dir.path().join("queue"));
4399 let mut t = interrupt_task("rec-fail-1");
4400 record(&queue, &mut t);
4401
4402 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
4403 assert_eq!(found.len(), 1);
4404 assert_eq!(found[0].key, "loop:record");
4405 assert_eq!(
4406 found[0].link,
4407 Some(Link::Task {
4408 id: "rec-fail-1".to_owned()
4409 })
4410 );
4411 }
4412
4413 fn interrupt_task(id: &str) -> Task {
4416 let mut t = task();
4417 t.id = id.to_owned();
4418 t.interrupt = true;
4419 t
4420 }
4421
4422 fn task_with_id(id: &str) -> Task {
4424 let mut t = task();
4425 t.id = id.to_owned();
4426 t
4427 }
4428
4429 fn urgent_task(id: &str) -> Task {
4431 let mut t = task();
4432 t.id = id.to_owned();
4433 t.urgent = true;
4434 t
4435 }
4436
4437 #[test]
4442 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4443 assert_eq!(permit_kind(true, false), PermitKind::None);
4444 assert_eq!(permit_kind(true, true), PermitKind::None);
4445 }
4446
4447 #[test]
4452 fn permit_kind_separates_urgent_from_ordinary() {
4453 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4454 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4455 }
4456
4457 #[test]
4464 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4465 let cfg = Config::default();
4466 let repo = Path::new("/any/repo/path");
4467
4468 let reason =
4469 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4470 assert!(reason.contains("1024"), "{reason}");
4471 assert!(
4472 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4473 "{reason}"
4474 );
4475
4476 assert_eq!(
4477 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4478 None,
4479 "exactly at the floor is open"
4480 );
4481 assert_eq!(
4482 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4483 None,
4484 "comfortably above the floor is open"
4485 );
4486 }
4487
4488 #[test]
4489 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4490 let mut cfg = Config::default();
4491 cfg.disk.min_free_bytes = 0;
4492 let repo = Path::new("/any/repo/path");
4493 assert_eq!(
4494 disk_gate_with(repo, &cfg, |_| Ok(0)),
4495 None,
4496 "a zero floor never measures at all"
4497 );
4498 }
4499
4500 #[test]
4501 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
4502 let cfg = Config::default();
4503 let repo = Path::new("/any/repo/path");
4504 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
4505 .expect("a measurement failure must close the gate, not open it");
4506 assert!(reason.contains("could not measure"), "{reason}");
4507 }
4508
4509 #[test]
4510 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
4511 let ordinary = task();
4512 let next = advance_interrupt(
4513 Interrupt::Idle,
4514 std::slice::from_ref(&ordinary.id),
4515 std::slice::from_ref(&ordinary),
4516 );
4517 assert_eq!(next, Interrupt::Idle);
4518 }
4519
4520 #[test]
4521 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
4522 let marked = interrupt_task("marked");
4525 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4526 assert_eq!(next, Interrupt::Idle);
4527 }
4528
4529 #[test]
4530 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
4531 let marked = interrupt_task("marked");
4532 let next = advance_interrupt(
4533 Interrupt::Idle,
4534 &["running".to_owned()],
4535 std::slice::from_ref(&marked),
4536 );
4537 assert_eq!(
4538 next,
4539 Interrupt::Parking {
4540 parked: vec!["running".to_owned()],
4541 interrupt_task: "marked".to_owned(),
4542 }
4543 );
4544 }
4545
4546 #[test]
4555 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
4556 let marked = interrupt_task("marked");
4557
4558 let two = advance_interrupt(
4559 Interrupt::Idle,
4560 &["a".to_owned(), "b".to_owned()],
4561 std::slice::from_ref(&marked),
4562 );
4563 assert_eq!(two, Interrupt::Idle);
4564
4565 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4566 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
4567 }
4568
4569 #[test]
4570 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
4571 let state = Interrupt::Parking {
4572 parked: vec!["running".to_owned()],
4573 interrupt_task: "marked".to_owned(),
4574 };
4575 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
4577 assert_eq!(still_going, state);
4578
4579 let stopped_but_not_yet_dispatched =
4583 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
4584 assert_eq!(stopped_but_not_yet_dispatched, state);
4585
4586 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
4588 assert_eq!(
4589 dispatched,
4590 Interrupt::Running {
4591 parked: vec!["running".to_owned()],
4592 interrupt_task: "marked".to_owned(),
4593 }
4594 );
4595 }
4596
4597 #[test]
4598 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
4599 let state = Interrupt::Running {
4600 parked: vec!["running".to_owned()],
4601 interrupt_task: "marked".to_owned(),
4602 };
4603 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
4604 assert_eq!(still_running, state);
4605
4606 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
4613 assert_eq!(
4614 ended,
4615 Interrupt::Resuming {
4616 parked: vec!["running".to_owned()]
4617 }
4618 );
4619 }
4620
4621 #[test]
4622 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
4623 let state = Interrupt::Resuming {
4624 parked: vec!["running".to_owned()],
4625 };
4626 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
4627 assert_eq!(still_waiting, state);
4628
4629 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
4630 assert_eq!(dispatched, Interrupt::Idle);
4631 }
4632
4633 #[test]
4639 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
4640 {
4641 let state = Interrupt::Parking {
4642 parked: vec!["running".to_owned()],
4643 interrupt_task: "marked".to_owned(),
4644 };
4645 let next = advance_interrupt(state, &[], &[]);
4648 assert_eq!(
4649 next,
4650 Interrupt::Resuming {
4651 parked: vec!["running".to_owned()]
4652 },
4653 "abandoning the interrupt must not abandon the resume it owes"
4654 );
4655 }
4656
4657 #[test]
4660 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
4661 let state = Interrupt::Resuming {
4662 parked: vec!["running".to_owned()],
4663 };
4664 let next = advance_interrupt(state, &[], &[]);
4665 assert_eq!(
4666 next,
4667 Interrupt::Idle,
4668 "nothing is left to wait for; the loop must not stay wedged"
4669 );
4670 }
4671
4672 #[test]
4673 fn disabled_by_config_the_sequence_can_never_leave_idle() {
4674 let marked = interrupt_task("marked");
4675 let next = advance_interrupt_tick(
4676 false,
4677 Interrupt::Idle,
4678 &["running".to_owned()],
4679 std::slice::from_ref(&marked),
4680 );
4681 assert_eq!(
4682 next,
4683 Interrupt::Idle,
4684 "an unmarked, unconfigured daemon must behave exactly as before"
4685 );
4686 }
4687
4688 #[test]
4689 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
4690 let state = Interrupt::Parking {
4691 parked: vec!["running".to_owned()],
4692 interrupt_task: "marked".to_owned(),
4693 };
4694 let candidates = vec![interrupt_task("marked"), task()];
4695 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4696 assert!(
4697 allowed.is_empty(),
4698 "nothing may dispatch - not even the interrupt task itself - \
4699 until the parked run has actually stopped"
4700 );
4701 }
4702
4703 #[test]
4717 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
4718 for state in [
4719 Interrupt::Parking {
4720 parked: vec!["running".to_owned()],
4721 interrupt_task: "marked".to_owned(),
4722 },
4723 Interrupt::Running {
4724 parked: vec!["running".to_owned()],
4725 interrupt_task: "marked".to_owned(),
4726 },
4727 Interrupt::Resuming {
4728 parked: vec!["running".to_owned()],
4729 },
4730 ] {
4731 let candidates = vec![
4732 interrupt_task("marked"),
4733 urgent_task("hot"),
4734 task_with_id("ordinary"),
4735 ];
4736 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4737 assert!(
4738 !allowed.iter().any(|t| t.id == "hot"),
4739 "an urgent candidate must wait out the same gate as anything \
4740 else while the run it would run alongside has not actually \
4741 left flight, for state {state:?}: {allowed:?}"
4742 );
4743 }
4744 }
4745
4746 #[test]
4752 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
4753 let state = Interrupt::Resuming {
4754 parked: vec!["hot".to_owned()],
4755 };
4756 let candidates = vec![urgent_task("hot"), task()];
4757 let allowed = interrupt_gate(&state, &[], candidates);
4758 assert_eq!(
4759 allowed.iter().filter(|t| t.id == "hot").count(),
4760 1,
4761 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
4762 );
4763 }
4764
4765 #[test]
4766 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
4767 let state = Interrupt::Parking {
4768 parked: vec!["running".to_owned()],
4769 interrupt_task: "marked".to_owned(),
4770 };
4771 let other = task();
4772 let candidates = vec![interrupt_task("marked"), other.clone()];
4773 let allowed = interrupt_gate(&state, &[], candidates);
4774 assert_eq!(allowed.len(), 1);
4775 assert_eq!(allowed[0].id, "marked");
4776 }
4777
4778 #[test]
4779 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4780 let state = Interrupt::Running {
4781 parked: vec!["running".to_owned()],
4782 interrupt_task: "marked".to_owned(),
4783 };
4784 let candidates = vec![task(), task()];
4785 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4786 assert!(allowed.is_empty());
4787 }
4788
4789 #[test]
4796 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4797 let state = Interrupt::Resuming {
4798 parked: vec!["a".to_owned(), "c".to_owned()],
4799 };
4800 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4801 let allowed = interrupt_gate(&state, &[], candidates);
4802 assert_eq!(
4803 allowed.len(),
4804 1,
4805 "at most one candidate may be offered while resuming: {allowed:?}"
4806 );
4807 assert_eq!(allowed[0].id, "a");
4808 }
4809
4810 #[test]
4811 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4812 let state = Interrupt::Resuming {
4813 parked: vec!["a".to_owned()],
4814 };
4815 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4816 assert!(allowed.is_empty());
4817 }
4818
4819 #[test]
4825 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4826 let running = task(); let marked = interrupt_task("marked");
4828
4829 let mut state = Interrupt::Idle;
4830 let in_flight = vec![running.id.clone()];
4832 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4833 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4834 assert!(gated.is_empty(), "still waiting on `running` to park");
4835
4836 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4838 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4839 assert_eq!(
4840 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4841 vec!["marked"],
4842 "only the interrupt task may be offered to the dispatcher now"
4843 );
4844
4845 state = advance_interrupt_tick(
4847 true,
4848 state,
4849 &["marked".to_owned()],
4850 std::slice::from_ref(&running),
4851 );
4852 let gated = interrupt_gate(
4853 &state,
4854 &["marked".to_owned()],
4855 vec![marked.clone(), running.clone()],
4856 );
4857 assert!(
4858 gated.is_empty(),
4859 "the parked run must not be offered back while the interrupt \
4860 task is still running"
4861 );
4862
4863 let other = task_with_id("other");
4867 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4868 assert_eq!(
4869 state,
4870 Interrupt::Resuming {
4871 parked: vec![running.id.clone()]
4872 }
4873 );
4874 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4875 assert_eq!(
4876 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4877 vec![running.id.as_str()],
4878 "exactly the parked run resumes - not the unrelated task, even \
4879 though it was offered first"
4880 );
4881
4882 state = advance_interrupt_tick(
4886 true,
4887 state,
4888 std::slice::from_ref(&running.id),
4889 std::slice::from_ref(&other),
4890 );
4891 assert_eq!(state, Interrupt::Idle);
4892 let gated = interrupt_gate(
4893 &state,
4894 std::slice::from_ref(&running.id),
4895 vec![other.clone()],
4896 );
4897 assert_eq!(
4898 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4899 vec![other.id.as_str()],
4900 "ordinary dispatch is unrestricted again"
4901 );
4902 }
4903
4904 #[test]
4905 fn every_run_status_settles_the_task_it_came_from() {
4906 let table = [
4908 (RunStatus::Merged, TaskStatus::Done, 1),
4909 (RunStatus::Ready, TaskStatus::Done, 1),
4910 (RunStatus::Stalled, TaskStatus::Failed, 0),
4911 (RunStatus::Blocked, TaskStatus::Failed, 1),
4912 (RunStatus::Failed, TaskStatus::Failed, 1),
4913 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4914 (RunStatus::Prep, TaskStatus::Failed, 1),
4915 (RunStatus::Implementing, TaskStatus::Failed, 1),
4916 (RunStatus::Judging, TaskStatus::Failed, 1),
4917 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4918 (RunStatus::Voting, TaskStatus::Failed, 1),
4919 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4920 (RunStatus::Gating, TaskStatus::Failed, 1),
4921 ];
4922 for (run, want, attempts) in table {
4923 let mut t = task();
4924 t.start("20260902-000000-aaaa".to_owned());
4925 settle(
4926 &mut t,
4927 Verdict {
4928 status: run,
4929 left_pr: false,
4930 parked: false,
4931 quota_hit: matches!(run, RunStatus::Stalled),
4932 no_viable_candidates: false,
4933 },
4934 "why",
4935 2,
4936 );
4937 assert_eq!(t.status, want, "task status after {}", label(run));
4938 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4939 }
4940 }
4941
4942 #[test]
4943 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4944 let mut stalled = task();
4945 stalled.start("20260902-000000-aaaa".to_owned());
4946 settle(
4947 &mut stalled,
4948 Verdict {
4949 status: RunStatus::Stalled,
4950 left_pr: false,
4951 parked: false,
4952 quota_hit: true,
4953 no_viable_candidates: false,
4954 },
4955 "quota",
4956 1,
4957 );
4958 assert_eq!(stalled.attempts, 0);
4959 assert!(
4960 stalled.status.runnable(),
4961 "a machine problem must leave the task in line"
4962 );
4963
4964 let mut blocked = task();
4965 blocked.start("20260902-000000-aaaa".to_owned());
4966 settle(
4967 &mut blocked,
4968 Verdict {
4969 status: RunStatus::Blocked,
4970 left_pr: false,
4971 parked: false,
4972 quota_hit: false,
4973 no_viable_candidates: false,
4974 },
4975 "findings open",
4976 1,
4977 );
4978 assert_eq!(blocked.attempts, 1);
4979 assert_eq!(
4980 blocked.status,
4981 TaskStatus::Held,
4982 "the last attempt hands the task to a human"
4983 );
4984 }
4985
4986 #[test]
4987 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4988 let mut delivered = task();
4991 delivered.start("20260903-080619-01c2".to_owned());
4992 settle(
4993 &mut delivered,
4994 Verdict {
4995 status: RunStatus::Blocked,
4996 left_pr: true,
4997 parked: false,
4998 quota_hit: false,
4999 no_viable_candidates: false,
5000 },
5001 "no check status",
5002 4,
5003 );
5004 assert_eq!(
5005 delivered.status,
5006 TaskStatus::Held,
5007 "a pull request waiting on CI or a person is not a retryable failure"
5008 );
5009 assert!(
5010 !delivered.status.runnable(),
5011 "the loop must not pick this task up again"
5012 );
5013 assert_eq!(
5014 delivered.last_error.as_deref(),
5015 Some("no check status"),
5016 "the operator needs to be told what the gate was waiting for"
5017 );
5018
5019 let mut empty_handed = task();
5022 empty_handed.start("20260903-080619-01c2".to_owned());
5023 settle(
5024 &mut empty_handed,
5025 Verdict {
5026 status: RunStatus::Blocked,
5027 left_pr: false,
5028 parked: false,
5029 quota_hit: false,
5030 no_viable_candidates: false,
5031 },
5032 "findings open",
5033 4,
5034 );
5035 assert_eq!(empty_handed.status, TaskStatus::Failed);
5036 assert!(empty_handed.status.runnable());
5037 }
5038
5039 #[test]
5040 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
5041 let mut noop = task();
5047 noop.start("20260912-131304-391f".to_owned());
5048 settle(
5049 &mut noop,
5050 Verdict {
5051 status: RunStatus::VerifiedNoop,
5052 left_pr: false,
5053 parked: false,
5054 quota_hit: false,
5055 no_viable_candidates: true,
5056 },
5057 "candidate A: already fixed by b32cfc4, on main",
5058 4,
5059 );
5060 assert_eq!(
5061 noop.status,
5062 TaskStatus::Held,
5063 "an unverified claim is a request for a human, not a failure"
5064 );
5065 assert!(
5066 !noop.status.runnable(),
5067 "the loop must not requeue this on the same unverified claim"
5068 );
5069 assert_eq!(noop.attempts, 1);
5074 }
5075
5076 #[test]
5077 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
5078 let mut parked = task();
5083 parked.start("20260903-183634-2d98".to_owned());
5084 settle(
5085 &mut parked,
5086 Verdict {
5087 status: RunStatus::Implementing,
5088 left_pr: false,
5089 quota_hit: false,
5090 parked: true,
5091 no_viable_candidates: false,
5092 },
5093 "parked after `implementing`",
5094 2,
5095 );
5096 assert_eq!(parked.attempts, 0, "a park is refunded");
5097 assert!(
5098 parked.status.runnable(),
5099 "and the task stays in line so the next loop resumes its run"
5100 );
5101 assert_eq!(parked.status, TaskStatus::Parked);
5102 assert_eq!(
5103 parked.park_reason.as_deref(),
5104 Some("parked after `implementing`"),
5105 "the card says where it stopped"
5106 );
5107 assert_eq!(parked.last_error, None, "nothing failed");
5108
5109 let mut broken = task();
5113 broken.start("20260903-183634-2d98".to_owned());
5114 settle(
5115 &mut broken,
5116 Verdict {
5117 status: RunStatus::Implementing,
5118 left_pr: false,
5119 quota_hit: false,
5120 parked: false,
5121 no_viable_candidates: false,
5122 },
5123 "returned mid-flight",
5124 2,
5125 );
5126 assert_eq!(broken.attempts, 1);
5127 }
5128
5129 #[test]
5130 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
5131 let mut flaky = task();
5136 flaky.start("20260903-123023-e633".to_owned());
5137 settle(
5138 &mut flaky,
5139 Verdict {
5140 status: RunStatus::Stalled,
5141 left_pr: false,
5142 parked: false,
5143 quota_hit: false,
5144 no_viable_candidates: false,
5145 },
5146 "verdict rests on 1 of 3 judges",
5147 2,
5148 );
5149 assert_eq!(
5150 flaky.attempts, 1,
5151 "flakiness spends an attempt, so `max_attempts` still bounds it"
5152 );
5153 assert!(flaky.status.runnable(), "and it is still worth retrying");
5154
5155 let mut limited = task();
5157 limited.start("20260903-123023-e633".to_owned());
5158 settle(
5159 &mut limited,
5160 Verdict {
5161 status: RunStatus::Stalled,
5162 left_pr: false,
5163 parked: false,
5164 quota_hit: true,
5165 no_viable_candidates: false,
5166 },
5167 "judge-2, judge-3 out of quota",
5168 2,
5169 );
5170 assert_eq!(limited.attempts, 0, "a quota window is refunded");
5171 assert!(limited.status.runnable());
5172
5173 let mut worn = task();
5176 for _ in 0..2 {
5177 worn.release();
5178 }
5179 worn.start("20260903-123023-e633".to_owned());
5180 worn.attempts = 2;
5181 settle(
5182 &mut worn,
5183 Verdict {
5184 status: RunStatus::Stalled,
5185 left_pr: false,
5186 parked: false,
5187 quota_hit: false,
5188 no_viable_candidates: false,
5189 },
5190 "no quorum again",
5191 2,
5192 );
5193 assert_eq!(worn.status, TaskStatus::Held);
5194 assert!(!worn.status.runnable());
5195 }
5196
5197 #[test]
5198 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5199 let mut wiped_out = task();
5206 wiped_out.start("20260907-025000-a1b2".to_owned());
5207 settle(
5208 &mut wiped_out,
5209 Verdict {
5210 status: RunStatus::Failed,
5211 left_pr: false,
5212 parked: false,
5213 quota_hit: true,
5214 no_viable_candidates: true,
5215 },
5216 "no candidate produced a change; nothing to judge",
5217 2,
5218 );
5219 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5220 assert!(
5221 wiped_out.status.runnable(),
5222 "a machine problem must leave the task in line"
5223 );
5224
5225 let mut partial_progress = task();
5231 partial_progress.start("20260907-025500-c3d4".to_owned());
5232 settle(
5233 &mut partial_progress,
5234 Verdict {
5235 status: RunStatus::Failed,
5236 left_pr: false,
5237 parked: false,
5238 quota_hit: true,
5239 no_viable_candidates: false,
5240 },
5241 "gate failed on the winning candidate",
5242 2,
5243 );
5244 assert_eq!(
5245 partial_progress.attempts, 1,
5246 "a candidate that actually produced a change spends the attempt \
5247 even though some other seat hit its quota"
5248 );
5249 assert!(partial_progress.status.runnable());
5250 }
5251
5252 #[test]
5253 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5254 let mut t = task();
5260 t.start("20260907-025000-a1b2".to_owned());
5261 let mut state = run_state(RunStatus::Failed);
5262 state.quota.push(QuotaLoss {
5263 seat: "cand-a".to_owned(),
5264 node: "implement".to_owned(),
5265 at: Timestamp::now(),
5266 reset: None,
5267 });
5268 assert!(
5269 state.viable().is_empty(),
5270 "no candidate was added, so nothing is viable"
5271 );
5272 reclaim(&mut t, Some(state), 2, "en");
5273 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5274 assert!(t.status.runnable());
5275 }
5276
5277 #[test]
5278 fn a_held_task_is_never_offered_to_the_loop() {
5279 let dir = tempfile::tempdir().unwrap();
5280 let queue = Queue::at(dir.path().to_path_buf());
5281 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5282 let mut t = task();
5283 t.id = format!("2026090{n}-000000-000{n}");
5284 t.priority = priority;
5285 queue.put(&mut t).unwrap();
5286 }
5287 let mut held = task();
5288 held.id = "20260909-000000-9999".to_owned();
5289 held.priority = 99;
5290 held.hold_machine(None);
5291 queue.put(&mut held).unwrap();
5292
5293 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5294 assert_eq!(order.len(), 3);
5295 assert!(!order.contains(&held.id));
5296 assert_eq!(
5297 order.first().cloned(),
5298 queue.next_runnable().map(|t| t.id),
5299 "the loop's first candidate is exactly what the queue offers"
5300 );
5301 assert_eq!(
5302 order,
5303 vec![
5304 "20260902-000000-0002".to_owned(),
5305 "20260903-000000-0003".to_owned(),
5306 "20260901-000000-0001".to_owned(),
5307 ],
5308 "priority first, then oldest, so nothing starves"
5309 );
5310 }
5311
5312 #[test]
5313 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5314 let dir = tempfile::tempdir().unwrap();
5315 let queue = Queue::at(dir.path().to_path_buf());
5316 let mut old = task();
5317 old.id = "20260101-000000-old0".to_owned();
5318 queue.put(&mut old).unwrap();
5319 let mut fresh = task();
5320 fresh.id = "20260101-000000-new0".to_owned();
5321 queue.put(&mut fresh).unwrap();
5322
5323 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5327 std::thread::sleep(Duration::from_millis(60));
5328 let live = queue.claim(&fresh.id).unwrap();
5329
5330 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5331 assert_eq!(swept, vec![old.id.clone()]);
5332 assert!(
5333 queue.claim(&old.id).is_ok(),
5334 "an unparseable lock older than the threshold is swept"
5335 );
5336 assert!(
5337 queue.claim(&fresh.id).is_err(),
5338 "a live pid protects its lock regardless of age"
5339 );
5340 drop(live);
5341 }
5342
5343 #[test]
5344 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5345 let dir = tempfile::tempdir().unwrap();
5355 let queue = Queue::at(dir.path().to_path_buf());
5356 let mut t = task();
5357 t.id = "20260101-000000-live".to_owned();
5358 queue.put(&mut t).unwrap();
5359
5360 let claim = queue.claim(&t.id).unwrap();
5361 std::thread::sleep(Duration::from_millis(60));
5362
5363 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5364 assert!(
5365 swept.is_empty(),
5366 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5367 );
5368 assert!(
5369 queue.claim(&t.id).is_err(),
5370 "the lock still protects its task"
5371 );
5372 drop(claim);
5373 }
5374
5375 fn injected_dead_pid() -> u32 {
5378 std::process::id().checked_add(1).unwrap_or(1)
5379 }
5380
5381 #[test]
5382 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5383 let dir = tempfile::tempdir().unwrap();
5384 let queue = Queue::at(dir.path().to_path_buf());
5385 let mut t = task();
5386 t.id = "20260101-000000-dead".to_owned();
5387 queue.put(&mut t).unwrap();
5388 let dead_pid = injected_dead_pid();
5389
5390 std::fs::write(
5395 dir.path().join(format!("{}.lock", t.id)),
5396 dead_pid.to_string(),
5397 )
5398 .unwrap();
5399
5400 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5401 pid != dead_pid
5402 });
5403 assert_eq!(
5404 swept,
5405 vec![t.id.clone()],
5406 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5407 );
5408 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5409 }
5410
5411 #[test]
5412 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5413 let dir = tempfile::tempdir().unwrap();
5414 let queue = Queue::at(dir.path().to_path_buf());
5415 let mut t = task();
5416 t.id = "20260101-000000-late".to_owned();
5417 queue.put(&mut t).unwrap();
5418 let dead_pid = injected_dead_pid();
5419
5420 assert!(
5423 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5424 "nothing has claimed the task yet"
5425 );
5426
5427 std::fs::write(
5430 dir.path().join(format!("{}.lock", t.id)),
5431 dead_pid.to_string(),
5432 )
5433 .unwrap();
5434
5435 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5439 pid != dead_pid
5440 });
5441 assert_eq!(swept, vec![t.id.clone()]);
5442 }
5443
5444 #[test]
5445 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5446 crate::run::pin_test_home();
5451 let dir = tempfile::tempdir().unwrap();
5452 let queue = Queue::at(dir.path().to_path_buf());
5453 let mut t = task();
5454 t.id = "20260101-000000-crsh".to_owned();
5455 t.status = TaskStatus::Running;
5456 t.attempts = 1;
5457 t.runs.push("20260904-000000-4043".to_owned());
5461 queue.put(&mut t).unwrap();
5462 let dead_pid = injected_dead_pid();
5463
5464 std::fs::write(
5467 dir.path().join(format!("{}.lock", t.id)),
5468 dead_pid.to_string(),
5469 )
5470 .unwrap();
5471
5472 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5478 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5479
5480 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5481 pid != dead_pid
5482 });
5483 assert_eq!(swept, vec![t.id.clone()]);
5484
5485 let reclaimed = reclaim_orphaned_running(&queue, 2);
5486 assert_eq!(reclaimed, vec![t.id.clone()]);
5487 let after = queue.get(&t.id).unwrap();
5488 assert_eq!(
5489 after.status,
5490 TaskStatus::Held,
5491 "no run.json to recover from, so a human is asked"
5492 );
5493 assert_eq!(
5494 after.runs,
5495 vec!["20260904-000000-4043".to_owned()],
5496 "the crashed run's id is kept as evidence, not discarded"
5497 );
5498 }
5499
5500 #[test]
5501 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
5502 let dir = tempfile::tempdir().unwrap();
5503 let queue = Queue::at(dir.path().to_path_buf());
5504 let mut t = task();
5505 t.id = "20260101-000000-unknown".to_owned();
5506 queue.put(&mut t).unwrap();
5507 let dead_pid = injected_dead_pid();
5508 std::fs::write(
5509 dir.path().join(format!("{}.lock", t.id)),
5510 dead_pid.to_string(),
5511 )
5512 .unwrap();
5513
5514 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
5515 assert!(swept.is_empty(), "an unknown pid must keep its lock");
5516 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
5517 }
5518
5519 fn run_state_in(status: RunStatus, language: &str) -> RunState {
5520 let mut s = run_state(status);
5521 s.config.graph.language = language.to_owned();
5522 s
5523 }
5524
5525 fn unstarted_verdict(status: RunStatus) -> Verdict {
5526 Verdict {
5527 status,
5528 left_pr: false,
5529 quota_hit: false,
5530 parked: false,
5531 no_viable_candidates: false,
5532 }
5533 }
5534
5535 #[test]
5536 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
5537 let mut t = task();
5538 t.attempts = 1;
5539 settle_in(
5540 &mut t,
5541 unstarted_verdict(RunStatus::AlreadyInBase),
5542 "already in main",
5543 1,
5544 phrases("en"),
5545 );
5546 assert_eq!(t.status, TaskStatus::Done);
5547 assert_eq!(t.attempts, 0);
5548 }
5549
5550 #[test]
5551 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
5552 let reason = |language: &str| {
5553 let mut t = task();
5554 settle_in(
5555 &mut t,
5556 unstarted_verdict(RunStatus::Judging),
5557 "boom",
5558 1,
5559 phrases(language),
5560 );
5561 t.last_error.or(t.hold_reason).unwrap_or_default()
5562 };
5563 assert!(
5564 reason("en").starts_with("the graph stopped at `"),
5565 "{}",
5566 reason("en")
5567 );
5568 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
5569 assert!(reason("日本語").contains("boom"));
5570 assert_eq!(reason("fr"), reason("en"));
5571 }
5572
5573 #[test]
5574 fn describe_follows_the_run_language_and_keeps_the_run_id() {
5575 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
5576 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
5577 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
5578 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
5579 assert!(ja.contains("[run "), "{ja}");
5580 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
5581 assert!(ended.starts_with("run 終了: "), "{ended}");
5582 let mut de = run_state_in(RunStatus::Failed, "de");
5583 let mut en = run_state_in(RunStatus::Failed, "en");
5584 de.id = "same".to_owned();
5585 en.id = "same".to_owned();
5586 assert_eq!(describe(&de), describe(&en));
5587 }
5588
5589 #[test]
5590 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
5591 use crate::handover::Refused;
5592 let cases = [
5593 Refused::Foreign {
5594 branch: "b".into(),
5595 path: "/w/x".into(),
5596 why: "made by hand".into(),
5597 },
5598 Refused::Unsafe {
5599 branch: "b".into(),
5600 path: "/w/x".into(),
5601 why: "its worktree has uncommitted changes (a.rs)".into(),
5602 },
5603 Refused::ReleaseFailed {
5604 branch: "b".into(),
5605 path: "/w/x".into(),
5606 run: "ab12".into(),
5607 },
5608 ];
5609 for r in &cases {
5610 let en = (phrases("en").handover_refused)(r);
5611 assert_eq!(en, r.to_string());
5612 let ja = (phrases("ja").handover_refused)(r);
5613 assert!(
5614 !ja.contains("is checked out") && !ja.contains("try again"),
5615 "{ja}"
5616 );
5617 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
5618 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
5619 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
5620 }
5621 }
5622 assert!(phrases("en").handover_hint.contains("release the task"));
5623 assert!(phrases("ja").handover_hint.contains("解放"));
5624 }
5625
5626 #[test]
5627 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
5628 let build = |lang: &str| {
5629 let mut s = run_state_in(RunStatus::Blocked, lang);
5630 s.id = "same".to_owned();
5631 s.config.graph.review_rounds = 3;
5632 let mut r = review_round(3);
5633 r.expected = 3;
5634 r.answered = 1;
5635 s.reviews.push(r);
5636 s.event(
5637 "review",
5638 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
5639 );
5640 s
5641 };
5642 let en = describe(&build("en"));
5643 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
5644 let ja = describe(&build("ja"));
5645 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
5646 assert!(!ja.contains("never answered"), "{ja}");
5647 assert!(ja.contains("[run "), "{ja}");
5648
5649 let mut failed = build("ja");
5652 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
5653 command: "cargo test".to_owned(),
5654 code: Some(1),
5655 output_tail: String::new(),
5656 duration_ms: 0,
5657 resource_blocked: false,
5658 });
5659 failed.event("review", "stopped; e2e failed: cargo test");
5660 let ja = describe(&failed);
5661 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
5662 assert!(!ja.contains("席のレビュアー"), "{ja}");
5663 }
5664
5665 #[test]
5666 fn refusals_and_recovery_prose_follow_the_language() {
5667 let t = held_task_with("r1");
5668 let q = action_question(
5669 "r1",
5670 ask::ChoiceAction::Resume {
5671 run: "r1".to_owned(),
5672 },
5673 );
5674 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
5675 ActionDecision::Refuse(s) => s,
5676 other => panic!("{other:?}"),
5677 };
5678 assert!(refuse(phrases("en")).contains("could not be read: gone"));
5679 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
5680 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
5681
5682 let mut held = task();
5683 reclaim(&mut held, None, 2, "ja");
5684 assert!(held.hold_reason.unwrap().contains("保留にしました"));
5685 let mut held = task();
5686 reclaim(&mut held, None, 2, "xx");
5687 assert!(held.hold_reason.unwrap().contains("held for a human"));
5688 }
5689
5690 fn run_state(status: RunStatus) -> RunState {
5691 let mut state = RunState::new(
5692 PathBuf::from("/repo"),
5693 "main".to_owned(),
5694 "abc1234def".to_owned(),
5695 "add retries".to_owned(),
5696 Config::default(),
5697 );
5698 state.status = status;
5699 state
5700 }
5701
5702 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
5703 Candidate {
5704 index: 0,
5705 label,
5706 agent: "claude".to_owned(),
5707 branch: format!("magi/x/{label}"),
5708 worktree: PathBuf::from("/repo"),
5709 summary: summary.to_owned(),
5710 stat: String::new(),
5711 files: 0,
5712 commits: usize::from(!empty),
5713 empty,
5714 failed: failed.map(str::to_owned),
5715 verified_noop: None,
5716 duration_ms: 0,
5717 folded: false,
5718 }
5719 }
5720
5721 #[test]
5722 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
5723 let mut state = run_state(RunStatus::Blocked);
5724 state.gate = vec![
5725 CommandOutcome {
5726 command: "cargo make check".to_owned(),
5727 code: Some(0),
5728 output_tail: "ok".to_owned(),
5729 duration_ms: 0,
5730 resource_blocked: false,
5731 },
5732 CommandOutcome {
5733 command: "cargo test".to_owned(),
5734 code: Some(101),
5735 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
5736 duration_ms: 0,
5737 resource_blocked: false,
5738 },
5739 ];
5740 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
5741 assert!(d.contains("cargo test"), "{d}");
5742 assert!(
5743 !d.contains("cargo make check"),
5744 "a passing check is not a diagnostic: {d}"
5745 );
5746 assert!(d.contains("assertion failed"), "{d}");
5747 }
5748
5749 #[test]
5750 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
5751 let mut state = run_state(RunStatus::Blocked);
5752 state.event(
5753 "land",
5754 "stopped: the fixer produced no commit while 2 check(s) were failing \
5755 (build, lint); stopping instead of looping on an unchanged tree",
5756 );
5757 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
5758 assert!(d.contains("build"), "{d}");
5759 assert!(d.contains("lint"), "{d}");
5760 assert!(d.contains("fixer produced no commit"), "{d}");
5761 }
5762
5763 #[test]
5764 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
5765 let state = run_state(RunStatus::VerifiedNoop);
5770 let d = describe(&state);
5771 assert!(
5772 d.contains("agent-verified no-op"),
5773 "expected the display label, not the wire spelling: {d}"
5774 );
5775 assert!(!d.contains("verified_noop"), "{d}");
5776 }
5777
5778 #[test]
5779 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
5780 let mut state = run_state(RunStatus::Failed);
5786 state.candidates = vec![candidate(
5787 'A',
5788 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
5789 true,
5790 None,
5791 )];
5792 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
5793 assert!(d.contains("candidate A"), "{d}");
5794 assert!(d.contains("tagged v1.2.3"), "{d}");
5795 }
5796
5797 #[test]
5798 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
5799 let mut state = run_state(RunStatus::Failed);
5800 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
5801 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
5802 assert!(d.contains("candidate A"), "{d}");
5803 assert!(d.contains("agent timed out"), "{d}");
5804 }
5805
5806 #[test]
5807 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
5808 let mut state = run_state(RunStatus::Failed);
5811 state.candidates = vec![candidate('A', "did the work", false, None)];
5812 assert!(diagnostic(&state).is_none());
5813 }
5814
5815 #[test]
5816 fn diagnostic_is_bounded_however_much_a_run_printed() {
5817 let mut state = run_state(RunStatus::Blocked);
5818 state.gate = vec![
5819 CommandOutcome {
5820 command: "cargo test".to_owned(),
5821 code: Some(101),
5822 output_tail: "x".repeat(50_000),
5823 duration_ms: 0,
5824 resource_blocked: false,
5825 },
5826 CommandOutcome {
5827 command: "cargo clippy".to_owned(),
5828 code: Some(1),
5829 output_tail: "y".repeat(50_000),
5830 duration_ms: 0,
5831 resource_blocked: false,
5832 },
5833 ];
5834 state.candidates = vec![
5835 candidate('A', &"z".repeat(50_000), true, None),
5836 candidate('B', &"w".repeat(50_000), true, None),
5837 ];
5838 let d = diagnostic(&state).expect("plenty here to diagnose");
5839 assert!(
5840 d.len() <= DIAGNOSTIC_MAX,
5841 "diagnostic grew to {} bytes, unbounded",
5842 d.len()
5843 );
5844 }
5845
5846 #[test]
5847 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
5848 let mut state = run_state(RunStatus::Blocked);
5849 state.gate = vec![CommandOutcome {
5850 command: "cargo test".to_owned(),
5851 code: Some(101),
5852 output_tail: "assertion failed".to_owned(),
5853 duration_ms: 0,
5854 resource_blocked: false,
5855 }];
5856 let verdict = Verdict {
5857 status: RunStatus::Blocked,
5858 left_pr: false,
5859 quota_hit: false,
5860 parked: false,
5861 no_viable_candidates: false,
5862 };
5863
5864 let mut t = task();
5867 t.start("run-1".to_owned());
5868 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5869 assert_eq!(t.status, TaskStatus::Failed);
5870 assert!(t.diagnostic.is_none());
5871
5872 t.start("run-2".to_owned());
5875 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5876 assert_eq!(t.status, TaskStatus::Held);
5877 let d = t.diagnostic.expect("a held task must carry its diagnostic");
5878 assert!(d.contains("cargo test"), "{d}");
5879 }
5880
5881 #[test]
5882 fn a_held_task_names_the_open_question_it_is_waiting_on() {
5883 crate::run::pin_test_home();
5888 let home = crate::run::home();
5889 let state = run_state(RunStatus::VerifiedNoop);
5890 let mut q = ask::Question::new(
5891 state.id.clone(),
5892 "implement".to_owned(),
5893 "impl-A".to_owned(),
5894 "is this really a no-op?".to_owned(),
5895 String::new(),
5896 Vec::new(),
5897 );
5898 Questions::at(home.join("questions")).put(&mut q).unwrap();
5899
5900 let verdict = Verdict {
5901 status: RunStatus::VerifiedNoop,
5902 left_pr: false,
5903 quota_hit: false,
5904 parked: false,
5905 no_viable_candidates: false,
5906 };
5907 let mut t = task();
5908 t.start(state.id.clone());
5909 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5910
5911 assert_eq!(t.status, TaskStatus::Held);
5912 let reason = t.hold_reason.expect("a held task must record why");
5913 assert!(
5914 reason.starts_with("run ended agent-verified no-op"),
5915 "the original settle reason must survive unchanged: {reason}"
5916 );
5917 assert!(
5918 reason.contains(q.short()),
5919 "the open question's id must be named so the notice is actionable: {reason}"
5920 );
5921 }
5922
5923 #[test]
5924 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
5925 crate::run::pin_test_home();
5926 let state = run_state(RunStatus::VerifiedNoop);
5927
5928 let verdict = Verdict {
5929 status: RunStatus::VerifiedNoop,
5930 left_pr: false,
5931 quota_hit: false,
5932 parked: false,
5933 no_viable_candidates: false,
5934 };
5935 let mut t = task();
5936 t.start(state.id.clone());
5937 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5938
5939 assert_eq!(t.status, TaskStatus::Held);
5940 assert_eq!(
5941 t.hold_reason.as_deref(),
5942 Some("run ended agent-verified no-op"),
5943 "nothing to append when the question was already answered or never asked"
5944 );
5945 }
5946
5947 #[test]
5948 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5949 crate::run::pin_test_home();
5950 let mut first = run_state(RunStatus::Blocked);
5951 first.id = "20260101-000000-sup1".to_owned();
5952 first.save().unwrap();
5953 let mut second = run_state(RunStatus::Merged);
5954 second.id = "20260101-000000-sup2".to_owned();
5955 second.save().unwrap();
5956
5957 let mut t = task();
5958 t.runs = vec![first.id.clone(), second.id.clone()];
5959 t.status = TaskStatus::Done;
5960
5961 supersede_prior_runs(&t, &crate::run::home());
5962
5963 assert_eq!(
5964 RunState::load(&first.id).unwrap().status,
5965 RunStatus::Superseded,
5966 "the first attempt's Blocked no longer needs anyone's attention"
5967 );
5968 assert_eq!(
5969 RunState::load(&second.id).unwrap().status,
5970 RunStatus::Merged,
5971 "the run that actually succeeded is left exactly as it was"
5972 );
5973 }
5974
5975 #[test]
5976 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5977 crate::run::pin_test_home();
5983 let mut first = run_state(RunStatus::Blocked);
5984 first.id = "20260101-000000-sup9".to_owned();
5985 first.driver_pid = Some(std::process::id());
5988 first.driver_started_at = Some(
5989 crate::proc::process_started_at(std::process::id())
5990 .expect("this test process's own start time must be queryable"),
5991 );
5992 first.save().unwrap();
5993 let mut second = run_state(RunStatus::Merged);
5994 second.id = "20260101-000000-supa".to_owned();
5995 second.save().unwrap();
5996
5997 let mut t = task();
5998 t.runs = vec![first.id.clone(), second.id.clone()];
5999 t.status = TaskStatus::Done;
6000
6001 supersede_prior_runs(&t, &crate::run::home());
6002
6003 assert_eq!(
6004 RunState::load(&first.id).unwrap().status,
6005 RunStatus::Blocked,
6006 "a live driver_pid means something is still actually working this run, \
6007 even though no daemon claims it - rewriting under it would just be \
6008 undone the next time that process saves"
6009 );
6010 }
6011
6012 #[test]
6013 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
6014 let dir = tempfile::tempdir().unwrap();
6020 let home = dir.path().to_path_buf();
6021 let queue = Queue::at(dir.path().join("queue"));
6022
6023 let mut first = run_state(RunStatus::Blocked);
6024 first.id = "20260101-000000-supd".to_owned();
6025 first.driver_pid = Some(std::process::id());
6026 first.driver_started_at = Some(
6027 crate::proc::process_started_at(std::process::id())
6028 .expect("this test process's own start time must be queryable"),
6029 );
6030 first.save_under(&home).unwrap();
6031 let mut second = run_state(RunStatus::Merged);
6032 second.id = "20260101-000000-supe".to_owned();
6033 second.save_under(&home).unwrap();
6034
6035 let mut t = task();
6036 t.runs = vec![first.id.clone(), second.id.clone()];
6037 t.status = TaskStatus::Done;
6038 queue.put(&mut t).unwrap();
6039
6040 resweep_superseded_attempts(&queue, &home);
6041 assert_eq!(
6042 RunState::load_under(&first.id, &home).unwrap().status,
6043 RunStatus::Blocked,
6044 "still live on the first pass, so still untouched"
6045 );
6046
6047 let mut stale = RunState::load_under(&first.id, &home).unwrap();
6053 stale.driver_started_at = Some("1".to_owned());
6054 stale.save_under(&home).unwrap();
6055
6056 resweep_superseded_attempts(&queue, &home);
6057 assert_eq!(
6058 RunState::load_under(&first.id, &home).unwrap().status,
6059 RunStatus::Superseded,
6060 "the second pass catches up what the first one correctly skipped"
6061 );
6062 }
6063
6064 #[test]
6065 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
6066 crate::run::pin_test_home();
6067 let mut first = run_state(RunStatus::Blocked);
6068 first.id = "20260101-000000-sup3".to_owned();
6069 first.save().unwrap();
6070 let mut second = run_state(RunStatus::Blocked);
6071 second.id = "20260101-000000-sup4".to_owned();
6072 second.save().unwrap();
6073
6074 let mut t = task();
6075 t.runs = vec![first.id.clone(), second.id.clone()];
6076 t.status = TaskStatus::Failed;
6080
6081 supersede_prior_runs(&t, &crate::run::home());
6082
6083 assert_eq!(
6084 RunState::load(&first.id).unwrap().status,
6085 RunStatus::Blocked
6086 );
6087 assert_eq!(
6088 RunState::load(&second.id).unwrap().status,
6089 RunStatus::Blocked
6090 );
6091 }
6092
6093 #[test]
6094 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
6095 crate::run::pin_test_home();
6099 let mut first = run_state(RunStatus::Blocked);
6100 first.id = "20260101-000000-sup5".to_owned();
6101 first.save().unwrap();
6102
6103 let mut t = task();
6104 t.runs = vec![first.id.clone()];
6105 t.status = TaskStatus::Done;
6106
6107 supersede_prior_runs(&t, &crate::run::home());
6108
6109 assert_eq!(
6110 RunState::load(&first.id).unwrap().status,
6111 RunStatus::Blocked,
6112 "a single-attempt task has no earlier run to supersede"
6113 );
6114 }
6115
6116 #[test]
6117 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
6118 crate::run::pin_test_home();
6125 let mut first = run_state(RunStatus::Blocked);
6126 first.id = "20260101-000000-supb".to_owned();
6127 first.save().unwrap();
6128 let mut second = run_state(RunStatus::Failed);
6129 second.id = "20260101-000000-supc".to_owned();
6130 second.save().unwrap();
6131
6132 let mut t = task();
6133 t.runs = vec![first.id.clone(), second.id.clone()];
6134 t.status = TaskStatus::Done;
6135
6136 supersede_prior_runs(&t, &crate::run::home());
6137
6138 assert_eq!(
6139 RunState::load(&first.id).unwrap().status,
6140 RunStatus::Blocked,
6141 "the task's last attempt never landed, so there is nothing here \
6142 actually superseding it"
6143 );
6144 }
6145
6146 #[test]
6147 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6148 crate::run::pin_test_home();
6152 let mut failed = run_state(RunStatus::Failed);
6153 failed.id = "20260101-000000-sup6".to_owned();
6154 failed.save().unwrap();
6155 let mut noop = run_state(RunStatus::VerifiedNoop);
6156 noop.id = "20260101-000000-sup7".to_owned();
6157 noop.save().unwrap();
6158 let mut winner = run_state(RunStatus::Ready);
6159 winner.id = "20260101-000000-sup8".to_owned();
6160 winner.save().unwrap();
6161
6162 let mut t = task();
6163 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6164 t.status = TaskStatus::Done;
6165
6166 supersede_prior_runs(&t, &crate::run::home());
6167
6168 assert_eq!(
6169 RunState::load(&failed.id).unwrap().status,
6170 RunStatus::Failed
6171 );
6172 assert_eq!(
6173 RunState::load(&noop.id).unwrap().status,
6174 RunStatus::VerifiedNoop
6175 );
6176 }
6177
6178 fn approval_question(run: &str) -> ask::Question {
6179 ask::Question::new(
6180 run.to_owned(),
6181 land::APPROVAL_NODE.to_owned(),
6182 "land".to_owned(),
6183 "merge?".to_owned(),
6184 String::new(),
6185 vec!["merge".to_owned(), "hold".to_owned()],
6186 )
6187 }
6188
6189 #[test]
6190 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6191 crate::run::pin_test_home();
6192 let mut state = run_state(RunStatus::Landing);
6193 state.id = "20260101-000000-fre1".to_owned();
6194 state.parked = true;
6195 state.save().unwrap();
6196 ask::Questions::open()
6197 .put(&mut approval_question(&state.id))
6198 .unwrap();
6199
6200 let mut t = task();
6201 t.runs.push(state.id.clone());
6202 assert_eq!(
6203 land_resume_state(&t),
6204 LandResume::StillWaiting,
6205 "nobody has answered and the timeout has not passed"
6206 );
6207 }
6208
6209 #[test]
6210 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6211 crate::run::pin_test_home();
6212 let mut state = run_state(RunStatus::Gating);
6213 state.id = "20260101-000000-gt01".to_owned();
6214 state.parked = true;
6215 state.config.graph.answer_timeout = 60;
6216 state.github_text = Some(crate::run::GithubTextAsk {
6217 rewrite: None,
6218 fingerprint: "f".into(),
6219 title: true,
6220 body: false,
6221 categories: vec!["title-language".into()],
6222 question: None,
6223 asks: 1,
6224 resolved: false,
6225 chosen_title: None,
6226 choice: None,
6227 });
6228 state.save().unwrap();
6229 let store = ask::Questions::open();
6230 let mut q = ask::Question::new(
6231 state.id.clone(),
6232 crate::github_text::ASK_NODE.to_owned(),
6233 crate::github_text::ASK_SEAT.to_owned(),
6234 "s".into(),
6235 String::new(),
6236 vec!["use fallback".into()],
6237 );
6238 store.put(&mut q).unwrap();
6239 let mut t = task();
6240 t.runs.push(state.id.clone());
6241 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6242 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6243 store.put(&mut q).unwrap();
6244 assert_eq!(land_resume_state(&t), LandResume::Ready);
6245 assert!(!store.get(&q.id).unwrap().status.open());
6246 state.github_text.as_mut().unwrap().resolved = true;
6248 state.save().unwrap();
6249 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6250 }
6251
6252 #[test]
6253 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6254 crate::run::pin_test_home();
6259 let mut state = run_state(RunStatus::Landing);
6260 state.id = "20260101-000000-exp1".to_owned();
6261 state.parked = true;
6262 state.config.graph.answer_timeout = 60;
6263 state.save().unwrap();
6264
6265 let store = ask::Questions::open();
6266 let mut q = approval_question(&state.id);
6267 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6268 store.put(&mut q).unwrap();
6269
6270 let mut t = task();
6271 t.runs.push(state.id.clone());
6272 assert_eq!(
6273 land_resume_state(&t),
6274 LandResume::Ready,
6275 "an expired question must not be waited on forever"
6276 );
6277
6278 let after = store.get(&q.id).unwrap();
6279 assert!(
6280 !after.status.open(),
6281 "the question is abandoned, not silently ignored"
6282 );
6283 assert!(
6284 after.resolution().is_none(),
6285 "an abandoned question is not read as a decision"
6286 );
6287 }
6288
6289 #[test]
6290 fn reclaim_settles_a_running_task_against_its_last_run() {
6291 let mut t = task();
6292 t.start("20260904-000000-4043".to_owned());
6293 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6294 assert_eq!(
6295 t.status,
6296 TaskStatus::Done,
6297 "a run that actually finished must not stay `running` forever"
6298 );
6299 }
6300
6301 #[test]
6302 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6303 let mut t = task();
6304 t.start("20260904-000000-4043".to_owned());
6305 t.last_error = Some("earlier trouble".to_owned());
6306 let mut state = run_state(RunStatus::Judging);
6307 state.parked = true;
6308 reclaim(&mut t, Some(state), 1, "en");
6309 assert_eq!(t.status, TaskStatus::Parked);
6310 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6311 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6312 assert!(t.park_reason.is_some());
6313 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6314 assert!(!t.fresh_start);
6315 assert!(t.status.runnable());
6316 }
6317
6318 #[test]
6319 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6320 let mut t = task();
6321 t.start("20260904-000000-4043".to_owned());
6322 t.last_error = Some("earlier trouble".to_owned());
6323 settle(
6324 &mut t,
6325 Verdict {
6326 status: RunStatus::Judging,
6327 left_pr: false,
6328 quota_hit: false,
6329 parked: true,
6330 no_viable_candidates: false,
6331 },
6332 "parked after `judging`",
6333 1,
6334 );
6335 assert_eq!(t.status, TaskStatus::Parked);
6336 assert_eq!(t.attempts, 0);
6337 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6338 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6339 assert_eq!(t.schema, crate::queue::SCHEMA);
6340 assert!(
6341 crate::notices::task_held(&t).is_none(),
6342 "a park is not news"
6343 );
6344 t.start("20260904-000000-4043".to_owned());
6345 assert_eq!(t.park_reason, None);
6346 }
6347
6348 #[test]
6349 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6350 let mut t = task();
6354 t.start("20260904-000000-4043".to_owned());
6355 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6356 assert_eq!(t.status, TaskStatus::Failed);
6357 assert!(t.status.runnable());
6358 }
6359
6360 #[test]
6361 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
6362 let mut t = task();
6363 t.start("20260904-000000-4043".to_owned());
6364 assert_eq!(t.attempts, 1);
6365 let mut run = run_state(RunStatus::Implementing);
6366 run.id = "20260904-000000-4043".to_owned();
6367 run.begin_pass();
6368 let cause = crate::run::ParkCause::Upgrade {
6369 from: "0.121.0".to_owned(),
6370 to: Some("0.121.1".to_owned()),
6371 };
6372 run.end_pass_parked(cause.clone());
6373 run.parked = true;
6374 let verdict = Verdict {
6375 status: run.status,
6376 left_pr: false,
6377 quota_hit: false,
6378 parked: true,
6379 no_viable_candidates: false,
6380 };
6381 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
6382 assert_eq!(t.attempts, 0);
6383 assert_eq!(t.passes.len(), 1);
6384 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6385 assert_eq!(t.passes[0].parked, Some(cause));
6386 assert_eq!(t.passes[0].pass_index, 0);
6387
6388 t.start("20260904-000000-4043".to_owned());
6391 run.begin_pass();
6392 run.status = RunStatus::Failed;
6393 let verdict = Verdict {
6394 status: RunStatus::Failed,
6395 left_pr: false,
6396 quota_hit: false,
6397 parked: false,
6398 no_viable_candidates: false,
6399 };
6400 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
6401 assert_eq!(t.passes.len(), 2);
6402 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6403 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
6404 assert_eq!(t.passes[1].pass_index, 1);
6405 assert_eq!(t.attempts, 1);
6406 }
6407
6408 #[test]
6409 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6410 let mut t = task();
6411 t.start("20260904-000000-4043".to_owned());
6412 reclaim(&mut t, None, 2, "en");
6413 assert_eq!(t.status, TaskStatus::Held);
6414 assert!(
6415 t.last_error
6416 .as_deref()
6417 .is_some_and(|e| e.contains("running")),
6418 "the operator needs to know why this task was held"
6419 );
6420 }
6421
6422 #[test]
6423 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6424 let dir = tempfile::tempdir().unwrap();
6425 let queue = Queue::at(dir.path().to_path_buf());
6426
6427 let mut orphaned = task();
6429 orphaned.id = "20260904-000000-orph".to_owned();
6430 orphaned.status = TaskStatus::Running;
6431 orphaned.attempts = 1;
6432 queue.put(&mut orphaned).unwrap();
6433
6434 let mut alive = task();
6435 alive.id = "20260904-000000-live".to_owned();
6436 alive.status = TaskStatus::Running;
6437 alive.attempts = 1;
6438 queue.put(&mut alive).unwrap();
6439 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6440
6441 let mut queued = task();
6442 queued.id = "20260904-000000-wait".to_owned();
6443 queue.put(&mut queued).unwrap();
6444
6445 let reclaimed = reclaim_orphaned_running(&queue, 2);
6446 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6447
6448 assert_eq!(
6449 queue.get(&orphaned.id).unwrap().status,
6450 TaskStatus::Held,
6451 "nothing was driving it and there was no run to recover"
6452 );
6453 assert_eq!(
6454 queue.get(&alive.id).unwrap().status,
6455 TaskStatus::Running,
6456 "a live claim must protect the task it belongs to"
6457 );
6458 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6459 }
6460
6461 fn read_run_under(home: &Path, id: &str) -> RunState {
6467 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6468 serde_json::from_str(&body).unwrap()
6469 }
6470
6471 #[test]
6472 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6473 let dir = tempfile::tempdir().unwrap();
6474 let home = dir.path().to_path_buf();
6475 let now = Timestamp::now();
6476 let overrun_seat = || crate::run::ActiveSeat {
6477 node: "implement".to_owned(),
6478 started_at: now - jiff::SignedDuration::new(21_000, 0),
6479 timeout_secs: 3_600,
6480 attempt: 0,
6481 task: None,
6482 command: None,
6483 index: None,
6484 total: None,
6485 };
6486
6487 let mut dead = run_state(RunStatus::Implementing);
6488 dead.id = "20260101-000000-dead".to_owned();
6489 dead.active.insert("impl-A".to_owned(), overrun_seat());
6490 dead.driver_pid = Some(4242);
6493 dead.save_under(&home).unwrap();
6494
6495 let mut alive = run_state(RunStatus::Implementing);
6498 alive.id = "20260101-000000-aliv".to_owned();
6499 alive.active.insert("impl-A".to_owned(), overrun_seat());
6500 alive.save_under(&home).unwrap();
6501 let mut status = Status::new();
6502 status.current = vec![Current {
6503 task: "20260101-000000-task".to_owned(),
6504 run: alive.id.clone(),
6505 }];
6506 write_status_to(&home.join("daemon.json"), &status).unwrap();
6507
6508 let questions = Questions::at(home.join("questions"));
6512 let mut q = ask::Question::new(
6513 dead.id.clone(),
6514 "implement".to_owned(),
6515 "impl-A".to_owned(),
6516 "Which storage backend?".to_owned(),
6517 String::new(),
6518 vec!["SQLite".to_owned(), "Redis".to_owned()],
6519 );
6520 questions.put(&mut q).unwrap();
6521
6522 let abandoned = reclaim_abandoned_runs_with(
6523 &home,
6524 now,
6525 |pid| if pid == 4242 { Some(false) } else { None },
6526 |_| panic!("a query answering Dead outright needs no identity corroboration"),
6527 );
6528 assert_eq!(abandoned, vec![dead.id.clone()]);
6529
6530 let reloaded = read_run_under(&home, &dead.id);
6531 assert_eq!(reloaded.status, RunStatus::Failed);
6532 assert!(reloaded.active.is_empty());
6533 assert!(
6534 !questions.get(&q.id).unwrap().status.open(),
6535 "the failed run's own open question must be settled in the same pass"
6536 );
6537
6538 let still_alive = read_run_under(&home, &alive.id);
6539 assert_eq!(
6540 still_alive.status,
6541 RunStatus::Implementing,
6542 "a live daemon's claim protects it"
6543 );
6544 assert!(!still_alive.active.is_empty());
6545 }
6546
6547 #[test]
6557 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
6558 let dir = tempfile::tempdir().unwrap();
6559 let home = dir.path().to_path_buf();
6560 let now = Timestamp::now();
6561
6562 let mut manual = run_state(RunStatus::Reviewing);
6563 manual.id = "20260101-000000-manl".to_owned();
6564 manual.active.insert(
6565 "review-1".to_owned(),
6566 crate::run::ActiveSeat {
6567 node: "review".to_owned(),
6568 started_at: now - jiff::SignedDuration::new(21_000, 0),
6569 timeout_secs: 3_600,
6570 attempt: 0,
6571 task: None,
6572 command: None,
6573 index: None,
6574 total: None,
6575 },
6576 );
6577 manual.driver_pid = Some(4242);
6581 manual.driver_started_at = Some("1790000000".to_owned());
6582 manual.save_under(&home).unwrap();
6583
6584 let abandoned = reclaim_abandoned_runs_with(
6585 &home,
6586 now,
6587 |pid| if pid == 4242 { Some(true) } else { None },
6588 |pid| {
6589 if pid == 4242 {
6590 Some("1790000000".to_owned())
6591 } else {
6592 None
6593 }
6594 },
6595 );
6596 assert!(
6597 abandoned.is_empty(),
6598 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
6599 );
6600
6601 let reloaded = read_run_under(&home, &manual.id);
6602 assert_eq!(reloaded.status, RunStatus::Reviewing);
6603 assert!(!reloaded.active.is_empty());
6604 }
6605
6606 #[test]
6607 fn an_already_claimed_task_is_skipped_rather_than_failed() {
6608 let dir = tempfile::tempdir().unwrap();
6609 let queue = Queue::at(dir.path().to_path_buf());
6610 let mut only = task();
6611 queue.put(&mut only).unwrap();
6612
6613 let _elsewhere = queue.claim(&only.id).unwrap();
6614 let candidates = runnable(&queue);
6615 assert_eq!(candidates.len(), 1, "the task is still runnable");
6616 assert!(
6617 queue.claim(&candidates[0].id).is_err(),
6618 "the loop cannot take a claim somebody else holds"
6619 );
6620
6621 let after = queue.get(&only.id).unwrap();
6622 assert_eq!(after.status, TaskStatus::Queued);
6623 assert_eq!(
6624 after.attempts, 0,
6625 "losing the race is not an attempt at the task"
6626 );
6627 assert_eq!(after.last_error, None);
6628 }
6629
6630 #[test]
6631 fn the_status_file_round_trips_and_its_heartbeat_advances() {
6632 let dir = tempfile::tempdir().unwrap();
6633 let path = dir.path().join("daemon.json");
6634
6635 let mut status = Status::new();
6636 status.idle = false;
6637 status.completed = 7;
6638 status.current = vec![Current {
6639 task: "20260902-000000-t111".to_owned(),
6640 run: "20260902-000001-r111".to_owned(),
6641 }];
6642 write_status_to(&path, &status).unwrap();
6643 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6644 assert_eq!(first.schema, SCHEMA);
6645 assert_eq!(first.pid, std::process::id());
6646 assert!(!first.idle);
6647 assert_eq!(first.completed, 7);
6648 assert_eq!(first.current, status.current);
6649 assert!(
6650 !path.with_extension("json.tmp").exists(),
6651 "the temp file is renamed, not left behind"
6652 );
6653
6654 std::thread::sleep(Duration::from_millis(5));
6655 status.updated_at = Timestamp::now();
6656 status.polls = 3;
6657 write_status_to(&path, &status).unwrap();
6658 let second: Status =
6659 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6660 assert!(
6661 second.updated_at > first.updated_at,
6662 "a reader can only detect staleness if the heartbeat moves"
6663 );
6664 assert_eq!(
6665 second.started_at, first.started_at,
6666 "the start time is not a heartbeat"
6667 );
6668 assert_eq!(second.polls, 3);
6669 }
6670
6671 #[test]
6672 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
6673 let dir = tempfile::tempdir().unwrap();
6674
6675 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
6676
6677 let mut status = Status::new();
6678 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
6679 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6680 let stale = read_status(dir.path()).unwrap();
6681 assert!(
6682 !stale.running(Timestamp::now()),
6683 "a minute without a heartbeat is a dead daemon, not a busy one"
6684 );
6685 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
6686
6687 status.updated_at = Timestamp::now();
6688 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6689 let fresh = read_status(dir.path()).unwrap();
6690 assert!(fresh.running(Timestamp::now()));
6691 }
6692
6693 #[test]
6694 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
6695 let dir = tempfile::tempdir().unwrap();
6696 let now = Timestamp::now();
6697 let mine = "20260903-080619-01c2";
6698
6699 assert!(
6700 !is_working_on(dir.path(), mine, now),
6701 "no status file means nobody is working on anything"
6702 );
6703
6704 let mut status = Status::new();
6705 status.current = vec![Current {
6706 task: "20260903-080340-0167".to_owned(),
6707 run: mine.to_owned(),
6708 }];
6709 status.updated_at = now;
6710 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6711 assert!(is_working_on(dir.path(), mine, now));
6712 assert!(
6713 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
6714 "a daemon busy with one run is not working on another"
6715 );
6716
6717 status.updated_at = now - jiff::SignedDuration::from_secs(600);
6720 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6721 assert!(
6722 !is_working_on(dir.path(), mine, now),
6723 "a stale heartbeat is a dead daemon, so its run is a leftover"
6724 );
6725 }
6726
6727 #[test]
6728 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
6729 let dir = tempfile::tempdir().unwrap();
6730 let now = Timestamp::now();
6731
6732 assert!(
6733 !is_working_on_short(dir.path(), "01c2", now),
6734 "no status file means nobody is working on anything"
6735 );
6736
6737 let mut status = Status::new();
6738 status.current = vec![Current {
6739 task: "20260903-080340-0167".to_owned(),
6740 run: "20260903-080619-01c2".to_owned(),
6741 }];
6742 status.updated_at = now;
6743 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6744 assert!(
6745 is_working_on_short(dir.path(), "01c2", now),
6746 "the run's short id is the last block of its full id"
6747 );
6748 assert!(
6749 !is_working_on_short(dir.path(), "3cbf", now),
6750 "a daemon busy with one worktree bay is not working on another"
6751 );
6752 }
6753
6754 #[test]
6755 fn a_newer_status_file_still_yields_a_reading() {
6756 let dir = tempfile::tempdir().unwrap();
6757 std::fs::write(
6760 dir.path().join("daemon.json"),
6761 serde_json::json!({
6762 "schema": 2,
6763 "updated_at": Timestamp::now().to_string(),
6764 "idle": true,
6765 "surprise": { "nested": [1, 2, 3] },
6766 })
6767 .to_string(),
6768 )
6769 .unwrap();
6770
6771 let reading = read_status(dir.path()).expect("a forward-compatible read");
6772 assert!(reading.running(Timestamp::now()));
6773 assert!(reading.idle);
6774 assert!(reading.current.is_empty());
6775 }
6776
6777 #[test]
6778 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
6779 let dir = tempfile::tempdir().unwrap();
6785 std::fs::write(
6786 dir.path().join("daemon.json"),
6787 serde_json::json!({
6788 "schema": 1,
6789 "pid": 4242,
6790 "updated_at": Timestamp::now().to_string(),
6791 "idle": false,
6792 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
6793 "completed": 3,
6794 "polls": 9,
6795 })
6796 .to_string(),
6797 )
6798 .unwrap();
6799
6800 let reading = read_status(dir.path()).expect("an older shape must still parse");
6801 assert!(reading.running(Timestamp::now()));
6802 assert_eq!(
6803 reading.current,
6804 vec![Current {
6805 task: "20260902-140501-aaaa".to_owned(),
6806 run: "20260902-140502-bbbb".to_owned(),
6807 }]
6808 );
6809 }
6810
6811 #[test]
6812 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
6813 let dir = tempfile::tempdir().unwrap();
6814 std::fs::write(
6815 dir.path().join("daemon.json"),
6816 serde_json::json!({
6817 "schema": 1,
6818 "updated_at": Timestamp::now().to_string(),
6819 "idle": true,
6820 "current": null,
6821 })
6822 .to_string(),
6823 )
6824 .unwrap();
6825 let with_null = read_status(dir.path()).expect("null must still parse");
6826 assert!(with_null.current.is_empty());
6827
6828 std::fs::write(
6829 dir.path().join("daemon.json"),
6830 serde_json::json!({
6831 "schema": 1,
6832 "updated_at": Timestamp::now().to_string(),
6833 "idle": true,
6834 })
6835 .to_string(),
6836 )
6837 .unwrap();
6838 let absent = read_status(dir.path()).expect("a missing field must still parse");
6839 assert!(absent.current.is_empty());
6840 }
6841
6842 #[test]
6843 fn a_task_without_a_repository_runs_in_the_daemons_default() {
6844 let fallback = Path::new("/default");
6845 let mut blank = task();
6846 blank.repo = PathBuf::new();
6847 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
6848 let mut dot = task();
6849 dot.repo = PathBuf::from(".");
6850 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
6851 assert_eq!(
6852 repo_for(&task(), fallback),
6853 PathBuf::from("/repo"),
6854 "a task that names a repository keeps it"
6855 );
6856 }
6857
6858 #[test]
6859 fn task_implementers_edit_inherits_daemon_config_and_merge() {
6860 let dir = tempfile::tempdir().unwrap();
6861 let path = dir.path().join("explicit.toml");
6862 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
6863 let opts = Opts {
6864 config: Some(path),
6865 merge: Some("none".into()),
6866 ..Default::default()
6867 };
6868 let mut t = task();
6869 t.set_implementers(
6870 2,
6871 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
6872 .unwrap(),
6873 )
6874 .unwrap();
6875 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
6876 assert_eq!(cfg.graph.implementers, 2);
6877 assert_eq!(cfg.graph.judges, 1);
6878 assert_eq!(cfg.merge.mode, MergeMode::None);
6879 t.set_implementers(1, &cfg).unwrap();
6880 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
6881 apply_task_implementers(&mut cfg, &t);
6882 assert_eq!(cfg.graph.implementers, 1);
6883 assert_eq!(cfg.graph.judges, 1);
6884 assert_eq!(cfg.merge.mode, MergeMode::None);
6885 }
6886
6887 #[test]
6888 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
6889 let dir = tempfile::tempdir().unwrap();
6890 let repo = dir.path().join("repo");
6891 std::fs::create_dir(&repo).unwrap();
6892 std::fs::write(
6893 repo.join("magi.toml"),
6894 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
6895 )
6896 .unwrap();
6897 let daemon_config = dir.path().join("daemon.toml");
6898 std::fs::write(
6899 &daemon_config,
6900 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
6901 )
6902 .unwrap();
6903 let opts = Opts {
6904 config: Some(daemon_config),
6905 merge: Some("pr".into()),
6906 ..Default::default()
6907 };
6908 let q = Queue::at(dir.path().join("queue"));
6909 let validation: Config =
6910 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
6911 .unwrap();
6912 for record in ["{}", r#"{"candidates":2}"#] {
6914 let overrides = serde_json::from_str(record).unwrap();
6915 let filing = crate::direct::Filing {
6916 instruction: "work".into(),
6917 title: "direct".into(),
6918 repo: repo.clone(),
6919 source: crate::queue::Source::Human,
6920 solo: false,
6921 overrides,
6922 review_of: None,
6923 };
6924 let filed =
6925 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
6926 let crate::direct::Filed::Standalone {
6927 mut task,
6928 claim: _claim,
6929 } = filed
6930 else {
6931 panic!("local filing")
6932 };
6933 let before = prepare_for(&repo, &opts, &task).unwrap();
6934 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
6935 assert_eq!(
6936 before.merge.mode,
6937 MergeMode::None,
6938 "daemon --merge must not leak"
6939 );
6940 for n in [2, 1, 2] {
6941 task.set_implementers(n, &validation).unwrap();
6942 q.put(&mut task).unwrap();
6943 task = q.get(&task.id).unwrap();
6944 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
6945 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
6946 apply_task_implementers(&mut cfg, &task);
6947 assert_eq!(cfg.graph.implementers, usize::from(n));
6948 assert_eq!(cfg.graph.judges, 2);
6949 assert_eq!(cfg.merge.mode, MergeMode::None);
6950 }
6951 }
6952 }
6953
6954 #[test]
6955 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
6956 let cfg: Config =
6957 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
6958 .unwrap();
6959 let mut t = task();
6960 t.review_of = Some("review-target".into());
6961 t.hold_manual(Some("retry".into()));
6962 let mut previous = RunState::new(
6963 PathBuf::from("/repo"),
6964 "main".into(),
6965 "abc1234".into(),
6966 "review".into(),
6967 cfg.clone(),
6968 );
6969 previous.config.graph.implementers = 2;
6970 for count in [1, 3] {
6971 t.set_implementers(count, &cfg).unwrap();
6972 t.release();
6973 assert_eq!(t.review_of.as_deref(), Some("review-target"));
6974 for proposed in [
6975 Starter::Resume(previous.id.clone()),
6976 Starter::Review("recovery-target".into()),
6977 ] {
6978 assert_eq!(
6979 starter_with_implementers(&t, Some(&previous), proposed),
6980 Starter::Review("review-target".into())
6981 );
6982 }
6983 let mut configured = cfg.clone();
6984 apply_task_implementers(&mut configured, &t);
6985 assert_eq!(configured.graph.implementers, usize::from(count));
6986 assert_eq!(previous.config.graph.implementers, 2);
6987 }
6988 }
6989
6990 #[test]
6991 fn task_implementers_dispatch_and_resume_agree() {
6992 let mut t = task();
6993 let cfg: crate::config::Config =
6994 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
6995 .unwrap();
6996 let mut run = RunState::new(
6997 PathBuf::from("/repo"),
6998 "main".into(),
6999 "abc1234".into(),
7000 "work".into(),
7001 cfg.clone(),
7002 );
7003 run.config.graph.implementers = 2;
7004 for n in [2, 1, 3, 2] {
7005 t.set_implementers(n, &cfg).unwrap();
7006 let mut dispatched = cfg.clone();
7007 apply_task_implementers(&mut dispatched, &t);
7008 assert_eq!(dispatched.graph.implementers, usize::from(n));
7009 assert_eq!(implementers_match(&t, &run), n == 2);
7010 for proposed in [
7011 Starter::Resume(run.id.clone()),
7012 Starter::Review("old-branch".into()),
7013 ] {
7014 let expected = if n == 2 {
7015 proposed.clone()
7016 } else {
7017 Starter::Start
7018 };
7019 assert_eq!(
7020 starter_with_implementers(&t, Some(&run), proposed),
7021 expected
7022 );
7023 }
7024 assert_eq!(
7025 run.config.graph.implementers, 2,
7026 "history must not be rewritten"
7027 );
7028 }
7029 t.solo = false;
7030 t.overrides = None;
7031 assert!(implementers_match(&t, &run));
7032 }
7033
7034 #[test]
7035 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
7036 let mut solo_cfg = Config::default();
7042 solo_cfg.graph.implementers = 3;
7043 let mut solo_task = task();
7044 solo_task.solo = true;
7045 apply_task_implementers(&mut solo_cfg, &solo_task);
7046 assert_eq!(solo_cfg.graph.implementers, 1);
7047
7048 let mut plain_cfg = Config::default();
7049 plain_cfg.graph.implementers = 3;
7050 let plain_task = task();
7051 assert!(!plain_task.solo);
7052 apply_task_implementers(&mut plain_cfg, &plain_task);
7053 assert_eq!(
7054 plain_cfg.graph.implementers, 3,
7055 "a task that did not ask to run alone keeps the config's candidates"
7056 );
7057 }
7058
7059 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
7060 QuotaLoss {
7061 seat: seat.into(),
7062 node: "judge".into(),
7063 at: at.parse().unwrap(),
7064 reset: reset.map(str::to_string),
7065 }
7066 }
7067
7068 #[test]
7069 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
7070 let old: Vec<QuotaLoss> = (1..=4)
7071 .map(|i| {
7072 loss(
7073 &format!("judge-{i}"),
7074 "2026-09-23T05:23:00Z",
7075 Some("2:40pm (Asia/Tokyo)"),
7076 )
7077 })
7078 .collect();
7079 let fresh = losses_this_attempt(&old, &old);
7080 assert!(fresh.is_empty());
7081 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
7082 }
7084
7085 #[test]
7086 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
7087 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
7088 let now = Timestamp::now();
7089 let mut after = old.clone();
7090 after.push(loss("judge-2", &now.to_string(), None));
7091 let fresh = losses_this_attempt(&old, &after);
7092 assert_eq!(fresh, vec![after[1].clone()]);
7093 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
7094 assert_eq!(
7095 until,
7096 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
7097 );
7098 }
7099
7100 #[test]
7101 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
7102 let before = vec![
7105 loss("judge-1", "2026-09-23T05:23:00Z", None),
7106 loss("judge-2", "2026-09-23T05:24:00Z", None),
7107 ];
7108 let after = vec![
7109 loss("judge-2", "2026-09-23T05:24:00Z", None),
7110 loss("judge-1", "2026-09-24T01:00:00Z", None),
7111 ];
7112 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
7113 }
7114
7115 #[test]
7116 fn merge_overrides_are_parsed_or_refused() {
7117 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
7118 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
7119 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
7120 assert!(merge_mode("squash").is_err());
7121 }
7122
7123 #[test]
7124 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
7125 let now = Timestamp::now();
7126 let fallback = Duration::from_secs(300);
7127 let cap = Duration::from_secs(1800);
7128
7129 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
7131
7132 let soon = now + jiff::SignedDuration::from_secs(600);
7134 assert_eq!(
7135 quota_wait(Some(soon), now, fallback, cap),
7136 Duration::from_secs(600)
7137 );
7138
7139 let past = now - jiff::SignedDuration::from_secs(60);
7142 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
7143
7144 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
7147 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
7148 }
7149
7150 #[test]
7151 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
7152 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7153
7154 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
7155 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
7156
7157 let already_past =
7161 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
7162 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
7163
7164 assert!(
7165 parse_reset_hint("session limit reached", now, now).is_none(),
7166 "free text with no recognised shape is not guessed at"
7167 );
7168 assert!(
7169 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
7170 "an unresolvable zone name is not guessed at either"
7171 );
7172 }
7173
7174 #[test]
7175 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
7176 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7177
7178 let at = parse_reset_hint(
7179 "You've hit your usage limit. Visit \
7180 https://chatgpt.com/codex/settings/usage to purchase more \
7181 credits or try again at Sep 19th, 2026 5:10 PM.",
7182 now,
7183 now,
7184 )
7185 .expect("the codex reset wording is a recognised shape");
7186 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
7187
7188 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
7193 .expect("an explicit year needs no rollover");
7194 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
7195
7196 assert!(
7197 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
7198 "a two-digit year is not the documented shape and is not guessed at"
7199 );
7200 assert!(
7201 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
7202 "a four-letter month name is not the documented three-letter abbreviation"
7203 );
7204 assert!(
7205 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
7206 "an explicit zone on the dated shape is a format nobody has \
7207 documented, and is refused rather than guessed at as UTC"
7208 );
7209 }
7210
7211 #[test]
7212 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
7213 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
7214 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
7215
7216 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
7217 assert_eq!(at.as_second() - recorded.as_second(), 3769);
7218
7219 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
7220 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
7221
7222 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
7223 assert!(
7224 parse_reset_hint(bad, now, recorded).is_none(),
7225 "{bad:?} must not be guessed at"
7226 );
7227 }
7228 }
7229
7230 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
7234 let config = dir.join("magi.toml");
7235 std::fs::write(
7236 &config,
7237 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
7238 )
7239 .unwrap();
7240 let opts = Opts {
7241 poll: Duration::from_secs(30),
7242 config: Some(config),
7243 repo: dir.join("repo"),
7247 ..Opts::default()
7248 };
7249 let home = dir.join("home");
7258 let worktrees = dir.join("wt");
7259 (
7260 opts,
7261 Queue::at(dir.join("queue")),
7262 home.join("daemon.json"),
7263 home,
7264 worktrees,
7265 )
7266 }
7267
7268 #[test]
7269 fn a_stop_is_idempotent_and_once_set_stays_set() {
7270 let stop = Stop::new();
7271 assert!(!stop.stopped());
7272
7273 stop.stop();
7274 assert!(stop.stopped());
7275 stop.stop();
7276 assert!(stop.stopped(), "a second stop is not a toggle");
7277
7278 let shared = stop.clone();
7279 assert!(
7280 shared.stopped(),
7281 "a clone is the same stop; that is how the loop and its caller share one"
7282 );
7283 }
7284
7285 #[test]
7286 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
7287 let stop = Stop::new();
7288 stop.enter();
7289 assert!(
7290 !stop.finishing(),
7291 "a busy loop nobody has asked to stop is just running"
7292 );
7293
7294 stop.stop();
7295 assert!(
7296 stop.finishing(),
7297 "a stop asked for mid-run has not landed until the run is settled"
7298 );
7299
7300 stop.exit();
7301 assert!(
7302 !stop.finishing(),
7303 "once the run is settled the stop has landed and there is nothing to finish"
7304 );
7305 }
7306
7307 #[test]
7308 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
7309 let stop = Stop::new();
7310 stop.enter();
7311 stop.enter();
7312 stop.stop();
7313 assert!(stop.finishing(), "two runs still in flight");
7314
7315 stop.exit();
7316 assert!(
7317 stop.finishing(),
7318 "one run finished, but a sibling is still working"
7319 );
7320
7321 stop.exit();
7322 assert!(
7323 !stop.finishing(),
7324 "the last run out is what actually lands the stop"
7325 );
7326 }
7327
7328 #[tokio::test]
7329 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
7330 let dir = tempfile::tempdir().unwrap();
7331 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7332 let stop = Stop::new();
7333 stop.stop();
7334
7335 let began = std::time::Instant::now();
7336 tokio::time::timeout(
7337 Duration::from_secs(2),
7338 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7339 )
7340 .await
7341 .expect("a stopped loop must return, not sit out its poll interval")
7342 .expect("the loop's own setup and teardown must not fail");
7343 assert!(
7344 began.elapsed() < opts.poll,
7345 "returned only after {:?}, which is a poll interval, not a stop",
7346 began.elapsed()
7347 );
7348 }
7349
7350 #[tokio::test]
7351 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
7352 let dir = tempfile::tempdir().unwrap();
7353 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7354 let stop = Stop::new();
7355
7356 let asker = {
7359 let stop = stop.clone();
7360 tokio::spawn(async move {
7361 tokio::time::sleep(Duration::from_millis(20)).await;
7362 stop.stop();
7363 })
7364 };
7365
7366 let began = std::time::Instant::now();
7367 tokio::time::timeout(
7368 Duration::from_secs(2),
7369 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7370 )
7371 .await
7372 .expect("a stop asked for while idle must wake the wait")
7373 .expect("the loop's own setup and teardown must not fail");
7374 asker.await.unwrap();
7375 assert!(
7376 began.elapsed() < opts.poll,
7377 "returned only after {:?}, so the stop waited on the sleep",
7378 began.elapsed()
7379 );
7380 }
7381
7382 #[tokio::test]
7383 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
7384 let dir = tempfile::tempdir().unwrap();
7385 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7386 let stop = Stop::new();
7387 stop.stop();
7388
7389 tokio::time::timeout(
7390 Duration::from_secs(2),
7391 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7392 )
7393 .await
7394 .expect("a stopped loop must return")
7395 .expect("the loop's own setup and teardown must not fail");
7396
7397 assert!(
7398 home.is_dir(),
7399 "the loop did publish a status file, so its removal is the teardown and not an absence"
7400 );
7401 assert!(
7402 !status_file.exists(),
7403 "a stopped loop clears its status file"
7404 );
7405 assert!(
7406 read_status(&home).is_none(),
7407 "a reader must see no daemon at all, not a heartbeat that merely stopped"
7408 );
7409 }
7410
7411 #[tokio::test]
7412 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
7413 let dir = tempfile::tempdir().unwrap();
7414 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7415 opts.once = true;
7416
7417 let mut settled = RunState::new(
7418 dir.path().join("repo"),
7419 "main".to_owned(),
7420 "abc1234".to_owned(),
7421 "fixture".to_owned(),
7422 Config::default(),
7423 );
7424 settled.status = RunStatus::Ready;
7425 let run_dir = home.join("runs").join(&settled.id);
7426 std::fs::create_dir_all(&run_dir).unwrap();
7427 std::fs::write(
7428 run_dir.join("run.json"),
7429 serde_json::to_string_pretty(&settled).unwrap(),
7430 )
7431 .unwrap();
7432 let questions = Questions::at(home.join("questions"));
7433 let mut question = ask::Question::new(
7434 settled.id.clone(),
7435 "review".to_owned(),
7436 "reviewer-1".to_owned(),
7437 "Continue?".to_owned(),
7438 String::new(),
7439 Vec::new(),
7440 );
7441 questions.put(&mut question).unwrap();
7442
7443 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
7444 .await
7445 .unwrap();
7446
7447 assert_eq!(
7448 questions.get(&question.id).unwrap().status,
7449 ask::QuestionStatus::Abandoned,
7450 "an empty --once drain still performs startup question cleanup"
7451 );
7452 }
7453
7454 #[test]
7455 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
7456 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7457
7458 assert!(
7459 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
7460 "never checked before: due at once"
7461 );
7462
7463 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
7464 assert!(
7465 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
7466 "well inside the interval: not due yet"
7467 );
7468
7469 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
7470 assert!(
7471 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
7472 "exactly at the edge: not yet due, same convention as `clean::due`"
7473 );
7474
7475 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7476 assert!(
7477 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
7478 "past the interval: due again"
7479 );
7480 }
7481
7482 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
7487 let config = dir.join("magi.toml");
7488 std::fs::write(
7494 &config,
7495 format!(
7496 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7497 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7498 cache_dir.display()
7499 ),
7500 )
7501 .unwrap();
7502 Opts {
7503 config: Some(config),
7504 repo: dir.join("repo"),
7505 ..Opts::default()
7506 }
7507 }
7508
7509 #[tokio::test]
7510 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
7511 let dir = tempfile::tempdir().unwrap();
7512 let home = dir.path().join("home");
7513 let cache_dir = dir.path().join("cache");
7514 std::fs::create_dir_all(&cache_dir).unwrap();
7515 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7516 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7517
7518 let running = Stop::new();
7521 let mut last_checked = None;
7522 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7523 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
7524 .await;
7525 assert_eq!(
7526 crate::disk::dir_size(&cache_dir),
7527 0,
7528 "over the cap on the first check ever: pruned at once, no idle queue required"
7529 );
7530 assert_eq!(last_checked, Some(t0));
7531
7532 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
7534 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
7535 maybe_prune_cache_between_runs(
7536 &opts.repo,
7537 &opts,
7538 &home,
7539 &running,
7540 &mut last_checked,
7541 too_soon,
7542 )
7543 .await;
7544 assert_eq!(
7545 crate::disk::dir_size(&cache_dir),
7546 10,
7547 "too soon since the last check: left alone rather than rescanned every call"
7548 );
7549 assert_eq!(
7550 last_checked,
7551 Some(t0),
7552 "an idle check does not reset the clock"
7553 );
7554
7555 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7557 maybe_prune_cache_between_runs(
7558 &opts.repo,
7559 &opts,
7560 &home,
7561 &running,
7562 &mut last_checked,
7563 due_again,
7564 )
7565 .await;
7566 assert_eq!(
7567 crate::disk::dir_size(&cache_dir),
7568 0,
7569 "due again: pruned back under the cap"
7570 );
7571 }
7572
7573 #[tokio::test]
7581 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
7582 let dir = tempfile::tempdir().unwrap();
7583 let home = dir.path().join("home");
7584 let cache_dir = dir.path().join("cache");
7585 std::fs::create_dir_all(&cache_dir).unwrap();
7586 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
7587 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
7588
7589 let stop = Stop::new();
7590 stop.stop();
7591 assert!(
7592 !stop.finishing(),
7593 "no run is in flight at a between-runs boundary, so nothing else \
7594 would tell the operator this stop had not taken effect yet"
7595 );
7596
7597 let mut last_checked = None;
7598 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7599 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
7600 .await;
7601 assert_eq!(
7602 crate::disk::dir_size(&cache_dir),
7603 10,
7604 "over its cap, and due for the first check ever, but a stop outranks \
7605 it: the cap is a standing policy the next start measures again"
7606 );
7607 assert_eq!(
7608 last_checked, None,
7609 "a check that never happened must not claim the interval"
7610 );
7611 }
7612
7613 #[tokio::test]
7627 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
7628 let dir = tempfile::tempdir().unwrap();
7629 let cache_dir = dir.path().join("cache");
7630 std::fs::create_dir_all(&cache_dir).unwrap();
7631 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
7632
7633 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
7634 opts.poll = Duration::from_millis(20);
7635 opts.max_attempts = 1_000;
7636
7637 let queue = Queue::at(dir.path().join("queue"));
7638 let mut t = Task::new(
7639 "x".to_owned(),
7640 "x".to_owned(),
7641 opts.repo.clone(),
7642 Source::Human,
7643 );
7644 queue.put(&mut t).unwrap();
7645
7646 let home = dir.path().join("home");
7647 let worktrees = dir.path().join("wt");
7648 let status_file = home.join("daemon.json");
7649 let stop = Stop::new();
7650 let stopper = {
7651 let stop = stop.clone();
7652 let queue = Queue::at(dir.path().join("queue"));
7653 let id = t.id.clone();
7654 tokio::spawn(async move {
7655 tokio::time::sleep(Duration::from_millis(400)).await;
7659 for _ in 0..200 {
7660 if queue.get(&id).is_ok_and(|t| t.attempts >= 2) {
7661 break;
7662 }
7663 tokio::time::sleep(Duration::from_millis(50)).await;
7664 }
7665 stop.stop();
7666 })
7667 };
7668
7669 tokio::time::timeout(
7670 Duration::from_secs(20),
7671 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7672 )
7673 .await
7674 .expect("the loop must not hang on a queue that keeps producing failing work")
7675 .expect("the loop's own setup and teardown must not fail");
7676 stopper.await.unwrap();
7677
7678 let after = queue.get(&t.id).unwrap();
7679 assert!(
7680 after.attempts >= 2,
7681 "the harness must actually have retried more than once, or this is not \
7682 exercising a busy queue at all (got {} attempt(s))",
7683 after.attempts
7684 );
7685 assert!(
7686 after.status.runnable(),
7687 "still under its attempt budget: the queue never reached a natural idle \
7688 on its own, only the external stop ended the test"
7689 );
7690
7691 assert_eq!(
7692 crate::disk::dir_size(&cache_dir),
7693 0,
7694 "an oversized cache must not be left to grow unboundedly just because the \
7695 queue kept the loop busy the whole time"
7696 );
7697 }
7698
7699 #[test]
7700 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
7701 let dir = tempfile::tempdir().unwrap();
7702 let queue = Queue::at(dir.path().join("queue"));
7703 let questions = Questions::at(dir.path().join("questions"));
7704 let mut task = task();
7705 queue.put(&mut task).unwrap();
7706
7707 let mut task_question = ask::Question::new(
7708 task.id.clone(),
7709 crate::conduct::NODE.to_owned(),
7710 "conduct".to_owned(),
7711 "Which backend?".to_owned(),
7712 String::new(),
7713 Vec::new(),
7714 );
7715 questions.put(&mut task_question).unwrap();
7716 task.block(vec![task_question.id.clone()], None);
7717 queue.put(&mut task).unwrap();
7718
7719 let mut run_question = ask::Question::new(
7720 "20260101-000000-run1".to_owned(),
7721 "review".to_owned(),
7722 "reviewer-1".to_owned(),
7723 "Run question".to_owned(),
7724 String::new(),
7725 Vec::new(),
7726 );
7727 questions.put(&mut run_question).unwrap();
7728
7729 let mut coincidental = ask::Question::new(
7734 task.id.clone(),
7735 "review".to_owned(),
7736 "reviewer-1".to_owned(),
7737 "Unrelated review question".to_owned(),
7738 String::new(),
7739 Vec::new(),
7740 );
7741 questions.put(&mut coincidental).unwrap();
7742
7743 reconcile_task_questions(&queue, &questions);
7744 assert!(questions.get(&task_question.id).unwrap().status.open());
7745 assert!(questions.get(&run_question.id).unwrap().status.open());
7746 assert!(questions.get(&coincidental.id).unwrap().status.open());
7747
7748 task.release();
7749 queue.put(&mut task).unwrap();
7750 reconcile_task_questions(&queue, &questions);
7751 assert_eq!(
7752 questions.get(&task_question.id).unwrap().status,
7753 ask::QuestionStatus::Abandoned
7754 );
7755 assert!(
7756 questions.get(&run_question.id).unwrap().status.open(),
7757 "run questions remain the run janitor's responsibility"
7758 );
7759 assert!(
7760 questions.get(&coincidental.id).unwrap().status.open(),
7761 "a non-conductor question must not be abandoned just because its \
7762 run id coincides with a task id"
7763 );
7764 }
7765
7766 #[test]
7767 fn a_freshly_started_running_task_is_never_stalled() {
7768 let dir = tempfile::tempdir().unwrap();
7769 let mut t = task();
7770 t.start("run-1".to_owned());
7771 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
7774 }
7775
7776 #[test]
7777 fn a_long_running_task_with_no_live_daemon_is_stalled() {
7778 let dir = tempfile::tempdir().unwrap();
7779 let mut t = task();
7780 t.start("run-1".to_owned());
7781 t.updated_at = Timestamp::now()
7782 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7783 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
7784 assert_eq!(
7785 stalled_tasks(
7786 &Queue::at(dir.path().join("q")),
7787 dir.path(),
7788 Timestamp::now()
7789 )
7790 .len(),
7791 0,
7792 "the task was never written to this queue"
7793 );
7794 }
7795
7796 #[test]
7797 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
7798 let dir = tempfile::tempdir().unwrap();
7799 let mut t = task();
7800 t.id = "20260903-080340-0167".to_owned();
7801 t.start("20260903-080619-01c2".to_owned());
7802 t.updated_at = Timestamp::now()
7803 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7804
7805 let mut status = Status::new();
7806 status.current = vec![Current {
7807 task: t.id.clone(),
7808 run: "20260903-080619-01c2".to_owned(),
7809 }];
7810 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7811
7812 assert!(
7813 !is_stalled(&t, dir.path(), Timestamp::now()),
7814 "a live daemon's own heartbeat rules out stalled, however long the task has run"
7815 );
7816 }
7817
7818 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
7822 let path = queue.path_of(id);
7823 let body = std::fs::read_to_string(&path).unwrap();
7824 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
7825 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
7826 v["updated_at"] = serde_json::Value::String(old.to_string());
7827 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
7828 }
7829
7830 #[test]
7831 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
7832 let dir = tempfile::tempdir().unwrap();
7845 let queue = Queue::at(dir.path().join("queue"));
7846 let home = dir.path().join("home");
7847
7848 let mut t = task();
7849 t.id = "20260101-000001-lock".to_owned();
7850 t.start("run-1".to_owned());
7851 queue.put(&mut t).unwrap();
7852 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7853 std::fs::write(
7854 dir.path().join("queue").join(format!("{}.lock", t.id)),
7855 "not a pid",
7856 )
7857 .unwrap();
7858
7859 let now = Timestamp::now();
7860 assert!(
7861 reclaim_orphaned_running(&queue, 2).is_empty(),
7862 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
7863 and reclaim must leave the task alone"
7864 );
7865 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7866
7867 let stalled = stalled_tasks(&queue, &home, now);
7868 assert_eq!(
7869 stalled.len(),
7870 1,
7871 "reclaim's inability to claim it yet must not hide it from the conductor"
7872 );
7873 assert_eq!(stalled[0].id, t.id);
7874 }
7875
7876 #[test]
7877 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
7878 let dir = tempfile::tempdir().unwrap();
7879 crate::run::set_home(dir.path().join("run-home"));
7880 let queue = Queue::at(dir.path().join("queue"));
7881 let home = dir.path().join("home");
7882 let questions = Questions::at(dir.path().join("questions"));
7883
7884 let mut t = task();
7885 t.id = "20260101-000003-dead".to_owned();
7886 t.start("missing-run".to_owned());
7887 queue.put(&mut t).unwrap();
7888 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7889
7890 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7893 assert_eq!(
7894 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
7895 [&t.id]
7896 );
7897 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
7898 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7899
7900 crate::conduct::apply(
7903 &queue,
7904 &questions,
7905 &crate::conduct::Verdict {
7906 decisions: vec![crate::conduct::Decision {
7907 id: t.id.clone(),
7908 recovery: Some(crate::conduct::Recovery::Requeue),
7909 ..crate::conduct::Decision::default()
7910 }],
7911 },
7912 )
7913 .unwrap();
7914 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7915 }
7916
7917 #[test]
7918 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
7919 let dir = tempfile::tempdir().unwrap();
7920 let queue = Queue::at(dir.path().join("queue"));
7921 let home = dir.path().join("home");
7922
7923 let mut fresh = task();
7924 fresh.id = "20260101-000001-aaaa".to_owned();
7925 fresh.start("run-1".to_owned());
7926 queue.put(&mut fresh).unwrap();
7927
7928 let mut old = task();
7929 old.id = "20260101-000002-bbbb".to_owned();
7930 old.start("run-2".to_owned());
7931 queue.put(&mut old).unwrap();
7932 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
7933
7934 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7935 assert_eq!(stalled.len(), 1);
7936 assert_eq!(stalled[0].id, old.id);
7937 }
7938
7939 #[test]
7940 fn queued_and_finished_task_views_partition_by_status() {
7941 let dir = tempfile::tempdir().unwrap();
7942 let queue = Queue::at(dir.path().join("queue"));
7943
7944 let mut queued = task();
7945 queued.id = "20260101-000001-aaaa".to_owned();
7946 queue.put(&mut queued).unwrap();
7947
7948 let mut failed = task();
7949 failed.id = "20260101-000002-bbbb".to_owned();
7950 failed.start("run-1".to_owned());
7951 failed.fail("gate red", 5);
7952 queue.put(&mut failed).unwrap();
7953
7954 let mut held = task();
7955 held.id = "20260101-000003-cccc".to_owned();
7956 held.hold_machine(None);
7957 queue.put(&mut held).unwrap();
7958
7959 let mut running = task();
7960 running.id = "20260101-000004-dddd".to_owned();
7961 running.start("run-2".to_owned());
7962 queue.put(&mut running).unwrap();
7963
7964 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
7965 assert_eq!(queued_ids, [queued.id.clone()]);
7966
7967 let mut finished_ids: Vec<String> =
7968 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
7969 finished_ids.sort_unstable();
7970 let mut want = vec![failed.id.clone(), held.id.clone()];
7971 want.sort_unstable();
7972 assert_eq!(finished_ids, want);
7973 }
7974
7975 #[test]
7976 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
7977 let dir = tempfile::tempdir().unwrap();
7978 let queue = Queue::at(dir.path().join("queue"));
7979 let questions = ask::Questions::at(dir.path().join("questions"));
7980
7981 let mut dep = task();
7982 dep.id = "20260101-000001-dep0".to_owned();
7983 dep.succeed();
7984 queue.put(&mut dep).unwrap();
7985
7986 let mut still_going = task();
7987 still_going.id = "20260101-000002-dep1".to_owned();
7988 queue.put(&mut still_going).unwrap();
7989
7990 let mut blocked = task();
7991 blocked.id = "20260101-000003-main".to_owned();
7992 blocked.block(
7993 vec![dep.id.clone(), still_going.id.clone()],
7994 Some("waits on both".to_owned()),
7995 );
7996 queue.put(&mut blocked).unwrap();
7997
7998 resolve_blockers(&queue, &questions);
7999
8000 let after = queue.get(&blocked.id).unwrap();
8001 assert_eq!(
8002 after.status,
8003 TaskStatus::Blocked,
8004 "one dependency is still outstanding"
8005 );
8006 assert_eq!(after.blocked_by, [still_going.id.clone()]);
8007 }
8008
8009 #[test]
8010 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
8011 let dir = tempfile::tempdir().unwrap();
8012 let queue = Queue::at(dir.path().join("queue"));
8013 let questions = ask::Questions::at(dir.path().join("questions"));
8014
8015 let mut q = crate::ask::Question::new(
8016 "20260101-000001-main".to_owned(),
8017 crate::conduct::NODE.to_owned(),
8018 "conduct".to_owned(),
8019 "Which backend?".to_owned(),
8020 String::new(),
8021 Vec::new(),
8022 );
8023 questions.put(&mut q).unwrap();
8024 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
8025 .unwrap();
8026 questions.put(&mut q).unwrap();
8027
8028 let mut blocked = task();
8029 blocked.id = "20260101-000001-main".to_owned();
8030 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
8031 queue.put(&mut blocked).unwrap();
8032
8033 resolve_blockers(&queue, &questions);
8034
8035 let after = queue.get(&blocked.id).unwrap();
8036 assert_eq!(
8037 after.status,
8038 TaskStatus::Queued,
8039 "the only blocker resolved"
8040 );
8041 assert_eq!(after.answers.len(), 1);
8042 assert_eq!(after.answers[0].question, "Which backend?");
8043 assert_eq!(after.answers[0].answer, "SQLite");
8044
8045 let instruction = instruction_for(&after);
8047 assert!(instruction.contains("Which backend?"));
8048 assert!(instruction.contains("SQLite"));
8049 }
8050
8051 #[test]
8052 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
8053 let dir = tempfile::tempdir().unwrap();
8054 let queue = Queue::at(dir.path().join("queue"));
8055 let questions = ask::Questions::at(dir.path().join("questions"));
8056
8057 let mut q = crate::ask::Question::new(
8058 "20260101-000001-main".to_owned(),
8059 crate::conduct::NODE.to_owned(),
8060 "conduct".to_owned(),
8061 "Is the setup done?".to_owned(),
8062 String::new(),
8063 Vec::new(),
8064 );
8065 q.abandon("no answer within 60s of asking");
8066 questions.put(&mut q).unwrap();
8067
8068 let mut blocked = task();
8069 blocked.id = "20260101-000001-main".to_owned();
8070 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
8071 queue.put(&mut blocked).unwrap();
8072
8073 resolve_blockers(&queue, &questions);
8074
8075 let after = queue.get(&blocked.id).unwrap();
8076 assert_eq!(
8077 after.status,
8078 TaskStatus::Held,
8079 "never left blocked on nothing"
8080 );
8081 assert!(!after.operator_held(), "a machine hold, for triage");
8082 assert!(
8083 after
8084 .hold_reason
8085 .as_deref()
8086 .unwrap_or_default()
8087 .contains("went unanswered")
8088 );
8089 }
8090
8091 #[test]
8092 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
8093 let dir = tempfile::tempdir().unwrap();
8099 let queue = Queue::at(dir.path().join("queue"));
8100 let questions = ask::Questions::at(dir.path().join("questions"));
8101
8102 let mut q = crate::ask::Question::new(
8103 "20260101-000001-main".to_owned(),
8104 crate::conduct::NODE.to_owned(),
8105 "conduct".to_owned(),
8106 "How should this be handled?".to_owned(),
8107 String::new(),
8108 Vec::new(),
8109 );
8110 questions.put(&mut q).unwrap();
8111 q.answer(crate::ask::Answer::Text(
8112 "leave it held, a human will look at it later".to_owned(),
8113 ))
8114 .unwrap();
8115 questions.put(&mut q).unwrap();
8116
8117 let mut held = task();
8118 held.id = "20260101-000001-main".to_owned();
8119 held.hold_machine(Some("out of attempts".to_owned()));
8120 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
8121 queue.put(&mut held).unwrap();
8122
8123 resolve_blockers(&queue, &questions);
8124
8125 let after = queue.get(&held.id).unwrap();
8126 assert_eq!(after.status, TaskStatus::Held);
8127 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
8128 assert_eq!(
8129 after.answers[0].answer,
8130 "leave it held, a human will look at it later"
8131 );
8132 }
8133
8134 #[test]
8135 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
8136 let dir = tempfile::tempdir().unwrap();
8137 let queue = Queue::at(dir.path().join("queue"));
8138 let questions = ask::Questions::at(dir.path().join("questions"));
8139 let mut dep = task();
8140 dep.id = "20260101-000001-gone".to_owned();
8141 queue.put(&mut dep).unwrap();
8142 let mut blocked = task();
8143 blocked.id = "20260101-000003-main".to_owned();
8144 blocked.block(vec![dep.id.clone()], None);
8145 queue.put(&mut blocked).unwrap();
8146
8147 let claim = queue.claim(&blocked.id).unwrap();
8149 queue.remove(&dep.id, false, &questions).unwrap();
8150 drop(claim);
8151 resolve_blockers(&queue, &questions);
8152
8153 let after = queue.get(&blocked.id).unwrap();
8154 assert_eq!(after.status, TaskStatus::Queued);
8155 assert!(after.blocked_by.is_empty());
8156 }
8157
8158 #[test]
8159 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
8160 let dir = tempfile::tempdir().unwrap();
8166 let queue = Queue::at(dir.path().join("queue"));
8167 let questions = ask::Questions::at(dir.path().join("questions"));
8168
8169 let mut still_going = task();
8170 still_going.id = "20260101-000002-dep1".to_owned();
8171 queue.put(&mut still_going).unwrap();
8172
8173 let mut blocked = task();
8174 blocked.id = "20260101-000003-main".to_owned();
8175 blocked.block(
8176 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
8177 Some("waits on both".to_owned()),
8178 );
8179 queue.put(&mut blocked).unwrap();
8180
8181 resolve_blockers(&queue, &questions);
8182
8183 let after = queue.get(&blocked.id).unwrap();
8184 assert_eq!(
8185 after.status,
8186 TaskStatus::Held,
8187 "a missing dependency must not leave the task blocked forever"
8188 );
8189 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
8190 assert!(after.blocked_by.is_empty());
8191 let reason = after.hold_reason.as_deref().unwrap_or_default();
8192 assert!(
8193 reason.contains("20260101-000001-gone"),
8194 "the missing id must be named so an operator can tell what happened: {reason}"
8195 );
8196 assert!(
8197 reason.contains(&still_going.id),
8198 "the still-valid dependency must not silently vanish from the record: {reason}"
8199 );
8200 }
8201
8202 #[test]
8203 fn instruction_for_is_unchanged_without_any_answers() {
8204 let t = task();
8205 assert_eq!(instruction_for(&t), t.instruction);
8206 }
8207
8208 #[test]
8209 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
8210 let dir = tempfile::tempdir().unwrap();
8211 let q = Queue::at(dir.path().join("queue"));
8212 let src = dir.path().join("shot.png");
8213 std::fs::write(&src, "x").unwrap();
8214 let mut t = task();
8215 q.attach(&mut t, &[src]).unwrap();
8216 let paths = task_attachments(&q, &t).unwrap();
8217 assert_eq!(paths.len(), 1);
8218 assert!(paths[0].is_absolute() && paths[0].is_file());
8219 std::fs::remove_file(&paths[0]).unwrap();
8220 let err = task_attachments(&q, &t).unwrap_err().to_string();
8221 assert!(err.contains("shot.png"), "{err}");
8222 }
8223
8224 #[test]
8225 fn resumed_instruction_is_unchanged_without_any_answers() {
8226 let t = task();
8227 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
8228 }
8229
8230 #[test]
8231 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
8232 let mut t = task();
8233 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8234 let old = t.instruction.clone();
8238
8239 let refreshed = resumed_instruction(&old, &t);
8240 assert!(refreshed.starts_with(&old), "the original text is kept");
8241 assert!(refreshed.contains("Which backend?"));
8242 assert!(refreshed.contains("SQLite"));
8243 }
8244
8245 #[test]
8246 fn resumed_instruction_keeps_an_original_answers_heading() {
8247 let mut t = task();
8248 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
8249 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8250
8251 let refreshed = resumed_instruction(&t.instruction, &t);
8252
8253 assert!(
8254 refreshed.starts_with(&t.instruction),
8255 "an answers heading in the original instruction is not the appended block"
8256 );
8257 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
8258 assert!(refreshed.contains("Which backend?"));
8259 assert!(refreshed.contains("SQLite"));
8260
8261 let repeated = resumed_instruction(&refreshed, &t);
8262 assert_eq!(
8263 repeated, refreshed,
8264 "only the final appended block is refreshed"
8265 );
8266 }
8267
8268 #[test]
8269 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
8270 let mut t = task();
8271 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8272
8273 let once = resumed_instruction(&t.instruction, &t);
8277 let twice = resumed_instruction(&once, &t);
8278 assert_eq!(once, twice);
8279 assert_eq!(once.matches("Which backend?").count(), 1);
8280
8281 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
8283 let refreshed = resumed_instruction(&once, &t);
8284 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
8285 assert!(refreshed.contains("Which backend?"));
8286 assert!(refreshed.contains("Which cache?"));
8287 }
8288
8289 #[test]
8290 fn prepare_instruction_covers_all_three_starters() {
8291 let mut t = task();
8292 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8293
8294 assert_eq!(
8297 prepare_instruction(&Starter::Start, None, &t),
8298 Some(instruction_for(&t))
8299 );
8300
8301 let old = t.instruction.clone();
8304 assert_eq!(
8305 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
8306 Some(resumed_instruction(&old, &t))
8307 );
8308
8309 assert_eq!(
8313 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
8314 None
8315 );
8316 }
8317
8318 #[test]
8319 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
8320 assert_eq!(
8321 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
8322 Starter::Review("magi/eba2/A".to_owned())
8323 );
8324 }
8325
8326 #[test]
8327 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
8328 assert_eq!(
8329 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
8330 Starter::Start,
8331 "a vanished review branch must not fall back to resuming the old run either"
8332 );
8333 }
8334
8335 #[test]
8336 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
8337 let mut t = task();
8338 t.start("old-run".to_owned());
8339 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
8340 t.release();
8341 let branch = t.review_branch.take();
8342 assert_eq!(
8343 choose_starter(branch.as_deref(), true, Some("old-run")),
8344 Starter::Review("magi/eba2/A".to_owned()),
8345 "a review wins over resuming the old run"
8346 );
8347 }
8348
8349 #[test]
8350 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
8351 assert_eq!(
8352 choose_starter(None, false, Some("some-run")),
8353 Starter::Resume("some-run".to_owned())
8354 );
8355 assert_eq!(choose_starter(None, false, None), Starter::Start);
8356 }
8357
8358 #[test]
8359 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
8360 let mut released = task();
8361 released.start("stalled-run".to_owned());
8362 released.requeue();
8363 let unfinished = (!released.fresh_start)
8364 .then(|| Some("stalled-run".to_owned()))
8365 .flatten();
8366 assert_eq!(
8367 choose_starter(None, false, unfinished.as_deref()),
8368 Starter::Start,
8369 "release keeps run history but must not resume it"
8370 );
8371 assert_eq!(released.runs, ["stalled-run"]);
8372 }
8373
8374 #[test]
8375 fn an_ordinary_release_keeps_a_resumable_run_available() {
8376 let mut released = task();
8377 released.start("stalled-run".to_owned());
8378 released.release();
8379 let unfinished = (!released.fresh_start)
8380 .then(|| Some("stalled-run".to_owned()))
8381 .flatten();
8382 assert_eq!(
8383 choose_starter(None, false, unfinished.as_deref()),
8384 Starter::Resume("stalled-run".to_owned()),
8385 "manual release must preserve the normal resume path"
8386 );
8387 }
8388
8389 #[test]
8390 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
8391 let mut state = run_state(RunStatus::Blocked);
8392 state.config.graph.review_rounds = 3;
8393 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
8394 assert!(exhausted_review_budget(&state));
8395
8396 state.reviews.pop();
8398 assert!(!exhausted_review_budget(&state));
8399
8400 let mut stalled = run_state(RunStatus::Stalled);
8403 stalled.config.graph.review_rounds = 1;
8404 stalled.reviews = vec![review_round(1)];
8405 assert!(!exhausted_review_budget(&stalled));
8406 }
8407
8408 fn review_round(round: usize) -> crate::run::ReviewRound {
8409 crate::run::ReviewRound {
8410 round,
8411 head: "deadbeef".to_owned(),
8412 verified_head: None,
8413 verified_at: None,
8414 reviews: Vec::new(),
8415 e2e: Vec::new(),
8416 verify_retried: false,
8417 e2e_deferred: false,
8418 e2e_defer_reason: None,
8419 fix: None,
8420 blocking: 0,
8421 answered: 1,
8422 expected: 1,
8423 clean: false,
8424 progressed: true,
8425 vote_split: false,
8426 reconsideration: Vec::new(),
8427 verdict: None,
8428 }
8429 }
8430
8431 #[test]
8432 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
8433 let mut run = RunState::new(
8434 PathBuf::from("/repo"),
8435 "main".to_owned(),
8436 "abc1234def".to_owned(),
8437 "add retries".to_owned(),
8438 Config::default(),
8439 );
8440 run.status = RunStatus::Judging;
8441 run.parked = true;
8442 let mut task = Task::new(
8443 "add retries".to_owned(),
8444 "add retries".to_owned(),
8445 PathBuf::from("/repo"),
8446 crate::queue::Source::Human,
8447 );
8448 task.status = TaskStatus::Failed;
8449 task.runs = vec![run.id.clone()];
8450 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
8451 assert!(with(&task, &run), "parked after judging is the case");
8452 let mut parked_task = task.clone();
8453 parked_task.status = TaskStatus::Parked;
8454 assert!(with(&parked_task, &run), "the Parked status is the case");
8455
8456 let mut not_parked = run.clone();
8457 not_parked.parked = false;
8458 not_parked.status = RunStatus::Stalled;
8459 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
8460
8461 let mut fresh = task.clone();
8462 fresh.fresh_start = true;
8463 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
8464
8465 let mut review = task.clone();
8466 review.review_branch = Some("magi/x/A".to_owned());
8467 assert!(!with(&review, &run), "review is ranked before resume");
8468
8469 let mut held = task.clone();
8470 held.status = TaskStatus::Held;
8471 assert!(!with(&held, &run), "a hold stays visible to the conductor");
8472
8473 let mut released = run.clone();
8474 released.released_to = Some("20260901-000000-new1".to_owned());
8475 assert!(!with(&task, &released), "nothing left to resume into");
8476
8477 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
8478 "unreadable"
8479 )));
8480 }
8481
8482 #[test]
8483 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
8484 let mut released = RunState::new(
8485 PathBuf::from("/repo"),
8486 "main".to_owned(),
8487 "abc1234def".to_owned(),
8488 "add retries".to_owned(),
8489 Config::default(),
8490 );
8491 released.status = RunStatus::Blocked;
8492 assert_eq!(
8493 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8494 Some(released.id.clone())
8495 );
8496 released.released_to = Some("20260901-000000-new1".to_owned());
8497 assert_eq!(
8498 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8499 None,
8500 "there is nothing left to resume it into"
8501 );
8502 }
8503
8504 #[test]
8505 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
8506 let mut exhausted = RunState::new(
8515 PathBuf::from("/repo"),
8516 "main".to_owned(),
8517 "abc1234def".to_owned(),
8518 "add retries".to_owned(),
8519 Config::default(),
8520 );
8521 exhausted.status = RunStatus::Blocked;
8522 exhausted.config.graph.review_rounds = 1;
8523 exhausted.reviews = vec![review_round(1)];
8524
8525 assert_eq!(
8526 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
8527 None,
8528 "an exhausted `Blocked` run must not be offered as resumable"
8529 );
8530
8531 let mut has_budget_left = RunState::new(
8534 PathBuf::from("/repo"),
8535 "main".to_owned(),
8536 "abc1234def".to_owned(),
8537 "add retries".to_owned(),
8538 Config::default(),
8539 );
8540 has_budget_left.status = RunStatus::Blocked;
8541 has_budget_left.config.graph.review_rounds = 3;
8542 has_budget_left.reviews = vec![review_round(1)];
8543
8544 assert_eq!(
8545 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
8546 Ok(has_budget_left.clone())
8547 }),
8548 Some(has_budget_left.id.clone())
8549 );
8550 }
8551
8552 #[test]
8553 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
8554 let mut run = RunState::new(
8555 PathBuf::from("/repo"),
8556 "main".to_owned(),
8557 "abc1234def".to_owned(),
8558 "add retries".to_owned(),
8559 Config::default(),
8560 );
8561 run.status = RunStatus::Blocked;
8562 run.config.graph.review_rounds = 1;
8563 run.reviews = vec![review_round(1)];
8564 run.pr_publication_pending = true;
8565 assert_eq!(
8566 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
8567 Some(run.id.clone()),
8568 "a spent review budget must not turn a failed publication into a re-competition"
8569 );
8570 }
8571
8572 #[test]
8573 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
8574 let mut older_stalled = RunState::new(
8582 PathBuf::from("/repo"),
8583 "main".to_owned(),
8584 "abc1234def".to_owned(),
8585 "add retries".to_owned(),
8586 Config::default(),
8587 );
8588 older_stalled.status = RunStatus::Stalled;
8589
8590 let mut newest_exhausted = RunState::new(
8591 PathBuf::from("/repo"),
8592 "main".to_owned(),
8593 "abc1234def".to_owned(),
8594 "add retries".to_owned(),
8595 Config::default(),
8596 );
8597 newest_exhausted.status = RunStatus::Blocked;
8598 newest_exhausted.config.graph.review_rounds = 1;
8599 newest_exhausted.reviews = vec![review_round(1)];
8600
8601 assert_eq!(
8602 unfinished_run_with(
8603 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
8604 "t",
8605 |_| Ok(newest_exhausted.clone())
8606 ),
8607 None,
8608 "the newest run is exhausted, so nothing here is worth resuming - \
8609 least of all the older, already-superseded run"
8610 );
8611 }
8612
8613 #[test]
8614 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
8615 assert_eq!(
8616 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
8617 Err(anyhow::anyhow!("fixture is absent"))
8618 }),
8619 None
8620 );
8621 }
8622
8623 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
8624 let mut q = ask::Question::new(
8625 run.to_owned(),
8626 "implement".to_owned(),
8627 "impl-A".to_owned(),
8628 "continue?".to_owned(),
8629 String::new(),
8630 vec!["resume で続行する".to_owned(), "other".to_owned()],
8631 );
8632 q.actions.insert("resume で続行する".to_owned(), action);
8633 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
8634 .unwrap();
8635 q
8636 }
8637
8638 fn held_task_with(run: &str) -> Task {
8639 let mut t = task();
8640 t.runs = vec![run.to_owned()];
8641 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
8642 t
8643 }
8644
8645 fn resume_action(run: &str) -> ask::ChoiceAction {
8646 ask::ChoiceAction::Resume { run: run.into() }
8647 }
8648
8649 #[test]
8650 fn decide_action_resumes_only_the_latest_resumable_run() {
8651 let t = held_task_with("r1");
8652 let q = action_question("r1", resume_action("r1"));
8653 let load = |s: RunState| move |_: &str| Ok(s);
8654 assert_eq!(
8655 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
8656 ActionDecision::Resume("r1".into())
8657 );
8658 let q_other = action_question("r1", resume_action("r0"));
8660 assert!(matches!(
8661 decide_action(
8662 &t,
8663 &q_other,
8664 &PHRASES_EN,
8665 load(run_state(RunStatus::Blocked))
8666 ),
8667 ActionDecision::Refuse(_)
8668 ));
8669 assert!(matches!(
8671 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
8672 ActionDecision::Refuse(_)
8673 ));
8674 let mut released = run_state(RunStatus::Blocked);
8676 released.released_to = Some("elsewhere".into());
8677 assert!(matches!(
8678 decide_action(&t, &q, &PHRASES_EN, load(released)),
8679 ActionDecision::Refuse(_)
8680 ));
8681 assert!(matches!(
8683 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
8684 ActionDecision::Refuse(_)
8685 ));
8686 }
8687
8688 #[test]
8689 fn decide_action_ignores_a_question_about_an_earlier_run() {
8690 let mut t = held_task_with("r1");
8691 t.runs.push("r2".to_owned());
8692 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8693 assert_eq!(
8694 decide_action(
8695 &t,
8696 &action_question("r1", ask::ChoiceAction::Done),
8697 &PHRASES_EN,
8698 never
8699 ),
8700 ActionDecision::Stale
8701 );
8702 }
8703
8704 #[test]
8705 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
8706 let mut t = held_task_with("r1");
8707 let never = |_: &str| -> Result<RunState> { bail!("not read") };
8708 assert_eq!(
8709 decide_action(
8710 &t,
8711 &action_question("r1", ask::ChoiceAction::Requeue),
8712 &PHRASES_EN,
8713 never
8714 ),
8715 ActionDecision::Requeue
8716 );
8717 let done_q = action_question("r1", ask::ChoiceAction::Done);
8718 assert_eq!(
8719 decide_action(&t, &done_q, &PHRASES_EN, never),
8720 ActionDecision::Done
8721 );
8722 t.mark_action_applied(&done_q.id);
8723 assert_eq!(
8724 decide_action(&t, &done_q, &PHRASES_EN, never),
8725 ActionDecision::Skip
8726 );
8727
8728 let mut plain = action_question("r1", ask::ChoiceAction::Done);
8730 plain.actions.clear();
8731 assert_eq!(
8732 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
8733 ActionDecision::Skip
8734 );
8735 let mut running = held_task_with("r1");
8737 running.status = TaskStatus::Running;
8738 assert_eq!(
8739 decide_action(
8740 &running,
8741 &action_question("r1", ask::ChoiceAction::Done),
8742 &PHRASES_EN,
8743 never
8744 ),
8745 ActionDecision::Skip
8746 );
8747 }
8748
8749 #[test]
8750 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
8751 let dir = tempfile::tempdir().unwrap();
8752 let queue = Queue::at(dir.path().join("queue"));
8753 let questions = Questions::at(dir.path().join("questions"));
8754 let home = dir.path().join("home");
8755 let mut state = run_state(RunStatus::Blocked);
8756 state.id = "20260101-000000-act1".to_owned();
8757 state.save_under(&home).unwrap();
8758
8759 let mut t = held_task_with(&state.id);
8760 queue.put(&mut t).unwrap();
8761 let mut q = action_question(&state.id, resume_action(&state.id));
8762 questions.put(&mut q).unwrap();
8763
8764 apply_choice_actions(&queue, &questions, &home);
8765 let after = queue.get(&t.id).unwrap();
8766 assert_eq!(after.status, TaskStatus::Queued);
8767 assert!(!after.fresh_start);
8768 assert!(after.action_applied(&q.id));
8769 let pin = after.resume_override.clone().unwrap();
8770 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
8771 assert!(pin.forced);
8772
8773 let mut again = queue.get(&t.id).unwrap();
8775 again.hold_machine(Some("later".into()));
8776 queue.put(&mut again).unwrap();
8777 apply_choice_actions(&queue, &questions, &home);
8778 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8779 }
8780
8781 #[test]
8782 fn a_delivered_answer_is_still_acted_on_exactly_once() {
8783 let dir = tempfile::tempdir().unwrap();
8784 let queue = Queue::at(dir.path().join("queue"));
8785 let questions = Questions::at(dir.path().join("questions"));
8786 let home = dir.path().join("home");
8787 let mut state = run_state(RunStatus::Blocked);
8788 state.id = "20260101-000000-act2".to_owned();
8789 state.save_under(&home).unwrap();
8790
8791 let mut t = held_task_with(&state.id);
8792 queue.put(&mut t).unwrap();
8793 let mut q = action_question(&state.id, resume_action(&state.id));
8794 q.answer_delivered = true;
8795 questions.put(&mut q).unwrap();
8796
8797 apply_choice_actions(&queue, &questions, &home);
8800 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8801 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
8802
8803 let mut again = queue.get(&t.id).unwrap();
8805 again.hold_machine(Some("later".into()));
8806 queue.put(&mut again).unwrap();
8807 apply_choice_actions(&queue, &questions, &home);
8808 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8809 }
8810
8811 #[test]
8812 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
8813 let dir = tempfile::tempdir().unwrap();
8814 let queue = Queue::at(dir.path().join("queue"));
8815 let questions = Questions::at(dir.path().join("questions"));
8816 let home = dir.path().join("home");
8817 let mut state = run_state(RunStatus::Blocked);
8818 state.id = "20260101-000000-act3".to_owned();
8819 state.save_under(&home).unwrap();
8820 let mut t = held_task_with(&state.id);
8821 queue.put(&mut t).unwrap();
8822 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
8823 questions.put(&mut q).unwrap();
8824
8825 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
8826 apply_choice_actions(&queue, &questions, &home);
8827 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8828
8829 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
8830 apply_choice_actions(&queue, &questions, &home);
8831 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8832 }
8833
8834 #[test]
8835 fn action_standing_tells_the_reasons_apart() {
8836 let mut t = held_task_with("r1");
8837 let q = action_question("r1", ask::ChoiceAction::Requeue);
8838 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
8839 let mut plain = q.clone();
8840 plain.actions.clear();
8841 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
8842
8843 t.mark_action_applied(&q.id);
8845 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
8846
8847 let mut t = held_task_with("r1");
8849 t.start("r2".to_owned());
8850 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
8851 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
8853 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8854 t.status = TaskStatus::Blocked;
8855 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8856
8857 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
8859 c.node = crate::conduct::NODE.to_owned();
8860 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
8861 assert!(!ActionStanding::Busy.daemon_owns());
8862 }
8863
8864 #[test]
8865 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
8866 let dir = tempfile::tempdir().unwrap();
8867 let queue = Queue::at(dir.path().join("queue"));
8868 let questions = Questions::at(dir.path().join("questions"));
8869 let home = dir.path().join("home");
8870 let mut state = run_state(RunStatus::Blocked);
8871 state.id = "20260101-000000-act4".to_owned();
8872 state.save_under(&home).unwrap();
8873 let mut t = held_task_with(&state.id);
8874 t.status = TaskStatus::Running;
8875 queue.put(&mut t).unwrap();
8876 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
8877 q.cwd = Some(dir.path().display().to_string());
8878 questions.put(&mut q).unwrap();
8879
8880 let running = queue.get(&t.id).unwrap();
8883 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
8884 assert!(matches!(
8885 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
8886 crate::waiter::Action::Deliver(_)
8887 ));
8888 apply_choice_actions(&queue, &questions, &home);
8890 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8891 let mut back = queue.get(&t.id).unwrap();
8892 back.hold_machine(Some("later".into()));
8893 queue.put(&mut back).unwrap();
8894 apply_choice_actions(&queue, &questions, &home);
8895 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
8896 let mut again = queue.get(&t.id).unwrap();
8897 again.hold_machine(Some("again".into()));
8898 queue.put(&mut again).unwrap();
8899 apply_choice_actions(&queue, &questions, &home);
8900 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8901 }
8902}