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