1use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71pub const SCHEMA: u32 = 1;
73
74pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79pub const STALE_SECS: i64 = 30;
88
89pub const POLL: Duration = Duration::from_secs(5);
91
92pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 pub task: String,
123 pub run: String,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 pub schema: u32,
137 pub pid: u32,
139 pub started_at: Timestamp,
141 pub updated_at: Timestamp,
143 pub idle: bool,
145 pub current: Vec<Current>,
151 pub completed: usize,
153 pub polls: u64,
155}
156
157impl Status {
158 #[must_use]
160 pub fn new() -> Self {
161 let now = Timestamp::now();
162 Self {
163 schema: SCHEMA,
164 pid: std::process::id(),
165 started_at: now,
166 updated_at: now,
167 idle: true,
168 current: Vec::new(),
169 completed: 0,
170 polls: 0,
171 }
172 }
173}
174
175impl Default for Status {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180
181#[derive(Debug, Clone)]
183pub struct Opts {
184 pub repo: PathBuf,
186 pub config: Option<PathBuf>,
188 pub poll: Duration,
190 pub max_attempts: usize,
192 pub once: bool,
194 pub merge: Option<String>,
196 pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208 fn default() -> Self {
209 Self {
210 repo: PathBuf::from("."),
211 config: None,
212 poll: POLL,
213 max_attempts: 2,
214 once: false,
215 merge: None,
216 worktrees_root: None,
217 }
218 }
219}
220
221fn max_concurrent(n: usize) -> usize {
226 n.max(1)
227}
228
229#[must_use]
231pub fn status_path() -> PathBuf {
232 crate::run::home().join("daemon.json")
233}
234
235pub fn write_status(status: &Status) -> Result<()> {
237 write_status_to(&status_path(), status)
238}
239
240pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247 }
248 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249 let tmp = path.with_extension("json.tmp");
250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252 Ok(())
253}
254
255pub fn clear_status() {
258 clear_status_at(&status_path());
259}
260
261fn clear_status_at(path: &Path) {
265 let _ = std::fs::remove_file(path);
266}
267
268#[derive(Debug, Clone, Default)]
281pub struct Stop {
282 stopped: Arc<AtomicBool>,
286 busy: Arc<std::sync::atomic::AtomicUsize>,
292 wake: Arc<Notify>,
296 pause: crate::graph::Pause,
299}
300
301impl Stop {
302 #[must_use]
304 pub fn new() -> Self {
305 Self::default()
306 }
307
308 pub fn stop(&self) {
311 self.stopped.store(true, Ordering::SeqCst);
312 self.wake.notify_one();
316 }
317
318 #[must_use]
320 pub fn stopped(&self) -> bool {
321 self.stopped.load(Ordering::SeqCst)
322 }
323
324 #[must_use]
332 pub fn finishing(&self) -> bool {
333 self.stopped() && self.busy_now()
334 }
335
336 pub fn park(&self) {
347 self.pause.park();
348 self.stop();
349 }
350
351 #[must_use]
353 pub fn parking(&self) -> bool {
354 self.pause.parked()
355 }
356
357 #[must_use]
359 pub fn pause(&self) -> crate::graph::Pause {
360 self.pause.clone()
361 }
362
363 #[must_use]
369 pub fn busy_now(&self) -> bool {
370 self.busy.load(Ordering::SeqCst) > 0
371 }
372
373 fn enter(&self) {
375 self.busy.fetch_add(1, Ordering::SeqCst);
376 }
377
378 fn exit(&self) {
381 self.busy.fetch_sub(1, Ordering::SeqCst);
382 }
383
384 async fn idle(&self, poll: Duration) {
386 tokio::select! {
387 () = tokio::time::sleep(poll) => {}
388 () = self.wake.notified() => {}
389 }
390 }
391}
392
393#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402 pub schema: u32,
404 pub pid: Option<u32>,
406 pub started_at: Option<Timestamp>,
408 pub updated_at: Option<Timestamp>,
410 pub idle: bool,
412 #[serde(deserialize_with = "de_current")]
424 pub current: Vec<Current>,
425 pub completed: u64,
427 pub polls: u64,
429}
430
431fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435 D: serde::Deserializer<'de>,
436{
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum Shape {
440 Many(Vec<Current>),
441 One(Current),
442 }
443 Ok(
444 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445 Shape::Many(v) => v,
446 Shape::One(c) => vec![c],
447 }),
448 )
449}
450
451impl Reading {
452 #[must_use]
455 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456 self.updated_at
457 .map(|at| (now.as_second() - at.as_second()).max(0))
458 }
459
460 #[must_use]
464 pub fn running(&self, now: Timestamp) -> bool {
465 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466 }
467}
468
469#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478 serde_json::from_str(&body).ok()
479}
480
481#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494 read_status(home)
495 .filter(|reading| reading.running(now))
496 .map(|reading| reading.current)
497 .unwrap_or_default()
498}
499
500#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503 current_work(home, now).iter().any(|c| c.run == run)
504}
505
506#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517 current_work(home, now)
518 .iter()
519 .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525 current_work(home, now).iter().any(|c| c.task == task)
526}
527
528pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580 F: Fn(u32) -> bool,
581{
582 let this_process = std::process::id();
583 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584 .into_iter()
585 .flatten()
586 .flatten()
587 .map(|e| e.path())
588 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589 .filter(|p| {
590 match std::fs::read_to_string(p)
591 .ok()
592 .and_then(|body| body.trim().parse::<u32>().ok())
593 {
594 Some(pid) if pid == this_process => false,
598 Some(pid) => !pid_alive(pid),
599 None => p
600 .metadata()
601 .and_then(|m| m.modified())
602 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603 .is_ok_and(|age| age >= older_than),
604 }
605 })
606 .filter(|p| std::fs::remove_file(p).is_ok())
607 .filter_map(|p| {
608 p.file_stem()
609 .and_then(|s| s.to_str())
610 .map(std::borrow::ToOwned::to_owned)
611 })
612 .collect();
613 swept.sort_unstable();
614 swept
615}
616
617fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622 task.status == TaskStatus::Running
623 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624 && !is_working_on_task(home, &task.id, now)
625}
626
627fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630 queue
631 .list()
632 .into_iter()
633 .filter(|t| is_stalled(t, home, now))
634 .collect()
635}
636
637fn queued_tasks(queue: &Queue) -> Vec<Task> {
643 queue
644 .list()
645 .into_iter()
646 .filter(|t| t.status == TaskStatus::Queued)
647 .collect()
648}
649
650fn finished_tasks(queue: &Queue) -> Vec<Task> {
653 queue
654 .list()
655 .into_iter()
656 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657 .collect()
658}
659
660fn resolve_blockers(queue: &Queue, questions: &Questions) {
677 for listed in queue.list() {
678 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679 continue;
680 }
681 let Ok(_claim) = queue.claim(&listed.id) else {
682 continue;
683 };
684 let Ok(mut task) = queue.get(&listed.id) else {
685 continue;
686 };
687 if task.status != TaskStatus::Blocked {
688 continue;
689 }
690 let deleted = queue.apply_deleted_blockers(&mut task);
694 if !deleted.is_empty() {
695 record(queue, &mut task);
696 for id in &deleted {
697 queue.note_dependency_deleted(&task, id);
698 }
699 if task.status != TaskStatus::Blocked {
700 continue;
701 }
702 }
703 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
704 if !missing.is_empty() {
705 let language = language_of(&task, Path::new("."));
706 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
707 &task.blocked_by,
708 &missing,
709 &language,
710 )));
711 record(queue, &mut task);
712 continue;
713 }
714 if let Some(q) = task.blocked_by.iter().find_map(|id| {
717 questions.get(id).ok().filter(|q| {
718 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
719 })
720 }) {
721 let language = language_of(&task, Path::new("."));
722 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
723 record(queue, &mut task);
724 continue;
725 }
726 let mut changed = false;
727 for id in task.blocked_by.clone() {
728 if let Ok(dep) = queue.get(&id) {
729 if dep.status == TaskStatus::Done {
730 task.unblock(&id);
731 changed = true;
732 }
733 continue;
734 }
735 if let Ok(q) = questions.get(&id)
736 && q.status == ask::QuestionStatus::Answered
737 {
738 let answer = match &q.answer {
739 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
740 None => String::new(),
741 };
742 task.record_answer(q.summary.clone(), answer);
743 task.unblock(&id);
744 changed = true;
745 }
746 }
747 if changed {
748 record(queue, &mut task);
749 }
750 }
751}
752
753fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
755 if crate::lang::is_japanese(language) {
756 format!(
757 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
758 q.short(),
759 q.summary
760 )
761 } else {
762 format!(
763 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
764 q.short(),
765 q.summary
766 )
767 }
768}
769
770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
773pub(crate) enum ActionStanding {
774 NoAction,
776 Pending,
778 Applied,
781 Stale,
783 Busy,
785}
786
787impl ActionStanding {
788 pub(crate) fn daemon_owns(self) -> bool {
790 matches!(self, Self::Pending | Self::Applied | Self::Stale)
791 }
792}
793
794pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
798 if q.chosen_action().is_none() {
799 ActionStanding::NoAction
800 } else if task.action_applied(&q.id) {
801 ActionStanding::Applied
802 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
803 ActionStanding::Stale
804 } else if matches!(
805 task.status,
806 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
807 ) {
808 ActionStanding::Busy
809 } else {
810 ActionStanding::Pending
811 }
812}
813
814#[derive(Debug, Clone, PartialEq, Eq)]
816enum ActionDecision {
817 Skip,
819 Resume(String),
821 Requeue,
823 Done,
825 Stale,
828 Refuse(String),
831}
832
833fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
841where
842 F: FnOnce(&str) -> Result<RunState>,
843{
844 let Some(action) = q.chosen_action() else {
845 return ActionDecision::Skip;
846 };
847 if task.action_applied(&q.id)
848 || matches!(
849 task.status,
850 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
851 )
852 {
853 return ActionDecision::Skip;
854 }
855 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
858 return ActionDecision::Stale;
859 }
860 match action {
861 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
862 ask::ChoiceAction::Done => ActionDecision::Done,
863 ask::ChoiceAction::Resume { run } => {
864 if task.runs.last() != Some(run) {
865 return ActionDecision::Refuse((p.resume_not_latest)(
866 q.short(),
867 ask::short_id(run),
868 ));
869 }
870 match load(run) {
871 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
872 ActionDecision::Resume(run.clone())
873 }
874 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
875 q.short(),
876 ask::short_id(run),
877 )),
878 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
879 q.short(),
880 ask::short_id(run),
881 &format!("{e:#}"),
882 )),
883 }
884 }
885 }
886}
887
888struct Phrases {
902 graph_stopped: fn(&str, &str) -> String,
904 quorum_lost: &'static str,
905 quota_took_out: &'static str,
907 run_ended: &'static str,
909 waiting_for_answer: &'static str,
911 recovered_running: &'static str,
912 no_run_to_recover: &'static str,
913 could_not_start: &'static str,
914 resume_not_latest: fn(&str, &str) -> String,
915 resume_cannot_progress: fn(&str, &str) -> String,
916 resume_unreadable: fn(&str, &str, &str) -> String,
917 handover_refused: fn(&crate::handover::Refused) -> String,
920 handover_hint: &'static str,
922 reviewers_never_answered: fn(usize, usize) -> String,
925}
926
927const PHRASES_EN: Phrases = Phrases {
928 graph_stopped: |status, detail| {
929 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
930 },
931 quorum_lost: "the judging panel lost its quorum",
932 quota_took_out: "; quota took out ",
933 run_ended: "run ended ",
934 waiting_for_answer: " - waiting for operator answer to question ",
935 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
936 no_run_to_recover: "task was `running` with no live daemon and no readable \
937 run to recover; held for a human to check what happened",
938 could_not_start: "could not start the run: ",
939 resume_not_latest: |q, run| {
940 format!("question {q} asked to resume run {run}, which is not this task's latest run")
941 },
942 resume_cannot_progress: |q, run| {
943 format!("question {q} asked to resume run {run}, which cannot make progress")
944 },
945 resume_unreadable: |q, run, e| {
946 format!("question {q} asked to resume run {run}, which could not be read: {e}")
947 },
948 handover_refused: |r| r.to_string(),
949 handover_hint: " (clean up the other worktree, then release the task from the queue)",
950 reviewers_never_answered: |missing, rounds| {
951 format!(
952 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
953 refusing to call it clean"
954 )
955 },
956};
957
958const PHRASES_JA: Phrases = Phrases {
959 graph_stopped: |status, detail| {
960 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
961 },
962 quorum_lost: "審査パネルが定足数を失いました",
963 quota_took_out: "。クォータで脱落: ",
964 run_ended: "run 終了: ",
965 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
966 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
967 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
968 何が起きたか人が確認するため保留にしました",
969 could_not_start: "run を開始できませんでした: ",
970 resume_not_latest: |q, run| {
971 format!(
972 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
973 )
974 },
975 resume_cannot_progress: |q, run| {
976 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
977 },
978 resume_unreadable: |q, run, e| {
979 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
980 },
981 handover_refused: |r| {
982 use crate::handover::Refused;
983 match r {
984 Refused::Foreign { branch, path, why } => format!(
985 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
986 削除しません。不要なら `git worktree remove` でその worktree を削除して\
987 から、やり直してください(詳細: {why})"
988 ),
989 Refused::Unsafe { branch, path, why } => format!(
990 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
991 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
992 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
993 ),
994 Refused::ReleaseFailed { branch, path, run } => format!(
995 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
996 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
997 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
998 ),
999 }
1000 },
1001 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1002 reviewers_never_answered: |missing, rounds| {
1003 format!(
1004 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1005 クリーンとは認めません"
1006 )
1007 },
1008};
1009
1010fn phrases(language: &str) -> &'static Phrases {
1011 if crate::lang::is_japanese(language) {
1012 &PHRASES_JA
1013 } else {
1014 &PHRASES_EN
1015 }
1016}
1017
1018fn language_of(task: &Task, fallback: &Path) -> String {
1022 crate::lang::of_repo(&repo_for(task, fallback))
1023}
1024
1025pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1029 if q.node == crate::conduct::NODE {
1030 return tasks.iter().find(|t| t.id == q.run);
1031 }
1032 tasks.iter().find(|t| t.runs.contains(&q.run))
1033}
1034
1035fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1044 let tasks = queue.list();
1045 for q in questions.list() {
1046 if q.chosen_action().is_none() {
1047 continue;
1048 }
1049 let Some(listed) = task_of_question(&tasks, &q) else {
1050 continue;
1051 };
1052 if listed.action_applied(&q.id) {
1053 continue;
1054 }
1055 let Ok(_claim) = queue.claim(&listed.id) else {
1056 continue;
1057 };
1058 let Ok(mut task) = queue.get(&listed.id) else {
1059 continue;
1060 };
1061 let language = language_of(&task, Path::new("."));
1062 let decision = decide_action(&task, &q, phrases(&language), |id| {
1063 RunState::load_under(id, home)
1064 });
1065 let ran = matches!(
1066 decision,
1067 ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1068 );
1069 if ran && asker_may_still_read(questions, &q, home) {
1070 continue;
1079 }
1080 let done = matches!(decision, ActionDecision::Done);
1081 match decision {
1082 ActionDecision::Skip => continue,
1083 ActionDecision::Resume(run) => {
1084 task.release();
1085 task.resume_override = Some(crate::queue::OperatorResume {
1086 question_id: q.id.clone(),
1087 at: Timestamp::now(),
1088 conductor_rehold: None,
1089 forced: true,
1090 pinned_run: Some(run),
1091 });
1092 }
1093 ActionDecision::Stale => {}
1094 ActionDecision::Requeue => task.requeue(),
1095 ActionDecision::Done => task.succeed(),
1096 ActionDecision::Refuse(why) => {
1097 task.hold_machine(Some(why));
1098 notices::raise(
1099 Notice::warn(
1100 &format!("action:{}", q.id),
1101 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1102 )
1103 .link(Link::Task {
1104 id: task.id.clone(),
1105 }),
1106 );
1107 }
1108 }
1109 task.mark_action_applied(&q.id);
1110 record(queue, &mut task);
1113 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1114 supersede_prior_runs(&task, home);
1115 }
1116 let _ = questions.update(&q.id, |r| {
1119 r.answer_delivered = true;
1120 Ok(())
1121 });
1122 }
1123}
1124
1125fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1129 let now = Timestamp::now();
1130 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1131 return true;
1132 }
1133 q.node != crate::conduct::NODE
1134 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1135 s.seats_active()
1136 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1137 })
1138}
1139
1140fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1151 let tasks = queue.list();
1152 let by_id: std::collections::BTreeMap<&str, &Task> =
1153 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1154 let referenced: std::collections::BTreeSet<&str> = tasks
1155 .iter()
1156 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1157 .collect();
1158
1159 for mut question in questions.list() {
1160 if !question.status.open() || question.node != crate::conduct::NODE {
1161 continue;
1162 }
1163 if referenced.contains(question.id.as_str()) {
1166 continue;
1167 }
1168 let Some(task) = by_id.get(question.run.as_str()) else {
1169 continue;
1170 };
1171 question.abandon(format!(
1172 "task {} no longer waits for this answer",
1173 task.short()
1174 ));
1175 if let Err(e) = questions.put(&mut question) {
1176 tracing::warn!(
1177 "could not retire question {} for task {}: {e:#}",
1178 question.short(),
1179 task.short()
1180 );
1181 }
1182 }
1183}
1184
1185#[derive(Debug, Clone, Copy)]
1192pub struct Verdict {
1193 pub status: RunStatus,
1195 pub left_pr: bool,
1197 pub quota_hit: bool,
1199 pub parked: bool,
1201 pub no_viable_candidates: bool,
1208}
1209
1210pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1267 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1268}
1269
1270fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1272 if verdict.parked {
1278 task.stall(detail);
1279 return;
1280 }
1281 match verdict.status {
1282 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1283 RunStatus::AlreadyInBase => task.already_landed(detail),
1284 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1285 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1286 task.stall(detail)
1287 }
1288 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1289 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1290 RunStatus::Blocked => task.fail(detail, max_attempts),
1291 RunStatus::VerifiedNoop => task.handed_off(detail),
1292 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1293 }
1294}
1295
1296pub fn supersede_prior_runs(task: &Task, home: &Path) {
1345 let now = Timestamp::now();
1346 let last_run_succeeded = task
1353 .runs
1354 .last()
1355 .and_then(|id| RunState::load_under(id, home).ok())
1356 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1357 for id in task.superseded_attempts(last_run_succeeded) {
1358 let mut state = match RunState::load_under(id, home) {
1359 Ok(s) => s,
1360 Err(e) => {
1361 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1362 continue;
1363 }
1364 };
1365 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1366 continue;
1367 }
1368 let daemon_claims = is_working_on(home, id, now);
1369 if state.liveness(daemon_claims) == Liveness::Live {
1370 continue;
1371 }
1372 state.status = RunStatus::Superseded;
1373 if let Err(e) = state.save_under(home) {
1374 tracing::warn!("could not mark run {id} superseded: {e:#}");
1375 }
1376 }
1377}
1378
1379fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1401 for task in queue.list() {
1402 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1403 continue;
1404 }
1405 supersede_prior_runs(&task, home);
1406 }
1407}
1408
1409fn settle_and_diagnose(
1416 task: &mut Task,
1417 verdict: Verdict,
1418 detail: &str,
1419 max_attempts: usize,
1420 state: &RunState,
1421) {
1422 let p = phrases(&state.config.graph.language);
1423 settle_in(task, verdict, detail, max_attempts, p);
1424 if task.status == TaskStatus::Held {
1425 task.diagnostic = diagnostic(state);
1426 note_open_question(task, &state.id, p);
1427 }
1428}
1429
1430fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1445 let Some(home) = crate::run::try_home() else {
1446 return;
1447 };
1448 let open = Questions::at(home.join("questions")).open_for(run);
1449 let Some(q) = open.first() else {
1450 return;
1451 };
1452 let base = task.hold_reason.clone().unwrap_or_default();
1453 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1454}
1455
1456fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1467 match last_run {
1468 Some(state) => {
1469 let verdict = Verdict {
1470 status: state.status,
1471 left_pr: state.pr.is_some(),
1472 quota_hit: !state.quota.is_empty(),
1473 parked: state.parked,
1474 no_viable_candidates: state.viable().is_empty(),
1475 };
1476 let detail = format!(
1477 "{}{}",
1478 phrases(&state.config.graph.language).recovered_running,
1479 describe(&state)
1480 );
1481 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1482 }
1483 None => {
1484 let why = phrases(language).no_run_to_recover;
1487 task.last_error = Some(why.to_owned());
1488 task.hold_machine(Some(why.to_owned()));
1491 }
1492 }
1493}
1494
1495fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1517 let mut reclaimed = Vec::new();
1518 for listed in queue.list() {
1519 if listed.status != TaskStatus::Running {
1520 continue;
1521 }
1522 let Ok(_claim) = queue.claim(&listed.id) else {
1523 continue;
1524 };
1525 let Ok(mut task) = queue.get(&listed.id) else {
1529 continue;
1530 };
1531 if task.status != TaskStatus::Running {
1532 continue;
1533 }
1534 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1535 if let Some(state) = &last_run
1545 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1546 {
1547 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1548 }
1549 let language = if last_run.is_none() {
1550 language_of(&task, Path::new("."))
1551 } else {
1552 String::new()
1553 };
1554 reclaim(&mut task, last_run, max_attempts, &language);
1555 if task.status == TaskStatus::Done {
1556 supersede_prior_runs(&task, &crate::run::home());
1557 }
1558 record(queue, &mut task);
1559 reclaimed.push(task.id.clone());
1560 }
1561 reclaimed
1562}
1563
1564fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1596 reclaim_abandoned_runs_with(
1597 home,
1598 now,
1599 crate::proc::pid_status,
1600 crate::proc::process_started_at,
1601 )
1602}
1603
1604fn reclaim_abandoned_runs_with<F, G>(
1610 home: &Path,
1611 now: Timestamp,
1612 query: F,
1613 identity: G,
1614) -> Vec<String>
1615where
1616 F: Fn(u32) -> Option<bool>,
1617 G: Fn(u32) -> Option<String>,
1618{
1619 let mut abandoned = Vec::new();
1620 for entry in std::fs::read_dir(home.join("runs"))
1621 .into_iter()
1622 .flatten()
1623 .flatten()
1624 {
1625 let id = entry.file_name().to_string_lossy().into_owned();
1626 if !crate::run::is_run_id(&id) {
1627 continue;
1628 }
1629 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1637 continue;
1638 };
1639 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1640 continue;
1641 };
1642 if state.status.done() || !state.active_all_overrun(now) {
1643 continue;
1644 }
1645 let daemon_claims = is_working_on(home, &id, now);
1657 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1658 continue;
1659 }
1660 state.abandon("daemon");
1661 if let Err(e) = state.save_under(home) {
1662 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1663 continue;
1664 }
1665 if let Some(notice) = notices::run_ended(&state) {
1668 notices::raise_in(home, notice);
1669 }
1670 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1678 tracing::warn!("abandon questions for {id}: {e:#}");
1679 }
1680 abandoned.push(id);
1681 }
1682 abandoned
1683}
1684
1685pub async fn serve(opts: Opts) -> Result<()> {
1691 serve_until(opts, Stop::new()).await
1692}
1693
1694pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1711 let signal = {
1712 let stop = stop.clone();
1713 tokio::spawn(async move {
1714 if tokio::signal::ctrl_c().await.is_ok() {
1715 stop.stop();
1716 tracing::info!("shutdown requested; a run in flight will be finished first");
1717 }
1718 })
1719 };
1720
1721 let worktrees_root = opts
1722 .worktrees_root
1723 .clone()
1724 .unwrap_or_else(crate::run::default_worktree_root);
1725 let outcome = drive(
1726 &opts,
1727 &Queue::open(),
1728 &status_path(),
1729 &crate::run::home(),
1730 &worktrees_root,
1731 &stop,
1732 )
1733 .await;
1734
1735 signal.abort();
1736 outcome
1737}
1738
1739async fn drive(
1752 opts: &Opts,
1753 queue: &Queue,
1754 status_file: &Path,
1755 home: &Path,
1756 worktrees_root: &Path,
1757 stop: &Stop,
1758) -> Result<()> {
1759 let status = Arc::new(Mutex::new(Status::new()));
1767 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1768 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1769
1770 let daemon_cfg = prepare(&opts.repo, opts)
1776 .map(|c| c.daemon)
1777 .unwrap_or_default();
1778 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1779
1780 let waiter = tokio::spawn(crate::waiter::run(
1785 crate::waiter::Waiter::new(
1786 crate::ask::Questions::at(home.join("questions")),
1787 home.to_path_buf(),
1788 prepare(&opts.repo, opts).ok(),
1789 ),
1790 stop.clone(),
1791 ));
1792
1793 let deputies = tokio::spawn(crate::deputy::run(
1797 crate::deputy::Deputies::new(
1798 crate::ask::Questions::at(home.join("questions")),
1799 home.to_path_buf(),
1800 prepare(&opts.repo, opts).ok(),
1801 opts.repo.clone(),
1802 daemon_cfg.max_deputies,
1803 {
1804 let stop = stop.clone();
1805 Arc::new(move || stop.parking())
1806 },
1807 ),
1808 stop.clone(),
1809 ));
1810
1811 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1814
1815 tracing::info!(
1816 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1817 queue.root().display(),
1818 opts.poll.as_secs(),
1819 opts.max_attempts,
1820 concurrency,
1821 if daemon_cfg.pause_for_interrupts {
1822 ", interrupts enabled"
1823 } else {
1824 ""
1825 }
1826 );
1827
1828 janitor(&opts.repo, opts, home, worktrees_root).await;
1831 resweep_superseded_attempts(queue, home);
1832
1833 let outcome = poll(
1834 opts,
1835 queue,
1836 &status,
1837 home,
1838 worktrees_root,
1839 stop,
1840 DispatchLimits {
1841 max_concurrent: concurrency,
1842 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1843 },
1844 )
1845 .await;
1846
1847 beat.abort();
1848 waiter.abort();
1849 deputies.abort();
1850 fetcher.abort();
1851 clear_status_at(status_file);
1852 outcome
1853}
1854
1855const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
1857
1858async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
1862 while !stop.stopped() {
1863 let (interval, roots) = match prepare(&repo, &opts) {
1864 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
1865 Err(_) => (0, Vec::new()),
1866 };
1867 if interval > 0 && !roots.is_empty() {
1868 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
1869 tracing::debug!("fetch origins: {r:?}");
1870 }
1871 let wait = if interval > 0 { interval } else { 60 };
1873 let mut slept = 0;
1874 while slept < wait && !stop.stopped() {
1875 tokio::time::sleep(Duration::from_secs(1)).await;
1876 slept += 1;
1877 }
1878 }
1879}
1880
1881async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1887 loop {
1888 tokio::time::sleep(HEARTBEAT).await;
1889 let snapshot = {
1890 let mut guard = lock(&status);
1891 guard.updated_at = Timestamp::now();
1892 guard.clone()
1893 };
1894 if let Err(e) = write_status_to(&path, &snapshot) {
1895 tracing::warn!("could not refresh the daemon status file: {e:#}");
1898 }
1899 }
1900}
1901
1902#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1905enum LandResume {
1906 NotLanding,
1909 StillWaiting,
1914 Ready,
1918}
1919
1920fn land_resume_state(task: &Task) -> LandResume {
1924 let Some(run_id) = task.runs.last() else {
1925 return LandResume::NotLanding;
1926 };
1927 let Ok(state) = RunState::load(run_id) else {
1928 return LandResume::NotLanding;
1929 };
1930 if state.status != RunStatus::Landing || !state.parked {
1931 return LandResume::NotLanding;
1932 }
1933 let store = ask::Questions::open();
1934 let waiting = store
1935 .list()
1936 .into_iter()
1937 .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1938 .max_by(|a, b| a.id.cmp(&b.id));
1939 let Some(mut q) = waiting else {
1940 return LandResume::Ready;
1941 };
1942 if !q.status.open() {
1943 return LandResume::Ready;
1944 }
1945 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1952 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1953 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1954 q.abandon(format!(
1955 "no answer within {}s of asking",
1956 timeout.as_secs().max(1)
1957 ));
1958 if store.put(&mut q).is_ok() {
1961 return LandResume::Ready;
1962 }
1963 }
1964 LandResume::StillWaiting
1965}
1966
1967const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1975
1976const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
1988
1989struct InFlightGuard<'a> {
2002 status: &'a Arc<Mutex<Status>>,
2003 stop: &'a Stop,
2004 task_id: &'a str,
2005}
2006
2007impl Drop for InFlightGuard<'_> {
2008 fn drop(&mut self) {
2009 lock(self.status).current.retain(|c| c.task != self.task_id);
2010 self.stop.exit();
2011 }
2012}
2013
2014#[derive(Debug, Clone, PartialEq, Eq)]
2036enum Interrupt {
2037 Idle,
2039 Parking {
2051 parked: Vec<String>,
2052 interrupt_task: String,
2053 },
2054 Running {
2062 parked: Vec<String>,
2063 interrupt_task: String,
2064 },
2065 Resuming { parked: Vec<String> },
2072}
2073
2074fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2095 match state {
2096 Interrupt::Idle => {
2097 if in_flight.len() != 1 {
2109 return Interrupt::Idle;
2110 }
2111 match runnable.iter().find(|t| t.interrupt) {
2112 Some(t) => Interrupt::Parking {
2113 parked: in_flight.to_vec(),
2114 interrupt_task: t.id.clone(),
2115 },
2116 None => Interrupt::Idle,
2117 }
2118 }
2119 Interrupt::Parking {
2120 parked,
2121 interrupt_task,
2122 } => {
2123 if in_flight.iter().any(|id| parked.contains(id)) {
2124 Interrupt::Parking {
2126 parked,
2127 interrupt_task,
2128 }
2129 } else if in_flight.contains(&interrupt_task) {
2130 Interrupt::Running {
2131 parked,
2132 interrupt_task,
2133 }
2134 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2135 Interrupt::Parking {
2139 parked,
2140 interrupt_task,
2141 }
2142 } else {
2143 Interrupt::Resuming { parked }
2148 }
2149 }
2150 Interrupt::Running {
2151 parked,
2152 interrupt_task,
2153 } => {
2154 if in_flight.contains(&interrupt_task) {
2155 Interrupt::Running {
2156 parked,
2157 interrupt_task,
2158 }
2159 } else {
2160 Interrupt::Resuming { parked }
2166 }
2167 }
2168 Interrupt::Resuming { parked } => {
2169 if in_flight.iter().any(|id| parked.contains(id)) {
2170 Interrupt::Idle
2176 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2177 Interrupt::Resuming { parked }
2178 } else {
2179 Interrupt::Idle
2182 }
2183 }
2184 }
2185}
2186
2187fn advance_interrupt_tick(
2193 enabled: bool,
2194 state: Interrupt,
2195 in_flight: &[String],
2196 runnable: &[Task],
2197) -> Interrupt {
2198 if !enabled {
2199 return Interrupt::Idle;
2200 }
2201 advance_interrupt(state, in_flight, runnable)
2202}
2203
2204fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2209 match state {
2210 Interrupt::Idle => candidates,
2211 Interrupt::Parking {
2212 parked,
2213 interrupt_task,
2214 } => {
2215 if in_flight.iter().any(|id| parked.contains(id)) {
2216 Vec::new()
2217 } else {
2218 candidates
2219 .into_iter()
2220 .filter(|t| &t.id == interrupt_task)
2221 .collect()
2222 }
2223 }
2224 Interrupt::Running { .. } => Vec::new(),
2225 Interrupt::Resuming { parked } => candidates
2233 .into_iter()
2234 .find(|t| parked.contains(&t.id))
2235 .into_iter()
2236 .collect(),
2237 }
2238}
2239
2240struct DispatchLimits {
2244 max_concurrent: usize,
2247 pause_for_interrupts: bool,
2249}
2250
2251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2260enum PermitKind {
2261 None,
2266 Urgent,
2273 Ordinary,
2276}
2277
2278fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2281 if priority {
2282 PermitKind::None
2283 } else if urgent {
2284 PermitKind::Urgent
2285 } else {
2286 PermitKind::Ordinary
2287 }
2288}
2289
2290async fn poll(
2309 opts: &Opts,
2310 queue: &Queue,
2311 status: &Arc<Mutex<Status>>,
2312 home: &Path,
2313 worktrees_root: &Path,
2314 stop: &Stop,
2315 limits: DispatchLimits,
2316) -> Result<()> {
2317 let DispatchLimits {
2318 max_concurrent,
2319 pause_for_interrupts,
2320 } = limits;
2321 let mut attempted: Vec<String> = Vec::new();
2326 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2327 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2335 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2341 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2342 let mut conductor = Conductor::new();
2343 let mut cache_last_checked: Option<Timestamp> = None;
2346 let mut interrupt = Interrupt::Idle;
2348 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2354 std::collections::HashMap::new();
2355
2356 while !stop.stopped() {
2357 lock(status).polls += 1;
2358
2359 while let Some(result) = inflight.try_join_next() {
2364 if let Err(e) = result {
2365 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2366 notices::raise(Notice::error(
2367 "loop:attempt",
2368 "A queued attempt ended abnormally; check the task it was running.",
2369 ));
2370 }
2371 }
2372
2373 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2374 if !swept.is_empty() {
2375 tracing::warn!(
2376 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2377 swept.len(),
2378 swept.join(", ")
2379 );
2380 }
2381 let now = Timestamp::now();
2386
2387 if !stop.busy_now() {
2392 maybe_prune_cache_between_runs(
2393 &opts.repo,
2394 opts,
2395 home,
2396 stop,
2397 &mut cache_last_checked,
2398 now,
2399 )
2400 .await;
2401 }
2402
2403 let stalled = stalled_tasks(queue, home, now);
2404 let stalled_ids: std::collections::BTreeSet<_> =
2405 stalled.iter().map(|task| task.id.clone()).collect();
2406 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2407 if !reclaimed.is_empty() {
2408 tracing::warn!(
2409 "reclaimed {} task(s) left `running` by a daemon that never \
2410 recorded the outcome: {}",
2411 reclaimed.len(),
2412 reclaimed.join(", ")
2413 );
2414 }
2415 let abandoned_runs = reclaim_abandoned_runs(home, now);
2416 if !abandoned_runs.is_empty() {
2417 tracing::warn!(
2418 "failed {} run(s) left behind by a killed process, past every \
2419 active seat's own timeout: {}",
2420 abandoned_runs.len(),
2421 abandoned_runs.join(", ")
2422 );
2423 }
2424
2425 let questions = Questions::at(home.join("questions"));
2430
2431 resolve_blockers(queue, &questions);
2434 apply_choice_actions(queue, &questions, home);
2435 reconcile_task_questions(queue, &questions);
2436
2437 let finished: Vec<Task> = finished_tasks(queue)
2443 .into_iter()
2444 .filter(|task| !stalled_ids.contains(&task.id))
2445 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2449 .collect();
2450 let queued = queued_tasks(queue);
2451 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2455 && conductor.worth_a_look(queue, &stalled, &finished)
2456 {
2457 match prepare(&opts.repo, opts) {
2458 Ok(cfg) => {
2459 conductor
2460 .maybe_run(
2461 &cfg,
2462 &opts.repo,
2463 queue,
2464 &questions,
2465 home,
2466 &queued,
2467 &stalled,
2468 &finished,
2469 opts.max_attempts,
2470 )
2471 .await;
2472 }
2473 Err(e) => {
2474 tracing::warn!("conductor: no config: {e:#}");
2475 notices::raise(Notice::warn(
2476 "loop:no-config",
2477 "The loop could not read this repository's config, so held tasks are not being triaged.",
2478 ));
2479 }
2480 }
2481 }
2482
2483 let candidates: Vec<Task> = runnable(queue)
2484 .into_iter()
2485 .filter(|t| !opts.once || !attempted.contains(&t.id))
2486 .collect();
2487
2488 let in_flight: Vec<String> = lock(status)
2493 .current
2494 .iter()
2495 .map(|c| c.task.clone())
2496 .collect();
2497 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2498
2499 interrupt =
2500 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2501 if let Interrupt::Parking {
2502 parked,
2503 interrupt_task,
2504 } = &interrupt
2505 {
2506 let reason = format!(
2507 "task {} asked to run first",
2508 crate::run::short_of(interrupt_task)
2509 );
2510 for id in parked {
2511 if let Some(pause) = interrupt_pauses.get(id) {
2512 pause.park_because(reason.clone());
2513 }
2514 }
2515 }
2516 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2517
2518 let cooling_down =
2519 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2520
2521 let mut started_any = false;
2522 for candidate in candidates {
2523 if stop.stopped() {
2524 break;
2525 }
2526
2527 let resume = land_resume_state(&candidate);
2528 if resume == LandResume::StillWaiting {
2529 continue;
2530 }
2531 let priority = resume == LandResume::Ready;
2532
2533 if !priority && cooling_down {
2534 continue;
2535 }
2536 let permit = match permit_kind(priority, candidate.urgent) {
2537 PermitKind::None => None,
2538 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2539 Ok(p) => Some(p),
2540 Err(_) => continue,
2546 },
2547 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2548 Ok(p) => Some(p),
2549 Err(_) => continue,
2553 },
2554 };
2555
2556 let Ok(claim) = queue.claim(&candidate.id) else {
2561 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2562 continue;
2563 };
2564 let mut task = match queue.get(&candidate.id) {
2567 Ok(t) if t.status.runnable() => t,
2568 Ok(_) => continue,
2569 Err(e) => {
2570 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2571 continue;
2572 }
2573 };
2574 let task_id = task.id.clone();
2575 attempted.push(task_id.clone());
2576 lock(status).idle = false;
2577 stop.enter();
2580 started_any = true;
2581
2582 let run_pause = crate::graph::Pause::new();
2586 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2587
2588 let opts = opts.clone();
2589 let queue = queue.clone();
2590 let status = Arc::clone(status);
2591 let stop = stop.clone();
2592 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2593 inflight.spawn(async move {
2594 let _claim = claim;
2598 let _permit = permit;
2599 let _inflight = InFlightGuard {
2601 status: &status,
2602 stop: &stop,
2603 task_id: &task_id,
2604 };
2605 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2606 lock(&status).completed += 1;
2607 let now = Timestamp::now();
2613 if let Some(until) = cooldown_until("a, now) {
2614 let wait = until.as_second() - now.as_second();
2615 *lock("a_cooldown_until) = Some(until);
2616 let hint = quota
2617 .iter()
2618 .find(|q| q.reset.is_some())
2619 .and_then(|q| q.reset.as_deref());
2620 match hint {
2621 Some(h) => tracing::warn!(
2622 "quota hit; waiting {wait}s before taking another ordinary task \
2623 (CLI reported reset: {h})"
2624 ),
2625 None => tracing::warn!(
2626 "quota hit; waiting {wait}s before taking another ordinary task \
2627 (no reset hint reported)"
2628 ),
2629 }
2630 }
2631 });
2632 }
2633
2634 if started_any {
2635 continue;
2636 }
2637
2638 if stop.busy_now() {
2639 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2644 continue;
2645 }
2646
2647 lock(status).idle = true;
2649 if opts.once {
2650 janitor(&opts.repo, opts, home, worktrees_root).await;
2654 resweep_superseded_attempts(queue, home);
2655 triage_held(queue, home, opts).await;
2656 break;
2657 }
2658 stop.idle(opts.poll).await;
2659 if stop.stopped() {
2660 continue;
2661 }
2662 janitor(&opts.repo, opts, home, worktrees_root).await;
2668 resweep_superseded_attempts(queue, home);
2669 triage_held(queue, home, opts).await;
2670 }
2671
2672 while let Some(result) = inflight.join_next().await {
2677 if let Err(e) = result {
2678 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2679 notices::raise(Notice::error(
2680 "loop:attempt",
2681 "A queued attempt ended abnormally; check the task it was running.",
2682 ));
2683 }
2684 }
2685 Ok(())
2686}
2687
2688async fn attempt(
2694 opts: &Opts,
2695 queue: &Queue,
2696 status: &Arc<Mutex<Status>>,
2697 stop: &Stop,
2698 interrupt_pause: crate::graph::Pause,
2699 task: &mut Task,
2700) -> Vec<QuotaLoss> {
2701 let repo = repo_for(task, &opts.repo);
2702 tracing::info!(
2703 "task {} — {} (repo {})",
2704 task.short(),
2705 task.title,
2706 repo.display()
2707 );
2708
2709 let mut config = match prepare(&repo, opts) {
2710 Ok(c) => c,
2711 Err(e) => {
2712 task.attempts += 1;
2716 task.fail(format!("config: {e:#}"), opts.max_attempts);
2717 record(queue, task);
2718 return Vec::new();
2719 }
2720 };
2721 apply_solo(&mut config, task);
2722 let p = phrases(&config.graph.language);
2723 let start_failed = p.could_not_start;
2724
2725 if let Some(reason) = disk_gate(&repo, &config) {
2733 task.last_error = Some(reason.clone());
2734 task.hold_machine(Some(reason.clone()));
2735 record(queue, task);
2736 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2737 notices::raise(
2740 Notice::warn(
2741 &format!("disk:{}", repo.display()),
2742 "A task was held for want of free disk space; free some, then release it from the queue.",
2743 )
2744 .link(Link::Task {
2745 id: task.id.clone(),
2746 }),
2747 );
2748 return Vec::new();
2749 }
2750
2751 let unfinished = (!task.fresh_start)
2771 .then(|| unfinished_run(&task.runs, task.short()))
2772 .flatten();
2773 let review_branch = task.review_branch.take();
2779 let branch_exists = match &review_branch {
2780 Some(branch) => crate::git::branch_exists(&repo, branch)
2781 .await
2782 .unwrap_or(false),
2783 None => false,
2784 };
2785 let starter = choose_starter(
2786 review_branch.as_deref(),
2787 branch_exists,
2788 unfinished.as_deref(),
2789 );
2790 let attachments = match task_attachments(queue, task) {
2795 Ok(a) => a,
2796 Err(e) => {
2797 task.attempts += 1;
2798 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2799 record(queue, task);
2800 return Vec::new();
2801 }
2802 };
2803 let started = match &starter {
2804 Starter::Review(branch) => {
2805 tracing::info!(
2806 "task {} reopens `{branch}` as a review-only pass",
2807 task.short()
2808 );
2809 let takeover = crate::handover::Takeover {
2812 earlier: task.earlier_attempts().to_vec(),
2813 home: crate::run::home(),
2814 choice: take_divergence_answer(branch, &config.merge.remote, task),
2815 };
2816 Runner::review_taking_over(
2817 &repo,
2818 branch,
2819 config,
2820 Some(takeover),
2821 crate::run::Origin::queue(&task.id),
2822 )
2823 .await
2824 }
2825 Starter::Resume(id) => {
2826 tracing::info!("resuming run {id} rather than competing again");
2827 Runner::resume(id).map(|mut r| {
2828 if let Some(instruction) =
2829 prepare_instruction(&starter, Some(&r.state.instruction), task)
2830 {
2831 r.state.instruction = instruction;
2832 }
2833 r.state.attachments = attachments.clone();
2834 r
2835 })
2836 }
2837 Starter::Start => {
2838 if let Some(branch) = &review_branch {
2839 tracing::warn!(
2840 "conductor chose review for task {} but branch `{branch}` no longer \
2841 exists; requeuing as a fresh competition instead",
2842 task.short()
2843 );
2844 }
2845 let instruction = prepare_instruction(&starter, None, task)
2846 .unwrap_or_else(|| task.instruction.clone());
2847 Runner::start_naming(
2848 &repo,
2849 instruction,
2850 &task.title,
2851 config,
2852 crate::run::Origin::queue(&task.id),
2853 )
2854 .await
2855 .map(|mut r| {
2856 r.state.attachments = attachments.clone();
2857 r
2858 })
2859 }
2860 };
2861 let mut runner = match started {
2862 Ok(r) => r,
2863 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2867 let detail = match e.downcast_ref::<crate::handover::Refused>() {
2868 Some(r) => (p.handover_refused)(r),
2869 None => format!("{e:#}"),
2870 };
2871 let reason = format!("{start_failed}{detail}");
2872 task.last_error = Some(reason.clone());
2873 let branch = match &starter {
2876 Starter::Review(branch) => Some(branch.clone()),
2877 _ => None,
2878 };
2879 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
2883 record(queue, task);
2884 tracing::warn!(
2885 "holding {} for a branch it cannot take over: {e:#}",
2886 task.short()
2887 );
2888 return Vec::new();
2889 }
2890 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
2895 let d = e
2896 .downcast_ref::<crate::reconcile::Diverged>()
2897 .expect("checked by the guard");
2898 let mut q = ask::Question::new(
2899 task.id.clone(),
2900 "review".to_owned(),
2901 "sync".to_owned(),
2902 d.summary(),
2903 d.detail(),
2904 d.choices(),
2905 );
2906 match Questions::open().put(&mut q) {
2907 Ok(()) => {
2908 task.last_error = Some(format!("{e:#}"));
2909 task.review_branch = Some(d.branch.clone());
2912 task.block(vec![q.id.clone()], Some(d.summary()));
2913 }
2914 Err(put) => {
2915 tracing::warn!("could not file the divergence question: {put:#}");
2916 task.attempts += 1;
2917 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2918 }
2919 }
2920 record(queue, task);
2921 return Vec::new();
2922 }
2923 Err(e) => {
2924 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
2930 && let Starter::Review(branch) = &starter
2931 {
2932 task.review_branch = Some(branch.clone());
2933 task.last_error = Some(format!("{start_failed}{e:#}"));
2934 task.status = crate::queue::TaskStatus::Failed;
2935 record(queue, task);
2936 return Vec::new();
2937 }
2938 task.attempts += 1;
2939 task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2940 record(queue, task);
2941 return Vec::new();
2942 }
2943 };
2944 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
2947 runner.on_pause(stop.pause());
2949 runner.watch_interrupt(interrupt_pause);
2953
2954 let run = runner.state.id.clone();
2957 task.start(run.clone());
2958 record(queue, task);
2959 lock(status).current.push(Current {
2960 task: task.id.clone(),
2961 run,
2962 });
2963
2964 let quota_before = runner.state.quota.clone();
2967 let detail = match runner.execute().await {
2968 Ok(()) => describe(&runner.state),
2969 Err(e) => format!("{e:#}"),
2970 };
2971 let fresh = losses_this_attempt("a_before, &runner.state.quota);
2972 let verdict = Verdict {
2973 status: runner.state.status,
2974 left_pr: runner.state.pr.is_some(),
2977 quota_hit: !fresh.is_empty(),
2983 parked: runner.state.parked,
2987 no_viable_candidates: runner.state.viable().is_empty(),
2990 };
2991 settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2992 if task.status == TaskStatus::Done {
2993 supersede_prior_runs(task, &crate::run::home());
2994 }
2995 record(queue, task);
2996 tracing::info!(
2997 "task {} is {} after run {} ({})",
2998 task.short(),
2999 task.status.as_str(),
3000 runner.state.short(),
3001 label(runner.state.status)
3002 );
3003 fresh
3004}
3005
3006fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3016 after
3017 .iter()
3018 .filter(|q| !before.contains(q))
3019 .cloned()
3020 .collect()
3021}
3022
3023fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3026 if quota.is_empty() {
3027 return None;
3028 }
3029 let with_hint = quota.iter().find(|q| q.reset.is_some());
3030 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3031 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3032 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3033 Some(
3034 now.checked_add(jiff::SignedDuration::from_secs(secs))
3035 .unwrap_or(Timestamp::MAX),
3036 )
3037}
3038
3039fn apply_solo(config: &mut Config, task: &Task) {
3049 if task.solo {
3050 config.graph.candidates = 1;
3051 }
3052}
3053
3054fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3056 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3057 if let Some(mode) = &opts.merge {
3058 config.merge.mode = merge_mode(mode)?;
3059 }
3060 Ok(config)
3061}
3062
3063async fn maybe_prune_cache_between_runs(
3094 repo: &Path,
3095 opts: &Opts,
3096 home: &Path,
3097 stop: &Stop,
3098 last_checked: &mut Option<Timestamp>,
3099 now: Timestamp,
3100) {
3101 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3102 return;
3103 }
3104 *last_checked = Some(now);
3105 let cfg = match prepare(repo, opts) {
3106 Ok(cfg) => cfg,
3107 Err(e) => {
3108 tracing::warn!("cache check: no config: {e:#}");
3109 return;
3110 }
3111 };
3112 match clean::prune_cache_if_over_limit(&cfg, home) {
3113 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3114 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3115 pruned.files,
3116 pruned.freed
3117 ),
3118 Ok(_) => {}
3119 Err(e) => {
3120 tracing::warn!("housekeep: prune cache: {e:#}");
3121 notices::raise_in(
3122 home,
3123 Notice::warn(
3124 "housekeep:cache",
3125 "Pruning the shared build cache failed; disk usage may keep growing.",
3126 ),
3127 );
3128 }
3129 }
3130}
3131
3132fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3136 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3137}
3138
3139async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3158 let cfg = match prepare(repo, opts) {
3159 Ok(cfg) => cfg,
3160 Err(e) => {
3161 tracing::warn!("housekeep: no config: {e:#}");
3162 return;
3163 }
3164 };
3165 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3174 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3175 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3180 let mut extra = Vec::new();
3181 if out.unreadable > 0 {
3182 extra.push(format!("{} unreadable", out.unreadable));
3183 }
3184 if out.orphaned_worktrees > 0 {
3185 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3186 }
3187 let detail = if extra.is_empty() {
3188 String::new()
3189 } else {
3190 format!(" ({})", extra.join(", "))
3191 };
3192 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3193 }
3194 if out.external_merges_recorded > 0 {
3195 tracing::info!(
3196 "housekeep: recorded {} run(s) as merged externally",
3197 out.external_merges_recorded
3198 );
3199 }
3200 if out.stale_pr_states_repaired > 0 {
3201 tracing::info!(
3202 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3203 out.stale_pr_states_repaired
3204 );
3205 }
3206 if out.cache_files > 0 {
3207 tracing::info!(
3208 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3209 out.cache_files,
3210 out.cache_freed
3211 );
3212 }
3213 if out.questions_abandoned > 0 {
3214 tracing::info!(
3215 "housekeep: abandoned {} question(s) left open by a finished run",
3216 out.questions_abandoned
3217 );
3218 }
3219}
3220
3221async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3230 let questions = Questions::at(home.join("questions"));
3231 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3232 if report.is_empty() {
3233 return;
3234 }
3235 if !report.quarantined.is_empty() {
3236 tracing::info!(
3237 "triage: held {} blocked task(s) whose blocked-on task or \
3238 question no longer exists: {}",
3239 report.quarantined.len(),
3240 report.quarantined.join(", ")
3241 );
3242 }
3243 if !report.resumed.is_empty() {
3244 tracing::info!(
3245 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3246 report.resumed.len(),
3247 report.resumed.join(", ")
3248 );
3249 }
3250 if !report.asked.is_empty() {
3251 tracing::info!(
3252 "triage: asked about {} held task(s): {}",
3253 report.asked.len(),
3254 report.asked.join(", ")
3255 );
3256 }
3257 if !report.answered.is_empty() {
3258 tracing::info!(
3259 "triage: applied {} operator answer(s): {}",
3260 report.answered.len(),
3261 report.answered.join(", ")
3262 );
3263 }
3264}
3265
3266fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3273 disk_gate_with(repo, config, crate::disk::free_bytes)
3274}
3275
3276fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3280 repo: &Path,
3281 config: &Config,
3282 free_bytes: F,
3283) -> Option<String> {
3284 let min = config.disk.min_free_bytes;
3285 if min == 0 {
3286 return None;
3287 }
3288 match free_bytes(repo) {
3289 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3290 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3291 }
3292}
3293
3294const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3301
3302const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3306
3307fn quota_wait(
3316 reset_at: Option<Timestamp>,
3317 now: Timestamp,
3318 fallback: Duration,
3319 cap: Duration,
3320) -> Duration {
3321 match reset_at {
3322 Some(at) if at > now => {
3323 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3324 Duration::from_secs(secs).min(cap)
3325 }
3326 _ => fallback,
3327 }
3328}
3329
3330fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3344 parse_reset_hint_zoned(text, now)
3345 .or_else(|| parse_reset_hint_dated(text))
3346 .or_else(|| parse_reset_hint_relative(text, recorded))
3347}
3348
3349fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3353 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3354 let mut rest = rest.trim();
3355 if rest.is_empty() {
3356 return None;
3357 }
3358 let mut total: i64 = 0;
3359 let mut matched = false;
3360 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3361 if let Some((digits, tail)) = rest.split_once(unit)
3362 && !digits.is_empty()
3363 && digits.bytes().all(|b| b.is_ascii_digit())
3364 {
3365 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3366 rest = tail;
3367 matched = true;
3368 }
3369 }
3370 if !rest.is_empty() || !matched {
3371 return None;
3372 }
3373 recorded
3374 .checked_add(jiff::SignedDuration::from_secs(total))
3375 .ok()
3376}
3377
3378fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3382 let clock = clock.trim().to_lowercase();
3383 let (digits, pm) = clock
3384 .strip_suffix("am")
3385 .map(|d| (d, false))
3386 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3387 let (h, m) = digits.trim().split_once(':')?;
3388 let mut hour: i8 = h.trim().parse().ok()?;
3389 let minute: i8 = m.trim().parse().ok()?;
3390 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3391 return None;
3392 }
3393 if pm && hour != 12 {
3394 hour += 12;
3395 } else if !pm && hour == 12 {
3396 hour = 0;
3397 }
3398 Some((hour, minute))
3399}
3400
3401fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3406 let open = text.find('(')?;
3407 let close = text.rfind(')')?;
3408 if close <= open {
3409 return None;
3410 }
3411 let zone = text[open + 1..close].trim();
3412 let (hour, minute) = parse_12h_clock(&text[..open])?;
3413 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3414 let candidate = now
3415 .to_zoned(tz)
3416 .with()
3417 .hour(hour)
3418 .minute(minute)
3419 .second(0)
3420 .millisecond(0)
3421 .microsecond(0)
3422 .nanosecond(0)
3423 .build()
3424 .ok()?;
3425 let mut at = candidate.timestamp();
3426 if at <= now {
3427 at += jiff::SignedDuration::from_hours(24);
3428 }
3429 Some(at)
3430}
3431
3432fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3441 let words: Vec<&str> = text.split_whitespace().collect();
3442 if words.len() < 5 {
3443 return None;
3444 }
3445 (0..=words.len() - 5)
3446 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3447}
3448
3449fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3455 if trailing.is_some_and(|next| next.starts_with('(')) {
3456 return None;
3457 }
3458 let month = month_number(window[0])?;
3459 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3460 let day_digits = ["st", "nd", "rd", "th"]
3461 .iter()
3462 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3463 let day: i8 = day_digits.parse().ok()?;
3464 let year_token = window[2];
3465 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3466 return None;
3467 }
3468 let year: i16 = year_token.parse().ok()?;
3469 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3473 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3474 let date = jiff::civil::Date::new(year, month, day).ok()?;
3475 let candidate = date
3476 .at(hour, minute, 0, 0)
3477 .to_zoned(jiff::tz::TimeZone::UTC)
3478 .ok()?;
3479 Some(candidate.timestamp())
3480}
3481
3482fn month_number(name: &str) -> Option<i8> {
3485 const NAMES: [&str; 12] = [
3486 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3487 ];
3488 let lower = name.to_lowercase();
3489 NAMES
3490 .iter()
3491 .position(|n| *n == lower.as_str())
3492 .map(|i| i as i8 + 1)
3493}
3494
3495fn exhausted_review_budget(state: &RunState) -> bool {
3507 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
3508}
3509
3510fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3547 unfinished_run_with(runs, short, RunState::load)
3548}
3549
3550fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3553where
3554 F: FnOnce(&str) -> Result<RunState>,
3555{
3556 let id = runs.last()?;
3557 match load(id) {
3558 Ok(s)
3563 if s.status.resumable()
3564 && !s.released()
3565 && !exhausted_review_budget(&s)
3566 && s.liveness(false) != crate::run::Liveness::Live =>
3567 {
3568 Some(id.clone())
3569 }
3570 Ok(_) => None,
3571 Err(e) => {
3572 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3573 None
3574 }
3575 }
3576}
3577
3578fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3586where
3587 F: FnOnce(&str) -> Result<RunState>,
3588{
3589 if task.status != TaskStatus::Failed || task.fresh_start || task.review_branch.is_some() {
3590 return false;
3591 }
3592 let Some(id) = task.runs.last() else {
3593 return false;
3594 };
3595 load(id).is_ok_and(|s| {
3596 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3597 })
3598}
3599
3600#[derive(Debug, Clone, PartialEq, Eq)]
3603enum Starter {
3604 Review(String),
3607 Resume(String),
3609 Start,
3611}
3612
3613fn take_divergence_answer(
3617 branch: &str,
3618 remote: &str,
3619 task: &mut Task,
3620) -> Option<crate::reconcile::Choice> {
3621 let summary = crate::reconcile::summary_for(branch, remote);
3622 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3623 (a.question == summary)
3624 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3625 .flatten()
3626 .map(|c| (i, c))
3627 })?;
3628 task.answers.remove(idx);
3629 Some(choice)
3630}
3631
3632fn choose_starter(
3644 review_branch: Option<&str>,
3645 branch_exists: bool,
3646 unfinished: Option<&str>,
3647) -> Starter {
3648 match review_branch {
3649 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3650 Some(_) => Starter::Start,
3651 None => match unfinished {
3652 Some(id) => Starter::Resume(id.to_owned()),
3653 None => Starter::Start,
3654 },
3655 }
3656}
3657
3658fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3661 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3662 return fallback.to_path_buf();
3663 }
3664 task.repo.clone()
3665}
3666
3667const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3671
3672fn answers_block(task: &Task, count: usize) -> String {
3674 let mut s = ANSWERS_HEADER.to_owned();
3675 for a in &task.answers[..count] {
3676 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3677 }
3678 s
3679}
3680
3681fn append_answers(base: &str, task: &Task) -> String {
3684 if task.answers.is_empty() {
3685 return base.to_owned();
3686 }
3687 let mut s = base.to_owned();
3688 s.push_str(&answers_block(task, task.answers.len()));
3689 s
3690}
3691
3692fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3696 for count in (1..=task.answers.len()).rev() {
3697 let block = answers_block(task, count);
3698 if let Some(base) = instruction.strip_suffix(&block) {
3699 return base;
3700 }
3701 }
3702 instruction
3703}
3704
3705fn instruction_for(task: &Task) -> String {
3713 append_answers(&task.instruction, task)
3714}
3715
3716fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3728 append_answers(strip_answers_block(old_instruction, task), task)
3729}
3730
3731fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
3733 let paths = queue.attachment_paths(task);
3734 for (name, path) in task.attachments.iter().zip(&paths) {
3735 if !path.is_file() {
3736 bail!(
3737 "attachment `{name}` is recorded on the task but {} is missing",
3738 path.display()
3739 );
3740 }
3741 }
3742 Ok(paths)
3743}
3744
3745fn prepare_instruction(
3756 starter: &Starter,
3757 old_instruction: Option<&str>,
3758 task: &Task,
3759) -> Option<String> {
3760 match starter {
3761 Starter::Start => Some(instruction_for(task)),
3762 Starter::Resume(_) => Some(resumed_instruction(
3763 old_instruction.expect("a resumed run always has a prior instruction"),
3764 task,
3765 )),
3766 Starter::Review(_) => None,
3767 }
3768}
3769
3770fn record(queue: &Queue, task: &mut Task) {
3774 if let Err(e) = queue.put(task) {
3775 tracing::error!("could not record task {}: {e:#}", task.short());
3776 notices::raise(Notice::error(
3777 "loop:record",
3778 "The loop could not save a task's state; check the disk.",
3779 ));
3780 }
3781}
3782
3783fn runnable(queue: &Queue) -> Vec<Task> {
3789 let mut tasks: Vec<Task> = queue
3790 .list()
3791 .into_iter()
3792 .filter(|t| t.status.runnable())
3793 .collect();
3794 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3795 tasks
3796}
3797
3798fn describe(state: &RunState) -> String {
3812 let p = phrases(&state.config.graph.language);
3813 let mut detail = if state.status == RunStatus::Stalled {
3814 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
3815 seats.sort_unstable();
3816 seats.dedup();
3817 if seats.is_empty() {
3818 p.quorum_lost.to_owned()
3819 } else {
3820 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
3821 }
3822 } else {
3823 format!("{}{}", p.run_ended, state.status.display_label())
3824 };
3825 if let Some(last) = state.events.last() {
3826 let unanswered = state
3830 .reviews
3831 .last()
3832 .filter(|r| {
3833 state.status == RunStatus::Blocked
3834 && last.node == "review"
3835 && r.incomplete()
3836 && r.blocking == 0
3837 && r.round == state.config.graph.review_rounds
3838 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
3839 })
3840 .map(|r| (r.expected - r.answered, r.round));
3841 match unanswered {
3842 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
3843 detail.push_str(&format!(
3844 " ({}: {})",
3845 last.node,
3846 (p.reviewers_never_answered)(missing, rounds)
3847 ));
3848 }
3849 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
3850 }
3851 }
3852 detail.push_str(&format!(" [run {}]", state.id));
3853 detail
3854}
3855
3856const DIAGNOSTIC_MAX: usize = 4_000;
3862
3863const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3868
3869fn diagnostic(state: &RunState) -> Option<String> {
3883 let mut parts: Vec<String> = Vec::new();
3884
3885 for o in state.gate.iter().filter(|o| !o.ok()) {
3887 parts.push(format!(
3888 "gate `{}` failed ({:?}):\n{}",
3889 o.command,
3890 o.code,
3891 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3892 ));
3893 }
3894
3895 if let Some(last) = state
3898 .events
3899 .iter()
3900 .rev()
3901 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3902 {
3903 parts.push(last.message.clone());
3904 }
3905
3906 if state.viable().is_empty() {
3913 for c in &state.candidates {
3914 if let Some(evidence) = &c.verified_noop {
3915 parts.push(format!(
3916 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3917 c.label
3918 ));
3919 } else if !c.summary.trim().is_empty() {
3920 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3921 } else if let Some(why) = &c.failed {
3922 parts.push(format!("candidate {}: {why}", c.label));
3923 }
3924 }
3925 }
3926
3927 if parts.is_empty() {
3928 return None;
3929 }
3930 Some(crate::run::tail(
3935 &parts.join("\n\n"),
3936 DIAGNOSTIC_MAX.saturating_sub(100),
3937 ))
3938}
3939
3940fn label(status: RunStatus) -> &'static str {
3948 status.as_str()
3949}
3950
3951fn merge_mode(mode: &str) -> Result<MergeMode> {
3953 match mode {
3954 "none" => Ok(MergeMode::None),
3955 "local" => Ok(MergeMode::Local),
3956 "pr" => Ok(MergeMode::Pr),
3957 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3958 }
3959}
3960
3961fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3966 mutex
3967 .lock()
3968 .unwrap_or_else(std::sync::PoisonError::into_inner)
3969}
3970
3971#[cfg(test)]
3972mod tests {
3973 use super::*;
3974 use crate::queue::{Source, TaskStatus};
3975 use crate::run::{Candidate, CommandOutcome};
3976 use pretty_assertions::assert_eq;
3977
3978 fn task() -> Task {
3979 Task::new(
3980 "add retries".to_owned(),
3981 "add retries".to_owned(),
3982 PathBuf::from("/repo"),
3983 Source::Human,
3984 )
3985 }
3986
3987 fn interrupt_task(id: &str) -> Task {
3990 let mut t = task();
3991 t.id = id.to_owned();
3992 t.interrupt = true;
3993 t
3994 }
3995
3996 fn task_with_id(id: &str) -> Task {
3998 let mut t = task();
3999 t.id = id.to_owned();
4000 t
4001 }
4002
4003 fn urgent_task(id: &str) -> Task {
4005 let mut t = task();
4006 t.id = id.to_owned();
4007 t.urgent = true;
4008 t
4009 }
4010
4011 #[test]
4016 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4017 assert_eq!(permit_kind(true, false), PermitKind::None);
4018 assert_eq!(permit_kind(true, true), PermitKind::None);
4019 }
4020
4021 #[test]
4026 fn permit_kind_separates_urgent_from_ordinary() {
4027 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4028 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4029 }
4030
4031 #[test]
4038 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4039 let cfg = Config::default();
4040 let repo = Path::new("/any/repo/path");
4041
4042 let reason =
4043 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4044 assert!(reason.contains("1024"), "{reason}");
4045 assert!(
4046 reason.contains(&cfg.disk.min_free_bytes.to_string()),
4047 "{reason}"
4048 );
4049
4050 assert_eq!(
4051 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4052 None,
4053 "exactly at the floor is open"
4054 );
4055 assert_eq!(
4056 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4057 None,
4058 "comfortably above the floor is open"
4059 );
4060 }
4061
4062 #[test]
4063 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4064 let mut cfg = Config::default();
4065 cfg.disk.min_free_bytes = 0;
4066 let repo = Path::new("/any/repo/path");
4067 assert_eq!(
4068 disk_gate_with(repo, &cfg, |_| Ok(0)),
4069 None,
4070 "a zero floor never measures at all"
4071 );
4072 }
4073
4074 #[test]
4075 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
4076 let cfg = Config::default();
4077 let repo = Path::new("/any/repo/path");
4078 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
4079 .expect("a measurement failure must close the gate, not open it");
4080 assert!(reason.contains("could not measure"), "{reason}");
4081 }
4082
4083 #[test]
4084 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
4085 let ordinary = task();
4086 let next = advance_interrupt(
4087 Interrupt::Idle,
4088 std::slice::from_ref(&ordinary.id),
4089 std::slice::from_ref(&ordinary),
4090 );
4091 assert_eq!(next, Interrupt::Idle);
4092 }
4093
4094 #[test]
4095 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
4096 let marked = interrupt_task("marked");
4099 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4100 assert_eq!(next, Interrupt::Idle);
4101 }
4102
4103 #[test]
4104 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
4105 let marked = interrupt_task("marked");
4106 let next = advance_interrupt(
4107 Interrupt::Idle,
4108 &["running".to_owned()],
4109 std::slice::from_ref(&marked),
4110 );
4111 assert_eq!(
4112 next,
4113 Interrupt::Parking {
4114 parked: vec!["running".to_owned()],
4115 interrupt_task: "marked".to_owned(),
4116 }
4117 );
4118 }
4119
4120 #[test]
4129 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
4130 let marked = interrupt_task("marked");
4131
4132 let two = advance_interrupt(
4133 Interrupt::Idle,
4134 &["a".to_owned(), "b".to_owned()],
4135 std::slice::from_ref(&marked),
4136 );
4137 assert_eq!(two, Interrupt::Idle);
4138
4139 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
4140 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
4141 }
4142
4143 #[test]
4144 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
4145 let state = Interrupt::Parking {
4146 parked: vec!["running".to_owned()],
4147 interrupt_task: "marked".to_owned(),
4148 };
4149 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
4151 assert_eq!(still_going, state);
4152
4153 let stopped_but_not_yet_dispatched =
4157 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
4158 assert_eq!(stopped_but_not_yet_dispatched, state);
4159
4160 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
4162 assert_eq!(
4163 dispatched,
4164 Interrupt::Running {
4165 parked: vec!["running".to_owned()],
4166 interrupt_task: "marked".to_owned(),
4167 }
4168 );
4169 }
4170
4171 #[test]
4172 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
4173 let state = Interrupt::Running {
4174 parked: vec!["running".to_owned()],
4175 interrupt_task: "marked".to_owned(),
4176 };
4177 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
4178 assert_eq!(still_running, state);
4179
4180 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
4187 assert_eq!(
4188 ended,
4189 Interrupt::Resuming {
4190 parked: vec!["running".to_owned()]
4191 }
4192 );
4193 }
4194
4195 #[test]
4196 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
4197 let state = Interrupt::Resuming {
4198 parked: vec!["running".to_owned()],
4199 };
4200 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
4201 assert_eq!(still_waiting, state);
4202
4203 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
4204 assert_eq!(dispatched, Interrupt::Idle);
4205 }
4206
4207 #[test]
4213 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
4214 {
4215 let state = Interrupt::Parking {
4216 parked: vec!["running".to_owned()],
4217 interrupt_task: "marked".to_owned(),
4218 };
4219 let next = advance_interrupt(state, &[], &[]);
4222 assert_eq!(
4223 next,
4224 Interrupt::Resuming {
4225 parked: vec!["running".to_owned()]
4226 },
4227 "abandoning the interrupt must not abandon the resume it owes"
4228 );
4229 }
4230
4231 #[test]
4234 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
4235 let state = Interrupt::Resuming {
4236 parked: vec!["running".to_owned()],
4237 };
4238 let next = advance_interrupt(state, &[], &[]);
4239 assert_eq!(
4240 next,
4241 Interrupt::Idle,
4242 "nothing is left to wait for; the loop must not stay wedged"
4243 );
4244 }
4245
4246 #[test]
4247 fn disabled_by_config_the_sequence_can_never_leave_idle() {
4248 let marked = interrupt_task("marked");
4249 let next = advance_interrupt_tick(
4250 false,
4251 Interrupt::Idle,
4252 &["running".to_owned()],
4253 std::slice::from_ref(&marked),
4254 );
4255 assert_eq!(
4256 next,
4257 Interrupt::Idle,
4258 "an unmarked, unconfigured daemon must behave exactly as before"
4259 );
4260 }
4261
4262 #[test]
4263 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
4264 let state = Interrupt::Parking {
4265 parked: vec!["running".to_owned()],
4266 interrupt_task: "marked".to_owned(),
4267 };
4268 let candidates = vec![interrupt_task("marked"), task()];
4269 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4270 assert!(
4271 allowed.is_empty(),
4272 "nothing may dispatch - not even the interrupt task itself - \
4273 until the parked run has actually stopped"
4274 );
4275 }
4276
4277 #[test]
4291 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
4292 for state in [
4293 Interrupt::Parking {
4294 parked: vec!["running".to_owned()],
4295 interrupt_task: "marked".to_owned(),
4296 },
4297 Interrupt::Running {
4298 parked: vec!["running".to_owned()],
4299 interrupt_task: "marked".to_owned(),
4300 },
4301 Interrupt::Resuming {
4302 parked: vec!["running".to_owned()],
4303 },
4304 ] {
4305 let candidates = vec![
4306 interrupt_task("marked"),
4307 urgent_task("hot"),
4308 task_with_id("ordinary"),
4309 ];
4310 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
4311 assert!(
4312 !allowed.iter().any(|t| t.id == "hot"),
4313 "an urgent candidate must wait out the same gate as anything \
4314 else while the run it would run alongside has not actually \
4315 left flight, for state {state:?}: {allowed:?}"
4316 );
4317 }
4318 }
4319
4320 #[test]
4326 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
4327 let state = Interrupt::Resuming {
4328 parked: vec!["hot".to_owned()],
4329 };
4330 let candidates = vec![urgent_task("hot"), task()];
4331 let allowed = interrupt_gate(&state, &[], candidates);
4332 assert_eq!(
4333 allowed.iter().filter(|t| t.id == "hot").count(),
4334 1,
4335 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
4336 );
4337 }
4338
4339 #[test]
4340 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
4341 let state = Interrupt::Parking {
4342 parked: vec!["running".to_owned()],
4343 interrupt_task: "marked".to_owned(),
4344 };
4345 let other = task();
4346 let candidates = vec![interrupt_task("marked"), other.clone()];
4347 let allowed = interrupt_gate(&state, &[], candidates);
4348 assert_eq!(allowed.len(), 1);
4349 assert_eq!(allowed[0].id, "marked");
4350 }
4351
4352 #[test]
4353 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4354 let state = Interrupt::Running {
4355 parked: vec!["running".to_owned()],
4356 interrupt_task: "marked".to_owned(),
4357 };
4358 let candidates = vec![task(), task()];
4359 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4360 assert!(allowed.is_empty());
4361 }
4362
4363 #[test]
4370 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4371 let state = Interrupt::Resuming {
4372 parked: vec!["a".to_owned(), "c".to_owned()],
4373 };
4374 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4375 let allowed = interrupt_gate(&state, &[], candidates);
4376 assert_eq!(
4377 allowed.len(),
4378 1,
4379 "at most one candidate may be offered while resuming: {allowed:?}"
4380 );
4381 assert_eq!(allowed[0].id, "a");
4382 }
4383
4384 #[test]
4385 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4386 let state = Interrupt::Resuming {
4387 parked: vec!["a".to_owned()],
4388 };
4389 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4390 assert!(allowed.is_empty());
4391 }
4392
4393 #[test]
4399 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4400 let running = task(); let marked = interrupt_task("marked");
4402
4403 let mut state = Interrupt::Idle;
4404 let in_flight = vec![running.id.clone()];
4406 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4407 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4408 assert!(gated.is_empty(), "still waiting on `running` to park");
4409
4410 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4412 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4413 assert_eq!(
4414 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4415 vec!["marked"],
4416 "only the interrupt task may be offered to the dispatcher now"
4417 );
4418
4419 state = advance_interrupt_tick(
4421 true,
4422 state,
4423 &["marked".to_owned()],
4424 std::slice::from_ref(&running),
4425 );
4426 let gated = interrupt_gate(
4427 &state,
4428 &["marked".to_owned()],
4429 vec![marked.clone(), running.clone()],
4430 );
4431 assert!(
4432 gated.is_empty(),
4433 "the parked run must not be offered back while the interrupt \
4434 task is still running"
4435 );
4436
4437 let other = task_with_id("other");
4441 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4442 assert_eq!(
4443 state,
4444 Interrupt::Resuming {
4445 parked: vec![running.id.clone()]
4446 }
4447 );
4448 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4449 assert_eq!(
4450 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4451 vec![running.id.as_str()],
4452 "exactly the parked run resumes - not the unrelated task, even \
4453 though it was offered first"
4454 );
4455
4456 state = advance_interrupt_tick(
4460 true,
4461 state,
4462 std::slice::from_ref(&running.id),
4463 std::slice::from_ref(&other),
4464 );
4465 assert_eq!(state, Interrupt::Idle);
4466 let gated = interrupt_gate(
4467 &state,
4468 std::slice::from_ref(&running.id),
4469 vec![other.clone()],
4470 );
4471 assert_eq!(
4472 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4473 vec![other.id.as_str()],
4474 "ordinary dispatch is unrestricted again"
4475 );
4476 }
4477
4478 #[test]
4479 fn every_run_status_settles_the_task_it_came_from() {
4480 let table = [
4482 (RunStatus::Merged, TaskStatus::Done, 1),
4483 (RunStatus::Ready, TaskStatus::Done, 1),
4484 (RunStatus::Stalled, TaskStatus::Failed, 0),
4485 (RunStatus::Blocked, TaskStatus::Failed, 1),
4486 (RunStatus::Failed, TaskStatus::Failed, 1),
4487 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4488 (RunStatus::Prep, TaskStatus::Failed, 1),
4489 (RunStatus::Implementing, TaskStatus::Failed, 1),
4490 (RunStatus::Judging, TaskStatus::Failed, 1),
4491 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4492 (RunStatus::Voting, TaskStatus::Failed, 1),
4493 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4494 (RunStatus::Gating, TaskStatus::Failed, 1),
4495 ];
4496 for (run, want, attempts) in table {
4497 let mut t = task();
4498 t.start("20260902-000000-aaaa".to_owned());
4499 settle(
4500 &mut t,
4501 Verdict {
4502 status: run,
4503 left_pr: false,
4504 parked: false,
4505 quota_hit: matches!(run, RunStatus::Stalled),
4506 no_viable_candidates: false,
4507 },
4508 "why",
4509 2,
4510 );
4511 assert_eq!(t.status, want, "task status after {}", label(run));
4512 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4513 }
4514 }
4515
4516 #[test]
4517 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4518 let mut stalled = task();
4519 stalled.start("20260902-000000-aaaa".to_owned());
4520 settle(
4521 &mut stalled,
4522 Verdict {
4523 status: RunStatus::Stalled,
4524 left_pr: false,
4525 parked: false,
4526 quota_hit: true,
4527 no_viable_candidates: false,
4528 },
4529 "quota",
4530 1,
4531 );
4532 assert_eq!(stalled.attempts, 0);
4533 assert!(
4534 stalled.status.runnable(),
4535 "a machine problem must leave the task in line"
4536 );
4537
4538 let mut blocked = task();
4539 blocked.start("20260902-000000-aaaa".to_owned());
4540 settle(
4541 &mut blocked,
4542 Verdict {
4543 status: RunStatus::Blocked,
4544 left_pr: false,
4545 parked: false,
4546 quota_hit: false,
4547 no_viable_candidates: false,
4548 },
4549 "findings open",
4550 1,
4551 );
4552 assert_eq!(blocked.attempts, 1);
4553 assert_eq!(
4554 blocked.status,
4555 TaskStatus::Held,
4556 "the last attempt hands the task to a human"
4557 );
4558 }
4559
4560 #[test]
4561 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4562 let mut delivered = task();
4565 delivered.start("20260903-080619-01c2".to_owned());
4566 settle(
4567 &mut delivered,
4568 Verdict {
4569 status: RunStatus::Blocked,
4570 left_pr: true,
4571 parked: false,
4572 quota_hit: false,
4573 no_viable_candidates: false,
4574 },
4575 "no check status",
4576 4,
4577 );
4578 assert_eq!(
4579 delivered.status,
4580 TaskStatus::Held,
4581 "a pull request waiting on CI or a person is not a retryable failure"
4582 );
4583 assert!(
4584 !delivered.status.runnable(),
4585 "the loop must not pick this task up again"
4586 );
4587 assert_eq!(
4588 delivered.last_error.as_deref(),
4589 Some("no check status"),
4590 "the operator needs to be told what the gate was waiting for"
4591 );
4592
4593 let mut empty_handed = task();
4596 empty_handed.start("20260903-080619-01c2".to_owned());
4597 settle(
4598 &mut empty_handed,
4599 Verdict {
4600 status: RunStatus::Blocked,
4601 left_pr: false,
4602 parked: false,
4603 quota_hit: false,
4604 no_viable_candidates: false,
4605 },
4606 "findings open",
4607 4,
4608 );
4609 assert_eq!(empty_handed.status, TaskStatus::Failed);
4610 assert!(empty_handed.status.runnable());
4611 }
4612
4613 #[test]
4614 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4615 let mut noop = task();
4621 noop.start("20260912-131304-391f".to_owned());
4622 settle(
4623 &mut noop,
4624 Verdict {
4625 status: RunStatus::VerifiedNoop,
4626 left_pr: false,
4627 parked: false,
4628 quota_hit: false,
4629 no_viable_candidates: true,
4630 },
4631 "candidate A: already fixed by b32cfc4, on main",
4632 4,
4633 );
4634 assert_eq!(
4635 noop.status,
4636 TaskStatus::Held,
4637 "an unverified claim is a request for a human, not a failure"
4638 );
4639 assert!(
4640 !noop.status.runnable(),
4641 "the loop must not requeue this on the same unverified claim"
4642 );
4643 assert_eq!(noop.attempts, 1);
4648 }
4649
4650 #[test]
4651 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4652 let mut parked = task();
4657 parked.start("20260903-183634-2d98".to_owned());
4658 settle(
4659 &mut parked,
4660 Verdict {
4661 status: RunStatus::Implementing,
4662 left_pr: false,
4663 quota_hit: false,
4664 parked: true,
4665 no_viable_candidates: false,
4666 },
4667 "parked after `implementing`",
4668 2,
4669 );
4670 assert_eq!(parked.attempts, 0, "a park is refunded");
4671 assert!(
4672 parked.status.runnable(),
4673 "and the task stays in line so the next loop resumes its run"
4674 );
4675 assert_eq!(
4676 parked.last_error.as_deref(),
4677 Some("parked after `implementing`"),
4678 "the card says where it stopped"
4679 );
4680
4681 let mut broken = task();
4685 broken.start("20260903-183634-2d98".to_owned());
4686 settle(
4687 &mut broken,
4688 Verdict {
4689 status: RunStatus::Implementing,
4690 left_pr: false,
4691 quota_hit: false,
4692 parked: false,
4693 no_viable_candidates: false,
4694 },
4695 "returned mid-flight",
4696 2,
4697 );
4698 assert_eq!(broken.attempts, 1);
4699 }
4700
4701 #[test]
4702 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4703 let mut flaky = task();
4708 flaky.start("20260903-123023-e633".to_owned());
4709 settle(
4710 &mut flaky,
4711 Verdict {
4712 status: RunStatus::Stalled,
4713 left_pr: false,
4714 parked: false,
4715 quota_hit: false,
4716 no_viable_candidates: false,
4717 },
4718 "verdict rests on 1 of 3 judges",
4719 2,
4720 );
4721 assert_eq!(
4722 flaky.attempts, 1,
4723 "flakiness spends an attempt, so `max_attempts` still bounds it"
4724 );
4725 assert!(flaky.status.runnable(), "and it is still worth retrying");
4726
4727 let mut limited = task();
4729 limited.start("20260903-123023-e633".to_owned());
4730 settle(
4731 &mut limited,
4732 Verdict {
4733 status: RunStatus::Stalled,
4734 left_pr: false,
4735 parked: false,
4736 quota_hit: true,
4737 no_viable_candidates: false,
4738 },
4739 "judge-2, judge-3 out of quota",
4740 2,
4741 );
4742 assert_eq!(limited.attempts, 0, "a quota window is refunded");
4743 assert!(limited.status.runnable());
4744
4745 let mut worn = task();
4748 for _ in 0..2 {
4749 worn.release();
4750 }
4751 worn.start("20260903-123023-e633".to_owned());
4752 worn.attempts = 2;
4753 settle(
4754 &mut worn,
4755 Verdict {
4756 status: RunStatus::Stalled,
4757 left_pr: false,
4758 parked: false,
4759 quota_hit: false,
4760 no_viable_candidates: false,
4761 },
4762 "no quorum again",
4763 2,
4764 );
4765 assert_eq!(worn.status, TaskStatus::Held);
4766 assert!(!worn.status.runnable());
4767 }
4768
4769 #[test]
4770 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4771 let mut wiped_out = task();
4778 wiped_out.start("20260907-025000-a1b2".to_owned());
4779 settle(
4780 &mut wiped_out,
4781 Verdict {
4782 status: RunStatus::Failed,
4783 left_pr: false,
4784 parked: false,
4785 quota_hit: true,
4786 no_viable_candidates: true,
4787 },
4788 "no candidate produced a change; nothing to judge",
4789 2,
4790 );
4791 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4792 assert!(
4793 wiped_out.status.runnable(),
4794 "a machine problem must leave the task in line"
4795 );
4796
4797 let mut partial_progress = task();
4803 partial_progress.start("20260907-025500-c3d4".to_owned());
4804 settle(
4805 &mut partial_progress,
4806 Verdict {
4807 status: RunStatus::Failed,
4808 left_pr: false,
4809 parked: false,
4810 quota_hit: true,
4811 no_viable_candidates: false,
4812 },
4813 "gate failed on the winning candidate",
4814 2,
4815 );
4816 assert_eq!(
4817 partial_progress.attempts, 1,
4818 "a candidate that actually produced a change spends the attempt \
4819 even though some other seat hit its quota"
4820 );
4821 assert!(partial_progress.status.runnable());
4822 }
4823
4824 #[test]
4825 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
4826 let mut t = task();
4832 t.start("20260907-025000-a1b2".to_owned());
4833 let mut state = run_state(RunStatus::Failed);
4834 state.quota.push(QuotaLoss {
4835 seat: "cand-a".to_owned(),
4836 node: "implement".to_owned(),
4837 at: Timestamp::now(),
4838 reset: None,
4839 });
4840 assert!(
4841 state.viable().is_empty(),
4842 "no candidate was added, so nothing is viable"
4843 );
4844 reclaim(&mut t, Some(state), 2, "en");
4845 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
4846 assert!(t.status.runnable());
4847 }
4848
4849 #[test]
4850 fn a_held_task_is_never_offered_to_the_loop() {
4851 let dir = tempfile::tempdir().unwrap();
4852 let queue = Queue::at(dir.path().to_path_buf());
4853 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4854 let mut t = task();
4855 t.id = format!("2026090{n}-000000-000{n}");
4856 t.priority = priority;
4857 queue.put(&mut t).unwrap();
4858 }
4859 let mut held = task();
4860 held.id = "20260909-000000-9999".to_owned();
4861 held.priority = 99;
4862 held.hold_machine(None);
4863 queue.put(&mut held).unwrap();
4864
4865 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4866 assert_eq!(order.len(), 3);
4867 assert!(!order.contains(&held.id));
4868 assert_eq!(
4869 order.first().cloned(),
4870 queue.next_runnable().map(|t| t.id),
4871 "the loop's first candidate is exactly what the queue offers"
4872 );
4873 assert_eq!(
4874 order,
4875 vec![
4876 "20260902-000000-0002".to_owned(),
4877 "20260903-000000-0003".to_owned(),
4878 "20260901-000000-0001".to_owned(),
4879 ],
4880 "priority first, then oldest, so nothing starves"
4881 );
4882 }
4883
4884 #[test]
4885 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4886 let dir = tempfile::tempdir().unwrap();
4887 let queue = Queue::at(dir.path().to_path_buf());
4888 let mut old = task();
4889 old.id = "20260101-000000-old0".to_owned();
4890 queue.put(&mut old).unwrap();
4891 let mut fresh = task();
4892 fresh.id = "20260101-000000-new0".to_owned();
4893 queue.put(&mut fresh).unwrap();
4894
4895 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4899 std::thread::sleep(Duration::from_millis(60));
4900 let live = queue.claim(&fresh.id).unwrap();
4901
4902 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4903 assert_eq!(swept, vec![old.id.clone()]);
4904 assert!(
4905 queue.claim(&old.id).is_ok(),
4906 "an unparseable lock older than the threshold is swept"
4907 );
4908 assert!(
4909 queue.claim(&fresh.id).is_err(),
4910 "a live pid protects its lock regardless of age"
4911 );
4912 drop(live);
4913 }
4914
4915 #[test]
4916 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4917 let dir = tempfile::tempdir().unwrap();
4927 let queue = Queue::at(dir.path().to_path_buf());
4928 let mut t = task();
4929 t.id = "20260101-000000-live".to_owned();
4930 queue.put(&mut t).unwrap();
4931
4932 let claim = queue.claim(&t.id).unwrap();
4933 std::thread::sleep(Duration::from_millis(60));
4934
4935 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4936 assert!(
4937 swept.is_empty(),
4938 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4939 );
4940 assert!(
4941 queue.claim(&t.id).is_err(),
4942 "the lock still protects its task"
4943 );
4944 drop(claim);
4945 }
4946
4947 fn injected_dead_pid() -> u32 {
4950 std::process::id().checked_add(1).unwrap_or(1)
4951 }
4952
4953 #[test]
4954 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4955 let dir = tempfile::tempdir().unwrap();
4956 let queue = Queue::at(dir.path().to_path_buf());
4957 let mut t = task();
4958 t.id = "20260101-000000-dead".to_owned();
4959 queue.put(&mut t).unwrap();
4960 let dead_pid = injected_dead_pid();
4961
4962 std::fs::write(
4967 dir.path().join(format!("{}.lock", t.id)),
4968 dead_pid.to_string(),
4969 )
4970 .unwrap();
4971
4972 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4973 pid != dead_pid
4974 });
4975 assert_eq!(
4976 swept,
4977 vec![t.id.clone()],
4978 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4979 );
4980 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4981 }
4982
4983 #[test]
4984 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4985 let dir = tempfile::tempdir().unwrap();
4986 let queue = Queue::at(dir.path().to_path_buf());
4987 let mut t = task();
4988 t.id = "20260101-000000-late".to_owned();
4989 queue.put(&mut t).unwrap();
4990 let dead_pid = injected_dead_pid();
4991
4992 assert!(
4995 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4996 "nothing has claimed the task yet"
4997 );
4998
4999 std::fs::write(
5002 dir.path().join(format!("{}.lock", t.id)),
5003 dead_pid.to_string(),
5004 )
5005 .unwrap();
5006
5007 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5011 pid != dead_pid
5012 });
5013 assert_eq!(swept, vec![t.id.clone()]);
5014 }
5015
5016 #[test]
5017 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5018 crate::run::pin_test_home();
5023 let dir = tempfile::tempdir().unwrap();
5024 let queue = Queue::at(dir.path().to_path_buf());
5025 let mut t = task();
5026 t.id = "20260101-000000-crsh".to_owned();
5027 t.status = TaskStatus::Running;
5028 t.attempts = 1;
5029 t.runs.push("20260904-000000-4043".to_owned());
5033 queue.put(&mut t).unwrap();
5034 let dead_pid = injected_dead_pid();
5035
5036 std::fs::write(
5039 dir.path().join(format!("{}.lock", t.id)),
5040 dead_pid.to_string(),
5041 )
5042 .unwrap();
5043
5044 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5050 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5051
5052 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5053 pid != dead_pid
5054 });
5055 assert_eq!(swept, vec![t.id.clone()]);
5056
5057 let reclaimed = reclaim_orphaned_running(&queue, 2);
5058 assert_eq!(reclaimed, vec![t.id.clone()]);
5059 let after = queue.get(&t.id).unwrap();
5060 assert_eq!(
5061 after.status,
5062 TaskStatus::Held,
5063 "no run.json to recover from, so a human is asked"
5064 );
5065 assert_eq!(
5066 after.runs,
5067 vec!["20260904-000000-4043".to_owned()],
5068 "the crashed run's id is kept as evidence, not discarded"
5069 );
5070 }
5071
5072 #[test]
5073 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
5074 let dir = tempfile::tempdir().unwrap();
5075 let queue = Queue::at(dir.path().to_path_buf());
5076 let mut t = task();
5077 t.id = "20260101-000000-unknown".to_owned();
5078 queue.put(&mut t).unwrap();
5079 let dead_pid = injected_dead_pid();
5080 std::fs::write(
5081 dir.path().join(format!("{}.lock", t.id)),
5082 dead_pid.to_string(),
5083 )
5084 .unwrap();
5085
5086 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
5087 assert!(swept.is_empty(), "an unknown pid must keep its lock");
5088 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
5089 }
5090
5091 fn run_state_in(status: RunStatus, language: &str) -> RunState {
5092 let mut s = run_state(status);
5093 s.config.graph.language = language.to_owned();
5094 s
5095 }
5096
5097 fn unstarted_verdict(status: RunStatus) -> Verdict {
5098 Verdict {
5099 status,
5100 left_pr: false,
5101 quota_hit: false,
5102 parked: false,
5103 no_viable_candidates: false,
5104 }
5105 }
5106
5107 #[test]
5108 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
5109 let mut t = task();
5110 t.attempts = 1;
5111 settle_in(
5112 &mut t,
5113 unstarted_verdict(RunStatus::AlreadyInBase),
5114 "already in main",
5115 1,
5116 phrases("en"),
5117 );
5118 assert_eq!(t.status, TaskStatus::Done);
5119 assert_eq!(t.attempts, 0);
5120 }
5121
5122 #[test]
5123 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
5124 let reason = |language: &str| {
5125 let mut t = task();
5126 settle_in(
5127 &mut t,
5128 unstarted_verdict(RunStatus::Judging),
5129 "boom",
5130 1,
5131 phrases(language),
5132 );
5133 t.last_error.or(t.hold_reason).unwrap_or_default()
5134 };
5135 assert!(
5136 reason("en").starts_with("the graph stopped at `"),
5137 "{}",
5138 reason("en")
5139 );
5140 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
5141 assert!(reason("日本語").contains("boom"));
5142 assert_eq!(reason("fr"), reason("en"));
5143 }
5144
5145 #[test]
5146 fn describe_follows_the_run_language_and_keeps_the_run_id() {
5147 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
5148 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
5149 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
5150 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
5151 assert!(ja.contains("[run "), "{ja}");
5152 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
5153 assert!(ended.starts_with("run 終了: "), "{ended}");
5154 let mut de = run_state_in(RunStatus::Failed, "de");
5155 let mut en = run_state_in(RunStatus::Failed, "en");
5156 de.id = "same".to_owned();
5157 en.id = "same".to_owned();
5158 assert_eq!(describe(&de), describe(&en));
5159 }
5160
5161 #[test]
5162 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
5163 use crate::handover::Refused;
5164 let cases = [
5165 Refused::Foreign {
5166 branch: "b".into(),
5167 path: "/w/x".into(),
5168 why: "made by hand".into(),
5169 },
5170 Refused::Unsafe {
5171 branch: "b".into(),
5172 path: "/w/x".into(),
5173 why: "its worktree has uncommitted changes (a.rs)".into(),
5174 },
5175 Refused::ReleaseFailed {
5176 branch: "b".into(),
5177 path: "/w/x".into(),
5178 run: "ab12".into(),
5179 },
5180 ];
5181 for r in &cases {
5182 let en = (phrases("en").handover_refused)(r);
5183 assert_eq!(en, r.to_string());
5184 let ja = (phrases("ja").handover_refused)(r);
5185 assert!(
5186 !ja.contains("is checked out") && !ja.contains("try again"),
5187 "{ja}"
5188 );
5189 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
5190 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
5191 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
5192 }
5193 }
5194 assert!(phrases("en").handover_hint.contains("release the task"));
5195 assert!(phrases("ja").handover_hint.contains("解放"));
5196 }
5197
5198 #[test]
5199 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
5200 let build = |lang: &str| {
5201 let mut s = run_state_in(RunStatus::Blocked, lang);
5202 s.id = "same".to_owned();
5203 s.config.graph.review_rounds = 3;
5204 let mut r = review_round(3);
5205 r.expected = 3;
5206 r.answered = 1;
5207 s.reviews.push(r);
5208 s.event(
5209 "review",
5210 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
5211 );
5212 s
5213 };
5214 let en = describe(&build("en"));
5215 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
5216 let ja = describe(&build("ja"));
5217 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
5218 assert!(!ja.contains("never answered"), "{ja}");
5219 assert!(ja.contains("[run "), "{ja}");
5220
5221 let mut failed = build("ja");
5224 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
5225 command: "cargo test".to_owned(),
5226 code: Some(1),
5227 output_tail: String::new(),
5228 duration_ms: 0,
5229 resource_blocked: false,
5230 });
5231 failed.event("review", "stopped; e2e failed: cargo test");
5232 let ja = describe(&failed);
5233 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
5234 assert!(!ja.contains("席のレビュアー"), "{ja}");
5235 }
5236
5237 #[test]
5238 fn refusals_and_recovery_prose_follow_the_language() {
5239 let t = held_task_with("r1");
5240 let q = action_question(
5241 "r1",
5242 ask::ChoiceAction::Resume {
5243 run: "r1".to_owned(),
5244 },
5245 );
5246 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
5247 ActionDecision::Refuse(s) => s,
5248 other => panic!("{other:?}"),
5249 };
5250 assert!(refuse(phrases("en")).contains("could not be read: gone"));
5251 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
5252 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
5253
5254 let mut held = task();
5255 reclaim(&mut held, None, 2, "ja");
5256 assert!(held.hold_reason.unwrap().contains("保留にしました"));
5257 let mut held = task();
5258 reclaim(&mut held, None, 2, "xx");
5259 assert!(held.hold_reason.unwrap().contains("held for a human"));
5260 }
5261
5262 fn run_state(status: RunStatus) -> RunState {
5263 let mut state = RunState::new(
5264 PathBuf::from("/repo"),
5265 "main".to_owned(),
5266 "abc1234def".to_owned(),
5267 "add retries".to_owned(),
5268 Config::default(),
5269 );
5270 state.status = status;
5271 state
5272 }
5273
5274 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
5275 Candidate {
5276 index: 0,
5277 label,
5278 agent: "claude".to_owned(),
5279 branch: format!("magi/x/{label}"),
5280 worktree: PathBuf::from("/repo"),
5281 summary: summary.to_owned(),
5282 stat: String::new(),
5283 files: 0,
5284 commits: usize::from(!empty),
5285 empty,
5286 failed: failed.map(str::to_owned),
5287 verified_noop: None,
5288 duration_ms: 0,
5289 folded: false,
5290 }
5291 }
5292
5293 #[test]
5294 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
5295 let mut state = run_state(RunStatus::Blocked);
5296 state.gate = vec![
5297 CommandOutcome {
5298 command: "cargo make check".to_owned(),
5299 code: Some(0),
5300 output_tail: "ok".to_owned(),
5301 duration_ms: 0,
5302 resource_blocked: false,
5303 },
5304 CommandOutcome {
5305 command: "cargo test".to_owned(),
5306 code: Some(101),
5307 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
5308 duration_ms: 0,
5309 resource_blocked: false,
5310 },
5311 ];
5312 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
5313 assert!(d.contains("cargo test"), "{d}");
5314 assert!(
5315 !d.contains("cargo make check"),
5316 "a passing check is not a diagnostic: {d}"
5317 );
5318 assert!(d.contains("assertion failed"), "{d}");
5319 }
5320
5321 #[test]
5322 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
5323 let mut state = run_state(RunStatus::Blocked);
5324 state.event(
5325 "land",
5326 "stopped: the fixer produced no commit while 2 check(s) were failing \
5327 (build, lint); stopping instead of looping on an unchanged tree",
5328 );
5329 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
5330 assert!(d.contains("build"), "{d}");
5331 assert!(d.contains("lint"), "{d}");
5332 assert!(d.contains("fixer produced no commit"), "{d}");
5333 }
5334
5335 #[test]
5336 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
5337 let state = run_state(RunStatus::VerifiedNoop);
5342 let d = describe(&state);
5343 assert!(
5344 d.contains("agent-verified no-op"),
5345 "expected the display label, not the wire spelling: {d}"
5346 );
5347 assert!(!d.contains("verified_noop"), "{d}");
5348 }
5349
5350 #[test]
5351 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
5352 let mut state = run_state(RunStatus::Failed);
5358 state.candidates = vec![candidate(
5359 'A',
5360 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
5361 true,
5362 None,
5363 )];
5364 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
5365 assert!(d.contains("candidate A"), "{d}");
5366 assert!(d.contains("tagged v1.2.3"), "{d}");
5367 }
5368
5369 #[test]
5370 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
5371 let mut state = run_state(RunStatus::Failed);
5372 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
5373 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
5374 assert!(d.contains("candidate A"), "{d}");
5375 assert!(d.contains("agent timed out"), "{d}");
5376 }
5377
5378 #[test]
5379 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
5380 let mut state = run_state(RunStatus::Failed);
5383 state.candidates = vec![candidate('A', "did the work", false, None)];
5384 assert!(diagnostic(&state).is_none());
5385 }
5386
5387 #[test]
5388 fn diagnostic_is_bounded_however_much_a_run_printed() {
5389 let mut state = run_state(RunStatus::Blocked);
5390 state.gate = vec![
5391 CommandOutcome {
5392 command: "cargo test".to_owned(),
5393 code: Some(101),
5394 output_tail: "x".repeat(50_000),
5395 duration_ms: 0,
5396 resource_blocked: false,
5397 },
5398 CommandOutcome {
5399 command: "cargo clippy".to_owned(),
5400 code: Some(1),
5401 output_tail: "y".repeat(50_000),
5402 duration_ms: 0,
5403 resource_blocked: false,
5404 },
5405 ];
5406 state.candidates = vec![
5407 candidate('A', &"z".repeat(50_000), true, None),
5408 candidate('B', &"w".repeat(50_000), true, None),
5409 ];
5410 let d = diagnostic(&state).expect("plenty here to diagnose");
5411 assert!(
5412 d.len() <= DIAGNOSTIC_MAX,
5413 "diagnostic grew to {} bytes, unbounded",
5414 d.len()
5415 );
5416 }
5417
5418 #[test]
5419 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
5420 let mut state = run_state(RunStatus::Blocked);
5421 state.gate = vec![CommandOutcome {
5422 command: "cargo test".to_owned(),
5423 code: Some(101),
5424 output_tail: "assertion failed".to_owned(),
5425 duration_ms: 0,
5426 resource_blocked: false,
5427 }];
5428 let verdict = Verdict {
5429 status: RunStatus::Blocked,
5430 left_pr: false,
5431 quota_hit: false,
5432 parked: false,
5433 no_viable_candidates: false,
5434 };
5435
5436 let mut t = task();
5439 t.start("run-1".to_owned());
5440 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5441 assert_eq!(t.status, TaskStatus::Failed);
5442 assert!(t.diagnostic.is_none());
5443
5444 t.start("run-2".to_owned());
5447 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
5448 assert_eq!(t.status, TaskStatus::Held);
5449 let d = t.diagnostic.expect("a held task must carry its diagnostic");
5450 assert!(d.contains("cargo test"), "{d}");
5451 }
5452
5453 #[test]
5454 fn a_held_task_names_the_open_question_it_is_waiting_on() {
5455 crate::run::pin_test_home();
5460 let home = crate::run::home();
5461 let state = run_state(RunStatus::VerifiedNoop);
5462 let mut q = ask::Question::new(
5463 state.id.clone(),
5464 "implement".to_owned(),
5465 "impl-A".to_owned(),
5466 "is this really a no-op?".to_owned(),
5467 String::new(),
5468 Vec::new(),
5469 );
5470 Questions::at(home.join("questions")).put(&mut q).unwrap();
5471
5472 let verdict = Verdict {
5473 status: RunStatus::VerifiedNoop,
5474 left_pr: false,
5475 quota_hit: false,
5476 parked: false,
5477 no_viable_candidates: false,
5478 };
5479 let mut t = task();
5480 t.start(state.id.clone());
5481 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5482
5483 assert_eq!(t.status, TaskStatus::Held);
5484 let reason = t.hold_reason.expect("a held task must record why");
5485 assert!(
5486 reason.starts_with("run ended agent-verified no-op"),
5487 "the original settle reason must survive unchanged: {reason}"
5488 );
5489 assert!(
5490 reason.contains(q.short()),
5491 "the open question's id must be named so the notice is actionable: {reason}"
5492 );
5493 }
5494
5495 #[test]
5496 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
5497 crate::run::pin_test_home();
5498 let state = run_state(RunStatus::VerifiedNoop);
5499
5500 let verdict = Verdict {
5501 status: RunStatus::VerifiedNoop,
5502 left_pr: false,
5503 quota_hit: false,
5504 parked: false,
5505 no_viable_candidates: false,
5506 };
5507 let mut t = task();
5508 t.start(state.id.clone());
5509 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
5510
5511 assert_eq!(t.status, TaskStatus::Held);
5512 assert_eq!(
5513 t.hold_reason.as_deref(),
5514 Some("run ended agent-verified no-op"),
5515 "nothing to append when the question was already answered or never asked"
5516 );
5517 }
5518
5519 #[test]
5520 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5521 crate::run::pin_test_home();
5522 let mut first = run_state(RunStatus::Blocked);
5523 first.id = "20260101-000000-sup1".to_owned();
5524 first.save().unwrap();
5525 let mut second = run_state(RunStatus::Merged);
5526 second.id = "20260101-000000-sup2".to_owned();
5527 second.save().unwrap();
5528
5529 let mut t = task();
5530 t.runs = vec![first.id.clone(), second.id.clone()];
5531 t.status = TaskStatus::Done;
5532
5533 supersede_prior_runs(&t, &crate::run::home());
5534
5535 assert_eq!(
5536 RunState::load(&first.id).unwrap().status,
5537 RunStatus::Superseded,
5538 "the first attempt's Blocked no longer needs anyone's attention"
5539 );
5540 assert_eq!(
5541 RunState::load(&second.id).unwrap().status,
5542 RunStatus::Merged,
5543 "the run that actually succeeded is left exactly as it was"
5544 );
5545 }
5546
5547 #[test]
5548 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5549 crate::run::pin_test_home();
5555 let mut first = run_state(RunStatus::Blocked);
5556 first.id = "20260101-000000-sup9".to_owned();
5557 first.driver_pid = Some(std::process::id());
5560 first.driver_started_at = Some(
5561 crate::proc::process_started_at(std::process::id())
5562 .expect("this test process's own start time must be queryable"),
5563 );
5564 first.save().unwrap();
5565 let mut second = run_state(RunStatus::Merged);
5566 second.id = "20260101-000000-supa".to_owned();
5567 second.save().unwrap();
5568
5569 let mut t = task();
5570 t.runs = vec![first.id.clone(), second.id.clone()];
5571 t.status = TaskStatus::Done;
5572
5573 supersede_prior_runs(&t, &crate::run::home());
5574
5575 assert_eq!(
5576 RunState::load(&first.id).unwrap().status,
5577 RunStatus::Blocked,
5578 "a live driver_pid means something is still actually working this run, \
5579 even though no daemon claims it - rewriting under it would just be \
5580 undone the next time that process saves"
5581 );
5582 }
5583
5584 #[test]
5585 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5586 let dir = tempfile::tempdir().unwrap();
5592 let home = dir.path().to_path_buf();
5593 let queue = Queue::at(dir.path().join("queue"));
5594
5595 let mut first = run_state(RunStatus::Blocked);
5596 first.id = "20260101-000000-supd".to_owned();
5597 first.driver_pid = Some(std::process::id());
5598 first.driver_started_at = Some(
5599 crate::proc::process_started_at(std::process::id())
5600 .expect("this test process's own start time must be queryable"),
5601 );
5602 first.save_under(&home).unwrap();
5603 let mut second = run_state(RunStatus::Merged);
5604 second.id = "20260101-000000-supe".to_owned();
5605 second.save_under(&home).unwrap();
5606
5607 let mut t = task();
5608 t.runs = vec![first.id.clone(), second.id.clone()];
5609 t.status = TaskStatus::Done;
5610 queue.put(&mut t).unwrap();
5611
5612 resweep_superseded_attempts(&queue, &home);
5613 assert_eq!(
5614 RunState::load_under(&first.id, &home).unwrap().status,
5615 RunStatus::Blocked,
5616 "still live on the first pass, so still untouched"
5617 );
5618
5619 let mut stale = RunState::load_under(&first.id, &home).unwrap();
5625 stale.driver_started_at = Some("1".to_owned());
5626 stale.save_under(&home).unwrap();
5627
5628 resweep_superseded_attempts(&queue, &home);
5629 assert_eq!(
5630 RunState::load_under(&first.id, &home).unwrap().status,
5631 RunStatus::Superseded,
5632 "the second pass catches up what the first one correctly skipped"
5633 );
5634 }
5635
5636 #[test]
5637 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5638 crate::run::pin_test_home();
5639 let mut first = run_state(RunStatus::Blocked);
5640 first.id = "20260101-000000-sup3".to_owned();
5641 first.save().unwrap();
5642 let mut second = run_state(RunStatus::Blocked);
5643 second.id = "20260101-000000-sup4".to_owned();
5644 second.save().unwrap();
5645
5646 let mut t = task();
5647 t.runs = vec![first.id.clone(), second.id.clone()];
5648 t.status = TaskStatus::Failed;
5652
5653 supersede_prior_runs(&t, &crate::run::home());
5654
5655 assert_eq!(
5656 RunState::load(&first.id).unwrap().status,
5657 RunStatus::Blocked
5658 );
5659 assert_eq!(
5660 RunState::load(&second.id).unwrap().status,
5661 RunStatus::Blocked
5662 );
5663 }
5664
5665 #[test]
5666 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5667 crate::run::pin_test_home();
5671 let mut first = run_state(RunStatus::Blocked);
5672 first.id = "20260101-000000-sup5".to_owned();
5673 first.save().unwrap();
5674
5675 let mut t = task();
5676 t.runs = vec![first.id.clone()];
5677 t.status = TaskStatus::Done;
5678
5679 supersede_prior_runs(&t, &crate::run::home());
5680
5681 assert_eq!(
5682 RunState::load(&first.id).unwrap().status,
5683 RunStatus::Blocked,
5684 "a single-attempt task has no earlier run to supersede"
5685 );
5686 }
5687
5688 #[test]
5689 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
5690 crate::run::pin_test_home();
5697 let mut first = run_state(RunStatus::Blocked);
5698 first.id = "20260101-000000-supb".to_owned();
5699 first.save().unwrap();
5700 let mut second = run_state(RunStatus::Failed);
5701 second.id = "20260101-000000-supc".to_owned();
5702 second.save().unwrap();
5703
5704 let mut t = task();
5705 t.runs = vec![first.id.clone(), second.id.clone()];
5706 t.status = TaskStatus::Done;
5707
5708 supersede_prior_runs(&t, &crate::run::home());
5709
5710 assert_eq!(
5711 RunState::load(&first.id).unwrap().status,
5712 RunStatus::Blocked,
5713 "the task's last attempt never landed, so there is nothing here \
5714 actually superseding it"
5715 );
5716 }
5717
5718 #[test]
5719 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
5720 crate::run::pin_test_home();
5724 let mut failed = run_state(RunStatus::Failed);
5725 failed.id = "20260101-000000-sup6".to_owned();
5726 failed.save().unwrap();
5727 let mut noop = run_state(RunStatus::VerifiedNoop);
5728 noop.id = "20260101-000000-sup7".to_owned();
5729 noop.save().unwrap();
5730 let mut winner = run_state(RunStatus::Ready);
5731 winner.id = "20260101-000000-sup8".to_owned();
5732 winner.save().unwrap();
5733
5734 let mut t = task();
5735 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
5736 t.status = TaskStatus::Done;
5737
5738 supersede_prior_runs(&t, &crate::run::home());
5739
5740 assert_eq!(
5741 RunState::load(&failed.id).unwrap().status,
5742 RunStatus::Failed
5743 );
5744 assert_eq!(
5745 RunState::load(&noop.id).unwrap().status,
5746 RunStatus::VerifiedNoop
5747 );
5748 }
5749
5750 fn approval_question(run: &str) -> ask::Question {
5751 ask::Question::new(
5752 run.to_owned(),
5753 land::APPROVAL_NODE.to_owned(),
5754 "land".to_owned(),
5755 "merge?".to_owned(),
5756 String::new(),
5757 vec!["merge".to_owned(), "hold".to_owned()],
5758 )
5759 }
5760
5761 #[test]
5762 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
5763 crate::run::pin_test_home();
5764 let mut state = run_state(RunStatus::Landing);
5765 state.id = "20260101-000000-fre1".to_owned();
5766 state.parked = true;
5767 state.save().unwrap();
5768 ask::Questions::open()
5769 .put(&mut approval_question(&state.id))
5770 .unwrap();
5771
5772 let mut t = task();
5773 t.runs.push(state.id.clone());
5774 assert_eq!(
5775 land_resume_state(&t),
5776 LandResume::StillWaiting,
5777 "nobody has answered and the timeout has not passed"
5778 );
5779 }
5780
5781 #[test]
5782 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
5783 crate::run::pin_test_home();
5788 let mut state = run_state(RunStatus::Landing);
5789 state.id = "20260101-000000-exp1".to_owned();
5790 state.parked = true;
5791 state.config.graph.answer_timeout = 60;
5792 state.save().unwrap();
5793
5794 let store = ask::Questions::open();
5795 let mut q = approval_question(&state.id);
5796 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
5797 store.put(&mut q).unwrap();
5798
5799 let mut t = task();
5800 t.runs.push(state.id.clone());
5801 assert_eq!(
5802 land_resume_state(&t),
5803 LandResume::Ready,
5804 "an expired question must not be waited on forever"
5805 );
5806
5807 let after = store.get(&q.id).unwrap();
5808 assert!(
5809 !after.status.open(),
5810 "the question is abandoned, not silently ignored"
5811 );
5812 assert!(
5813 after.resolution().is_none(),
5814 "an abandoned question is not read as a decision"
5815 );
5816 }
5817
5818 #[test]
5819 fn reclaim_settles_a_running_task_against_its_last_run() {
5820 let mut t = task();
5821 t.start("20260904-000000-4043".to_owned());
5822 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
5823 assert_eq!(
5824 t.status,
5825 TaskStatus::Done,
5826 "a run that actually finished must not stay `running` forever"
5827 );
5828 }
5829
5830 #[test]
5831 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
5832 let mut t = task();
5836 t.start("20260904-000000-4043".to_owned());
5837 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
5838 assert_eq!(t.status, TaskStatus::Failed);
5839 assert!(t.status.runnable());
5840 }
5841
5842 #[test]
5843 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
5844 let mut t = task();
5845 t.start("20260904-000000-4043".to_owned());
5846 reclaim(&mut t, None, 2, "en");
5847 assert_eq!(t.status, TaskStatus::Held);
5848 assert!(
5849 t.last_error
5850 .as_deref()
5851 .is_some_and(|e| e.contains("running")),
5852 "the operator needs to know why this task was held"
5853 );
5854 }
5855
5856 #[test]
5857 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
5858 let dir = tempfile::tempdir().unwrap();
5859 let queue = Queue::at(dir.path().to_path_buf());
5860
5861 let mut orphaned = task();
5863 orphaned.id = "20260904-000000-orph".to_owned();
5864 orphaned.status = TaskStatus::Running;
5865 orphaned.attempts = 1;
5866 queue.put(&mut orphaned).unwrap();
5867
5868 let mut alive = task();
5869 alive.id = "20260904-000000-live".to_owned();
5870 alive.status = TaskStatus::Running;
5871 alive.attempts = 1;
5872 queue.put(&mut alive).unwrap();
5873 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
5874
5875 let mut queued = task();
5876 queued.id = "20260904-000000-wait".to_owned();
5877 queue.put(&mut queued).unwrap();
5878
5879 let reclaimed = reclaim_orphaned_running(&queue, 2);
5880 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
5881
5882 assert_eq!(
5883 queue.get(&orphaned.id).unwrap().status,
5884 TaskStatus::Held,
5885 "nothing was driving it and there was no run to recover"
5886 );
5887 assert_eq!(
5888 queue.get(&alive.id).unwrap().status,
5889 TaskStatus::Running,
5890 "a live claim must protect the task it belongs to"
5891 );
5892 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
5893 }
5894
5895 fn read_run_under(home: &Path, id: &str) -> RunState {
5901 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
5902 serde_json::from_str(&body).unwrap()
5903 }
5904
5905 #[test]
5906 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
5907 let dir = tempfile::tempdir().unwrap();
5908 let home = dir.path().to_path_buf();
5909 let now = Timestamp::now();
5910 let overrun_seat = || crate::run::ActiveSeat {
5911 node: "implement".to_owned(),
5912 started_at: now - jiff::SignedDuration::new(21_000, 0),
5913 timeout_secs: 3_600,
5914 attempt: 0,
5915 task: None,
5916 command: None,
5917 index: None,
5918 total: None,
5919 };
5920
5921 let mut dead = run_state(RunStatus::Implementing);
5922 dead.id = "20260101-000000-dead".to_owned();
5923 dead.active.insert("impl-A".to_owned(), overrun_seat());
5924 dead.driver_pid = Some(4242);
5927 dead.save_under(&home).unwrap();
5928
5929 let mut alive = run_state(RunStatus::Implementing);
5932 alive.id = "20260101-000000-aliv".to_owned();
5933 alive.active.insert("impl-A".to_owned(), overrun_seat());
5934 alive.save_under(&home).unwrap();
5935 let mut status = Status::new();
5936 status.current = vec![Current {
5937 task: "20260101-000000-task".to_owned(),
5938 run: alive.id.clone(),
5939 }];
5940 write_status_to(&home.join("daemon.json"), &status).unwrap();
5941
5942 let questions = Questions::at(home.join("questions"));
5946 let mut q = ask::Question::new(
5947 dead.id.clone(),
5948 "implement".to_owned(),
5949 "impl-A".to_owned(),
5950 "Which storage backend?".to_owned(),
5951 String::new(),
5952 vec!["SQLite".to_owned(), "Redis".to_owned()],
5953 );
5954 questions.put(&mut q).unwrap();
5955
5956 let abandoned = reclaim_abandoned_runs_with(
5957 &home,
5958 now,
5959 |pid| if pid == 4242 { Some(false) } else { None },
5960 |_| panic!("a query answering Dead outright needs no identity corroboration"),
5961 );
5962 assert_eq!(abandoned, vec![dead.id.clone()]);
5963
5964 let reloaded = read_run_under(&home, &dead.id);
5965 assert_eq!(reloaded.status, RunStatus::Failed);
5966 assert!(reloaded.active.is_empty());
5967 assert!(
5968 !questions.get(&q.id).unwrap().status.open(),
5969 "the failed run's own open question must be settled in the same pass"
5970 );
5971
5972 let still_alive = read_run_under(&home, &alive.id);
5973 assert_eq!(
5974 still_alive.status,
5975 RunStatus::Implementing,
5976 "a live daemon's claim protects it"
5977 );
5978 assert!(!still_alive.active.is_empty());
5979 }
5980
5981 #[test]
5991 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
5992 let dir = tempfile::tempdir().unwrap();
5993 let home = dir.path().to_path_buf();
5994 let now = Timestamp::now();
5995
5996 let mut manual = run_state(RunStatus::Reviewing);
5997 manual.id = "20260101-000000-manl".to_owned();
5998 manual.active.insert(
5999 "review-1".to_owned(),
6000 crate::run::ActiveSeat {
6001 node: "review".to_owned(),
6002 started_at: now - jiff::SignedDuration::new(21_000, 0),
6003 timeout_secs: 3_600,
6004 attempt: 0,
6005 task: None,
6006 command: None,
6007 index: None,
6008 total: None,
6009 },
6010 );
6011 manual.driver_pid = Some(4242);
6015 manual.driver_started_at = Some("1790000000".to_owned());
6016 manual.save_under(&home).unwrap();
6017
6018 let abandoned = reclaim_abandoned_runs_with(
6019 &home,
6020 now,
6021 |pid| if pid == 4242 { Some(true) } else { None },
6022 |pid| {
6023 if pid == 4242 {
6024 Some("1790000000".to_owned())
6025 } else {
6026 None
6027 }
6028 },
6029 );
6030 assert!(
6031 abandoned.is_empty(),
6032 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
6033 );
6034
6035 let reloaded = read_run_under(&home, &manual.id);
6036 assert_eq!(reloaded.status, RunStatus::Reviewing);
6037 assert!(!reloaded.active.is_empty());
6038 }
6039
6040 #[test]
6041 fn an_already_claimed_task_is_skipped_rather_than_failed() {
6042 let dir = tempfile::tempdir().unwrap();
6043 let queue = Queue::at(dir.path().to_path_buf());
6044 let mut only = task();
6045 queue.put(&mut only).unwrap();
6046
6047 let _elsewhere = queue.claim(&only.id).unwrap();
6048 let candidates = runnable(&queue);
6049 assert_eq!(candidates.len(), 1, "the task is still runnable");
6050 assert!(
6051 queue.claim(&candidates[0].id).is_err(),
6052 "the loop cannot take a claim somebody else holds"
6053 );
6054
6055 let after = queue.get(&only.id).unwrap();
6056 assert_eq!(after.status, TaskStatus::Queued);
6057 assert_eq!(
6058 after.attempts, 0,
6059 "losing the race is not an attempt at the task"
6060 );
6061 assert_eq!(after.last_error, None);
6062 }
6063
6064 #[test]
6065 fn the_status_file_round_trips_and_its_heartbeat_advances() {
6066 let dir = tempfile::tempdir().unwrap();
6067 let path = dir.path().join("daemon.json");
6068
6069 let mut status = Status::new();
6070 status.idle = false;
6071 status.completed = 7;
6072 status.current = vec![Current {
6073 task: "20260902-000000-t111".to_owned(),
6074 run: "20260902-000001-r111".to_owned(),
6075 }];
6076 write_status_to(&path, &status).unwrap();
6077 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6078 assert_eq!(first.schema, SCHEMA);
6079 assert_eq!(first.pid, std::process::id());
6080 assert!(!first.idle);
6081 assert_eq!(first.completed, 7);
6082 assert_eq!(first.current, status.current);
6083 assert!(
6084 !path.with_extension("json.tmp").exists(),
6085 "the temp file is renamed, not left behind"
6086 );
6087
6088 std::thread::sleep(Duration::from_millis(5));
6089 status.updated_at = Timestamp::now();
6090 status.polls = 3;
6091 write_status_to(&path, &status).unwrap();
6092 let second: Status =
6093 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6094 assert!(
6095 second.updated_at > first.updated_at,
6096 "a reader can only detect staleness if the heartbeat moves"
6097 );
6098 assert_eq!(
6099 second.started_at, first.started_at,
6100 "the start time is not a heartbeat"
6101 );
6102 assert_eq!(second.polls, 3);
6103 }
6104
6105 #[test]
6106 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
6107 let dir = tempfile::tempdir().unwrap();
6108
6109 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
6110
6111 let mut status = Status::new();
6112 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
6113 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6114 let stale = read_status(dir.path()).unwrap();
6115 assert!(
6116 !stale.running(Timestamp::now()),
6117 "a minute without a heartbeat is a dead daemon, not a busy one"
6118 );
6119 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
6120
6121 status.updated_at = Timestamp::now();
6122 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6123 let fresh = read_status(dir.path()).unwrap();
6124 assert!(fresh.running(Timestamp::now()));
6125 }
6126
6127 #[test]
6128 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
6129 let dir = tempfile::tempdir().unwrap();
6130 let now = Timestamp::now();
6131 let mine = "20260903-080619-01c2";
6132
6133 assert!(
6134 !is_working_on(dir.path(), mine, now),
6135 "no status file means nobody is working on anything"
6136 );
6137
6138 let mut status = Status::new();
6139 status.current = vec![Current {
6140 task: "20260903-080340-0167".to_owned(),
6141 run: mine.to_owned(),
6142 }];
6143 status.updated_at = now;
6144 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6145 assert!(is_working_on(dir.path(), mine, now));
6146 assert!(
6147 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
6148 "a daemon busy with one run is not working on another"
6149 );
6150
6151 status.updated_at = now - jiff::SignedDuration::from_secs(600);
6154 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6155 assert!(
6156 !is_working_on(dir.path(), mine, now),
6157 "a stale heartbeat is a dead daemon, so its run is a leftover"
6158 );
6159 }
6160
6161 #[test]
6162 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
6163 let dir = tempfile::tempdir().unwrap();
6164 let now = Timestamp::now();
6165
6166 assert!(
6167 !is_working_on_short(dir.path(), "01c2", now),
6168 "no status file means nobody is working on anything"
6169 );
6170
6171 let mut status = Status::new();
6172 status.current = vec![Current {
6173 task: "20260903-080340-0167".to_owned(),
6174 run: "20260903-080619-01c2".to_owned(),
6175 }];
6176 status.updated_at = now;
6177 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6178 assert!(
6179 is_working_on_short(dir.path(), "01c2", now),
6180 "the run's short id is the last block of its full id"
6181 );
6182 assert!(
6183 !is_working_on_short(dir.path(), "3cbf", now),
6184 "a daemon busy with one worktree bay is not working on another"
6185 );
6186 }
6187
6188 #[test]
6189 fn a_newer_status_file_still_yields_a_reading() {
6190 let dir = tempfile::tempdir().unwrap();
6191 std::fs::write(
6194 dir.path().join("daemon.json"),
6195 serde_json::json!({
6196 "schema": 2,
6197 "updated_at": Timestamp::now().to_string(),
6198 "idle": true,
6199 "surprise": { "nested": [1, 2, 3] },
6200 })
6201 .to_string(),
6202 )
6203 .unwrap();
6204
6205 let reading = read_status(dir.path()).expect("a forward-compatible read");
6206 assert!(reading.running(Timestamp::now()));
6207 assert!(reading.idle);
6208 assert!(reading.current.is_empty());
6209 }
6210
6211 #[test]
6212 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
6213 let dir = tempfile::tempdir().unwrap();
6219 std::fs::write(
6220 dir.path().join("daemon.json"),
6221 serde_json::json!({
6222 "schema": 1,
6223 "pid": 4242,
6224 "updated_at": Timestamp::now().to_string(),
6225 "idle": false,
6226 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
6227 "completed": 3,
6228 "polls": 9,
6229 })
6230 .to_string(),
6231 )
6232 .unwrap();
6233
6234 let reading = read_status(dir.path()).expect("an older shape must still parse");
6235 assert!(reading.running(Timestamp::now()));
6236 assert_eq!(
6237 reading.current,
6238 vec![Current {
6239 task: "20260902-140501-aaaa".to_owned(),
6240 run: "20260902-140502-bbbb".to_owned(),
6241 }]
6242 );
6243 }
6244
6245 #[test]
6246 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
6247 let dir = tempfile::tempdir().unwrap();
6248 std::fs::write(
6249 dir.path().join("daemon.json"),
6250 serde_json::json!({
6251 "schema": 1,
6252 "updated_at": Timestamp::now().to_string(),
6253 "idle": true,
6254 "current": null,
6255 })
6256 .to_string(),
6257 )
6258 .unwrap();
6259 let with_null = read_status(dir.path()).expect("null must still parse");
6260 assert!(with_null.current.is_empty());
6261
6262 std::fs::write(
6263 dir.path().join("daemon.json"),
6264 serde_json::json!({
6265 "schema": 1,
6266 "updated_at": Timestamp::now().to_string(),
6267 "idle": true,
6268 })
6269 .to_string(),
6270 )
6271 .unwrap();
6272 let absent = read_status(dir.path()).expect("a missing field must still parse");
6273 assert!(absent.current.is_empty());
6274 }
6275
6276 #[test]
6277 fn a_task_without_a_repository_runs_in_the_daemons_default() {
6278 let fallback = Path::new("/default");
6279 let mut blank = task();
6280 blank.repo = PathBuf::new();
6281 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
6282 let mut dot = task();
6283 dot.repo = PathBuf::from(".");
6284 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
6285 assert_eq!(
6286 repo_for(&task(), fallback),
6287 PathBuf::from("/repo"),
6288 "a task that names a repository keeps it"
6289 );
6290 }
6291
6292 #[test]
6293 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
6294 let mut solo_cfg = Config::default();
6300 solo_cfg.graph.candidates = 3;
6301 let mut solo_task = task();
6302 solo_task.solo = true;
6303 apply_solo(&mut solo_cfg, &solo_task);
6304 assert_eq!(solo_cfg.graph.candidates, 1);
6305
6306 let mut plain_cfg = Config::default();
6307 plain_cfg.graph.candidates = 3;
6308 let plain_task = task();
6309 assert!(!plain_task.solo);
6310 apply_solo(&mut plain_cfg, &plain_task);
6311 assert_eq!(
6312 plain_cfg.graph.candidates, 3,
6313 "a task that did not ask to run alone keeps the config's candidates"
6314 );
6315 }
6316
6317 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
6318 QuotaLoss {
6319 seat: seat.into(),
6320 node: "judge".into(),
6321 at: at.parse().unwrap(),
6322 reset: reset.map(str::to_string),
6323 }
6324 }
6325
6326 #[test]
6327 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
6328 let old: Vec<QuotaLoss> = (1..=4)
6329 .map(|i| {
6330 loss(
6331 &format!("judge-{i}"),
6332 "2026-09-23T05:23:00Z",
6333 Some("2:40pm (Asia/Tokyo)"),
6334 )
6335 })
6336 .collect();
6337 let fresh = losses_this_attempt(&old, &old);
6338 assert!(fresh.is_empty());
6339 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
6340 }
6342
6343 #[test]
6344 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
6345 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
6346 let now = Timestamp::now();
6347 let mut after = old.clone();
6348 after.push(loss("judge-2", &now.to_string(), None));
6349 let fresh = losses_this_attempt(&old, &after);
6350 assert_eq!(fresh, vec![after[1].clone()]);
6351 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
6352 assert_eq!(
6353 until,
6354 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
6355 );
6356 }
6357
6358 #[test]
6359 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
6360 let before = vec![
6363 loss("judge-1", "2026-09-23T05:23:00Z", None),
6364 loss("judge-2", "2026-09-23T05:24:00Z", None),
6365 ];
6366 let after = vec![
6367 loss("judge-2", "2026-09-23T05:24:00Z", None),
6368 loss("judge-1", "2026-09-24T01:00:00Z", None),
6369 ];
6370 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
6371 }
6372
6373 #[test]
6374 fn merge_overrides_are_parsed_or_refused() {
6375 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
6376 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
6377 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
6378 assert!(merge_mode("squash").is_err());
6379 }
6380
6381 #[test]
6382 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
6383 let now = Timestamp::now();
6384 let fallback = Duration::from_secs(300);
6385 let cap = Duration::from_secs(1800);
6386
6387 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
6389
6390 let soon = now + jiff::SignedDuration::from_secs(600);
6392 assert_eq!(
6393 quota_wait(Some(soon), now, fallback, cap),
6394 Duration::from_secs(600)
6395 );
6396
6397 let past = now - jiff::SignedDuration::from_secs(60);
6400 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
6401
6402 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
6405 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
6406 }
6407
6408 #[test]
6409 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
6410 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6411
6412 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
6413 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
6414
6415 let already_past =
6419 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
6420 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
6421
6422 assert!(
6423 parse_reset_hint("session limit reached", now, now).is_none(),
6424 "free text with no recognised shape is not guessed at"
6425 );
6426 assert!(
6427 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
6428 "an unresolvable zone name is not guessed at either"
6429 );
6430 }
6431
6432 #[test]
6433 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
6434 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
6435
6436 let at = parse_reset_hint(
6437 "You've hit your usage limit. Visit \
6438 https://chatgpt.com/codex/settings/usage to purchase more \
6439 credits or try again at Sep 19th, 2026 5:10 PM.",
6440 now,
6441 now,
6442 )
6443 .expect("the codex reset wording is a recognised shape");
6444 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
6445
6446 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
6451 .expect("an explicit year needs no rollover");
6452 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
6453
6454 assert!(
6455 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
6456 "a two-digit year is not the documented shape and is not guessed at"
6457 );
6458 assert!(
6459 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
6460 "a four-letter month name is not the documented three-letter abbreviation"
6461 );
6462 assert!(
6463 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
6464 "an explicit zone on the dated shape is a format nobody has \
6465 documented, and is refused rather than guessed at as UTC"
6466 );
6467 }
6468
6469 #[test]
6470 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
6471 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
6472 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
6473
6474 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
6475 assert_eq!(at.as_second() - recorded.as_second(), 3769);
6476
6477 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
6478 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
6479
6480 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
6481 assert!(
6482 parse_reset_hint(bad, now, recorded).is_none(),
6483 "{bad:?} must not be guessed at"
6484 );
6485 }
6486 }
6487
6488 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
6492 let config = dir.join("magi.toml");
6493 std::fs::write(
6494 &config,
6495 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
6496 )
6497 .unwrap();
6498 let opts = Opts {
6499 poll: Duration::from_secs(30),
6500 config: Some(config),
6501 repo: dir.join("repo"),
6505 ..Opts::default()
6506 };
6507 let home = dir.join("home");
6516 let worktrees = dir.join("wt");
6517 (
6518 opts,
6519 Queue::at(dir.join("queue")),
6520 home.join("daemon.json"),
6521 home,
6522 worktrees,
6523 )
6524 }
6525
6526 #[test]
6527 fn a_stop_is_idempotent_and_once_set_stays_set() {
6528 let stop = Stop::new();
6529 assert!(!stop.stopped());
6530
6531 stop.stop();
6532 assert!(stop.stopped());
6533 stop.stop();
6534 assert!(stop.stopped(), "a second stop is not a toggle");
6535
6536 let shared = stop.clone();
6537 assert!(
6538 shared.stopped(),
6539 "a clone is the same stop; that is how the loop and its caller share one"
6540 );
6541 }
6542
6543 #[test]
6544 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
6545 let stop = Stop::new();
6546 stop.enter();
6547 assert!(
6548 !stop.finishing(),
6549 "a busy loop nobody has asked to stop is just running"
6550 );
6551
6552 stop.stop();
6553 assert!(
6554 stop.finishing(),
6555 "a stop asked for mid-run has not landed until the run is settled"
6556 );
6557
6558 stop.exit();
6559 assert!(
6560 !stop.finishing(),
6561 "once the run is settled the stop has landed and there is nothing to finish"
6562 );
6563 }
6564
6565 #[test]
6566 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6567 let stop = Stop::new();
6568 stop.enter();
6569 stop.enter();
6570 stop.stop();
6571 assert!(stop.finishing(), "two runs still in flight");
6572
6573 stop.exit();
6574 assert!(
6575 stop.finishing(),
6576 "one run finished, but a sibling is still working"
6577 );
6578
6579 stop.exit();
6580 assert!(
6581 !stop.finishing(),
6582 "the last run out is what actually lands the stop"
6583 );
6584 }
6585
6586 #[tokio::test]
6587 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
6588 let dir = tempfile::tempdir().unwrap();
6589 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6590 let stop = Stop::new();
6591 stop.stop();
6592
6593 let began = std::time::Instant::now();
6594 tokio::time::timeout(
6595 Duration::from_secs(2),
6596 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6597 )
6598 .await
6599 .expect("a stopped loop must return, not sit out its poll interval")
6600 .expect("the loop's own setup and teardown must not fail");
6601 assert!(
6602 began.elapsed() < opts.poll,
6603 "returned only after {:?}, which is a poll interval, not a stop",
6604 began.elapsed()
6605 );
6606 }
6607
6608 #[tokio::test]
6609 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
6610 let dir = tempfile::tempdir().unwrap();
6611 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6612 let stop = Stop::new();
6613
6614 let asker = {
6617 let stop = stop.clone();
6618 tokio::spawn(async move {
6619 tokio::time::sleep(Duration::from_millis(20)).await;
6620 stop.stop();
6621 })
6622 };
6623
6624 let began = std::time::Instant::now();
6625 tokio::time::timeout(
6626 Duration::from_secs(2),
6627 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6628 )
6629 .await
6630 .expect("a stop asked for while idle must wake the wait")
6631 .expect("the loop's own setup and teardown must not fail");
6632 asker.await.unwrap();
6633 assert!(
6634 began.elapsed() < opts.poll,
6635 "returned only after {:?}, so the stop waited on the sleep",
6636 began.elapsed()
6637 );
6638 }
6639
6640 #[tokio::test]
6641 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
6642 let dir = tempfile::tempdir().unwrap();
6643 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6644 let stop = Stop::new();
6645 stop.stop();
6646
6647 tokio::time::timeout(
6648 Duration::from_secs(2),
6649 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6650 )
6651 .await
6652 .expect("a stopped loop must return")
6653 .expect("the loop's own setup and teardown must not fail");
6654
6655 assert!(
6656 home.is_dir(),
6657 "the loop did publish a status file, so its removal is the teardown and not an absence"
6658 );
6659 assert!(
6660 !status_file.exists(),
6661 "a stopped loop clears its status file"
6662 );
6663 assert!(
6664 read_status(&home).is_none(),
6665 "a reader must see no daemon at all, not a heartbeat that merely stopped"
6666 );
6667 }
6668
6669 #[tokio::test]
6670 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
6671 let dir = tempfile::tempdir().unwrap();
6672 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6673 opts.once = true;
6674
6675 let mut settled = RunState::new(
6676 dir.path().join("repo"),
6677 "main".to_owned(),
6678 "abc1234".to_owned(),
6679 "fixture".to_owned(),
6680 Config::default(),
6681 );
6682 settled.status = RunStatus::Ready;
6683 let run_dir = home.join("runs").join(&settled.id);
6684 std::fs::create_dir_all(&run_dir).unwrap();
6685 std::fs::write(
6686 run_dir.join("run.json"),
6687 serde_json::to_string_pretty(&settled).unwrap(),
6688 )
6689 .unwrap();
6690 let questions = Questions::at(home.join("questions"));
6691 let mut question = ask::Question::new(
6692 settled.id.clone(),
6693 "review".to_owned(),
6694 "reviewer-1".to_owned(),
6695 "Continue?".to_owned(),
6696 String::new(),
6697 Vec::new(),
6698 );
6699 questions.put(&mut question).unwrap();
6700
6701 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
6702 .await
6703 .unwrap();
6704
6705 assert_eq!(
6706 questions.get(&question.id).unwrap().status,
6707 ask::QuestionStatus::Abandoned,
6708 "an empty --once drain still performs startup question cleanup"
6709 );
6710 }
6711
6712 #[test]
6713 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
6714 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6715
6716 assert!(
6717 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
6718 "never checked before: due at once"
6719 );
6720
6721 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
6722 assert!(
6723 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
6724 "well inside the interval: not due yet"
6725 );
6726
6727 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
6728 assert!(
6729 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
6730 "exactly at the edge: not yet due, same convention as `clean::due`"
6731 );
6732
6733 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6734 assert!(
6735 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
6736 "past the interval: due again"
6737 );
6738 }
6739
6740 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
6745 let config = dir.join("magi.toml");
6746 std::fs::write(
6752 &config,
6753 format!(
6754 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
6755 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
6756 cache_dir.display()
6757 ),
6758 )
6759 .unwrap();
6760 Opts {
6761 config: Some(config),
6762 repo: dir.join("repo"),
6763 ..Opts::default()
6764 }
6765 }
6766
6767 #[tokio::test]
6768 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
6769 let dir = tempfile::tempdir().unwrap();
6770 let home = dir.path().join("home");
6771 let cache_dir = dir.path().join("cache");
6772 std::fs::create_dir_all(&cache_dir).unwrap();
6773 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6774 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6775
6776 let running = Stop::new();
6779 let mut last_checked = None;
6780 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6781 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
6782 .await;
6783 assert_eq!(
6784 crate::disk::dir_size(&cache_dir),
6785 0,
6786 "over the cap on the first check ever: pruned at once, no idle queue required"
6787 );
6788 assert_eq!(last_checked, Some(t0));
6789
6790 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
6792 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
6793 maybe_prune_cache_between_runs(
6794 &opts.repo,
6795 &opts,
6796 &home,
6797 &running,
6798 &mut last_checked,
6799 too_soon,
6800 )
6801 .await;
6802 assert_eq!(
6803 crate::disk::dir_size(&cache_dir),
6804 10,
6805 "too soon since the last check: left alone rather than rescanned every call"
6806 );
6807 assert_eq!(
6808 last_checked,
6809 Some(t0),
6810 "an idle check does not reset the clock"
6811 );
6812
6813 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6815 maybe_prune_cache_between_runs(
6816 &opts.repo,
6817 &opts,
6818 &home,
6819 &running,
6820 &mut last_checked,
6821 due_again,
6822 )
6823 .await;
6824 assert_eq!(
6825 crate::disk::dir_size(&cache_dir),
6826 0,
6827 "due again: pruned back under the cap"
6828 );
6829 }
6830
6831 #[tokio::test]
6839 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
6840 let dir = tempfile::tempdir().unwrap();
6841 let home = dir.path().join("home");
6842 let cache_dir = dir.path().join("cache");
6843 std::fs::create_dir_all(&cache_dir).unwrap();
6844 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6845 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6846
6847 let stop = Stop::new();
6848 stop.stop();
6849 assert!(
6850 !stop.finishing(),
6851 "no run is in flight at a between-runs boundary, so nothing else \
6852 would tell the operator this stop had not taken effect yet"
6853 );
6854
6855 let mut last_checked = None;
6856 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6857 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
6858 .await;
6859 assert_eq!(
6860 crate::disk::dir_size(&cache_dir),
6861 10,
6862 "over its cap, and due for the first check ever, but a stop outranks \
6863 it: the cap is a standing policy the next start measures again"
6864 );
6865 assert_eq!(
6866 last_checked, None,
6867 "a check that never happened must not claim the interval"
6868 );
6869 }
6870
6871 #[tokio::test]
6885 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
6886 let dir = tempfile::tempdir().unwrap();
6887 let cache_dir = dir.path().join("cache");
6888 std::fs::create_dir_all(&cache_dir).unwrap();
6889 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
6890
6891 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
6892 opts.poll = Duration::from_millis(20);
6893 opts.max_attempts = 1_000;
6894
6895 let queue = Queue::at(dir.path().join("queue"));
6896 let mut t = Task::new(
6897 "x".to_owned(),
6898 "x".to_owned(),
6899 opts.repo.clone(),
6900 Source::Human,
6901 );
6902 queue.put(&mut t).unwrap();
6903
6904 let home = dir.path().join("home");
6905 let worktrees = dir.path().join("wt");
6906 let status_file = home.join("daemon.json");
6907 let stop = Stop::new();
6908 let stopper = {
6909 let stop = stop.clone();
6910 tokio::spawn(async move {
6911 tokio::time::sleep(Duration::from_millis(400)).await;
6912 stop.stop();
6913 })
6914 };
6915
6916 tokio::time::timeout(
6917 Duration::from_secs(10),
6918 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6919 )
6920 .await
6921 .expect("the loop must not hang on a queue that keeps producing failing work")
6922 .expect("the loop's own setup and teardown must not fail");
6923 stopper.await.unwrap();
6924
6925 let after = queue.get(&t.id).unwrap();
6926 assert!(
6927 after.attempts >= 2,
6928 "the harness must actually have retried more than once, or this is not \
6929 exercising a busy queue at all (got {} attempt(s))",
6930 after.attempts
6931 );
6932 assert!(
6933 after.status.runnable(),
6934 "still under its attempt budget: the queue never reached a natural idle \
6935 on its own, only the external stop ended the test"
6936 );
6937
6938 assert_eq!(
6939 crate::disk::dir_size(&cache_dir),
6940 0,
6941 "an oversized cache must not be left to grow unboundedly just because the \
6942 queue kept the loop busy the whole time"
6943 );
6944 }
6945
6946 #[test]
6947 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
6948 let dir = tempfile::tempdir().unwrap();
6949 let queue = Queue::at(dir.path().join("queue"));
6950 let questions = Questions::at(dir.path().join("questions"));
6951 let mut task = task();
6952 queue.put(&mut task).unwrap();
6953
6954 let mut task_question = ask::Question::new(
6955 task.id.clone(),
6956 crate::conduct::NODE.to_owned(),
6957 "conduct".to_owned(),
6958 "Which backend?".to_owned(),
6959 String::new(),
6960 Vec::new(),
6961 );
6962 questions.put(&mut task_question).unwrap();
6963 task.block(vec![task_question.id.clone()], None);
6964 queue.put(&mut task).unwrap();
6965
6966 let mut run_question = ask::Question::new(
6967 "20260101-000000-run1".to_owned(),
6968 "review".to_owned(),
6969 "reviewer-1".to_owned(),
6970 "Run question".to_owned(),
6971 String::new(),
6972 Vec::new(),
6973 );
6974 questions.put(&mut run_question).unwrap();
6975
6976 let mut coincidental = ask::Question::new(
6981 task.id.clone(),
6982 "review".to_owned(),
6983 "reviewer-1".to_owned(),
6984 "Unrelated review question".to_owned(),
6985 String::new(),
6986 Vec::new(),
6987 );
6988 questions.put(&mut coincidental).unwrap();
6989
6990 reconcile_task_questions(&queue, &questions);
6991 assert!(questions.get(&task_question.id).unwrap().status.open());
6992 assert!(questions.get(&run_question.id).unwrap().status.open());
6993 assert!(questions.get(&coincidental.id).unwrap().status.open());
6994
6995 task.release();
6996 queue.put(&mut task).unwrap();
6997 reconcile_task_questions(&queue, &questions);
6998 assert_eq!(
6999 questions.get(&task_question.id).unwrap().status,
7000 ask::QuestionStatus::Abandoned
7001 );
7002 assert!(
7003 questions.get(&run_question.id).unwrap().status.open(),
7004 "run questions remain the run janitor's responsibility"
7005 );
7006 assert!(
7007 questions.get(&coincidental.id).unwrap().status.open(),
7008 "a non-conductor question must not be abandoned just because its \
7009 run id coincides with a task id"
7010 );
7011 }
7012
7013 #[test]
7014 fn a_freshly_started_running_task_is_never_stalled() {
7015 let dir = tempfile::tempdir().unwrap();
7016 let mut t = task();
7017 t.start("run-1".to_owned());
7018 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
7021 }
7022
7023 #[test]
7024 fn a_long_running_task_with_no_live_daemon_is_stalled() {
7025 let dir = tempfile::tempdir().unwrap();
7026 let mut t = task();
7027 t.start("run-1".to_owned());
7028 t.updated_at = Timestamp::now()
7029 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7030 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
7031 assert_eq!(
7032 stalled_tasks(
7033 &Queue::at(dir.path().join("q")),
7034 dir.path(),
7035 Timestamp::now()
7036 )
7037 .len(),
7038 0,
7039 "the task was never written to this queue"
7040 );
7041 }
7042
7043 #[test]
7044 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
7045 let dir = tempfile::tempdir().unwrap();
7046 let mut t = task();
7047 t.id = "20260903-080340-0167".to_owned();
7048 t.start("20260903-080619-01c2".to_owned());
7049 t.updated_at = Timestamp::now()
7050 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
7051
7052 let mut status = Status::new();
7053 status.current = vec![Current {
7054 task: t.id.clone(),
7055 run: "20260903-080619-01c2".to_owned(),
7056 }];
7057 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7058
7059 assert!(
7060 !is_stalled(&t, dir.path(), Timestamp::now()),
7061 "a live daemon's own heartbeat rules out stalled, however long the task has run"
7062 );
7063 }
7064
7065 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
7069 let path = queue.path_of(id);
7070 let body = std::fs::read_to_string(&path).unwrap();
7071 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
7072 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
7073 v["updated_at"] = serde_json::Value::String(old.to_string());
7074 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
7075 }
7076
7077 #[test]
7078 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
7079 let dir = tempfile::tempdir().unwrap();
7092 let queue = Queue::at(dir.path().join("queue"));
7093 let home = dir.path().join("home");
7094
7095 let mut t = task();
7096 t.id = "20260101-000001-lock".to_owned();
7097 t.start("run-1".to_owned());
7098 queue.put(&mut t).unwrap();
7099 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7100 std::fs::write(
7101 dir.path().join("queue").join(format!("{}.lock", t.id)),
7102 "not a pid",
7103 )
7104 .unwrap();
7105
7106 let now = Timestamp::now();
7107 assert!(
7108 reclaim_orphaned_running(&queue, 2).is_empty(),
7109 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
7110 and reclaim must leave the task alone"
7111 );
7112 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7113
7114 let stalled = stalled_tasks(&queue, &home, now);
7115 assert_eq!(
7116 stalled.len(),
7117 1,
7118 "reclaim's inability to claim it yet must not hide it from the conductor"
7119 );
7120 assert_eq!(stalled[0].id, t.id);
7121 }
7122
7123 #[test]
7124 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
7125 let dir = tempfile::tempdir().unwrap();
7126 crate::run::set_home(dir.path().join("run-home"));
7127 let queue = Queue::at(dir.path().join("queue"));
7128 let home = dir.path().join("home");
7129 let questions = Questions::at(dir.path().join("questions"));
7130
7131 let mut t = task();
7132 t.id = "20260101-000003-dead".to_owned();
7133 t.start("missing-run".to_owned());
7134 queue.put(&mut t).unwrap();
7135 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
7136
7137 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7140 assert_eq!(
7141 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
7142 [&t.id]
7143 );
7144 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
7145 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7146
7147 crate::conduct::apply(
7150 &queue,
7151 &questions,
7152 &crate::conduct::Verdict {
7153 decisions: vec![crate::conduct::Decision {
7154 id: t.id.clone(),
7155 recovery: Some(crate::conduct::Recovery::Requeue),
7156 ..crate::conduct::Decision::default()
7157 }],
7158 },
7159 )
7160 .unwrap();
7161 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7162 }
7163
7164 #[test]
7165 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
7166 let dir = tempfile::tempdir().unwrap();
7167 let queue = Queue::at(dir.path().join("queue"));
7168 let home = dir.path().join("home");
7169
7170 let mut fresh = task();
7171 fresh.id = "20260101-000001-aaaa".to_owned();
7172 fresh.start("run-1".to_owned());
7173 queue.put(&mut fresh).unwrap();
7174
7175 let mut old = task();
7176 old.id = "20260101-000002-bbbb".to_owned();
7177 old.start("run-2".to_owned());
7178 queue.put(&mut old).unwrap();
7179 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
7180
7181 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
7182 assert_eq!(stalled.len(), 1);
7183 assert_eq!(stalled[0].id, old.id);
7184 }
7185
7186 #[test]
7187 fn queued_and_finished_task_views_partition_by_status() {
7188 let dir = tempfile::tempdir().unwrap();
7189 let queue = Queue::at(dir.path().join("queue"));
7190
7191 let mut queued = task();
7192 queued.id = "20260101-000001-aaaa".to_owned();
7193 queue.put(&mut queued).unwrap();
7194
7195 let mut failed = task();
7196 failed.id = "20260101-000002-bbbb".to_owned();
7197 failed.start("run-1".to_owned());
7198 failed.fail("gate red", 5);
7199 queue.put(&mut failed).unwrap();
7200
7201 let mut held = task();
7202 held.id = "20260101-000003-cccc".to_owned();
7203 held.hold_machine(None);
7204 queue.put(&mut held).unwrap();
7205
7206 let mut running = task();
7207 running.id = "20260101-000004-dddd".to_owned();
7208 running.start("run-2".to_owned());
7209 queue.put(&mut running).unwrap();
7210
7211 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
7212 assert_eq!(queued_ids, [queued.id.clone()]);
7213
7214 let mut finished_ids: Vec<String> =
7215 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
7216 finished_ids.sort_unstable();
7217 let mut want = vec![failed.id.clone(), held.id.clone()];
7218 want.sort_unstable();
7219 assert_eq!(finished_ids, want);
7220 }
7221
7222 #[test]
7223 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
7224 let dir = tempfile::tempdir().unwrap();
7225 let queue = Queue::at(dir.path().join("queue"));
7226 let questions = ask::Questions::at(dir.path().join("questions"));
7227
7228 let mut dep = task();
7229 dep.id = "20260101-000001-dep0".to_owned();
7230 dep.succeed();
7231 queue.put(&mut dep).unwrap();
7232
7233 let mut still_going = task();
7234 still_going.id = "20260101-000002-dep1".to_owned();
7235 queue.put(&mut still_going).unwrap();
7236
7237 let mut blocked = task();
7238 blocked.id = "20260101-000003-main".to_owned();
7239 blocked.block(
7240 vec![dep.id.clone(), still_going.id.clone()],
7241 Some("waits on both".to_owned()),
7242 );
7243 queue.put(&mut blocked).unwrap();
7244
7245 resolve_blockers(&queue, &questions);
7246
7247 let after = queue.get(&blocked.id).unwrap();
7248 assert_eq!(
7249 after.status,
7250 TaskStatus::Blocked,
7251 "one dependency is still outstanding"
7252 );
7253 assert_eq!(after.blocked_by, [still_going.id.clone()]);
7254 }
7255
7256 #[test]
7257 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
7258 let dir = tempfile::tempdir().unwrap();
7259 let queue = Queue::at(dir.path().join("queue"));
7260 let questions = ask::Questions::at(dir.path().join("questions"));
7261
7262 let mut q = crate::ask::Question::new(
7263 "20260101-000001-main".to_owned(),
7264 crate::conduct::NODE.to_owned(),
7265 "conduct".to_owned(),
7266 "Which backend?".to_owned(),
7267 String::new(),
7268 Vec::new(),
7269 );
7270 questions.put(&mut q).unwrap();
7271 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
7272 .unwrap();
7273 questions.put(&mut q).unwrap();
7274
7275 let mut blocked = task();
7276 blocked.id = "20260101-000001-main".to_owned();
7277 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
7278 queue.put(&mut blocked).unwrap();
7279
7280 resolve_blockers(&queue, &questions);
7281
7282 let after = queue.get(&blocked.id).unwrap();
7283 assert_eq!(
7284 after.status,
7285 TaskStatus::Queued,
7286 "the only blocker resolved"
7287 );
7288 assert_eq!(after.answers.len(), 1);
7289 assert_eq!(after.answers[0].question, "Which backend?");
7290 assert_eq!(after.answers[0].answer, "SQLite");
7291
7292 let instruction = instruction_for(&after);
7294 assert!(instruction.contains("Which backend?"));
7295 assert!(instruction.contains("SQLite"));
7296 }
7297
7298 #[test]
7299 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
7300 let dir = tempfile::tempdir().unwrap();
7301 let queue = Queue::at(dir.path().join("queue"));
7302 let questions = ask::Questions::at(dir.path().join("questions"));
7303
7304 let mut q = crate::ask::Question::new(
7305 "20260101-000001-main".to_owned(),
7306 crate::conduct::NODE.to_owned(),
7307 "conduct".to_owned(),
7308 "Is the setup done?".to_owned(),
7309 String::new(),
7310 Vec::new(),
7311 );
7312 q.abandon("no answer within 60s of asking");
7313 questions.put(&mut q).unwrap();
7314
7315 let mut blocked = task();
7316 blocked.id = "20260101-000001-main".to_owned();
7317 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
7318 queue.put(&mut blocked).unwrap();
7319
7320 resolve_blockers(&queue, &questions);
7321
7322 let after = queue.get(&blocked.id).unwrap();
7323 assert_eq!(
7324 after.status,
7325 TaskStatus::Held,
7326 "never left blocked on nothing"
7327 );
7328 assert!(!after.operator_held(), "a machine hold, for triage");
7329 assert!(
7330 after
7331 .hold_reason
7332 .as_deref()
7333 .unwrap_or_default()
7334 .contains("went unanswered")
7335 );
7336 }
7337
7338 #[test]
7339 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
7340 let dir = tempfile::tempdir().unwrap();
7346 let queue = Queue::at(dir.path().join("queue"));
7347 let questions = ask::Questions::at(dir.path().join("questions"));
7348
7349 let mut q = crate::ask::Question::new(
7350 "20260101-000001-main".to_owned(),
7351 crate::conduct::NODE.to_owned(),
7352 "conduct".to_owned(),
7353 "How should this be handled?".to_owned(),
7354 String::new(),
7355 Vec::new(),
7356 );
7357 questions.put(&mut q).unwrap();
7358 q.answer(crate::ask::Answer::Text(
7359 "leave it held, a human will look at it later".to_owned(),
7360 ))
7361 .unwrap();
7362 questions.put(&mut q).unwrap();
7363
7364 let mut held = task();
7365 held.id = "20260101-000001-main".to_owned();
7366 held.hold_machine(Some("out of attempts".to_owned()));
7367 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
7368 queue.put(&mut held).unwrap();
7369
7370 resolve_blockers(&queue, &questions);
7371
7372 let after = queue.get(&held.id).unwrap();
7373 assert_eq!(after.status, TaskStatus::Held);
7374 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
7375 assert_eq!(
7376 after.answers[0].answer,
7377 "leave it held, a human will look at it later"
7378 );
7379 }
7380
7381 #[test]
7382 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
7383 let dir = tempfile::tempdir().unwrap();
7384 let queue = Queue::at(dir.path().join("queue"));
7385 let questions = ask::Questions::at(dir.path().join("questions"));
7386 let mut dep = task();
7387 dep.id = "20260101-000001-gone".to_owned();
7388 queue.put(&mut dep).unwrap();
7389 let mut blocked = task();
7390 blocked.id = "20260101-000003-main".to_owned();
7391 blocked.block(vec![dep.id.clone()], None);
7392 queue.put(&mut blocked).unwrap();
7393
7394 let claim = queue.claim(&blocked.id).unwrap();
7396 queue.remove(&dep.id, false, &questions).unwrap();
7397 drop(claim);
7398 resolve_blockers(&queue, &questions);
7399
7400 let after = queue.get(&blocked.id).unwrap();
7401 assert_eq!(after.status, TaskStatus::Queued);
7402 assert!(after.blocked_by.is_empty());
7403 }
7404
7405 #[test]
7406 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
7407 let dir = tempfile::tempdir().unwrap();
7413 let queue = Queue::at(dir.path().join("queue"));
7414 let questions = ask::Questions::at(dir.path().join("questions"));
7415
7416 let mut still_going = task();
7417 still_going.id = "20260101-000002-dep1".to_owned();
7418 queue.put(&mut still_going).unwrap();
7419
7420 let mut blocked = task();
7421 blocked.id = "20260101-000003-main".to_owned();
7422 blocked.block(
7423 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
7424 Some("waits on both".to_owned()),
7425 );
7426 queue.put(&mut blocked).unwrap();
7427
7428 resolve_blockers(&queue, &questions);
7429
7430 let after = queue.get(&blocked.id).unwrap();
7431 assert_eq!(
7432 after.status,
7433 TaskStatus::Held,
7434 "a missing dependency must not leave the task blocked forever"
7435 );
7436 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
7437 assert!(after.blocked_by.is_empty());
7438 let reason = after.hold_reason.as_deref().unwrap_or_default();
7439 assert!(
7440 reason.contains("20260101-000001-gone"),
7441 "the missing id must be named so an operator can tell what happened: {reason}"
7442 );
7443 assert!(
7444 reason.contains(&still_going.id),
7445 "the still-valid dependency must not silently vanish from the record: {reason}"
7446 );
7447 }
7448
7449 #[test]
7450 fn instruction_for_is_unchanged_without_any_answers() {
7451 let t = task();
7452 assert_eq!(instruction_for(&t), t.instruction);
7453 }
7454
7455 #[test]
7456 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
7457 let dir = tempfile::tempdir().unwrap();
7458 let q = Queue::at(dir.path().join("queue"));
7459 let src = dir.path().join("shot.png");
7460 std::fs::write(&src, "x").unwrap();
7461 let mut t = task();
7462 q.attach(&mut t, &[src]).unwrap();
7463 let paths = task_attachments(&q, &t).unwrap();
7464 assert_eq!(paths.len(), 1);
7465 assert!(paths[0].is_absolute() && paths[0].is_file());
7466 std::fs::remove_file(&paths[0]).unwrap();
7467 let err = task_attachments(&q, &t).unwrap_err().to_string();
7468 assert!(err.contains("shot.png"), "{err}");
7469 }
7470
7471 #[test]
7472 fn resumed_instruction_is_unchanged_without_any_answers() {
7473 let t = task();
7474 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
7475 }
7476
7477 #[test]
7478 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
7479 let mut t = task();
7480 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7481 let old = t.instruction.clone();
7485
7486 let refreshed = resumed_instruction(&old, &t);
7487 assert!(refreshed.starts_with(&old), "the original text is kept");
7488 assert!(refreshed.contains("Which backend?"));
7489 assert!(refreshed.contains("SQLite"));
7490 }
7491
7492 #[test]
7493 fn resumed_instruction_keeps_an_original_answers_heading() {
7494 let mut t = task();
7495 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
7496 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7497
7498 let refreshed = resumed_instruction(&t.instruction, &t);
7499
7500 assert!(
7501 refreshed.starts_with(&t.instruction),
7502 "an answers heading in the original instruction is not the appended block"
7503 );
7504 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
7505 assert!(refreshed.contains("Which backend?"));
7506 assert!(refreshed.contains("SQLite"));
7507
7508 let repeated = resumed_instruction(&refreshed, &t);
7509 assert_eq!(
7510 repeated, refreshed,
7511 "only the final appended block is refreshed"
7512 );
7513 }
7514
7515 #[test]
7516 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
7517 let mut t = task();
7518 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7519
7520 let once = resumed_instruction(&t.instruction, &t);
7524 let twice = resumed_instruction(&once, &t);
7525 assert_eq!(once, twice);
7526 assert_eq!(once.matches("Which backend?").count(), 1);
7527
7528 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
7530 let refreshed = resumed_instruction(&once, &t);
7531 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
7532 assert!(refreshed.contains("Which backend?"));
7533 assert!(refreshed.contains("Which cache?"));
7534 }
7535
7536 #[test]
7537 fn prepare_instruction_covers_all_three_starters() {
7538 let mut t = task();
7539 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
7540
7541 assert_eq!(
7544 prepare_instruction(&Starter::Start, None, &t),
7545 Some(instruction_for(&t))
7546 );
7547
7548 let old = t.instruction.clone();
7551 assert_eq!(
7552 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
7553 Some(resumed_instruction(&old, &t))
7554 );
7555
7556 assert_eq!(
7560 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
7561 None
7562 );
7563 }
7564
7565 #[test]
7566 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
7567 assert_eq!(
7568 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
7569 Starter::Review("magi/eba2/A".to_owned())
7570 );
7571 }
7572
7573 #[test]
7574 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
7575 assert_eq!(
7576 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
7577 Starter::Start,
7578 "a vanished review branch must not fall back to resuming the old run either"
7579 );
7580 }
7581
7582 #[test]
7583 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
7584 let mut t = task();
7585 t.start("old-run".to_owned());
7586 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
7587 t.release();
7588 let branch = t.review_branch.take();
7589 assert_eq!(
7590 choose_starter(branch.as_deref(), true, Some("old-run")),
7591 Starter::Review("magi/eba2/A".to_owned()),
7592 "a review wins over resuming the old run"
7593 );
7594 }
7595
7596 #[test]
7597 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
7598 assert_eq!(
7599 choose_starter(None, false, Some("some-run")),
7600 Starter::Resume("some-run".to_owned())
7601 );
7602 assert_eq!(choose_starter(None, false, None), Starter::Start);
7603 }
7604
7605 #[test]
7606 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
7607 let mut released = task();
7608 released.start("stalled-run".to_owned());
7609 released.requeue();
7610 let unfinished = (!released.fresh_start)
7611 .then(|| Some("stalled-run".to_owned()))
7612 .flatten();
7613 assert_eq!(
7614 choose_starter(None, false, unfinished.as_deref()),
7615 Starter::Start,
7616 "release keeps run history but must not resume it"
7617 );
7618 assert_eq!(released.runs, ["stalled-run"]);
7619 }
7620
7621 #[test]
7622 fn an_ordinary_release_keeps_a_resumable_run_available() {
7623 let mut released = task();
7624 released.start("stalled-run".to_owned());
7625 released.release();
7626 let unfinished = (!released.fresh_start)
7627 .then(|| Some("stalled-run".to_owned()))
7628 .flatten();
7629 assert_eq!(
7630 choose_starter(None, false, unfinished.as_deref()),
7631 Starter::Resume("stalled-run".to_owned()),
7632 "manual release must preserve the normal resume path"
7633 );
7634 }
7635
7636 #[test]
7637 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
7638 let mut state = run_state(RunStatus::Blocked);
7639 state.config.graph.review_rounds = 3;
7640 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
7641 assert!(exhausted_review_budget(&state));
7642
7643 state.reviews.pop();
7645 assert!(!exhausted_review_budget(&state));
7646
7647 let mut stalled = run_state(RunStatus::Stalled);
7650 stalled.config.graph.review_rounds = 1;
7651 stalled.reviews = vec![review_round(1)];
7652 assert!(!exhausted_review_budget(&stalled));
7653 }
7654
7655 fn review_round(round: usize) -> crate::run::ReviewRound {
7656 crate::run::ReviewRound {
7657 round,
7658 head: "deadbeef".to_owned(),
7659 verified_head: None,
7660 verified_at: None,
7661 reviews: Vec::new(),
7662 e2e: Vec::new(),
7663 verify_retried: false,
7664 e2e_deferred: false,
7665 e2e_defer_reason: None,
7666 fix: None,
7667 blocking: 0,
7668 answered: 1,
7669 expected: 1,
7670 clean: false,
7671 progressed: true,
7672 vote_split: false,
7673 reconsideration: Vec::new(),
7674 verdict: None,
7675 }
7676 }
7677
7678 #[test]
7679 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
7680 let mut run = RunState::new(
7681 PathBuf::from("/repo"),
7682 "main".to_owned(),
7683 "abc1234def".to_owned(),
7684 "add retries".to_owned(),
7685 Config::default(),
7686 );
7687 run.status = RunStatus::Judging;
7688 run.parked = true;
7689 let mut task = Task::new(
7690 "add retries".to_owned(),
7691 "add retries".to_owned(),
7692 PathBuf::from("/repo"),
7693 crate::queue::Source::Human,
7694 );
7695 task.status = TaskStatus::Failed;
7696 task.runs = vec![run.id.clone()];
7697 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
7698 assert!(with(&task, &run), "parked after judging is the case");
7699
7700 let mut not_parked = run.clone();
7701 not_parked.parked = false;
7702 not_parked.status = RunStatus::Stalled;
7703 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
7704
7705 let mut fresh = task.clone();
7706 fresh.fresh_start = true;
7707 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
7708
7709 let mut review = task.clone();
7710 review.review_branch = Some("magi/x/A".to_owned());
7711 assert!(!with(&review, &run), "review is ranked before resume");
7712
7713 let mut held = task.clone();
7714 held.status = TaskStatus::Held;
7715 assert!(!with(&held, &run), "a hold stays visible to the conductor");
7716
7717 let mut released = run.clone();
7718 released.released_to = Some("20260901-000000-new1".to_owned());
7719 assert!(!with(&task, &released), "nothing left to resume into");
7720
7721 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
7722 "unreadable"
7723 )));
7724 }
7725
7726 #[test]
7727 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
7728 let mut released = RunState::new(
7729 PathBuf::from("/repo"),
7730 "main".to_owned(),
7731 "abc1234def".to_owned(),
7732 "add retries".to_owned(),
7733 Config::default(),
7734 );
7735 released.status = RunStatus::Blocked;
7736 assert_eq!(
7737 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
7738 Some(released.id.clone())
7739 );
7740 released.released_to = Some("20260901-000000-new1".to_owned());
7741 assert_eq!(
7742 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
7743 None,
7744 "there is nothing left to resume it into"
7745 );
7746 }
7747
7748 #[test]
7749 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
7750 let mut exhausted = RunState::new(
7759 PathBuf::from("/repo"),
7760 "main".to_owned(),
7761 "abc1234def".to_owned(),
7762 "add retries".to_owned(),
7763 Config::default(),
7764 );
7765 exhausted.status = RunStatus::Blocked;
7766 exhausted.config.graph.review_rounds = 1;
7767 exhausted.reviews = vec![review_round(1)];
7768
7769 assert_eq!(
7770 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
7771 None,
7772 "an exhausted `Blocked` run must not be offered as resumable"
7773 );
7774
7775 let mut has_budget_left = RunState::new(
7778 PathBuf::from("/repo"),
7779 "main".to_owned(),
7780 "abc1234def".to_owned(),
7781 "add retries".to_owned(),
7782 Config::default(),
7783 );
7784 has_budget_left.status = RunStatus::Blocked;
7785 has_budget_left.config.graph.review_rounds = 3;
7786 has_budget_left.reviews = vec![review_round(1)];
7787
7788 assert_eq!(
7789 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
7790 Ok(has_budget_left.clone())
7791 }),
7792 Some(has_budget_left.id.clone())
7793 );
7794 }
7795
7796 #[test]
7797 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
7798 let mut older_stalled = RunState::new(
7806 PathBuf::from("/repo"),
7807 "main".to_owned(),
7808 "abc1234def".to_owned(),
7809 "add retries".to_owned(),
7810 Config::default(),
7811 );
7812 older_stalled.status = RunStatus::Stalled;
7813
7814 let mut newest_exhausted = RunState::new(
7815 PathBuf::from("/repo"),
7816 "main".to_owned(),
7817 "abc1234def".to_owned(),
7818 "add retries".to_owned(),
7819 Config::default(),
7820 );
7821 newest_exhausted.status = RunStatus::Blocked;
7822 newest_exhausted.config.graph.review_rounds = 1;
7823 newest_exhausted.reviews = vec![review_round(1)];
7824
7825 assert_eq!(
7826 unfinished_run_with(
7827 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
7828 "t",
7829 |_| Ok(newest_exhausted.clone())
7830 ),
7831 None,
7832 "the newest run is exhausted, so nothing here is worth resuming - \
7833 least of all the older, already-superseded run"
7834 );
7835 }
7836
7837 #[test]
7838 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
7839 assert_eq!(
7840 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
7841 Err(anyhow::anyhow!("fixture is absent"))
7842 }),
7843 None
7844 );
7845 }
7846
7847 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
7848 let mut q = ask::Question::new(
7849 run.to_owned(),
7850 "implement".to_owned(),
7851 "impl-A".to_owned(),
7852 "continue?".to_owned(),
7853 String::new(),
7854 vec!["resume で続行する".to_owned(), "other".to_owned()],
7855 );
7856 q.actions.insert("resume で続行する".to_owned(), action);
7857 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
7858 .unwrap();
7859 q
7860 }
7861
7862 fn held_task_with(run: &str) -> Task {
7863 let mut t = task();
7864 t.runs = vec![run.to_owned()];
7865 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
7866 t
7867 }
7868
7869 fn resume_action(run: &str) -> ask::ChoiceAction {
7870 ask::ChoiceAction::Resume { run: run.into() }
7871 }
7872
7873 #[test]
7874 fn decide_action_resumes_only_the_latest_resumable_run() {
7875 let t = held_task_with("r1");
7876 let q = action_question("r1", resume_action("r1"));
7877 let load = |s: RunState| move |_: &str| Ok(s);
7878 assert_eq!(
7879 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
7880 ActionDecision::Resume("r1".into())
7881 );
7882 let q_other = action_question("r1", resume_action("r0"));
7884 assert!(matches!(
7885 decide_action(
7886 &t,
7887 &q_other,
7888 &PHRASES_EN,
7889 load(run_state(RunStatus::Blocked))
7890 ),
7891 ActionDecision::Refuse(_)
7892 ));
7893 assert!(matches!(
7895 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
7896 ActionDecision::Refuse(_)
7897 ));
7898 let mut released = run_state(RunStatus::Blocked);
7900 released.released_to = Some("elsewhere".into());
7901 assert!(matches!(
7902 decide_action(&t, &q, &PHRASES_EN, load(released)),
7903 ActionDecision::Refuse(_)
7904 ));
7905 assert!(matches!(
7907 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
7908 ActionDecision::Refuse(_)
7909 ));
7910 }
7911
7912 #[test]
7913 fn decide_action_ignores_a_question_about_an_earlier_run() {
7914 let mut t = held_task_with("r1");
7915 t.runs.push("r2".to_owned());
7916 let never = |_: &str| -> Result<RunState> { bail!("not read") };
7917 assert_eq!(
7918 decide_action(
7919 &t,
7920 &action_question("r1", ask::ChoiceAction::Done),
7921 &PHRASES_EN,
7922 never
7923 ),
7924 ActionDecision::Stale
7925 );
7926 }
7927
7928 #[test]
7929 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
7930 let mut t = held_task_with("r1");
7931 let never = |_: &str| -> Result<RunState> { bail!("not read") };
7932 assert_eq!(
7933 decide_action(
7934 &t,
7935 &action_question("r1", ask::ChoiceAction::Requeue),
7936 &PHRASES_EN,
7937 never
7938 ),
7939 ActionDecision::Requeue
7940 );
7941 let done_q = action_question("r1", ask::ChoiceAction::Done);
7942 assert_eq!(
7943 decide_action(&t, &done_q, &PHRASES_EN, never),
7944 ActionDecision::Done
7945 );
7946 t.mark_action_applied(&done_q.id);
7947 assert_eq!(
7948 decide_action(&t, &done_q, &PHRASES_EN, never),
7949 ActionDecision::Skip
7950 );
7951
7952 let mut plain = action_question("r1", ask::ChoiceAction::Done);
7954 plain.actions.clear();
7955 assert_eq!(
7956 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
7957 ActionDecision::Skip
7958 );
7959 let mut running = held_task_with("r1");
7961 running.status = TaskStatus::Running;
7962 assert_eq!(
7963 decide_action(
7964 &running,
7965 &action_question("r1", ask::ChoiceAction::Done),
7966 &PHRASES_EN,
7967 never
7968 ),
7969 ActionDecision::Skip
7970 );
7971 }
7972
7973 #[test]
7974 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
7975 let dir = tempfile::tempdir().unwrap();
7976 let queue = Queue::at(dir.path().join("queue"));
7977 let questions = Questions::at(dir.path().join("questions"));
7978 let home = dir.path().join("home");
7979 let mut state = run_state(RunStatus::Blocked);
7980 state.id = "20260101-000000-act1".to_owned();
7981 state.save_under(&home).unwrap();
7982
7983 let mut t = held_task_with(&state.id);
7984 queue.put(&mut t).unwrap();
7985 let mut q = action_question(&state.id, resume_action(&state.id));
7986 questions.put(&mut q).unwrap();
7987
7988 apply_choice_actions(&queue, &questions, &home);
7989 let after = queue.get(&t.id).unwrap();
7990 assert_eq!(after.status, TaskStatus::Queued);
7991 assert!(!after.fresh_start);
7992 assert!(after.action_applied(&q.id));
7993 let pin = after.resume_override.clone().unwrap();
7994 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
7995 assert!(pin.forced);
7996
7997 let mut again = queue.get(&t.id).unwrap();
7999 again.hold_machine(Some("later".into()));
8000 queue.put(&mut again).unwrap();
8001 apply_choice_actions(&queue, &questions, &home);
8002 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8003 }
8004
8005 #[test]
8006 fn a_delivered_answer_is_still_acted_on_exactly_once() {
8007 let dir = tempfile::tempdir().unwrap();
8008 let queue = Queue::at(dir.path().join("queue"));
8009 let questions = Questions::at(dir.path().join("questions"));
8010 let home = dir.path().join("home");
8011 let mut state = run_state(RunStatus::Blocked);
8012 state.id = "20260101-000000-act2".to_owned();
8013 state.save_under(&home).unwrap();
8014
8015 let mut t = held_task_with(&state.id);
8016 queue.put(&mut t).unwrap();
8017 let mut q = action_question(&state.id, resume_action(&state.id));
8018 q.answer_delivered = true;
8019 questions.put(&mut q).unwrap();
8020
8021 apply_choice_actions(&queue, &questions, &home);
8024 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8025 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
8026
8027 let mut again = queue.get(&t.id).unwrap();
8029 again.hold_machine(Some("later".into()));
8030 queue.put(&mut again).unwrap();
8031 apply_choice_actions(&queue, &questions, &home);
8032 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8033 }
8034
8035 #[test]
8036 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
8037 let dir = tempfile::tempdir().unwrap();
8038 let queue = Queue::at(dir.path().join("queue"));
8039 let questions = Questions::at(dir.path().join("questions"));
8040 let home = dir.path().join("home");
8041 let mut state = run_state(RunStatus::Blocked);
8042 state.id = "20260101-000000-act3".to_owned();
8043 state.save_under(&home).unwrap();
8044 let mut t = held_task_with(&state.id);
8045 queue.put(&mut t).unwrap();
8046 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
8047 questions.put(&mut q).unwrap();
8048
8049 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
8050 apply_choice_actions(&queue, &questions, &home);
8051 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8052
8053 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
8054 apply_choice_actions(&queue, &questions, &home);
8055 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8056 }
8057
8058 #[test]
8059 fn action_standing_tells_the_reasons_apart() {
8060 let mut t = held_task_with("r1");
8061 let q = action_question("r1", ask::ChoiceAction::Requeue);
8062 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
8063 let mut plain = q.clone();
8064 plain.actions.clear();
8065 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
8066
8067 t.mark_action_applied(&q.id);
8069 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
8070
8071 let mut t = held_task_with("r1");
8073 t.start("r2".to_owned());
8074 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
8075 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
8077 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8078 t.status = TaskStatus::Blocked;
8079 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
8080
8081 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
8083 c.node = crate::conduct::NODE.to_owned();
8084 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
8085 assert!(!ActionStanding::Busy.daemon_owns());
8086 }
8087
8088 #[test]
8089 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
8090 let dir = tempfile::tempdir().unwrap();
8091 let queue = Queue::at(dir.path().join("queue"));
8092 let questions = Questions::at(dir.path().join("questions"));
8093 let home = dir.path().join("home");
8094 let mut state = run_state(RunStatus::Blocked);
8095 state.id = "20260101-000000-act4".to_owned();
8096 state.save_under(&home).unwrap();
8097 let mut t = held_task_with(&state.id);
8098 t.status = TaskStatus::Running;
8099 queue.put(&mut t).unwrap();
8100 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
8101 q.cwd = Some(dir.path().display().to_string());
8102 questions.put(&mut q).unwrap();
8103
8104 let running = queue.get(&t.id).unwrap();
8107 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
8108 assert!(matches!(
8109 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
8110 crate::waiter::Action::Deliver(_)
8111 ));
8112 apply_choice_actions(&queue, &questions, &home);
8114 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8115 let mut back = queue.get(&t.id).unwrap();
8116 back.hold_machine(Some("later".into()));
8117 queue.put(&mut back).unwrap();
8118 apply_choice_actions(&queue, &questions, &home);
8119 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
8120 let mut again = queue.get(&t.id).unwrap();
8121 again.hold_machine(Some("again".into()));
8122 queue.put(&mut again).unwrap();
8123 apply_choice_actions(&queue, &questions, &home);
8124 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8125 }
8126}