1use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71pub const SCHEMA: u32 = 1;
73
74pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79pub const STALE_SECS: i64 = 30;
88
89pub const POLL: Duration = Duration::from_secs(5);
91
92pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 pub task: String,
123 pub run: String,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 pub schema: u32,
137 pub pid: u32,
139 pub started_at: Timestamp,
141 pub updated_at: Timestamp,
143 pub idle: bool,
145 pub current: Vec<Current>,
151 pub completed: usize,
153 pub polls: u64,
155}
156
157impl Status {
158 #[must_use]
160 pub fn new() -> Self {
161 let now = Timestamp::now();
162 Self {
163 schema: SCHEMA,
164 pid: std::process::id(),
165 started_at: now,
166 updated_at: now,
167 idle: true,
168 current: Vec::new(),
169 completed: 0,
170 polls: 0,
171 }
172 }
173}
174
175impl Default for Status {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180
181#[derive(Debug, Clone)]
183pub struct Opts {
184 pub repo: PathBuf,
186 pub config: Option<PathBuf>,
188 pub poll: Duration,
190 pub max_attempts: usize,
192 pub once: bool,
194 pub merge: Option<String>,
196 pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208 fn default() -> Self {
209 Self {
210 repo: PathBuf::from("."),
211 config: None,
212 poll: POLL,
213 max_attempts: 2,
214 once: false,
215 merge: None,
216 worktrees_root: None,
217 }
218 }
219}
220
221fn max_concurrent(n: usize) -> usize {
226 n.max(1)
227}
228
229#[must_use]
231pub fn status_path() -> PathBuf {
232 crate::run::home().join("daemon.json")
233}
234
235pub fn write_status(status: &Status) -> Result<()> {
237 write_status_to(&status_path(), status)
238}
239
240pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247 }
248 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249 let tmp = path.with_extension("json.tmp");
250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252 Ok(())
253}
254
255pub fn clear_status() {
258 clear_status_at(&status_path());
259}
260
261fn clear_status_at(path: &Path) {
265 let _ = std::fs::remove_file(path);
266}
267
268#[derive(Debug, Clone, Default)]
281pub struct Stop {
282 stopped: Arc<AtomicBool>,
286 busy: Arc<std::sync::atomic::AtomicUsize>,
292 wake: Arc<Notify>,
296 pause: crate::graph::Pause,
299}
300
301impl Stop {
302 #[must_use]
304 pub fn new() -> Self {
305 Self::default()
306 }
307
308 pub fn stop(&self) {
311 self.stopped.store(true, Ordering::SeqCst);
312 self.wake.notify_one();
316 }
317
318 #[must_use]
320 pub fn stopped(&self) -> bool {
321 self.stopped.load(Ordering::SeqCst)
322 }
323
324 #[must_use]
332 pub fn finishing(&self) -> bool {
333 self.stopped() && self.busy_now()
334 }
335
336 pub fn park(&self, cause: crate::run::ParkCause) {
347 self.pause.park_for(cause);
348 self.stop();
349 }
350
351 #[must_use]
353 pub fn parking(&self) -> bool {
354 self.pause.parked()
355 }
356
357 #[must_use]
359 pub fn pause(&self) -> crate::graph::Pause {
360 self.pause.clone()
361 }
362
363 #[must_use]
369 pub fn busy_now(&self) -> bool {
370 self.busy.load(Ordering::SeqCst) > 0
371 }
372
373 fn enter(&self) {
375 self.busy.fetch_add(1, Ordering::SeqCst);
376 }
377
378 fn exit(&self) {
381 self.busy.fetch_sub(1, Ordering::SeqCst);
382 }
383
384 async fn idle(&self, poll: Duration) {
386 tokio::select! {
387 () = tokio::time::sleep(poll) => {}
388 () = self.wake.notified() => {}
389 }
390 }
391}
392
393#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402 pub schema: u32,
404 pub pid: Option<u32>,
406 pub started_at: Option<Timestamp>,
408 pub updated_at: Option<Timestamp>,
410 pub idle: bool,
412 #[serde(deserialize_with = "de_current")]
424 pub current: Vec<Current>,
425 pub completed: u64,
427 pub polls: u64,
429}
430
431fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435 D: serde::Deserializer<'de>,
436{
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum Shape {
440 Many(Vec<Current>),
441 One(Current),
442 }
443 Ok(
444 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445 Shape::Many(v) => v,
446 Shape::One(c) => vec![c],
447 }),
448 )
449}
450
451impl Reading {
452 #[must_use]
455 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456 self.updated_at
457 .map(|at| (now.as_second() - at.as_second()).max(0))
458 }
459
460 #[must_use]
464 pub fn running(&self, now: Timestamp) -> bool {
465 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466 }
467}
468
469#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478 serde_json::from_str(&body).ok()
479}
480
481#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494 read_status(home)
495 .filter(|reading| reading.running(now))
496 .map(|reading| reading.current)
497 .unwrap_or_default()
498}
499
500#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503 current_work(home, now).iter().any(|c| c.run == run)
504}
505
506#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517 current_work(home, now)
518 .iter()
519 .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525 current_work(home, now).iter().any(|c| c.task == task)
526}
527
528pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580 F: Fn(u32) -> bool,
581{
582 let this_process = std::process::id();
583 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584 .into_iter()
585 .flatten()
586 .flatten()
587 .map(|e| e.path())
588 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589 .filter(|p| {
590 match std::fs::read_to_string(p)
591 .ok()
592 .and_then(|body| body.trim().parse::<u32>().ok())
593 {
594 Some(pid) if pid == this_process => false,
598 Some(pid) => !pid_alive(pid),
599 None => p
600 .metadata()
601 .and_then(|m| m.modified())
602 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603 .is_ok_and(|age| age >= older_than),
604 }
605 })
606 .filter(|p| std::fs::remove_file(p).is_ok())
607 .filter_map(|p| {
608 p.file_stem()
609 .and_then(|s| s.to_str())
610 .map(std::borrow::ToOwned::to_owned)
611 })
612 .collect();
613 swept.sort_unstable();
614 swept
615}
616
617fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622 task.status == TaskStatus::Running
623 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624 && !is_working_on_task(home, &task.id, now)
625}
626
627fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630 queue
631 .list()
632 .into_iter()
633 .filter(|t| is_stalled(t, home, now))
634 .collect()
635}
636
637fn queued_tasks(queue: &Queue) -> Vec<Task> {
643 queue
644 .list()
645 .into_iter()
646 .filter(|t| t.status == TaskStatus::Queued)
647 .collect()
648}
649
650fn finished_tasks(queue: &Queue) -> Vec<Task> {
653 queue
654 .list()
655 .into_iter()
656 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657 .collect()
658}
659
660fn resolve_blockers(queue: &Queue, questions: &Questions) {
677 for listed in queue.list() {
678 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679 continue;
680 }
681 let Ok(_claim) = queue.claim(&listed.id) else {
682 continue;
683 };
684 let Ok(mut task) = queue.get(&listed.id) else {
685 continue;
686 };
687 if task.status != TaskStatus::Blocked {
688 continue;
689 }
690 let deleted = queue.apply_deleted_blockers(&mut task, questions);
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 let mut cause = missing.clone();
707 cause.sort();
708 cause.dedup();
709 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
710 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
711 &task.blocked_by,
712 &missing,
713 &language,
714 )));
715 record(queue, &mut task);
716 continue;
717 }
718 if let Some(q) = task.blocked_by.iter().find_map(|id| {
721 let crate::queue::Dependency::Question(full) =
722 crate::queue::dependency(queue, questions, id)
723 else {
724 return None;
725 };
726 questions.get(&full).ok().filter(|q| {
727 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
728 })
729 }) {
730 let language = language_of(&task, Path::new("."));
731 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
732 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
733 record(queue, &mut task);
734 continue;
735 }
736 let mut changed = false;
737 for id in task.blocked_by.clone() {
738 let resolved = crate::queue::dependency(queue, questions, &id);
739 if let crate::queue::Dependency::Task(full) = &resolved {
740 if queue
741 .get(full)
742 .is_ok_and(|dep| dep.status == TaskStatus::Done)
743 {
744 task.unblock(&id);
745 changed = true;
746 }
747 continue;
748 }
749 if let crate::queue::Dependency::Question(full) = resolved
750 && let Ok(q) = questions.get(&full)
751 && q.status == ask::QuestionStatus::Answered
752 {
753 let answer = match &q.answer {
754 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
755 None => String::new(),
756 };
757 task.record_answer(q.summary.clone(), answer);
758 task.unblock(&id);
759 changed = true;
760 }
761 }
762 if changed {
763 record(queue, &mut task);
764 }
765 }
766}
767
768fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
770 if crate::lang::is_japanese(language) {
771 format!(
772 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
773 q.short(),
774 q.summary
775 )
776 } else {
777 format!(
778 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
779 q.short(),
780 q.summary
781 )
782 }
783}
784
785#[derive(Debug, Clone, Copy, PartialEq, Eq)]
788pub(crate) enum ActionStanding {
789 NoAction,
791 Pending,
793 Applied,
796 Stale,
798 Busy,
800}
801
802impl ActionStanding {
803 pub(crate) fn daemon_owns(self) -> bool {
805 matches!(self, Self::Pending | Self::Applied | Self::Stale)
806 }
807}
808
809pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
813 if q.chosen_action().is_none() {
814 ActionStanding::NoAction
815 } else if task.action_applied(&q.id) {
816 ActionStanding::Applied
817 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
818 ActionStanding::Stale
819 } else if matches!(
820 task.status,
821 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
822 ) {
823 ActionStanding::Busy
824 } else {
825 ActionStanding::Pending
826 }
827}
828
829#[derive(Debug, Clone, PartialEq, Eq)]
831enum ActionDecision {
832 Skip,
834 Resume(String),
836 Requeue,
838 Done,
840 Stale,
843 Refuse(String),
846}
847
848fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
856where
857 F: FnOnce(&str) -> Result<RunState>,
858{
859 let Some(action) = q.chosen_action() else {
860 return ActionDecision::Skip;
861 };
862 if task.action_applied(&q.id)
863 || matches!(
864 task.status,
865 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
866 )
867 {
868 return ActionDecision::Skip;
869 }
870 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
873 return ActionDecision::Stale;
874 }
875 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
876 let decision_at = if repair {
880 q.answered_at.unwrap_or(q.asked_at)
881 } else {
882 q.asked_at
883 };
884 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
885 return if repair {
886 ActionDecision::Refuse(format!(
887 "repair answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if repair is still wanted, explicitly release the existing owner with `magi task release {}`",
888 q.id, q.run, task.id
889 ))
890 } else {
891 ActionDecision::Stale
892 };
893 }
894 match action {
895 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
896 ask::ChoiceAction::Done => ActionDecision::Done,
897 ask::ChoiceAction::Resume { run } => {
898 if task.runs.last() != Some(run) {
899 return ActionDecision::Refuse((p.resume_not_latest)(
900 q.short(),
901 ask::short_id(run),
902 ));
903 }
904 match load(run) {
905 Ok(s)
906 if q.node == land::APPROVAL_NODE
907 && q.resolution().as_deref() == Some(land::REPAIR) =>
908 {
909 if s.merge_repairs.iter().any(|r| r.question == q.id)
910 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
911 {
912 ActionDecision::Stale
915 } else if s.liveness(false) == Liveness::Live {
916 ActionDecision::Skip
917 } else if s.status != RunStatus::Landing
918 || s.released()
919 || !land::repair_available(&s)
920 || !implementers_match(task, &s)
921 || !s
922 .land_approval
923 .as_ref()
924 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
925 {
926 ActionDecision::Refuse(format!(
927 "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
928 q.id, run, run
929 ))
930 } else {
931 ActionDecision::Resume(run.clone())
932 }
933 }
934 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
935 ActionDecision::Resume(run.clone())
936 }
937 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
938 q.short(),
939 ask::short_id(run),
940 )),
941 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
942 q.short(),
943 ask::short_id(run),
944 &format!("{e:#}"),
945 )),
946 }
947 }
948 }
949}
950
951struct Phrases {
965 graph_stopped: fn(&str, &str) -> String,
967 quorum_lost: &'static str,
968 quota_took_out: &'static str,
970 run_ended: &'static str,
972 waiting_for_answer: &'static str,
974 recovered_running: &'static str,
975 no_run_to_recover: &'static str,
976 could_not_start: &'static str,
977 resume_not_latest: fn(&str, &str) -> String,
978 resume_cannot_progress: fn(&str, &str) -> String,
979 resume_unreadable: fn(&str, &str, &str) -> String,
980 handover_refused: fn(&crate::handover::Refused) -> String,
983 handover_hint: &'static str,
985 reviewers_never_answered: fn(usize, usize) -> String,
988}
989
990const PHRASES_EN: Phrases = Phrases {
991 graph_stopped: |status, detail| {
992 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
993 },
994 quorum_lost: "the judging panel lost its quorum",
995 quota_took_out: "; quota took out ",
996 run_ended: "run ended ",
997 waiting_for_answer: " - waiting for operator answer to question ",
998 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
999 no_run_to_recover: "task was `running` with no live daemon and no readable \
1000 run to recover; held for a human to check what happened",
1001 could_not_start: "could not start the run: ",
1002 resume_not_latest: |q, run| {
1003 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1004 },
1005 resume_cannot_progress: |q, run| {
1006 format!("question {q} asked to resume run {run}, which cannot make progress")
1007 },
1008 resume_unreadable: |q, run, e| {
1009 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1010 },
1011 handover_refused: |r| r.to_string(),
1012 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1013 reviewers_never_answered: |missing, rounds| {
1014 format!(
1015 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1016 refusing to call it clean"
1017 )
1018 },
1019};
1020
1021const PHRASES_JA: Phrases = Phrases {
1022 graph_stopped: |status, detail| {
1023 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1024 },
1025 quorum_lost: "審査パネルが定足数を失いました",
1026 quota_took_out: "。クォータで脱落: ",
1027 run_ended: "run 終了: ",
1028 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1029 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1030 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1031 何が起きたか人が確認するため保留にしました",
1032 could_not_start: "run を開始できませんでした: ",
1033 resume_not_latest: |q, run| {
1034 format!(
1035 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1036 )
1037 },
1038 resume_cannot_progress: |q, run| {
1039 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1040 },
1041 resume_unreadable: |q, run, e| {
1042 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1043 },
1044 handover_refused: |r| {
1045 use crate::handover::Refused;
1046 match r {
1047 Refused::Foreign { branch, path, why } => format!(
1048 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1049 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1050 から、やり直してください(詳細: {why})"
1051 ),
1052 Refused::Unsafe { branch, path, why } => format!(
1053 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1054 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1055 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1056 ),
1057 Refused::ReleaseFailed { branch, path, run } => format!(
1058 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1059 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1060 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1061 ),
1062 }
1063 },
1064 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1065 reviewers_never_answered: |missing, rounds| {
1066 format!(
1067 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1068 クリーンとは認めません"
1069 )
1070 },
1071};
1072
1073fn phrases(language: &str) -> &'static Phrases {
1074 if crate::lang::is_japanese(language) {
1075 &PHRASES_JA
1076 } else {
1077 &PHRASES_EN
1078 }
1079}
1080
1081fn language_of(task: &Task, fallback: &Path) -> String {
1085 crate::lang::of_repo(&repo_for(task, fallback))
1086}
1087
1088pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1092 if q.node == crate::conduct::NODE {
1093 return tasks.iter().find(|t| t.id == q.run);
1094 }
1095 tasks.iter().find(|t| t.runs.contains(&q.run))
1096}
1097
1098pub(crate) fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1107 let tasks = queue.list();
1108 for q in questions.list() {
1109 if q.chosen_action().is_none() {
1110 continue;
1111 }
1112 let Some(listed) = task_of_question(&tasks, &q) else {
1113 if q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR) {
1114 notices::raise_in(
1115 home,
1116 Notice::warn(
1117 &format!("repair-owner:{}", q.id),
1118 format!(
1119 "Repair is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing repair task.",
1120 q.run, q.run
1121 ),
1122 ),
1123 );
1124 }
1125 continue;
1126 };
1127 if listed.action_applied(&q.id) {
1128 continue;
1129 }
1130 let Ok(_claim) = queue.claim(&listed.id) else {
1131 continue;
1132 };
1133 let Ok(mut task) = queue.get(&listed.id) else {
1134 continue;
1135 };
1136 let language = language_of(&task, Path::new("."));
1137 let decision = decide_action(&task, &q, phrases(&language), |id| {
1138 RunState::load_under(id, home)
1139 });
1140 let ran = matches!(
1141 decision,
1142 ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1143 );
1144 if ran && asker_may_still_read(questions, &q, home) {
1145 continue;
1154 }
1155 let done = matches!(decision, ActionDecision::Done);
1156 match decision {
1157 ActionDecision::Skip => continue,
1158 ActionDecision::Resume(run) => {
1159 task.release_operator("choice", Some(&q.id));
1160 task.resume_override = Some(crate::queue::OperatorResume {
1161 question_id: q.id.clone(),
1162 at: Timestamp::now(),
1163 conductor_rehold: None,
1164 forced: true,
1165 pinned_run: Some(run),
1166 });
1167 }
1168 ActionDecision::Stale => {}
1169 ActionDecision::Requeue => {
1170 task.release_operator("choice-requeue", Some(&q.id));
1171 task.requeue();
1172 }
1173 ActionDecision::Done => task.succeed(),
1174 ActionDecision::Refuse(why) => {
1175 if task.operator_held() {
1176 task.hold_reason = Some(match task.hold_reason.take() {
1179 Some(reason) => format!("{reason}\n\n{why}"),
1180 None => why,
1181 });
1182 } else {
1183 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1184 task.hold_machine(Some(why));
1185 }
1186 notices::raise(
1187 Notice::warn(
1188 &format!("action:{}", q.id),
1189 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1190 )
1191 .link(Link::Task {
1192 id: task.id.clone(),
1193 }),
1194 );
1195 }
1196 }
1197 task.mark_action_applied(&q.id);
1198 record(queue, &mut task);
1201 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1202 supersede_prior_runs(&task, home);
1203 }
1204 let _ = questions.update(&q.id, |r| {
1207 r.answer_delivered = true;
1208 Ok(())
1209 });
1210 }
1211}
1212
1213fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1217 let now = Timestamp::now();
1218 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1219 return true;
1220 }
1221 q.node != crate::conduct::NODE
1222 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1223 s.seats_active()
1224 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1225 })
1226}
1227
1228fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1239 let tasks = queue.list();
1240 let by_id: std::collections::BTreeMap<&str, &Task> =
1241 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1242 let referenced: Vec<&str> = tasks
1243 .iter()
1244 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1245 .collect();
1246
1247 for mut question in questions.list() {
1248 if !question.status.open() || question.node != crate::conduct::NODE {
1249 continue;
1250 }
1251 if referenced
1256 .iter()
1257 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1258 {
1259 continue;
1260 }
1261 let Some(task) = by_id.get(question.run.as_str()) else {
1262 continue;
1263 };
1264 question.abandon(format!(
1265 "task {} no longer waits for this answer",
1266 task.short()
1267 ));
1268 if let Err(e) = questions.put(&mut question) {
1269 tracing::warn!(
1270 "could not retire question {} for task {}: {e:#}",
1271 question.short(),
1272 task.short()
1273 );
1274 }
1275 }
1276}
1277
1278#[derive(Debug, Clone, Copy)]
1285pub struct Verdict {
1286 pub status: RunStatus,
1288 pub left_pr: bool,
1290 pub quota_hit: bool,
1292 pub parked: bool,
1294 pub no_viable_candidates: bool,
1301}
1302
1303pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1360 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1361}
1362
1363fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1365 if verdict.parked {
1371 task.park(detail);
1372 return;
1373 }
1374 match verdict.status {
1375 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1376 RunStatus::AlreadyInBase => task.already_landed(detail),
1377 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1378 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1379 task.stall(detail)
1380 }
1381 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1382 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1383 RunStatus::Blocked => task.fail(detail, max_attempts),
1384 RunStatus::VerifiedNoop => task.handed_off(detail),
1385 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1386 }
1387}
1388
1389pub fn supersede_prior_runs(task: &Task, home: &Path) {
1438 let now = Timestamp::now();
1439 let last_run_succeeded = task
1446 .runs
1447 .last()
1448 .and_then(|id| RunState::load_under(id, home).ok())
1449 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1450 for id in task.superseded_attempts(last_run_succeeded) {
1451 let mut state = match RunState::load_under(id, home) {
1452 Ok(s) => s,
1453 Err(e) => {
1454 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1455 continue;
1456 }
1457 };
1458 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1459 continue;
1460 }
1461 let daemon_claims = is_working_on(home, id, now);
1462 if state.liveness(daemon_claims) == Liveness::Live {
1463 continue;
1464 }
1465 state.status = RunStatus::Superseded;
1466 if let Err(e) = state.save_under(home) {
1467 tracing::warn!("could not mark run {id} superseded: {e:#}");
1468 }
1469 }
1470}
1471
1472fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1494 for task in queue.list() {
1495 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1496 continue;
1497 }
1498 supersede_prior_runs(&task, home);
1499 }
1500}
1501
1502fn settle_and_diagnose(
1509 task: &mut Task,
1510 verdict: Verdict,
1511 detail: &str,
1512 max_attempts: usize,
1513 state: &RunState,
1514) {
1515 let p = phrases(&state.config.graph.language);
1516 let attempts_before = task.attempts;
1517 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1523 task.notice_cause(
1524 &format!("resource:{}:{}", block.kind, block.node),
1525 None,
1526 None,
1527 );
1528 task.last_error = Some(detail.to_owned());
1529 task.diagnostic = None;
1530 task.attempts = task.attempts.saturating_sub(1);
1531 task.hold_machine(Some(format!(
1532 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1533 no agent was asked and no attempt was spent",
1534 crate::cache::RESOURCE_HOLD,
1535 block.kind,
1536 block.node
1537 )));
1538 if let Some(pass) = state.passes.last() {
1539 task.record_pass(&state.id, pass.index, attempts_before, None);
1540 }
1541 return;
1542 }
1543 let unresolved = task.hold_notice_cause.clone();
1544 settle_in(task, verdict, detail, max_attempts, p);
1545 if state.prep_failure.is_some() {
1546 task.hold_notice_cause = unresolved;
1549 task.startup_notice_cause("startup-candidates");
1550 }
1551 if let Some(pass) = state.passes.last() {
1554 let parked = match &pass.end {
1555 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1556 _ => None,
1557 };
1558 task.record_pass(&state.id, pass.index, attempts_before, parked);
1559 }
1560 if task.status == TaskStatus::Held {
1561 if state.prep_failure.is_none() {
1562 task.notice_cause(
1563 label(verdict.status),
1564 Some(&state.id),
1565 state.passes.last().map(|p| p.index),
1566 );
1567 }
1568 task.diagnostic = diagnostic(state);
1569 note_open_question(task, &state.id, p);
1570 }
1571}
1572
1573fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1588 let Some(home) = crate::run::try_home() else {
1589 return;
1590 };
1591 let open = Questions::at(home.join("questions")).open_for(run);
1592 let Some(q) = open.first() else {
1593 return;
1594 };
1595 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
1596 decisions.sort_unstable();
1597 task.notice_cause(
1598 &format!("questions:{}", decisions.join(",")),
1599 Some(run),
1600 None,
1601 );
1602 let base = task.hold_reason.clone().unwrap_or_default();
1603 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1604}
1605
1606fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1617 match last_run {
1618 Some(state) => {
1619 let verdict = Verdict {
1620 status: state.status,
1621 left_pr: state.pr.is_some(),
1622 quota_hit: !state.quota.is_empty(),
1623 parked: state.parked,
1624 no_viable_candidates: state.viable().is_empty(),
1625 };
1626 let detail = format!(
1627 "{}{}",
1628 phrases(&state.config.graph.language).recovered_running,
1629 describe(&state)
1630 );
1631 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1632 }
1633 None => {
1634 let why = phrases(language).no_run_to_recover;
1637 task.last_error = Some(why.to_owned());
1638 task.notice_cause("missing-run", None, None);
1641 task.hold_machine(Some(why.to_owned()));
1642 }
1643 }
1644}
1645
1646fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1668 let mut reclaimed = Vec::new();
1669 for listed in queue.list() {
1670 if listed.status != TaskStatus::Running {
1671 continue;
1672 }
1673 let Ok(_claim) = queue.claim(&listed.id) else {
1674 continue;
1675 };
1676 let Ok(mut task) = queue.get(&listed.id) else {
1680 continue;
1681 };
1682 if task.status != TaskStatus::Running {
1683 continue;
1684 }
1685 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1686 if let Some(state) = &last_run
1696 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1697 {
1698 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1699 }
1700 let language = if last_run.is_none() {
1701 language_of(&task, Path::new("."))
1702 } else {
1703 String::new()
1704 };
1705 reclaim(&mut task, last_run, max_attempts, &language);
1706 if task.status == TaskStatus::Done {
1707 supersede_prior_runs(&task, &crate::run::home());
1708 }
1709 record(queue, &mut task);
1710 reclaimed.push(task.id.clone());
1711 }
1712 reclaimed
1713}
1714
1715fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1747 reclaim_abandoned_runs_with(
1748 home,
1749 now,
1750 crate::proc::pid_status,
1751 crate::proc::process_started_at,
1752 )
1753}
1754
1755fn reclaim_abandoned_runs_with<F, G>(
1761 home: &Path,
1762 now: Timestamp,
1763 query: F,
1764 identity: G,
1765) -> Vec<String>
1766where
1767 F: Fn(u32) -> Option<bool>,
1768 G: Fn(u32) -> Option<String>,
1769{
1770 let mut abandoned = Vec::new();
1771 for entry in std::fs::read_dir(home.join("runs"))
1772 .into_iter()
1773 .flatten()
1774 .flatten()
1775 {
1776 let id = entry.file_name().to_string_lossy().into_owned();
1777 if !crate::run::is_run_id(&id) {
1778 continue;
1779 }
1780 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1788 continue;
1789 };
1790 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1791 continue;
1792 };
1793 if state.status.done() || !state.active_all_overrun(now) {
1794 continue;
1795 }
1796 let daemon_claims = is_working_on(home, &id, now);
1808 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1809 continue;
1810 }
1811 state.abandon("daemon");
1812 if let Err(e) = state.save_under(home) {
1813 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1814 continue;
1815 }
1816 if let Some(notice) = notices::run_ended(&state) {
1819 notices::raise_in(home, notice);
1820 }
1821 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1829 tracing::warn!("abandon questions for {id}: {e:#}");
1830 }
1831 abandoned.push(id);
1832 }
1833 abandoned
1834}
1835
1836pub async fn serve(opts: Opts) -> Result<()> {
1842 serve_until(opts, Stop::new()).await
1843}
1844
1845pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1862 let signal = {
1863 let stop = stop.clone();
1864 tokio::spawn(async move {
1865 if tokio::signal::ctrl_c().await.is_ok() {
1866 stop.stop();
1867 tracing::info!("shutdown requested; a run in flight will be finished first");
1868 }
1869 })
1870 };
1871
1872 let worktrees_root = opts
1873 .worktrees_root
1874 .clone()
1875 .unwrap_or_else(crate::run::default_worktree_root);
1876 let outcome = drive(
1877 &opts,
1878 &Queue::open(),
1879 &status_path(),
1880 &crate::run::home(),
1881 &worktrees_root,
1882 &stop,
1883 )
1884 .await;
1885
1886 signal.abort();
1887 outcome
1888}
1889
1890async fn drive(
1903 opts: &Opts,
1904 queue: &Queue,
1905 status_file: &Path,
1906 home: &Path,
1907 worktrees_root: &Path,
1908 stop: &Stop,
1909) -> Result<()> {
1910 let status = Arc::new(Mutex::new(Status::new()));
1918 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1919 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1920
1921 let daemon_cfg = prepare(&opts.repo, opts)
1927 .map(|c| c.daemon)
1928 .unwrap_or_default();
1929 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1930
1931 let waiter = tokio::spawn(crate::waiter::run(
1936 crate::waiter::Waiter::new(
1937 crate::ask::Questions::at(home.join("questions")),
1938 home.to_path_buf(),
1939 prepare(&opts.repo, opts).ok(),
1940 ),
1941 stop.clone(),
1942 ));
1943
1944 let deputies = tokio::spawn(crate::deputy::run(
1948 crate::deputy::Deputies::new(
1949 crate::ask::Questions::at(home.join("questions")),
1950 home.to_path_buf(),
1951 prepare(&opts.repo, opts).ok(),
1952 opts.repo.clone(),
1953 daemon_cfg.max_deputies,
1954 {
1955 let stop = stop.clone();
1956 Arc::new(move || stop.parking())
1957 },
1958 ),
1959 stop.clone(),
1960 ));
1961
1962 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1965
1966 let release_watch = tokio::spawn(crate::release_watch::run(
1969 crate::release_watch::Watcher::new(
1970 Box::new(crate::release_watch::GhForge),
1971 home.to_path_buf(),
1972 ),
1973 {
1974 let (repo, opts) = (opts.repo.clone(), opts.clone());
1975 move || release_watch_settings(&repo, &opts)
1976 },
1977 stop.clone(),
1978 ));
1979
1980 tracing::info!(
1981 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1982 queue.root().display(),
1983 opts.poll.as_secs(),
1984 opts.max_attempts,
1985 concurrency,
1986 if daemon_cfg.pause_for_interrupts {
1987 ", interrupts enabled"
1988 } else {
1989 ""
1990 }
1991 );
1992
1993 janitor(&opts.repo, opts, home, worktrees_root).await;
1996 resweep_superseded_attempts(queue, home);
1997
1998 let outcome = poll(
1999 opts,
2000 queue,
2001 &status,
2002 home,
2003 worktrees_root,
2004 stop,
2005 DispatchLimits {
2006 max_concurrent: concurrency,
2007 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2008 },
2009 )
2010 .await;
2011
2012 beat.abort();
2013 waiter.abort();
2014 deputies.abort();
2015 fetcher.abort();
2016 release_watch.abort();
2017 clear_status_at(status_file);
2018 outcome
2019}
2020
2021fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2024 let Ok(cfg) = prepare(repo, opts) else {
2025 return (Vec::new(), 0);
2026 };
2027 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2028 .into_iter()
2029 .map(|r| r.path)
2030 .collect();
2031 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2034 let runs = crate::run::home().join("runs");
2035 for id in crate::run::list_ids_in(&runs) {
2036 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2037 .ok()
2038 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2039 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2040 known.extend(repo);
2041 }
2042 for k in known {
2043 let k = k.canonicalize().unwrap_or(k);
2044 if k.join(".git").exists() && !paths.contains(&k) {
2045 paths.push(k);
2046 }
2047 }
2048 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2049 if !paths.contains(&own) {
2050 paths.push(own);
2051 }
2052 (paths, cfg.daemon.release_stall_minutes)
2053}
2054
2055const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2057
2058async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2062 while !stop.stopped() {
2063 let (interval, roots) = match prepare(&repo, &opts) {
2064 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2065 Err(_) => (0, Vec::new()),
2066 };
2067 if interval > 0 && !roots.is_empty() {
2068 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2069 tracing::debug!("fetch origins: {r:?}");
2070 }
2071 let wait = if interval > 0 { interval } else { 60 };
2073 let mut slept = 0;
2074 while slept < wait && !stop.stopped() {
2075 tokio::time::sleep(Duration::from_secs(1)).await;
2076 slept += 1;
2077 }
2078 }
2079}
2080
2081async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2087 loop {
2088 tokio::time::sleep(HEARTBEAT).await;
2089 let snapshot = {
2090 let mut guard = lock(&status);
2091 guard.updated_at = Timestamp::now();
2092 guard.clone()
2093 };
2094 if let Err(e) = write_status_to(&path, &snapshot) {
2095 tracing::warn!("could not refresh the daemon status file: {e:#}");
2098 }
2099 }
2100}
2101
2102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2105enum LandResume {
2106 NotLanding,
2109 StillWaiting,
2114 Ready,
2118}
2119
2120fn land_resume_state(task: &Task) -> LandResume {
2124 let Some(run_id) = task.runs.last() else {
2125 return LandResume::NotLanding;
2126 };
2127 let Ok(state) = RunState::load(run_id) else {
2128 return LandResume::NotLanding;
2129 };
2130 if !implementers_match(task, &state) || !state.parked {
2131 return LandResume::NotLanding;
2132 }
2133 let node = if state.status == RunStatus::Landing {
2137 land::APPROVAL_NODE
2138 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2139 crate::github_text::ASK_NODE
2140 } else {
2141 return LandResume::NotLanding;
2142 };
2143 let store = ask::Questions::open();
2144 let waiting = store
2145 .list()
2146 .into_iter()
2147 .filter(|q| &q.run == run_id && q.node == node)
2148 .max_by(|a, b| a.id.cmp(&b.id));
2149 let Some(mut q) = waiting else {
2150 return LandResume::Ready;
2151 };
2152 if !q.status.open() {
2153 if q.resolution().as_deref() == Some(land::REPAIR) {
2156 return if state.liveness(false) == Liveness::Live {
2157 LandResume::StillWaiting
2158 } else {
2159 LandResume::NotLanding
2160 };
2161 }
2162 return LandResume::Ready;
2163 }
2164 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2171 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2172 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2173 q.abandon(format!(
2174 "no answer within {}s of asking",
2175 timeout.as_secs().max(1)
2176 ));
2177 if store.put(&mut q).is_ok() {
2180 return LandResume::Ready;
2181 }
2182 }
2183 LandResume::StillWaiting
2184}
2185
2186const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2194
2195const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2207
2208struct InFlightGuard<'a> {
2221 status: &'a Arc<Mutex<Status>>,
2222 stop: &'a Stop,
2223 task_id: &'a str,
2224}
2225
2226impl Drop for InFlightGuard<'_> {
2227 fn drop(&mut self) {
2228 lock(self.status).current.retain(|c| c.task != self.task_id);
2229 self.stop.exit();
2230 }
2231}
2232
2233#[derive(Debug, Clone, PartialEq, Eq)]
2255enum Interrupt {
2256 Idle,
2258 Parking {
2270 parked: Vec<String>,
2271 interrupt_task: String,
2272 },
2273 Running {
2281 parked: Vec<String>,
2282 interrupt_task: String,
2283 },
2284 Resuming { parked: Vec<String> },
2291}
2292
2293fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2314 match state {
2315 Interrupt::Idle => {
2316 if in_flight.len() != 1 {
2328 return Interrupt::Idle;
2329 }
2330 match runnable.iter().find(|t| t.interrupt) {
2331 Some(t) => Interrupt::Parking {
2332 parked: in_flight.to_vec(),
2333 interrupt_task: t.id.clone(),
2334 },
2335 None => Interrupt::Idle,
2336 }
2337 }
2338 Interrupt::Parking {
2339 parked,
2340 interrupt_task,
2341 } => {
2342 if in_flight.iter().any(|id| parked.contains(id)) {
2343 Interrupt::Parking {
2345 parked,
2346 interrupt_task,
2347 }
2348 } else if in_flight.contains(&interrupt_task) {
2349 Interrupt::Running {
2350 parked,
2351 interrupt_task,
2352 }
2353 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2354 Interrupt::Parking {
2358 parked,
2359 interrupt_task,
2360 }
2361 } else {
2362 Interrupt::Resuming { parked }
2367 }
2368 }
2369 Interrupt::Running {
2370 parked,
2371 interrupt_task,
2372 } => {
2373 if in_flight.contains(&interrupt_task) {
2374 Interrupt::Running {
2375 parked,
2376 interrupt_task,
2377 }
2378 } else {
2379 Interrupt::Resuming { parked }
2385 }
2386 }
2387 Interrupt::Resuming { parked } => {
2388 if in_flight.iter().any(|id| parked.contains(id)) {
2389 Interrupt::Idle
2395 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2396 Interrupt::Resuming { parked }
2397 } else {
2398 Interrupt::Idle
2401 }
2402 }
2403 }
2404}
2405
2406fn advance_interrupt_tick(
2412 enabled: bool,
2413 state: Interrupt,
2414 in_flight: &[String],
2415 runnable: &[Task],
2416) -> Interrupt {
2417 if !enabled {
2418 return Interrupt::Idle;
2419 }
2420 advance_interrupt(state, in_flight, runnable)
2421}
2422
2423fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2428 match state {
2429 Interrupt::Idle => candidates,
2430 Interrupt::Parking {
2431 parked,
2432 interrupt_task,
2433 } => {
2434 if in_flight.iter().any(|id| parked.contains(id)) {
2435 Vec::new()
2436 } else {
2437 candidates
2438 .into_iter()
2439 .filter(|t| &t.id == interrupt_task)
2440 .collect()
2441 }
2442 }
2443 Interrupt::Running { .. } => Vec::new(),
2444 Interrupt::Resuming { parked } => candidates
2452 .into_iter()
2453 .find(|t| parked.contains(&t.id))
2454 .into_iter()
2455 .collect(),
2456 }
2457}
2458
2459struct DispatchLimits {
2463 max_concurrent: usize,
2466 pause_for_interrupts: bool,
2468}
2469
2470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2479enum PermitKind {
2480 None,
2485 Urgent,
2492 Ordinary,
2495}
2496
2497fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2500 if priority {
2501 PermitKind::None
2502 } else if urgent {
2503 PermitKind::Urgent
2504 } else {
2505 PermitKind::Ordinary
2506 }
2507}
2508
2509struct DispatchClaim {
2510 task: Task,
2511 claim: crate::queue::Claim,
2512 permit: Option<tokio::sync::OwnedSemaphorePermit>,
2513}
2514
2515fn claim_dispatch(
2518 queue: &Queue,
2519 candidate: &Task,
2520 cooling_down: bool,
2521 ordinary: &Arc<tokio::sync::Semaphore>,
2522 urgent: &Arc<tokio::sync::Semaphore>,
2523) -> Option<DispatchClaim> {
2524 let Ok(claim) = queue.claim(&candidate.id) else {
2525 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2526 return None;
2527 };
2528 let task = match queue.get(&candidate.id) {
2529 Ok(t) if t.status.runnable() => t,
2530 Ok(_) => return None,
2531 Err(e) => {
2532 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2533 return None;
2534 }
2535 };
2536 let resume = land_resume_state(&task);
2537 if resume == LandResume::StillWaiting {
2538 return None;
2539 }
2540 let priority = resume == LandResume::Ready;
2541 if !priority && cooling_down {
2542 return None;
2543 }
2544 let permit = match permit_kind(priority, task.urgent) {
2547 PermitKind::None => None,
2548 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
2549 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
2550 };
2551 Some(DispatchClaim {
2552 task,
2553 claim,
2554 permit,
2555 })
2556}
2557
2558async fn poll(
2577 opts: &Opts,
2578 queue: &Queue,
2579 status: &Arc<Mutex<Status>>,
2580 home: &Path,
2581 worktrees_root: &Path,
2582 stop: &Stop,
2583 limits: DispatchLimits,
2584) -> Result<()> {
2585 let DispatchLimits {
2586 max_concurrent,
2587 pause_for_interrupts,
2588 } = limits;
2589 let mut attempted: Vec<String> = Vec::new();
2594 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2595 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2603 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2609 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2610 let mut conductor = Conductor::new();
2611 let mut cache_last_checked: Option<Timestamp> = None;
2614 let mut interrupt = Interrupt::Idle;
2616 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2622 std::collections::HashMap::new();
2623
2624 while !stop.stopped() {
2625 lock(status).polls += 1;
2626
2627 while let Some(result) = inflight.try_join_next() {
2632 if let Err(e) = result {
2633 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2634 notices::raise(Notice::error(
2635 "loop:attempt",
2636 "A queued attempt ended abnormally; check the task it was running.",
2637 ));
2638 }
2639 }
2640
2641 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2642 if !swept.is_empty() {
2643 tracing::warn!(
2644 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2645 swept.len(),
2646 swept.join(", ")
2647 );
2648 }
2649 let now = Timestamp::now();
2654
2655 if !stop.busy_now() {
2660 maybe_prune_cache_between_runs(
2661 &opts.repo,
2662 opts,
2663 home,
2664 stop,
2665 &mut cache_last_checked,
2666 now,
2667 )
2668 .await;
2669 }
2670
2671 let stalled = stalled_tasks(queue, home, now);
2672 let stalled_ids: std::collections::BTreeSet<_> =
2673 stalled.iter().map(|task| task.id.clone()).collect();
2674 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2675 if !reclaimed.is_empty() {
2676 tracing::warn!(
2677 "reclaimed {} task(s) left `running` by a daemon that never \
2678 recorded the outcome: {}",
2679 reclaimed.len(),
2680 reclaimed.join(", ")
2681 );
2682 }
2683 let abandoned_runs = reclaim_abandoned_runs(home, now);
2684 if !abandoned_runs.is_empty() {
2685 tracing::warn!(
2686 "failed {} run(s) left behind by a killed process, past every \
2687 active seat's own timeout: {}",
2688 abandoned_runs.len(),
2689 abandoned_runs.join(", ")
2690 );
2691 }
2692
2693 let questions = Questions::at(home.join("questions"));
2698
2699 resolve_blockers(queue, &questions);
2702 apply_choice_actions(queue, &questions, home);
2703 triage::apply_answers(queue, &questions);
2704 reconcile_task_questions(queue, &questions);
2705 {
2709 let talks = crate::talk::Talks::at(home.join("talks"));
2710 crate::chat_notify::sweep(queue, &talks, home);
2711 crate::chat_watch::sweep(home, &talks);
2712 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2713 }
2714
2715 let finished: Vec<Task> = finished_tasks(queue)
2721 .into_iter()
2722 .filter(|task| !stalled_ids.contains(&task.id))
2723 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2727 .collect();
2728 let queued = queued_tasks(queue);
2729 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2733 && conductor.worth_a_look(queue, &stalled, &finished)
2734 {
2735 match prepare(&opts.repo, opts) {
2736 Ok(cfg) => {
2737 conductor
2738 .maybe_run(
2739 &cfg,
2740 &opts.repo,
2741 queue,
2742 &questions,
2743 home,
2744 &queued,
2745 &stalled,
2746 &finished,
2747 opts.max_attempts,
2748 )
2749 .await;
2750 }
2751 Err(e) => {
2752 tracing::warn!("conductor: no config: {e:#}");
2753 notices::raise(Notice::warn(
2754 "loop:no-config",
2755 "The loop could not read this repository's config, so held tasks are not being triaged.",
2756 ));
2757 }
2758 }
2759 }
2760
2761 let candidates: Vec<Task> = runnable(queue)
2762 .into_iter()
2763 .filter(|t| !opts.once || !attempted.contains(&t.id))
2764 .collect();
2765
2766 let in_flight: Vec<String> = lock(status)
2771 .current
2772 .iter()
2773 .map(|c| c.task.clone())
2774 .collect();
2775 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2776
2777 interrupt =
2778 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2779 if let Interrupt::Parking {
2780 parked,
2781 interrupt_task,
2782 } = &interrupt
2783 {
2784 let reason = format!(
2785 "task {} asked to run first",
2786 crate::run::short_of(interrupt_task)
2787 );
2788 for id in parked {
2789 if let Some(pause) = interrupt_pauses.get(id) {
2790 pause.park_because(reason.clone());
2791 }
2792 }
2793 }
2794 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2795
2796 let cooling_down =
2797 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2798
2799 let mut started_any = false;
2800 for candidate in candidates {
2801 if stop.stopped() {
2802 break;
2803 }
2804
2805 let Some(DispatchClaim {
2806 mut task,
2807 claim,
2808 permit,
2809 }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
2810 else {
2811 continue;
2812 };
2813
2814 let task_id = task.id.clone();
2815 attempted.push(task_id.clone());
2816 lock(status).idle = false;
2817 stop.enter();
2820 started_any = true;
2821
2822 let run_pause = crate::graph::Pause::new();
2826 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2827
2828 let opts = opts.clone();
2829 let queue = queue.clone();
2830 let status = Arc::clone(status);
2831 let stop = stop.clone();
2832 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2833 inflight.spawn(async move {
2834 let _claim = claim;
2838 let _permit = permit;
2839 let _inflight = InFlightGuard {
2841 status: &status,
2842 stop: &stop,
2843 task_id: &task_id,
2844 };
2845 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2846 lock(&status).completed += 1;
2847 let now = Timestamp::now();
2853 if let Some(until) = cooldown_until("a, now) {
2854 let wait = until.as_second() - now.as_second();
2855 *lock("a_cooldown_until) = Some(until);
2856 let hint = quota
2857 .iter()
2858 .find(|q| q.reset.is_some())
2859 .and_then(|q| q.reset.as_deref());
2860 match hint {
2861 Some(h) => tracing::warn!(
2862 "quota hit; waiting {wait}s before taking another ordinary task \
2863 (CLI reported reset: {h})"
2864 ),
2865 None => tracing::warn!(
2866 "quota hit; waiting {wait}s before taking another ordinary task \
2867 (no reset hint reported)"
2868 ),
2869 }
2870 }
2871 });
2872 }
2873
2874 if started_any {
2875 continue;
2876 }
2877
2878 if stop.busy_now() {
2879 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2884 continue;
2885 }
2886
2887 lock(status).idle = true;
2889 if opts.once {
2890 janitor(&opts.repo, opts, home, worktrees_root).await;
2894 resweep_superseded_attempts(queue, home);
2895 triage_held(queue, home, opts).await;
2896 break;
2897 }
2898 stop.idle(opts.poll).await;
2899 if stop.stopped() {
2900 continue;
2901 }
2902 janitor(&opts.repo, opts, home, worktrees_root).await;
2908 resweep_superseded_attempts(queue, home);
2909 triage_held(queue, home, opts).await;
2910 }
2911
2912 while let Some(result) = inflight.join_next().await {
2917 if let Err(e) = result {
2918 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2919 notices::raise(Notice::error(
2920 "loop:attempt",
2921 "A queued attempt ended abnormally; check the task it was running.",
2922 ));
2923 }
2924 }
2925 Ok(())
2926}
2927
2928async fn attempt(
2934 opts: &Opts,
2935 queue: &Queue,
2936 status: &Arc<Mutex<Status>>,
2937 stop: &Stop,
2938 interrupt_pause: crate::graph::Pause,
2939 task: &mut Task,
2940) -> Vec<QuotaLoss> {
2941 let repo = repo_for(task, &opts.repo);
2942 tracing::info!(
2943 "task {} — {} (repo {})",
2944 task.short(),
2945 task.title,
2946 repo.display()
2947 );
2948
2949 let explicit = match &task.overrides {
2953 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
2954 Some(_) => opts.config.as_deref(),
2955 None => opts.config.as_deref(),
2956 };
2957 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2958 let reason = format!("[config] {e:#}");
2959 record_config_failure(task, &e);
2960 task.last_error = Some(reason.clone());
2961 task.hold_machine(Some(reason.clone()));
2962 record(queue, task);
2963 tracing::warn!("holding {}: {reason}", task.short());
2964 return Vec::new();
2965 }
2966 let mut config = match prepare_for(&repo, opts, task) {
2967 Ok(c) => c,
2968 Err(e) => {
2969 task.attempts += 1;
2973 task.fail_startup(
2974 "startup-config",
2975 format!("config: {e:#}"),
2976 opts.max_attempts,
2977 );
2978 record(queue, task);
2979 return Vec::new();
2980 }
2981 };
2982 apply_task_implementers(&mut config, task);
2983 let p = phrases(&config.graph.language);
2984 let start_failed = p.could_not_start;
2985
2986 if let Some(reason) = disk_gate(&repo, &config) {
2994 task.notice_cause("disk-space", None, None);
2995 task.last_error = Some(reason.clone());
2996 task.hold_machine(Some(reason.clone()));
2997 record(queue, task);
2998 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2999 notices::raise(
3002 Notice::warn(
3003 &format!("disk:{}", repo.display()),
3004 "A task was held for want of free disk space; free some, then release it from the queue.",
3005 )
3006 .link(Link::Task {
3007 id: task.id.clone(),
3008 }),
3009 );
3010 return Vec::new();
3011 }
3012
3013 let unfinished = (!task.fresh_start)
3033 .then(|| unfinished_run(&task.runs, task.short()))
3034 .flatten()
3035 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3036 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3042 let review_branch = take_review_branch(task, previous.as_ref());
3043 let branch_exists = match &review_branch {
3044 Some(branch) => crate::git::branch_exists(&repo, branch)
3045 .await
3046 .unwrap_or(false),
3047 None => false,
3048 };
3049 let proposed = match (&review_branch, &unfinished, &task.review_of) {
3053 (None, None, Some(branch)) => Starter::Review(branch.clone()),
3054 _ => choose_starter(
3055 review_branch.as_deref(),
3056 branch_exists,
3057 unfinished.as_deref(),
3058 ),
3059 };
3060 let starter = if let Some(selected) = &task.pr_recovery {
3061 if selected.check_task(&task.id, &task.instruction).is_ok() {
3062 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3063 } else {
3064 Starter::Review(selected.branch.clone())
3065 }
3066 } else {
3067 starter_with_implementers(task, previous.as_ref(), proposed)
3068 };
3069 if let Some(pin) = &task.resume_override
3072 && let Some(run) = &pin.pinned_run
3073 && Questions::open().get(&pin.question_id).map_or(true, |q| {
3074 q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR)
3075 })
3076 && starter != Starter::Resume(run.clone())
3077 {
3078 let run = run.clone();
3079 task.notice_cause("repair-owner", Some(&run), None);
3080 task.hold_machine(Some(format!(
3081 "repair owner cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3082 task.id
3083 )));
3084 record(queue, task);
3085 return Vec::new();
3086 }
3087 let attachments = match task_attachments(queue, task) {
3092 Ok(a) => a,
3093 Err(e) => {
3094 task.attempts += 1;
3095 task.fail_startup_target(
3096 "startup-attachments",
3097 e.name.clone(),
3098 format!("{start_failed}{e:#}"),
3099 opts.max_attempts,
3100 );
3101 record(queue, task);
3102 return Vec::new();
3103 }
3104 };
3105 let started = match &starter {
3106 Starter::Review(_) if task.pr_recovery.is_some() => {
3107 let selected = task.pr_recovery.clone().expect("selected recovery");
3108 match selected.check_task(&task.id, &task.instruction) {
3109 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3110 .await
3111 .map(|mut r| {
3112 r.state.attachments = attachments.clone();
3113 r
3114 }),
3115 Err(e) => Err(e),
3116 }
3117 }
3118 Starter::Review(branch) => {
3119 tracing::info!(
3120 "task {} reopens `{branch}` as a review-only pass",
3121 task.short()
3122 );
3123 let takeover = crate::handover::Takeover {
3126 earlier: task.earlier_attempts().to_vec(),
3127 home: crate::run::home(),
3128 choice: take_divergence_answer(branch, &config.merge.remote, task),
3129 task_instruction: Some(instruction_for(task)),
3130 };
3131 Runner::review_taking_over(
3132 &repo,
3133 branch,
3134 config,
3135 Some(takeover),
3136 crate::run::Origin::queue(&task.id),
3137 )
3138 .await
3139 }
3140 Starter::Resume(id) => {
3141 tracing::info!("resuming run {id} rather than competing again");
3142 Runner::resume(id).and_then(|mut r| {
3143 if r.state.prep_failure.is_some() {
3144 let approval = task
3145 .resumption
3146 .as_ref()
3147 .context("preparation retry requires an explicit task release")?;
3148 r.retry_preparation(approval.at)?;
3149 }
3150 if let Some(instruction) =
3151 prepare_instruction(&starter, Some(&r.state.instruction), task)
3152 {
3153 r.state.instruction = instruction;
3154 }
3155 r.state.attachments = attachments.clone();
3156 if let Some(mode) = task
3159 .overrides
3160 .as_ref()
3161 .and_then(|o| o.merge.as_deref())
3162 .and_then(|m| merge_mode(m).ok())
3163 {
3164 r.state.config.merge.mode = mode;
3165 }
3166 Ok(r)
3167 })
3168 }
3169 Starter::Start => {
3170 if let Some(branch) = &review_branch {
3171 tracing::warn!(
3172 "conductor chose review for task {} but branch `{branch}` no longer \
3173 exists; requeuing as a fresh competition instead",
3174 task.short()
3175 );
3176 }
3177 let instruction = prepare_instruction(&starter, None, task)
3178 .unwrap_or_else(|| task.instruction.clone());
3179 Runner::start_naming(
3180 &repo,
3181 instruction,
3182 &task.title,
3183 config,
3184 crate::run::Origin::queue(&task.id),
3185 )
3186 .await
3187 .map(|mut r| {
3188 r.state.attachments = attachments.clone();
3189 r
3190 })
3191 }
3192 };
3193 let mut runner = match started {
3194 Ok(r) => r,
3195 Err(e) if task.pr_recovery.is_some() => {
3199 task.startup_notice_cause("startup-public-head");
3200 task.attempts += 1;
3201 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3202 task.link_run(&partial.run);
3203 task.record_pass(&partial.run, 0, task.attempts, None);
3204 }
3205 task.last_error = Some(format!("{start_failed}{e:#}"));
3206 task.hold_unrequested_retry(Some(format!(
3207 "Selected public-head recovery could not start: {e:#}. Correct the cause and use `magi task recover-pr` with the approved public head; automatic recovery is stopped."
3208 )));
3209 record(queue, task);
3210 return Vec::new();
3211 }
3212 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3213 let detail = match e.downcast_ref::<crate::handover::Refused>() {
3214 Some(r) => (p.handover_refused)(r),
3215 None => format!("{e:#}"),
3216 };
3217 task.startup_notice_cause("startup-handover");
3218 let reason = format!("{start_failed}{detail}");
3219 task.last_error = Some(reason.clone());
3220 let branch = match &starter {
3223 Starter::Review(branch) => Some(branch.clone()),
3224 _ => None,
3225 };
3226 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3230 record(queue, task);
3231 tracing::warn!(
3232 "holding {} for a branch it cannot take over: {e:#}",
3233 task.short()
3234 );
3235 return Vec::new();
3236 }
3237 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3242 let d = e
3243 .downcast_ref::<crate::reconcile::Diverged>()
3244 .expect("checked by the guard");
3245 let mut q = ask::Question::new(
3246 task.id.clone(),
3247 crate::reconcile::NODE.to_owned(),
3248 crate::reconcile::SEAT.to_owned(),
3249 d.summary(),
3250 d.detail(),
3251 d.choices(),
3252 );
3253 match Questions::open().put(&mut q) {
3254 Ok(()) => {
3255 task.last_error = Some(format!("{e:#}"));
3256 task.review_branch = Some(d.branch.clone());
3259 task.review_instruction = Some(task.instruction.clone());
3260 task.block(vec![q.id.clone()], Some(d.summary()));
3261 }
3262 Err(put) => {
3263 tracing::warn!("could not file the divergence question: {put:#}");
3264 task.attempts += 1;
3265 task.fail_startup(
3266 "startup-question-store",
3267 format!("{start_failed}{e:#}"),
3268 opts.max_attempts,
3269 );
3270 }
3271 }
3272 record(queue, task);
3273 return Vec::new();
3274 }
3275 Err(e) => {
3276 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3282 && let Starter::Review(branch) = &starter
3283 {
3284 task.review_branch = Some(branch.clone());
3285 task.review_instruction = Some(task.instruction.clone());
3286 task.last_error = Some(format!("{start_failed}{e:#}"));
3287 task.status = crate::queue::TaskStatus::Failed;
3288 record(queue, task);
3289 return Vec::new();
3290 }
3291 task.attempts += 1;
3292 task.last_error = Some(format!("{start_failed}{e:#}"));
3293 task.startup_notice_cause("startup-source");
3294 task.hold_unrequested_retry(Some(format!(
3295 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3296 )));
3297 record(queue, task);
3298 return Vec::new();
3299 }
3300 };
3301 runner.state.task_instruction = Some(task.instruction.clone());
3302 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3305 if runner.state.origin_chat.is_none() {
3306 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3307 }
3308 runner.on_pause(stop.pause());
3310 runner.watch_interrupt(interrupt_pause);
3314
3315 let run = runner.state.id.clone();
3318 task.start(run.clone());
3319 record(queue, task);
3320 lock(status).current.push(Current {
3321 task: task.id.clone(),
3322 run,
3323 });
3324
3325 let quota_before = runner.state.quota.clone();
3328 runner.state.next_pass_task_entry = true;
3329 let result = runner.execute().await;
3330 finish_attempt(
3331 opts.max_attempts,
3332 queue,
3333 task,
3334 &runner.state,
3335 "a_before,
3336 result,
3337 )
3338}
3339
3340pub fn finish_attempt(
3345 max_attempts: usize,
3346 queue: &Queue,
3347 task: &mut Task,
3348 state: &RunState,
3349 quota_before: &[QuotaLoss],
3350 result: Result<()>,
3351) -> Vec<QuotaLoss> {
3352 let detail = match result {
3353 Ok(()) => describe(state),
3354 Err(e) => format!("{e:#}"),
3355 };
3356 let fresh = losses_this_attempt(quota_before, &state.quota);
3357 let verdict = Verdict {
3358 status: state.status,
3359 left_pr: state.pr.is_some(),
3362 quota_hit: !fresh.is_empty(),
3368 parked: state.parked,
3372 no_viable_candidates: state.viable().is_empty(),
3375 };
3376 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3377 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
3378 task.hold_unrequested_retry(Some(format!(
3379 "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
3380 )));
3381 }
3382 if task.status == TaskStatus::Done {
3383 supersede_prior_runs(task, &crate::run::home());
3384 }
3385 record(queue, task);
3386 tracing::info!(
3387 "task {} is {} after run {} ({})",
3388 task.short(),
3389 task.status.as_str(),
3390 state.short(),
3391 label(state.status)
3392 );
3393 fresh
3394}
3395
3396pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3400 let waits_on_owner = withheld_text_wait(task).is_some();
3405 if task.status.runnable() && !waits_on_owner {
3406 let why = task.last_error.clone().map_or_else(
3407 || "the run did not finish".to_owned(),
3408 |e| format!("the run did not finish: {e}"),
3409 );
3410 task.hold_unrequested_retry(Some(format!(
3411 "{why}. It was started by hand, so it is not retried \
3412 automatically; `magi task release` retries it."
3413 )));
3414 record(queue, task);
3415 }
3416}
3417
3418#[must_use]
3422pub fn loop_would_resume(run: &str) -> bool {
3423 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3424}
3425
3426#[must_use]
3436pub fn foreign_loop(
3437 reading: Option<&Reading>,
3438 now: Timestamp,
3439 own_pid: u32,
3440) -> Option<Option<u32>> {
3441 let reading = reading.filter(|r| r.running(now))?;
3442 match reading.pid {
3443 Some(pid) if pid == own_pid => None,
3444 pid => Some(pid),
3445 }
3446}
3447
3448pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3463 let status = Arc::new(Mutex::new(Status::new()));
3464 let stop = Stop::new();
3465 attempt(
3466 opts,
3467 queue,
3468 &status,
3469 &stop,
3470 crate::graph::Pause::new(),
3471 task,
3472 )
3473 .await;
3474 let mut resumes = 0;
3483 while resumes < MAX_WITHHELD_RESUMES {
3484 let Some(timeout) = withheld_text_wait(task) else {
3485 break;
3486 };
3487 eprintln!(
3488 "waiting for the owner's answer on a withheld pull request text \
3489 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3490 );
3491 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3494 let ready = loop {
3495 match land_resume_state(task) {
3496 LandResume::StillWaiting if std::time::Instant::now() < limit => {
3497 tokio::time::sleep(WITHHELD_POLL).await;
3498 }
3499 LandResume::Ready => break true,
3500 _ => break false,
3501 }
3502 };
3503 if !ready {
3504 break;
3505 }
3506 resumes += 1;
3507 attempt(
3508 opts,
3509 queue,
3510 &status,
3511 &stop,
3512 crate::graph::Pause::new(),
3513 task,
3514 )
3515 .await;
3516 }
3517 hold_if_runnable(queue, task);
3518}
3519
3520const MAX_WITHHELD_RESUMES: u32 = 3;
3523
3524const WITHHELD_POLL: Duration = Duration::from_secs(15);
3526
3527fn withheld_text_wait(task: &Task) -> Option<u64> {
3530 let id = task.runs.last()?;
3531 let s = RunState::load(id).ok()?;
3532 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3533 .then_some(s.config.graph.answer_timeout)
3534}
3535
3536fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3546 after
3547 .iter()
3548 .filter(|q| !before.contains(q))
3549 .cloned()
3550 .collect()
3551}
3552
3553fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3556 if quota.is_empty() {
3557 return None;
3558 }
3559 let with_hint = quota.iter().find(|q| q.reset.is_some());
3560 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3561 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3562 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3563 Some(
3564 now.checked_add(jiff::SignedDuration::from_secs(secs))
3565 .unwrap_or(Timestamp::MAX),
3566 )
3567}
3568
3569fn implementers_match(task: &Task, state: &RunState) -> bool {
3571 task.implementers()
3572 .is_none_or(|n| n == state.config.graph.implementers)
3573}
3574
3575fn starter_with_implementers(
3577 task: &Task,
3578 previous: Option<&RunState>,
3579 proposed: Starter,
3580) -> Starter {
3581 if previous.is_some_and(|s| !implementers_match(task, s)) {
3582 task.review_of
3583 .as_ref()
3584 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3585 } else {
3586 proposed
3587 }
3588}
3589
3590fn apply_task_implementers(config: &mut Config, task: &Task) {
3592 if let Some(n) = task.implementers() {
3593 config.graph.implementers = n;
3594 }
3595}
3596
3597fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3602 let Some(o) = &task.overrides else {
3603 return prepare(repo, opts);
3604 };
3605 let own = Opts {
3609 config: o.config.clone(),
3610 merge: None,
3611 ..opts.clone()
3612 };
3613 let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3614 o.apply(&mut config);
3615 Ok(config)
3616}
3617
3618fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3620 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3621 if let Some(mode) = &opts.merge {
3622 config.merge.mode = merge_mode(mode)?;
3623 }
3624 Ok(config)
3625}
3626
3627async fn maybe_prune_cache_between_runs(
3658 repo: &Path,
3659 opts: &Opts,
3660 home: &Path,
3661 stop: &Stop,
3662 last_checked: &mut Option<Timestamp>,
3663 now: Timestamp,
3664) {
3665 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3666 return;
3667 }
3668 *last_checked = Some(now);
3669 let cfg = match prepare(repo, opts) {
3670 Ok(cfg) => cfg,
3671 Err(e) => {
3672 tracing::warn!("cache check: no config: {e:#}");
3673 return;
3674 }
3675 };
3676 match clean::prune_cache_if_over_limit(&cfg, home) {
3677 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3678 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3679 pruned.files,
3680 pruned.freed
3681 ),
3682 Ok(_) => {}
3683 Err(e) => {
3684 tracing::warn!("housekeep: prune cache: {e:#}");
3685 notices::raise_in(
3686 home,
3687 Notice::warn(
3688 "housekeep:cache",
3689 "Pruning the shared build cache failed; disk usage may keep growing.",
3690 ),
3691 );
3692 }
3693 }
3694}
3695
3696fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3700 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3701}
3702
3703async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3722 let cfg = match prepare(repo, opts) {
3723 Ok(cfg) => cfg,
3724 Err(e) => {
3725 tracing::warn!("housekeep: no config: {e:#}");
3726 return;
3727 }
3728 };
3729 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3738 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3739 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3744 let mut extra = Vec::new();
3745 if out.unreadable > 0 {
3746 extra.push(format!("{} unreadable", out.unreadable));
3747 }
3748 if out.orphaned_worktrees > 0 {
3749 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3750 }
3751 let detail = if extra.is_empty() {
3752 String::new()
3753 } else {
3754 format!(" ({})", extra.join(", "))
3755 };
3756 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3757 }
3758 if out.external_merges_recorded > 0 {
3759 tracing::info!(
3760 "housekeep: recorded {} run(s) as merged externally",
3761 out.external_merges_recorded
3762 );
3763 }
3764 if out.stale_pr_states_repaired > 0 {
3765 tracing::info!(
3766 "housekeep: rewrote {} run record(s) whose pull request had already settled",
3767 out.stale_pr_states_repaired
3768 );
3769 }
3770 if out.cache_files > 0 {
3771 tracing::info!(
3772 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3773 out.cache_files,
3774 out.cache_freed
3775 );
3776 }
3777 if out.questions_abandoned > 0 {
3778 tracing::info!(
3779 "housekeep: abandoned {} question(s) left open by a finished run",
3780 out.questions_abandoned
3781 );
3782 }
3783}
3784
3785async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3794 let questions = Questions::at(home.join("questions"));
3795 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3796 if report.is_empty() {
3797 return;
3798 }
3799 if !report.quarantined.is_empty() {
3800 tracing::info!(
3801 "triage: held {} blocked task(s) whose blocked-on task or \
3802 question no longer exists: {}",
3803 report.quarantined.len(),
3804 report.quarantined.join(", ")
3805 );
3806 }
3807 if !report.resumed.is_empty() {
3808 tracing::info!(
3809 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3810 report.resumed.len(),
3811 report.resumed.join(", ")
3812 );
3813 }
3814 if !report.asked.is_empty() {
3815 tracing::info!(
3816 "triage: asked about {} held task(s): {}",
3817 report.asked.len(),
3818 report.asked.join(", ")
3819 );
3820 }
3821 if !report.answered.is_empty() {
3822 tracing::info!(
3823 "triage: applied {} operator answer(s): {}",
3824 report.answered.len(),
3825 report.answered.join(", ")
3826 );
3827 }
3828}
3829
3830fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3837 disk_gate_with(repo, config, crate::disk::free_bytes)
3838}
3839
3840fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3844 repo: &Path,
3845 config: &Config,
3846 free_bytes: F,
3847) -> Option<String> {
3848 let min = config.disk.min_free_bytes;
3849 if min == 0 {
3850 return None;
3851 }
3852 match free_bytes(repo) {
3853 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3854 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3855 }
3856}
3857
3858const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3865
3866const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3870
3871fn quota_wait(
3880 reset_at: Option<Timestamp>,
3881 now: Timestamp,
3882 fallback: Duration,
3883 cap: Duration,
3884) -> Duration {
3885 match reset_at {
3886 Some(at) if at > now => {
3887 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3888 Duration::from_secs(secs).min(cap)
3889 }
3890 _ => fallback,
3891 }
3892}
3893
3894fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3908 parse_reset_hint_zoned(text, now)
3909 .or_else(|| parse_reset_hint_dated(text))
3910 .or_else(|| parse_reset_hint_relative(text, recorded))
3911}
3912
3913fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3917 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3918 let mut rest = rest.trim();
3919 if rest.is_empty() {
3920 return None;
3921 }
3922 let mut total: i64 = 0;
3923 let mut matched = false;
3924 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3925 if let Some((digits, tail)) = rest.split_once(unit)
3926 && !digits.is_empty()
3927 && digits.bytes().all(|b| b.is_ascii_digit())
3928 {
3929 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3930 rest = tail;
3931 matched = true;
3932 }
3933 }
3934 if !rest.is_empty() || !matched {
3935 return None;
3936 }
3937 recorded
3938 .checked_add(jiff::SignedDuration::from_secs(total))
3939 .ok()
3940}
3941
3942fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3946 let clock = clock.trim().to_lowercase();
3947 let (digits, pm) = clock
3948 .strip_suffix("am")
3949 .map(|d| (d, false))
3950 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3951 let (h, m) = digits.trim().split_once(':')?;
3952 let mut hour: i8 = h.trim().parse().ok()?;
3953 let minute: i8 = m.trim().parse().ok()?;
3954 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3955 return None;
3956 }
3957 if pm && hour != 12 {
3958 hour += 12;
3959 } else if !pm && hour == 12 {
3960 hour = 0;
3961 }
3962 Some((hour, minute))
3963}
3964
3965fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3970 let open = text.find('(')?;
3971 let close = text.rfind(')')?;
3972 if close <= open {
3973 return None;
3974 }
3975 let zone = text[open + 1..close].trim();
3976 let (hour, minute) = parse_12h_clock(&text[..open])?;
3977 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3978 let candidate = now
3979 .to_zoned(tz)
3980 .with()
3981 .hour(hour)
3982 .minute(minute)
3983 .second(0)
3984 .millisecond(0)
3985 .microsecond(0)
3986 .nanosecond(0)
3987 .build()
3988 .ok()?;
3989 let mut at = candidate.timestamp();
3990 if at <= now {
3991 at += jiff::SignedDuration::from_hours(24);
3992 }
3993 Some(at)
3994}
3995
3996fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4005 let words: Vec<&str> = text.split_whitespace().collect();
4006 if words.len() < 5 {
4007 return None;
4008 }
4009 (0..=words.len() - 5)
4010 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4011}
4012
4013fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4019 if trailing.is_some_and(|next| next.starts_with('(')) {
4020 return None;
4021 }
4022 let month = month_number(window[0])?;
4023 let day_token = window[1].strip_suffix(',')?.to_lowercase();
4024 let day_digits = ["st", "nd", "rd", "th"]
4025 .iter()
4026 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4027 let day: i8 = day_digits.parse().ok()?;
4028 let year_token = window[2];
4029 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4030 return None;
4031 }
4032 let year: i16 = year_token.parse().ok()?;
4033 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4037 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4038 let date = jiff::civil::Date::new(year, month, day).ok()?;
4039 let candidate = date
4040 .at(hour, minute, 0, 0)
4041 .to_zoned(jiff::tz::TimeZone::UTC)
4042 .ok()?;
4043 Some(candidate.timestamp())
4044}
4045
4046fn month_number(name: &str) -> Option<i8> {
4049 const NAMES: [&str; 12] = [
4050 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4051 ];
4052 let lower = name.to_lowercase();
4053 NAMES
4054 .iter()
4055 .position(|n| *n == lower.as_str())
4056 .map(|i| i as i8 + 1)
4057}
4058
4059fn exhausted_review_budget(state: &RunState) -> bool {
4071 state.status == RunStatus::Blocked
4074 && !state.pr_publication_pending
4075 && state.reviews.len() >= state.config.graph.review_rounds
4076}
4077
4078fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4115 unfinished_run_with(runs, short, RunState::load)
4116}
4117
4118fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
4121where
4122 F: FnOnce(&str) -> Result<RunState>,
4123{
4124 let id = runs.last()?;
4125 match load(id) {
4126 Ok(s)
4131 if s.status.resumable()
4132 && !s.released()
4133 && !exhausted_review_budget(&s)
4134 && s.liveness(false) != crate::run::Liveness::Live =>
4135 {
4136 Some(id.clone())
4137 }
4138 Ok(_) => None,
4139 Err(e) => {
4140 tracing::warn!("could not read run {id} for task {short}: {e:#}");
4141 None
4142 }
4143 }
4144}
4145
4146fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
4154where
4155 F: FnOnce(&str) -> Result<RunState>,
4156{
4157 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4159 || task.fresh_start
4160 || task.review_branch.is_some()
4161 {
4162 return false;
4163 }
4164 let Some(id) = task.runs.last() else {
4165 return false;
4166 };
4167 load(id).is_ok_and(|s| {
4168 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4169 })
4170}
4171
4172#[derive(Debug, Clone, PartialEq, Eq)]
4175enum Starter {
4176 Review(String),
4179 Resume(String),
4181 Start,
4183}
4184
4185fn selected_starter(
4187 selected: &crate::pr_recovery::Selection,
4188 previous: Option<&RunState>,
4189 unfinished: Option<&str>,
4190) -> Starter {
4191 if let Some(id) = unfinished
4192 && previous.is_some_and(|r| {
4193 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4194 })
4195 {
4196 Starter::Resume(id.to_owned())
4197 } else {
4198 Starter::Review(selected.branch.clone())
4199 }
4200}
4201
4202fn take_divergence_answer(
4206 branch: &str,
4207 remote: &str,
4208 task: &mut Task,
4209) -> Option<crate::reconcile::Choice> {
4210 let summary = crate::reconcile::summary_for(branch, remote);
4211 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4212 (a.question == summary)
4213 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4214 .flatten()
4215 .map(|c| (i, c))
4216 })?;
4217 task.answers.remove(idx);
4218 Some(choice)
4219}
4220
4221fn choose_starter(
4233 review_branch: Option<&str>,
4234 branch_exists: bool,
4235 unfinished: Option<&str>,
4236) -> Starter {
4237 match review_branch {
4238 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4239 Some(_) => Starter::Start,
4240 None => match unfinished {
4241 Some(id) => Starter::Resume(id.to_owned()),
4242 None => Starter::Start,
4243 },
4244 }
4245}
4246
4247fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4249 let branch = task.review_branch.take();
4250 let instruction = task.review_instruction.take();
4251 branch.filter(|branch| match &instruction {
4252 Some(authored) => *authored == task.instruction,
4253 None => previous.map_or_else(
4256 || task.review_of.as_ref() == Some(branch),
4257 |run| compatible_run_instruction(run, task),
4258 ),
4259 })
4260}
4261
4262fn may_resume_run(run: &RunState, task: &Task) -> bool {
4265 task.resume_override
4266 .as_ref()
4267 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
4268 || compatible_run_instruction(run, task)
4269}
4270
4271pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
4273 if let Some(authored) = &run.task_instruction {
4274 return compatible_instruction(authored, task);
4275 }
4276 if compatible_instruction(&run.instruction, task) {
4277 return true;
4278 }
4279 if run.reviewed_commits.is_some() {
4282 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
4283 return strip_answers_block(authored, task).trim() == task.instruction.trim();
4284 }
4285 if let Some(branch) = &task.review_of {
4286 let canonical = format!(
4287 "Review the branch `{branch}` (review-only: no implementation, no judging)."
4288 );
4289 let generated = format!(
4290 "Review the work already on branch `{branch}`. There is no task statement: what the change claims to do is whatever its commits say.\n\n"
4291 );
4292 return task.instruction == canonical && run.instruction.starts_with(&generated);
4293 }
4294 }
4295 false
4296}
4297
4298pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
4300 strip_answers_block(old, task) == task.instruction
4301}
4302
4303fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4306 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4307 return fallback.to_path_buf();
4308 }
4309 task.repo.clone()
4310}
4311
4312const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4316
4317fn answers_block(task: &Task, count: usize) -> String {
4319 let mut s = ANSWERS_HEADER.to_owned();
4320 for a in &task.answers[..count] {
4321 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4322 }
4323 s
4324}
4325
4326fn resumption_block(r: &crate::queue::Resumption) -> String {
4329 format!(
4330 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
4331 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
4332 r.generation, r.at, r.instruction, r.answers_through,
4333 )
4334}
4335
4336fn append_answers(base: &str, task: &Task) -> String {
4338 let mut s = base.to_owned();
4339 if !task.answers.is_empty() {
4340 s.push_str(&answers_block(task, task.answers.len()));
4341 }
4342 if let Some(r) = &task.resumption {
4343 s.push_str(&resumption_block(r));
4344 }
4345 s
4346}
4347
4348fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4352 let mut instruction = instruction;
4353 for approval in task
4354 .resumption
4355 .iter()
4356 .chain(task.resumption_history.iter().rev())
4357 {
4358 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
4359 instruction = base;
4360 break;
4361 }
4362 }
4363 for count in (1..=task.answers.len()).rev() {
4364 let block = answers_block(task, count);
4365 if let Some(base) = instruction.strip_suffix(&block) {
4366 return base;
4367 }
4368 }
4369 instruction
4370}
4371
4372fn instruction_for(task: &Task) -> String {
4380 append_answers(&task.instruction, task)
4381}
4382
4383fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4395 append_answers(strip_answers_block(old_instruction, task), task)
4396}
4397
4398fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
4400 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
4401 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
4402 if let Some(cause) = task.hold_notice_cause.as_mut() {
4403 cause.target = failure.map(|f| f.target.clone());
4404 }
4405}
4406
4407#[derive(Debug, thiserror::Error)]
4408#[error("attachment `{name}` is recorded on the task but {path} is missing")]
4409struct MissingAttachment {
4410 name: String,
4411 path: PathBuf,
4412}
4413
4414fn task_attachments(
4416 queue: &Queue,
4417 task: &Task,
4418) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
4419 let paths = queue.attachment_paths(task);
4420 for (name, path) in task.attachments.iter().zip(&paths) {
4421 if !path.is_file() {
4422 return Err(MissingAttachment {
4423 name: name.clone(),
4424 path: path.clone(),
4425 });
4426 }
4427 }
4428 Ok(paths)
4429}
4430
4431fn prepare_instruction(
4442 starter: &Starter,
4443 old_instruction: Option<&str>,
4444 task: &Task,
4445) -> Option<String> {
4446 match starter {
4447 Starter::Start => Some(instruction_for(task)),
4448 Starter::Resume(_) => Some(resumed_instruction(
4449 old_instruction.expect("a resumed run always has a prior instruction"),
4450 task,
4451 )),
4452 Starter::Review(_) => None,
4453 }
4454}
4455
4456fn record(queue: &Queue, task: &mut Task) {
4460 if let Err(e) = queue.put(task) {
4461 tracing::error!("could not record task {}: {e:#}", task.short());
4462 let notice = Notice::error(
4463 "loop:record",
4464 "The loop could not save a task's state; check the disk.",
4465 )
4466 .link(Link::Task {
4467 id: task.id.clone(),
4468 });
4469 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4471 Some(home) => notices::raise_in(home, notice),
4472 None => notices::raise(notice),
4473 }
4474 }
4475}
4476
4477fn runnable(queue: &Queue) -> Vec<Task> {
4483 let mut tasks: Vec<Task> = queue
4484 .list()
4485 .into_iter()
4486 .filter(|t| t.status.runnable())
4487 .collect();
4488 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4489 tasks
4490}
4491
4492fn describe(state: &RunState) -> String {
4506 let p = phrases(&state.config.graph.language);
4507 let mut detail = if state.status == RunStatus::Stalled {
4508 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4509 seats.sort_unstable();
4510 seats.dedup();
4511 if seats.is_empty() {
4512 p.quorum_lost.to_owned()
4513 } else {
4514 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4515 }
4516 } else {
4517 format!("{}{}", p.run_ended, state.status.display_label())
4518 };
4519 if let Some(last) = state.events.last() {
4520 let unanswered = state
4524 .reviews
4525 .last()
4526 .filter(|r| {
4527 state.status == RunStatus::Blocked
4528 && last.node == "review"
4529 && r.incomplete()
4530 && r.blocking == 0
4531 && r.round == state.config.graph.review_rounds
4532 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4533 })
4534 .map(|r| (r.expected - r.answered, r.round));
4535 match unanswered {
4536 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4537 detail.push_str(&format!(
4538 " ({}: {})",
4539 last.node,
4540 (p.reviewers_never_answered)(missing, rounds)
4541 ));
4542 }
4543 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4544 }
4545 }
4546 detail.push_str(&format!(" [run {}]", state.id));
4547 detail
4548}
4549
4550const DIAGNOSTIC_MAX: usize = 4_000;
4556
4557const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4562
4563fn diagnostic(state: &RunState) -> Option<String> {
4577 let mut parts: Vec<String> = Vec::new();
4578
4579 for o in state.gate.iter().filter(|o| !o.ok()) {
4581 parts.push(format!(
4582 "gate `{}` failed ({:?}):\n{}",
4583 o.command,
4584 o.code,
4585 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4586 ));
4587 }
4588
4589 if let Some(last) = state
4592 .events
4593 .iter()
4594 .rev()
4595 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4596 {
4597 parts.push(last.message.clone());
4598 }
4599
4600 if state.viable().is_empty() {
4607 for c in &state.candidates {
4608 if let Some(evidence) = &c.verified_noop {
4609 parts.push(format!(
4610 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4611 c.label
4612 ));
4613 } else if !c.summary.trim().is_empty() {
4614 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4615 } else if let Some(why) = &c.failed {
4616 parts.push(format!("candidate {}: {why}", c.label));
4617 }
4618 }
4619 }
4620
4621 if parts.is_empty() {
4622 return None;
4623 }
4624 Some(crate::run::tail(
4629 &parts.join("\n\n"),
4630 DIAGNOSTIC_MAX.saturating_sub(100),
4631 ))
4632}
4633
4634fn label(status: RunStatus) -> &'static str {
4642 status.as_str()
4643}
4644
4645pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4647 match mode {
4648 "none" => Ok(MergeMode::None),
4649 "local" => Ok(MergeMode::Local),
4650 "pr" => Ok(MergeMode::Pr),
4651 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4652 }
4653}
4654
4655fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4660 mutex
4661 .lock()
4662 .unwrap_or_else(std::sync::PoisonError::into_inner)
4663}
4664
4665#[cfg(test)]
4666mod tests {
4667 use super::*;
4668 use crate::queue::{Source, TaskStatus};
4669 use crate::run::{Candidate, CommandOutcome};
4670 use pretty_assertions::assert_eq;
4671
4672 fn task() -> Task {
4673 Task::new(
4674 "add retries".to_owned(),
4675 "add retries".to_owned(),
4676 PathBuf::from("/repo"),
4677 Source::Human,
4678 )
4679 }
4680
4681 #[test]
4682 fn selected_public_head_overrides_historical_resume_and_pin() {
4683 let mut t = task();
4684 let mut old = run_state(RunStatus::Blocked);
4685 let selection = crate::pr_recovery::Selection {
4686 url: "url".into(),
4687 branch: format!("magi/task-{}", t.id),
4688 head: "a".repeat(40),
4689 instruction: t.instruction.clone(),
4690 approved_at: Timestamp::now(),
4691 };
4692 t.resume_override = Some(crate::queue::OperatorResume {
4693 pinned_run: Some(old.id.clone()),
4694 question_id: "choice".into(),
4695 at: Timestamp::now(),
4696 conductor_rehold: None,
4697 forced: false,
4698 });
4699 assert_eq!(
4700 selected_starter(&selection, Some(&old), Some(&old.id)),
4701 Starter::Review(selection.branch.clone())
4702 );
4703 old.pr_recovery = Some(selection.clone());
4704 assert_eq!(
4705 selected_starter(&selection, Some(&old), Some(&old.id)),
4706 Starter::Review(selection.branch.clone())
4707 );
4708 old.reviewed_commits = Some(vec!["implementation".into()]);
4709 assert_eq!(
4710 selected_starter(&selection, Some(&old), Some(&old.id)),
4711 Starter::Resume(old.id.clone())
4712 );
4713 let mut changed = selection.clone();
4714 changed.head = "b".repeat(40);
4715 assert_eq!(
4716 selected_starter(&changed, Some(&old), Some(&old.id)),
4717 Starter::Review(changed.branch)
4718 );
4719 }
4720
4721 #[test]
4722 fn candidate_transplant_failure_is_one_actionable_hold() {
4723 let dir = tempfile::tempdir().unwrap();
4724 let q = Queue::at(dir.path().join("queue"));
4725 let mut t = task();
4726 let mut state = run_state(RunStatus::Blocked);
4727 state.event("prep", "cannot apply referenced commit: conflict");
4728 state.prep_failure = Some("conflict".into());
4729 t.start(state.id.clone());
4730 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
4731 assert_eq!(t.attempts, 1);
4732 assert_eq!(t.status, TaskStatus::Held);
4733 assert!(t.operator_held());
4734 assert!(!t.status.runnable());
4735 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
4736 let first = t.chat_notice_key().unwrap();
4737 t.chat_notices.push(first.clone());
4738 t.release_operator("test", None);
4739 state.id = "another-unprepared-run".into();
4740 t.start(state.id.clone());
4741 finish_attempt(
4742 3,
4743 &q,
4744 &mut t,
4745 &state,
4746 &[],
4747 Err(anyhow::anyhow!("still conflicts")),
4748 );
4749 assert_eq!(
4750 t.chat_notice_key().as_ref(),
4751 Some(&first),
4752 "no work happened"
4753 );
4754 t.release_operator("test", None);
4755 state.prep_failure = None;
4756 state.status = RunStatus::Failed;
4757 state.begin_pass();
4758 t.start(state.id.clone());
4759 finish_attempt(
4760 1,
4761 &q,
4762 &mut t,
4763 &state,
4764 &[],
4765 Err(anyhow::anyhow!("new gate failure")),
4766 );
4767 let failure = t.chat_notice_key().unwrap();
4768 assert_ne!(failure, first, "approved recovery reached a real failure");
4769 t.release_operator("test", None);
4770 state.begin_pass();
4771 t.start(state.id.clone());
4772 finish_attempt(
4773 1,
4774 &q,
4775 &mut t,
4776 &state,
4777 &[],
4778 Err(anyhow::anyhow!("new failure on resume")),
4779 );
4780 assert_ne!(
4781 t.chat_notice_key().as_ref(),
4782 Some(&failure),
4783 "a new settled pass"
4784 );
4785 }
4786
4787 #[test]
4788 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
4789 for source in ["cli", "web"] {
4790 let mut t = task();
4791 let mut run = run_state(RunStatus::Blocked);
4792 run.instruction = "Run A original criteria".into();
4793 run.task_instruction = Some(run.instruction.clone());
4794 t.start(run.id.clone());
4795 t.release_operator("choice", Some("resume-question"));
4796 t.resume_override = Some(crate::queue::OperatorResume {
4797 question_id: "resume-question".into(),
4798 at: Timestamp::now(),
4799 conductor_rehold: None,
4800 forced: true,
4801 pinned_run: Some(run.id.clone()),
4802 });
4803 t.hold_machine(Some("not enough free space to start a run".into()));
4804 let mut unchanged = t.clone();
4805 unchanged
4806 .edit("title changed".into(), unchanged.instruction.clone())
4807 .unwrap();
4808 unchanged.release_operator(source, None);
4809 assert_eq!(
4810 unchanged
4811 .resume_override
4812 .as_ref()
4813 .unwrap()
4814 .pinned_run
4815 .as_deref(),
4816 Some(run.id.as_str())
4817 );
4818 assert!(!compatible_run_instruction(&run, &unchanged));
4819 assert!(may_resume_run(&run, &unchanged));
4820
4821 t.edit(
4822 "approved recovery".into(),
4823 "Reuse measured PR head B; fix Clippy; review".into(),
4824 )
4825 .unwrap();
4826 assert!(t.resume_override.is_none());
4827 t.release_operator(source, None);
4828 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
4829 assert!(reloaded.resume_override.is_none());
4830 assert!(!may_resume_run(&run, &reloaded));
4831 let unfinished =
4832 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
4833 .filter(|_| may_resume_run(&run, &reloaded));
4834 assert_eq!(
4835 choose_starter(None, false, unfinished.as_deref()),
4836 Starter::Start
4837 );
4838 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
4839 assert_eq!(
4840 reloaded.resumption_history[0].question_id.as_deref(),
4841 Some("resume-question")
4842 );
4843
4844 unchanged.instruction = "Reuse measured PR head B".into();
4847 unchanged.hold_machine(Some("disk hold".into()));
4848 unchanged.release_operator(source, None);
4849 assert!(unchanged.resume_override.is_none());
4850 assert!(!may_resume_run(&run, &unchanged));
4851 }
4852 }
4853
4854 #[test]
4855 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
4856 let mut t = task();
4857 let mut run = run_state(RunStatus::Blocked);
4858 t.review_of = Some("approved-head".into());
4859 t.instruction =
4860 "Review the branch `approved-head` (review-only: no implementation, no judging)."
4861 .into();
4862 run.instruction = "Review the work already on branch `approved-head`. There is no task statement: what the change claims to do is whatever its commits say.\n\nCommit log".into();
4863 run.reviewed_commits = Some(vec!["Commit log".into()]);
4864 t.start(run.id.clone());
4865 t.hold_machine(Some("interrupted review".into()));
4866 t.release_operator("cli", None);
4867 assert!(
4868 compatible_run_instruction(&run, &t),
4869 "legacy explicit review remains resumable"
4870 );
4871 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
4872 .filter(|_| compatible_run_instruction(&run, &t));
4873 assert_eq!(
4874 choose_starter(None, false, unfinished.as_deref()),
4875 Starter::Resume(run.id.clone())
4876 );
4877 run.task_instruction = Some(t.instruction.clone());
4878 assert!(compatible_run_instruction(&run, &t));
4879 let reloaded: RunState =
4880 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
4881 assert!(compatible_run_instruction(&reloaded, &t));
4882 t.edit(
4883 "new approved head".into(),
4884 "Reuse measured PR head B".into(),
4885 )
4886 .unwrap();
4887 assert!(!compatible_run_instruction(&run, &t));
4888
4889 t.review_of = None;
4891 t.instruction = "Fix Clippy on approved head".into();
4892 run.task_instruction = None;
4893 run.instruction = format!(
4894 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
4895 t.instruction
4896 );
4897 assert!(compatible_run_instruction(&run, &t));
4898 t.instruction.push('\n');
4899 assert!(
4900 compatible_run_instruction(&run, &t),
4901 "legacy generated review trimmed the original criteria"
4902 );
4903 t.hold_for_handover(Some("approved-head".into()), "refused".into());
4904 let mut unchanged = t.clone();
4905 assert_eq!(
4906 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
4907 Some("approved-head")
4908 );
4909 t.edit("new plan".into(), "Reuse measured PR head B".into())
4910 .unwrap();
4911 assert!(take_review_branch(&mut t, Some(&run)).is_none());
4912 assert!(!compatible_run_instruction(&run, &t));
4913 t.review_branch = Some("approved-head".into());
4914 t.review_instruction = None;
4915 assert!(
4916 take_review_branch(&mut t, Some(&run)).is_none(),
4917 "legacy retained candidate cannot replace a revised approved head"
4918 );
4919 }
4920
4921 #[test]
4922 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
4923 crate::run::pin_test_home();
4924 let dir = tempfile::tempdir().unwrap();
4925 let queue = Queue::at(dir.path().join("queue"));
4926 for resume in [true, false] {
4927 let state = run_state(RunStatus::Blocked);
4928 let mut t = task();
4929 t.start(state.id.clone());
4930 let action = if resume {
4931 ask::ChoiceAction::Resume {
4932 run: state.id.clone(),
4933 }
4934 } else {
4935 ask::ChoiceAction::Requeue
4936 };
4937 let mut q = action_question(&state.id, action);
4938 q.status = ask::QuestionStatus::Open;
4939 q.answer = None;
4940 q.answered_at = None;
4941 t.fail("run stopped with a question", 3);
4942 hold_if_runnable(&queue, &mut t);
4943 assert!(t.operator_decided_at.is_none());
4944 assert!(t.operator_held());
4945 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
4946 let expected = if resume {
4947 ActionDecision::Resume(state.id.clone())
4948 } else {
4949 ActionDecision::Requeue
4950 };
4951 assert_eq!(
4952 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4953 expected
4954 );
4955 t.hold_manual(Some("later explicit hold".into()));
4956 assert_eq!(
4957 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4958 ActionDecision::Stale
4959 );
4960 }
4961 }
4962
4963 #[test]
4964 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
4965 let mut t = task();
4966 t.answers.push(crate::queue::AnsweredQuestion {
4967 question: "Inspect the remote?".into(),
4968 answer: "Inspect then wait".into(),
4969 });
4970 let old = instruction_for(&t);
4971 assert!(compatible_instruction(&old, &t));
4972 t.instruction = "Reuse approved PR head and review".into();
4973 t.release_operator("cli", None);
4974 assert!(!compatible_instruction(&old, &t));
4975 let approved = instruction_for(&t);
4976 assert!(approved.contains("waiting premises are superseded"));
4977 assert!(compatible_instruction(&approved, &t));
4978 assert_eq!(resumed_instruction(&approved, &t), approved);
4979 t.release_operator("web", None);
4980 assert!(compatible_instruction(&approved, &t));
4981 assert_eq!(t.resumption_history.len(), 1);
4982 t.start("run".into());
4983 assert!(instruction_for(&t).contains("Explicit operator resumption"));
4984 }
4985
4986 #[test]
4990 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
4991 let mut state = RunState::new(
4992 PathBuf::from("/repo"),
4993 "main".to_owned(),
4994 "abc1234".to_owned(),
4995 "task".to_owned(),
4996 Config::default(),
4997 );
4998 state.status = RunStatus::Blocked;
4999 state.resource_block = Some(crate::run::ResourceBlock {
5000 node: "graft".to_owned(),
5001 kind: "shared build cache".to_owned(),
5002 detail: "timed out".to_owned(),
5003 at: jiff::Timestamp::now(),
5004 });
5005 let mut t = task();
5006 t.start("20260902-000000-aaaa".to_owned());
5007 assert_eq!(t.attempts, 1);
5008 let verdict = Verdict {
5009 status: RunStatus::Blocked,
5010 left_pr: false,
5011 quota_hit: false,
5012 parked: false,
5013 no_viable_candidates: false,
5014 };
5015 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5016 assert_eq!(t.status, TaskStatus::Held);
5017 assert_eq!(t.attempts, 0, "the attempt is refunded");
5018 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5019 assert!(
5020 !t.operator_held(),
5021 "a machine hold, released without a human"
5022 );
5023
5024 let mut p = task();
5026 p.start("20260902-000000-bbbb".to_owned());
5027 settle_and_diagnose(
5028 &mut p,
5029 Verdict {
5030 parked: true,
5031 ..verdict
5032 },
5033 "parked",
5034 2,
5035 &state,
5036 );
5037 assert_eq!(p.status, TaskStatus::Parked);
5038 }
5039
5040 #[test]
5041 fn record_failure_notice_links_the_task() {
5042 let dir = tempfile::tempdir().unwrap();
5043 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5046 let queue = Queue::at(dir.path().join("queue"));
5047 let mut t = interrupt_task("rec-fail-1");
5048 record(&queue, &mut t);
5049
5050 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5051 assert_eq!(found.len(), 1);
5052 assert_eq!(found[0].key, "loop:record");
5053 assert_eq!(
5054 found[0].link,
5055 Some(Link::Task {
5056 id: "rec-fail-1".to_owned()
5057 })
5058 );
5059 }
5060
5061 fn interrupt_task(id: &str) -> Task {
5064 let mut t = task();
5065 t.id = id.to_owned();
5066 t.interrupt = true;
5067 t
5068 }
5069
5070 fn task_with_id(id: &str) -> Task {
5072 let mut t = task();
5073 t.id = id.to_owned();
5074 t
5075 }
5076
5077 fn urgent_task(id: &str) -> Task {
5079 let mut t = task();
5080 t.id = id.to_owned();
5081 t.urgent = true;
5082 t
5083 }
5084
5085 #[test]
5086 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
5087 let dir = tempfile::tempdir().unwrap();
5088 let queue = Queue::at(dir.path().join("queue"));
5089 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5090 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5091 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
5092 let mut first = task();
5093 queue.put(&mut first).unwrap();
5094 let stale_plain = queue.get(&first.id).unwrap();
5095 first.set_urgent(true).unwrap();
5096 queue.put(&mut first).unwrap();
5097 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
5098 let mut second = urgent_task("second");
5099 queue.put(&mut second).unwrap();
5100 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
5101 drop(queue.claim(&second.id).unwrap());
5102 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
5103 drop(dispatched);
5104 let stale_urgent = queue.get(&first.id).unwrap();
5105 first.set_urgent(false).unwrap();
5106 queue.put(&mut first).unwrap();
5107 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
5108 assert_eq!(urgent.available_permits(), 1);
5109 drop(queue.claim(&first.id).unwrap());
5110 drop(occupied);
5111 }
5112
5113 #[test]
5114 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
5115 let dir = tempfile::tempdir().unwrap();
5116 let queue = Queue::at(dir.path().join("queue"));
5117 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5118 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5119 let mut t = task();
5120 queue.put(&mut t).unwrap();
5121 for enabled in [true, false] {
5122 let stale = queue.get(&t.id).unwrap();
5123 t.set_urgent(enabled).unwrap();
5124 queue.put(&mut t).unwrap();
5125 assert_ne!(stale.urgent, enabled);
5126 let DispatchClaim {
5127 task: fresh,
5128 claim,
5129 permit,
5130 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
5131 assert_eq!(fresh.urgent, enabled);
5132 assert_eq!(ordinary.available_permits(), usize::from(enabled));
5133 assert_eq!(urgent.available_permits(), usize::from(!enabled));
5134 assert!(queue.claim(&t.id).is_err());
5135 assert_eq!(fresh.attempts, stale.attempts);
5136 drop((claim, permit));
5137 assert_eq!(ordinary.available_permits(), 1);
5138 assert_eq!(urgent.available_permits(), 1);
5139 }
5140 t.set_urgent(true).unwrap();
5141 queue.put(&mut t).unwrap();
5142 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
5143 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5144 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
5145 drop(queue.claim(&t.id).unwrap());
5146 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
5147 drop(occupied);
5148 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
5149 drop(queue.claim(&t.id).unwrap());
5150 let held = queue.claim(&t.id).unwrap();
5151 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5152 drop(held);
5153 t.status = TaskStatus::Held;
5154 queue.put(&mut t).unwrap();
5155 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5156 drop(queue.claim(&t.id).unwrap());
5157 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
5158 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5159 drop(queue.claim(&t.id).unwrap());
5160 assert_eq!(urgent.available_permits(), 1);
5161 }
5162
5163 #[test]
5168 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
5169 assert_eq!(permit_kind(true, false), PermitKind::None);
5170 assert_eq!(permit_kind(true, true), PermitKind::None);
5171 }
5172
5173 #[test]
5178 fn permit_kind_separates_urgent_from_ordinary() {
5179 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
5180 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
5181 }
5182
5183 #[test]
5190 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
5191 let cfg = Config::default();
5192 let repo = Path::new("/any/repo/path");
5193
5194 let reason =
5195 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
5196 assert!(reason.contains("1024"), "{reason}");
5197 assert!(
5198 reason.contains(&cfg.disk.min_free_bytes.to_string()),
5199 "{reason}"
5200 );
5201
5202 assert_eq!(
5203 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
5204 None,
5205 "exactly at the floor is open"
5206 );
5207 assert_eq!(
5208 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
5209 None,
5210 "comfortably above the floor is open"
5211 );
5212 }
5213
5214 #[test]
5215 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
5216 let mut cfg = Config::default();
5217 cfg.disk.min_free_bytes = 0;
5218 let repo = Path::new("/any/repo/path");
5219 assert_eq!(
5220 disk_gate_with(repo, &cfg, |_| Ok(0)),
5221 None,
5222 "a zero floor never measures at all"
5223 );
5224 }
5225
5226 #[test]
5227 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5228 let cfg = Config::default();
5229 let repo = Path::new("/any/repo/path");
5230 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5231 .expect("a measurement failure must close the gate, not open it");
5232 assert!(reason.contains("could not measure"), "{reason}");
5233 }
5234
5235 #[test]
5236 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5237 let ordinary = task();
5238 let next = advance_interrupt(
5239 Interrupt::Idle,
5240 std::slice::from_ref(&ordinary.id),
5241 std::slice::from_ref(&ordinary),
5242 );
5243 assert_eq!(next, Interrupt::Idle);
5244 }
5245
5246 #[test]
5247 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
5248 let marked = interrupt_task("marked");
5251 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5252 assert_eq!(next, Interrupt::Idle);
5253 }
5254
5255 #[test]
5256 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
5257 let marked = interrupt_task("marked");
5258 let next = advance_interrupt(
5259 Interrupt::Idle,
5260 &["running".to_owned()],
5261 std::slice::from_ref(&marked),
5262 );
5263 assert_eq!(
5264 next,
5265 Interrupt::Parking {
5266 parked: vec!["running".to_owned()],
5267 interrupt_task: "marked".to_owned(),
5268 }
5269 );
5270 }
5271
5272 #[test]
5281 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
5282 let marked = interrupt_task("marked");
5283
5284 let two = advance_interrupt(
5285 Interrupt::Idle,
5286 &["a".to_owned(), "b".to_owned()],
5287 std::slice::from_ref(&marked),
5288 );
5289 assert_eq!(two, Interrupt::Idle);
5290
5291 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5292 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
5293 }
5294
5295 #[test]
5296 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
5297 let state = Interrupt::Parking {
5298 parked: vec!["running".to_owned()],
5299 interrupt_task: "marked".to_owned(),
5300 };
5301 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
5303 assert_eq!(still_going, state);
5304
5305 let stopped_but_not_yet_dispatched =
5309 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
5310 assert_eq!(stopped_but_not_yet_dispatched, state);
5311
5312 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
5314 assert_eq!(
5315 dispatched,
5316 Interrupt::Running {
5317 parked: vec!["running".to_owned()],
5318 interrupt_task: "marked".to_owned(),
5319 }
5320 );
5321 }
5322
5323 #[test]
5324 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
5325 let state = Interrupt::Running {
5326 parked: vec!["running".to_owned()],
5327 interrupt_task: "marked".to_owned(),
5328 };
5329 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
5330 assert_eq!(still_running, state);
5331
5332 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
5339 assert_eq!(
5340 ended,
5341 Interrupt::Resuming {
5342 parked: vec!["running".to_owned()]
5343 }
5344 );
5345 }
5346
5347 #[test]
5348 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
5349 let state = Interrupt::Resuming {
5350 parked: vec!["running".to_owned()],
5351 };
5352 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
5353 assert_eq!(still_waiting, state);
5354
5355 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
5356 assert_eq!(dispatched, Interrupt::Idle);
5357 }
5358
5359 #[test]
5365 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
5366 {
5367 let state = Interrupt::Parking {
5368 parked: vec!["running".to_owned()],
5369 interrupt_task: "marked".to_owned(),
5370 };
5371 let next = advance_interrupt(state, &[], &[]);
5374 assert_eq!(
5375 next,
5376 Interrupt::Resuming {
5377 parked: vec!["running".to_owned()]
5378 },
5379 "abandoning the interrupt must not abandon the resume it owes"
5380 );
5381 }
5382
5383 #[test]
5386 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
5387 let state = Interrupt::Resuming {
5388 parked: vec!["running".to_owned()],
5389 };
5390 let next = advance_interrupt(state, &[], &[]);
5391 assert_eq!(
5392 next,
5393 Interrupt::Idle,
5394 "nothing is left to wait for; the loop must not stay wedged"
5395 );
5396 }
5397
5398 #[test]
5399 fn disabled_by_config_the_sequence_can_never_leave_idle() {
5400 let marked = interrupt_task("marked");
5401 let next = advance_interrupt_tick(
5402 false,
5403 Interrupt::Idle,
5404 &["running".to_owned()],
5405 std::slice::from_ref(&marked),
5406 );
5407 assert_eq!(
5408 next,
5409 Interrupt::Idle,
5410 "an unmarked, unconfigured daemon must behave exactly as before"
5411 );
5412 }
5413
5414 #[test]
5415 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
5416 let state = Interrupt::Parking {
5417 parked: vec!["running".to_owned()],
5418 interrupt_task: "marked".to_owned(),
5419 };
5420 let candidates = vec![interrupt_task("marked"), task()];
5421 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5422 assert!(
5423 allowed.is_empty(),
5424 "nothing may dispatch - not even the interrupt task itself - \
5425 until the parked run has actually stopped"
5426 );
5427 }
5428
5429 #[test]
5443 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
5444 for state in [
5445 Interrupt::Parking {
5446 parked: vec!["running".to_owned()],
5447 interrupt_task: "marked".to_owned(),
5448 },
5449 Interrupt::Running {
5450 parked: vec!["running".to_owned()],
5451 interrupt_task: "marked".to_owned(),
5452 },
5453 Interrupt::Resuming {
5454 parked: vec!["running".to_owned()],
5455 },
5456 ] {
5457 let candidates = vec![
5458 interrupt_task("marked"),
5459 urgent_task("hot"),
5460 task_with_id("ordinary"),
5461 ];
5462 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5463 assert!(
5464 !allowed.iter().any(|t| t.id == "hot"),
5465 "an urgent candidate must wait out the same gate as anything \
5466 else while the run it would run alongside has not actually \
5467 left flight, for state {state:?}: {allowed:?}"
5468 );
5469 }
5470 }
5471
5472 #[test]
5478 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
5479 let state = Interrupt::Resuming {
5480 parked: vec!["hot".to_owned()],
5481 };
5482 let candidates = vec![urgent_task("hot"), task()];
5483 let allowed = interrupt_gate(&state, &[], candidates);
5484 assert_eq!(
5485 allowed.iter().filter(|t| t.id == "hot").count(),
5486 1,
5487 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
5488 );
5489 }
5490
5491 #[test]
5492 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
5493 let state = Interrupt::Parking {
5494 parked: vec!["running".to_owned()],
5495 interrupt_task: "marked".to_owned(),
5496 };
5497 let other = task();
5498 let candidates = vec![interrupt_task("marked"), other.clone()];
5499 let allowed = interrupt_gate(&state, &[], candidates);
5500 assert_eq!(allowed.len(), 1);
5501 assert_eq!(allowed[0].id, "marked");
5502 }
5503
5504 #[test]
5505 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
5506 let state = Interrupt::Running {
5507 parked: vec!["running".to_owned()],
5508 interrupt_task: "marked".to_owned(),
5509 };
5510 let candidates = vec![task(), task()];
5511 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
5512 assert!(allowed.is_empty());
5513 }
5514
5515 #[test]
5522 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
5523 let state = Interrupt::Resuming {
5524 parked: vec!["a".to_owned(), "c".to_owned()],
5525 };
5526 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
5527 let allowed = interrupt_gate(&state, &[], candidates);
5528 assert_eq!(
5529 allowed.len(),
5530 1,
5531 "at most one candidate may be offered while resuming: {allowed:?}"
5532 );
5533 assert_eq!(allowed[0].id, "a");
5534 }
5535
5536 #[test]
5537 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
5538 let state = Interrupt::Resuming {
5539 parked: vec!["a".to_owned()],
5540 };
5541 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
5542 assert!(allowed.is_empty());
5543 }
5544
5545 #[test]
5551 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
5552 let running = task(); let marked = interrupt_task("marked");
5554
5555 let mut state = Interrupt::Idle;
5556 let in_flight = vec![running.id.clone()];
5558 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
5559 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
5560 assert!(gated.is_empty(), "still waiting on `running` to park");
5561
5562 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
5564 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
5565 assert_eq!(
5566 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5567 vec!["marked"],
5568 "only the interrupt task may be offered to the dispatcher now"
5569 );
5570
5571 state = advance_interrupt_tick(
5573 true,
5574 state,
5575 &["marked".to_owned()],
5576 std::slice::from_ref(&running),
5577 );
5578 let gated = interrupt_gate(
5579 &state,
5580 &["marked".to_owned()],
5581 vec![marked.clone(), running.clone()],
5582 );
5583 assert!(
5584 gated.is_empty(),
5585 "the parked run must not be offered back while the interrupt \
5586 task is still running"
5587 );
5588
5589 let other = task_with_id("other");
5593 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
5594 assert_eq!(
5595 state,
5596 Interrupt::Resuming {
5597 parked: vec![running.id.clone()]
5598 }
5599 );
5600 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
5601 assert_eq!(
5602 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5603 vec![running.id.as_str()],
5604 "exactly the parked run resumes - not the unrelated task, even \
5605 though it was offered first"
5606 );
5607
5608 state = advance_interrupt_tick(
5612 true,
5613 state,
5614 std::slice::from_ref(&running.id),
5615 std::slice::from_ref(&other),
5616 );
5617 assert_eq!(state, Interrupt::Idle);
5618 let gated = interrupt_gate(
5619 &state,
5620 std::slice::from_ref(&running.id),
5621 vec![other.clone()],
5622 );
5623 assert_eq!(
5624 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5625 vec![other.id.as_str()],
5626 "ordinary dispatch is unrestricted again"
5627 );
5628 }
5629
5630 #[test]
5631 fn every_run_status_settles_the_task_it_came_from() {
5632 let table = [
5634 (RunStatus::Merged, TaskStatus::Done, 1),
5635 (RunStatus::Ready, TaskStatus::Done, 1),
5636 (RunStatus::Stalled, TaskStatus::Failed, 0),
5637 (RunStatus::Blocked, TaskStatus::Failed, 1),
5638 (RunStatus::Failed, TaskStatus::Failed, 1),
5639 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
5640 (RunStatus::Prep, TaskStatus::Failed, 1),
5641 (RunStatus::Implementing, TaskStatus::Failed, 1),
5642 (RunStatus::Judging, TaskStatus::Failed, 1),
5643 (RunStatus::Deliberating, TaskStatus::Failed, 1),
5644 (RunStatus::Voting, TaskStatus::Failed, 1),
5645 (RunStatus::Reviewing, TaskStatus::Failed, 1),
5646 (RunStatus::Gating, TaskStatus::Failed, 1),
5647 ];
5648 for (run, want, attempts) in table {
5649 let mut t = task();
5650 t.start("20260902-000000-aaaa".to_owned());
5651 settle(
5652 &mut t,
5653 Verdict {
5654 status: run,
5655 left_pr: false,
5656 parked: false,
5657 quota_hit: matches!(run, RunStatus::Stalled),
5658 no_viable_candidates: false,
5659 },
5660 "why",
5661 2,
5662 );
5663 assert_eq!(t.status, want, "task status after {}", label(run));
5664 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
5665 }
5666 }
5667
5668 #[test]
5669 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
5670 let mut stalled = task();
5671 stalled.start("20260902-000000-aaaa".to_owned());
5672 settle(
5673 &mut stalled,
5674 Verdict {
5675 status: RunStatus::Stalled,
5676 left_pr: false,
5677 parked: false,
5678 quota_hit: true,
5679 no_viable_candidates: false,
5680 },
5681 "quota",
5682 1,
5683 );
5684 assert_eq!(stalled.attempts, 0);
5685 assert!(
5686 stalled.status.runnable(),
5687 "a machine problem must leave the task in line"
5688 );
5689
5690 let mut blocked = task();
5691 blocked.start("20260902-000000-aaaa".to_owned());
5692 settle(
5693 &mut blocked,
5694 Verdict {
5695 status: RunStatus::Blocked,
5696 left_pr: false,
5697 parked: false,
5698 quota_hit: false,
5699 no_viable_candidates: false,
5700 },
5701 "findings open",
5702 1,
5703 );
5704 assert_eq!(blocked.attempts, 1);
5705 assert_eq!(
5706 blocked.status,
5707 TaskStatus::Held,
5708 "the last attempt hands the task to a human"
5709 );
5710 }
5711
5712 #[test]
5713 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
5714 let mut delivered = task();
5717 delivered.start("20260903-080619-01c2".to_owned());
5718 settle(
5719 &mut delivered,
5720 Verdict {
5721 status: RunStatus::Blocked,
5722 left_pr: true,
5723 parked: false,
5724 quota_hit: false,
5725 no_viable_candidates: false,
5726 },
5727 "no check status",
5728 4,
5729 );
5730 assert_eq!(
5731 delivered.status,
5732 TaskStatus::Held,
5733 "a pull request waiting on CI or a person is not a retryable failure"
5734 );
5735 assert!(
5736 !delivered.status.runnable(),
5737 "the loop must not pick this task up again"
5738 );
5739 assert_eq!(
5740 delivered.last_error.as_deref(),
5741 Some("no check status"),
5742 "the operator needs to be told what the gate was waiting for"
5743 );
5744
5745 let mut empty_handed = task();
5748 empty_handed.start("20260903-080619-01c2".to_owned());
5749 settle(
5750 &mut empty_handed,
5751 Verdict {
5752 status: RunStatus::Blocked,
5753 left_pr: false,
5754 parked: false,
5755 quota_hit: false,
5756 no_viable_candidates: false,
5757 },
5758 "findings open",
5759 4,
5760 );
5761 assert_eq!(empty_handed.status, TaskStatus::Failed);
5762 assert!(empty_handed.status.runnable());
5763 }
5764
5765 #[test]
5766 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
5767 let mut noop = task();
5773 noop.start("20260912-131304-391f".to_owned());
5774 settle(
5775 &mut noop,
5776 Verdict {
5777 status: RunStatus::VerifiedNoop,
5778 left_pr: false,
5779 parked: false,
5780 quota_hit: false,
5781 no_viable_candidates: true,
5782 },
5783 "candidate A: already fixed by b32cfc4, on main",
5784 4,
5785 );
5786 assert_eq!(
5787 noop.status,
5788 TaskStatus::Held,
5789 "an unverified claim is a request for a human, not a failure"
5790 );
5791 assert!(
5792 !noop.status.runnable(),
5793 "the loop must not requeue this on the same unverified claim"
5794 );
5795 assert_eq!(noop.attempts, 1);
5800 }
5801
5802 #[test]
5803 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
5804 let mut parked = task();
5809 parked.start("20260903-183634-2d98".to_owned());
5810 settle(
5811 &mut parked,
5812 Verdict {
5813 status: RunStatus::Implementing,
5814 left_pr: false,
5815 quota_hit: false,
5816 parked: true,
5817 no_viable_candidates: false,
5818 },
5819 "parked after `implementing`",
5820 2,
5821 );
5822 assert_eq!(parked.attempts, 0, "a park is refunded");
5823 assert!(
5824 parked.status.runnable(),
5825 "and the task stays in line so the next loop resumes its run"
5826 );
5827 assert_eq!(parked.status, TaskStatus::Parked);
5828 assert_eq!(
5829 parked.park_reason.as_deref(),
5830 Some("parked after `implementing`"),
5831 "the card says where it stopped"
5832 );
5833 assert_eq!(parked.last_error, None, "nothing failed");
5834
5835 let mut broken = task();
5839 broken.start("20260903-183634-2d98".to_owned());
5840 settle(
5841 &mut broken,
5842 Verdict {
5843 status: RunStatus::Implementing,
5844 left_pr: false,
5845 quota_hit: false,
5846 parked: false,
5847 no_viable_candidates: false,
5848 },
5849 "returned mid-flight",
5850 2,
5851 );
5852 assert_eq!(broken.attempts, 1);
5853 }
5854
5855 #[test]
5856 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
5857 let mut flaky = task();
5862 flaky.start("20260903-123023-e633".to_owned());
5863 settle(
5864 &mut flaky,
5865 Verdict {
5866 status: RunStatus::Stalled,
5867 left_pr: false,
5868 parked: false,
5869 quota_hit: false,
5870 no_viable_candidates: false,
5871 },
5872 "verdict rests on 1 of 3 judges",
5873 2,
5874 );
5875 assert_eq!(
5876 flaky.attempts, 1,
5877 "flakiness spends an attempt, so `max_attempts` still bounds it"
5878 );
5879 assert!(flaky.status.runnable(), "and it is still worth retrying");
5880
5881 let mut limited = task();
5883 limited.start("20260903-123023-e633".to_owned());
5884 settle(
5885 &mut limited,
5886 Verdict {
5887 status: RunStatus::Stalled,
5888 left_pr: false,
5889 parked: false,
5890 quota_hit: true,
5891 no_viable_candidates: false,
5892 },
5893 "judge-2, judge-3 out of quota",
5894 2,
5895 );
5896 assert_eq!(limited.attempts, 0, "a quota window is refunded");
5897 assert!(limited.status.runnable());
5898
5899 let mut worn = task();
5902 for _ in 0..2 {
5903 worn.release();
5904 }
5905 worn.start("20260903-123023-e633".to_owned());
5906 worn.attempts = 2;
5907 settle(
5908 &mut worn,
5909 Verdict {
5910 status: RunStatus::Stalled,
5911 left_pr: false,
5912 parked: false,
5913 quota_hit: false,
5914 no_viable_candidates: false,
5915 },
5916 "no quorum again",
5917 2,
5918 );
5919 assert_eq!(worn.status, TaskStatus::Held);
5920 assert!(!worn.status.runnable());
5921 }
5922
5923 #[test]
5924 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5925 let mut wiped_out = task();
5932 wiped_out.start("20260907-025000-a1b2".to_owned());
5933 settle(
5934 &mut wiped_out,
5935 Verdict {
5936 status: RunStatus::Failed,
5937 left_pr: false,
5938 parked: false,
5939 quota_hit: true,
5940 no_viable_candidates: true,
5941 },
5942 "no candidate produced a change; nothing to judge",
5943 2,
5944 );
5945 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5946 assert!(
5947 wiped_out.status.runnable(),
5948 "a machine problem must leave the task in line"
5949 );
5950
5951 let mut partial_progress = task();
5957 partial_progress.start("20260907-025500-c3d4".to_owned());
5958 settle(
5959 &mut partial_progress,
5960 Verdict {
5961 status: RunStatus::Failed,
5962 left_pr: false,
5963 parked: false,
5964 quota_hit: true,
5965 no_viable_candidates: false,
5966 },
5967 "gate failed on the winning candidate",
5968 2,
5969 );
5970 assert_eq!(
5971 partial_progress.attempts, 1,
5972 "a candidate that actually produced a change spends the attempt \
5973 even though some other seat hit its quota"
5974 );
5975 assert!(partial_progress.status.runnable());
5976 }
5977
5978 #[test]
5979 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5980 let mut t = task();
5986 t.start("20260907-025000-a1b2".to_owned());
5987 let mut state = run_state(RunStatus::Failed);
5988 state.quota.push(QuotaLoss {
5989 seat: "cand-a".to_owned(),
5990 node: "implement".to_owned(),
5991 at: Timestamp::now(),
5992 reset: None,
5993 });
5994 assert!(
5995 state.viable().is_empty(),
5996 "no candidate was added, so nothing is viable"
5997 );
5998 reclaim(&mut t, Some(state), 2, "en");
5999 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6000 assert!(t.status.runnable());
6001 }
6002
6003 #[test]
6004 fn a_held_task_is_never_offered_to_the_loop() {
6005 let dir = tempfile::tempdir().unwrap();
6006 let queue = Queue::at(dir.path().to_path_buf());
6007 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6008 let mut t = task();
6009 t.id = format!("2026090{n}-000000-000{n}");
6010 t.priority = priority;
6011 queue.put(&mut t).unwrap();
6012 }
6013 let mut held = task();
6014 held.id = "20260909-000000-9999".to_owned();
6015 held.priority = 99;
6016 held.hold_machine(None);
6017 queue.put(&mut held).unwrap();
6018
6019 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6020 assert_eq!(order.len(), 3);
6021 assert!(!order.contains(&held.id));
6022 assert_eq!(
6023 order.first().cloned(),
6024 queue.next_runnable().map(|t| t.id),
6025 "the loop's first candidate is exactly what the queue offers"
6026 );
6027 assert_eq!(
6028 order,
6029 vec![
6030 "20260902-000000-0002".to_owned(),
6031 "20260903-000000-0003".to_owned(),
6032 "20260901-000000-0001".to_owned(),
6033 ],
6034 "priority first, then oldest, so nothing starves"
6035 );
6036 }
6037
6038 #[test]
6039 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6040 let dir = tempfile::tempdir().unwrap();
6041 let queue = Queue::at(dir.path().to_path_buf());
6042 let mut old = task();
6043 old.id = "20260101-000000-old0".to_owned();
6044 queue.put(&mut old).unwrap();
6045 let mut fresh = task();
6046 fresh.id = "20260101-000000-new0".to_owned();
6047 queue.put(&mut fresh).unwrap();
6048
6049 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
6053 std::thread::sleep(Duration::from_millis(60));
6054 let live = queue.claim(&fresh.id).unwrap();
6055
6056 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6057 assert_eq!(swept, vec![old.id.clone()]);
6058 assert!(
6059 queue.claim(&old.id).is_ok(),
6060 "an unparseable lock older than the threshold is swept"
6061 );
6062 assert!(
6063 queue.claim(&fresh.id).is_err(),
6064 "a live pid protects its lock regardless of age"
6065 );
6066 drop(live);
6067 }
6068
6069 #[test]
6070 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
6071 let dir = tempfile::tempdir().unwrap();
6081 let queue = Queue::at(dir.path().to_path_buf());
6082 let mut t = task();
6083 t.id = "20260101-000000-live".to_owned();
6084 queue.put(&mut t).unwrap();
6085
6086 let claim = queue.claim(&t.id).unwrap();
6087 std::thread::sleep(Duration::from_millis(60));
6088
6089 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6090 assert!(
6091 swept.is_empty(),
6092 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
6093 );
6094 assert!(
6095 queue.claim(&t.id).is_err(),
6096 "the lock still protects its task"
6097 );
6098 drop(claim);
6099 }
6100
6101 fn injected_dead_pid() -> u32 {
6104 std::process::id().checked_add(1).unwrap_or(1)
6105 }
6106
6107 #[test]
6108 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
6109 let dir = tempfile::tempdir().unwrap();
6110 let queue = Queue::at(dir.path().to_path_buf());
6111 let mut t = task();
6112 t.id = "20260101-000000-dead".to_owned();
6113 queue.put(&mut t).unwrap();
6114 let dead_pid = injected_dead_pid();
6115
6116 std::fs::write(
6121 dir.path().join(format!("{}.lock", t.id)),
6122 dead_pid.to_string(),
6123 )
6124 .unwrap();
6125
6126 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6127 pid != dead_pid
6128 });
6129 assert_eq!(
6130 swept,
6131 vec![t.id.clone()],
6132 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
6133 );
6134 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
6135 }
6136
6137 #[test]
6138 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
6139 let dir = tempfile::tempdir().unwrap();
6140 let queue = Queue::at(dir.path().to_path_buf());
6141 let mut t = task();
6142 t.id = "20260101-000000-late".to_owned();
6143 queue.put(&mut t).unwrap();
6144 let dead_pid = injected_dead_pid();
6145
6146 assert!(
6149 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
6150 "nothing has claimed the task yet"
6151 );
6152
6153 std::fs::write(
6156 dir.path().join(format!("{}.lock", t.id)),
6157 dead_pid.to_string(),
6158 )
6159 .unwrap();
6160
6161 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6165 pid != dead_pid
6166 });
6167 assert_eq!(swept, vec![t.id.clone()]);
6168 }
6169
6170 #[test]
6171 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
6172 crate::run::pin_test_home();
6177 let dir = tempfile::tempdir().unwrap();
6178 let queue = Queue::at(dir.path().to_path_buf());
6179 let mut t = task();
6180 t.id = "20260101-000000-crsh".to_owned();
6181 t.status = TaskStatus::Running;
6182 t.attempts = 1;
6183 t.runs.push("20260904-000000-4043".to_owned());
6187 queue.put(&mut t).unwrap();
6188 let dead_pid = injected_dead_pid();
6189
6190 std::fs::write(
6193 dir.path().join(format!("{}.lock", t.id)),
6194 dead_pid.to_string(),
6195 )
6196 .unwrap();
6197
6198 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
6204 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6205
6206 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6207 pid != dead_pid
6208 });
6209 assert_eq!(swept, vec![t.id.clone()]);
6210
6211 let reclaimed = reclaim_orphaned_running(&queue, 2);
6212 assert_eq!(reclaimed, vec![t.id.clone()]);
6213 let after = queue.get(&t.id).unwrap();
6214 assert_eq!(
6215 after.status,
6216 TaskStatus::Held,
6217 "no run.json to recover from, so a human is asked"
6218 );
6219 assert_eq!(
6220 after.runs,
6221 vec!["20260904-000000-4043".to_owned()],
6222 "the crashed run's id is kept as evidence, not discarded"
6223 );
6224 }
6225
6226 #[test]
6227 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6228 let dir = tempfile::tempdir().unwrap();
6229 let queue = Queue::at(dir.path().to_path_buf());
6230 let mut t = task();
6231 t.id = "20260101-000000-unknown".to_owned();
6232 queue.put(&mut t).unwrap();
6233 let dead_pid = injected_dead_pid();
6234 std::fs::write(
6235 dir.path().join(format!("{}.lock", t.id)),
6236 dead_pid.to_string(),
6237 )
6238 .unwrap();
6239
6240 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
6241 assert!(swept.is_empty(), "an unknown pid must keep its lock");
6242 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
6243 }
6244
6245 fn run_state_in(status: RunStatus, language: &str) -> RunState {
6246 let mut s = run_state(status);
6247 s.config.graph.language = language.to_owned();
6248 s
6249 }
6250
6251 fn unstarted_verdict(status: RunStatus) -> Verdict {
6252 Verdict {
6253 status,
6254 left_pr: false,
6255 quota_hit: false,
6256 parked: false,
6257 no_viable_candidates: false,
6258 }
6259 }
6260
6261 #[test]
6262 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
6263 let mut t = task();
6264 t.attempts = 1;
6265 settle_in(
6266 &mut t,
6267 unstarted_verdict(RunStatus::AlreadyInBase),
6268 "already in main",
6269 1,
6270 phrases("en"),
6271 );
6272 assert_eq!(t.status, TaskStatus::Done);
6273 assert_eq!(t.attempts, 0);
6274 }
6275
6276 #[test]
6277 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
6278 let reason = |language: &str| {
6279 let mut t = task();
6280 settle_in(
6281 &mut t,
6282 unstarted_verdict(RunStatus::Judging),
6283 "boom",
6284 1,
6285 phrases(language),
6286 );
6287 t.last_error.or(t.hold_reason).unwrap_or_default()
6288 };
6289 assert!(
6290 reason("en").starts_with("the graph stopped at `"),
6291 "{}",
6292 reason("en")
6293 );
6294 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
6295 assert!(reason("日本語").contains("boom"));
6296 assert_eq!(reason("fr"), reason("en"));
6297 }
6298
6299 #[test]
6300 fn describe_follows_the_run_language_and_keeps_the_run_id() {
6301 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
6302 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
6303 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
6304 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
6305 assert!(ja.contains("[run "), "{ja}");
6306 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
6307 assert!(ended.starts_with("run 終了: "), "{ended}");
6308 let mut de = run_state_in(RunStatus::Failed, "de");
6309 let mut en = run_state_in(RunStatus::Failed, "en");
6310 de.id = "same".to_owned();
6311 en.id = "same".to_owned();
6312 assert_eq!(describe(&de), describe(&en));
6313 }
6314
6315 #[test]
6316 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
6317 use crate::handover::Refused;
6318 let cases = [
6319 Refused::Foreign {
6320 branch: "b".into(),
6321 path: "/w/x".into(),
6322 why: "made by hand".into(),
6323 },
6324 Refused::Unsafe {
6325 branch: "b".into(),
6326 path: "/w/x".into(),
6327 why: "its worktree has uncommitted changes (a.rs)".into(),
6328 },
6329 Refused::ReleaseFailed {
6330 branch: "b".into(),
6331 path: "/w/x".into(),
6332 run: "ab12".into(),
6333 },
6334 ];
6335 for r in &cases {
6336 let en = (phrases("en").handover_refused)(r);
6337 assert_eq!(en, r.to_string());
6338 let ja = (phrases("ja").handover_refused)(r);
6339 assert!(
6340 !ja.contains("is checked out") && !ja.contains("try again"),
6341 "{ja}"
6342 );
6343 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
6344 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
6345 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
6346 }
6347 }
6348 assert!(phrases("en").handover_hint.contains("release the task"));
6349 assert!(phrases("ja").handover_hint.contains("解放"));
6350 }
6351
6352 #[test]
6353 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
6354 let build = |lang: &str| {
6355 let mut s = run_state_in(RunStatus::Blocked, lang);
6356 s.id = "same".to_owned();
6357 s.config.graph.review_rounds = 3;
6358 let mut r = review_round(3);
6359 r.expected = 3;
6360 r.answered = 1;
6361 s.reviews.push(r);
6362 s.event(
6363 "review",
6364 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
6365 );
6366 s
6367 };
6368 let en = describe(&build("en"));
6369 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
6370 let ja = describe(&build("ja"));
6371 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
6372 assert!(!ja.contains("never answered"), "{ja}");
6373 assert!(ja.contains("[run "), "{ja}");
6374
6375 let mut failed = build("ja");
6378 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
6379 command: "cargo test".to_owned(),
6380 code: Some(1),
6381 output_tail: String::new(),
6382 duration_ms: 0,
6383 resource_blocked: false,
6384 });
6385 failed.event("review", "stopped; e2e failed: cargo test");
6386 let ja = describe(&failed);
6387 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
6388 assert!(!ja.contains("席のレビュアー"), "{ja}");
6389 }
6390
6391 #[test]
6392 fn refusals_and_recovery_prose_follow_the_language() {
6393 let t = held_task_with("r1");
6394 let q = action_question(
6395 "r1",
6396 ask::ChoiceAction::Resume {
6397 run: "r1".to_owned(),
6398 },
6399 );
6400 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
6401 ActionDecision::Refuse(s) => s,
6402 other => panic!("{other:?}"),
6403 };
6404 assert!(refuse(phrases("en")).contains("could not be read: gone"));
6405 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
6406 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
6407
6408 let mut held = task();
6409 reclaim(&mut held, None, 2, "ja");
6410 assert!(held.hold_reason.unwrap().contains("保留にしました"));
6411 let mut held = task();
6412 reclaim(&mut held, None, 2, "xx");
6413 assert!(held.hold_reason.unwrap().contains("held for a human"));
6414 }
6415
6416 fn run_state(status: RunStatus) -> RunState {
6417 let mut state = RunState::new(
6418 PathBuf::from("/repo"),
6419 "main".to_owned(),
6420 "abc1234def".to_owned(),
6421 "add retries".to_owned(),
6422 Config::default(),
6423 );
6424 state.status = status;
6425 state
6426 }
6427
6428 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
6429 Candidate {
6430 index: 0,
6431 label,
6432 agent: "claude".to_owned(),
6433 branch: format!("magi/x/{label}"),
6434 worktree: PathBuf::from("/repo"),
6435 summary: summary.to_owned(),
6436 stat: String::new(),
6437 files: 0,
6438 commits: usize::from(!empty),
6439 empty,
6440 failed: failed.map(str::to_owned),
6441 verified_noop: None,
6442 duration_ms: 0,
6443 folded: false,
6444 }
6445 }
6446
6447 #[test]
6448 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
6449 let mut state = run_state(RunStatus::Blocked);
6450 state.gate = vec![
6451 CommandOutcome {
6452 command: "cargo make check".to_owned(),
6453 code: Some(0),
6454 output_tail: "ok".to_owned(),
6455 duration_ms: 0,
6456 resource_blocked: false,
6457 },
6458 CommandOutcome {
6459 command: "cargo test".to_owned(),
6460 code: Some(101),
6461 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
6462 duration_ms: 0,
6463 resource_blocked: false,
6464 },
6465 ];
6466 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
6467 assert!(d.contains("cargo test"), "{d}");
6468 assert!(
6469 !d.contains("cargo make check"),
6470 "a passing check is not a diagnostic: {d}"
6471 );
6472 assert!(d.contains("assertion failed"), "{d}");
6473 }
6474
6475 #[test]
6476 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
6477 let mut state = run_state(RunStatus::Blocked);
6478 state.event(
6479 "land",
6480 "stopped: the fixer produced no commit while 2 check(s) were failing \
6481 (build, lint); stopping instead of looping on an unchanged tree",
6482 );
6483 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
6484 assert!(d.contains("build"), "{d}");
6485 assert!(d.contains("lint"), "{d}");
6486 assert!(d.contains("fixer produced no commit"), "{d}");
6487 }
6488
6489 #[test]
6490 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
6491 let state = run_state(RunStatus::VerifiedNoop);
6496 let d = describe(&state);
6497 assert!(
6498 d.contains("agent-verified no-op"),
6499 "expected the display label, not the wire spelling: {d}"
6500 );
6501 assert!(!d.contains("verified_noop"), "{d}");
6502 }
6503
6504 #[test]
6505 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
6506 let mut state = run_state(RunStatus::Failed);
6512 state.candidates = vec![candidate(
6513 'A',
6514 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
6515 true,
6516 None,
6517 )];
6518 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
6519 assert!(d.contains("candidate A"), "{d}");
6520 assert!(d.contains("tagged v1.2.3"), "{d}");
6521 }
6522
6523 #[test]
6524 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
6525 let mut state = run_state(RunStatus::Failed);
6526 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
6527 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
6528 assert!(d.contains("candidate A"), "{d}");
6529 assert!(d.contains("agent timed out"), "{d}");
6530 }
6531
6532 #[test]
6533 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
6534 let mut state = run_state(RunStatus::Failed);
6537 state.candidates = vec![candidate('A', "did the work", false, None)];
6538 assert!(diagnostic(&state).is_none());
6539 }
6540
6541 #[test]
6542 fn diagnostic_is_bounded_however_much_a_run_printed() {
6543 let mut state = run_state(RunStatus::Blocked);
6544 state.gate = vec![
6545 CommandOutcome {
6546 command: "cargo test".to_owned(),
6547 code: Some(101),
6548 output_tail: "x".repeat(50_000),
6549 duration_ms: 0,
6550 resource_blocked: false,
6551 },
6552 CommandOutcome {
6553 command: "cargo clippy".to_owned(),
6554 code: Some(1),
6555 output_tail: "y".repeat(50_000),
6556 duration_ms: 0,
6557 resource_blocked: false,
6558 },
6559 ];
6560 state.candidates = vec![
6561 candidate('A', &"z".repeat(50_000), true, None),
6562 candidate('B', &"w".repeat(50_000), true, None),
6563 ];
6564 let d = diagnostic(&state).expect("plenty here to diagnose");
6565 assert!(
6566 d.len() <= DIAGNOSTIC_MAX,
6567 "diagnostic grew to {} bytes, unbounded",
6568 d.len()
6569 );
6570 }
6571
6572 #[test]
6573 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
6574 let mut state = run_state(RunStatus::Blocked);
6575 state.gate = vec![CommandOutcome {
6576 command: "cargo test".to_owned(),
6577 code: Some(101),
6578 output_tail: "assertion failed".to_owned(),
6579 duration_ms: 0,
6580 resource_blocked: false,
6581 }];
6582 let verdict = Verdict {
6583 status: RunStatus::Blocked,
6584 left_pr: false,
6585 quota_hit: false,
6586 parked: false,
6587 no_viable_candidates: false,
6588 };
6589
6590 let mut t = task();
6593 t.start("run-1".to_owned());
6594 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6595 assert_eq!(t.status, TaskStatus::Failed);
6596 assert!(t.diagnostic.is_none());
6597
6598 t.start("run-2".to_owned());
6601 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6602 assert_eq!(t.status, TaskStatus::Held);
6603 let d = t.diagnostic.expect("a held task must carry its diagnostic");
6604 assert!(d.contains("cargo test"), "{d}");
6605 }
6606
6607 #[test]
6608 fn a_held_task_names_the_open_question_it_is_waiting_on() {
6609 crate::run::pin_test_home();
6614 let home = crate::run::home();
6615 let state = run_state(RunStatus::VerifiedNoop);
6616 let mut q = ask::Question::new(
6617 state.id.clone(),
6618 "implement".to_owned(),
6619 "impl-A".to_owned(),
6620 "is this really a no-op?".to_owned(),
6621 String::new(),
6622 Vec::new(),
6623 );
6624 Questions::at(home.join("questions")).put(&mut q).unwrap();
6625
6626 let verdict = Verdict {
6627 status: RunStatus::VerifiedNoop,
6628 left_pr: false,
6629 quota_hit: false,
6630 parked: false,
6631 no_viable_candidates: false,
6632 };
6633 let mut t = task();
6634 t.start(state.id.clone());
6635 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6636
6637 assert_eq!(t.status, TaskStatus::Held);
6638 let reason = t.hold_reason.expect("a held task must record why");
6639 assert!(
6640 reason.starts_with("run ended agent-verified no-op"),
6641 "the original settle reason must survive unchanged: {reason}"
6642 );
6643 assert!(
6644 reason.contains(q.short()),
6645 "the open question's id must be named so the notice is actionable: {reason}"
6646 );
6647 }
6648
6649 #[test]
6650 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
6651 crate::run::pin_test_home();
6652 let state = run_state(RunStatus::VerifiedNoop);
6653
6654 let verdict = Verdict {
6655 status: RunStatus::VerifiedNoop,
6656 left_pr: false,
6657 quota_hit: false,
6658 parked: false,
6659 no_viable_candidates: false,
6660 };
6661 let mut t = task();
6662 t.start(state.id.clone());
6663 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6664
6665 assert_eq!(t.status, TaskStatus::Held);
6666 assert_eq!(
6667 t.hold_reason.as_deref(),
6668 Some("run ended agent-verified no-op"),
6669 "nothing to append when the question was already answered or never asked"
6670 );
6671 }
6672
6673 #[test]
6674 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
6675 crate::run::pin_test_home();
6676 let mut first = run_state(RunStatus::Blocked);
6677 first.id = "20260101-000000-sup1".to_owned();
6678 first.save().unwrap();
6679 let mut second = run_state(RunStatus::Merged);
6680 second.id = "20260101-000000-sup2".to_owned();
6681 second.save().unwrap();
6682
6683 let mut t = task();
6684 t.runs = vec![first.id.clone(), second.id.clone()];
6685 t.status = TaskStatus::Done;
6686
6687 supersede_prior_runs(&t, &crate::run::home());
6688
6689 assert_eq!(
6690 RunState::load(&first.id).unwrap().status,
6691 RunStatus::Superseded,
6692 "the first attempt's Blocked no longer needs anyone's attention"
6693 );
6694 assert_eq!(
6695 RunState::load(&second.id).unwrap().status,
6696 RunStatus::Merged,
6697 "the run that actually succeeded is left exactly as it was"
6698 );
6699 }
6700
6701 #[test]
6702 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
6703 crate::run::pin_test_home();
6709 let mut first = run_state(RunStatus::Blocked);
6710 first.id = "20260101-000000-sup9".to_owned();
6711 first.driver_pid = Some(std::process::id());
6714 first.driver_started_at = Some(
6715 crate::proc::process_started_at(std::process::id())
6716 .expect("this test process's own start time must be queryable"),
6717 );
6718 first.save().unwrap();
6719 let mut second = run_state(RunStatus::Merged);
6720 second.id = "20260101-000000-supa".to_owned();
6721 second.save().unwrap();
6722
6723 let mut t = task();
6724 t.runs = vec![first.id.clone(), second.id.clone()];
6725 t.status = TaskStatus::Done;
6726
6727 supersede_prior_runs(&t, &crate::run::home());
6728
6729 assert_eq!(
6730 RunState::load(&first.id).unwrap().status,
6731 RunStatus::Blocked,
6732 "a live driver_pid means something is still actually working this run, \
6733 even though no daemon claims it - rewriting under it would just be \
6734 undone the next time that process saves"
6735 );
6736 }
6737
6738 #[test]
6739 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
6740 let dir = tempfile::tempdir().unwrap();
6746 let home = dir.path().to_path_buf();
6747 let queue = Queue::at(dir.path().join("queue"));
6748
6749 let mut first = run_state(RunStatus::Blocked);
6750 first.id = "20260101-000000-supd".to_owned();
6751 first.driver_pid = Some(std::process::id());
6752 first.driver_started_at = Some(
6753 crate::proc::process_started_at(std::process::id())
6754 .expect("this test process's own start time must be queryable"),
6755 );
6756 first.save_under(&home).unwrap();
6757 let mut second = run_state(RunStatus::Merged);
6758 second.id = "20260101-000000-supe".to_owned();
6759 second.save_under(&home).unwrap();
6760
6761 let mut t = task();
6762 t.runs = vec![first.id.clone(), second.id.clone()];
6763 t.status = TaskStatus::Done;
6764 queue.put(&mut t).unwrap();
6765
6766 resweep_superseded_attempts(&queue, &home);
6767 assert_eq!(
6768 RunState::load_under(&first.id, &home).unwrap().status,
6769 RunStatus::Blocked,
6770 "still live on the first pass, so still untouched"
6771 );
6772
6773 let mut stale = RunState::load_under(&first.id, &home).unwrap();
6779 stale.driver_started_at = Some("1".to_owned());
6780 stale.save_under(&home).unwrap();
6781
6782 resweep_superseded_attempts(&queue, &home);
6783 assert_eq!(
6784 RunState::load_under(&first.id, &home).unwrap().status,
6785 RunStatus::Superseded,
6786 "the second pass catches up what the first one correctly skipped"
6787 );
6788 }
6789
6790 #[test]
6791 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
6792 crate::run::pin_test_home();
6793 let mut first = run_state(RunStatus::Blocked);
6794 first.id = "20260101-000000-sup3".to_owned();
6795 first.save().unwrap();
6796 let mut second = run_state(RunStatus::Blocked);
6797 second.id = "20260101-000000-sup4".to_owned();
6798 second.save().unwrap();
6799
6800 let mut t = task();
6801 t.runs = vec![first.id.clone(), second.id.clone()];
6802 t.status = TaskStatus::Failed;
6806
6807 supersede_prior_runs(&t, &crate::run::home());
6808
6809 assert_eq!(
6810 RunState::load(&first.id).unwrap().status,
6811 RunStatus::Blocked
6812 );
6813 assert_eq!(
6814 RunState::load(&second.id).unwrap().status,
6815 RunStatus::Blocked
6816 );
6817 }
6818
6819 #[test]
6820 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
6821 crate::run::pin_test_home();
6825 let mut first = run_state(RunStatus::Blocked);
6826 first.id = "20260101-000000-sup5".to_owned();
6827 first.save().unwrap();
6828
6829 let mut t = task();
6830 t.runs = vec![first.id.clone()];
6831 t.status = TaskStatus::Done;
6832
6833 supersede_prior_runs(&t, &crate::run::home());
6834
6835 assert_eq!(
6836 RunState::load(&first.id).unwrap().status,
6837 RunStatus::Blocked,
6838 "a single-attempt task has no earlier run to supersede"
6839 );
6840 }
6841
6842 #[test]
6843 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
6844 crate::run::pin_test_home();
6851 let mut first = run_state(RunStatus::Blocked);
6852 first.id = "20260101-000000-supb".to_owned();
6853 first.save().unwrap();
6854 let mut second = run_state(RunStatus::Failed);
6855 second.id = "20260101-000000-supc".to_owned();
6856 second.save().unwrap();
6857
6858 let mut t = task();
6859 t.runs = vec![first.id.clone(), second.id.clone()];
6860 t.status = TaskStatus::Done;
6861
6862 supersede_prior_runs(&t, &crate::run::home());
6863
6864 assert_eq!(
6865 RunState::load(&first.id).unwrap().status,
6866 RunStatus::Blocked,
6867 "the task's last attempt never landed, so there is nothing here \
6868 actually superseding it"
6869 );
6870 }
6871
6872 #[test]
6873 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6874 crate::run::pin_test_home();
6878 let mut failed = run_state(RunStatus::Failed);
6879 failed.id = "20260101-000000-sup6".to_owned();
6880 failed.save().unwrap();
6881 let mut noop = run_state(RunStatus::VerifiedNoop);
6882 noop.id = "20260101-000000-sup7".to_owned();
6883 noop.save().unwrap();
6884 let mut winner = run_state(RunStatus::Ready);
6885 winner.id = "20260101-000000-sup8".to_owned();
6886 winner.save().unwrap();
6887
6888 let mut t = task();
6889 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6890 t.status = TaskStatus::Done;
6891
6892 supersede_prior_runs(&t, &crate::run::home());
6893
6894 assert_eq!(
6895 RunState::load(&failed.id).unwrap().status,
6896 RunStatus::Failed
6897 );
6898 assert_eq!(
6899 RunState::load(&noop.id).unwrap().status,
6900 RunStatus::VerifiedNoop
6901 );
6902 }
6903
6904 fn approval_question(run: &str) -> ask::Question {
6905 ask::Question::new(
6906 run.to_owned(),
6907 land::APPROVAL_NODE.to_owned(),
6908 "land".to_owned(),
6909 "merge?".to_owned(),
6910 String::new(),
6911 vec!["merge".to_owned(), "hold".to_owned()],
6912 )
6913 }
6914
6915 #[test]
6916 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6917 crate::run::pin_test_home();
6918 let mut state = run_state(RunStatus::Landing);
6919 state.id = "20260101-000000-fre1".to_owned();
6920 state.parked = true;
6921 state.save().unwrap();
6922 ask::Questions::open()
6923 .put(&mut approval_question(&state.id))
6924 .unwrap();
6925
6926 let mut t = task();
6927 t.runs.push(state.id.clone());
6928 assert_eq!(
6929 land_resume_state(&t),
6930 LandResume::StillWaiting,
6931 "nobody has answered and the timeout has not passed"
6932 );
6933 }
6934
6935 #[test]
6936 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6937 crate::run::pin_test_home();
6938 let mut state = run_state(RunStatus::Gating);
6939 state.id = "20260101-000000-gt01".to_owned();
6940 state.parked = true;
6941 state.config.graph.answer_timeout = 60;
6942 state.github_text = Some(crate::run::GithubTextAsk {
6943 rewrite: None,
6944 fingerprint: "f".into(),
6945 title: true,
6946 body: false,
6947 categories: vec!["title-language".into()],
6948 question: None,
6949 asks: 1,
6950 resolved: false,
6951 chosen_title: None,
6952 choice: None,
6953 });
6954 state.save().unwrap();
6955 let store = ask::Questions::open();
6956 let mut q = ask::Question::new(
6957 state.id.clone(),
6958 crate::github_text::ASK_NODE.to_owned(),
6959 crate::github_text::ASK_SEAT.to_owned(),
6960 "s".into(),
6961 String::new(),
6962 vec!["use fallback".into()],
6963 );
6964 store.put(&mut q).unwrap();
6965 let mut t = task();
6966 t.runs.push(state.id.clone());
6967 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6968 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6969 store.put(&mut q).unwrap();
6970 assert_eq!(land_resume_state(&t), LandResume::Ready);
6971 assert!(!store.get(&q.id).unwrap().status.open());
6972 state.github_text.as_mut().unwrap().resolved = true;
6974 state.save().unwrap();
6975 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6976 }
6977
6978 #[test]
6979 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6980 crate::run::pin_test_home();
6985 let mut state = run_state(RunStatus::Landing);
6986 state.id = "20260101-000000-exp1".to_owned();
6987 state.parked = true;
6988 state.config.graph.answer_timeout = 60;
6989 state.save().unwrap();
6990
6991 let store = ask::Questions::open();
6992 let mut q = approval_question(&state.id);
6993 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6994 store.put(&mut q).unwrap();
6995
6996 let mut t = task();
6997 t.runs.push(state.id.clone());
6998 assert_eq!(
6999 land_resume_state(&t),
7000 LandResume::Ready,
7001 "an expired question must not be waited on forever"
7002 );
7003
7004 let after = store.get(&q.id).unwrap();
7005 assert!(
7006 !after.status.open(),
7007 "the question is abandoned, not silently ignored"
7008 );
7009 assert!(
7010 after.resolution().is_none(),
7011 "an abandoned question is not read as a decision"
7012 );
7013 }
7014
7015 #[test]
7016 fn reclaim_settles_a_running_task_against_its_last_run() {
7017 let mut t = task();
7018 t.start("20260904-000000-4043".to_owned());
7019 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
7020 assert_eq!(
7021 t.status,
7022 TaskStatus::Done,
7023 "a run that actually finished must not stay `running` forever"
7024 );
7025 }
7026
7027 #[test]
7028 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
7029 let mut t = task();
7030 t.start("20260904-000000-4043".to_owned());
7031 t.last_error = Some("earlier trouble".to_owned());
7032 let mut state = run_state(RunStatus::Judging);
7033 state.parked = true;
7034 reclaim(&mut t, Some(state), 1, "en");
7035 assert_eq!(t.status, TaskStatus::Parked);
7036 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
7037 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7038 assert!(t.park_reason.is_some());
7039 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
7040 assert!(!t.fresh_start);
7041 assert!(t.status.runnable());
7042 }
7043
7044 #[test]
7045 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
7046 let mut t = task();
7047 t.start("20260904-000000-4043".to_owned());
7048 t.last_error = Some("earlier trouble".to_owned());
7049 settle(
7050 &mut t,
7051 Verdict {
7052 status: RunStatus::Judging,
7053 left_pr: false,
7054 quota_hit: false,
7055 parked: true,
7056 no_viable_candidates: false,
7057 },
7058 "parked after `judging`",
7059 1,
7060 );
7061 assert_eq!(t.status, TaskStatus::Parked);
7062 assert_eq!(t.attempts, 0);
7063 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7064 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
7065 assert_eq!(t.schema, crate::queue::SCHEMA);
7066 assert!(
7067 crate::notices::task_held(&t).is_none(),
7068 "a park is not news"
7069 );
7070 t.start("20260904-000000-4043".to_owned());
7071 assert_eq!(t.park_reason, None);
7072 }
7073
7074 #[test]
7075 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
7076 let mut t = task();
7080 t.start("20260904-000000-4043".to_owned());
7081 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
7082 assert_eq!(t.status, TaskStatus::Failed);
7083 assert!(t.status.runnable());
7084 }
7085
7086 #[test]
7087 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
7088 let mut t = task();
7089 t.start("20260904-000000-4043".to_owned());
7090 assert_eq!(t.attempts, 1);
7091 let mut run = run_state(RunStatus::Implementing);
7092 run.id = "20260904-000000-4043".to_owned();
7093 run.begin_pass();
7094 let cause = crate::run::ParkCause::Upgrade {
7095 from: "0.121.0".to_owned(),
7096 to: Some("0.121.1".to_owned()),
7097 };
7098 run.end_pass_parked(cause.clone());
7099 run.parked = true;
7100 let verdict = Verdict {
7101 status: run.status,
7102 left_pr: false,
7103 quota_hit: false,
7104 parked: true,
7105 no_viable_candidates: false,
7106 };
7107 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
7108 assert_eq!(t.attempts, 0);
7109 assert_eq!(t.passes.len(), 1);
7110 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7111 assert_eq!(t.passes[0].parked, Some(cause));
7112 assert_eq!(t.passes[0].pass_index, 0);
7113
7114 t.start("20260904-000000-4043".to_owned());
7117 run.begin_pass();
7118 run.status = RunStatus::Failed;
7119 let verdict = Verdict {
7120 status: RunStatus::Failed,
7121 left_pr: false,
7122 quota_hit: false,
7123 parked: false,
7124 no_viable_candidates: false,
7125 };
7126 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
7127 assert_eq!(t.passes.len(), 2);
7128 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7129 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
7130 assert_eq!(t.passes[1].pass_index, 1);
7131 assert_eq!(t.attempts, 1);
7132 }
7133
7134 #[test]
7135 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
7136 let mut t = task();
7137 t.start("20260904-000000-4043".to_owned());
7138 reclaim(&mut t, None, 2, "en");
7139 assert_eq!(t.status, TaskStatus::Held);
7140 assert!(
7141 t.last_error
7142 .as_deref()
7143 .is_some_and(|e| e.contains("running")),
7144 "the operator needs to know why this task was held"
7145 );
7146 }
7147
7148 #[test]
7149 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
7150 let dir = tempfile::tempdir().unwrap();
7151 let queue = Queue::at(dir.path().to_path_buf());
7152
7153 let mut orphaned = task();
7155 orphaned.id = "20260904-000000-orph".to_owned();
7156 orphaned.status = TaskStatus::Running;
7157 orphaned.attempts = 1;
7158 queue.put(&mut orphaned).unwrap();
7159
7160 let mut alive = task();
7161 alive.id = "20260904-000000-live".to_owned();
7162 alive.status = TaskStatus::Running;
7163 alive.attempts = 1;
7164 queue.put(&mut alive).unwrap();
7165 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
7166
7167 let mut queued = task();
7168 queued.id = "20260904-000000-wait".to_owned();
7169 queue.put(&mut queued).unwrap();
7170
7171 let reclaimed = reclaim_orphaned_running(&queue, 2);
7172 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
7173
7174 assert_eq!(
7175 queue.get(&orphaned.id).unwrap().status,
7176 TaskStatus::Held,
7177 "nothing was driving it and there was no run to recover"
7178 );
7179 assert_eq!(
7180 queue.get(&alive.id).unwrap().status,
7181 TaskStatus::Running,
7182 "a live claim must protect the task it belongs to"
7183 );
7184 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
7185 }
7186
7187 fn read_run_under(home: &Path, id: &str) -> RunState {
7193 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
7194 serde_json::from_str(&body).unwrap()
7195 }
7196
7197 #[test]
7198 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
7199 let dir = tempfile::tempdir().unwrap();
7200 let home = dir.path().to_path_buf();
7201 let now = Timestamp::now();
7202 let overrun_seat = || crate::run::ActiveSeat {
7203 node: "implement".to_owned(),
7204 started_at: now - jiff::SignedDuration::new(21_000, 0),
7205 timeout_secs: 3_600,
7206 attempt: 0,
7207 task: None,
7208 command: None,
7209 index: None,
7210 total: None,
7211 };
7212
7213 let mut dead = run_state(RunStatus::Implementing);
7214 dead.id = "20260101-000000-dead".to_owned();
7215 dead.active.insert("impl-A".to_owned(), overrun_seat());
7216 dead.driver_pid = Some(4242);
7219 dead.save_under(&home).unwrap();
7220
7221 let mut alive = run_state(RunStatus::Implementing);
7224 alive.id = "20260101-000000-aliv".to_owned();
7225 alive.active.insert("impl-A".to_owned(), overrun_seat());
7226 alive.save_under(&home).unwrap();
7227 let mut status = Status::new();
7228 status.current = vec![Current {
7229 task: "20260101-000000-task".to_owned(),
7230 run: alive.id.clone(),
7231 }];
7232 write_status_to(&home.join("daemon.json"), &status).unwrap();
7233
7234 let questions = Questions::at(home.join("questions"));
7238 let mut q = ask::Question::new(
7239 dead.id.clone(),
7240 "implement".to_owned(),
7241 "impl-A".to_owned(),
7242 "Which storage backend?".to_owned(),
7243 String::new(),
7244 vec!["SQLite".to_owned(), "Redis".to_owned()],
7245 );
7246 questions.put(&mut q).unwrap();
7247
7248 let abandoned = reclaim_abandoned_runs_with(
7249 &home,
7250 now,
7251 |pid| if pid == 4242 { Some(false) } else { None },
7252 |_| panic!("a query answering Dead outright needs no identity corroboration"),
7253 );
7254 assert_eq!(abandoned, vec![dead.id.clone()]);
7255
7256 let reloaded = read_run_under(&home, &dead.id);
7257 assert_eq!(reloaded.status, RunStatus::Failed);
7258 assert!(reloaded.active.is_empty());
7259 assert!(
7260 !questions.get(&q.id).unwrap().status.open(),
7261 "the failed run's own open question must be settled in the same pass"
7262 );
7263
7264 let still_alive = read_run_under(&home, &alive.id);
7265 assert_eq!(
7266 still_alive.status,
7267 RunStatus::Implementing,
7268 "a live daemon's claim protects it"
7269 );
7270 assert!(!still_alive.active.is_empty());
7271 }
7272
7273 #[test]
7283 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
7284 let dir = tempfile::tempdir().unwrap();
7285 let home = dir.path().to_path_buf();
7286 let now = Timestamp::now();
7287
7288 let mut manual = run_state(RunStatus::Reviewing);
7289 manual.id = "20260101-000000-manl".to_owned();
7290 manual.active.insert(
7291 "review-1".to_owned(),
7292 crate::run::ActiveSeat {
7293 node: "review".to_owned(),
7294 started_at: now - jiff::SignedDuration::new(21_000, 0),
7295 timeout_secs: 3_600,
7296 attempt: 0,
7297 task: None,
7298 command: None,
7299 index: None,
7300 total: None,
7301 },
7302 );
7303 manual.driver_pid = Some(4242);
7307 manual.driver_started_at = Some("1790000000".to_owned());
7308 manual.save_under(&home).unwrap();
7309
7310 let abandoned = reclaim_abandoned_runs_with(
7311 &home,
7312 now,
7313 |pid| if pid == 4242 { Some(true) } else { None },
7314 |pid| {
7315 if pid == 4242 {
7316 Some("1790000000".to_owned())
7317 } else {
7318 None
7319 }
7320 },
7321 );
7322 assert!(
7323 abandoned.is_empty(),
7324 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
7325 );
7326
7327 let reloaded = read_run_under(&home, &manual.id);
7328 assert_eq!(reloaded.status, RunStatus::Reviewing);
7329 assert!(!reloaded.active.is_empty());
7330 }
7331
7332 #[test]
7333 fn an_already_claimed_task_is_skipped_rather_than_failed() {
7334 let dir = tempfile::tempdir().unwrap();
7335 let queue = Queue::at(dir.path().to_path_buf());
7336 let mut only = task();
7337 queue.put(&mut only).unwrap();
7338
7339 let _elsewhere = queue.claim(&only.id).unwrap();
7340 let candidates = runnable(&queue);
7341 assert_eq!(candidates.len(), 1, "the task is still runnable");
7342 assert!(
7343 queue.claim(&candidates[0].id).is_err(),
7344 "the loop cannot take a claim somebody else holds"
7345 );
7346
7347 let after = queue.get(&only.id).unwrap();
7348 assert_eq!(after.status, TaskStatus::Queued);
7349 assert_eq!(
7350 after.attempts, 0,
7351 "losing the race is not an attempt at the task"
7352 );
7353 assert_eq!(after.last_error, None);
7354 }
7355
7356 #[test]
7357 fn the_status_file_round_trips_and_its_heartbeat_advances() {
7358 let dir = tempfile::tempdir().unwrap();
7359 let path = dir.path().join("daemon.json");
7360
7361 let mut status = Status::new();
7362 status.idle = false;
7363 status.completed = 7;
7364 status.current = vec![Current {
7365 task: "20260902-000000-t111".to_owned(),
7366 run: "20260902-000001-r111".to_owned(),
7367 }];
7368 write_status_to(&path, &status).unwrap();
7369 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7370 assert_eq!(first.schema, SCHEMA);
7371 assert_eq!(first.pid, std::process::id());
7372 assert!(!first.idle);
7373 assert_eq!(first.completed, 7);
7374 assert_eq!(first.current, status.current);
7375 assert!(
7376 !path.with_extension("json.tmp").exists(),
7377 "the temp file is renamed, not left behind"
7378 );
7379
7380 std::thread::sleep(Duration::from_millis(5));
7381 status.updated_at = Timestamp::now();
7382 status.polls = 3;
7383 write_status_to(&path, &status).unwrap();
7384 let second: Status =
7385 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7386 assert!(
7387 second.updated_at > first.updated_at,
7388 "a reader can only detect staleness if the heartbeat moves"
7389 );
7390 assert_eq!(
7391 second.started_at, first.started_at,
7392 "the start time is not a heartbeat"
7393 );
7394 assert_eq!(second.polls, 3);
7395 }
7396
7397 #[test]
7398 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
7399 let dir = tempfile::tempdir().unwrap();
7400
7401 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
7402
7403 let mut status = Status::new();
7404 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
7405 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7406 let stale = read_status(dir.path()).unwrap();
7407 assert!(
7408 !stale.running(Timestamp::now()),
7409 "a minute without a heartbeat is a dead daemon, not a busy one"
7410 );
7411 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
7412
7413 status.updated_at = Timestamp::now();
7414 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7415 let fresh = read_status(dir.path()).unwrap();
7416 assert!(fresh.running(Timestamp::now()));
7417 }
7418
7419 #[test]
7420 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
7421 let dir = tempfile::tempdir().unwrap();
7422 let now = Timestamp::now();
7423 let mine = "20260903-080619-01c2";
7424
7425 assert!(
7426 !is_working_on(dir.path(), mine, now),
7427 "no status file means nobody is working on anything"
7428 );
7429
7430 let mut status = Status::new();
7431 status.current = vec![Current {
7432 task: "20260903-080340-0167".to_owned(),
7433 run: mine.to_owned(),
7434 }];
7435 status.updated_at = now;
7436 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7437 assert!(is_working_on(dir.path(), mine, now));
7438 assert!(
7439 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
7440 "a daemon busy with one run is not working on another"
7441 );
7442
7443 status.updated_at = now - jiff::SignedDuration::from_secs(600);
7446 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7447 assert!(
7448 !is_working_on(dir.path(), mine, now),
7449 "a stale heartbeat is a dead daemon, so its run is a leftover"
7450 );
7451 }
7452
7453 #[test]
7454 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
7455 let dir = tempfile::tempdir().unwrap();
7456 let now = Timestamp::now();
7457
7458 assert!(
7459 !is_working_on_short(dir.path(), "01c2", now),
7460 "no status file means nobody is working on anything"
7461 );
7462
7463 let mut status = Status::new();
7464 status.current = vec![Current {
7465 task: "20260903-080340-0167".to_owned(),
7466 run: "20260903-080619-01c2".to_owned(),
7467 }];
7468 status.updated_at = now;
7469 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7470 assert!(
7471 is_working_on_short(dir.path(), "01c2", now),
7472 "the run's short id is the last block of its full id"
7473 );
7474 assert!(
7475 !is_working_on_short(dir.path(), "3cbf", now),
7476 "a daemon busy with one worktree bay is not working on another"
7477 );
7478 }
7479
7480 #[test]
7481 fn a_newer_status_file_still_yields_a_reading() {
7482 let dir = tempfile::tempdir().unwrap();
7483 std::fs::write(
7486 dir.path().join("daemon.json"),
7487 serde_json::json!({
7488 "schema": 2,
7489 "updated_at": Timestamp::now().to_string(),
7490 "idle": true,
7491 "surprise": { "nested": [1, 2, 3] },
7492 })
7493 .to_string(),
7494 )
7495 .unwrap();
7496
7497 let reading = read_status(dir.path()).expect("a forward-compatible read");
7498 assert!(reading.running(Timestamp::now()));
7499 assert!(reading.idle);
7500 assert!(reading.current.is_empty());
7501 }
7502
7503 #[test]
7504 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
7505 let dir = tempfile::tempdir().unwrap();
7511 std::fs::write(
7512 dir.path().join("daemon.json"),
7513 serde_json::json!({
7514 "schema": 1,
7515 "pid": 4242,
7516 "updated_at": Timestamp::now().to_string(),
7517 "idle": false,
7518 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
7519 "completed": 3,
7520 "polls": 9,
7521 })
7522 .to_string(),
7523 )
7524 .unwrap();
7525
7526 let reading = read_status(dir.path()).expect("an older shape must still parse");
7527 assert!(reading.running(Timestamp::now()));
7528 assert_eq!(
7529 reading.current,
7530 vec![Current {
7531 task: "20260902-140501-aaaa".to_owned(),
7532 run: "20260902-140502-bbbb".to_owned(),
7533 }]
7534 );
7535 }
7536
7537 #[test]
7538 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
7539 let dir = tempfile::tempdir().unwrap();
7540 std::fs::write(
7541 dir.path().join("daemon.json"),
7542 serde_json::json!({
7543 "schema": 1,
7544 "updated_at": Timestamp::now().to_string(),
7545 "idle": true,
7546 "current": null,
7547 })
7548 .to_string(),
7549 )
7550 .unwrap();
7551 let with_null = read_status(dir.path()).expect("null must still parse");
7552 assert!(with_null.current.is_empty());
7553
7554 std::fs::write(
7555 dir.path().join("daemon.json"),
7556 serde_json::json!({
7557 "schema": 1,
7558 "updated_at": Timestamp::now().to_string(),
7559 "idle": true,
7560 })
7561 .to_string(),
7562 )
7563 .unwrap();
7564 let absent = read_status(dir.path()).expect("a missing field must still parse");
7565 assert!(absent.current.is_empty());
7566 }
7567
7568 #[test]
7569 fn a_task_without_a_repository_runs_in_the_daemons_default() {
7570 let fallback = Path::new("/default");
7571 let mut blank = task();
7572 blank.repo = PathBuf::new();
7573 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
7574 let mut dot = task();
7575 dot.repo = PathBuf::from(".");
7576 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
7577 assert_eq!(
7578 repo_for(&task(), fallback),
7579 PathBuf::from("/repo"),
7580 "a task that names a repository keeps it"
7581 );
7582 }
7583
7584 #[test]
7585 fn task_implementers_edit_inherits_daemon_config_and_merge() {
7586 let dir = tempfile::tempdir().unwrap();
7587 let path = dir.path().join("explicit.toml");
7588 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
7589 let opts = Opts {
7590 config: Some(path),
7591 merge: Some("none".into()),
7592 ..Default::default()
7593 };
7594 let mut t = task();
7595 t.set_implementers(
7596 2,
7597 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7598 .unwrap(),
7599 )
7600 .unwrap();
7601 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7602 assert_eq!(cfg.graph.implementers, 2);
7603 assert_eq!(cfg.graph.judges, 1);
7604 assert_eq!(cfg.merge.mode, MergeMode::None);
7605 t.set_implementers(1, &cfg).unwrap();
7606 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7607 apply_task_implementers(&mut cfg, &t);
7608 assert_eq!(cfg.graph.implementers, 1);
7609 assert_eq!(cfg.graph.judges, 1);
7610 assert_eq!(cfg.merge.mode, MergeMode::None);
7611 }
7612
7613 #[test]
7614 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
7615 let dir = tempfile::tempdir().unwrap();
7616 let repo = dir.path().join("repo");
7617 std::fs::create_dir(&repo).unwrap();
7618 std::fs::write(
7619 repo.join("magi.toml"),
7620 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
7621 )
7622 .unwrap();
7623 let daemon_config = dir.path().join("daemon.toml");
7624 std::fs::write(
7625 &daemon_config,
7626 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
7627 )
7628 .unwrap();
7629 let opts = Opts {
7630 config: Some(daemon_config),
7631 merge: Some("pr".into()),
7632 ..Default::default()
7633 };
7634 let q = Queue::at(dir.path().join("queue"));
7635 let validation: Config =
7636 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7637 .unwrap();
7638 for record in ["{}", r#"{"candidates":2}"#] {
7640 let overrides = serde_json::from_str(record).unwrap();
7641 let filing = crate::direct::Filing {
7642 instruction: "work".into(),
7643 title: "direct".into(),
7644 repo: repo.clone(),
7645 source: crate::queue::Source::Human,
7646 solo: false,
7647 overrides,
7648 review_of: None,
7649 };
7650 let filed =
7651 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
7652 let crate::direct::Filed::Standalone {
7653 mut task,
7654 claim: _claim,
7655 } = filed
7656 else {
7657 panic!("local filing")
7658 };
7659 let before = prepare_for(&repo, &opts, &task).unwrap();
7660 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
7661 assert_eq!(
7662 before.merge.mode,
7663 MergeMode::None,
7664 "daemon --merge must not leak"
7665 );
7666 for n in [2, 1, 2] {
7667 task.set_implementers(n, &validation).unwrap();
7668 q.put(&mut task).unwrap();
7669 task = q.get(&task.id).unwrap();
7670 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
7671 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
7672 apply_task_implementers(&mut cfg, &task);
7673 assert_eq!(cfg.graph.implementers, usize::from(n));
7674 assert_eq!(cfg.graph.judges, 2);
7675 assert_eq!(cfg.merge.mode, MergeMode::None);
7676 }
7677 }
7678 }
7679
7680 #[test]
7681 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
7682 let cfg: Config =
7683 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7684 .unwrap();
7685 let mut t = task();
7686 t.review_of = Some("review-target".into());
7687 t.hold_manual(Some("retry".into()));
7688 let mut previous = RunState::new(
7689 PathBuf::from("/repo"),
7690 "main".into(),
7691 "abc1234".into(),
7692 "review".into(),
7693 cfg.clone(),
7694 );
7695 previous.config.graph.implementers = 2;
7696 for count in [1, 3] {
7697 t.set_implementers(count, &cfg).unwrap();
7698 t.release();
7699 assert_eq!(t.review_of.as_deref(), Some("review-target"));
7700 for proposed in [
7701 Starter::Resume(previous.id.clone()),
7702 Starter::Review("recovery-target".into()),
7703 ] {
7704 assert_eq!(
7705 starter_with_implementers(&t, Some(&previous), proposed),
7706 Starter::Review("review-target".into())
7707 );
7708 }
7709 let mut configured = cfg.clone();
7710 apply_task_implementers(&mut configured, &t);
7711 assert_eq!(configured.graph.implementers, usize::from(count));
7712 assert_eq!(previous.config.graph.implementers, 2);
7713 }
7714 }
7715
7716 #[test]
7717 fn task_implementers_dispatch_and_resume_agree() {
7718 let mut t = task();
7719 let cfg: crate::config::Config =
7720 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7721 .unwrap();
7722 let mut run = RunState::new(
7723 PathBuf::from("/repo"),
7724 "main".into(),
7725 "abc1234".into(),
7726 "work".into(),
7727 cfg.clone(),
7728 );
7729 run.config.graph.implementers = 2;
7730 for n in [2, 1, 3, 2] {
7731 t.set_implementers(n, &cfg).unwrap();
7732 let mut dispatched = cfg.clone();
7733 apply_task_implementers(&mut dispatched, &t);
7734 assert_eq!(dispatched.graph.implementers, usize::from(n));
7735 assert_eq!(implementers_match(&t, &run), n == 2);
7736 for proposed in [
7737 Starter::Resume(run.id.clone()),
7738 Starter::Review("old-branch".into()),
7739 ] {
7740 let expected = if n == 2 {
7741 proposed.clone()
7742 } else {
7743 Starter::Start
7744 };
7745 assert_eq!(
7746 starter_with_implementers(&t, Some(&run), proposed),
7747 expected
7748 );
7749 }
7750 assert_eq!(
7751 run.config.graph.implementers, 2,
7752 "history must not be rewritten"
7753 );
7754 }
7755 t.solo = false;
7756 t.overrides = None;
7757 assert!(implementers_match(&t, &run));
7758 }
7759
7760 #[test]
7761 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
7762 let mut solo_cfg = Config::default();
7768 solo_cfg.graph.implementers = 3;
7769 let mut solo_task = task();
7770 solo_task.solo = true;
7771 apply_task_implementers(&mut solo_cfg, &solo_task);
7772 assert_eq!(solo_cfg.graph.implementers, 1);
7773
7774 let mut plain_cfg = Config::default();
7775 plain_cfg.graph.implementers = 3;
7776 let plain_task = task();
7777 assert!(!plain_task.solo);
7778 apply_task_implementers(&mut plain_cfg, &plain_task);
7779 assert_eq!(
7780 plain_cfg.graph.implementers, 3,
7781 "a task that did not ask to run alone keeps the config's candidates"
7782 );
7783 }
7784
7785 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
7786 QuotaLoss {
7787 seat: seat.into(),
7788 node: "judge".into(),
7789 at: at.parse().unwrap(),
7790 reset: reset.map(str::to_string),
7791 }
7792 }
7793
7794 #[test]
7795 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
7796 let old: Vec<QuotaLoss> = (1..=4)
7797 .map(|i| {
7798 loss(
7799 &format!("judge-{i}"),
7800 "2026-09-23T05:23:00Z",
7801 Some("2:40pm (Asia/Tokyo)"),
7802 )
7803 })
7804 .collect();
7805 let fresh = losses_this_attempt(&old, &old);
7806 assert!(fresh.is_empty());
7807 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
7808 }
7810
7811 #[test]
7812 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
7813 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
7814 let now = Timestamp::now();
7815 let mut after = old.clone();
7816 after.push(loss("judge-2", &now.to_string(), None));
7817 let fresh = losses_this_attempt(&old, &after);
7818 assert_eq!(fresh, vec![after[1].clone()]);
7819 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
7820 assert_eq!(
7821 until,
7822 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
7823 );
7824 }
7825
7826 #[test]
7827 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
7828 let before = vec![
7831 loss("judge-1", "2026-09-23T05:23:00Z", None),
7832 loss("judge-2", "2026-09-23T05:24:00Z", None),
7833 ];
7834 let after = vec![
7835 loss("judge-2", "2026-09-23T05:24:00Z", None),
7836 loss("judge-1", "2026-09-24T01:00:00Z", None),
7837 ];
7838 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
7839 }
7840
7841 #[test]
7842 fn merge_overrides_are_parsed_or_refused() {
7843 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
7844 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
7845 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
7846 assert!(merge_mode("squash").is_err());
7847 }
7848
7849 #[test]
7850 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
7851 let now = Timestamp::now();
7852 let fallback = Duration::from_secs(300);
7853 let cap = Duration::from_secs(1800);
7854
7855 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
7857
7858 let soon = now + jiff::SignedDuration::from_secs(600);
7860 assert_eq!(
7861 quota_wait(Some(soon), now, fallback, cap),
7862 Duration::from_secs(600)
7863 );
7864
7865 let past = now - jiff::SignedDuration::from_secs(60);
7868 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
7869
7870 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
7873 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
7874 }
7875
7876 #[test]
7877 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
7878 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7879
7880 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
7881 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
7882
7883 let already_past =
7887 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
7888 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
7889
7890 assert!(
7891 parse_reset_hint("session limit reached", now, now).is_none(),
7892 "free text with no recognised shape is not guessed at"
7893 );
7894 assert!(
7895 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
7896 "an unresolvable zone name is not guessed at either"
7897 );
7898 }
7899
7900 #[test]
7901 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
7902 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7903
7904 let at = parse_reset_hint(
7905 "You've hit your usage limit. Visit \
7906 https://chatgpt.com/codex/settings/usage to purchase more \
7907 credits or try again at Sep 19th, 2026 5:10 PM.",
7908 now,
7909 now,
7910 )
7911 .expect("the codex reset wording is a recognised shape");
7912 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
7913
7914 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
7919 .expect("an explicit year needs no rollover");
7920 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
7921
7922 assert!(
7923 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
7924 "a two-digit year is not the documented shape and is not guessed at"
7925 );
7926 assert!(
7927 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
7928 "a four-letter month name is not the documented three-letter abbreviation"
7929 );
7930 assert!(
7931 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
7932 "an explicit zone on the dated shape is a format nobody has \
7933 documented, and is refused rather than guessed at as UTC"
7934 );
7935 }
7936
7937 #[test]
7938 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
7939 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
7940 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
7941
7942 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
7943 assert_eq!(at.as_second() - recorded.as_second(), 3769);
7944
7945 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
7946 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
7947
7948 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
7949 assert!(
7950 parse_reset_hint(bad, now, recorded).is_none(),
7951 "{bad:?} must not be guessed at"
7952 );
7953 }
7954 }
7955
7956 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
7960 let config = dir.join("magi.toml");
7961 std::fs::write(
7962 &config,
7963 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
7964 )
7965 .unwrap();
7966 let opts = Opts {
7967 poll: Duration::from_secs(30),
7968 config: Some(config),
7969 repo: dir.join("repo"),
7973 ..Opts::default()
7974 };
7975 let home = dir.join("home");
7984 let worktrees = dir.join("wt");
7985 (
7986 opts,
7987 Queue::at(dir.join("queue")),
7988 home.join("daemon.json"),
7989 home,
7990 worktrees,
7991 )
7992 }
7993
7994 #[test]
7995 fn a_stop_is_idempotent_and_once_set_stays_set() {
7996 let stop = Stop::new();
7997 assert!(!stop.stopped());
7998
7999 stop.stop();
8000 assert!(stop.stopped());
8001 stop.stop();
8002 assert!(stop.stopped(), "a second stop is not a toggle");
8003
8004 let shared = stop.clone();
8005 assert!(
8006 shared.stopped(),
8007 "a clone is the same stop; that is how the loop and its caller share one"
8008 );
8009 }
8010
8011 #[test]
8012 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
8013 let stop = Stop::new();
8014 stop.enter();
8015 assert!(
8016 !stop.finishing(),
8017 "a busy loop nobody has asked to stop is just running"
8018 );
8019
8020 stop.stop();
8021 assert!(
8022 stop.finishing(),
8023 "a stop asked for mid-run has not landed until the run is settled"
8024 );
8025
8026 stop.exit();
8027 assert!(
8028 !stop.finishing(),
8029 "once the run is settled the stop has landed and there is nothing to finish"
8030 );
8031 }
8032
8033 #[test]
8034 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
8035 let stop = Stop::new();
8036 stop.enter();
8037 stop.enter();
8038 stop.stop();
8039 assert!(stop.finishing(), "two runs still in flight");
8040
8041 stop.exit();
8042 assert!(
8043 stop.finishing(),
8044 "one run finished, but a sibling is still working"
8045 );
8046
8047 stop.exit();
8048 assert!(
8049 !stop.finishing(),
8050 "the last run out is what actually lands the stop"
8051 );
8052 }
8053
8054 #[tokio::test]
8055 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
8056 let dir = tempfile::tempdir().unwrap();
8057 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8058 let stop = Stop::new();
8059 stop.stop();
8060
8061 let began = std::time::Instant::now();
8062 tokio::time::timeout(
8063 Duration::from_secs(2),
8064 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8065 )
8066 .await
8067 .expect("a stopped loop must return, not sit out its poll interval")
8068 .expect("the loop's own setup and teardown must not fail");
8069 assert!(
8070 began.elapsed() < opts.poll,
8071 "returned only after {:?}, which is a poll interval, not a stop",
8072 began.elapsed()
8073 );
8074 }
8075
8076 #[tokio::test]
8077 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
8078 let dir = tempfile::tempdir().unwrap();
8079 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8080 let stop = Stop::new();
8081
8082 let asker = {
8085 let stop = stop.clone();
8086 tokio::spawn(async move {
8087 tokio::time::sleep(Duration::from_millis(20)).await;
8088 stop.stop();
8089 })
8090 };
8091
8092 let began = std::time::Instant::now();
8093 tokio::time::timeout(
8094 Duration::from_secs(2),
8095 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8096 )
8097 .await
8098 .expect("a stop asked for while idle must wake the wait")
8099 .expect("the loop's own setup and teardown must not fail");
8100 asker.await.unwrap();
8101 assert!(
8102 began.elapsed() < opts.poll,
8103 "returned only after {:?}, so the stop waited on the sleep",
8104 began.elapsed()
8105 );
8106 }
8107
8108 #[tokio::test]
8109 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
8110 let dir = tempfile::tempdir().unwrap();
8111 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8112 let stop = Stop::new();
8113 stop.stop();
8114
8115 tokio::time::timeout(
8116 Duration::from_secs(2),
8117 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8118 )
8119 .await
8120 .expect("a stopped loop must return")
8121 .expect("the loop's own setup and teardown must not fail");
8122
8123 assert!(
8124 home.is_dir(),
8125 "the loop did publish a status file, so its removal is the teardown and not an absence"
8126 );
8127 assert!(
8128 !status_file.exists(),
8129 "a stopped loop clears its status file"
8130 );
8131 assert!(
8132 read_status(&home).is_none(),
8133 "a reader must see no daemon at all, not a heartbeat that merely stopped"
8134 );
8135 }
8136
8137 #[tokio::test]
8138 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
8139 let dir = tempfile::tempdir().unwrap();
8140 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8141 opts.once = true;
8142
8143 let mut settled = RunState::new(
8144 dir.path().join("repo"),
8145 "main".to_owned(),
8146 "abc1234".to_owned(),
8147 "fixture".to_owned(),
8148 Config::default(),
8149 );
8150 settled.status = RunStatus::Ready;
8151 let run_dir = home.join("runs").join(&settled.id);
8152 std::fs::create_dir_all(&run_dir).unwrap();
8153 std::fs::write(
8154 run_dir.join("run.json"),
8155 serde_json::to_string_pretty(&settled).unwrap(),
8156 )
8157 .unwrap();
8158 let questions = Questions::at(home.join("questions"));
8159 let mut question = ask::Question::new(
8160 settled.id.clone(),
8161 "review".to_owned(),
8162 "reviewer-1".to_owned(),
8163 "Continue?".to_owned(),
8164 String::new(),
8165 Vec::new(),
8166 );
8167 questions.put(&mut question).unwrap();
8168
8169 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
8170 .await
8171 .unwrap();
8172
8173 assert_eq!(
8174 questions.get(&question.id).unwrap().status,
8175 ask::QuestionStatus::Abandoned,
8176 "an empty --once drain still performs startup question cleanup"
8177 );
8178 }
8179
8180 #[test]
8181 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
8182 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8183
8184 assert!(
8185 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
8186 "never checked before: due at once"
8187 );
8188
8189 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
8190 assert!(
8191 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
8192 "well inside the interval: not due yet"
8193 );
8194
8195 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
8196 assert!(
8197 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
8198 "exactly at the edge: not yet due, same convention as `clean::due`"
8199 );
8200
8201 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8202 assert!(
8203 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
8204 "past the interval: due again"
8205 );
8206 }
8207
8208 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
8213 let config = dir.join("magi.toml");
8214 std::fs::write(
8220 &config,
8221 format!(
8222 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
8223 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
8224 cache_dir.display()
8225 ),
8226 )
8227 .unwrap();
8228 Opts {
8229 config: Some(config),
8230 repo: dir.join("repo"),
8231 ..Opts::default()
8232 }
8233 }
8234
8235 #[tokio::test]
8236 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8237 let dir = tempfile::tempdir().unwrap();
8238 let home = dir.path().join("home");
8239 let cache_dir = dir.path().join("cache");
8240 std::fs::create_dir_all(&cache_dir).unwrap();
8241 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8242 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8243
8244 let running = Stop::new();
8247 let mut last_checked = None;
8248 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8249 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
8250 .await;
8251 assert_eq!(
8252 crate::disk::dir_size(&cache_dir),
8253 0,
8254 "over the cap on the first check ever: pruned at once, no idle queue required"
8255 );
8256 assert_eq!(last_checked, Some(t0));
8257
8258 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
8260 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
8261 maybe_prune_cache_between_runs(
8262 &opts.repo,
8263 &opts,
8264 &home,
8265 &running,
8266 &mut last_checked,
8267 too_soon,
8268 )
8269 .await;
8270 assert_eq!(
8271 crate::disk::dir_size(&cache_dir),
8272 10,
8273 "too soon since the last check: left alone rather than rescanned every call"
8274 );
8275 assert_eq!(
8276 last_checked,
8277 Some(t0),
8278 "an idle check does not reset the clock"
8279 );
8280
8281 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8283 maybe_prune_cache_between_runs(
8284 &opts.repo,
8285 &opts,
8286 &home,
8287 &running,
8288 &mut last_checked,
8289 due_again,
8290 )
8291 .await;
8292 assert_eq!(
8293 crate::disk::dir_size(&cache_dir),
8294 0,
8295 "due again: pruned back under the cap"
8296 );
8297 }
8298
8299 #[tokio::test]
8307 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
8308 let dir = tempfile::tempdir().unwrap();
8309 let home = dir.path().join("home");
8310 let cache_dir = dir.path().join("cache");
8311 std::fs::create_dir_all(&cache_dir).unwrap();
8312 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8313 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8314
8315 let stop = Stop::new();
8316 stop.stop();
8317 assert!(
8318 !stop.finishing(),
8319 "no run is in flight at a between-runs boundary, so nothing else \
8320 would tell the operator this stop had not taken effect yet"
8321 );
8322
8323 let mut last_checked = None;
8324 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8325 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
8326 .await;
8327 assert_eq!(
8328 crate::disk::dir_size(&cache_dir),
8329 10,
8330 "over its cap, and due for the first check ever, but a stop outranks \
8331 it: the cap is a standing policy the next start measures again"
8332 );
8333 assert_eq!(
8334 last_checked, None,
8335 "a check that never happened must not claim the interval"
8336 );
8337 }
8338
8339 #[tokio::test]
8350 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
8351 let dir = tempfile::tempdir().unwrap();
8352 let cache_dir = dir.path().join("cache");
8353 std::fs::create_dir_all(&cache_dir).unwrap();
8354 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
8355
8356 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
8357 opts.poll = Duration::from_millis(20);
8358 opts.max_attempts = 1_000;
8359
8360 let queue = Queue::at(dir.path().join("queue"));
8361 for i in 0..128 {
8362 let mut task = Task::new(
8363 format!("queued work {i}"),
8364 format!("queued work {i}"),
8365 opts.repo.clone(),
8366 Source::Human,
8367 );
8368 queue.put(&mut task).unwrap();
8369 }
8370
8371 let home = dir.path().join("home");
8372 let worktrees = dir.path().join("wt");
8373 let status_file = home.join("daemon.json");
8374 let stop = Stop::new();
8375 let stopper = {
8376 let stop = stop.clone();
8377 let queue = Queue::at(dir.path().join("queue"));
8378 tokio::spawn(async move {
8379 for _ in 0..2_000 {
8383 if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
8384 break;
8385 }
8386 tokio::time::sleep(Duration::from_millis(5)).await;
8387 }
8388 stop.stop();
8389 })
8390 };
8391
8392 tokio::time::timeout(
8393 Duration::from_secs(20),
8394 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8395 )
8396 .await
8397 .expect("the loop must not hang on a queue that keeps producing failing work")
8398 .expect("the loop's own setup and teardown must not fail");
8399 stopper.await.unwrap();
8400
8401 let after = queue.list();
8402 let completed = after.iter().filter(|t| t.attempts == 1).count();
8403 assert!(
8404 completed >= 2,
8405 "the harness must have processed multiple tasks to exercise a busy queue \
8406 (got {completed} completed task(s))"
8407 );
8408 assert!(
8409 after.iter().any(|t| t.status.runnable()),
8410 "unprocessed tasks must remain: the external stop, rather than an \
8411 exhausted backlog, must end the test"
8412 );
8413 assert!(
8414 after
8415 .iter()
8416 .filter(|t| t.attempts > 0)
8417 .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
8418 "a busy backlog must not retry a task's unchanged startup failure"
8419 );
8420
8421 assert_eq!(
8422 crate::disk::dir_size(&cache_dir),
8423 0,
8424 "an oversized cache must not be left to grow unboundedly just because the \
8425 queue kept the loop busy the whole time"
8426 );
8427 }
8428
8429 #[test]
8430 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
8431 let dir = tempfile::tempdir().unwrap();
8432 let queue = Queue::at(dir.path().join("queue"));
8433 let questions = Questions::at(dir.path().join("questions"));
8434 let mut task = task();
8435 queue.put(&mut task).unwrap();
8436
8437 let mut task_question = ask::Question::new(
8438 task.id.clone(),
8439 crate::conduct::NODE.to_owned(),
8440 "conduct".to_owned(),
8441 "Which backend?".to_owned(),
8442 String::new(),
8443 Vec::new(),
8444 );
8445 questions.put(&mut task_question).unwrap();
8446 task.block(vec![task_question.id.clone()], None);
8447 queue.put(&mut task).unwrap();
8448
8449 let mut run_question = ask::Question::new(
8450 "20260101-000000-run1".to_owned(),
8451 "review".to_owned(),
8452 "reviewer-1".to_owned(),
8453 "Run question".to_owned(),
8454 String::new(),
8455 Vec::new(),
8456 );
8457 questions.put(&mut run_question).unwrap();
8458
8459 let mut coincidental = ask::Question::new(
8464 task.id.clone(),
8465 "review".to_owned(),
8466 "reviewer-1".to_owned(),
8467 "Unrelated review question".to_owned(),
8468 String::new(),
8469 Vec::new(),
8470 );
8471 questions.put(&mut coincidental).unwrap();
8472
8473 reconcile_task_questions(&queue, &questions);
8474 assert!(questions.get(&task_question.id).unwrap().status.open());
8475 assert!(questions.get(&run_question.id).unwrap().status.open());
8476 assert!(questions.get(&coincidental.id).unwrap().status.open());
8477
8478 task.release();
8479 queue.put(&mut task).unwrap();
8480 reconcile_task_questions(&queue, &questions);
8481 assert_eq!(
8482 questions.get(&task_question.id).unwrap().status,
8483 ask::QuestionStatus::Abandoned
8484 );
8485 assert!(
8486 questions.get(&run_question.id).unwrap().status.open(),
8487 "run questions remain the run janitor's responsibility"
8488 );
8489 assert!(
8490 questions.get(&coincidental.id).unwrap().status.open(),
8491 "a non-conductor question must not be abandoned just because its \
8492 run id coincides with a task id"
8493 );
8494 }
8495
8496 #[test]
8497 fn a_freshly_started_running_task_is_never_stalled() {
8498 let dir = tempfile::tempdir().unwrap();
8499 let mut t = task();
8500 t.start("run-1".to_owned());
8501 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
8504 }
8505
8506 #[test]
8507 fn a_long_running_task_with_no_live_daemon_is_stalled() {
8508 let dir = tempfile::tempdir().unwrap();
8509 let mut t = task();
8510 t.start("run-1".to_owned());
8511 t.updated_at = Timestamp::now()
8512 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8513 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
8514 assert_eq!(
8515 stalled_tasks(
8516 &Queue::at(dir.path().join("q")),
8517 dir.path(),
8518 Timestamp::now()
8519 )
8520 .len(),
8521 0,
8522 "the task was never written to this queue"
8523 );
8524 }
8525
8526 #[test]
8527 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
8528 let dir = tempfile::tempdir().unwrap();
8529 let mut t = task();
8530 t.id = "20260903-080340-0167".to_owned();
8531 t.start("20260903-080619-01c2".to_owned());
8532 t.updated_at = Timestamp::now()
8533 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8534
8535 let mut status = Status::new();
8536 status.current = vec![Current {
8537 task: t.id.clone(),
8538 run: "20260903-080619-01c2".to_owned(),
8539 }];
8540 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8541
8542 assert!(
8543 !is_stalled(&t, dir.path(), Timestamp::now()),
8544 "a live daemon's own heartbeat rules out stalled, however long the task has run"
8545 );
8546 }
8547
8548 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
8552 let path = queue.path_of(id);
8553 let body = std::fs::read_to_string(&path).unwrap();
8554 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
8555 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
8556 v["updated_at"] = serde_json::Value::String(old.to_string());
8557 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
8558 }
8559
8560 #[test]
8561 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
8562 let dir = tempfile::tempdir().unwrap();
8575 let queue = Queue::at(dir.path().join("queue"));
8576 let home = dir.path().join("home");
8577
8578 let mut t = task();
8579 t.id = "20260101-000001-lock".to_owned();
8580 t.start("run-1".to_owned());
8581 queue.put(&mut t).unwrap();
8582 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8583 std::fs::write(
8584 dir.path().join("queue").join(format!("{}.lock", t.id)),
8585 "not a pid",
8586 )
8587 .unwrap();
8588
8589 let now = Timestamp::now();
8590 assert!(
8591 reclaim_orphaned_running(&queue, 2).is_empty(),
8592 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
8593 and reclaim must leave the task alone"
8594 );
8595 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8596
8597 let stalled = stalled_tasks(&queue, &home, now);
8598 assert_eq!(
8599 stalled.len(),
8600 1,
8601 "reclaim's inability to claim it yet must not hide it from the conductor"
8602 );
8603 assert_eq!(stalled[0].id, t.id);
8604 }
8605
8606 #[test]
8607 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
8608 let dir = tempfile::tempdir().unwrap();
8609 crate::run::set_home(dir.path().join("run-home"));
8610 let queue = Queue::at(dir.path().join("queue"));
8611 let home = dir.path().join("home");
8612 let questions = Questions::at(dir.path().join("questions"));
8613
8614 let mut t = task();
8615 t.id = "20260101-000003-dead".to_owned();
8616 t.start("missing-run".to_owned());
8617 queue.put(&mut t).unwrap();
8618 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8619
8620 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8623 assert_eq!(
8624 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
8625 [&t.id]
8626 );
8627 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
8628 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8629
8630 crate::conduct::apply(
8633 &queue,
8634 &questions,
8635 &crate::conduct::Verdict {
8636 decisions: vec![crate::conduct::Decision {
8637 id: t.id.clone(),
8638 recovery: Some(crate::conduct::Recovery::Requeue),
8639 ..crate::conduct::Decision::default()
8640 }],
8641 },
8642 )
8643 .unwrap();
8644 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8645 }
8646
8647 #[test]
8648 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
8649 let dir = tempfile::tempdir().unwrap();
8650 let queue = Queue::at(dir.path().join("queue"));
8651 let home = dir.path().join("home");
8652
8653 let mut fresh = task();
8654 fresh.id = "20260101-000001-aaaa".to_owned();
8655 fresh.start("run-1".to_owned());
8656 queue.put(&mut fresh).unwrap();
8657
8658 let mut old = task();
8659 old.id = "20260101-000002-bbbb".to_owned();
8660 old.start("run-2".to_owned());
8661 queue.put(&mut old).unwrap();
8662 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
8663
8664 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8665 assert_eq!(stalled.len(), 1);
8666 assert_eq!(stalled[0].id, old.id);
8667 }
8668
8669 #[test]
8670 fn queued_and_finished_task_views_partition_by_status() {
8671 let dir = tempfile::tempdir().unwrap();
8672 let queue = Queue::at(dir.path().join("queue"));
8673
8674 let mut queued = task();
8675 queued.id = "20260101-000001-aaaa".to_owned();
8676 queue.put(&mut queued).unwrap();
8677
8678 let mut failed = task();
8679 failed.id = "20260101-000002-bbbb".to_owned();
8680 failed.start("run-1".to_owned());
8681 failed.fail("gate red", 5);
8682 queue.put(&mut failed).unwrap();
8683
8684 let mut held = task();
8685 held.id = "20260101-000003-cccc".to_owned();
8686 held.hold_machine(None);
8687 queue.put(&mut held).unwrap();
8688
8689 let mut running = task();
8690 running.id = "20260101-000004-dddd".to_owned();
8691 running.start("run-2".to_owned());
8692 queue.put(&mut running).unwrap();
8693
8694 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
8695 assert_eq!(queued_ids, [queued.id.clone()]);
8696
8697 let mut finished_ids: Vec<String> =
8698 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
8699 finished_ids.sort_unstable();
8700 let mut want = vec![failed.id.clone(), held.id.clone()];
8701 want.sort_unstable();
8702 assert_eq!(finished_ids, want);
8703 }
8704
8705 #[test]
8706 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
8707 for short in [false, true] {
8708 let dir = tempfile::tempdir().unwrap();
8709 let queue = Queue::at(dir.path().join("queue"));
8710 let questions = ask::Questions::at(dir.path().join("questions"));
8711 let mut running = task();
8712 running.id = "20261013-192213-feb2".into();
8713 running.start("existing-run".into());
8714 queue.put(&mut running).unwrap();
8715 let mut middle = task();
8716 middle.id = "20261013-193611-ca5b".into();
8717 middle.block(
8718 vec![if short {
8719 "feb2".into()
8720 } else {
8721 running.id.clone()
8722 }],
8723 None,
8724 );
8725 queue.put(&mut middle).unwrap();
8726 let mut waiting = task();
8727 waiting.id = "20261013-202849-ee37".into();
8728 waiting.block(
8729 vec![if short {
8730 "ca5b".into()
8731 } else {
8732 middle.id.clone()
8733 }],
8734 Some("wait for implementation".into()),
8735 );
8736 queue.put(&mut waiting).unwrap();
8737 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
8738 let inv = crate::blockers::Inventory::load(&queue, &questions);
8739 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
8740 assert!(inv.stuck().is_empty());
8741 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
8742 assert!(report.quarantined.is_empty());
8743 assert!(report.asked.is_empty());
8744 resolve_blockers(&queue, &questions);
8745 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8746 assert!(questions.list().is_empty());
8747 running.succeed();
8750 queue.put(&mut running).unwrap();
8751 resolve_blockers(&queue, &questions);
8752 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
8753 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8754 middle = queue.get(&middle.id).unwrap();
8755 middle.succeed();
8756 queue.put(&mut middle).unwrap();
8757 resolve_blockers(&queue, &questions);
8758 let after = queue.get(&waiting.id).unwrap();
8759 assert_eq!(after.status, TaskStatus::Queued);
8760 assert!(after.blocked_by.is_empty());
8761 assert_eq!(after.instruction, waiting.instruction);
8762 }
8763 }
8764
8765 #[test]
8766 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
8767 for future_schema in [false, true] {
8768 let name = "20261013-193611-ca5b";
8769 let mut future = task();
8770 future.id = name.into();
8771 future.schema = crate::queue::SCHEMA + 1;
8772 let contents = if future_schema {
8773 serde_json::to_string(&future).unwrap()
8774 } else {
8775 "corrupt".into()
8776 };
8777 let dir = tempfile::tempdir().unwrap();
8778 let queue = Queue::at(dir.path().join("queue"));
8779 let questions = ask::Questions::at(dir.path().join("questions"));
8780 let mut waiting = task();
8781 waiting.id = "20261013-202849-ee37".into();
8782 waiting.block(vec!["ca5b".into()], None);
8783 queue.put(&mut waiting).unwrap();
8784 std::fs::write(queue.path_of(name), contents).unwrap();
8785 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
8786 assert!(
8787 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
8788 );
8789 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
8790 assert!(report.asked.is_empty());
8791 resolve_blockers(&queue, &questions);
8792 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8793 assert!(questions.list().is_empty());
8794 }
8795 let dir = tempfile::tempdir().unwrap();
8796 let queue = Queue::at(dir.path().join("queue"));
8797 let questions = ask::Questions::at(dir.path().join("questions"));
8798 let mut waiting = task();
8799 waiting.id = "20261013-202849-ee37".into();
8800 waiting.block(vec!["ca5b".into()], None);
8801 queue.put(&mut waiting).unwrap();
8802 let mut done = task();
8803 done.id = "20261013-193611-ca5b".into();
8804 done.succeed();
8805 queue.put(&mut done).unwrap();
8806 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
8809 assert!(queue.get("ca5b").is_err());
8810 assert_eq!(
8811 crate::queue::dependency(&queue, &questions, "ca5b"),
8812 crate::queue::Dependency::Ambiguous
8813 );
8814 resolve_blockers(&queue, &questions);
8815 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
8816 assert!(report.asked.is_empty());
8817 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8818 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
8819 }
8820
8821 #[test]
8822 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
8823 for held in [false, true] {
8824 for question in [false, true] {
8825 for reference in ["ca5b", "20261013-193611-ca5b"] {
8826 let dir = tempfile::tempdir().unwrap();
8827 let queue = Queue::at(dir.path().join("queue"));
8828 let questions = ask::Questions::at(dir.path().join("questions"));
8829 let mut prerequisite = task();
8830 prerequisite.id = "20261013-193611-ca5b".into();
8831 prerequisite.start("existing-run".into());
8832 queue.put(&mut prerequisite).unwrap();
8833 let mut waiting = task();
8834 waiting.id = "20261013-202849-ee37".into();
8835 if held {
8836 waiting.hold_machine(Some("waiting for separate consent".into()));
8837 }
8838 queue.put(&mut waiting).unwrap();
8839 let reason = "Deleting saved data requires separate owner consent";
8840 crate::conduct::apply(
8841 &queue,
8842 &questions,
8843 &crate::conduct::Verdict {
8844 decisions: vec![crate::conduct::Decision {
8845 id: waiting.id.clone(),
8846 blocked_by: vec![reference.into()],
8847 question: question.then(|| "May the saved data be deleted?".into()),
8848 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
8849 reason: Some(reason.into()),
8850 ..crate::conduct::Decision::default()
8851 }],
8852 },
8853 )
8854 .unwrap();
8855 let before = queue.get(&waiting.id).unwrap();
8856 if question {
8857 assert_eq!(before.status, TaskStatus::Blocked);
8858 let q = questions.get(&before.blocked_by[0]).unwrap();
8859 assert_eq!(q.summary, "May the saved data be deleted?");
8860 assert!(q.status.open());
8861 } else {
8862 assert_eq!(before.status, TaskStatus::Held);
8863 let recorded_reason = before.hold_reason.as_deref().unwrap();
8864 assert!(recorded_reason.starts_with(reason));
8865 if held {
8866 assert!(recorded_reason.contains("waiting for separate consent"));
8867 }
8868 }
8869 prerequisite.succeed();
8870 queue.put(&mut prerequisite).unwrap();
8871 resolve_blockers(&queue, &questions);
8872 let after = queue.get(&waiting.id).unwrap();
8873 assert_eq!(after.status, before.status);
8874 assert_eq!(after.blocked_by, before.blocked_by);
8875 assert_eq!(after.hold_reason, before.hold_reason);
8876 assert_eq!(after.instruction, waiting.instruction);
8877 if question {
8878 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
8879 }
8880 assert!(
8881 queue.next_runnable().is_none(),
8882 "dependency completion is not consent"
8883 );
8884 }
8885 }
8886 }
8887 }
8888
8889 #[test]
8890 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
8891 let dir = tempfile::tempdir().unwrap();
8892 let queue = Queue::at(dir.path().join("queue"));
8893 let questions = ask::Questions::at(dir.path().join("questions"));
8894
8895 let mut dep = task();
8896 dep.id = "20260101-000001-dep0".to_owned();
8897 dep.succeed();
8898 queue.put(&mut dep).unwrap();
8899
8900 let mut still_going = task();
8901 still_going.id = "20260101-000002-dep1".to_owned();
8902 queue.put(&mut still_going).unwrap();
8903
8904 let mut blocked = task();
8905 blocked.id = "20260101-000003-main".to_owned();
8906 blocked.block(
8907 vec![dep.id.clone(), still_going.id.clone()],
8908 Some("waits on both".to_owned()),
8909 );
8910 queue.put(&mut blocked).unwrap();
8911
8912 resolve_blockers(&queue, &questions);
8913
8914 let after = queue.get(&blocked.id).unwrap();
8915 assert_eq!(
8916 after.status,
8917 TaskStatus::Blocked,
8918 "one dependency is still outstanding"
8919 );
8920 assert_eq!(after.blocked_by, [still_going.id.clone()]);
8921 }
8922
8923 #[test]
8924 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
8925 let dir = tempfile::tempdir().unwrap();
8926 let queue = Queue::at(dir.path().join("queue"));
8927 let questions = ask::Questions::at(dir.path().join("questions"));
8928
8929 let mut q = crate::ask::Question::new(
8930 "20260101-000001-main".to_owned(),
8931 crate::conduct::NODE.to_owned(),
8932 "conduct".to_owned(),
8933 "Which backend?".to_owned(),
8934 String::new(),
8935 Vec::new(),
8936 );
8937 questions.put(&mut q).unwrap();
8938 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
8939 .unwrap();
8940 questions.put(&mut q).unwrap();
8941
8942 let mut blocked = task();
8943 blocked.id = "20260101-000001-main".to_owned();
8944 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
8945 queue.put(&mut blocked).unwrap();
8946
8947 resolve_blockers(&queue, &questions);
8948
8949 let after = queue.get(&blocked.id).unwrap();
8950 assert_eq!(
8951 after.status,
8952 TaskStatus::Queued,
8953 "the only blocker resolved"
8954 );
8955 assert_eq!(after.answers.len(), 1);
8956 assert_eq!(after.answers[0].question, "Which backend?");
8957 assert_eq!(after.answers[0].answer, "SQLite");
8958
8959 let instruction = instruction_for(&after);
8961 assert!(instruction.contains("Which backend?"));
8962 assert!(instruction.contains("SQLite"));
8963 }
8964
8965 #[test]
8966 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
8967 let dir = tempfile::tempdir().unwrap();
8968 let queue = Queue::at(dir.path().join("queue"));
8969 let questions = ask::Questions::at(dir.path().join("questions"));
8970
8971 let mut q = crate::ask::Question::new(
8972 "20260101-000001-main".to_owned(),
8973 crate::conduct::NODE.to_owned(),
8974 "conduct".to_owned(),
8975 "Is the setup done?".to_owned(),
8976 String::new(),
8977 Vec::new(),
8978 );
8979 q.abandon("no answer within 60s of asking");
8980 questions.put(&mut q).unwrap();
8981
8982 let mut blocked = task();
8983 blocked.id = "20260101-000001-main".to_owned();
8984 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
8985 queue.put(&mut blocked).unwrap();
8986
8987 resolve_blockers(&queue, &questions);
8988
8989 let after = queue.get(&blocked.id).unwrap();
8990 assert_eq!(
8991 after.status,
8992 TaskStatus::Held,
8993 "never left blocked on nothing"
8994 );
8995 assert!(!after.operator_held(), "a machine hold, for triage");
8996 assert!(
8997 after
8998 .hold_reason
8999 .as_deref()
9000 .unwrap_or_default()
9001 .contains("went unanswered")
9002 );
9003 }
9004
9005 #[test]
9006 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9007 let dir = tempfile::tempdir().unwrap();
9013 let queue = Queue::at(dir.path().join("queue"));
9014 let questions = ask::Questions::at(dir.path().join("questions"));
9015
9016 let mut q = crate::ask::Question::new(
9017 "20260101-000001-main".to_owned(),
9018 crate::conduct::NODE.to_owned(),
9019 "conduct".to_owned(),
9020 "How should this be handled?".to_owned(),
9021 String::new(),
9022 Vec::new(),
9023 );
9024 questions.put(&mut q).unwrap();
9025 q.answer(crate::ask::Answer::Text(
9026 "leave it held, a human will look at it later".to_owned(),
9027 ))
9028 .unwrap();
9029 questions.put(&mut q).unwrap();
9030
9031 let mut held = task();
9032 held.id = "20260101-000001-main".to_owned();
9033 held.hold_machine(Some("out of attempts".to_owned()));
9034 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
9035 queue.put(&mut held).unwrap();
9036
9037 resolve_blockers(&queue, &questions);
9038
9039 let after = queue.get(&held.id).unwrap();
9040 assert_eq!(after.status, TaskStatus::Held);
9041 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
9042 assert_eq!(
9043 after.answers[0].answer,
9044 "leave it held, a human will look at it later"
9045 );
9046 }
9047
9048 #[test]
9049 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
9050 let dir = tempfile::tempdir().unwrap();
9051 let queue = Queue::at(dir.path().join("queue"));
9052 let questions = ask::Questions::at(dir.path().join("questions"));
9053 let mut dep = task();
9054 dep.id = "20260101-000001-gone".to_owned();
9055 queue.put(&mut dep).unwrap();
9056 let mut blocked = task();
9057 blocked.id = "20260101-000003-main".to_owned();
9058 blocked.block(vec![dep.id.clone()], None);
9059 queue.put(&mut blocked).unwrap();
9060
9061 let claim = queue.claim(&blocked.id).unwrap();
9063 queue.remove(&dep.id, false, &questions).unwrap();
9064 drop(claim);
9065 resolve_blockers(&queue, &questions);
9066
9067 let after = queue.get(&blocked.id).unwrap();
9068 assert_eq!(after.status, TaskStatus::Queued);
9069 assert!(after.blocked_by.is_empty());
9070 }
9071
9072 #[test]
9073 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
9074 let dir = tempfile::tempdir().unwrap();
9080 let queue = Queue::at(dir.path().join("queue"));
9081 let questions = ask::Questions::at(dir.path().join("questions"));
9082
9083 let mut still_going = task();
9084 still_going.id = "20260101-000002-dep1".to_owned();
9085 queue.put(&mut still_going).unwrap();
9086
9087 let mut blocked = task();
9088 blocked.id = "20260101-000003-main".to_owned();
9089 blocked.block(
9090 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
9091 Some("waits on both".to_owned()),
9092 );
9093 queue.put(&mut blocked).unwrap();
9094
9095 resolve_blockers(&queue, &questions);
9096
9097 let after = queue.get(&blocked.id).unwrap();
9098 assert_eq!(
9099 after.status,
9100 TaskStatus::Held,
9101 "a missing dependency must not leave the task blocked forever"
9102 );
9103 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
9104 assert!(after.blocked_by.is_empty());
9105 let reason = after.hold_reason.as_deref().unwrap_or_default();
9106 assert!(
9107 reason.contains("20260101-000001-gone"),
9108 "the missing id must be named so an operator can tell what happened: {reason}"
9109 );
9110 assert!(
9111 reason.contains(&still_going.id),
9112 "the still-valid dependency must not silently vanish from the record: {reason}"
9113 );
9114 }
9115
9116 #[test]
9117 fn instruction_for_is_unchanged_without_any_answers() {
9118 let t = task();
9119 assert_eq!(instruction_for(&t), t.instruction);
9120 }
9121
9122 #[test]
9123 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
9124 let dir = tempfile::tempdir().unwrap();
9125 let q = Queue::at(dir.path().join("queue"));
9126 let src = dir.path().join("shot.png");
9127 std::fs::write(&src, "x").unwrap();
9128 let mut t = task();
9129 q.attach(&mut t, &[src]).unwrap();
9130 let paths = task_attachments(&q, &t).unwrap();
9131 assert_eq!(paths.len(), 1);
9132 assert!(paths[0].is_absolute() && paths[0].is_file());
9133 std::fs::remove_file(&paths[0]).unwrap();
9134 let err = task_attachments(&q, &t).unwrap_err().to_string();
9135 assert!(err.contains("shot.png"), "{err}");
9136 }
9137
9138 #[tokio::test]
9139 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
9140 let dir = tempfile::tempdir().unwrap();
9141 let queue_path = dir.path().join("queue");
9142 let queue = Queue::at(queue_path.clone());
9143 let mut t = task();
9144 t.source = Source::Agent {
9145 run: "originating-chat".into(),
9146 node: crate::queue::CHAT_NODE.into(),
9147 };
9148 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
9149 stage: "config-fetch",
9150 target: "origin/main".into(),
9151 });
9152 record_config_failure(&mut t, &fetch);
9153 t.hold_machine(Some(format!("{fetch:#}")));
9154 let fetch_key = t.chat_notice_due().unwrap();
9155 t.chat_notices.push(fetch_key.clone());
9156 queue.put(&mut t).unwrap();
9157
9158 let queue = Queue::at(queue_path);
9159 let mut t = queue.get(&t.id).unwrap();
9160 let a = dir.path().join("a.toml");
9161 let b = dir.path().join("b.toml");
9162 for (path, text, new_cause) in [
9163 (&a, "[graph", true),
9164 (&a, "[verify", false),
9165 (&a, "[graph]\nimplementers = 'invalid-type'", true),
9166 (&b, "[graph]\nimplementers = 'invalid-type'", true),
9167 ] {
9168 t.release_operator("test", None);
9169 std::fs::write(path, text).unwrap();
9170 let error = Config::discover_fetched(dir.path(), Some(path))
9171 .await
9172 .unwrap_err();
9173 record_config_failure(&mut t, &error);
9174 t.hold_machine(Some(format!("{error:#}")));
9175 let due = t.chat_notice_due();
9176 assert_eq!(due.is_some(), new_cause, "{error:#}");
9177 if let Some(key) = due {
9178 assert_ne!(key, fetch_key);
9179 t.chat_notices.push(key);
9180 }
9181 }
9182 t.succeed();
9183 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
9184 }
9185
9186 #[test]
9187 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
9188 let dir = tempfile::tempdir().unwrap();
9189 let queue_path = dir.path().join("queue");
9190 let queue = Queue::at(queue_path.clone());
9191 let mut t = task();
9192 t.source = crate::queue::Source::Agent {
9193 run: "originating-chat".into(),
9194 node: crate::queue::CHAT_NODE.into(),
9195 };
9196 let a = dir.path().join("a.png");
9197 let b = dir.path().join("b.png");
9198 std::fs::write(&a, "a").unwrap();
9199 std::fs::write(&b, "b").unwrap();
9200 queue.attach(&mut t, &[a, b]).unwrap();
9201 let paths = task_attachments(&queue, &t).unwrap();
9202 for path in &paths {
9203 std::fs::remove_file(path).unwrap();
9204 }
9205 let missing = task_attachments(&queue, &t).unwrap_err();
9206 t.attempts += 1;
9207 let reason = missing.to_string();
9208 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9209 let first = t.chat_notice_due().expect("first attachment notice");
9210 t.chat_notices.push(first.clone());
9211 queue.put(&mut t).unwrap();
9212
9213 let queue = Queue::at(queue_path.clone());
9214 let mut t = queue.get(&t.id).unwrap();
9215 assert!(t.chat_notice_due().is_none(), "restart does not replay");
9216 t.release_operator("test", None);
9217 t.attempts += 1;
9218 let missing = task_attachments(&queue, &t).unwrap_err();
9219 t.fail_startup_target(
9220 "startup-attachments",
9221 missing.name,
9222 "same missing attachment with regenerated wording",
9223 1,
9224 );
9225 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
9226
9227 std::fs::write(&paths[0], "restored").unwrap();
9228 t.release_operator("test", None);
9229 t.attempts += 1;
9230 let missing = task_attachments(&queue, &t).unwrap_err();
9231 let reason = missing.to_string();
9232 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9233 let second = t
9234 .chat_notice_due()
9235 .expect("different attachment must notify");
9236 assert_ne!(first, second);
9237 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
9238 }
9239
9240 #[test]
9241 fn resumed_instruction_is_unchanged_without_any_answers() {
9242 let t = task();
9243 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
9244 }
9245
9246 #[test]
9247 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
9248 let mut t = task();
9249 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9250 let old = t.instruction.clone();
9254
9255 let refreshed = resumed_instruction(&old, &t);
9256 assert!(refreshed.starts_with(&old), "the original text is kept");
9257 assert!(refreshed.contains("Which backend?"));
9258 assert!(refreshed.contains("SQLite"));
9259 }
9260
9261 #[test]
9262 fn resumed_instruction_keeps_an_original_answers_heading() {
9263 let mut t = task();
9264 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
9265 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9266
9267 let refreshed = resumed_instruction(&t.instruction, &t);
9268
9269 assert!(
9270 refreshed.starts_with(&t.instruction),
9271 "an answers heading in the original instruction is not the appended block"
9272 );
9273 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
9274 assert!(refreshed.contains("Which backend?"));
9275 assert!(refreshed.contains("SQLite"));
9276
9277 let repeated = resumed_instruction(&refreshed, &t);
9278 assert_eq!(
9279 repeated, refreshed,
9280 "only the final appended block is refreshed"
9281 );
9282 }
9283
9284 #[test]
9285 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
9286 let mut t = task();
9287 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9288
9289 let once = resumed_instruction(&t.instruction, &t);
9293 let twice = resumed_instruction(&once, &t);
9294 assert_eq!(once, twice);
9295 assert_eq!(once.matches("Which backend?").count(), 1);
9296
9297 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
9299 let refreshed = resumed_instruction(&once, &t);
9300 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
9301 assert!(refreshed.contains("Which backend?"));
9302 assert!(refreshed.contains("Which cache?"));
9303 }
9304
9305 #[test]
9306 fn prepare_instruction_covers_all_three_starters() {
9307 let mut t = task();
9308 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9309
9310 assert_eq!(
9313 prepare_instruction(&Starter::Start, None, &t),
9314 Some(instruction_for(&t))
9315 );
9316
9317 let old = t.instruction.clone();
9320 assert_eq!(
9321 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
9322 Some(resumed_instruction(&old, &t))
9323 );
9324
9325 assert_eq!(
9329 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
9330 None
9331 );
9332 }
9333
9334 #[test]
9335 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
9336 assert_eq!(
9337 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
9338 Starter::Review("magi/eba2/A".to_owned())
9339 );
9340 }
9341
9342 #[test]
9343 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
9344 assert_eq!(
9345 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
9346 Starter::Start,
9347 "a vanished review branch must not fall back to resuming the old run either"
9348 );
9349 }
9350
9351 #[test]
9352 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
9353 let mut t = task();
9354 t.start("old-run".to_owned());
9355 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
9356 t.release();
9357 let branch = t.review_branch.take();
9358 assert_eq!(
9359 choose_starter(branch.as_deref(), true, Some("old-run")),
9360 Starter::Review("magi/eba2/A".to_owned()),
9361 "a review wins over resuming the old run"
9362 );
9363 }
9364
9365 #[test]
9366 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
9367 assert_eq!(
9368 choose_starter(None, false, Some("some-run")),
9369 Starter::Resume("some-run".to_owned())
9370 );
9371 assert_eq!(choose_starter(None, false, None), Starter::Start);
9372 }
9373
9374 #[test]
9375 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
9376 let mut released = task();
9377 released.start("stalled-run".to_owned());
9378 released.requeue();
9379 let unfinished = (!released.fresh_start)
9380 .then(|| Some("stalled-run".to_owned()))
9381 .flatten();
9382 assert_eq!(
9383 choose_starter(None, false, unfinished.as_deref()),
9384 Starter::Start,
9385 "release keeps run history but must not resume it"
9386 );
9387 assert_eq!(released.runs, ["stalled-run"]);
9388 }
9389
9390 #[test]
9391 fn an_ordinary_release_keeps_a_resumable_run_available() {
9392 let mut released = task();
9393 released.start("stalled-run".to_owned());
9394 released.release();
9395 let unfinished = (!released.fresh_start)
9396 .then(|| Some("stalled-run".to_owned()))
9397 .flatten();
9398 assert_eq!(
9399 choose_starter(None, false, unfinished.as_deref()),
9400 Starter::Resume("stalled-run".to_owned()),
9401 "manual release must preserve the normal resume path"
9402 );
9403 }
9404
9405 #[test]
9406 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
9407 let mut state = run_state(RunStatus::Blocked);
9408 state.config.graph.review_rounds = 3;
9409 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
9410 assert!(exhausted_review_budget(&state));
9411
9412 state.reviews.pop();
9414 assert!(!exhausted_review_budget(&state));
9415
9416 let mut stalled = run_state(RunStatus::Stalled);
9419 stalled.config.graph.review_rounds = 1;
9420 stalled.reviews = vec![review_round(1)];
9421 assert!(!exhausted_review_budget(&stalled));
9422 }
9423
9424 fn review_round(round: usize) -> crate::run::ReviewRound {
9425 crate::run::ReviewRound {
9426 round,
9427 head: "deadbeef".to_owned(),
9428 verified_head: None,
9429 verified_at: None,
9430 reviews: Vec::new(),
9431 e2e: Vec::new(),
9432 verify_retried: false,
9433 e2e_deferred: false,
9434 e2e_defer_reason: None,
9435 fix: None,
9436 blocking: 0,
9437 answered: 1,
9438 expected: 1,
9439 clean: false,
9440 progressed: true,
9441 vote_split: false,
9442 reconsideration: Vec::new(),
9443 verdict: None,
9444 }
9445 }
9446
9447 #[test]
9448 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
9449 let mut run = RunState::new(
9450 PathBuf::from("/repo"),
9451 "main".to_owned(),
9452 "abc1234def".to_owned(),
9453 "add retries".to_owned(),
9454 Config::default(),
9455 );
9456 run.status = RunStatus::Judging;
9457 run.parked = true;
9458 let mut task = Task::new(
9459 "add retries".to_owned(),
9460 "add retries".to_owned(),
9461 PathBuf::from("/repo"),
9462 crate::queue::Source::Human,
9463 );
9464 task.status = TaskStatus::Failed;
9465 task.runs = vec![run.id.clone()];
9466 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
9467 assert!(with(&task, &run), "parked after judging is the case");
9468 let mut parked_task = task.clone();
9469 parked_task.status = TaskStatus::Parked;
9470 assert!(with(&parked_task, &run), "the Parked status is the case");
9471
9472 let mut not_parked = run.clone();
9473 not_parked.parked = false;
9474 not_parked.status = RunStatus::Stalled;
9475 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
9476
9477 let mut fresh = task.clone();
9478 fresh.fresh_start = true;
9479 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
9480
9481 let mut review = task.clone();
9482 review.review_branch = Some("magi/x/A".to_owned());
9483 assert!(!with(&review, &run), "review is ranked before resume");
9484
9485 let mut held = task.clone();
9486 held.status = TaskStatus::Held;
9487 assert!(!with(&held, &run), "a hold stays visible to the conductor");
9488
9489 let mut released = run.clone();
9490 released.released_to = Some("20260901-000000-new1".to_owned());
9491 assert!(!with(&task, &released), "nothing left to resume into");
9492
9493 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
9494 "unreadable"
9495 )));
9496 }
9497
9498 #[test]
9499 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
9500 let mut released = RunState::new(
9501 PathBuf::from("/repo"),
9502 "main".to_owned(),
9503 "abc1234def".to_owned(),
9504 "add retries".to_owned(),
9505 Config::default(),
9506 );
9507 released.status = RunStatus::Blocked;
9508 assert_eq!(
9509 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9510 Some(released.id.clone())
9511 );
9512 released.released_to = Some("20260901-000000-new1".to_owned());
9513 assert_eq!(
9514 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9515 None,
9516 "there is nothing left to resume it into"
9517 );
9518 }
9519
9520 #[test]
9521 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
9522 let mut exhausted = RunState::new(
9531 PathBuf::from("/repo"),
9532 "main".to_owned(),
9533 "abc1234def".to_owned(),
9534 "add retries".to_owned(),
9535 Config::default(),
9536 );
9537 exhausted.status = RunStatus::Blocked;
9538 exhausted.config.graph.review_rounds = 1;
9539 exhausted.reviews = vec![review_round(1)];
9540
9541 assert_eq!(
9542 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
9543 None,
9544 "an exhausted `Blocked` run must not be offered as resumable"
9545 );
9546
9547 let mut has_budget_left = RunState::new(
9550 PathBuf::from("/repo"),
9551 "main".to_owned(),
9552 "abc1234def".to_owned(),
9553 "add retries".to_owned(),
9554 Config::default(),
9555 );
9556 has_budget_left.status = RunStatus::Blocked;
9557 has_budget_left.config.graph.review_rounds = 3;
9558 has_budget_left.reviews = vec![review_round(1)];
9559
9560 assert_eq!(
9561 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
9562 Ok(has_budget_left.clone())
9563 }),
9564 Some(has_budget_left.id.clone())
9565 );
9566 }
9567
9568 #[test]
9569 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
9570 let mut run = RunState::new(
9571 PathBuf::from("/repo"),
9572 "main".to_owned(),
9573 "abc1234def".to_owned(),
9574 "add retries".to_owned(),
9575 Config::default(),
9576 );
9577 run.status = RunStatus::Blocked;
9578 run.config.graph.review_rounds = 1;
9579 run.reviews = vec![review_round(1)];
9580 run.pr_publication_pending = true;
9581 assert_eq!(
9582 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
9583 Some(run.id.clone()),
9584 "a spent review budget must not turn a failed publication into a re-competition"
9585 );
9586 }
9587
9588 #[test]
9589 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
9590 let mut older_stalled = RunState::new(
9598 PathBuf::from("/repo"),
9599 "main".to_owned(),
9600 "abc1234def".to_owned(),
9601 "add retries".to_owned(),
9602 Config::default(),
9603 );
9604 older_stalled.status = RunStatus::Stalled;
9605
9606 let mut newest_exhausted = RunState::new(
9607 PathBuf::from("/repo"),
9608 "main".to_owned(),
9609 "abc1234def".to_owned(),
9610 "add retries".to_owned(),
9611 Config::default(),
9612 );
9613 newest_exhausted.status = RunStatus::Blocked;
9614 newest_exhausted.config.graph.review_rounds = 1;
9615 newest_exhausted.reviews = vec![review_round(1)];
9616
9617 assert_eq!(
9618 unfinished_run_with(
9619 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
9620 "t",
9621 |_| Ok(newest_exhausted.clone())
9622 ),
9623 None,
9624 "the newest run is exhausted, so nothing here is worth resuming - \
9625 least of all the older, already-superseded run"
9626 );
9627 }
9628
9629 #[test]
9630 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
9631 assert_eq!(
9632 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
9633 Err(anyhow::anyhow!("fixture is absent"))
9634 }),
9635 None
9636 );
9637 }
9638
9639 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
9640 let mut q = ask::Question::new(
9641 run.to_owned(),
9642 "implement".to_owned(),
9643 "impl-A".to_owned(),
9644 "continue?".to_owned(),
9645 String::new(),
9646 vec!["resume で続行する".to_owned(), "other".to_owned()],
9647 );
9648 q.actions.insert("resume で続行する".to_owned(), action);
9649 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
9650 .unwrap();
9651 q
9652 }
9653
9654 fn held_task_with(run: &str) -> Task {
9655 let mut t = task();
9656 t.runs = vec![run.to_owned()];
9657 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
9658 t
9659 }
9660
9661 fn resume_action(run: &str) -> ask::ChoiceAction {
9662 ask::ChoiceAction::Resume { run: run.into() }
9663 }
9664
9665 #[test]
9666 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
9667 for parked in [false, true] {
9668 let mut t = task();
9669 t.start("A".into());
9670 t.start("B".into());
9671 assert_eq!(t.runs, vec!["A", "B"]);
9672 t.start("A".into());
9673 let mut resumed = run_state(RunStatus::Blocked);
9674 resumed.id = "A".into();
9675 resumed.parked = parked;
9676 resumed.driver_exited = true;
9677 t.hold_machine(Some("resumed run stopped".into()));
9678 let q = action_question("A", resume_action("A"));
9679 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
9680 assert_eq!(
9681 decide_action(&t, &q, &PHRASES_EN, |id| {
9682 assert_eq!(id, "A");
9683 Ok(resumed.clone())
9684 }),
9685 ActionDecision::Resume("A".into())
9686 );
9687 assert_eq!(
9688 action_standing(&t, &action_question("B", resume_action("B"))),
9689 ActionStanding::Stale
9690 );
9691 t.release_operator("cli", None);
9692 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
9693 assert_eq!(id, "A");
9694 Ok(resumed.clone())
9695 });
9696 assert_eq!(
9697 choose_starter(None, false, unfinished.as_deref()),
9698 Starter::Resume("A".into())
9699 );
9700 assert_eq!(t.runs, vec!["B", "A"]);
9701 }
9702 }
9703
9704 #[test]
9705 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
9706 let mut state = crate::land::tests::repair_state(true, true);
9707 state.status = RunStatus::Landing;
9708 state.parked = true;
9709 state.driver_exited = true;
9710 let mut q = ask::Question::new(
9711 state.id.clone(),
9712 land::APPROVAL_NODE.into(),
9713 "land".into(),
9714 "Merge?".into(),
9715 String::new(),
9716 vec![land::APPROVE.into(), land::HOLD.into()],
9717 );
9718 q.id = state.id.clone();
9719 state.land_approval = Some(crate::run::LandApproval {
9720 question: q.id.clone(),
9721 head: "current-head".into(),
9722 });
9723 assert!(land::upgrade_repair_choice(&mut q, &state));
9724 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
9725 let mut task = held_task_with(&state.id);
9726 task.status = TaskStatus::Parked;
9727 assert_eq!(
9728 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
9729 ActionDecision::Resume(state.id.clone())
9730 );
9731 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
9732 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
9733 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
9734 assert_eq!(
9735 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
9736 ActionDecision::Resume(state.id.clone()),
9737 "a repair answer newer than the manual hold resumes the existing owner"
9738 );
9739 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
9740 for answered_at in [q.answered_at, None] {
9741 let mut older = q.clone();
9742 older.answered_at = answered_at;
9743 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
9744 panic!("a later manual hold must prevent dispatch")
9745 });
9746 let ActionDecision::Refuse(reason) = refused else {
9747 panic!("expected an actionable refusal, got {refused:?}");
9748 };
9749 assert!(reason.contains("later operator decision"));
9750 assert!(reason.contains(&format!("magi task release {}", task.id)));
9751 }
9752 task.operator_decided_at = None;
9753 let mut superseded = state.clone();
9754 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
9755 assert_eq!(
9756 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
9757 ActionDecision::Stale
9758 );
9759 for case in 1..4 {
9760 let mut changed = state.clone();
9761 match case {
9762 1 => changed.status = RunStatus::Blocked,
9763 2 => changed.released_to = Some("new-owner".into()),
9764 _ => changed.land_approval.as_mut().unwrap().head.clear(),
9765 }
9766 assert!(matches!(
9767 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
9768 ActionDecision::Refuse(_)
9769 ));
9770 }
9771 assert!(matches!(
9772 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
9773 ActionDecision::Refuse(_)
9774 ));
9775 task.runs.push("replacement".into());
9776 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
9777 assert_eq!(
9778 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
9779 "old owner must not load"
9780 )),
9781 ActionDecision::Stale
9782 );
9783 }
9784
9785 #[test]
9786 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
9787 let mut state = crate::land::tests::repair_state(true, true);
9788 state.status = RunStatus::Landing;
9789 state.parked = true;
9790 state.driver_exited = true;
9791 let mut q = ask::Question::new(
9792 state.id.clone(),
9793 land::APPROVAL_NODE.into(),
9794 "land".into(),
9795 "Merge?".into(),
9796 String::new(),
9797 vec![land::APPROVE.into(), land::HOLD.into()],
9798 );
9799 q.id = state.id.clone();
9800 state.land_approval = Some(crate::run::LandApproval {
9801 question: q.id.clone(),
9802 head: "current-head".into(),
9803 });
9804 state.save().unwrap();
9805 land::upgrade_repair_choice(&mut q, &state);
9806 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
9807 Questions::open().put(&mut q).unwrap();
9808 let tmp = tempfile::tempdir().unwrap();
9809 let queue = Queue::at(tmp.path().join("queue"));
9810 let mut task = held_task_with(&state.id);
9811 task.status = TaskStatus::Parked;
9812 queue.put(&mut task).unwrap();
9813 let empty = Arc::new(tokio::sync::Semaphore::new(0));
9814 let free = Arc::new(tokio::sync::Semaphore::new(1));
9815 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
9816 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
9817 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
9818 assert!(claim.permit.is_some());
9819 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
9820 drop(claim);
9821 Questions::open()
9822 .update(&q.id, |q| {
9823 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
9824 Ok(())
9825 })
9826 .unwrap();
9827 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
9828 assert!(claim.permit.is_none());
9829 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
9830 }
9831
9832 #[test]
9833 fn decide_action_resumes_only_the_latest_resumable_run() {
9834 let t = held_task_with("r1");
9835 let q = action_question("r1", resume_action("r1"));
9836 let load = |s: RunState| move |_: &str| Ok(s);
9837 assert_eq!(
9838 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
9839 ActionDecision::Resume("r1".into())
9840 );
9841 let q_other = action_question("r1", resume_action("r0"));
9843 assert!(matches!(
9844 decide_action(
9845 &t,
9846 &q_other,
9847 &PHRASES_EN,
9848 load(run_state(RunStatus::Blocked))
9849 ),
9850 ActionDecision::Refuse(_)
9851 ));
9852 assert!(matches!(
9854 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
9855 ActionDecision::Refuse(_)
9856 ));
9857 let mut released = run_state(RunStatus::Blocked);
9859 released.released_to = Some("elsewhere".into());
9860 assert!(matches!(
9861 decide_action(&t, &q, &PHRASES_EN, load(released)),
9862 ActionDecision::Refuse(_)
9863 ));
9864 assert!(matches!(
9866 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
9867 ActionDecision::Refuse(_)
9868 ));
9869 }
9870
9871 #[test]
9872 fn decide_action_ignores_a_question_about_an_earlier_run() {
9873 let mut t = held_task_with("r1");
9874 t.runs.push("r2".to_owned());
9875 let never = |_: &str| -> Result<RunState> { bail!("not read") };
9876 assert_eq!(
9877 decide_action(
9878 &t,
9879 &action_question("r1", ask::ChoiceAction::Done),
9880 &PHRASES_EN,
9881 never
9882 ),
9883 ActionDecision::Stale
9884 );
9885 }
9886
9887 #[test]
9888 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
9889 let mut t = held_task_with("r1");
9890 let never = |_: &str| -> Result<RunState> { bail!("not read") };
9891 assert_eq!(
9892 decide_action(
9893 &t,
9894 &action_question("r1", ask::ChoiceAction::Requeue),
9895 &PHRASES_EN,
9896 never
9897 ),
9898 ActionDecision::Requeue
9899 );
9900 let done_q = action_question("r1", ask::ChoiceAction::Done);
9901 assert_eq!(
9902 decide_action(&t, &done_q, &PHRASES_EN, never),
9903 ActionDecision::Done
9904 );
9905 t.mark_action_applied(&done_q.id);
9906 assert_eq!(
9907 decide_action(&t, &done_q, &PHRASES_EN, never),
9908 ActionDecision::Skip
9909 );
9910
9911 let mut plain = action_question("r1", ask::ChoiceAction::Done);
9913 plain.actions.clear();
9914 assert_eq!(
9915 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
9916 ActionDecision::Skip
9917 );
9918 let mut running = held_task_with("r1");
9920 running.status = TaskStatus::Running;
9921 assert_eq!(
9922 decide_action(
9923 &running,
9924 &action_question("r1", ask::ChoiceAction::Done),
9925 &PHRASES_EN,
9926 never
9927 ),
9928 ActionDecision::Skip
9929 );
9930 }
9931
9932 #[test]
9933 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
9934 crate::run::pin_test_home();
9935 for legacy in [false, true] {
9936 let dir = tempfile::tempdir().unwrap();
9937 let queue = Queue::at(dir.path().join("queue"));
9938 let questions = Questions::at(dir.path().join("questions"));
9939 let run = "20260101-000000-hold";
9940 let mut task = held_task_with(run);
9941 task.status = TaskStatus::Parked;
9942 let mut q = ask::Question::new(
9943 run.into(),
9944 land::APPROVAL_NODE.into(),
9945 "land".into(),
9946 "Repair?".into(),
9947 String::new(),
9948 vec![land::REPAIR.into()],
9949 );
9950 q.actions.insert(land::REPAIR.into(), resume_action(run));
9951 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
9952 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
9954 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
9955 questions.put(&mut q).unwrap();
9956 task.hold_manual(Some("Keep this PR paused".into()));
9957 if legacy {
9958 task.hold_source = None;
9959 }
9960 queue.put(&mut task).unwrap();
9961
9962 apply_choice_actions(&queue, &questions, dir.path());
9963 let after = queue.get(&task.id).unwrap();
9964 assert!(after.operator_held());
9965 assert_eq!(after.hold_source, task.hold_source);
9966 assert_eq!(after.operator_decided_at, task.operator_decided_at);
9967 assert_eq!(after.runs, task.runs);
9968 assert_eq!(after.instruction, task.instruction);
9969 assert!(after.resume_override.is_none());
9970 assert!(after.action_applied(&q.id));
9971 let reason = after.hold_reason.as_deref().unwrap();
9972 assert!(reason.starts_with("Keep this PR paused"));
9973 assert!(reason.contains("later operator decision"));
9974 assert!(reason.contains(&format!("magi task release {}", task.id)));
9975
9976 for recovery in [
9977 crate::conduct::Recovery::Review,
9978 crate::conduct::Recovery::Requeue,
9979 ] {
9980 crate::conduct::apply(
9981 &queue,
9982 &questions,
9983 &crate::conduct::Verdict {
9984 decisions: vec![crate::conduct::Decision {
9985 id: task.id.clone(),
9986 recovery: Some(recovery),
9987 ..Default::default()
9988 }],
9989 },
9990 )
9991 .unwrap();
9992 }
9993 apply_choice_actions(&queue, &questions, dir.path());
9996 let still_held = queue.get(&task.id).unwrap();
9997 assert!(still_held.operator_held());
9998 assert_eq!(still_held.hold_reason, after.hold_reason);
9999 assert_eq!(still_held.runs, task.runs);
10000 assert!(still_held.review_branch.is_none());
10001 assert!(!still_held.fresh_start);
10002 assert!(queue.next_runnable().is_none());
10003 }
10004 }
10005
10006 #[test]
10007 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
10008 let dir = tempfile::tempdir().unwrap();
10009 let queue = Queue::at(dir.path().join("queue"));
10010 let questions = Questions::at(dir.path().join("questions"));
10011 let home = dir.path().join("home");
10012 let mut state = run_state(RunStatus::Blocked);
10013 state.id = "20260101-000000-act1".to_owned();
10014 state.save_under(&home).unwrap();
10015
10016 let mut t = held_task_with(&state.id);
10017 queue.put(&mut t).unwrap();
10018 let mut q = action_question(&state.id, resume_action(&state.id));
10019 questions.put(&mut q).unwrap();
10020
10021 apply_choice_actions(&queue, &questions, &home);
10022 let after = queue.get(&t.id).unwrap();
10023 assert_eq!(after.status, TaskStatus::Queued);
10024 assert!(!after.fresh_start);
10025 assert!(after.action_applied(&q.id));
10026 let pin = after.resume_override.clone().unwrap();
10027 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
10028 assert!(pin.forced);
10029
10030 let mut again = queue.get(&t.id).unwrap();
10032 again.hold_machine(Some("later".into()));
10033 queue.put(&mut again).unwrap();
10034 apply_choice_actions(&queue, &questions, &home);
10035 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10036 }
10037
10038 #[test]
10039 fn a_delivered_answer_is_still_acted_on_exactly_once() {
10040 let dir = tempfile::tempdir().unwrap();
10041 let queue = Queue::at(dir.path().join("queue"));
10042 let questions = Questions::at(dir.path().join("questions"));
10043 let home = dir.path().join("home");
10044 let mut state = run_state(RunStatus::Blocked);
10045 state.id = "20260101-000000-act2".to_owned();
10046 state.save_under(&home).unwrap();
10047
10048 let mut t = held_task_with(&state.id);
10049 queue.put(&mut t).unwrap();
10050 let mut q = action_question(&state.id, resume_action(&state.id));
10051 q.answer_delivered = true;
10052 questions.put(&mut q).unwrap();
10053
10054 apply_choice_actions(&queue, &questions, &home);
10057 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10058 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
10059
10060 let mut again = queue.get(&t.id).unwrap();
10062 again.hold_machine(Some("later".into()));
10063 queue.put(&mut again).unwrap();
10064 apply_choice_actions(&queue, &questions, &home);
10065 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10066 }
10067
10068 #[test]
10069 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
10070 let dir = tempfile::tempdir().unwrap();
10071 let queue = Queue::at(dir.path().join("queue"));
10072 let questions = Questions::at(dir.path().join("questions"));
10073 let home = dir.path().join("home");
10074 let mut state = run_state(RunStatus::Blocked);
10075 state.id = "20260101-000000-act3".to_owned();
10076 state.save_under(&home).unwrap();
10077 let mut t = held_task_with(&state.id);
10078 queue.put(&mut t).unwrap();
10079 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
10080 questions.put(&mut q).unwrap();
10081
10082 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
10083 apply_choice_actions(&queue, &questions, &home);
10084 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10085
10086 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10087 apply_choice_actions(&queue, &questions, &home);
10088 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10089 }
10090
10091 #[test]
10092 fn action_standing_tells_the_reasons_apart() {
10093 let mut t = held_task_with("r1");
10094 let q = action_question("r1", ask::ChoiceAction::Requeue);
10095 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10096 let mut plain = q.clone();
10097 plain.actions.clear();
10098 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
10099
10100 t.mark_action_applied(&q.id);
10102 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
10103
10104 let mut t = held_task_with("r1");
10106 t.start("r2".to_owned());
10107 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
10108 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
10110 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10111 t.status = TaskStatus::Blocked;
10112 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10113
10114 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
10116 c.node = crate::conduct::NODE.to_owned();
10117 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
10118 assert!(!ActionStanding::Busy.daemon_owns());
10119 }
10120
10121 #[test]
10122 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
10123 let dir = tempfile::tempdir().unwrap();
10124 let queue = Queue::at(dir.path().join("queue"));
10125 let questions = Questions::at(dir.path().join("questions"));
10126 let home = dir.path().join("home");
10127 let mut state = run_state(RunStatus::Blocked);
10128 state.id = "20260101-000000-act4".to_owned();
10129 state.save_under(&home).unwrap();
10130 let mut t = held_task_with(&state.id);
10131 t.status = TaskStatus::Running;
10132 queue.put(&mut t).unwrap();
10133 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
10134 q.cwd = Some(dir.path().display().to_string());
10135 questions.put(&mut q).unwrap();
10136
10137 let running = queue.get(&t.id).unwrap();
10140 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
10141 assert!(matches!(
10142 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
10143 crate::waiter::Action::Deliver(_)
10144 ));
10145 apply_choice_actions(&queue, &questions, &home);
10147 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10148 let mut back = queue.get(&t.id).unwrap();
10149 back.hold_machine(Some("later".into()));
10150 queue.put(&mut back).unwrap();
10151 apply_choice_actions(&queue, &questions, &home);
10152 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
10153 let mut again = queue.get(&t.id).unwrap();
10154 again.hold_machine(Some("again".into()));
10155 queue.put(&mut again).unwrap();
10156 apply_choice_actions(&queue, &questions, &home);
10157 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10158 }
10159}