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 #[serde(default)]
157 pub question_recovery: Option<crate::question_delivery::Recovery>,
158}
159
160impl Status {
161 #[must_use]
163 pub fn new() -> Self {
164 let now = Timestamp::now();
165 Self {
166 schema: SCHEMA,
167 pid: std::process::id(),
168 started_at: now,
169 updated_at: now,
170 idle: true,
171 current: Vec::new(),
172 completed: 0,
173 polls: 0,
174 question_recovery: None,
175 }
176 }
177}
178
179impl Default for Status {
180 fn default() -> Self {
181 Self::new()
182 }
183}
184
185#[derive(Debug, Clone)]
187pub struct Opts {
188 pub repo: PathBuf,
190 pub config: Option<PathBuf>,
192 pub poll: Duration,
194 pub max_attempts: usize,
196 pub once: bool,
198 pub merge: Option<String>,
200 pub worktrees_root: Option<PathBuf>,
209}
210
211impl Default for Opts {
212 fn default() -> Self {
213 Self {
214 repo: PathBuf::from("."),
215 config: None,
216 poll: POLL,
217 max_attempts: 2,
218 once: false,
219 merge: None,
220 worktrees_root: None,
221 }
222 }
223}
224
225fn max_concurrent(n: usize) -> usize {
230 n.max(1)
231}
232
233#[must_use]
235pub fn status_path() -> PathBuf {
236 crate::run::home().join("daemon.json")
237}
238
239pub fn write_status(status: &Status) -> Result<()> {
241 write_status_to(&status_path(), status)
242}
243
244pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
249 if let Some(parent) = path.parent() {
250 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
251 }
252 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
253 let tmp = path.with_extension("json.tmp");
254 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
255 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
256 Ok(())
257}
258
259pub fn clear_status() {
262 clear_status_at(&status_path());
263}
264
265fn clear_status_at(path: &Path) {
269 let _ = std::fs::remove_file(path);
270}
271
272#[derive(Debug, Clone, Default)]
285pub struct Stop {
286 stopped: Arc<AtomicBool>,
290 busy: Arc<std::sync::atomic::AtomicUsize>,
296 wake: Arc<Notify>,
300 pause: crate::graph::Pause,
303}
304
305impl Stop {
306 #[must_use]
308 pub fn new() -> Self {
309 Self::default()
310 }
311
312 pub fn stop(&self) {
315 self.stopped.store(true, Ordering::SeqCst);
316 self.wake.notify_one();
320 }
321
322 #[must_use]
324 pub fn stopped(&self) -> bool {
325 self.stopped.load(Ordering::SeqCst)
326 }
327
328 #[must_use]
336 pub fn finishing(&self) -> bool {
337 self.stopped() && self.busy_now()
338 }
339
340 pub fn park(&self, cause: crate::run::ParkCause) {
351 self.pause.park_for(cause);
352 self.stop();
353 }
354
355 #[must_use]
357 pub fn parking(&self) -> bool {
358 self.pause.parked()
359 }
360
361 #[must_use]
363 pub fn pause(&self) -> crate::graph::Pause {
364 self.pause.clone()
365 }
366
367 #[must_use]
373 pub fn busy_now(&self) -> bool {
374 self.busy.load(Ordering::SeqCst) > 0
375 }
376
377 fn enter(&self) {
379 self.busy.fetch_add(1, Ordering::SeqCst);
380 }
381
382 fn exit(&self) {
385 self.busy.fetch_sub(1, Ordering::SeqCst);
386 }
387
388 async fn idle(&self, poll: Duration) {
390 tokio::select! {
391 () = tokio::time::sleep(poll) => {}
392 () = self.wake.notified() => {}
393 }
394 }
395}
396
397#[derive(Debug, Clone, Default, Deserialize)]
404#[serde(default)]
405pub struct Reading {
406 pub schema: u32,
408 pub pid: Option<u32>,
410 pub started_at: Option<Timestamp>,
412 pub updated_at: Option<Timestamp>,
414 pub idle: bool,
416 #[serde(deserialize_with = "de_current")]
428 pub current: Vec<Current>,
429 pub completed: u64,
431 pub polls: u64,
433 #[serde(default)]
435 pub question_recovery: Option<crate::question_delivery::Recovery>,
436}
437
438fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
441where
442 D: serde::Deserializer<'de>,
443{
444 #[derive(Deserialize)]
445 #[serde(untagged)]
446 enum Shape {
447 Many(Vec<Current>),
448 One(Current),
449 }
450 Ok(
451 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
452 Shape::Many(v) => v,
453 Shape::One(c) => vec![c],
454 }),
455 )
456}
457
458impl Reading {
459 #[must_use]
462 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
463 self.updated_at
464 .map(|at| (now.as_second() - at.as_second()).max(0))
465 }
466
467 #[must_use]
471 pub fn running(&self, now: Timestamp) -> bool {
472 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
473 }
474}
475
476#[must_use]
483pub fn read_status(home: &Path) -> Option<Reading> {
484 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
485 serde_json::from_str(&body).ok()
486}
487
488#[must_use]
500pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
501 read_status(home)
502 .filter(|reading| reading.running(now))
503 .map(|reading| reading.current)
504 .unwrap_or_default()
505}
506
507#[must_use]
509pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
510 current_work(home, now).iter().any(|c| c.run == run)
511}
512
513#[must_use]
523pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
524 current_work(home, now)
525 .iter()
526 .any(|c| crate::run::short_of(&c.run) == short)
527}
528
529#[must_use]
531pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
532 current_work(home, now).iter().any(|c| c.task == task)
533}
534
535pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
579 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
580}
581
582fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
586where
587 F: Fn(u32) -> bool,
588{
589 let this_process = std::process::id();
590 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
591 .into_iter()
592 .flatten()
593 .flatten()
594 .map(|e| e.path())
595 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
596 .filter(|p| {
597 match std::fs::read_to_string(p)
598 .ok()
599 .and_then(|body| body.trim().parse::<u32>().ok())
600 {
601 Some(pid) if pid == this_process => false,
605 Some(pid) => !pid_alive(pid),
606 None => p
607 .metadata()
608 .and_then(|m| m.modified())
609 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
610 .is_ok_and(|age| age >= older_than),
611 }
612 })
613 .filter(|p| std::fs::remove_file(p).is_ok())
614 .filter_map(|p| {
615 p.file_stem()
616 .and_then(|s| s.to_str())
617 .map(std::borrow::ToOwned::to_owned)
618 })
619 .collect();
620 swept.sort_unstable();
621 swept
622}
623
624fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
629 task.status == TaskStatus::Running
630 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
631 && !is_working_on_task(home, &task.id, now)
632}
633
634fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
637 queue
638 .list()
639 .into_iter()
640 .filter(|t| is_stalled(t, home, now))
641 .collect()
642}
643
644fn queued_tasks(queue: &Queue) -> Vec<Task> {
650 queue
651 .list()
652 .into_iter()
653 .filter(|t| t.status == TaskStatus::Queued)
654 .collect()
655}
656
657fn finished_tasks(queue: &Queue) -> Vec<Task> {
660 queue
661 .list()
662 .into_iter()
663 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
664 .collect()
665}
666
667fn resolve_blockers(queue: &Queue, questions: &Questions) {
684 for listed in queue.list() {
685 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
686 continue;
687 }
688 let Ok(_claim) = queue.claim(&listed.id) else {
689 continue;
690 };
691 let Ok(mut task) = queue.get(&listed.id) else {
692 continue;
693 };
694 if task.status != TaskStatus::Blocked {
695 continue;
696 }
697 let deleted = queue.apply_deleted_blockers(&mut task, questions);
701 if !deleted.is_empty() {
702 record(queue, &mut task);
703 for id in &deleted {
704 queue.note_dependency_deleted(&task, id);
705 }
706 if task.status != TaskStatus::Blocked {
707 continue;
708 }
709 }
710 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
711 if !missing.is_empty() {
712 let language = language_of(&task, Path::new("."));
713 let mut cause = missing.clone();
714 cause.sort();
715 cause.dedup();
716 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
717 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
718 &task.blocked_by,
719 &missing,
720 &language,
721 )));
722 record(queue, &mut task);
723 continue;
724 }
725 if let Some(q) = task.blocked_by.iter().find_map(|id| {
728 let crate::queue::Dependency::Question(full) =
729 crate::queue::dependency(queue, questions, id)
730 else {
731 return None;
732 };
733 questions.get(&full).ok().filter(|q| {
734 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
735 })
736 }) {
737 let language = language_of(&task, Path::new("."));
738 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
739 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
740 record(queue, &mut task);
741 continue;
742 }
743 let mut changed = false;
744 for id in task.blocked_by.clone() {
745 let resolved = crate::queue::dependency(queue, questions, &id);
746 if let crate::queue::Dependency::Task(full) = &resolved {
747 if queue
748 .get(full)
749 .is_ok_and(|dep| dep.status == TaskStatus::Done)
750 {
751 task.unblock(&id);
752 changed = true;
753 }
754 continue;
755 }
756 if let crate::queue::Dependency::Question(full) = resolved
757 && let Ok(q) = questions.get(&full)
758 && q.status == ask::QuestionStatus::Answered
759 {
760 if q.node == crate::conduct::NODE
764 && q.chosen_action().is_some()
765 && !task.action_applied(&q.id)
766 {
767 continue;
768 }
769 let answer = match &q.answer {
770 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
771 None => String::new(),
772 };
773 task.record_answer(q.summary.clone(), answer);
774 task.unblock(&id);
775 changed = true;
776 }
777 }
778 if changed {
779 record(queue, &mut task);
780 }
781 }
782}
783
784fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
786 if crate::lang::is_japanese(language) {
787 format!(
788 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
789 q.short(),
790 q.summary
791 )
792 } else {
793 format!(
794 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
795 q.short(),
796 q.summary
797 )
798 }
799}
800
801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
804pub(crate) enum ActionStanding {
805 NoAction,
807 Pending,
809 Applied,
812 Stale,
814 Busy,
816}
817
818impl ActionStanding {
819 pub(crate) fn daemon_owns(self) -> bool {
821 matches!(self, Self::Pending | Self::Applied | Self::Stale)
822 }
823}
824
825pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
829 if q.chosen_action().is_none() {
830 ActionStanding::NoAction
831 } else if task.action_applied(&q.id) {
832 ActionStanding::Applied
833 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
834 ActionStanding::Stale
835 } else if matches!(
836 task.status,
837 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
838 ) {
839 ActionStanding::Busy
840 } else {
841 ActionStanding::Pending
842 }
843}
844
845#[derive(Debug, Clone, PartialEq, Eq)]
847enum ActionDecision {
848 Skip,
850 Resume(String),
852 Requeue,
854 Hold,
856 Done,
858 Stale,
861 Refuse(String),
864}
865
866fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
874where
875 F: FnOnce(&str) -> Result<RunState>,
876{
877 let Some(action) = q.chosen_action() else {
878 return ActionDecision::Skip;
879 };
880 if task.action_applied(&q.id)
881 || matches!(
882 task.status,
883 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
884 )
885 {
886 return ActionDecision::Skip;
887 }
888 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891 return ActionDecision::Stale;
892 }
893 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
894 let stopping = q.node == land::APPROVAL_NODE
895 && q.resolution()
896 .as_deref()
897 .is_some_and(crate::merge_decision::stops);
898 let decision_at = if repair || stopping {
902 q.answered_at.unwrap_or(q.asked_at)
903 } else {
904 q.asked_at
905 };
906 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
907 return if repair || stopping {
908 ActionDecision::Refuse(format!(
909 "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
910 if repair { "repair" } else { "stop" },
911 q.id,
912 q.run,
913 task.id
914 ))
915 } else {
916 ActionDecision::Stale
917 };
918 }
919 match action {
920 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
921 ask::ChoiceAction::Hold => ActionDecision::Hold,
922 ask::ChoiceAction::Done => ActionDecision::Done,
923 ask::ChoiceAction::Resume { run } => {
924 if task.runs.last() != Some(run) {
925 return ActionDecision::Refuse((p.resume_not_latest)(
926 q.short(),
927 ask::short_id(run),
928 ));
929 }
930 match load(run) {
931 Ok(s) if stopping => {
932 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
933 || !s
934 .land_approval
935 .as_ref()
936 .is_some_and(|binding| binding.question == q.id)
937 {
938 ActionDecision::Stale
939 } else if s.liveness(false) == Liveness::Live {
940 ActionDecision::Skip
941 } else if s.status == RunStatus::Landing && !s.released() {
942 ActionDecision::Resume(run.clone())
943 } else {
944 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
945 }
946 }
947 Ok(s)
948 if q.node == land::APPROVAL_NODE
949 && q.resolution().as_deref() == Some(land::REPAIR) =>
950 {
951 if s.merge_repairs.iter().any(|r| r.question == q.id)
952 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
953 {
954 ActionDecision::Stale
957 } else if s.liveness(false) == Liveness::Live {
958 ActionDecision::Skip
959 } else if s.status != RunStatus::Landing
960 || s.released()
961 || s.reviews.is_empty()
962 || !implementers_match(task, &s)
963 || !s
964 .land_approval
965 .as_ref()
966 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
967 {
968 ActionDecision::Refuse(format!(
969 "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",
970 q.id, run, run
971 ))
972 } else {
973 ActionDecision::Resume(run.clone())
974 }
975 }
976 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
977 ActionDecision::Resume(run.clone())
978 }
979 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
980 q.short(),
981 ask::short_id(run),
982 )),
983 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
984 q.short(),
985 ask::short_id(run),
986 &format!("{e:#}"),
987 )),
988 }
989 }
990 }
991}
992
993struct Phrases {
1007 graph_stopped: fn(&str, &str) -> String,
1009 quorum_lost: &'static str,
1010 quota_took_out: &'static str,
1012 run_ended: &'static str,
1014 waiting_for_answer: &'static str,
1016 recovered_running: &'static str,
1017 no_run_to_recover: &'static str,
1018 could_not_start: &'static str,
1019 resume_not_latest: fn(&str, &str) -> String,
1020 resume_cannot_progress: fn(&str, &str) -> String,
1021 resume_unreadable: fn(&str, &str, &str) -> String,
1022 handover_refused: fn(&crate::handover::Refused) -> String,
1025 handover_hint: &'static str,
1027 reviewers_never_answered: fn(usize, usize) -> String,
1030}
1031
1032const PHRASES_EN: Phrases = Phrases {
1033 graph_stopped: |status, detail| {
1034 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1035 },
1036 quorum_lost: "the judging panel lost its quorum",
1037 quota_took_out: "; quota took out ",
1038 run_ended: "run ended ",
1039 waiting_for_answer: " - waiting for operator answer to question ",
1040 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1041 no_run_to_recover: "task was `running` with no live daemon and no readable \
1042 run to recover; held for a human to check what happened",
1043 could_not_start: "could not start the run: ",
1044 resume_not_latest: |q, run| {
1045 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1046 },
1047 resume_cannot_progress: |q, run| {
1048 format!("question {q} asked to resume run {run}, which cannot make progress")
1049 },
1050 resume_unreadable: |q, run, e| {
1051 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1052 },
1053 handover_refused: |r| r.to_string(),
1054 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1055 reviewers_never_answered: |missing, rounds| {
1056 format!(
1057 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1058 refusing to call it clean"
1059 )
1060 },
1061};
1062
1063const PHRASES_JA: Phrases = Phrases {
1064 graph_stopped: |status, detail| {
1065 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1066 },
1067 quorum_lost: "審査パネルが定足数を失いました",
1068 quota_took_out: "。クォータで脱落: ",
1069 run_ended: "run 終了: ",
1070 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1071 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1072 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1073 何が起きたか人が確認するため保留にしました",
1074 could_not_start: "run を開始できませんでした: ",
1075 resume_not_latest: |q, run| {
1076 format!(
1077 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1078 )
1079 },
1080 resume_cannot_progress: |q, run| {
1081 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1082 },
1083 resume_unreadable: |q, run, e| {
1084 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1085 },
1086 handover_refused: |r| {
1087 use crate::handover::Refused;
1088 match r {
1089 Refused::Foreign { branch, path, why } => format!(
1090 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1091 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1092 から、やり直してください(詳細: {why})"
1093 ),
1094 Refused::Unsafe { branch, path, why } => format!(
1095 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1096 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1097 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1098 ),
1099 Refused::ReleaseFailed { branch, path, run } => format!(
1100 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1101 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1102 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1103 ),
1104 }
1105 },
1106 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1107 reviewers_never_answered: |missing, rounds| {
1108 format!(
1109 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1110 クリーンとは認めません"
1111 )
1112 },
1113};
1114
1115fn phrases(language: &str) -> &'static Phrases {
1116 if crate::lang::is_japanese(language) {
1117 &PHRASES_JA
1118 } else {
1119 &PHRASES_EN
1120 }
1121}
1122
1123fn language_of(task: &Task, fallback: &Path) -> String {
1127 crate::lang::of_repo(&repo_for(task, fallback))
1128}
1129
1130pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1134 if q.node == crate::conduct::NODE {
1135 return tasks.iter().find(|t| t.id == q.run);
1136 }
1137 tasks.iter().find(|t| t.runs.contains(&q.run))
1138}
1139
1140pub(crate) fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1149 let tasks = queue.list();
1150 for q in questions.list() {
1151 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1153 continue;
1154 }
1155 if q.chosen_action().is_none() {
1156 continue;
1157 }
1158 let Some(listed) = task_of_question(&tasks, &q) else {
1159 if q.node == land::APPROVAL_NODE
1160 && q.resolution().as_deref().is_some_and(|choice| {
1161 choice == land::REPAIR || crate::merge_decision::stops(choice)
1162 })
1163 {
1164 notices::raise_in(
1165 home,
1166 Notice::warn(
1167 &format!("repair-owner:{}", q.id),
1168 format!(
1169 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1170 q.run, q.run
1171 ),
1172 ),
1173 );
1174 }
1175 continue;
1176 };
1177 if listed.action_applied(&q.id) {
1178 continue;
1179 }
1180 let Ok(_claim) = queue.claim(&listed.id) else {
1181 continue;
1182 };
1183 let Ok(mut task) = queue.get(&listed.id) else {
1184 continue;
1185 };
1186 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1189 let blockers: Vec<_> = task
1190 .blocked_by
1191 .iter()
1192 .filter(|id| {
1193 crate::queue::dependency(queue, questions, id)
1194 == crate::queue::Dependency::Question(q.id.clone())
1195 })
1196 .cloned()
1197 .collect();
1198 if !blockers.is_empty() {
1199 for id in blockers {
1200 task.unblock(&id);
1201 }
1202 let answer = match &q.answer {
1203 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1204 None => String::new(),
1205 };
1206 task.record_answer(q.summary.clone(), answer);
1207 }
1208 }
1209 let language = language_of(&task, Path::new("."));
1210 let decision = decide_action(&task, &q, phrases(&language), |id| {
1211 RunState::load_under(id, home)
1212 });
1213 let ran = matches!(
1214 decision,
1215 ActionDecision::Resume(_)
1216 | ActionDecision::Requeue
1217 | ActionDecision::Hold
1218 | ActionDecision::Done
1219 );
1220 if ran && asker_may_still_read(questions, &q, home) {
1221 continue;
1230 }
1231 let done = matches!(decision, ActionDecision::Done);
1232 match decision {
1233 ActionDecision::Skip => continue,
1234 ActionDecision::Resume(run) => {
1235 task.release_operator("choice", Some(&q.id));
1236 task.resume_override = Some(crate::queue::OperatorResume {
1237 question_id: q.id.clone(),
1238 at: Timestamp::now(),
1239 conductor_rehold: None,
1240 forced: true,
1241 pinned_run: Some(run),
1242 });
1243 }
1244 ActionDecision::Stale => {}
1245 ActionDecision::Requeue => {
1246 task.release_operator("choice-requeue", Some(&q.id));
1247 task.requeue();
1248 }
1249 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1250 ActionDecision::Done => task.succeed(),
1251 ActionDecision::Refuse(why) => {
1252 if task.operator_held() {
1253 task.hold_reason = Some(match task.hold_reason.take() {
1256 Some(reason) => format!("{reason}\n\n{why}"),
1257 None => why,
1258 });
1259 } else {
1260 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1261 task.hold_machine(Some(why));
1262 }
1263 notices::raise(
1264 Notice::warn(
1265 &format!("action:{}", q.id),
1266 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1267 )
1268 .link(Link::Task {
1269 id: task.id.clone(),
1270 }),
1271 );
1272 }
1273 }
1274 task.mark_action_applied(&q.id);
1275 record(queue, &mut task);
1278 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1279 supersede_prior_runs(&task, home);
1280 }
1281 let _ = questions.update(&q.id, |r| {
1284 r.answer_delivered = true;
1285 Ok(())
1286 });
1287 }
1288}
1289
1290fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1294 let now = Timestamp::now();
1295 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1296 return true;
1297 }
1298 q.node != crate::conduct::NODE
1299 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1300 s.seats_active()
1301 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1302 })
1303}
1304
1305fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1316 let tasks = queue.list();
1317 let by_id: std::collections::BTreeMap<&str, &Task> =
1318 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1319 let referenced: Vec<&str> = tasks
1320 .iter()
1321 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1322 .collect();
1323
1324 for mut question in questions.list() {
1325 if !question.status.open() || question.node != crate::conduct::NODE {
1326 continue;
1327 }
1328 if referenced
1333 .iter()
1334 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1335 {
1336 continue;
1337 }
1338 let Some(task) = by_id.get(question.run.as_str()) else {
1339 continue;
1340 };
1341 question.abandon(format!(
1342 "task {} no longer waits for this answer",
1343 task.short()
1344 ));
1345 if let Err(e) = questions.put(&mut question) {
1346 tracing::warn!(
1347 "could not retire question {} for task {}: {e:#}",
1348 question.short(),
1349 task.short()
1350 );
1351 }
1352 }
1353}
1354
1355#[derive(Debug, Clone, Copy)]
1362pub struct Verdict {
1363 pub status: RunStatus,
1365 pub left_pr: bool,
1367 pub quota_hit: bool,
1369 pub parked: bool,
1371 pub no_viable_candidates: bool,
1378}
1379
1380pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1437 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1438}
1439
1440fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1442 if verdict.parked {
1448 task.park(detail);
1449 return;
1450 }
1451 match verdict.status {
1452 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1453 RunStatus::AlreadyInBase => task.already_landed(detail),
1454 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1455 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1456 task.stall(detail)
1457 }
1458 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1459 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1460 RunStatus::Blocked => task.fail(detail, max_attempts),
1461 RunStatus::VerifiedNoop => task.handed_off(detail),
1462 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1463 }
1464}
1465
1466pub fn supersede_prior_runs(task: &Task, home: &Path) {
1515 let now = Timestamp::now();
1516 let last_run_succeeded = task
1523 .runs
1524 .last()
1525 .and_then(|id| RunState::load_under(id, home).ok())
1526 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1527 for id in task.superseded_attempts(last_run_succeeded) {
1528 let mut state = match RunState::load_under(id, home) {
1529 Ok(s) => s,
1530 Err(e) => {
1531 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1532 continue;
1533 }
1534 };
1535 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1536 continue;
1537 }
1538 let daemon_claims = is_working_on(home, id, now);
1539 if state.liveness(daemon_claims) == Liveness::Live {
1540 continue;
1541 }
1542 state.status = RunStatus::Superseded;
1543 if let Err(e) = state.save_under(home) {
1544 tracing::warn!("could not mark run {id} superseded: {e:#}");
1545 }
1546 }
1547}
1548
1549fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1571 for task in queue.list() {
1572 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1573 continue;
1574 }
1575 supersede_prior_runs(&task, home);
1576 }
1577}
1578
1579fn settle_and_diagnose(
1586 task: &mut Task,
1587 verdict: Verdict,
1588 detail: &str,
1589 max_attempts: usize,
1590 state: &RunState,
1591) {
1592 let p = phrases(&state.config.graph.language);
1593 if let Some(d) = &state.merge_decision {
1596 use crate::merge_decision as md;
1597 if task.runs.last().is_some_and(|id| id != &state.id) {
1598 return;
1599 }
1600 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1601 task.succeed();
1602 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1603 if state.liveness(false) != Liveness::Dead {
1604 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1605 return;
1606 }
1607 let replacement = md::Replacement {
1608 question: d.question.clone(),
1609 run: state.id.clone(),
1610 pr: d.target.pr.clone(),
1611 agent: agent.to_owned(),
1612 context: format!(
1613 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1614 d.target.pr,
1615 state.id,
1616 serde_json::to_string(&state.reviews).unwrap_or_default()
1617 ),
1618 };
1619 task.requeue();
1620 task.pr_recovery = None;
1621 task.review_of = None;
1622 task.replacement = Some(replacement);
1623 } else {
1624 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1625 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1626 } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
1627 }
1628 task.mark_action_applied(&d.question);
1629 if let Some(pass) = state.passes.last() {
1630 task.record_pass(&state.id, pass.index, task.attempts, None);
1631 }
1632 return;
1633 }
1634 if let Some(replacement) = &task.replacement
1635 && !state.parked
1636 && state.resource_block.is_none()
1637 && (state.viable().is_empty()
1638 || (state.status == RunStatus::Blocked && state.tally.is_none()))
1639 {
1640 task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
1641 return;
1642 }
1643 let attempts_before = task.attempts;
1644 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1650 task.notice_cause(
1651 &format!("resource:{}:{}", block.kind, block.node),
1652 None,
1653 None,
1654 );
1655 task.last_error = Some(detail.to_owned());
1656 task.diagnostic = None;
1657 task.attempts = task.attempts.saturating_sub(1);
1658 task.hold_machine(Some(format!(
1659 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1660 no agent was asked and no attempt was spent",
1661 crate::cache::RESOURCE_HOLD,
1662 block.kind,
1663 block.node
1664 )));
1665 if let Some(pass) = state.passes.last() {
1666 task.record_pass(&state.id, pass.index, attempts_before, None);
1667 }
1668 return;
1669 }
1670 let unresolved = task.hold_notice_cause.clone();
1671 settle_in(task, verdict, detail, max_attempts, p);
1672 if state.prep_failure.is_some() {
1673 task.hold_notice_cause = unresolved;
1676 task.startup_notice_cause("startup-candidates");
1677 }
1678 if let Some(pass) = state.passes.last() {
1681 let parked = match &pass.end {
1682 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1683 _ => None,
1684 };
1685 task.record_pass(&state.id, pass.index, attempts_before, parked);
1686 }
1687 if task.status == TaskStatus::Held {
1688 if state.prep_failure.is_none() {
1689 task.notice_cause(
1690 label(verdict.status),
1691 Some(&state.id),
1692 state.passes.last().map(|p| p.index),
1693 );
1694 }
1695 task.diagnostic = diagnostic(state);
1696 note_open_question(task, &state.id, p);
1697 }
1698}
1699
1700fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1715 let Some(home) = crate::run::try_home() else {
1716 return;
1717 };
1718 let open = Questions::at(home.join("questions")).open_for(run);
1719 let Some(q) = open.first() else {
1720 return;
1721 };
1722 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
1723 decisions.sort_unstable();
1724 task.notice_cause(
1725 &format!("questions:{}", decisions.join(",")),
1726 Some(run),
1727 None,
1728 );
1729 let base = task.hold_reason.clone().unwrap_or_default();
1730 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1731}
1732
1733fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1744 match last_run {
1745 Some(state) => {
1746 let verdict = Verdict {
1747 status: state.status,
1748 left_pr: state.pr.is_some(),
1749 quota_hit: !state.quota.is_empty(),
1750 parked: state.parked,
1751 no_viable_candidates: state.viable().is_empty(),
1752 };
1753 let detail = format!(
1754 "{}{}",
1755 phrases(&state.config.graph.language).recovered_running,
1756 describe(&state)
1757 );
1758 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1759 }
1760 None => {
1761 let why = phrases(language).no_run_to_recover;
1764 task.last_error = Some(why.to_owned());
1765 task.notice_cause("missing-run", None, None);
1768 task.hold_machine(Some(why.to_owned()));
1769 }
1770 }
1771}
1772
1773fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1795 let mut reclaimed = Vec::new();
1796 for listed in queue.list() {
1797 if listed.status != TaskStatus::Running {
1798 continue;
1799 }
1800 let Ok(_claim) = queue.claim(&listed.id) else {
1801 continue;
1802 };
1803 let Ok(mut task) = queue.get(&listed.id) else {
1807 continue;
1808 };
1809 if task.status != TaskStatus::Running {
1810 continue;
1811 }
1812 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1813 if let Some(state) = &last_run
1823 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1824 {
1825 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1826 }
1827 let language = if last_run.is_none() {
1828 language_of(&task, Path::new("."))
1829 } else {
1830 String::new()
1831 };
1832 reclaim(&mut task, last_run, max_attempts, &language);
1833 if task.status == TaskStatus::Done {
1834 supersede_prior_runs(&task, &crate::run::home());
1835 }
1836 record(queue, &mut task);
1837 reclaimed.push(task.id.clone());
1838 }
1839 reclaimed
1840}
1841
1842fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1874 reclaim_abandoned_runs_with(
1875 home,
1876 now,
1877 crate::proc::pid_status,
1878 crate::proc::process_started_at,
1879 )
1880}
1881
1882fn reclaim_abandoned_runs_with<F, G>(
1888 home: &Path,
1889 now: Timestamp,
1890 query: F,
1891 identity: G,
1892) -> Vec<String>
1893where
1894 F: Fn(u32) -> Option<bool>,
1895 G: Fn(u32) -> Option<String>,
1896{
1897 let mut abandoned = Vec::new();
1898 for entry in std::fs::read_dir(home.join("runs"))
1899 .into_iter()
1900 .flatten()
1901 .flatten()
1902 {
1903 let id = entry.file_name().to_string_lossy().into_owned();
1904 if !crate::run::is_run_id(&id) {
1905 continue;
1906 }
1907 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
1910 continue;
1911 };
1912 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1920 continue;
1921 };
1922 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1923 continue;
1924 };
1925 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
1926 continue;
1927 }
1928 let daemon_claims = is_working_on(home, &id, now);
1940 if state.liveness_under_with(home, daemon_claims, &query, &identity)
1941 != crate::run::Liveness::Dead
1942 {
1943 continue;
1944 }
1945 state.abandon("daemon");
1946 if let Err(e) = state.save_under(home) {
1947 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1948 continue;
1949 }
1950 if let Some(notice) = notices::run_ended(&state) {
1953 notices::raise_in(home, notice);
1954 }
1955 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1963 tracing::warn!("abandon questions for {id}: {e:#}");
1964 }
1965 abandoned.push(id);
1966 }
1967 abandoned
1968}
1969
1970pub async fn serve(opts: Opts) -> Result<()> {
1976 serve_until(opts, Stop::new()).await
1977}
1978
1979pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1996 let signal = {
1997 let stop = stop.clone();
1998 tokio::spawn(async move {
1999 if tokio::signal::ctrl_c().await.is_ok() {
2000 stop.stop();
2001 tracing::info!("shutdown requested; a run in flight will be finished first");
2002 }
2003 })
2004 };
2005
2006 let worktrees_root = opts
2007 .worktrees_root
2008 .clone()
2009 .unwrap_or_else(crate::run::default_worktree_root);
2010 let outcome = drive(
2011 &opts,
2012 &Queue::open(),
2013 &status_path(),
2014 &crate::run::home(),
2015 &worktrees_root,
2016 &stop,
2017 )
2018 .await;
2019
2020 signal.abort();
2021 outcome
2022}
2023
2024async fn drive(
2037 opts: &Opts,
2038 queue: &Queue,
2039 status_file: &Path,
2040 home: &Path,
2041 worktrees_root: &Path,
2042 stop: &Stop,
2043) -> Result<()> {
2044 let recovery_cfg = prepare(&opts.repo, opts).ok();
2052 let daemon_cfg = recovery_cfg
2053 .as_ref()
2054 .map(|c| c.daemon.clone())
2055 .unwrap_or_default();
2056 let reconciled = crate::driver::reconcile(home);
2057 if !reconciled.is_empty() {
2058 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2059 }
2060 let mut initial_status = Status::new();
2061 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2062 recovery_cfg.as_ref(),
2063 daemon_cfg.max_deputies,
2064 ));
2065 let status = Arc::new(Mutex::new(initial_status));
2066 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2067 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2068
2069 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2075
2076 let waiter = tokio::spawn(crate::waiter::run(
2081 crate::waiter::Waiter::new(
2082 crate::ask::Questions::at(home.join("questions")),
2083 home.to_path_buf(),
2084 recovery_cfg.clone(),
2085 ),
2086 stop.clone(),
2087 ));
2088
2089 let deputies = tokio::spawn(crate::deputy::run(
2093 crate::deputy::Deputies::new(
2094 crate::ask::Questions::at(home.join("questions")),
2095 home.to_path_buf(),
2096 recovery_cfg.clone(),
2097 opts.repo.clone(),
2098 daemon_cfg.max_deputies,
2099 {
2100 let stop = stop.clone();
2101 Arc::new(move || stop.parking())
2102 },
2103 ),
2104 stop.clone(),
2105 ));
2106
2107 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2110
2111 let release_watch = tokio::spawn(crate::release_watch::run(
2114 crate::release_watch::Watcher::new(
2115 Box::new(crate::release_watch::GhForge),
2116 home.to_path_buf(),
2117 ),
2118 {
2119 let (repo, opts) = (opts.repo.clone(), opts.clone());
2120 move || release_watch_settings(&repo, &opts)
2121 },
2122 stop.clone(),
2123 ));
2124
2125 tracing::info!(
2126 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2127 queue.root().display(),
2128 opts.poll.as_secs(),
2129 opts.max_attempts,
2130 concurrency,
2131 if daemon_cfg.pause_for_interrupts {
2132 ", interrupts enabled"
2133 } else {
2134 ""
2135 }
2136 );
2137
2138 janitor(&opts.repo, opts, home, worktrees_root).await;
2141 resweep_superseded_attempts(queue, home);
2142
2143 let outcome = poll(
2144 opts,
2145 queue,
2146 &status,
2147 home,
2148 worktrees_root,
2149 stop,
2150 DispatchLimits {
2151 max_concurrent: concurrency,
2152 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2153 },
2154 )
2155 .await;
2156
2157 beat.abort();
2158 waiter.abort();
2159 deputies.abort();
2160 fetcher.abort();
2161 release_watch.abort();
2162 clear_status_at(status_file);
2163 outcome
2164}
2165
2166fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2169 let Ok(cfg) = prepare(repo, opts) else {
2170 return (Vec::new(), 0);
2171 };
2172 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2173 .into_iter()
2174 .map(|r| r.path)
2175 .collect();
2176 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2179 let runs = crate::run::home().join("runs");
2180 for id in crate::run::list_ids_in(&runs) {
2181 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2182 .ok()
2183 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2184 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2185 known.extend(repo);
2186 }
2187 for k in known {
2188 let k = k.canonicalize().unwrap_or(k);
2189 if k.join(".git").exists() && !paths.contains(&k) {
2190 paths.push(k);
2191 }
2192 }
2193 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2194 if !paths.contains(&own) {
2195 paths.push(own);
2196 }
2197 (paths, cfg.daemon.release_stall_minutes)
2198}
2199
2200const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2202
2203async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2207 while !stop.stopped() {
2208 let (interval, roots) = match prepare(&repo, &opts) {
2209 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2210 Err(_) => (0, Vec::new()),
2211 };
2212 if interval > 0 && !roots.is_empty() {
2213 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2214 tracing::debug!("fetch origins: {r:?}");
2215 }
2216 let wait = if interval > 0 { interval } else { 60 };
2218 let mut slept = 0;
2219 while slept < wait && !stop.stopped() {
2220 tokio::time::sleep(Duration::from_secs(1)).await;
2221 slept += 1;
2222 }
2223 }
2224}
2225
2226async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2232 loop {
2233 tokio::time::sleep(HEARTBEAT).await;
2234 let snapshot = {
2235 let mut guard = lock(&status);
2236 guard.updated_at = Timestamp::now();
2237 guard.clone()
2238 };
2239 if let Err(e) = write_status_to(&path, &snapshot) {
2240 tracing::warn!("could not refresh the daemon status file: {e:#}");
2243 }
2244 }
2245}
2246
2247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2250enum LandResume {
2251 NotLanding,
2254 StillWaiting,
2259 Ready,
2263}
2264
2265fn land_resume_state(task: &Task) -> LandResume {
2269 let Some(run_id) = task.runs.last() else {
2270 return LandResume::NotLanding;
2271 };
2272 let Ok(state) = RunState::load(run_id) else {
2273 return LandResume::NotLanding;
2274 };
2275 if !state.parked {
2276 return LandResume::NotLanding;
2277 }
2278 if state.status == RunStatus::Landing
2279 && state.land_approval.as_ref().is_some_and(|binding| {
2280 ask::Questions::open()
2281 .get(&binding.question)
2282 .is_ok_and(|q| {
2283 q.run == state.id
2284 && q.resolution()
2285 .as_deref()
2286 .is_some_and(crate::merge_decision::stops)
2287 })
2288 })
2289 {
2290 return LandResume::Ready;
2291 }
2292 if !implementers_match(task, &state) {
2293 return LandResume::NotLanding;
2294 }
2295 let node = if state.status == RunStatus::Landing {
2299 land::APPROVAL_NODE
2300 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2301 crate::github_text::ASK_NODE
2302 } else {
2303 return LandResume::NotLanding;
2304 };
2305 let store = ask::Questions::open();
2306 let waiting = store
2307 .list()
2308 .into_iter()
2309 .filter(|q| &q.run == run_id && q.node == node)
2310 .max_by(|a, b| a.id.cmp(&b.id));
2311 let Some(mut q) = waiting else {
2312 return LandResume::Ready;
2313 };
2314 if !q.status.open() {
2315 if q.resolution().as_deref() == Some(land::REPAIR) {
2318 return if state.liveness(false) == Liveness::Live {
2319 LandResume::StillWaiting
2320 } else {
2321 LandResume::NotLanding
2322 };
2323 }
2324 return LandResume::Ready;
2325 }
2326 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2333 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2334 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2335 q.abandon(format!(
2336 "no answer within {}s of asking",
2337 timeout.as_secs().max(1)
2338 ));
2339 if store.put(&mut q).is_ok() {
2342 return LandResume::Ready;
2343 }
2344 }
2345 LandResume::StillWaiting
2346}
2347
2348const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2356
2357const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2369
2370struct InFlightGuard<'a> {
2383 status: &'a Arc<Mutex<Status>>,
2384 stop: &'a Stop,
2385 task_id: &'a str,
2386}
2387
2388impl Drop for InFlightGuard<'_> {
2389 fn drop(&mut self) {
2390 lock(self.status).current.retain(|c| c.task != self.task_id);
2391 self.stop.exit();
2392 }
2393}
2394
2395#[derive(Debug, Clone, PartialEq, Eq)]
2417enum Interrupt {
2418 Idle,
2420 Parking {
2432 parked: Vec<String>,
2433 interrupt_task: String,
2434 },
2435 Running {
2443 parked: Vec<String>,
2444 interrupt_task: String,
2445 },
2446 Resuming { parked: Vec<String> },
2453}
2454
2455fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2476 match state {
2477 Interrupt::Idle => {
2478 if in_flight.len() != 1 {
2490 return Interrupt::Idle;
2491 }
2492 match runnable.iter().find(|t| t.interrupt) {
2493 Some(t) => Interrupt::Parking {
2494 parked: in_flight.to_vec(),
2495 interrupt_task: t.id.clone(),
2496 },
2497 None => Interrupt::Idle,
2498 }
2499 }
2500 Interrupt::Parking {
2501 parked,
2502 interrupt_task,
2503 } => {
2504 if in_flight.iter().any(|id| parked.contains(id)) {
2505 Interrupt::Parking {
2507 parked,
2508 interrupt_task,
2509 }
2510 } else if in_flight.contains(&interrupt_task) {
2511 Interrupt::Running {
2512 parked,
2513 interrupt_task,
2514 }
2515 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2516 Interrupt::Parking {
2520 parked,
2521 interrupt_task,
2522 }
2523 } else {
2524 Interrupt::Resuming { parked }
2529 }
2530 }
2531 Interrupt::Running {
2532 parked,
2533 interrupt_task,
2534 } => {
2535 if in_flight.contains(&interrupt_task) {
2536 Interrupt::Running {
2537 parked,
2538 interrupt_task,
2539 }
2540 } else {
2541 Interrupt::Resuming { parked }
2547 }
2548 }
2549 Interrupt::Resuming { parked } => {
2550 if in_flight.iter().any(|id| parked.contains(id)) {
2551 Interrupt::Idle
2557 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2558 Interrupt::Resuming { parked }
2559 } else {
2560 Interrupt::Idle
2563 }
2564 }
2565 }
2566}
2567
2568fn advance_interrupt_tick(
2574 enabled: bool,
2575 state: Interrupt,
2576 in_flight: &[String],
2577 runnable: &[Task],
2578) -> Interrupt {
2579 if !enabled {
2580 return Interrupt::Idle;
2581 }
2582 advance_interrupt(state, in_flight, runnable)
2583}
2584
2585fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2590 match state {
2591 Interrupt::Idle => candidates,
2592 Interrupt::Parking {
2593 parked,
2594 interrupt_task,
2595 } => {
2596 if in_flight.iter().any(|id| parked.contains(id)) {
2597 Vec::new()
2598 } else {
2599 candidates
2600 .into_iter()
2601 .filter(|t| &t.id == interrupt_task)
2602 .collect()
2603 }
2604 }
2605 Interrupt::Running { .. } => Vec::new(),
2606 Interrupt::Resuming { parked } => candidates
2614 .into_iter()
2615 .find(|t| parked.contains(&t.id))
2616 .into_iter()
2617 .collect(),
2618 }
2619}
2620
2621struct DispatchLimits {
2625 max_concurrent: usize,
2628 pause_for_interrupts: bool,
2630}
2631
2632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2641enum PermitKind {
2642 None,
2647 Urgent,
2654 Ordinary,
2657}
2658
2659fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2662 if priority {
2663 PermitKind::None
2664 } else if urgent {
2665 PermitKind::Urgent
2666 } else {
2667 PermitKind::Ordinary
2668 }
2669}
2670
2671struct DispatchClaim {
2672 task: Task,
2673 claim: crate::queue::Claim,
2674 permit: Option<tokio::sync::OwnedSemaphorePermit>,
2675}
2676
2677fn claim_dispatch(
2680 queue: &Queue,
2681 candidate: &Task,
2682 cooling_down: bool,
2683 ordinary: &Arc<tokio::sync::Semaphore>,
2684 urgent: &Arc<tokio::sync::Semaphore>,
2685) -> Option<DispatchClaim> {
2686 let Ok(claim) = queue.claim(&candidate.id) else {
2687 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2688 return None;
2689 };
2690 let task = match queue.get(&candidate.id) {
2691 Ok(t) if t.status.runnable() => t,
2692 Ok(_) => return None,
2693 Err(e) => {
2694 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2695 return None;
2696 }
2697 };
2698 let resume = land_resume_state(&task);
2699 if resume == LandResume::StillWaiting {
2700 return None;
2701 }
2702 let priority = resume == LandResume::Ready;
2703 if !priority && cooling_down {
2704 return None;
2705 }
2706 let permit = match permit_kind(priority, task.urgent) {
2709 PermitKind::None => None,
2710 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
2711 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
2712 };
2713 Some(DispatchClaim {
2714 task,
2715 claim,
2716 permit,
2717 })
2718}
2719
2720async fn poll(
2739 opts: &Opts,
2740 queue: &Queue,
2741 status: &Arc<Mutex<Status>>,
2742 home: &Path,
2743 worktrees_root: &Path,
2744 stop: &Stop,
2745 limits: DispatchLimits,
2746) -> Result<()> {
2747 let DispatchLimits {
2748 max_concurrent,
2749 pause_for_interrupts,
2750 } = limits;
2751 let mut attempted: Vec<String> = Vec::new();
2756 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2757 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2765 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2771 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2772 let mut conductor = Conductor::new();
2773 let mut cache_last_checked: Option<Timestamp> = None;
2776 let mut interrupt = Interrupt::Idle;
2778 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2784 std::collections::HashMap::new();
2785
2786 while !stop.stopped() {
2787 lock(status).polls += 1;
2788
2789 while let Some(result) = inflight.try_join_next() {
2794 if let Err(e) = result {
2795 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2796 notices::raise(Notice::error(
2797 "loop:attempt",
2798 "A queued attempt ended abnormally; check the task it was running.",
2799 ));
2800 }
2801 }
2802
2803 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2804 if !swept.is_empty() {
2805 tracing::warn!(
2806 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2807 swept.len(),
2808 swept.join(", ")
2809 );
2810 }
2811 let now = Timestamp::now();
2816
2817 if !stop.busy_now() {
2822 maybe_prune_cache_between_runs(
2823 &opts.repo,
2824 opts,
2825 home,
2826 stop,
2827 &mut cache_last_checked,
2828 now,
2829 )
2830 .await;
2831 }
2832
2833 let stalled = stalled_tasks(queue, home, now);
2834 let stalled_ids: std::collections::BTreeSet<_> =
2835 stalled.iter().map(|task| task.id.clone()).collect();
2836 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2837 if !reclaimed.is_empty() {
2838 tracing::warn!(
2839 "reclaimed {} task(s) left `running` by a daemon that never \
2840 recorded the outcome: {}",
2841 reclaimed.len(),
2842 reclaimed.join(", ")
2843 );
2844 }
2845 let abandoned_runs = reclaim_abandoned_runs(home, now);
2846 if !abandoned_runs.is_empty() {
2847 tracing::warn!(
2848 "failed {} run(s) left behind by a killed process, past every \
2849 active seat's own timeout: {}",
2850 abandoned_runs.len(),
2851 abandoned_runs.join(", ")
2852 );
2853 }
2854
2855 let questions = Questions::at(home.join("questions"));
2860
2861 resolve_blockers(queue, &questions);
2864 apply_choice_actions(queue, &questions, home);
2865 triage::apply_answers(queue, &questions);
2866 reconcile_task_questions(queue, &questions);
2867 {
2871 let talks = crate::talk::Talks::at(home.join("talks"));
2872 crate::chat_notify::sweep(queue, &talks, home);
2873 crate::chat_watch::sweep(home, &talks);
2874 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2875 }
2876
2877 let finished: Vec<Task> = finished_tasks(queue)
2883 .into_iter()
2884 .filter(|task| !stalled_ids.contains(&task.id))
2885 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2889 .collect();
2890 let queued = queued_tasks(queue);
2891 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2895 && conductor.worth_a_look(queue, &stalled, &finished)
2896 {
2897 match prepare(&opts.repo, opts) {
2898 Ok(cfg) => {
2899 conductor
2900 .maybe_run(
2901 &cfg,
2902 &opts.repo,
2903 queue,
2904 &questions,
2905 home,
2906 &queued,
2907 &stalled,
2908 &finished,
2909 opts.max_attempts,
2910 )
2911 .await;
2912 }
2913 Err(e) => {
2914 tracing::warn!("conductor: no config: {e:#}");
2915 notices::raise(Notice::warn(
2916 "loop:no-config",
2917 "The loop could not read this repository's config, so held tasks are not being triaged.",
2918 ));
2919 }
2920 }
2921 }
2922
2923 let candidates: Vec<Task> = runnable(queue)
2924 .into_iter()
2925 .filter(|t| !opts.once || !attempted.contains(&t.id))
2926 .collect();
2927
2928 let in_flight: Vec<String> = lock(status)
2933 .current
2934 .iter()
2935 .map(|c| c.task.clone())
2936 .collect();
2937 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2938
2939 interrupt =
2940 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2941 if let Interrupt::Parking {
2942 parked,
2943 interrupt_task,
2944 } = &interrupt
2945 {
2946 let reason = format!(
2947 "task {} asked to run first",
2948 crate::run::short_of(interrupt_task)
2949 );
2950 for id in parked {
2951 if let Some(pause) = interrupt_pauses.get(id) {
2952 pause.park_because(reason.clone());
2953 }
2954 }
2955 }
2956 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2957
2958 let cooling_down =
2959 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2960
2961 let mut started_any = false;
2962 for candidate in candidates {
2963 if stop.stopped() {
2964 break;
2965 }
2966
2967 let Some(DispatchClaim {
2968 mut task,
2969 claim,
2970 permit,
2971 }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
2972 else {
2973 continue;
2974 };
2975
2976 let task_id = task.id.clone();
2977 attempted.push(task_id.clone());
2978 lock(status).idle = false;
2979 stop.enter();
2982 started_any = true;
2983
2984 let run_pause = crate::graph::Pause::new();
2988 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2989
2990 let opts = opts.clone();
2991 let queue = queue.clone();
2992 let status = Arc::clone(status);
2993 let stop = stop.clone();
2994 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2995 inflight.spawn(async move {
2996 let _claim = claim;
3000 let _permit = permit;
3001 let _inflight = InFlightGuard {
3003 status: &status,
3004 stop: &stop,
3005 task_id: &task_id,
3006 };
3007 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3008 lock(&status).completed += 1;
3009 let now = Timestamp::now();
3015 if let Some(until) = cooldown_until("a, now) {
3016 let wait = until.as_second() - now.as_second();
3017 *lock("a_cooldown_until) = Some(until);
3018 let hint = quota
3019 .iter()
3020 .find(|q| q.reset.is_some())
3021 .and_then(|q| q.reset.as_deref());
3022 match hint {
3023 Some(h) => tracing::warn!(
3024 "quota hit; waiting {wait}s before taking another ordinary task \
3025 (CLI reported reset: {h})"
3026 ),
3027 None => tracing::warn!(
3028 "quota hit; waiting {wait}s before taking another ordinary task \
3029 (no reset hint reported)"
3030 ),
3031 }
3032 }
3033 });
3034 }
3035
3036 if started_any {
3037 continue;
3038 }
3039
3040 if stop.busy_now() {
3041 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3046 continue;
3047 }
3048
3049 lock(status).idle = true;
3051 if opts.once {
3052 janitor(&opts.repo, opts, home, worktrees_root).await;
3056 resweep_superseded_attempts(queue, home);
3057 triage_held(queue, home, opts).await;
3058 break;
3059 }
3060 stop.idle(opts.poll).await;
3061 if stop.stopped() {
3062 continue;
3063 }
3064 janitor(&opts.repo, opts, home, worktrees_root).await;
3070 resweep_superseded_attempts(queue, home);
3071 triage_held(queue, home, opts).await;
3072 }
3073
3074 while let Some(result) = inflight.join_next().await {
3079 if let Err(e) = result {
3080 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3081 notices::raise(Notice::error(
3082 "loop:attempt",
3083 "A queued attempt ended abnormally; check the task it was running.",
3084 ));
3085 }
3086 }
3087 Ok(())
3088}
3089
3090async fn attempt(
3096 opts: &Opts,
3097 queue: &Queue,
3098 status: &Arc<Mutex<Status>>,
3099 stop: &Stop,
3100 interrupt_pause: crate::graph::Pause,
3101 task: &mut Task,
3102) -> Vec<QuotaLoss> {
3103 let repo = repo_for(task, &opts.repo);
3104 tracing::info!(
3105 "task {} — {} (repo {})",
3106 task.short(),
3107 task.title,
3108 repo.display()
3109 );
3110
3111 if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3115 && previous
3116 .merge_decision
3117 .as_ref()
3118 .is_some_and(|decision| !decision.closed)
3119 && previous.status != RunStatus::Landing
3120 && !crate::merge_decision::resumable_hold(&previous)
3121 {
3122 task.hold_unrequested_retry(Some(format!("The existing owner stop decision remains held. Inspect run {} and its PR; request an explicit fresh review/decision before further work. No replacement or merge was started.", previous.id)));
3123 record(queue, task);
3124 return Vec::new();
3125 }
3126 let stop_owner = task
3127 .runs
3128 .last()
3129 .and_then(|id| RunState::load(id).ok())
3130 .filter(|state| {
3131 crate::merge_decision::resumable_hold(state)
3132 || state.status == RunStatus::Landing
3133 && state.land_approval.as_ref().is_some_and(|binding| {
3134 Questions::open().get(&binding.question).is_ok_and(|q| {
3135 q.run == state.id
3136 && q.resolution()
3137 .as_deref()
3138 .is_some_and(crate::merge_decision::stops)
3139 })
3140 })
3141 });
3142 if let Some(owner) = stop_owner {
3143 let mut runner = match Runner::resume(&owner.id) {
3144 Ok(runner) => runner,
3145 Err(e) => {
3146 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3147 record(queue, task);
3148 return Vec::new();
3149 }
3150 };
3151 runner.on_pause(stop.pause());
3152 runner.watch_interrupt(interrupt_pause);
3153 let quota_before = runner.state.quota.clone();
3154 task.start(owner.id.clone());
3155 record(queue, task);
3156 lock(status).current.push(Current {
3157 task: task.id.clone(),
3158 run: owner.id,
3159 });
3160 runner.state.next_pass_task_entry = true;
3161 let result = runner.execute().await;
3162 return finish_attempt(
3163 opts.max_attempts,
3164 queue,
3165 task,
3166 &runner.state,
3167 "a_before,
3168 result,
3169 );
3170 }
3171
3172 let explicit = match &task.overrides {
3176 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3177 Some(_) => opts.config.as_deref(),
3178 None => opts.config.as_deref(),
3179 };
3180 if let Err(e) = Config::discover_fetched(&repo, explicit).await {
3181 let reason = format!("[config] {e:#}");
3182 record_config_failure(task, &e);
3183 task.last_error = Some(reason.clone());
3184 task.hold_machine(Some(reason.clone()));
3185 record(queue, task);
3186 tracing::warn!("holding {}: {reason}", task.short());
3187 return Vec::new();
3188 }
3189 let mut config = match prepare_for(&repo, opts, task) {
3190 Ok(c) => c,
3191 Err(e) => {
3192 task.attempts += 1;
3196 task.fail_startup(
3197 "startup-config",
3198 format!("config: {e:#}"),
3199 opts.max_attempts,
3200 );
3201 record(queue, task);
3202 return Vec::new();
3203 }
3204 };
3205 apply_task_implementers(&mut config, task);
3206 if let Some(replacement) = &task.replacement {
3207 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3208 old.liveness(false) == Liveness::Dead
3209 && old.merge_decision.as_ref().is_some_and(|d| {
3210 d.closed
3211 && d.question == replacement.question
3212 && d.replacement_run.as_ref().is_none_or(|run| {
3213 task.runs.last() == Some(run)
3214 && RunState::load(run).is_ok_and(|current| {
3215 current.replaces.as_ref().is_some_and(|pin| {
3216 pin.question == replacement.question
3217 && pin.agent == replacement.agent
3218 })
3219 })
3220 })
3221 })
3222 });
3223 if !safe {
3224 task.hold_manual(Some("Replacement ownership cannot be confirmed, or a replacement run was already minted before a crash. Inspect the task and its linked runs; no second replacement was started.".into()));
3225 record(queue, task);
3226 return Vec::new();
3227 }
3228 match config.agent(&replacement.agent) {
3229 Ok(agent) if crate::agent::installed(agent) => {}
3230 _ => {
3231 task.hold_manual(Some(format!("Selected implementer `{}` is unavailable or no longer configured. No substitute was dispatched. Restore it and explicitly release the task.", replacement.agent)));
3232 record(queue, task);
3233 return Vec::new();
3234 }
3235 }
3236 config.graph.implementers = 1;
3237 config.graph.land_approval = true;
3238 config.merge.mode = MergeMode::Pr;
3239 config.graph.selected_implementer = Some(replacement.agent.clone());
3240 }
3241 let p = phrases(&config.graph.language);
3242 let start_failed = p.could_not_start;
3243
3244 if let Some(reason) = disk_gate(&repo, &config) {
3252 task.notice_cause("disk-space", None, None);
3253 task.last_error = Some(reason.clone());
3254 task.hold_machine(Some(reason.clone()));
3255 record(queue, task);
3256 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3257 notices::raise(
3260 Notice::warn(
3261 &format!("disk:{}", repo.display()),
3262 "A task was held for want of free disk space; free some, then release it from the queue.",
3263 )
3264 .link(Link::Task {
3265 id: task.id.clone(),
3266 }),
3267 );
3268 return Vec::new();
3269 }
3270
3271 let unfinished = (!task.fresh_start)
3291 .then(|| unfinished_run(&task.runs, task.short()))
3292 .flatten()
3293 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3294 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3300 let review_branch = take_review_branch(task, previous.as_ref());
3301 let branch_exists = match &review_branch {
3302 Some(branch) => crate::git::branch_exists(&repo, branch)
3303 .await
3304 .unwrap_or(false),
3305 None => false,
3306 };
3307 let proposed = match (&review_branch, &unfinished, &task.review_of) {
3311 (None, None, Some(branch)) => Starter::Review(branch.clone()),
3312 _ => choose_starter(
3313 review_branch.as_deref(),
3314 branch_exists,
3315 unfinished.as_deref(),
3316 ),
3317 };
3318 let retry_selected = task.replacement.is_some()
3319 && task.resumption.is_some()
3320 && !task.fresh_start
3321 && previous.as_ref().is_some_and(|run| {
3322 run.replaces.is_some()
3323 && ((run.status == RunStatus::Failed && run.viable().is_empty())
3324 || (run.status == RunStatus::Blocked && run.tally.is_none()))
3325 });
3326 let stop_pin = task
3327 .resume_override
3328 .as_ref()
3329 .filter(|pin| {
3330 Questions::open().get(&pin.question_id).is_ok_and(|q| {
3331 q.node == land::APPROVAL_NODE
3332 && q.resolution()
3333 .as_deref()
3334 .is_some_and(crate::merge_decision::stops)
3335 })
3336 })
3337 .and_then(|pin| pin.pinned_run.clone());
3338 let starter = if let Some(run) = stop_pin {
3339 Starter::Resume(run)
3342 } else if retry_selected {
3343 Starter::Resume(previous.as_ref().unwrap().id.clone())
3344 } else if let Some(selected) = &task.pr_recovery {
3345 if selected.check_task(&task.id, &task.instruction).is_ok() {
3346 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3347 } else {
3348 Starter::Review(selected.branch.clone())
3349 }
3350 } else {
3351 starter_with_implementers(task, previous.as_ref(), proposed)
3352 };
3353 if let Some(pin) = &task.resume_override
3356 && let Some(run) = &pin.pinned_run
3357 && Questions::open().get(&pin.question_id).map_or(true, |q| {
3358 q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR)
3359 })
3360 && starter != Starter::Resume(run.clone())
3361 {
3362 let run = run.clone();
3363 task.notice_cause("repair-owner", Some(&run), None);
3364 task.hold_machine(Some(format!(
3365 "repair owner cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3366 task.id
3367 )));
3368 record(queue, task);
3369 return Vec::new();
3370 }
3371 if task.replacement.is_some()
3372 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3373 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3374 {
3375 task.hold_manual(Some("The selected replacement already has an attempt. It cannot be resumed safely; inspect its saved pin and restore the existing run. No additional replacement was started.".into()));
3376 record(queue, task);
3377 return Vec::new();
3378 }
3379 let attachments = match task_attachments(queue, task) {
3384 Ok(a) => a,
3385 Err(e) => {
3386 task.attempts += 1;
3387 task.fail_startup_target(
3388 "startup-attachments",
3389 e.name.clone(),
3390 format!("{start_failed}{e:#}"),
3391 opts.max_attempts,
3392 );
3393 record(queue, task);
3394 return Vec::new();
3395 }
3396 };
3397 let startup_pause = stop.pause();
3398 let startup_interrupt = interrupt_pause.clone();
3399 let wait = crate::repo_lock::WaitPolicy::new(
3400 Duration::from_secs(config.graph.timeout_resource_wait),
3401 move || startup_pause.parked() || startup_interrupt.parked(),
3402 );
3403 let started = wait.scope(async { match &starter {
3404 Starter::Review(_) if task.pr_recovery.is_some() => {
3405 let selected = task.pr_recovery.clone().expect("selected recovery");
3406 match selected.check_task(&task.id, &task.instruction) {
3407 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3408 .await
3409 .map(|mut r| {
3410 r.state.attachments = attachments.clone();
3411 r
3412 }),
3413 Err(e) => Err(e),
3414 }
3415 }
3416 Starter::Review(branch) => {
3417 tracing::info!(
3418 "task {} reopens `{branch}` as a review-only pass",
3419 task.short()
3420 );
3421 let takeover = crate::handover::Takeover {
3424 earlier: task.earlier_attempts().to_vec(),
3425 home: crate::run::home(),
3426 choice: take_divergence_answer(branch, &config.merge.remote, task),
3427 task_instruction: Some(instruction_for(task)),
3428 };
3429 Runner::review_taking_over(
3430 &repo,
3431 branch,
3432 config,
3433 Some(takeover),
3434 crate::run::Origin::queue(&task.id),
3435 )
3436 .await
3437 }
3438 Starter::Resume(id) => {
3439 tracing::info!("resuming run {id} rather than competing again");
3440 Runner::resume(id).and_then(|mut r| {
3441 if retry_selected {
3442 for candidate in &mut r.state.candidates {
3445 candidate.failed = None;
3446 candidate.empty = false;
3447 candidate.commits = 0;
3448 }
3449 r.state.status = RunStatus::Implementing;
3450 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3451 }
3452 if r.state.prep_failure.is_some() {
3453 let approval = task
3454 .resumption
3455 .as_ref()
3456 .context("preparation retry requires an explicit task release")?;
3457 r.retry_preparation(approval.at)?;
3458 }
3459 if let Some(instruction) =
3460 prepare_instruction(&starter, Some(&r.state.instruction), task)
3461 {
3462 r.state.instruction = instruction;
3463 }
3464 r.state.attachments = attachments.clone();
3465 if task.replacement.is_some() {
3466 r.state.config.merge.mode = MergeMode::Pr;
3467 r.state.config.graph.land_approval = true;
3468 }
3469 if task.replacement.is_none() && let Some(mode) = task
3472 .overrides
3473 .as_ref()
3474 .and_then(|o| o.merge.as_deref())
3475 .and_then(|m| merge_mode(m).ok())
3476 {
3477 r.state.config.merge.mode = mode;
3478 }
3479 Ok(r)
3480 })
3481 }
3482 Starter::Start => {
3483 if let Some(branch) = &review_branch {
3484 tracing::warn!(
3485 "conductor chose review for task {} but branch `{branch}` no longer \
3486 exists; requeuing as a fresh competition instead",
3487 task.short()
3488 );
3489 }
3490 let instruction = prepare_instruction(&starter, None, task)
3491 .unwrap_or_else(|| task.instruction.clone());
3492 Runner::start_naming(
3493 &repo,
3494 instruction,
3495 &task.title,
3496 config,
3497 crate::run::Origin::queue(&task.id),
3498 )
3499 .await
3500 .map(|mut r| {
3501 r.state.attachments = attachments.clone();
3502 r
3503 })
3504 }
3505 }}).await;
3506 let mut runner = match started {
3507 Ok(r) => r,
3508 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3509 task.last_error = Some(e.to_string());
3510 if stop.parking() || interrupt_pause.parked() {
3511 let attempts = task.attempts;
3512 task.park(e.to_string());
3513 task.attempts = attempts;
3515 } else {
3516 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3517 }
3518 record(queue, task);
3519 return Vec::new();
3520 }
3521 Err(e) if task.pr_recovery.is_some() => {
3525 task.startup_notice_cause("startup-public-head");
3526 task.attempts += 1;
3527 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3528 task.link_run(&partial.run);
3529 task.record_pass(&partial.run, 0, task.attempts, None);
3530 }
3531 task.last_error = Some(format!("{start_failed}{e:#}"));
3532 task.hold_unrequested_retry(Some(format!(
3533 "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."
3534 )));
3535 record(queue, task);
3536 return Vec::new();
3537 }
3538 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3539 let detail = match e.downcast_ref::<crate::handover::Refused>() {
3540 Some(r) => (p.handover_refused)(r),
3541 None => format!("{e:#}"),
3542 };
3543 task.startup_notice_cause("startup-handover");
3544 let reason = format!("{start_failed}{detail}");
3545 task.last_error = Some(reason.clone());
3546 let branch = match &starter {
3549 Starter::Review(branch) => Some(branch.clone()),
3550 _ => None,
3551 };
3552 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3556 record(queue, task);
3557 tracing::warn!(
3558 "holding {} for a branch it cannot take over: {e:#}",
3559 task.short()
3560 );
3561 return Vec::new();
3562 }
3563 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3568 let d = e
3569 .downcast_ref::<crate::reconcile::Diverged>()
3570 .expect("checked by the guard");
3571 let mut q = ask::Question::new(
3572 task.id.clone(),
3573 crate::reconcile::NODE.to_owned(),
3574 crate::reconcile::SEAT.to_owned(),
3575 d.summary(),
3576 d.detail(),
3577 d.choices(),
3578 );
3579 match Questions::open().put(&mut q) {
3580 Ok(()) => {
3581 task.last_error = Some(format!("{e:#}"));
3582 task.review_branch = Some(d.branch.clone());
3585 task.review_instruction = Some(task.instruction.clone());
3586 task.block(vec![q.id.clone()], Some(d.summary()));
3587 }
3588 Err(put) => {
3589 tracing::warn!("could not file the divergence question: {put:#}");
3590 task.attempts += 1;
3591 task.fail_startup(
3592 "startup-question-store",
3593 format!("{start_failed}{e:#}"),
3594 opts.max_attempts,
3595 );
3596 }
3597 }
3598 record(queue, task);
3599 return Vec::new();
3600 }
3601 Err(e) => {
3602 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3608 && let Starter::Review(branch) = &starter
3609 {
3610 task.review_branch = Some(branch.clone());
3611 task.review_instruction = Some(task.instruction.clone());
3612 task.last_error = Some(format!("{start_failed}{e:#}"));
3613 task.status = crate::queue::TaskStatus::Failed;
3614 record(queue, task);
3615 return Vec::new();
3616 }
3617 task.attempts += 1;
3618 task.last_error = Some(format!("{start_failed}{e:#}"));
3619 task.startup_notice_cause("startup-source");
3620 task.hold_unrequested_retry(Some(format!(
3621 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3622 )));
3623 record(queue, task);
3624 return Vec::new();
3625 }
3626 };
3627 if let Some(replacement) = &task.replacement {
3628 if matches!(starter, Starter::Start) {
3629 runner.state.instruction.push_str(&format!(
3630 "\n\n# Replacement review context\n{}",
3631 replacement.context
3632 ));
3633 }
3634 runner.state.replaces = Some(replacement.clone());
3635 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
3636 if let Ok(mut old) = RunState::load(&replacement.run)
3637 && let Some(d) = &mut old.merge_decision
3638 {
3639 d.replacement_run = Some(runner.state.id.clone());
3640 old.event(
3641 "replacement",
3642 format!(
3643 "replacement run {} owns the next attempt; old PR remains closed",
3644 runner.state.id
3645 ),
3646 );
3647 if let Err(e) = old.save() {
3648 task.hold_manual(Some(format!(
3649 "Could not link replacement history: {e}; no agents dispatched"
3650 )));
3651 record(queue, task);
3652 return Vec::new();
3653 }
3654 }
3655 }
3656 runner.state.task_instruction = Some(task.instruction.clone());
3657 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3660 if runner.state.origin_chat.is_none() {
3661 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3662 }
3663 runner.on_pause(stop.pause());
3665 runner.watch_interrupt(interrupt_pause);
3669
3670 let run = runner.state.id.clone();
3673 task.start(run.clone());
3674 record(queue, task);
3675 lock(status).current.push(Current {
3676 task: task.id.clone(),
3677 run,
3678 });
3679
3680 let quota_before = runner.state.quota.clone();
3683 runner.state.next_pass_task_entry = true;
3684 let result = runner.execute().await;
3685 finish_attempt(
3686 opts.max_attempts,
3687 queue,
3688 task,
3689 &runner.state,
3690 "a_before,
3691 result,
3692 )
3693}
3694
3695pub fn finish_attempt(
3700 max_attempts: usize,
3701 queue: &Queue,
3702 task: &mut Task,
3703 state: &RunState,
3704 quota_before: &[QuotaLoss],
3705 result: Result<()>,
3706) -> Vec<QuotaLoss> {
3707 let detail = match result {
3708 Ok(()) => describe(state),
3709 Err(e) => format!("{e:#}"),
3710 };
3711 let fresh = losses_this_attempt(quota_before, &state.quota);
3712 let verdict = Verdict {
3713 status: state.status,
3714 left_pr: state.pr.is_some(),
3717 quota_hit: !fresh.is_empty(),
3723 parked: state.parked,
3727 no_viable_candidates: state.viable().is_empty(),
3730 };
3731 if let Some(replacement) = &state.replaces
3732 && let Some(pr) = &state.pr
3733 && let Ok(mut old) = RunState::load(&replacement.run)
3734 && let Some(d) = &mut old.merge_decision
3735 {
3736 d.replacement_pr = Some(pr.url.clone());
3737 let _ = old.save();
3738 }
3739 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3740 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
3741 task.hold_unrequested_retry(Some(format!(
3742 "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
3743 )));
3744 }
3745 if task.status == TaskStatus::Done {
3746 supersede_prior_runs(task, &crate::run::home());
3747 }
3748 record(queue, task);
3749 tracing::info!(
3750 "task {} is {} after run {} ({})",
3751 task.short(),
3752 task.status.as_str(),
3753 state.short(),
3754 label(state.status)
3755 );
3756 fresh
3757}
3758
3759pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3763 let waits_on_owner = withheld_text_wait(task).is_some();
3768 if task.status.runnable()
3769 && !waits_on_owner
3770 && !(task.fresh_start && task.replacement.is_some())
3771 {
3772 let why = task.last_error.clone().map_or_else(
3773 || "the run did not finish".to_owned(),
3774 |e| format!("the run did not finish: {e}"),
3775 );
3776 task.hold_unrequested_retry(Some(format!(
3777 "{why}. It was started by hand, so it is not retried \
3778 automatically; `magi task release` retries it."
3779 )));
3780 record(queue, task);
3781 }
3782}
3783
3784#[must_use]
3788pub fn loop_would_resume(run: &str) -> bool {
3789 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3790}
3791
3792#[must_use]
3802pub fn foreign_loop(
3803 reading: Option<&Reading>,
3804 now: Timestamp,
3805 own_pid: u32,
3806) -> Option<Option<u32>> {
3807 let reading = reading.filter(|r| r.running(now))?;
3808 match reading.pid {
3809 Some(pid) if pid == own_pid => None,
3810 pid => Some(pid),
3811 }
3812}
3813
3814pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3829 let status = Arc::new(Mutex::new(Status::new()));
3830 let stop = Stop::new();
3831 attempt(
3832 opts,
3833 queue,
3834 &status,
3835 &stop,
3836 crate::graph::Pause::new(),
3837 task,
3838 )
3839 .await;
3840 let mut resumes = 0;
3849 while resumes < MAX_WITHHELD_RESUMES {
3850 let Some(timeout) = withheld_text_wait(task) else {
3851 break;
3852 };
3853 eprintln!(
3854 "waiting for the owner's answer on a withheld pull request text \
3855 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3856 );
3857 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3860 let ready = loop {
3861 match land_resume_state(task) {
3862 LandResume::StillWaiting if std::time::Instant::now() < limit => {
3863 tokio::time::sleep(WITHHELD_POLL).await;
3864 }
3865 LandResume::Ready => break true,
3866 _ => break false,
3867 }
3868 };
3869 if !ready {
3870 break;
3871 }
3872 resumes += 1;
3873 attempt(
3874 opts,
3875 queue,
3876 &status,
3877 &stop,
3878 crate::graph::Pause::new(),
3879 task,
3880 )
3881 .await;
3882 }
3883 hold_if_runnable(queue, task);
3884}
3885
3886const MAX_WITHHELD_RESUMES: u32 = 3;
3889
3890const WITHHELD_POLL: Duration = Duration::from_secs(15);
3892
3893fn withheld_text_wait(task: &Task) -> Option<u64> {
3896 let id = task.runs.last()?;
3897 let s = RunState::load(id).ok()?;
3898 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3899 .then_some(s.config.graph.answer_timeout)
3900}
3901
3902fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3912 after
3913 .iter()
3914 .filter(|q| !before.contains(q))
3915 .cloned()
3916 .collect()
3917}
3918
3919fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3922 if quota.is_empty() {
3923 return None;
3924 }
3925 let with_hint = quota.iter().find(|q| q.reset.is_some());
3926 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3927 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3928 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3929 Some(
3930 now.checked_add(jiff::SignedDuration::from_secs(secs))
3931 .unwrap_or(Timestamp::MAX),
3932 )
3933}
3934
3935fn implementers_match(task: &Task, state: &RunState) -> bool {
3937 task.replacement.as_ref().map_or_else(
3938 || {
3939 task.implementers()
3940 .is_none_or(|n| n == state.config.graph.implementers)
3941 },
3942 |replacement| {
3943 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
3944 && state.config.graph.implementers == 1
3945 },
3946 )
3947}
3948
3949fn starter_with_implementers(
3951 task: &Task,
3952 previous: Option<&RunState>,
3953 proposed: Starter,
3954) -> Starter {
3955 if previous.is_some_and(|s| !implementers_match(task, s)) {
3956 task.review_of
3957 .as_ref()
3958 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3959 } else {
3960 proposed
3961 }
3962}
3963
3964fn apply_task_implementers(config: &mut Config, task: &Task) {
3966 if let Some(n) = task.implementers() {
3967 config.graph.implementers = n;
3968 }
3969}
3970
3971fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3976 let Some(o) = &task.overrides else {
3977 return prepare(repo, opts);
3978 };
3979 let own = Opts {
3983 config: o.config.clone(),
3984 merge: None,
3985 ..opts.clone()
3986 };
3987 let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3988 o.apply(&mut config);
3989 Ok(config)
3990}
3991
3992fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3994 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3995 if let Some(mode) = &opts.merge {
3996 config.merge.mode = merge_mode(mode)?;
3997 }
3998 Ok(config)
3999}
4000
4001async fn maybe_prune_cache_between_runs(
4032 repo: &Path,
4033 opts: &Opts,
4034 home: &Path,
4035 stop: &Stop,
4036 last_checked: &mut Option<Timestamp>,
4037 now: Timestamp,
4038) {
4039 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4040 return;
4041 }
4042 *last_checked = Some(now);
4043 let cfg = match prepare(repo, opts) {
4044 Ok(cfg) => cfg,
4045 Err(e) => {
4046 tracing::warn!("cache check: no config: {e:#}");
4047 return;
4048 }
4049 };
4050 match clean::prune_cache_if_over_limit(&cfg, home) {
4051 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4052 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4053 pruned.files,
4054 pruned.freed
4055 ),
4056 Ok(_) => {}
4057 Err(e) => {
4058 tracing::warn!("housekeep: prune cache: {e:#}");
4059 notices::raise_in(
4060 home,
4061 Notice::warn(
4062 "housekeep:cache",
4063 "Pruning the shared build cache failed; disk usage may keep growing.",
4064 ),
4065 );
4066 }
4067 }
4068}
4069
4070fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4074 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4075}
4076
4077async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4096 let cfg = match prepare(repo, opts) {
4097 Ok(cfg) => cfg,
4098 Err(e) => {
4099 tracing::warn!("housekeep: no config: {e:#}");
4100 return;
4101 }
4102 };
4103 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4112 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4113 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4118 let mut extra = Vec::new();
4119 if out.unreadable > 0 {
4120 extra.push(format!("{} unreadable", out.unreadable));
4121 }
4122 if out.orphaned_worktrees > 0 {
4123 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4124 }
4125 let detail = if extra.is_empty() {
4126 String::new()
4127 } else {
4128 format!(" ({})", extra.join(", "))
4129 };
4130 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4131 }
4132 if out.external_merges_recorded > 0 {
4133 tracing::info!(
4134 "housekeep: recorded {} run(s) as merged externally",
4135 out.external_merges_recorded
4136 );
4137 }
4138 if out.stale_pr_states_repaired > 0 {
4139 tracing::info!(
4140 "housekeep: rewrote {} run record(s) whose pull request had already settled",
4141 out.stale_pr_states_repaired
4142 );
4143 }
4144 if out.cache_files > 0 {
4145 tracing::info!(
4146 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4147 out.cache_files,
4148 out.cache_freed
4149 );
4150 }
4151 if out.questions_abandoned > 0 {
4152 tracing::info!(
4153 "housekeep: abandoned {} question(s) left open by a finished run",
4154 out.questions_abandoned
4155 );
4156 }
4157}
4158
4159async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4168 let questions = Questions::at(home.join("questions"));
4169 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4170 if report.is_empty() {
4171 return;
4172 }
4173 if !report.quarantined.is_empty() {
4174 tracing::info!(
4175 "triage: held {} blocked task(s) whose blocked-on task or \
4176 question no longer exists: {}",
4177 report.quarantined.len(),
4178 report.quarantined.join(", ")
4179 );
4180 }
4181 if !report.resumed.is_empty() {
4182 tracing::info!(
4183 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4184 report.resumed.len(),
4185 report.resumed.join(", ")
4186 );
4187 }
4188 if !report.asked.is_empty() {
4189 tracing::info!(
4190 "triage: asked about {} held task(s): {}",
4191 report.asked.len(),
4192 report.asked.join(", ")
4193 );
4194 }
4195 if !report.answered.is_empty() {
4196 tracing::info!(
4197 "triage: applied {} operator answer(s): {}",
4198 report.answered.len(),
4199 report.answered.join(", ")
4200 );
4201 }
4202}
4203
4204fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4211 disk_gate_with(repo, config, crate::disk::free_bytes)
4212}
4213
4214fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4218 repo: &Path,
4219 config: &Config,
4220 free_bytes: F,
4221) -> Option<String> {
4222 let min = config.disk.min_free_bytes;
4223 if min == 0 {
4224 return None;
4225 }
4226 match free_bytes(repo) {
4227 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4228 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
4229 }
4230}
4231
4232const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4239
4240const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4244
4245fn quota_wait(
4254 reset_at: Option<Timestamp>,
4255 now: Timestamp,
4256 fallback: Duration,
4257 cap: Duration,
4258) -> Duration {
4259 match reset_at {
4260 Some(at) if at > now => {
4261 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4262 Duration::from_secs(secs).min(cap)
4263 }
4264 _ => fallback,
4265 }
4266}
4267
4268fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4282 parse_reset_hint_zoned(text, now)
4283 .or_else(|| parse_reset_hint_dated(text))
4284 .or_else(|| parse_reset_hint_relative(text, recorded))
4285}
4286
4287fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4291 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4292 let mut rest = rest.trim();
4293 if rest.is_empty() {
4294 return None;
4295 }
4296 let mut total: i64 = 0;
4297 let mut matched = false;
4298 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4299 if let Some((digits, tail)) = rest.split_once(unit)
4300 && !digits.is_empty()
4301 && digits.bytes().all(|b| b.is_ascii_digit())
4302 {
4303 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4304 rest = tail;
4305 matched = true;
4306 }
4307 }
4308 if !rest.is_empty() || !matched {
4309 return None;
4310 }
4311 recorded
4312 .checked_add(jiff::SignedDuration::from_secs(total))
4313 .ok()
4314}
4315
4316fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4320 let clock = clock.trim().to_lowercase();
4321 let (digits, pm) = clock
4322 .strip_suffix("am")
4323 .map(|d| (d, false))
4324 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4325 let (h, m) = digits.trim().split_once(':')?;
4326 let mut hour: i8 = h.trim().parse().ok()?;
4327 let minute: i8 = m.trim().parse().ok()?;
4328 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4329 return None;
4330 }
4331 if pm && hour != 12 {
4332 hour += 12;
4333 } else if !pm && hour == 12 {
4334 hour = 0;
4335 }
4336 Some((hour, minute))
4337}
4338
4339fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4344 let open = text.find('(')?;
4345 let close = text.rfind(')')?;
4346 if close <= open {
4347 return None;
4348 }
4349 let zone = text[open + 1..close].trim();
4350 let (hour, minute) = parse_12h_clock(&text[..open])?;
4351 let tz = jiff::tz::TimeZone::get(zone).ok()?;
4352 let candidate = now
4353 .to_zoned(tz)
4354 .with()
4355 .hour(hour)
4356 .minute(minute)
4357 .second(0)
4358 .millisecond(0)
4359 .microsecond(0)
4360 .nanosecond(0)
4361 .build()
4362 .ok()?;
4363 let mut at = candidate.timestamp();
4364 if at <= now {
4365 at += jiff::SignedDuration::from_hours(24);
4366 }
4367 Some(at)
4368}
4369
4370fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4379 let words: Vec<&str> = text.split_whitespace().collect();
4380 if words.len() < 5 {
4381 return None;
4382 }
4383 (0..=words.len() - 5)
4384 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4385}
4386
4387fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4393 if trailing.is_some_and(|next| next.starts_with('(')) {
4394 return None;
4395 }
4396 let month = month_number(window[0])?;
4397 let day_token = window[1].strip_suffix(',')?.to_lowercase();
4398 let day_digits = ["st", "nd", "rd", "th"]
4399 .iter()
4400 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4401 let day: i8 = day_digits.parse().ok()?;
4402 let year_token = window[2];
4403 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4404 return None;
4405 }
4406 let year: i16 = year_token.parse().ok()?;
4407 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4411 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4412 let date = jiff::civil::Date::new(year, month, day).ok()?;
4413 let candidate = date
4414 .at(hour, minute, 0, 0)
4415 .to_zoned(jiff::tz::TimeZone::UTC)
4416 .ok()?;
4417 Some(candidate.timestamp())
4418}
4419
4420fn month_number(name: &str) -> Option<i8> {
4423 const NAMES: [&str; 12] = [
4424 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4425 ];
4426 let lower = name.to_lowercase();
4427 NAMES
4428 .iter()
4429 .position(|n| *n == lower.as_str())
4430 .map(|i| i as i8 + 1)
4431}
4432
4433fn exhausted_review_budget(state: &RunState) -> bool {
4445 state.status == RunStatus::Blocked
4448 && !state.pr_publication_pending
4449 && state.reviews.len() >= state.config.graph.review_rounds
4450}
4451
4452fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4489 unfinished_run_with(runs, short, RunState::load)
4490}
4491
4492fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
4495where
4496 F: FnOnce(&str) -> Result<RunState>,
4497{
4498 let id = runs.last()?;
4499 match load(id) {
4500 Ok(s)
4505 if s.status.resumable()
4506 && !s.released()
4507 && !exhausted_review_budget(&s)
4508 && s.liveness(false) != crate::run::Liveness::Live =>
4509 {
4510 Some(id.clone())
4511 }
4512 Ok(_) => None,
4513 Err(e) => {
4514 tracing::warn!("could not read run {id} for task {short}: {e:#}");
4515 None
4516 }
4517 }
4518}
4519
4520fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
4528where
4529 F: FnOnce(&str) -> Result<RunState>,
4530{
4531 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4533 || task.fresh_start
4534 || task.review_branch.is_some()
4535 {
4536 return false;
4537 }
4538 let Some(id) = task.runs.last() else {
4539 return false;
4540 };
4541 load(id).is_ok_and(|s| {
4542 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4543 })
4544}
4545
4546#[derive(Debug, Clone, PartialEq, Eq)]
4549enum Starter {
4550 Review(String),
4553 Resume(String),
4555 Start,
4557}
4558
4559fn selected_starter(
4561 selected: &crate::pr_recovery::Selection,
4562 previous: Option<&RunState>,
4563 unfinished: Option<&str>,
4564) -> Starter {
4565 if let Some(id) = unfinished
4566 && previous.is_some_and(|r| {
4567 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4568 })
4569 {
4570 Starter::Resume(id.to_owned())
4571 } else {
4572 Starter::Review(selected.branch.clone())
4573 }
4574}
4575
4576fn take_divergence_answer(
4580 branch: &str,
4581 remote: &str,
4582 task: &mut Task,
4583) -> Option<crate::reconcile::Choice> {
4584 let summary = crate::reconcile::summary_for(branch, remote);
4585 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4586 (a.question == summary)
4587 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4588 .flatten()
4589 .map(|c| (i, c))
4590 })?;
4591 task.answers.remove(idx);
4592 Some(choice)
4593}
4594
4595fn choose_starter(
4607 review_branch: Option<&str>,
4608 branch_exists: bool,
4609 unfinished: Option<&str>,
4610) -> Starter {
4611 match review_branch {
4612 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4613 Some(_) => Starter::Start,
4614 None => match unfinished {
4615 Some(id) => Starter::Resume(id.to_owned()),
4616 None => Starter::Start,
4617 },
4618 }
4619}
4620
4621fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4623 let branch = task.review_branch.take();
4624 let instruction = task.review_instruction.take();
4625 branch.filter(|branch| match &instruction {
4626 Some(authored) => *authored == task.instruction,
4627 None => previous.map_or_else(
4630 || task.review_of.as_ref() == Some(branch),
4631 |run| compatible_run_instruction(run, task),
4632 ),
4633 })
4634}
4635
4636fn may_resume_run(run: &RunState, task: &Task) -> bool {
4639 task.resume_override
4640 .as_ref()
4641 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
4642 || compatible_run_instruction(run, task)
4643}
4644
4645pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
4647 if let Some(authored) = &run.task_instruction {
4648 return compatible_instruction(authored, task);
4649 }
4650 if compatible_instruction(&run.instruction, task) {
4651 return true;
4652 }
4653 if run.reviewed_commits.is_some() {
4656 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
4657 return strip_answers_block(authored, task).trim() == task.instruction.trim();
4658 }
4659 if let Some(branch) = &task.review_of {
4660 let canonical = format!(
4661 "Review the branch `{branch}` (review-only: no implementation, no judging)."
4662 );
4663 let generated = format!(
4664 "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"
4665 );
4666 return task.instruction == canonical && run.instruction.starts_with(&generated);
4667 }
4668 }
4669 false
4670}
4671
4672pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
4674 strip_answers_block(old, task) == task.instruction
4675}
4676
4677fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4680 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4681 return fallback.to_path_buf();
4682 }
4683 task.repo.clone()
4684}
4685
4686const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4690
4691fn answers_block(task: &Task, count: usize) -> String {
4693 let mut s = ANSWERS_HEADER.to_owned();
4694 for a in &task.answers[..count] {
4695 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4696 }
4697 s
4698}
4699
4700fn resumption_block(r: &crate::queue::Resumption) -> String {
4703 format!(
4704 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
4705 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
4706 r.generation, r.at, r.instruction, r.answers_through,
4707 )
4708}
4709
4710fn append_answers(base: &str, task: &Task) -> String {
4712 let mut s = base.to_owned();
4713 if !task.answers.is_empty() {
4714 s.push_str(&answers_block(task, task.answers.len()));
4715 }
4716 if let Some(r) = &task.resumption {
4717 s.push_str(&resumption_block(r));
4718 }
4719 s
4720}
4721
4722fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4726 let mut instruction = instruction;
4727 for approval in task
4728 .resumption
4729 .iter()
4730 .chain(task.resumption_history.iter().rev())
4731 {
4732 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
4733 instruction = base;
4734 break;
4735 }
4736 }
4737 for count in (1..=task.answers.len()).rev() {
4738 let block = answers_block(task, count);
4739 if let Some(base) = instruction.strip_suffix(&block) {
4740 return base;
4741 }
4742 }
4743 instruction
4744}
4745
4746fn instruction_for(task: &Task) -> String {
4754 append_answers(&task.instruction, task)
4755}
4756
4757fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4769 append_answers(strip_answers_block(old_instruction, task), task)
4770}
4771
4772fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
4774 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
4775 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
4776 if let Some(cause) = task.hold_notice_cause.as_mut() {
4777 cause.target = failure.map(|f| f.target.clone());
4778 }
4779}
4780
4781#[derive(Debug, thiserror::Error)]
4782#[error("attachment `{name}` is recorded on the task but {path} is missing")]
4783struct MissingAttachment {
4784 name: String,
4785 path: PathBuf,
4786}
4787
4788fn task_attachments(
4790 queue: &Queue,
4791 task: &Task,
4792) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
4793 let paths = queue.attachment_paths(task);
4794 for (name, path) in task.attachments.iter().zip(&paths) {
4795 if !path.is_file() {
4796 return Err(MissingAttachment {
4797 name: name.clone(),
4798 path: path.clone(),
4799 });
4800 }
4801 }
4802 Ok(paths)
4803}
4804
4805fn prepare_instruction(
4816 starter: &Starter,
4817 old_instruction: Option<&str>,
4818 task: &Task,
4819) -> Option<String> {
4820 match starter {
4821 Starter::Start => Some(instruction_for(task)),
4822 Starter::Resume(_) => Some(resumed_instruction(
4823 old_instruction.expect("a resumed run always has a prior instruction"),
4824 task,
4825 )),
4826 Starter::Review(_) => None,
4827 }
4828}
4829
4830fn record(queue: &Queue, task: &mut Task) {
4834 if let Err(e) = queue.put(task) {
4835 tracing::error!("could not record task {}: {e:#}", task.short());
4836 let notice = Notice::error(
4837 "loop:record",
4838 "The loop could not save a task's state; check the disk.",
4839 )
4840 .link(Link::Task {
4841 id: task.id.clone(),
4842 });
4843 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4845 Some(home) => notices::raise_in(home, notice),
4846 None => notices::raise(notice),
4847 }
4848 }
4849}
4850
4851fn runnable(queue: &Queue) -> Vec<Task> {
4857 let mut tasks: Vec<Task> = queue
4858 .list()
4859 .into_iter()
4860 .filter(|t| t.status.runnable())
4861 .collect();
4862 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4863 tasks
4864}
4865
4866fn describe(state: &RunState) -> String {
4880 let p = phrases(&state.config.graph.language);
4881 let mut detail = if state.status == RunStatus::Stalled {
4882 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4883 seats.sort_unstable();
4884 seats.dedup();
4885 if seats.is_empty() {
4886 p.quorum_lost.to_owned()
4887 } else {
4888 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4889 }
4890 } else {
4891 format!("{}{}", p.run_ended, state.status.display_label())
4892 };
4893 if let Some(last) = state.events.last() {
4894 let unanswered = state
4898 .reviews
4899 .last()
4900 .filter(|r| {
4901 state.status == RunStatus::Blocked
4902 && last.node == "review"
4903 && r.incomplete()
4904 && r.blocking == 0
4905 && r.round == state.config.graph.review_rounds
4906 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4907 })
4908 .map(|r| (r.expected - r.answered, r.round));
4909 match unanswered {
4910 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4911 detail.push_str(&format!(
4912 " ({}: {})",
4913 last.node,
4914 (p.reviewers_never_answered)(missing, rounds)
4915 ));
4916 }
4917 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4918 }
4919 }
4920 detail.push_str(&format!(" [run {}]", state.id));
4921 detail
4922}
4923
4924const DIAGNOSTIC_MAX: usize = 4_000;
4930
4931const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4936
4937fn diagnostic(state: &RunState) -> Option<String> {
4951 let mut parts: Vec<String> = Vec::new();
4952
4953 for o in state.gate.iter().filter(|o| !o.ok()) {
4955 parts.push(format!(
4956 "gate `{}` failed ({:?}):\n{}",
4957 o.command,
4958 o.code,
4959 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4960 ));
4961 }
4962
4963 if let Some(last) = state
4966 .events
4967 .iter()
4968 .rev()
4969 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4970 {
4971 parts.push(last.message.clone());
4972 }
4973
4974 if state.viable().is_empty() {
4981 for c in &state.candidates {
4982 if let Some(evidence) = &c.verified_noop {
4983 parts.push(format!(
4984 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4985 c.label
4986 ));
4987 } else if !c.summary.trim().is_empty() {
4988 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4989 } else if let Some(why) = &c.failed {
4990 parts.push(format!("candidate {}: {why}", c.label));
4991 }
4992 }
4993 }
4994
4995 if parts.is_empty() {
4996 return None;
4997 }
4998 Some(crate::run::tail(
5003 &parts.join("\n\n"),
5004 DIAGNOSTIC_MAX.saturating_sub(100),
5005 ))
5006}
5007
5008fn label(status: RunStatus) -> &'static str {
5016 status.as_str()
5017}
5018
5019pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5021 match mode {
5022 "none" => Ok(MergeMode::None),
5023 "local" => Ok(MergeMode::Local),
5024 "pr" => Ok(MergeMode::Pr),
5025 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5026 }
5027}
5028
5029fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5034 mutex
5035 .lock()
5036 .unwrap_or_else(std::sync::PoisonError::into_inner)
5037}
5038
5039#[cfg(test)]
5040mod tests {
5041 use super::*;
5042 use crate::queue::{Source, TaskStatus};
5043 use crate::run::{Candidate, CommandOutcome};
5044 use pretty_assertions::assert_eq;
5045
5046 fn task() -> Task {
5047 Task::new(
5048 "add retries".to_owned(),
5049 "add retries".to_owned(),
5050 PathBuf::from("/repo"),
5051 Source::Human,
5052 )
5053 }
5054
5055 #[test]
5056 fn selected_public_head_overrides_historical_resume_and_pin() {
5057 let mut t = task();
5058 let mut old = run_state(RunStatus::Blocked);
5059 let selection = crate::pr_recovery::Selection {
5060 url: "url".into(),
5061 branch: format!("magi/task-{}", t.id),
5062 head: "a".repeat(40),
5063 instruction: t.instruction.clone(),
5064 approved_at: Timestamp::now(),
5065 };
5066 t.resume_override = Some(crate::queue::OperatorResume {
5067 pinned_run: Some(old.id.clone()),
5068 question_id: "choice".into(),
5069 at: Timestamp::now(),
5070 conductor_rehold: None,
5071 forced: false,
5072 });
5073 assert_eq!(
5074 selected_starter(&selection, Some(&old), Some(&old.id)),
5075 Starter::Review(selection.branch.clone())
5076 );
5077 old.pr_recovery = Some(selection.clone());
5078 assert_eq!(
5079 selected_starter(&selection, Some(&old), Some(&old.id)),
5080 Starter::Review(selection.branch.clone())
5081 );
5082 old.reviewed_commits = Some(vec!["implementation".into()]);
5083 assert_eq!(
5084 selected_starter(&selection, Some(&old), Some(&old.id)),
5085 Starter::Resume(old.id.clone())
5086 );
5087 let mut changed = selection.clone();
5088 changed.head = "b".repeat(40);
5089 assert_eq!(
5090 selected_starter(&changed, Some(&old), Some(&old.id)),
5091 Starter::Review(changed.branch)
5092 );
5093 }
5094
5095 #[test]
5096 fn candidate_transplant_failure_is_one_actionable_hold() {
5097 let dir = tempfile::tempdir().unwrap();
5098 let q = Queue::at(dir.path().join("queue"));
5099 let mut t = task();
5100 let mut state = run_state(RunStatus::Blocked);
5101 state.event("prep", "cannot apply referenced commit: conflict");
5102 state.prep_failure = Some("conflict".into());
5103 t.start(state.id.clone());
5104 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5105 assert_eq!(t.attempts, 1);
5106 assert_eq!(t.status, TaskStatus::Held);
5107 assert!(t.operator_held());
5108 assert!(!t.status.runnable());
5109 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5110 let first = t.chat_notice_key().unwrap();
5111 t.chat_notices.push(first.clone());
5112 t.release_operator("test", None);
5113 state.id = "another-unprepared-run".into();
5114 t.start(state.id.clone());
5115 finish_attempt(
5116 3,
5117 &q,
5118 &mut t,
5119 &state,
5120 &[],
5121 Err(anyhow::anyhow!("still conflicts")),
5122 );
5123 assert_eq!(
5124 t.chat_notice_key().as_ref(),
5125 Some(&first),
5126 "no work happened"
5127 );
5128 t.release_operator("test", None);
5129 state.prep_failure = None;
5130 state.status = RunStatus::Failed;
5131 state.begin_pass();
5132 t.start(state.id.clone());
5133 finish_attempt(
5134 1,
5135 &q,
5136 &mut t,
5137 &state,
5138 &[],
5139 Err(anyhow::anyhow!("new gate failure")),
5140 );
5141 let failure = t.chat_notice_key().unwrap();
5142 assert_ne!(failure, first, "approved recovery reached a real failure");
5143 t.release_operator("test", None);
5144 state.begin_pass();
5145 t.start(state.id.clone());
5146 finish_attempt(
5147 1,
5148 &q,
5149 &mut t,
5150 &state,
5151 &[],
5152 Err(anyhow::anyhow!("new failure on resume")),
5153 );
5154 assert_ne!(
5155 t.chat_notice_key().as_ref(),
5156 Some(&failure),
5157 "a new settled pass"
5158 );
5159 }
5160
5161 #[test]
5162 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5163 for source in ["cli", "web"] {
5164 let mut t = task();
5165 let mut run = run_state(RunStatus::Blocked);
5166 run.instruction = "Run A original criteria".into();
5167 run.task_instruction = Some(run.instruction.clone());
5168 t.start(run.id.clone());
5169 t.release_operator("choice", Some("resume-question"));
5170 t.resume_override = Some(crate::queue::OperatorResume {
5171 question_id: "resume-question".into(),
5172 at: Timestamp::now(),
5173 conductor_rehold: None,
5174 forced: true,
5175 pinned_run: Some(run.id.clone()),
5176 });
5177 t.hold_machine(Some("not enough free space to start a run".into()));
5178 let mut unchanged = t.clone();
5179 unchanged
5180 .edit("title changed".into(), unchanged.instruction.clone())
5181 .unwrap();
5182 unchanged.release_operator(source, None);
5183 assert_eq!(
5184 unchanged
5185 .resume_override
5186 .as_ref()
5187 .unwrap()
5188 .pinned_run
5189 .as_deref(),
5190 Some(run.id.as_str())
5191 );
5192 assert!(!compatible_run_instruction(&run, &unchanged));
5193 assert!(may_resume_run(&run, &unchanged));
5194
5195 t.edit(
5196 "approved recovery".into(),
5197 "Reuse measured PR head B; fix Clippy; review".into(),
5198 )
5199 .unwrap();
5200 assert!(t.resume_override.is_none());
5201 t.release_operator(source, None);
5202 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5203 assert!(reloaded.resume_override.is_none());
5204 assert!(!may_resume_run(&run, &reloaded));
5205 let unfinished =
5206 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5207 .filter(|_| may_resume_run(&run, &reloaded));
5208 assert_eq!(
5209 choose_starter(None, false, unfinished.as_deref()),
5210 Starter::Start
5211 );
5212 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5213 assert_eq!(
5214 reloaded.resumption_history[0].question_id.as_deref(),
5215 Some("resume-question")
5216 );
5217
5218 unchanged.instruction = "Reuse measured PR head B".into();
5221 unchanged.hold_machine(Some("disk hold".into()));
5222 unchanged.release_operator(source, None);
5223 assert!(unchanged.resume_override.is_none());
5224 assert!(!may_resume_run(&run, &unchanged));
5225 }
5226 }
5227
5228 #[test]
5229 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5230 let mut t = task();
5231 let mut run = run_state(RunStatus::Blocked);
5232 t.review_of = Some("approved-head".into());
5233 t.instruction =
5234 "Review the branch `approved-head` (review-only: no implementation, no judging)."
5235 .into();
5236 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();
5237 run.reviewed_commits = Some(vec!["Commit log".into()]);
5238 t.start(run.id.clone());
5239 t.hold_machine(Some("interrupted review".into()));
5240 t.release_operator("cli", None);
5241 assert!(
5242 compatible_run_instruction(&run, &t),
5243 "legacy explicit review remains resumable"
5244 );
5245 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5246 .filter(|_| compatible_run_instruction(&run, &t));
5247 assert_eq!(
5248 choose_starter(None, false, unfinished.as_deref()),
5249 Starter::Resume(run.id.clone())
5250 );
5251 run.task_instruction = Some(t.instruction.clone());
5252 assert!(compatible_run_instruction(&run, &t));
5253 let reloaded: RunState =
5254 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5255 assert!(compatible_run_instruction(&reloaded, &t));
5256 t.edit(
5257 "new approved head".into(),
5258 "Reuse measured PR head B".into(),
5259 )
5260 .unwrap();
5261 assert!(!compatible_run_instruction(&run, &t));
5262
5263 t.review_of = None;
5265 t.instruction = "Fix Clippy on approved head".into();
5266 run.task_instruction = None;
5267 run.instruction = format!(
5268 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5269 t.instruction
5270 );
5271 assert!(compatible_run_instruction(&run, &t));
5272 t.instruction.push('\n');
5273 assert!(
5274 compatible_run_instruction(&run, &t),
5275 "legacy generated review trimmed the original criteria"
5276 );
5277 t.hold_for_handover(Some("approved-head".into()), "refused".into());
5278 let mut unchanged = t.clone();
5279 assert_eq!(
5280 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5281 Some("approved-head")
5282 );
5283 t.edit("new plan".into(), "Reuse measured PR head B".into())
5284 .unwrap();
5285 assert!(take_review_branch(&mut t, Some(&run)).is_none());
5286 assert!(!compatible_run_instruction(&run, &t));
5287 t.review_branch = Some("approved-head".into());
5288 t.review_instruction = None;
5289 assert!(
5290 take_review_branch(&mut t, Some(&run)).is_none(),
5291 "legacy retained candidate cannot replace a revised approved head"
5292 );
5293 }
5294
5295 #[test]
5296 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5297 crate::run::pin_test_home();
5298 let dir = tempfile::tempdir().unwrap();
5299 let queue = Queue::at(dir.path().join("queue"));
5300 for resume in [true, false] {
5301 let state = run_state(RunStatus::Blocked);
5302 let mut t = task();
5303 t.start(state.id.clone());
5304 let action = if resume {
5305 ask::ChoiceAction::Resume {
5306 run: state.id.clone(),
5307 }
5308 } else {
5309 ask::ChoiceAction::Requeue
5310 };
5311 let mut q = action_question(&state.id, action);
5312 q.status = ask::QuestionStatus::Open;
5313 q.answer = None;
5314 q.answered_at = None;
5315 t.fail("run stopped with a question", 3);
5316 hold_if_runnable(&queue, &mut t);
5317 assert!(t.operator_decided_at.is_none());
5318 assert!(t.operator_held());
5319 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5320 let expected = if resume {
5321 ActionDecision::Resume(state.id.clone())
5322 } else {
5323 ActionDecision::Requeue
5324 };
5325 assert_eq!(
5326 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5327 expected
5328 );
5329 t.hold_manual(Some("later explicit hold".into()));
5330 assert_eq!(
5331 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5332 ActionDecision::Stale
5333 );
5334 }
5335 }
5336
5337 #[test]
5338 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5339 let mut t = task();
5340 t.answers.push(crate::queue::AnsweredQuestion {
5341 question: "Inspect the remote?".into(),
5342 answer: "Inspect then wait".into(),
5343 });
5344 let old = instruction_for(&t);
5345 assert!(compatible_instruction(&old, &t));
5346 t.instruction = "Reuse approved PR head and review".into();
5347 t.release_operator("cli", None);
5348 assert!(!compatible_instruction(&old, &t));
5349 let approved = instruction_for(&t);
5350 assert!(approved.contains("waiting premises are superseded"));
5351 assert!(compatible_instruction(&approved, &t));
5352 assert_eq!(resumed_instruction(&approved, &t), approved);
5353 t.release_operator("web", None);
5354 assert!(compatible_instruction(&approved, &t));
5355 assert_eq!(t.resumption_history.len(), 1);
5356 t.start("run".into());
5357 assert!(instruction_for(&t).contains("Explicit operator resumption"));
5358 }
5359
5360 #[test]
5364 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5365 let mut state = RunState::new(
5366 PathBuf::from("/repo"),
5367 "main".to_owned(),
5368 "abc1234".to_owned(),
5369 "task".to_owned(),
5370 Config::default(),
5371 );
5372 state.status = RunStatus::Blocked;
5373 state.resource_block = Some(crate::run::ResourceBlock {
5374 node: "graft".to_owned(),
5375 kind: "shared build cache".to_owned(),
5376 detail: "timed out".to_owned(),
5377 at: jiff::Timestamp::now(),
5378 });
5379 let mut t = task();
5380 t.start("20260902-000000-aaaa".to_owned());
5381 assert_eq!(t.attempts, 1);
5382 let verdict = Verdict {
5383 status: RunStatus::Blocked,
5384 left_pr: false,
5385 quota_hit: false,
5386 parked: false,
5387 no_viable_candidates: false,
5388 };
5389 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5390 assert_eq!(t.status, TaskStatus::Held);
5391 assert_eq!(t.attempts, 0, "the attempt is refunded");
5392 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5393 assert!(
5394 !t.operator_held(),
5395 "a machine hold, released without a human"
5396 );
5397
5398 let mut selected = task();
5399 selected.start("20260902-000000-cccc".into());
5400 selected.replacement = Some(crate::merge_decision::Replacement {
5401 question: "fixture".into(),
5402 run: "earlier".into(),
5403 pr: "https://example.invalid/pr/1".into(),
5404 agent: "selected".into(),
5405 context: "fixture".into(),
5406 });
5407 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5408 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5409 assert_eq!(selected.attempts, 0);
5410 assert!(
5411 !selected.operator_held(),
5412 "a selected agent also retains a machine resource hold"
5413 );
5414 assert!(
5415 selected
5416 .hold_reason
5417 .as_deref()
5418 .unwrap()
5419 .starts_with("[resource] ")
5420 );
5421
5422 let mut p = task();
5424 p.start("20260902-000000-bbbb".to_owned());
5425 settle_and_diagnose(
5426 &mut p,
5427 Verdict {
5428 parked: true,
5429 ..verdict
5430 },
5431 "parked",
5432 2,
5433 &state,
5434 );
5435 assert_eq!(p.status, TaskStatus::Parked);
5436 }
5437
5438 #[test]
5439 fn record_failure_notice_links_the_task() {
5440 let dir = tempfile::tempdir().unwrap();
5441 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5444 let queue = Queue::at(dir.path().join("queue"));
5445 let mut t = interrupt_task("rec-fail-1");
5446 record(&queue, &mut t);
5447
5448 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5449 assert_eq!(found.len(), 1);
5450 assert_eq!(found[0].key, "loop:record");
5451 assert_eq!(
5452 found[0].link,
5453 Some(Link::Task {
5454 id: "rec-fail-1".to_owned()
5455 })
5456 );
5457 }
5458
5459 fn interrupt_task(id: &str) -> Task {
5462 let mut t = task();
5463 t.id = id.to_owned();
5464 t.interrupt = true;
5465 t
5466 }
5467
5468 fn task_with_id(id: &str) -> Task {
5470 let mut t = task();
5471 t.id = id.to_owned();
5472 t
5473 }
5474
5475 fn urgent_task(id: &str) -> Task {
5477 let mut t = task();
5478 t.id = id.to_owned();
5479 t.urgent = true;
5480 t
5481 }
5482
5483 #[test]
5484 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
5485 let dir = tempfile::tempdir().unwrap();
5486 let queue = Queue::at(dir.path().join("queue"));
5487 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5488 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5489 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
5490 let mut first = task();
5491 queue.put(&mut first).unwrap();
5492 let stale_plain = queue.get(&first.id).unwrap();
5493 first.set_urgent(true).unwrap();
5494 queue.put(&mut first).unwrap();
5495 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
5496 let mut second = urgent_task("second");
5497 queue.put(&mut second).unwrap();
5498 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
5499 drop(queue.claim(&second.id).unwrap());
5500 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
5501 drop(dispatched);
5502 let stale_urgent = queue.get(&first.id).unwrap();
5503 first.set_urgent(false).unwrap();
5504 queue.put(&mut first).unwrap();
5505 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
5506 assert_eq!(urgent.available_permits(), 1);
5507 drop(queue.claim(&first.id).unwrap());
5508 drop(occupied);
5509 }
5510
5511 #[test]
5512 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
5513 let dir = tempfile::tempdir().unwrap();
5514 let queue = Queue::at(dir.path().join("queue"));
5515 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5516 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5517 let mut t = task();
5518 queue.put(&mut t).unwrap();
5519 for enabled in [true, false] {
5520 let stale = queue.get(&t.id).unwrap();
5521 t.set_urgent(enabled).unwrap();
5522 queue.put(&mut t).unwrap();
5523 assert_ne!(stale.urgent, enabled);
5524 let DispatchClaim {
5525 task: fresh,
5526 claim,
5527 permit,
5528 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
5529 assert_eq!(fresh.urgent, enabled);
5530 assert_eq!(ordinary.available_permits(), usize::from(enabled));
5531 assert_eq!(urgent.available_permits(), usize::from(!enabled));
5532 assert!(queue.claim(&t.id).is_err());
5533 assert_eq!(fresh.attempts, stale.attempts);
5534 drop((claim, permit));
5535 assert_eq!(ordinary.available_permits(), 1);
5536 assert_eq!(urgent.available_permits(), 1);
5537 }
5538 t.set_urgent(true).unwrap();
5539 queue.put(&mut t).unwrap();
5540 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
5541 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5542 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
5543 drop(queue.claim(&t.id).unwrap());
5544 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
5545 drop(occupied);
5546 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
5547 drop(queue.claim(&t.id).unwrap());
5548 let held = queue.claim(&t.id).unwrap();
5549 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5550 drop(held);
5551 t.status = TaskStatus::Held;
5552 queue.put(&mut t).unwrap();
5553 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5554 drop(queue.claim(&t.id).unwrap());
5555 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
5556 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5557 drop(queue.claim(&t.id).unwrap());
5558 assert_eq!(urgent.available_permits(), 1);
5559 }
5560
5561 #[test]
5566 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
5567 assert_eq!(permit_kind(true, false), PermitKind::None);
5568 assert_eq!(permit_kind(true, true), PermitKind::None);
5569 }
5570
5571 #[test]
5576 fn permit_kind_separates_urgent_from_ordinary() {
5577 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
5578 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
5579 }
5580
5581 #[test]
5588 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
5589 let cfg = Config::default();
5590 let repo = Path::new("/any/repo/path");
5591
5592 let reason =
5593 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
5594 assert!(reason.contains("1024"), "{reason}");
5595 assert!(
5596 reason.contains(&cfg.disk.min_free_bytes.to_string()),
5597 "{reason}"
5598 );
5599
5600 assert_eq!(
5601 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
5602 None,
5603 "exactly at the floor is open"
5604 );
5605 assert_eq!(
5606 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
5607 None,
5608 "comfortably above the floor is open"
5609 );
5610 }
5611
5612 #[test]
5613 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
5614 let mut cfg = Config::default();
5615 cfg.disk.min_free_bytes = 0;
5616 let repo = Path::new("/any/repo/path");
5617 assert_eq!(
5618 disk_gate_with(repo, &cfg, |_| Ok(0)),
5619 None,
5620 "a zero floor never measures at all"
5621 );
5622 }
5623
5624 #[test]
5625 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5626 let cfg = Config::default();
5627 let repo = Path::new("/any/repo/path");
5628 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5629 .expect("a measurement failure must close the gate, not open it");
5630 assert!(reason.contains("could not measure"), "{reason}");
5631 }
5632
5633 #[test]
5634 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5635 let ordinary = task();
5636 let next = advance_interrupt(
5637 Interrupt::Idle,
5638 std::slice::from_ref(&ordinary.id),
5639 std::slice::from_ref(&ordinary),
5640 );
5641 assert_eq!(next, Interrupt::Idle);
5642 }
5643
5644 #[test]
5645 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
5646 let marked = interrupt_task("marked");
5649 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5650 assert_eq!(next, Interrupt::Idle);
5651 }
5652
5653 #[test]
5654 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
5655 let marked = interrupt_task("marked");
5656 let next = advance_interrupt(
5657 Interrupt::Idle,
5658 &["running".to_owned()],
5659 std::slice::from_ref(&marked),
5660 );
5661 assert_eq!(
5662 next,
5663 Interrupt::Parking {
5664 parked: vec!["running".to_owned()],
5665 interrupt_task: "marked".to_owned(),
5666 }
5667 );
5668 }
5669
5670 #[test]
5679 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
5680 let marked = interrupt_task("marked");
5681
5682 let two = advance_interrupt(
5683 Interrupt::Idle,
5684 &["a".to_owned(), "b".to_owned()],
5685 std::slice::from_ref(&marked),
5686 );
5687 assert_eq!(two, Interrupt::Idle);
5688
5689 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5690 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
5691 }
5692
5693 #[test]
5694 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
5695 let state = Interrupt::Parking {
5696 parked: vec!["running".to_owned()],
5697 interrupt_task: "marked".to_owned(),
5698 };
5699 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
5701 assert_eq!(still_going, state);
5702
5703 let stopped_but_not_yet_dispatched =
5707 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
5708 assert_eq!(stopped_but_not_yet_dispatched, state);
5709
5710 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
5712 assert_eq!(
5713 dispatched,
5714 Interrupt::Running {
5715 parked: vec!["running".to_owned()],
5716 interrupt_task: "marked".to_owned(),
5717 }
5718 );
5719 }
5720
5721 #[test]
5722 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
5723 let state = Interrupt::Running {
5724 parked: vec!["running".to_owned()],
5725 interrupt_task: "marked".to_owned(),
5726 };
5727 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
5728 assert_eq!(still_running, state);
5729
5730 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
5737 assert_eq!(
5738 ended,
5739 Interrupt::Resuming {
5740 parked: vec!["running".to_owned()]
5741 }
5742 );
5743 }
5744
5745 #[test]
5746 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
5747 let state = Interrupt::Resuming {
5748 parked: vec!["running".to_owned()],
5749 };
5750 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
5751 assert_eq!(still_waiting, state);
5752
5753 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
5754 assert_eq!(dispatched, Interrupt::Idle);
5755 }
5756
5757 #[test]
5763 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
5764 {
5765 let state = Interrupt::Parking {
5766 parked: vec!["running".to_owned()],
5767 interrupt_task: "marked".to_owned(),
5768 };
5769 let next = advance_interrupt(state, &[], &[]);
5772 assert_eq!(
5773 next,
5774 Interrupt::Resuming {
5775 parked: vec!["running".to_owned()]
5776 },
5777 "abandoning the interrupt must not abandon the resume it owes"
5778 );
5779 }
5780
5781 #[test]
5784 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
5785 let state = Interrupt::Resuming {
5786 parked: vec!["running".to_owned()],
5787 };
5788 let next = advance_interrupt(state, &[], &[]);
5789 assert_eq!(
5790 next,
5791 Interrupt::Idle,
5792 "nothing is left to wait for; the loop must not stay wedged"
5793 );
5794 }
5795
5796 #[test]
5797 fn disabled_by_config_the_sequence_can_never_leave_idle() {
5798 let marked = interrupt_task("marked");
5799 let next = advance_interrupt_tick(
5800 false,
5801 Interrupt::Idle,
5802 &["running".to_owned()],
5803 std::slice::from_ref(&marked),
5804 );
5805 assert_eq!(
5806 next,
5807 Interrupt::Idle,
5808 "an unmarked, unconfigured daemon must behave exactly as before"
5809 );
5810 }
5811
5812 #[test]
5813 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
5814 let state = Interrupt::Parking {
5815 parked: vec!["running".to_owned()],
5816 interrupt_task: "marked".to_owned(),
5817 };
5818 let candidates = vec![interrupt_task("marked"), task()];
5819 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5820 assert!(
5821 allowed.is_empty(),
5822 "nothing may dispatch - not even the interrupt task itself - \
5823 until the parked run has actually stopped"
5824 );
5825 }
5826
5827 #[test]
5841 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
5842 for state in [
5843 Interrupt::Parking {
5844 parked: vec!["running".to_owned()],
5845 interrupt_task: "marked".to_owned(),
5846 },
5847 Interrupt::Running {
5848 parked: vec!["running".to_owned()],
5849 interrupt_task: "marked".to_owned(),
5850 },
5851 Interrupt::Resuming {
5852 parked: vec!["running".to_owned()],
5853 },
5854 ] {
5855 let candidates = vec![
5856 interrupt_task("marked"),
5857 urgent_task("hot"),
5858 task_with_id("ordinary"),
5859 ];
5860 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5861 assert!(
5862 !allowed.iter().any(|t| t.id == "hot"),
5863 "an urgent candidate must wait out the same gate as anything \
5864 else while the run it would run alongside has not actually \
5865 left flight, for state {state:?}: {allowed:?}"
5866 );
5867 }
5868 }
5869
5870 #[test]
5876 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
5877 let state = Interrupt::Resuming {
5878 parked: vec!["hot".to_owned()],
5879 };
5880 let candidates = vec![urgent_task("hot"), task()];
5881 let allowed = interrupt_gate(&state, &[], candidates);
5882 assert_eq!(
5883 allowed.iter().filter(|t| t.id == "hot").count(),
5884 1,
5885 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
5886 );
5887 }
5888
5889 #[test]
5890 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
5891 let state = Interrupt::Parking {
5892 parked: vec!["running".to_owned()],
5893 interrupt_task: "marked".to_owned(),
5894 };
5895 let other = task();
5896 let candidates = vec![interrupt_task("marked"), other.clone()];
5897 let allowed = interrupt_gate(&state, &[], candidates);
5898 assert_eq!(allowed.len(), 1);
5899 assert_eq!(allowed[0].id, "marked");
5900 }
5901
5902 #[test]
5903 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
5904 let state = Interrupt::Running {
5905 parked: vec!["running".to_owned()],
5906 interrupt_task: "marked".to_owned(),
5907 };
5908 let candidates = vec![task(), task()];
5909 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
5910 assert!(allowed.is_empty());
5911 }
5912
5913 #[test]
5920 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
5921 let state = Interrupt::Resuming {
5922 parked: vec!["a".to_owned(), "c".to_owned()],
5923 };
5924 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
5925 let allowed = interrupt_gate(&state, &[], candidates);
5926 assert_eq!(
5927 allowed.len(),
5928 1,
5929 "at most one candidate may be offered while resuming: {allowed:?}"
5930 );
5931 assert_eq!(allowed[0].id, "a");
5932 }
5933
5934 #[test]
5935 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
5936 let state = Interrupt::Resuming {
5937 parked: vec!["a".to_owned()],
5938 };
5939 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
5940 assert!(allowed.is_empty());
5941 }
5942
5943 #[test]
5949 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
5950 let running = task(); let marked = interrupt_task("marked");
5952
5953 let mut state = Interrupt::Idle;
5954 let in_flight = vec![running.id.clone()];
5956 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
5957 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
5958 assert!(gated.is_empty(), "still waiting on `running` to park");
5959
5960 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
5962 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
5963 assert_eq!(
5964 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5965 vec!["marked"],
5966 "only the interrupt task may be offered to the dispatcher now"
5967 );
5968
5969 state = advance_interrupt_tick(
5971 true,
5972 state,
5973 &["marked".to_owned()],
5974 std::slice::from_ref(&running),
5975 );
5976 let gated = interrupt_gate(
5977 &state,
5978 &["marked".to_owned()],
5979 vec![marked.clone(), running.clone()],
5980 );
5981 assert!(
5982 gated.is_empty(),
5983 "the parked run must not be offered back while the interrupt \
5984 task is still running"
5985 );
5986
5987 let other = task_with_id("other");
5991 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
5992 assert_eq!(
5993 state,
5994 Interrupt::Resuming {
5995 parked: vec![running.id.clone()]
5996 }
5997 );
5998 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
5999 assert_eq!(
6000 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6001 vec![running.id.as_str()],
6002 "exactly the parked run resumes - not the unrelated task, even \
6003 though it was offered first"
6004 );
6005
6006 state = advance_interrupt_tick(
6010 true,
6011 state,
6012 std::slice::from_ref(&running.id),
6013 std::slice::from_ref(&other),
6014 );
6015 assert_eq!(state, Interrupt::Idle);
6016 let gated = interrupt_gate(
6017 &state,
6018 std::slice::from_ref(&running.id),
6019 vec![other.clone()],
6020 );
6021 assert_eq!(
6022 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6023 vec![other.id.as_str()],
6024 "ordinary dispatch is unrestricted again"
6025 );
6026 }
6027
6028 #[test]
6029 fn every_run_status_settles_the_task_it_came_from() {
6030 let table = [
6032 (RunStatus::Merged, TaskStatus::Done, 1),
6033 (RunStatus::Ready, TaskStatus::Done, 1),
6034 (RunStatus::Stalled, TaskStatus::Failed, 0),
6035 (RunStatus::Blocked, TaskStatus::Failed, 1),
6036 (RunStatus::Failed, TaskStatus::Failed, 1),
6037 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6038 (RunStatus::Prep, TaskStatus::Failed, 1),
6039 (RunStatus::Implementing, TaskStatus::Failed, 1),
6040 (RunStatus::Judging, TaskStatus::Failed, 1),
6041 (RunStatus::Deliberating, TaskStatus::Failed, 1),
6042 (RunStatus::Voting, TaskStatus::Failed, 1),
6043 (RunStatus::Reviewing, TaskStatus::Failed, 1),
6044 (RunStatus::Gating, TaskStatus::Failed, 1),
6045 ];
6046 for (run, want, attempts) in table {
6047 let mut t = task();
6048 t.start("20260902-000000-aaaa".to_owned());
6049 settle(
6050 &mut t,
6051 Verdict {
6052 status: run,
6053 left_pr: false,
6054 parked: false,
6055 quota_hit: matches!(run, RunStatus::Stalled),
6056 no_viable_candidates: false,
6057 },
6058 "why",
6059 2,
6060 );
6061 assert_eq!(t.status, want, "task status after {}", label(run));
6062 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6063 }
6064 }
6065
6066 #[test]
6067 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6068 let mut stalled = task();
6069 stalled.start("20260902-000000-aaaa".to_owned());
6070 settle(
6071 &mut stalled,
6072 Verdict {
6073 status: RunStatus::Stalled,
6074 left_pr: false,
6075 parked: false,
6076 quota_hit: true,
6077 no_viable_candidates: false,
6078 },
6079 "quota",
6080 1,
6081 );
6082 assert_eq!(stalled.attempts, 0);
6083 assert!(
6084 stalled.status.runnable(),
6085 "a machine problem must leave the task in line"
6086 );
6087
6088 let mut blocked = task();
6089 blocked.start("20260902-000000-aaaa".to_owned());
6090 settle(
6091 &mut blocked,
6092 Verdict {
6093 status: RunStatus::Blocked,
6094 left_pr: false,
6095 parked: false,
6096 quota_hit: false,
6097 no_viable_candidates: false,
6098 },
6099 "findings open",
6100 1,
6101 );
6102 assert_eq!(blocked.attempts, 1);
6103 assert_eq!(
6104 blocked.status,
6105 TaskStatus::Held,
6106 "the last attempt hands the task to a human"
6107 );
6108 }
6109
6110 #[test]
6111 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6112 let mut delivered = task();
6115 delivered.start("20260903-080619-01c2".to_owned());
6116 settle(
6117 &mut delivered,
6118 Verdict {
6119 status: RunStatus::Blocked,
6120 left_pr: true,
6121 parked: false,
6122 quota_hit: false,
6123 no_viable_candidates: false,
6124 },
6125 "no check status",
6126 4,
6127 );
6128 assert_eq!(
6129 delivered.status,
6130 TaskStatus::Held,
6131 "a pull request waiting on CI or a person is not a retryable failure"
6132 );
6133 assert!(
6134 !delivered.status.runnable(),
6135 "the loop must not pick this task up again"
6136 );
6137 assert_eq!(
6138 delivered.last_error.as_deref(),
6139 Some("no check status"),
6140 "the operator needs to be told what the gate was waiting for"
6141 );
6142
6143 let mut empty_handed = task();
6146 empty_handed.start("20260903-080619-01c2".to_owned());
6147 settle(
6148 &mut empty_handed,
6149 Verdict {
6150 status: RunStatus::Blocked,
6151 left_pr: false,
6152 parked: false,
6153 quota_hit: false,
6154 no_viable_candidates: false,
6155 },
6156 "findings open",
6157 4,
6158 );
6159 assert_eq!(empty_handed.status, TaskStatus::Failed);
6160 assert!(empty_handed.status.runnable());
6161 }
6162
6163 #[test]
6164 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6165 let mut noop = task();
6171 noop.start("20260912-131304-391f".to_owned());
6172 settle(
6173 &mut noop,
6174 Verdict {
6175 status: RunStatus::VerifiedNoop,
6176 left_pr: false,
6177 parked: false,
6178 quota_hit: false,
6179 no_viable_candidates: true,
6180 },
6181 "candidate A: already fixed by b32cfc4, on main",
6182 4,
6183 );
6184 assert_eq!(
6185 noop.status,
6186 TaskStatus::Held,
6187 "an unverified claim is a request for a human, not a failure"
6188 );
6189 assert!(
6190 !noop.status.runnable(),
6191 "the loop must not requeue this on the same unverified claim"
6192 );
6193 assert_eq!(noop.attempts, 1);
6198 }
6199
6200 #[test]
6201 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6202 let mut parked = task();
6207 parked.start("20260903-183634-2d98".to_owned());
6208 settle(
6209 &mut parked,
6210 Verdict {
6211 status: RunStatus::Implementing,
6212 left_pr: false,
6213 quota_hit: false,
6214 parked: true,
6215 no_viable_candidates: false,
6216 },
6217 "parked after `implementing`",
6218 2,
6219 );
6220 assert_eq!(parked.attempts, 0, "a park is refunded");
6221 assert!(
6222 parked.status.runnable(),
6223 "and the task stays in line so the next loop resumes its run"
6224 );
6225 assert_eq!(parked.status, TaskStatus::Parked);
6226 assert_eq!(
6227 parked.park_reason.as_deref(),
6228 Some("parked after `implementing`"),
6229 "the card says where it stopped"
6230 );
6231 assert_eq!(parked.last_error, None, "nothing failed");
6232
6233 let mut broken = task();
6237 broken.start("20260903-183634-2d98".to_owned());
6238 settle(
6239 &mut broken,
6240 Verdict {
6241 status: RunStatus::Implementing,
6242 left_pr: false,
6243 quota_hit: false,
6244 parked: false,
6245 no_viable_candidates: false,
6246 },
6247 "returned mid-flight",
6248 2,
6249 );
6250 assert_eq!(broken.attempts, 1);
6251 }
6252
6253 #[test]
6254 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6255 let mut flaky = task();
6260 flaky.start("20260903-123023-e633".to_owned());
6261 settle(
6262 &mut flaky,
6263 Verdict {
6264 status: RunStatus::Stalled,
6265 left_pr: false,
6266 parked: false,
6267 quota_hit: false,
6268 no_viable_candidates: false,
6269 },
6270 "verdict rests on 1 of 3 judges",
6271 2,
6272 );
6273 assert_eq!(
6274 flaky.attempts, 1,
6275 "flakiness spends an attempt, so `max_attempts` still bounds it"
6276 );
6277 assert!(flaky.status.runnable(), "and it is still worth retrying");
6278
6279 let mut limited = task();
6281 limited.start("20260903-123023-e633".to_owned());
6282 settle(
6283 &mut limited,
6284 Verdict {
6285 status: RunStatus::Stalled,
6286 left_pr: false,
6287 parked: false,
6288 quota_hit: true,
6289 no_viable_candidates: false,
6290 },
6291 "judge-2, judge-3 out of quota",
6292 2,
6293 );
6294 assert_eq!(limited.attempts, 0, "a quota window is refunded");
6295 assert!(limited.status.runnable());
6296
6297 let mut worn = task();
6300 for _ in 0..2 {
6301 worn.release();
6302 }
6303 worn.start("20260903-123023-e633".to_owned());
6304 worn.attempts = 2;
6305 settle(
6306 &mut worn,
6307 Verdict {
6308 status: RunStatus::Stalled,
6309 left_pr: false,
6310 parked: false,
6311 quota_hit: false,
6312 no_viable_candidates: false,
6313 },
6314 "no quorum again",
6315 2,
6316 );
6317 assert_eq!(worn.status, TaskStatus::Held);
6318 assert!(!worn.status.runnable());
6319 }
6320
6321 #[test]
6322 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6323 let mut wiped_out = task();
6330 wiped_out.start("20260907-025000-a1b2".to_owned());
6331 settle(
6332 &mut wiped_out,
6333 Verdict {
6334 status: RunStatus::Failed,
6335 left_pr: false,
6336 parked: false,
6337 quota_hit: true,
6338 no_viable_candidates: true,
6339 },
6340 "no candidate produced a change; nothing to judge",
6341 2,
6342 );
6343 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6344 assert!(
6345 wiped_out.status.runnable(),
6346 "a machine problem must leave the task in line"
6347 );
6348
6349 let mut partial_progress = task();
6355 partial_progress.start("20260907-025500-c3d4".to_owned());
6356 settle(
6357 &mut partial_progress,
6358 Verdict {
6359 status: RunStatus::Failed,
6360 left_pr: false,
6361 parked: false,
6362 quota_hit: true,
6363 no_viable_candidates: false,
6364 },
6365 "gate failed on the winning candidate",
6366 2,
6367 );
6368 assert_eq!(
6369 partial_progress.attempts, 1,
6370 "a candidate that actually produced a change spends the attempt \
6371 even though some other seat hit its quota"
6372 );
6373 assert!(partial_progress.status.runnable());
6374 }
6375
6376 #[test]
6377 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6378 let mut t = task();
6384 t.start("20260907-025000-a1b2".to_owned());
6385 let mut state = run_state(RunStatus::Failed);
6386 state.quota.push(QuotaLoss {
6387 seat: "cand-a".to_owned(),
6388 node: "implement".to_owned(),
6389 at: Timestamp::now(),
6390 reset: None,
6391 });
6392 assert!(
6393 state.viable().is_empty(),
6394 "no candidate was added, so nothing is viable"
6395 );
6396 reclaim(&mut t, Some(state), 2, "en");
6397 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6398 assert!(t.status.runnable());
6399 }
6400
6401 #[test]
6402 fn a_held_task_is_never_offered_to_the_loop() {
6403 let dir = tempfile::tempdir().unwrap();
6404 let queue = Queue::at(dir.path().to_path_buf());
6405 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6406 let mut t = task();
6407 t.id = format!("2026090{n}-000000-000{n}");
6408 t.priority = priority;
6409 queue.put(&mut t).unwrap();
6410 }
6411 let mut held = task();
6412 held.id = "20260909-000000-9999".to_owned();
6413 held.priority = 99;
6414 held.hold_machine(None);
6415 queue.put(&mut held).unwrap();
6416
6417 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6418 assert_eq!(order.len(), 3);
6419 assert!(!order.contains(&held.id));
6420 assert_eq!(
6421 order.first().cloned(),
6422 queue.next_runnable().map(|t| t.id),
6423 "the loop's first candidate is exactly what the queue offers"
6424 );
6425 assert_eq!(
6426 order,
6427 vec![
6428 "20260902-000000-0002".to_owned(),
6429 "20260903-000000-0003".to_owned(),
6430 "20260901-000000-0001".to_owned(),
6431 ],
6432 "priority first, then oldest, so nothing starves"
6433 );
6434 }
6435
6436 #[test]
6437 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6438 let dir = tempfile::tempdir().unwrap();
6439 let queue = Queue::at(dir.path().to_path_buf());
6440 let mut old = task();
6441 old.id = "20260101-000000-old0".to_owned();
6442 queue.put(&mut old).unwrap();
6443 let mut fresh = task();
6444 fresh.id = "20260101-000000-new0".to_owned();
6445 queue.put(&mut fresh).unwrap();
6446
6447 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
6451 std::thread::sleep(Duration::from_millis(60));
6452 let live = queue.claim(&fresh.id).unwrap();
6453
6454 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6455 assert_eq!(swept, vec![old.id.clone()]);
6456 assert!(
6457 queue.claim(&old.id).is_ok(),
6458 "an unparseable lock older than the threshold is swept"
6459 );
6460 assert!(
6461 queue.claim(&fresh.id).is_err(),
6462 "a live pid protects its lock regardless of age"
6463 );
6464 drop(live);
6465 }
6466
6467 #[test]
6468 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
6469 let dir = tempfile::tempdir().unwrap();
6479 let queue = Queue::at(dir.path().to_path_buf());
6480 let mut t = task();
6481 t.id = "20260101-000000-live".to_owned();
6482 queue.put(&mut t).unwrap();
6483
6484 let claim = queue.claim(&t.id).unwrap();
6485 std::thread::sleep(Duration::from_millis(60));
6486
6487 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6488 assert!(
6489 swept.is_empty(),
6490 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
6491 );
6492 assert!(
6493 queue.claim(&t.id).is_err(),
6494 "the lock still protects its task"
6495 );
6496 drop(claim);
6497 }
6498
6499 fn injected_dead_pid() -> u32 {
6502 std::process::id().checked_add(1).unwrap_or(1)
6503 }
6504
6505 #[test]
6506 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
6507 let dir = tempfile::tempdir().unwrap();
6508 let queue = Queue::at(dir.path().to_path_buf());
6509 let mut t = task();
6510 t.id = "20260101-000000-dead".to_owned();
6511 queue.put(&mut t).unwrap();
6512 let dead_pid = injected_dead_pid();
6513
6514 std::fs::write(
6519 dir.path().join(format!("{}.lock", t.id)),
6520 dead_pid.to_string(),
6521 )
6522 .unwrap();
6523
6524 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6525 pid != dead_pid
6526 });
6527 assert_eq!(
6528 swept,
6529 vec![t.id.clone()],
6530 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
6531 );
6532 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
6533 }
6534
6535 #[test]
6536 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
6537 let dir = tempfile::tempdir().unwrap();
6538 let queue = Queue::at(dir.path().to_path_buf());
6539 let mut t = task();
6540 t.id = "20260101-000000-late".to_owned();
6541 queue.put(&mut t).unwrap();
6542 let dead_pid = injected_dead_pid();
6543
6544 assert!(
6547 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
6548 "nothing has claimed the task yet"
6549 );
6550
6551 std::fs::write(
6554 dir.path().join(format!("{}.lock", t.id)),
6555 dead_pid.to_string(),
6556 )
6557 .unwrap();
6558
6559 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6563 pid != dead_pid
6564 });
6565 assert_eq!(swept, vec![t.id.clone()]);
6566 }
6567
6568 #[test]
6569 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
6570 crate::run::pin_test_home();
6575 let dir = tempfile::tempdir().unwrap();
6576 let queue = Queue::at(dir.path().to_path_buf());
6577 let mut t = task();
6578 t.id = "20260101-000000-crsh".to_owned();
6579 t.status = TaskStatus::Running;
6580 t.attempts = 1;
6581 t.runs.push("20260904-000000-4043".to_owned());
6585 queue.put(&mut t).unwrap();
6586 let dead_pid = injected_dead_pid();
6587
6588 std::fs::write(
6591 dir.path().join(format!("{}.lock", t.id)),
6592 dead_pid.to_string(),
6593 )
6594 .unwrap();
6595
6596 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
6602 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6603
6604 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6605 pid != dead_pid
6606 });
6607 assert_eq!(swept, vec![t.id.clone()]);
6608
6609 let reclaimed = reclaim_orphaned_running(&queue, 2);
6610 assert_eq!(reclaimed, vec![t.id.clone()]);
6611 let after = queue.get(&t.id).unwrap();
6612 assert_eq!(
6613 after.status,
6614 TaskStatus::Held,
6615 "no run.json to recover from, so a human is asked"
6616 );
6617 assert_eq!(
6618 after.runs,
6619 vec!["20260904-000000-4043".to_owned()],
6620 "the crashed run's id is kept as evidence, not discarded"
6621 );
6622 }
6623
6624 #[test]
6625 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6626 let dir = tempfile::tempdir().unwrap();
6627 let queue = Queue::at(dir.path().to_path_buf());
6628 let mut t = task();
6629 t.id = "20260101-000000-unknown".to_owned();
6630 queue.put(&mut t).unwrap();
6631 let dead_pid = injected_dead_pid();
6632 std::fs::write(
6633 dir.path().join(format!("{}.lock", t.id)),
6634 dead_pid.to_string(),
6635 )
6636 .unwrap();
6637
6638 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
6639 assert!(swept.is_empty(), "an unknown pid must keep its lock");
6640 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
6641 }
6642
6643 fn run_state_in(status: RunStatus, language: &str) -> RunState {
6644 let mut s = run_state(status);
6645 s.config.graph.language = language.to_owned();
6646 s
6647 }
6648
6649 fn unstarted_verdict(status: RunStatus) -> Verdict {
6650 Verdict {
6651 status,
6652 left_pr: false,
6653 quota_hit: false,
6654 parked: false,
6655 no_viable_candidates: false,
6656 }
6657 }
6658
6659 #[test]
6660 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
6661 let mut t = task();
6662 t.attempts = 1;
6663 settle_in(
6664 &mut t,
6665 unstarted_verdict(RunStatus::AlreadyInBase),
6666 "already in main",
6667 1,
6668 phrases("en"),
6669 );
6670 assert_eq!(t.status, TaskStatus::Done);
6671 assert_eq!(t.attempts, 0);
6672 }
6673
6674 #[test]
6675 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
6676 let reason = |language: &str| {
6677 let mut t = task();
6678 settle_in(
6679 &mut t,
6680 unstarted_verdict(RunStatus::Judging),
6681 "boom",
6682 1,
6683 phrases(language),
6684 );
6685 t.last_error.or(t.hold_reason).unwrap_or_default()
6686 };
6687 assert!(
6688 reason("en").starts_with("the graph stopped at `"),
6689 "{}",
6690 reason("en")
6691 );
6692 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
6693 assert!(reason("日本語").contains("boom"));
6694 assert_eq!(reason("fr"), reason("en"));
6695 }
6696
6697 #[test]
6698 fn describe_follows_the_run_language_and_keeps_the_run_id() {
6699 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
6700 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
6701 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
6702 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
6703 assert!(ja.contains("[run "), "{ja}");
6704 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
6705 assert!(ended.starts_with("run 終了: "), "{ended}");
6706 let mut de = run_state_in(RunStatus::Failed, "de");
6707 let mut en = run_state_in(RunStatus::Failed, "en");
6708 de.id = "same".to_owned();
6709 en.id = "same".to_owned();
6710 assert_eq!(describe(&de), describe(&en));
6711 }
6712
6713 #[test]
6714 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
6715 use crate::handover::Refused;
6716 let cases = [
6717 Refused::Foreign {
6718 branch: "b".into(),
6719 path: "/w/x".into(),
6720 why: "made by hand".into(),
6721 },
6722 Refused::Unsafe {
6723 branch: "b".into(),
6724 path: "/w/x".into(),
6725 why: "its worktree has uncommitted changes (a.rs)".into(),
6726 },
6727 Refused::ReleaseFailed {
6728 branch: "b".into(),
6729 path: "/w/x".into(),
6730 run: "ab12".into(),
6731 },
6732 ];
6733 for r in &cases {
6734 let en = (phrases("en").handover_refused)(r);
6735 assert_eq!(en, r.to_string());
6736 let ja = (phrases("ja").handover_refused)(r);
6737 assert!(
6738 !ja.contains("is checked out") && !ja.contains("try again"),
6739 "{ja}"
6740 );
6741 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
6742 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
6743 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
6744 }
6745 }
6746 assert!(phrases("en").handover_hint.contains("release the task"));
6747 assert!(phrases("ja").handover_hint.contains("解放"));
6748 }
6749
6750 #[test]
6751 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
6752 let build = |lang: &str| {
6753 let mut s = run_state_in(RunStatus::Blocked, lang);
6754 s.id = "same".to_owned();
6755 s.config.graph.review_rounds = 3;
6756 let mut r = review_round(3);
6757 r.expected = 3;
6758 r.answered = 1;
6759 s.reviews.push(r);
6760 s.event(
6761 "review",
6762 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
6763 );
6764 s
6765 };
6766 let en = describe(&build("en"));
6767 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
6768 let ja = describe(&build("ja"));
6769 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
6770 assert!(!ja.contains("never answered"), "{ja}");
6771 assert!(ja.contains("[run "), "{ja}");
6772
6773 let mut failed = build("ja");
6776 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
6777 command: "cargo test".to_owned(),
6778 code: Some(1),
6779 output_tail: String::new(),
6780 duration_ms: 0,
6781 resource_blocked: false,
6782 });
6783 failed.event("review", "stopped; e2e failed: cargo test");
6784 let ja = describe(&failed);
6785 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
6786 assert!(!ja.contains("席のレビュアー"), "{ja}");
6787 }
6788
6789 #[test]
6790 fn refusals_and_recovery_prose_follow_the_language() {
6791 let t = held_task_with("r1");
6792 let q = action_question(
6793 "r1",
6794 ask::ChoiceAction::Resume {
6795 run: "r1".to_owned(),
6796 },
6797 );
6798 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
6799 ActionDecision::Refuse(s) => s,
6800 other => panic!("{other:?}"),
6801 };
6802 assert!(refuse(phrases("en")).contains("could not be read: gone"));
6803 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
6804 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
6805
6806 let mut held = task();
6807 reclaim(&mut held, None, 2, "ja");
6808 assert!(held.hold_reason.unwrap().contains("保留にしました"));
6809 let mut held = task();
6810 reclaim(&mut held, None, 2, "xx");
6811 assert!(held.hold_reason.unwrap().contains("held for a human"));
6812 }
6813
6814 fn run_state(status: RunStatus) -> RunState {
6815 let mut state = RunState::new(
6816 PathBuf::from("/repo"),
6817 "main".to_owned(),
6818 "abc1234def".to_owned(),
6819 "add retries".to_owned(),
6820 Config::default(),
6821 );
6822 state.status = status;
6823 state
6824 }
6825
6826 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
6827 Candidate {
6828 index: 0,
6829 label,
6830 agent: "claude".to_owned(),
6831 branch: format!("magi/x/{label}"),
6832 worktree: PathBuf::from("/repo"),
6833 summary: summary.to_owned(),
6834 stat: String::new(),
6835 files: 0,
6836 commits: usize::from(!empty),
6837 empty,
6838 failed: failed.map(str::to_owned),
6839 verified_noop: None,
6840 duration_ms: 0,
6841 folded: false,
6842 }
6843 }
6844
6845 #[test]
6846 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
6847 let mut state = run_state(RunStatus::Blocked);
6848 state.gate = vec![
6849 CommandOutcome {
6850 command: "cargo make check".to_owned(),
6851 code: Some(0),
6852 output_tail: "ok".to_owned(),
6853 duration_ms: 0,
6854 resource_blocked: false,
6855 },
6856 CommandOutcome {
6857 command: "cargo test".to_owned(),
6858 code: Some(101),
6859 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
6860 duration_ms: 0,
6861 resource_blocked: false,
6862 },
6863 ];
6864 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
6865 assert!(d.contains("cargo test"), "{d}");
6866 assert!(
6867 !d.contains("cargo make check"),
6868 "a passing check is not a diagnostic: {d}"
6869 );
6870 assert!(d.contains("assertion failed"), "{d}");
6871 }
6872
6873 #[test]
6874 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
6875 let mut state = run_state(RunStatus::Blocked);
6876 state.event(
6877 "land",
6878 "stopped: the fixer produced no commit while 2 check(s) were failing \
6879 (build, lint); stopping instead of looping on an unchanged tree",
6880 );
6881 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
6882 assert!(d.contains("build"), "{d}");
6883 assert!(d.contains("lint"), "{d}");
6884 assert!(d.contains("fixer produced no commit"), "{d}");
6885 }
6886
6887 #[test]
6888 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
6889 let state = run_state(RunStatus::VerifiedNoop);
6894 let d = describe(&state);
6895 assert!(
6896 d.contains("agent-verified no-op"),
6897 "expected the display label, not the wire spelling: {d}"
6898 );
6899 assert!(!d.contains("verified_noop"), "{d}");
6900 }
6901
6902 #[test]
6903 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
6904 let mut state = run_state(RunStatus::Failed);
6910 state.candidates = vec![candidate(
6911 'A',
6912 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
6913 true,
6914 None,
6915 )];
6916 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
6917 assert!(d.contains("candidate A"), "{d}");
6918 assert!(d.contains("tagged v1.2.3"), "{d}");
6919 }
6920
6921 #[test]
6922 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
6923 let mut state = run_state(RunStatus::Failed);
6924 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
6925 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
6926 assert!(d.contains("candidate A"), "{d}");
6927 assert!(d.contains("agent timed out"), "{d}");
6928 }
6929
6930 #[test]
6931 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
6932 let mut state = run_state(RunStatus::Failed);
6935 state.candidates = vec![candidate('A', "did the work", false, None)];
6936 assert!(diagnostic(&state).is_none());
6937 }
6938
6939 #[test]
6940 fn diagnostic_is_bounded_however_much_a_run_printed() {
6941 let mut state = run_state(RunStatus::Blocked);
6942 state.gate = vec![
6943 CommandOutcome {
6944 command: "cargo test".to_owned(),
6945 code: Some(101),
6946 output_tail: "x".repeat(50_000),
6947 duration_ms: 0,
6948 resource_blocked: false,
6949 },
6950 CommandOutcome {
6951 command: "cargo clippy".to_owned(),
6952 code: Some(1),
6953 output_tail: "y".repeat(50_000),
6954 duration_ms: 0,
6955 resource_blocked: false,
6956 },
6957 ];
6958 state.candidates = vec![
6959 candidate('A', &"z".repeat(50_000), true, None),
6960 candidate('B', &"w".repeat(50_000), true, None),
6961 ];
6962 let d = diagnostic(&state).expect("plenty here to diagnose");
6963 assert!(
6964 d.len() <= DIAGNOSTIC_MAX,
6965 "diagnostic grew to {} bytes, unbounded",
6966 d.len()
6967 );
6968 }
6969
6970 #[test]
6971 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
6972 let mut state = run_state(RunStatus::Blocked);
6973 state.gate = vec![CommandOutcome {
6974 command: "cargo test".to_owned(),
6975 code: Some(101),
6976 output_tail: "assertion failed".to_owned(),
6977 duration_ms: 0,
6978 resource_blocked: false,
6979 }];
6980 let verdict = Verdict {
6981 status: RunStatus::Blocked,
6982 left_pr: false,
6983 quota_hit: false,
6984 parked: false,
6985 no_viable_candidates: false,
6986 };
6987
6988 let mut t = task();
6991 t.start("run-1".to_owned());
6992 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6993 assert_eq!(t.status, TaskStatus::Failed);
6994 assert!(t.diagnostic.is_none());
6995
6996 t.start("run-2".to_owned());
6999 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7000 assert_eq!(t.status, TaskStatus::Held);
7001 let d = t.diagnostic.expect("a held task must carry its diagnostic");
7002 assert!(d.contains("cargo test"), "{d}");
7003 }
7004
7005 #[test]
7006 fn a_held_task_names_the_open_question_it_is_waiting_on() {
7007 crate::run::pin_test_home();
7012 let home = crate::run::home();
7013 let state = run_state(RunStatus::VerifiedNoop);
7014 let mut q = ask::Question::new(
7015 state.id.clone(),
7016 "implement".to_owned(),
7017 "impl-A".to_owned(),
7018 "is this really a no-op?".to_owned(),
7019 String::new(),
7020 Vec::new(),
7021 );
7022 Questions::at(home.join("questions")).put(&mut q).unwrap();
7023
7024 let verdict = Verdict {
7025 status: RunStatus::VerifiedNoop,
7026 left_pr: false,
7027 quota_hit: false,
7028 parked: false,
7029 no_viable_candidates: false,
7030 };
7031 let mut t = task();
7032 t.start(state.id.clone());
7033 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7034
7035 assert_eq!(t.status, TaskStatus::Held);
7036 let reason = t.hold_reason.expect("a held task must record why");
7037 assert!(
7038 reason.starts_with("run ended agent-verified no-op"),
7039 "the original settle reason must survive unchanged: {reason}"
7040 );
7041 assert!(
7042 reason.contains(q.short()),
7043 "the open question's id must be named so the notice is actionable: {reason}"
7044 );
7045 }
7046
7047 #[test]
7048 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7049 crate::run::pin_test_home();
7050 let state = run_state(RunStatus::VerifiedNoop);
7051
7052 let verdict = Verdict {
7053 status: RunStatus::VerifiedNoop,
7054 left_pr: false,
7055 quota_hit: false,
7056 parked: false,
7057 no_viable_candidates: false,
7058 };
7059 let mut t = task();
7060 t.start(state.id.clone());
7061 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7062
7063 assert_eq!(t.status, TaskStatus::Held);
7064 assert_eq!(
7065 t.hold_reason.as_deref(),
7066 Some("run ended agent-verified no-op"),
7067 "nothing to append when the question was already answered or never asked"
7068 );
7069 }
7070
7071 #[test]
7072 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7073 crate::run::pin_test_home();
7074 let mut first = run_state(RunStatus::Blocked);
7075 first.id = "20260101-000000-sup1".to_owned();
7076 first.save().unwrap();
7077 let mut second = run_state(RunStatus::Merged);
7078 second.id = "20260101-000000-sup2".to_owned();
7079 second.save().unwrap();
7080
7081 let mut t = task();
7082 t.runs = vec![first.id.clone(), second.id.clone()];
7083 t.status = TaskStatus::Done;
7084
7085 supersede_prior_runs(&t, &crate::run::home());
7086
7087 assert_eq!(
7088 RunState::load(&first.id).unwrap().status,
7089 RunStatus::Superseded,
7090 "the first attempt's Blocked no longer needs anyone's attention"
7091 );
7092 assert_eq!(
7093 RunState::load(&second.id).unwrap().status,
7094 RunStatus::Merged,
7095 "the run that actually succeeded is left exactly as it was"
7096 );
7097 }
7098
7099 #[test]
7100 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7101 crate::run::pin_test_home();
7107 let mut first = run_state(RunStatus::Blocked);
7108 first.id = "20260101-000000-sup9".to_owned();
7109 first.driver_pid = Some(std::process::id());
7112 first.driver_started_at = Some(
7113 crate::proc::process_started_at(std::process::id())
7114 .expect("this test process's own start time must be queryable"),
7115 );
7116 first.save().unwrap();
7117 let mut second = run_state(RunStatus::Merged);
7118 second.id = "20260101-000000-supa".to_owned();
7119 second.save().unwrap();
7120
7121 let mut t = task();
7122 t.runs = vec![first.id.clone(), second.id.clone()];
7123 t.status = TaskStatus::Done;
7124
7125 supersede_prior_runs(&t, &crate::run::home());
7126
7127 assert_eq!(
7128 RunState::load(&first.id).unwrap().status,
7129 RunStatus::Blocked,
7130 "a live driver_pid means something is still actually working this run, \
7131 even though no daemon claims it - rewriting under it would just be \
7132 undone the next time that process saves"
7133 );
7134 }
7135
7136 #[test]
7137 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7138 let dir = tempfile::tempdir().unwrap();
7144 let home = dir.path().to_path_buf();
7145 let queue = Queue::at(dir.path().join("queue"));
7146
7147 let mut first = run_state(RunStatus::Blocked);
7148 first.id = "20260101-000000-supd".to_owned();
7149 first.driver_pid = Some(std::process::id());
7150 first.driver_started_at = Some(
7151 crate::proc::process_started_at(std::process::id())
7152 .expect("this test process's own start time must be queryable"),
7153 );
7154 first.save_under(&home).unwrap();
7155 let mut second = run_state(RunStatus::Merged);
7156 second.id = "20260101-000000-supe".to_owned();
7157 second.save_under(&home).unwrap();
7158
7159 let mut t = task();
7160 t.runs = vec![first.id.clone(), second.id.clone()];
7161 t.status = TaskStatus::Done;
7162 queue.put(&mut t).unwrap();
7163
7164 resweep_superseded_attempts(&queue, &home);
7165 assert_eq!(
7166 RunState::load_under(&first.id, &home).unwrap().status,
7167 RunStatus::Blocked,
7168 "still live on the first pass, so still untouched"
7169 );
7170
7171 let mut stale = RunState::load_under(&first.id, &home).unwrap();
7177 stale.driver_started_at = Some("1".to_owned());
7178 stale.save_under(&home).unwrap();
7179
7180 resweep_superseded_attempts(&queue, &home);
7181 assert_eq!(
7182 RunState::load_under(&first.id, &home).unwrap().status,
7183 RunStatus::Superseded,
7184 "the second pass catches up what the first one correctly skipped"
7185 );
7186 }
7187
7188 #[test]
7189 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7190 crate::run::pin_test_home();
7191 let mut first = run_state(RunStatus::Blocked);
7192 first.id = "20260101-000000-sup3".to_owned();
7193 first.save().unwrap();
7194 let mut second = run_state(RunStatus::Blocked);
7195 second.id = "20260101-000000-sup4".to_owned();
7196 second.save().unwrap();
7197
7198 let mut t = task();
7199 t.runs = vec![first.id.clone(), second.id.clone()];
7200 t.status = TaskStatus::Failed;
7204
7205 supersede_prior_runs(&t, &crate::run::home());
7206
7207 assert_eq!(
7208 RunState::load(&first.id).unwrap().status,
7209 RunStatus::Blocked
7210 );
7211 assert_eq!(
7212 RunState::load(&second.id).unwrap().status,
7213 RunStatus::Blocked
7214 );
7215 }
7216
7217 #[test]
7218 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7219 crate::run::pin_test_home();
7223 let mut first = run_state(RunStatus::Blocked);
7224 first.id = "20260101-000000-sup5".to_owned();
7225 first.save().unwrap();
7226
7227 let mut t = task();
7228 t.runs = vec![first.id.clone()];
7229 t.status = TaskStatus::Done;
7230
7231 supersede_prior_runs(&t, &crate::run::home());
7232
7233 assert_eq!(
7234 RunState::load(&first.id).unwrap().status,
7235 RunStatus::Blocked,
7236 "a single-attempt task has no earlier run to supersede"
7237 );
7238 }
7239
7240 #[test]
7241 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7242 crate::run::pin_test_home();
7249 let mut first = run_state(RunStatus::Blocked);
7250 first.id = "20260101-000000-supb".to_owned();
7251 first.save().unwrap();
7252 let mut second = run_state(RunStatus::Failed);
7253 second.id = "20260101-000000-supc".to_owned();
7254 second.save().unwrap();
7255
7256 let mut t = task();
7257 t.runs = vec![first.id.clone(), second.id.clone()];
7258 t.status = TaskStatus::Done;
7259
7260 supersede_prior_runs(&t, &crate::run::home());
7261
7262 assert_eq!(
7263 RunState::load(&first.id).unwrap().status,
7264 RunStatus::Blocked,
7265 "the task's last attempt never landed, so there is nothing here \
7266 actually superseding it"
7267 );
7268 }
7269
7270 #[test]
7271 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7272 crate::run::pin_test_home();
7276 let mut failed = run_state(RunStatus::Failed);
7277 failed.id = "20260101-000000-sup6".to_owned();
7278 failed.save().unwrap();
7279 let mut noop = run_state(RunStatus::VerifiedNoop);
7280 noop.id = "20260101-000000-sup7".to_owned();
7281 noop.save().unwrap();
7282 let mut winner = run_state(RunStatus::Ready);
7283 winner.id = "20260101-000000-sup8".to_owned();
7284 winner.save().unwrap();
7285
7286 let mut t = task();
7287 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7288 t.status = TaskStatus::Done;
7289
7290 supersede_prior_runs(&t, &crate::run::home());
7291
7292 assert_eq!(
7293 RunState::load(&failed.id).unwrap().status,
7294 RunStatus::Failed
7295 );
7296 assert_eq!(
7297 RunState::load(&noop.id).unwrap().status,
7298 RunStatus::VerifiedNoop
7299 );
7300 }
7301
7302 fn approval_question(run: &str) -> ask::Question {
7303 ask::Question::new(
7304 run.to_owned(),
7305 land::APPROVAL_NODE.to_owned(),
7306 "land".to_owned(),
7307 "merge?".to_owned(),
7308 String::new(),
7309 vec!["merge".to_owned(), "hold".to_owned()],
7310 )
7311 }
7312
7313 #[test]
7314 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7315 crate::run::pin_test_home();
7316 let mut state = run_state(RunStatus::Landing);
7317 state.id = "20260101-000000-fre1".to_owned();
7318 state.parked = true;
7319 state.save().unwrap();
7320 ask::Questions::open()
7321 .put(&mut approval_question(&state.id))
7322 .unwrap();
7323
7324 let mut t = task();
7325 t.runs.push(state.id.clone());
7326 assert_eq!(
7327 land_resume_state(&t),
7328 LandResume::StillWaiting,
7329 "nobody has answered and the timeout has not passed"
7330 );
7331 }
7332
7333 #[test]
7334 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7335 crate::run::pin_test_home();
7336 let mut state = run_state(RunStatus::Gating);
7337 state.id = "20260101-000000-gt01".to_owned();
7338 state.parked = true;
7339 state.config.graph.answer_timeout = 60;
7340 state.github_text = Some(crate::run::GithubTextAsk {
7341 rewrite: None,
7342 fingerprint: "f".into(),
7343 title: true,
7344 body: false,
7345 categories: vec!["title-language".into()],
7346 question: None,
7347 asks: 1,
7348 resolved: false,
7349 chosen_title: None,
7350 choice: None,
7351 });
7352 state.save().unwrap();
7353 let store = ask::Questions::open();
7354 let mut q = ask::Question::new(
7355 state.id.clone(),
7356 crate::github_text::ASK_NODE.to_owned(),
7357 crate::github_text::ASK_SEAT.to_owned(),
7358 "s".into(),
7359 String::new(),
7360 vec!["use fallback".into()],
7361 );
7362 store.put(&mut q).unwrap();
7363 let mut t = task();
7364 t.runs.push(state.id.clone());
7365 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7366 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7367 store.put(&mut q).unwrap();
7368 assert_eq!(land_resume_state(&t), LandResume::Ready);
7369 assert!(!store.get(&q.id).unwrap().status.open());
7370 state.github_text.as_mut().unwrap().resolved = true;
7372 state.save().unwrap();
7373 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7374 }
7375
7376 #[test]
7377 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7378 crate::run::pin_test_home();
7383 let mut state = run_state(RunStatus::Landing);
7384 state.id = "20260101-000000-exp1".to_owned();
7385 state.parked = true;
7386 state.config.graph.answer_timeout = 60;
7387 state.save().unwrap();
7388
7389 let store = ask::Questions::open();
7390 let mut q = approval_question(&state.id);
7391 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7392 store.put(&mut q).unwrap();
7393
7394 let mut t = task();
7395 t.runs.push(state.id.clone());
7396 assert_eq!(
7397 land_resume_state(&t),
7398 LandResume::Ready,
7399 "an expired question must not be waited on forever"
7400 );
7401
7402 let after = store.get(&q.id).unwrap();
7403 assert!(
7404 !after.status.open(),
7405 "the question is abandoned, not silently ignored"
7406 );
7407 assert!(
7408 after.resolution().is_none(),
7409 "an abandoned question is not read as a decision"
7410 );
7411 }
7412
7413 #[test]
7414 fn reclaim_settles_a_running_task_against_its_last_run() {
7415 let mut t = task();
7416 t.start("20260904-000000-4043".to_owned());
7417 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
7418 assert_eq!(
7419 t.status,
7420 TaskStatus::Done,
7421 "a run that actually finished must not stay `running` forever"
7422 );
7423 }
7424
7425 #[test]
7426 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
7427 let mut t = task();
7428 t.start("20260904-000000-4043".to_owned());
7429 t.last_error = Some("earlier trouble".to_owned());
7430 let mut state = run_state(RunStatus::Judging);
7431 state.parked = true;
7432 reclaim(&mut t, Some(state), 1, "en");
7433 assert_eq!(t.status, TaskStatus::Parked);
7434 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
7435 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7436 assert!(t.park_reason.is_some());
7437 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
7438 assert!(!t.fresh_start);
7439 assert!(t.status.runnable());
7440 }
7441
7442 #[test]
7443 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
7444 let mut t = task();
7445 t.start("20260904-000000-4043".to_owned());
7446 t.last_error = Some("earlier trouble".to_owned());
7447 settle(
7448 &mut t,
7449 Verdict {
7450 status: RunStatus::Judging,
7451 left_pr: false,
7452 quota_hit: false,
7453 parked: true,
7454 no_viable_candidates: false,
7455 },
7456 "parked after `judging`",
7457 1,
7458 );
7459 assert_eq!(t.status, TaskStatus::Parked);
7460 assert_eq!(t.attempts, 0);
7461 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7462 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
7463 assert_eq!(t.schema, crate::queue::SCHEMA);
7464 assert!(
7465 crate::notices::task_held(&t).is_none(),
7466 "a park is not news"
7467 );
7468 t.start("20260904-000000-4043".to_owned());
7469 assert_eq!(t.park_reason, None);
7470 }
7471
7472 #[test]
7473 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
7474 let mut t = task();
7478 t.start("20260904-000000-4043".to_owned());
7479 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
7480 assert_eq!(t.status, TaskStatus::Failed);
7481 assert!(t.status.runnable());
7482 }
7483
7484 #[test]
7485 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
7486 let mut t = task();
7487 t.start("20260904-000000-4043".to_owned());
7488 assert_eq!(t.attempts, 1);
7489 let mut run = run_state(RunStatus::Implementing);
7490 run.id = "20260904-000000-4043".to_owned();
7491 run.begin_pass();
7492 let cause = crate::run::ParkCause::Upgrade {
7493 from: "0.121.0".to_owned(),
7494 to: Some("0.121.1".to_owned()),
7495 };
7496 run.end_pass_parked(cause.clone());
7497 run.parked = true;
7498 let verdict = Verdict {
7499 status: run.status,
7500 left_pr: false,
7501 quota_hit: false,
7502 parked: true,
7503 no_viable_candidates: false,
7504 };
7505 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
7506 assert_eq!(t.attempts, 0);
7507 assert_eq!(t.passes.len(), 1);
7508 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7509 assert_eq!(t.passes[0].parked, Some(cause));
7510 assert_eq!(t.passes[0].pass_index, 0);
7511
7512 t.start("20260904-000000-4043".to_owned());
7515 run.begin_pass();
7516 run.status = RunStatus::Failed;
7517 let verdict = Verdict {
7518 status: RunStatus::Failed,
7519 left_pr: false,
7520 quota_hit: false,
7521 parked: false,
7522 no_viable_candidates: false,
7523 };
7524 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
7525 assert_eq!(t.passes.len(), 2);
7526 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7527 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
7528 assert_eq!(t.passes[1].pass_index, 1);
7529 assert_eq!(t.attempts, 1);
7530 }
7531
7532 #[test]
7533 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
7534 let mut t = task();
7535 t.start("20260904-000000-4043".to_owned());
7536 reclaim(&mut t, None, 2, "en");
7537 assert_eq!(t.status, TaskStatus::Held);
7538 assert!(
7539 t.last_error
7540 .as_deref()
7541 .is_some_and(|e| e.contains("running")),
7542 "the operator needs to know why this task was held"
7543 );
7544 }
7545
7546 #[test]
7547 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
7548 let dir = tempfile::tempdir().unwrap();
7549 let queue = Queue::at(dir.path().to_path_buf());
7550
7551 let mut orphaned = task();
7553 orphaned.id = "20260904-000000-orph".to_owned();
7554 orphaned.status = TaskStatus::Running;
7555 orphaned.attempts = 1;
7556 queue.put(&mut orphaned).unwrap();
7557
7558 let mut alive = task();
7559 alive.id = "20260904-000000-live".to_owned();
7560 alive.status = TaskStatus::Running;
7561 alive.attempts = 1;
7562 queue.put(&mut alive).unwrap();
7563 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
7564
7565 let mut queued = task();
7566 queued.id = "20260904-000000-wait".to_owned();
7567 queue.put(&mut queued).unwrap();
7568
7569 let reclaimed = reclaim_orphaned_running(&queue, 2);
7570 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
7571
7572 assert_eq!(
7573 queue.get(&orphaned.id).unwrap().status,
7574 TaskStatus::Held,
7575 "nothing was driving it and there was no run to recover"
7576 );
7577 assert_eq!(
7578 queue.get(&alive.id).unwrap().status,
7579 TaskStatus::Running,
7580 "a live claim must protect the task it belongs to"
7581 );
7582 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
7583 }
7584
7585 fn read_run_under(home: &Path, id: &str) -> RunState {
7591 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
7592 serde_json::from_str(&body).unwrap()
7593 }
7594
7595 #[test]
7596 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
7597 let dir = tempfile::tempdir().unwrap();
7598 let home = dir.path().to_path_buf();
7599 let now = Timestamp::now();
7600 let overrun_seat = || crate::run::ActiveSeat {
7601 node: "implement".to_owned(),
7602 started_at: now - jiff::SignedDuration::new(21_000, 0),
7603 timeout_secs: 3_600,
7604 attempt: 0,
7605 task: None,
7606 command: None,
7607 index: None,
7608 total: None,
7609 };
7610
7611 let mut dead = run_state(RunStatus::Implementing);
7612 dead.id = "20260101-000000-dead".to_owned();
7613 dead.active.insert("impl-A".to_owned(), overrun_seat());
7614 dead.driver_pid = Some(4242);
7617 dead.save_under(&home).unwrap();
7618
7619 let mut alive = run_state(RunStatus::Implementing);
7622 alive.id = "20260101-000000-aliv".to_owned();
7623 alive.active.insert("impl-A".to_owned(), overrun_seat());
7624 alive.save_under(&home).unwrap();
7625 let mut status = Status::new();
7626 status.current = vec![Current {
7627 task: "20260101-000000-task".to_owned(),
7628 run: alive.id.clone(),
7629 }];
7630 write_status_to(&home.join("daemon.json"), &status).unwrap();
7631
7632 let questions = Questions::at(home.join("questions"));
7636 let mut q = ask::Question::new(
7637 dead.id.clone(),
7638 "implement".to_owned(),
7639 "impl-A".to_owned(),
7640 "Which storage backend?".to_owned(),
7641 String::new(),
7642 vec!["SQLite".to_owned(), "Redis".to_owned()],
7643 );
7644 questions.put(&mut q).unwrap();
7645
7646 let abandoned = reclaim_abandoned_runs_with(
7647 &home,
7648 now,
7649 |pid| if pid == 4242 { Some(false) } else { None },
7650 |_| panic!("a query answering Dead outright needs no identity corroboration"),
7651 );
7652 assert_eq!(abandoned, vec![dead.id.clone()]);
7653
7654 let reloaded = read_run_under(&home, &dead.id);
7655 assert_eq!(reloaded.status, RunStatus::Failed);
7656 assert!(reloaded.active.is_empty());
7657 assert!(
7658 !questions.get(&q.id).unwrap().status.open(),
7659 "the failed run's own open question must be settled in the same pass"
7660 );
7661
7662 let still_alive = read_run_under(&home, &alive.id);
7663 assert_eq!(
7664 still_alive.status,
7665 RunStatus::Implementing,
7666 "a live daemon's claim protects it"
7667 );
7668 assert!(!still_alive.active.is_empty());
7669 }
7670
7671 #[test]
7681 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
7682 let dir = tempfile::tempdir().unwrap();
7683 let home = dir.path().to_path_buf();
7684 let now = Timestamp::now();
7685
7686 let mut manual = run_state(RunStatus::Reviewing);
7687 manual.id = "20260101-000000-manl".to_owned();
7688 manual.active.insert(
7689 "review-1".to_owned(),
7690 crate::run::ActiveSeat {
7691 node: "review".to_owned(),
7692 started_at: now - jiff::SignedDuration::new(21_000, 0),
7693 timeout_secs: 3_600,
7694 attempt: 0,
7695 task: None,
7696 command: None,
7697 index: None,
7698 total: None,
7699 },
7700 );
7701 manual.driver_pid = Some(4242);
7705 manual.driver_started_at = Some("1790000000".to_owned());
7706 manual.save_under(&home).unwrap();
7707
7708 let abandoned = reclaim_abandoned_runs_with(
7709 &home,
7710 now,
7711 |pid| if pid == 4242 { Some(true) } else { None },
7712 |pid| {
7713 if pid == 4242 {
7714 Some("1790000000".to_owned())
7715 } else {
7716 None
7717 }
7718 },
7719 );
7720 assert!(
7721 abandoned.is_empty(),
7722 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
7723 );
7724
7725 let reloaded = read_run_under(&home, &manual.id);
7726 assert_eq!(reloaded.status, RunStatus::Reviewing);
7727 assert!(!reloaded.active.is_empty());
7728 }
7729
7730 #[test]
7731 fn an_already_claimed_task_is_skipped_rather_than_failed() {
7732 let dir = tempfile::tempdir().unwrap();
7733 let queue = Queue::at(dir.path().to_path_buf());
7734 let mut only = task();
7735 queue.put(&mut only).unwrap();
7736
7737 let _elsewhere = queue.claim(&only.id).unwrap();
7738 let candidates = runnable(&queue);
7739 assert_eq!(candidates.len(), 1, "the task is still runnable");
7740 assert!(
7741 queue.claim(&candidates[0].id).is_err(),
7742 "the loop cannot take a claim somebody else holds"
7743 );
7744
7745 let after = queue.get(&only.id).unwrap();
7746 assert_eq!(after.status, TaskStatus::Queued);
7747 assert_eq!(
7748 after.attempts, 0,
7749 "losing the race is not an attempt at the task"
7750 );
7751 assert_eq!(after.last_error, None);
7752 }
7753
7754 #[test]
7755 fn the_status_file_round_trips_and_its_heartbeat_advances() {
7756 let dir = tempfile::tempdir().unwrap();
7757 let path = dir.path().join("daemon.json");
7758
7759 let mut status = Status::new();
7760 status.idle = false;
7761 status.completed = 7;
7762 status.current = vec![Current {
7763 task: "20260902-000000-t111".to_owned(),
7764 run: "20260902-000001-r111".to_owned(),
7765 }];
7766 write_status_to(&path, &status).unwrap();
7767 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7768 assert_eq!(first.schema, SCHEMA);
7769 assert_eq!(first.pid, std::process::id());
7770 assert!(!first.idle);
7771 assert_eq!(first.completed, 7);
7772 assert_eq!(first.current, status.current);
7773 assert!(
7774 !path.with_extension("json.tmp").exists(),
7775 "the temp file is renamed, not left behind"
7776 );
7777
7778 std::thread::sleep(Duration::from_millis(5));
7779 status.updated_at = Timestamp::now();
7780 status.polls = 3;
7781 write_status_to(&path, &status).unwrap();
7782 let second: Status =
7783 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7784 assert!(
7785 second.updated_at > first.updated_at,
7786 "a reader can only detect staleness if the heartbeat moves"
7787 );
7788 assert_eq!(
7789 second.started_at, first.started_at,
7790 "the start time is not a heartbeat"
7791 );
7792 assert_eq!(second.polls, 3);
7793 }
7794
7795 #[test]
7796 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
7797 let dir = tempfile::tempdir().unwrap();
7798
7799 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
7800
7801 let mut status = Status::new();
7802 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
7803 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7804 let stale = read_status(dir.path()).unwrap();
7805 assert!(
7806 !stale.running(Timestamp::now()),
7807 "a minute without a heartbeat is a dead daemon, not a busy one"
7808 );
7809 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
7810
7811 status.updated_at = Timestamp::now();
7812 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7813 let fresh = read_status(dir.path()).unwrap();
7814 assert!(fresh.running(Timestamp::now()));
7815 }
7816
7817 #[test]
7818 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
7819 let dir = tempfile::tempdir().unwrap();
7820 let now = Timestamp::now();
7821 let mine = "20260903-080619-01c2";
7822
7823 assert!(
7824 !is_working_on(dir.path(), mine, now),
7825 "no status file means nobody is working on anything"
7826 );
7827
7828 let mut status = Status::new();
7829 status.current = vec![Current {
7830 task: "20260903-080340-0167".to_owned(),
7831 run: mine.to_owned(),
7832 }];
7833 status.updated_at = now;
7834 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7835 assert!(is_working_on(dir.path(), mine, now));
7836 assert!(
7837 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
7838 "a daemon busy with one run is not working on another"
7839 );
7840
7841 status.updated_at = now - jiff::SignedDuration::from_secs(600);
7844 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7845 assert!(
7846 !is_working_on(dir.path(), mine, now),
7847 "a stale heartbeat is a dead daemon, so its run is a leftover"
7848 );
7849 }
7850
7851 #[test]
7852 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
7853 let dir = tempfile::tempdir().unwrap();
7854 let now = Timestamp::now();
7855
7856 assert!(
7857 !is_working_on_short(dir.path(), "01c2", now),
7858 "no status file means nobody is working on anything"
7859 );
7860
7861 let mut status = Status::new();
7862 status.current = vec![Current {
7863 task: "20260903-080340-0167".to_owned(),
7864 run: "20260903-080619-01c2".to_owned(),
7865 }];
7866 status.updated_at = now;
7867 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7868 assert!(
7869 is_working_on_short(dir.path(), "01c2", now),
7870 "the run's short id is the last block of its full id"
7871 );
7872 assert!(
7873 !is_working_on_short(dir.path(), "3cbf", now),
7874 "a daemon busy with one worktree bay is not working on another"
7875 );
7876 }
7877
7878 #[test]
7879 fn a_newer_status_file_still_yields_a_reading() {
7880 let dir = tempfile::tempdir().unwrap();
7881 std::fs::write(
7884 dir.path().join("daemon.json"),
7885 serde_json::json!({
7886 "schema": 2,
7887 "updated_at": Timestamp::now().to_string(),
7888 "idle": true,
7889 "surprise": { "nested": [1, 2, 3] },
7890 })
7891 .to_string(),
7892 )
7893 .unwrap();
7894
7895 let reading = read_status(dir.path()).expect("a forward-compatible read");
7896 assert!(reading.running(Timestamp::now()));
7897 assert!(reading.idle);
7898 assert!(reading.current.is_empty());
7899 }
7900
7901 #[test]
7902 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
7903 let dir = tempfile::tempdir().unwrap();
7909 std::fs::write(
7910 dir.path().join("daemon.json"),
7911 serde_json::json!({
7912 "schema": 1,
7913 "pid": 4242,
7914 "updated_at": Timestamp::now().to_string(),
7915 "idle": false,
7916 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
7917 "completed": 3,
7918 "polls": 9,
7919 })
7920 .to_string(),
7921 )
7922 .unwrap();
7923
7924 let reading = read_status(dir.path()).expect("an older shape must still parse");
7925 assert!(reading.running(Timestamp::now()));
7926 assert_eq!(
7927 reading.current,
7928 vec![Current {
7929 task: "20260902-140501-aaaa".to_owned(),
7930 run: "20260902-140502-bbbb".to_owned(),
7931 }]
7932 );
7933 }
7934
7935 #[test]
7936 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
7937 let dir = tempfile::tempdir().unwrap();
7938 std::fs::write(
7939 dir.path().join("daemon.json"),
7940 serde_json::json!({
7941 "schema": 1,
7942 "updated_at": Timestamp::now().to_string(),
7943 "idle": true,
7944 "current": null,
7945 })
7946 .to_string(),
7947 )
7948 .unwrap();
7949 let with_null = read_status(dir.path()).expect("null must still parse");
7950 assert!(with_null.current.is_empty());
7951
7952 std::fs::write(
7953 dir.path().join("daemon.json"),
7954 serde_json::json!({
7955 "schema": 1,
7956 "updated_at": Timestamp::now().to_string(),
7957 "idle": true,
7958 })
7959 .to_string(),
7960 )
7961 .unwrap();
7962 let absent = read_status(dir.path()).expect("a missing field must still parse");
7963 assert!(absent.current.is_empty());
7964 }
7965
7966 #[test]
7967 fn a_task_without_a_repository_runs_in_the_daemons_default() {
7968 let fallback = Path::new("/default");
7969 let mut blank = task();
7970 blank.repo = PathBuf::new();
7971 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
7972 let mut dot = task();
7973 dot.repo = PathBuf::from(".");
7974 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
7975 assert_eq!(
7976 repo_for(&task(), fallback),
7977 PathBuf::from("/repo"),
7978 "a task that names a repository keeps it"
7979 );
7980 }
7981
7982 #[test]
7983 fn task_implementers_edit_inherits_daemon_config_and_merge() {
7984 let dir = tempfile::tempdir().unwrap();
7985 let path = dir.path().join("explicit.toml");
7986 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
7987 let opts = Opts {
7988 config: Some(path),
7989 merge: Some("none".into()),
7990 ..Default::default()
7991 };
7992 let mut t = task();
7993 t.set_implementers(
7994 2,
7995 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7996 .unwrap(),
7997 )
7998 .unwrap();
7999 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8000 assert_eq!(cfg.graph.implementers, 2);
8001 assert_eq!(cfg.graph.judges, 1);
8002 assert_eq!(cfg.merge.mode, MergeMode::None);
8003 t.set_implementers(1, &cfg).unwrap();
8004 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8005 apply_task_implementers(&mut cfg, &t);
8006 assert_eq!(cfg.graph.implementers, 1);
8007 assert_eq!(cfg.graph.judges, 1);
8008 assert_eq!(cfg.merge.mode, MergeMode::None);
8009 }
8010
8011 #[test]
8012 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8013 let dir = tempfile::tempdir().unwrap();
8014 let repo = dir.path().join("repo");
8015 std::fs::create_dir(&repo).unwrap();
8016 std::fs::write(
8017 repo.join("magi.toml"),
8018 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8019 )
8020 .unwrap();
8021 let daemon_config = dir.path().join("daemon.toml");
8022 std::fs::write(
8023 &daemon_config,
8024 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8025 )
8026 .unwrap();
8027 let opts = Opts {
8028 config: Some(daemon_config),
8029 merge: Some("pr".into()),
8030 ..Default::default()
8031 };
8032 let q = Queue::at(dir.path().join("queue"));
8033 let validation: Config =
8034 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8035 .unwrap();
8036 for record in ["{}", r#"{"candidates":2}"#] {
8038 let overrides = serde_json::from_str(record).unwrap();
8039 let filing = crate::direct::Filing {
8040 instruction: "work".into(),
8041 title: "direct".into(),
8042 repo: repo.clone(),
8043 source: crate::queue::Source::Human,
8044 solo: false,
8045 overrides,
8046 review_of: None,
8047 };
8048 let filed =
8049 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8050 let crate::direct::Filed::Standalone {
8051 mut task,
8052 claim: _claim,
8053 } = filed
8054 else {
8055 panic!("local filing")
8056 };
8057 let before = prepare_for(&repo, &opts, &task).unwrap();
8058 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8059 assert_eq!(
8060 before.merge.mode,
8061 MergeMode::None,
8062 "daemon --merge must not leak"
8063 );
8064 for n in [2, 1, 2] {
8065 task.set_implementers(n, &validation).unwrap();
8066 q.put(&mut task).unwrap();
8067 task = q.get(&task.id).unwrap();
8068 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8069 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8070 apply_task_implementers(&mut cfg, &task);
8071 assert_eq!(cfg.graph.implementers, usize::from(n));
8072 assert_eq!(cfg.graph.judges, 2);
8073 assert_eq!(cfg.merge.mode, MergeMode::None);
8074 }
8075 }
8076 }
8077
8078 #[test]
8079 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8080 let cfg: Config =
8081 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8082 .unwrap();
8083 let mut t = task();
8084 t.review_of = Some("review-target".into());
8085 t.hold_manual(Some("retry".into()));
8086 let mut previous = RunState::new(
8087 PathBuf::from("/repo"),
8088 "main".into(),
8089 "abc1234".into(),
8090 "review".into(),
8091 cfg.clone(),
8092 );
8093 previous.config.graph.implementers = 2;
8094 for count in [1, 3] {
8095 t.set_implementers(count, &cfg).unwrap();
8096 t.release();
8097 assert_eq!(t.review_of.as_deref(), Some("review-target"));
8098 for proposed in [
8099 Starter::Resume(previous.id.clone()),
8100 Starter::Review("recovery-target".into()),
8101 ] {
8102 assert_eq!(
8103 starter_with_implementers(&t, Some(&previous), proposed),
8104 Starter::Review("review-target".into())
8105 );
8106 }
8107 let mut configured = cfg.clone();
8108 apply_task_implementers(&mut configured, &t);
8109 assert_eq!(configured.graph.implementers, usize::from(count));
8110 assert_eq!(previous.config.graph.implementers, 2);
8111 }
8112 }
8113
8114 #[test]
8115 fn task_implementers_dispatch_and_resume_agree() {
8116 let mut t = task();
8117 let cfg: crate::config::Config =
8118 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8119 .unwrap();
8120 let mut run = RunState::new(
8121 PathBuf::from("/repo"),
8122 "main".into(),
8123 "abc1234".into(),
8124 "work".into(),
8125 cfg.clone(),
8126 );
8127 run.config.graph.implementers = 2;
8128 for n in [2, 1, 3, 2] {
8129 t.set_implementers(n, &cfg).unwrap();
8130 let mut dispatched = cfg.clone();
8131 apply_task_implementers(&mut dispatched, &t);
8132 assert_eq!(dispatched.graph.implementers, usize::from(n));
8133 assert_eq!(implementers_match(&t, &run), n == 2);
8134 for proposed in [
8135 Starter::Resume(run.id.clone()),
8136 Starter::Review("old-branch".into()),
8137 ] {
8138 let expected = if n == 2 {
8139 proposed.clone()
8140 } else {
8141 Starter::Start
8142 };
8143 assert_eq!(
8144 starter_with_implementers(&t, Some(&run), proposed),
8145 expected
8146 );
8147 }
8148 assert_eq!(
8149 run.config.graph.implementers, 2,
8150 "history must not be rewritten"
8151 );
8152 }
8153 t.solo = false;
8154 t.overrides = None;
8155 assert!(implementers_match(&t, &run));
8156 }
8157
8158 #[test]
8159 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8160 let mut solo_cfg = Config::default();
8166 solo_cfg.graph.implementers = 3;
8167 let mut solo_task = task();
8168 solo_task.solo = true;
8169 apply_task_implementers(&mut solo_cfg, &solo_task);
8170 assert_eq!(solo_cfg.graph.implementers, 1);
8171
8172 let mut plain_cfg = Config::default();
8173 plain_cfg.graph.implementers = 3;
8174 let plain_task = task();
8175 assert!(!plain_task.solo);
8176 apply_task_implementers(&mut plain_cfg, &plain_task);
8177 assert_eq!(
8178 plain_cfg.graph.implementers, 3,
8179 "a task that did not ask to run alone keeps the config's candidates"
8180 );
8181 }
8182
8183 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8184 QuotaLoss {
8185 seat: seat.into(),
8186 node: "judge".into(),
8187 at: at.parse().unwrap(),
8188 reset: reset.map(str::to_string),
8189 }
8190 }
8191
8192 #[test]
8193 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8194 let old: Vec<QuotaLoss> = (1..=4)
8195 .map(|i| {
8196 loss(
8197 &format!("judge-{i}"),
8198 "2026-09-23T05:23:00Z",
8199 Some("2:40pm (Asia/Tokyo)"),
8200 )
8201 })
8202 .collect();
8203 let fresh = losses_this_attempt(&old, &old);
8204 assert!(fresh.is_empty());
8205 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8206 }
8208
8209 #[test]
8210 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8211 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8212 let now = Timestamp::now();
8213 let mut after = old.clone();
8214 after.push(loss("judge-2", &now.to_string(), None));
8215 let fresh = losses_this_attempt(&old, &after);
8216 assert_eq!(fresh, vec![after[1].clone()]);
8217 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8218 assert_eq!(
8219 until,
8220 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8221 );
8222 }
8223
8224 #[test]
8225 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8226 let before = vec![
8229 loss("judge-1", "2026-09-23T05:23:00Z", None),
8230 loss("judge-2", "2026-09-23T05:24:00Z", None),
8231 ];
8232 let after = vec![
8233 loss("judge-2", "2026-09-23T05:24:00Z", None),
8234 loss("judge-1", "2026-09-24T01:00:00Z", None),
8235 ];
8236 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8237 }
8238
8239 #[test]
8240 fn merge_overrides_are_parsed_or_refused() {
8241 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8242 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8243 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8244 assert!(merge_mode("squash").is_err());
8245 }
8246
8247 #[test]
8248 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8249 let now = Timestamp::now();
8250 let fallback = Duration::from_secs(300);
8251 let cap = Duration::from_secs(1800);
8252
8253 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8255
8256 let soon = now + jiff::SignedDuration::from_secs(600);
8258 assert_eq!(
8259 quota_wait(Some(soon), now, fallback, cap),
8260 Duration::from_secs(600)
8261 );
8262
8263 let past = now - jiff::SignedDuration::from_secs(60);
8266 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8267
8268 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8271 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8272 }
8273
8274 #[test]
8275 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8276 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8277
8278 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8279 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8280
8281 let already_past =
8285 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8286 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8287
8288 assert!(
8289 parse_reset_hint("session limit reached", now, now).is_none(),
8290 "free text with no recognised shape is not guessed at"
8291 );
8292 assert!(
8293 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8294 "an unresolvable zone name is not guessed at either"
8295 );
8296 }
8297
8298 #[test]
8299 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8300 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8301
8302 let at = parse_reset_hint(
8303 "You've hit your usage limit. Visit \
8304 https://chatgpt.com/codex/settings/usage to purchase more \
8305 credits or try again at Sep 19th, 2026 5:10 PM.",
8306 now,
8307 now,
8308 )
8309 .expect("the codex reset wording is a recognised shape");
8310 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8311
8312 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8317 .expect("an explicit year needs no rollover");
8318 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8319
8320 assert!(
8321 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8322 "a two-digit year is not the documented shape and is not guessed at"
8323 );
8324 assert!(
8325 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8326 "a four-letter month name is not the documented three-letter abbreviation"
8327 );
8328 assert!(
8329 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8330 "an explicit zone on the dated shape is a format nobody has \
8331 documented, and is refused rather than guessed at as UTC"
8332 );
8333 }
8334
8335 #[test]
8336 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8337 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8338 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8339
8340 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8341 assert_eq!(at.as_second() - recorded.as_second(), 3769);
8342
8343 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8344 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8345
8346 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8347 assert!(
8348 parse_reset_hint(bad, now, recorded).is_none(),
8349 "{bad:?} must not be guessed at"
8350 );
8351 }
8352 }
8353
8354 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8358 let config = dir.join("magi.toml");
8359 std::fs::write(
8360 &config,
8361 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8362 )
8363 .unwrap();
8364 let opts = Opts {
8365 poll: Duration::from_secs(30),
8366 config: Some(config),
8367 repo: dir.join("repo"),
8371 ..Opts::default()
8372 };
8373 let home = dir.join("home");
8382 let worktrees = dir.join("wt");
8383 (
8384 opts,
8385 Queue::at(dir.join("queue")),
8386 home.join("daemon.json"),
8387 home,
8388 worktrees,
8389 )
8390 }
8391
8392 #[test]
8393 fn a_stop_is_idempotent_and_once_set_stays_set() {
8394 let stop = Stop::new();
8395 assert!(!stop.stopped());
8396
8397 stop.stop();
8398 assert!(stop.stopped());
8399 stop.stop();
8400 assert!(stop.stopped(), "a second stop is not a toggle");
8401
8402 let shared = stop.clone();
8403 assert!(
8404 shared.stopped(),
8405 "a clone is the same stop; that is how the loop and its caller share one"
8406 );
8407 }
8408
8409 #[test]
8410 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
8411 let stop = Stop::new();
8412 stop.enter();
8413 assert!(
8414 !stop.finishing(),
8415 "a busy loop nobody has asked to stop is just running"
8416 );
8417
8418 stop.stop();
8419 assert!(
8420 stop.finishing(),
8421 "a stop asked for mid-run has not landed until the run is settled"
8422 );
8423
8424 stop.exit();
8425 assert!(
8426 !stop.finishing(),
8427 "once the run is settled the stop has landed and there is nothing to finish"
8428 );
8429 }
8430
8431 #[test]
8432 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
8433 let stop = Stop::new();
8434 stop.enter();
8435 stop.enter();
8436 stop.stop();
8437 assert!(stop.finishing(), "two runs still in flight");
8438
8439 stop.exit();
8440 assert!(
8441 stop.finishing(),
8442 "one run finished, but a sibling is still working"
8443 );
8444
8445 stop.exit();
8446 assert!(
8447 !stop.finishing(),
8448 "the last run out is what actually lands the stop"
8449 );
8450 }
8451
8452 #[tokio::test]
8453 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
8454 let dir = tempfile::tempdir().unwrap();
8455 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8456 let stop = Stop::new();
8457 stop.stop();
8458
8459 let began = std::time::Instant::now();
8460 tokio::time::timeout(
8461 Duration::from_secs(2),
8462 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8463 )
8464 .await
8465 .expect("a stopped loop must return, not sit out its poll interval")
8466 .expect("the loop's own setup and teardown must not fail");
8467 assert!(
8468 began.elapsed() < opts.poll,
8469 "returned only after {:?}, which is a poll interval, not a stop",
8470 began.elapsed()
8471 );
8472 }
8473
8474 #[tokio::test]
8475 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
8476 let dir = tempfile::tempdir().unwrap();
8477 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8478 let stop = Stop::new();
8479
8480 let asker = {
8483 let stop = stop.clone();
8484 tokio::spawn(async move {
8485 tokio::time::sleep(Duration::from_millis(20)).await;
8486 stop.stop();
8487 })
8488 };
8489
8490 let began = std::time::Instant::now();
8491 tokio::time::timeout(
8492 Duration::from_secs(2),
8493 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8494 )
8495 .await
8496 .expect("a stop asked for while idle must wake the wait")
8497 .expect("the loop's own setup and teardown must not fail");
8498 asker.await.unwrap();
8499 assert!(
8500 began.elapsed() < opts.poll,
8501 "returned only after {:?}, so the stop waited on the sleep",
8502 began.elapsed()
8503 );
8504 }
8505
8506 #[tokio::test]
8507 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
8508 let dir = tempfile::tempdir().unwrap();
8509 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8510 let stop = Stop::new();
8511 stop.stop();
8512
8513 tokio::time::timeout(
8514 Duration::from_secs(2),
8515 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8516 )
8517 .await
8518 .expect("a stopped loop must return")
8519 .expect("the loop's own setup and teardown must not fail");
8520
8521 assert!(
8522 home.is_dir(),
8523 "the loop did publish a status file, so its removal is the teardown and not an absence"
8524 );
8525 assert!(
8526 !status_file.exists(),
8527 "a stopped loop clears its status file"
8528 );
8529 assert!(
8530 read_status(&home).is_none(),
8531 "a reader must see no daemon at all, not a heartbeat that merely stopped"
8532 );
8533 }
8534
8535 #[tokio::test]
8536 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
8537 let dir = tempfile::tempdir().unwrap();
8538 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8539 opts.once = true;
8540
8541 let mut settled = RunState::new(
8542 dir.path().join("repo"),
8543 "main".to_owned(),
8544 "abc1234".to_owned(),
8545 "fixture".to_owned(),
8546 Config::default(),
8547 );
8548 settled.status = RunStatus::Ready;
8549 let run_dir = home.join("runs").join(&settled.id);
8550 std::fs::create_dir_all(&run_dir).unwrap();
8551 std::fs::write(
8552 run_dir.join("run.json"),
8553 serde_json::to_string_pretty(&settled).unwrap(),
8554 )
8555 .unwrap();
8556 let questions = Questions::at(home.join("questions"));
8557 let mut question = ask::Question::new(
8558 settled.id.clone(),
8559 "review".to_owned(),
8560 "reviewer-1".to_owned(),
8561 "Continue?".to_owned(),
8562 String::new(),
8563 Vec::new(),
8564 );
8565 questions.put(&mut question).unwrap();
8566
8567 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
8568 .await
8569 .unwrap();
8570
8571 assert_eq!(
8572 questions.get(&question.id).unwrap().status,
8573 ask::QuestionStatus::Abandoned,
8574 "an empty --once drain still performs startup question cleanup"
8575 );
8576 }
8577
8578 #[test]
8579 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
8580 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8581
8582 assert!(
8583 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
8584 "never checked before: due at once"
8585 );
8586
8587 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
8588 assert!(
8589 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
8590 "well inside the interval: not due yet"
8591 );
8592
8593 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
8594 assert!(
8595 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
8596 "exactly at the edge: not yet due, same convention as `clean::due`"
8597 );
8598
8599 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8600 assert!(
8601 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
8602 "past the interval: due again"
8603 );
8604 }
8605
8606 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
8611 let config = dir.join("magi.toml");
8612 std::fs::write(
8618 &config,
8619 format!(
8620 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
8621 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
8622 cache_dir.display()
8623 ),
8624 )
8625 .unwrap();
8626 Opts {
8627 config: Some(config),
8628 repo: dir.join("repo"),
8629 ..Opts::default()
8630 }
8631 }
8632
8633 #[tokio::test]
8634 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8635 let dir = tempfile::tempdir().unwrap();
8636 let home = dir.path().join("home");
8637 let cache_dir = dir.path().join("cache");
8638 std::fs::create_dir_all(&cache_dir).unwrap();
8639 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8640 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8641
8642 let running = Stop::new();
8645 let mut last_checked = None;
8646 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8647 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
8648 .await;
8649 assert_eq!(
8650 crate::disk::dir_size(&cache_dir),
8651 0,
8652 "over the cap on the first check ever: pruned at once, no idle queue required"
8653 );
8654 assert_eq!(last_checked, Some(t0));
8655
8656 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
8658 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
8659 maybe_prune_cache_between_runs(
8660 &opts.repo,
8661 &opts,
8662 &home,
8663 &running,
8664 &mut last_checked,
8665 too_soon,
8666 )
8667 .await;
8668 assert_eq!(
8669 crate::disk::dir_size(&cache_dir),
8670 10,
8671 "too soon since the last check: left alone rather than rescanned every call"
8672 );
8673 assert_eq!(
8674 last_checked,
8675 Some(t0),
8676 "an idle check does not reset the clock"
8677 );
8678
8679 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8681 maybe_prune_cache_between_runs(
8682 &opts.repo,
8683 &opts,
8684 &home,
8685 &running,
8686 &mut last_checked,
8687 due_again,
8688 )
8689 .await;
8690 assert_eq!(
8691 crate::disk::dir_size(&cache_dir),
8692 0,
8693 "due again: pruned back under the cap"
8694 );
8695 }
8696
8697 #[tokio::test]
8705 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
8706 let dir = tempfile::tempdir().unwrap();
8707 let home = dir.path().join("home");
8708 let cache_dir = dir.path().join("cache");
8709 std::fs::create_dir_all(&cache_dir).unwrap();
8710 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8711 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8712
8713 let stop = Stop::new();
8714 stop.stop();
8715 assert!(
8716 !stop.finishing(),
8717 "no run is in flight at a between-runs boundary, so nothing else \
8718 would tell the operator this stop had not taken effect yet"
8719 );
8720
8721 let mut last_checked = None;
8722 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8723 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
8724 .await;
8725 assert_eq!(
8726 crate::disk::dir_size(&cache_dir),
8727 10,
8728 "over its cap, and due for the first check ever, but a stop outranks \
8729 it: the cap is a standing policy the next start measures again"
8730 );
8731 assert_eq!(
8732 last_checked, None,
8733 "a check that never happened must not claim the interval"
8734 );
8735 }
8736
8737 #[tokio::test]
8748 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
8749 let dir = tempfile::tempdir().unwrap();
8750 let cache_dir = dir.path().join("cache");
8751 std::fs::create_dir_all(&cache_dir).unwrap();
8752 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
8753
8754 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
8755 opts.poll = Duration::from_millis(20);
8756 opts.max_attempts = 1_000;
8757
8758 let queue = Queue::at(dir.path().join("queue"));
8759 for i in 0..128 {
8760 let mut task = Task::new(
8761 format!("queued work {i}"),
8762 format!("queued work {i}"),
8763 opts.repo.clone(),
8764 Source::Human,
8765 );
8766 queue.put(&mut task).unwrap();
8767 }
8768
8769 let home = dir.path().join("home");
8770 let worktrees = dir.path().join("wt");
8771 let status_file = home.join("daemon.json");
8772 let stop = Stop::new();
8773 let stopper = {
8774 let stop = stop.clone();
8775 let queue = Queue::at(dir.path().join("queue"));
8776 tokio::spawn(async move {
8777 for _ in 0..2_000 {
8781 if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
8782 break;
8783 }
8784 tokio::time::sleep(Duration::from_millis(5)).await;
8785 }
8786 stop.stop();
8787 })
8788 };
8789
8790 tokio::time::timeout(
8791 Duration::from_secs(20),
8792 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8793 )
8794 .await
8795 .expect("the loop must not hang on a queue that keeps producing failing work")
8796 .expect("the loop's own setup and teardown must not fail");
8797 stopper.await.unwrap();
8798
8799 let after = queue.list();
8800 let completed = after.iter().filter(|t| t.attempts == 1).count();
8801 assert!(
8802 completed >= 2,
8803 "the harness must have processed multiple tasks to exercise a busy queue \
8804 (got {completed} completed task(s))"
8805 );
8806 assert!(
8807 after.iter().any(|t| t.status.runnable()),
8808 "unprocessed tasks must remain: the external stop, rather than an \
8809 exhausted backlog, must end the test"
8810 );
8811 assert!(
8812 after
8813 .iter()
8814 .filter(|t| t.attempts > 0)
8815 .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
8816 "a busy backlog must not retry a task's unchanged startup failure"
8817 );
8818
8819 assert_eq!(
8820 crate::disk::dir_size(&cache_dir),
8821 0,
8822 "an oversized cache must not be left to grow unboundedly just because the \
8823 queue kept the loop busy the whole time"
8824 );
8825 }
8826
8827 #[test]
8828 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
8829 let dir = tempfile::tempdir().unwrap();
8830 let queue = Queue::at(dir.path().join("queue"));
8831 let questions = Questions::at(dir.path().join("questions"));
8832 let mut task = task();
8833 queue.put(&mut task).unwrap();
8834
8835 let mut task_question = ask::Question::new(
8836 task.id.clone(),
8837 crate::conduct::NODE.to_owned(),
8838 "conduct".to_owned(),
8839 "Which backend?".to_owned(),
8840 String::new(),
8841 Vec::new(),
8842 );
8843 questions.put(&mut task_question).unwrap();
8844 task.block(vec![task_question.id.clone()], None);
8845 queue.put(&mut task).unwrap();
8846
8847 let mut run_question = ask::Question::new(
8848 "20260101-000000-run1".to_owned(),
8849 "review".to_owned(),
8850 "reviewer-1".to_owned(),
8851 "Run question".to_owned(),
8852 String::new(),
8853 Vec::new(),
8854 );
8855 questions.put(&mut run_question).unwrap();
8856
8857 let mut coincidental = ask::Question::new(
8862 task.id.clone(),
8863 "review".to_owned(),
8864 "reviewer-1".to_owned(),
8865 "Unrelated review question".to_owned(),
8866 String::new(),
8867 Vec::new(),
8868 );
8869 questions.put(&mut coincidental).unwrap();
8870
8871 reconcile_task_questions(&queue, &questions);
8872 assert!(questions.get(&task_question.id).unwrap().status.open());
8873 assert!(questions.get(&run_question.id).unwrap().status.open());
8874 assert!(questions.get(&coincidental.id).unwrap().status.open());
8875
8876 task.release();
8877 queue.put(&mut task).unwrap();
8878 reconcile_task_questions(&queue, &questions);
8879 assert_eq!(
8880 questions.get(&task_question.id).unwrap().status,
8881 ask::QuestionStatus::Abandoned
8882 );
8883 assert!(
8884 questions.get(&run_question.id).unwrap().status.open(),
8885 "run questions remain the run janitor's responsibility"
8886 );
8887 assert!(
8888 questions.get(&coincidental.id).unwrap().status.open(),
8889 "a non-conductor question must not be abandoned just because its \
8890 run id coincides with a task id"
8891 );
8892 }
8893
8894 #[test]
8895 fn a_freshly_started_running_task_is_never_stalled() {
8896 let dir = tempfile::tempdir().unwrap();
8897 let mut t = task();
8898 t.start("run-1".to_owned());
8899 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
8902 }
8903
8904 #[test]
8905 fn a_long_running_task_with_no_live_daemon_is_stalled() {
8906 let dir = tempfile::tempdir().unwrap();
8907 let mut t = task();
8908 t.start("run-1".to_owned());
8909 t.updated_at = Timestamp::now()
8910 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8911 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
8912 assert_eq!(
8913 stalled_tasks(
8914 &Queue::at(dir.path().join("q")),
8915 dir.path(),
8916 Timestamp::now()
8917 )
8918 .len(),
8919 0,
8920 "the task was never written to this queue"
8921 );
8922 }
8923
8924 #[test]
8925 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
8926 let dir = tempfile::tempdir().unwrap();
8927 let mut t = task();
8928 t.id = "20260903-080340-0167".to_owned();
8929 t.start("20260903-080619-01c2".to_owned());
8930 t.updated_at = Timestamp::now()
8931 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8932
8933 let mut status = Status::new();
8934 status.current = vec![Current {
8935 task: t.id.clone(),
8936 run: "20260903-080619-01c2".to_owned(),
8937 }];
8938 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8939
8940 assert!(
8941 !is_stalled(&t, dir.path(), Timestamp::now()),
8942 "a live daemon's own heartbeat rules out stalled, however long the task has run"
8943 );
8944 }
8945
8946 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
8950 let path = queue.path_of(id);
8951 let body = std::fs::read_to_string(&path).unwrap();
8952 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
8953 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
8954 v["updated_at"] = serde_json::Value::String(old.to_string());
8955 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
8956 }
8957
8958 #[test]
8959 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
8960 let dir = tempfile::tempdir().unwrap();
8973 let queue = Queue::at(dir.path().join("queue"));
8974 let home = dir.path().join("home");
8975
8976 let mut t = task();
8977 t.id = "20260101-000001-lock".to_owned();
8978 t.start("run-1".to_owned());
8979 queue.put(&mut t).unwrap();
8980 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8981 std::fs::write(
8982 dir.path().join("queue").join(format!("{}.lock", t.id)),
8983 "not a pid",
8984 )
8985 .unwrap();
8986
8987 let now = Timestamp::now();
8988 assert!(
8989 reclaim_orphaned_running(&queue, 2).is_empty(),
8990 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
8991 and reclaim must leave the task alone"
8992 );
8993 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8994
8995 let stalled = stalled_tasks(&queue, &home, now);
8996 assert_eq!(
8997 stalled.len(),
8998 1,
8999 "reclaim's inability to claim it yet must not hide it from the conductor"
9000 );
9001 assert_eq!(stalled[0].id, t.id);
9002 }
9003
9004 #[test]
9005 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9006 let dir = tempfile::tempdir().unwrap();
9007 crate::run::set_home(dir.path().join("run-home"));
9008 let queue = Queue::at(dir.path().join("queue"));
9009 let home = dir.path().join("home");
9010 let questions = Questions::at(dir.path().join("questions"));
9011
9012 let mut t = task();
9013 t.id = "20260101-000003-dead".to_owned();
9014 t.start("missing-run".to_owned());
9015 queue.put(&mut t).unwrap();
9016 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9017
9018 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9021 assert_eq!(
9022 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9023 [&t.id]
9024 );
9025 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9026 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9027
9028 crate::conduct::apply(
9031 &queue,
9032 &questions,
9033 &crate::conduct::Verdict {
9034 decisions: vec![crate::conduct::Decision {
9035 id: t.id.clone(),
9036 recovery: Some(crate::conduct::Recovery::Requeue),
9037 ..crate::conduct::Decision::default()
9038 }],
9039 },
9040 )
9041 .unwrap();
9042 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9043 }
9044
9045 #[test]
9046 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9047 let dir = tempfile::tempdir().unwrap();
9048 let queue = Queue::at(dir.path().join("queue"));
9049 let home = dir.path().join("home");
9050
9051 let mut fresh = task();
9052 fresh.id = "20260101-000001-aaaa".to_owned();
9053 fresh.start("run-1".to_owned());
9054 queue.put(&mut fresh).unwrap();
9055
9056 let mut old = task();
9057 old.id = "20260101-000002-bbbb".to_owned();
9058 old.start("run-2".to_owned());
9059 queue.put(&mut old).unwrap();
9060 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9061
9062 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9063 assert_eq!(stalled.len(), 1);
9064 assert_eq!(stalled[0].id, old.id);
9065 }
9066
9067 #[test]
9068 fn queued_and_finished_task_views_partition_by_status() {
9069 let dir = tempfile::tempdir().unwrap();
9070 let queue = Queue::at(dir.path().join("queue"));
9071
9072 let mut queued = task();
9073 queued.id = "20260101-000001-aaaa".to_owned();
9074 queue.put(&mut queued).unwrap();
9075
9076 let mut failed = task();
9077 failed.id = "20260101-000002-bbbb".to_owned();
9078 failed.start("run-1".to_owned());
9079 failed.fail("gate red", 5);
9080 queue.put(&mut failed).unwrap();
9081
9082 let mut held = task();
9083 held.id = "20260101-000003-cccc".to_owned();
9084 held.hold_machine(None);
9085 queue.put(&mut held).unwrap();
9086
9087 let mut running = task();
9088 running.id = "20260101-000004-dddd".to_owned();
9089 running.start("run-2".to_owned());
9090 queue.put(&mut running).unwrap();
9091
9092 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9093 assert_eq!(queued_ids, [queued.id.clone()]);
9094
9095 let mut finished_ids: Vec<String> =
9096 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9097 finished_ids.sort_unstable();
9098 let mut want = vec![failed.id.clone(), held.id.clone()];
9099 want.sort_unstable();
9100 assert_eq!(finished_ids, want);
9101 }
9102
9103 #[test]
9104 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9105 for short in [false, true] {
9106 let dir = tempfile::tempdir().unwrap();
9107 let queue = Queue::at(dir.path().join("queue"));
9108 let questions = ask::Questions::at(dir.path().join("questions"));
9109 let mut running = task();
9110 running.id = "20261013-192213-feb2".into();
9111 running.start("existing-run".into());
9112 queue.put(&mut running).unwrap();
9113 let mut middle = task();
9114 middle.id = "20261013-193611-ca5b".into();
9115 middle.block(
9116 vec![if short {
9117 "feb2".into()
9118 } else {
9119 running.id.clone()
9120 }],
9121 None,
9122 );
9123 queue.put(&mut middle).unwrap();
9124 let mut waiting = task();
9125 waiting.id = "20261013-202849-ee37".into();
9126 waiting.block(
9127 vec![if short {
9128 "ca5b".into()
9129 } else {
9130 middle.id.clone()
9131 }],
9132 Some("wait for implementation".into()),
9133 );
9134 queue.put(&mut waiting).unwrap();
9135 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9136 let inv = crate::blockers::Inventory::load(&queue, &questions);
9137 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9138 assert!(inv.stuck().is_empty());
9139 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9140 assert!(report.quarantined.is_empty());
9141 assert!(report.asked.is_empty());
9142 resolve_blockers(&queue, &questions);
9143 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9144 assert!(questions.list().is_empty());
9145 running.succeed();
9148 queue.put(&mut running).unwrap();
9149 resolve_blockers(&queue, &questions);
9150 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9151 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9152 middle = queue.get(&middle.id).unwrap();
9153 middle.succeed();
9154 queue.put(&mut middle).unwrap();
9155 resolve_blockers(&queue, &questions);
9156 let after = queue.get(&waiting.id).unwrap();
9157 assert_eq!(after.status, TaskStatus::Queued);
9158 assert!(after.blocked_by.is_empty());
9159 assert_eq!(after.instruction, waiting.instruction);
9160 }
9161 }
9162
9163 #[test]
9164 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9165 for future_schema in [false, true] {
9166 let name = "20261013-193611-ca5b";
9167 let mut future = task();
9168 future.id = name.into();
9169 future.schema = crate::queue::SCHEMA + 1;
9170 let contents = if future_schema {
9171 serde_json::to_string(&future).unwrap()
9172 } else {
9173 "corrupt".into()
9174 };
9175 let dir = tempfile::tempdir().unwrap();
9176 let queue = Queue::at(dir.path().join("queue"));
9177 let questions = ask::Questions::at(dir.path().join("questions"));
9178 let mut waiting = task();
9179 waiting.id = "20261013-202849-ee37".into();
9180 waiting.block(vec!["ca5b".into()], None);
9181 queue.put(&mut waiting).unwrap();
9182 std::fs::write(queue.path_of(name), contents).unwrap();
9183 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9184 assert!(
9185 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9186 );
9187 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9188 assert!(report.asked.is_empty());
9189 resolve_blockers(&queue, &questions);
9190 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9191 assert!(questions.list().is_empty());
9192 }
9193 let dir = tempfile::tempdir().unwrap();
9194 let queue = Queue::at(dir.path().join("queue"));
9195 let questions = ask::Questions::at(dir.path().join("questions"));
9196 let mut waiting = task();
9197 waiting.id = "20261013-202849-ee37".into();
9198 waiting.block(vec!["ca5b".into()], None);
9199 queue.put(&mut waiting).unwrap();
9200 let mut done = task();
9201 done.id = "20261013-193611-ca5b".into();
9202 done.succeed();
9203 queue.put(&mut done).unwrap();
9204 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9207 assert!(queue.get("ca5b").is_err());
9208 assert_eq!(
9209 crate::queue::dependency(&queue, &questions, "ca5b"),
9210 crate::queue::Dependency::Ambiguous
9211 );
9212 resolve_blockers(&queue, &questions);
9213 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9214 assert!(report.asked.is_empty());
9215 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9216 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9217 }
9218
9219 #[test]
9220 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9221 for held in [false, true] {
9222 for question in [false, true] {
9223 for reference in ["ca5b", "20261013-193611-ca5b"] {
9224 let dir = tempfile::tempdir().unwrap();
9225 let queue = Queue::at(dir.path().join("queue"));
9226 let questions = ask::Questions::at(dir.path().join("questions"));
9227 let mut prerequisite = task();
9228 prerequisite.id = "20261013-193611-ca5b".into();
9229 prerequisite.start("existing-run".into());
9230 queue.put(&mut prerequisite).unwrap();
9231 let mut waiting = task();
9232 waiting.id = "20261013-202849-ee37".into();
9233 if held {
9234 waiting.hold_machine(Some("waiting for separate consent".into()));
9235 }
9236 queue.put(&mut waiting).unwrap();
9237 let reason = "Deleting saved data requires separate owner consent";
9238 crate::conduct::apply(
9239 &queue,
9240 &questions,
9241 &crate::conduct::Verdict {
9242 decisions: vec![crate::conduct::Decision {
9243 id: waiting.id.clone(),
9244 blocked_by: vec![reference.into()],
9245 question: question.then(|| "May the saved data be deleted?".into()),
9246 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9247 reason: Some(reason.into()),
9248 ..crate::conduct::Decision::default()
9249 }],
9250 },
9251 )
9252 .unwrap();
9253 let before = queue.get(&waiting.id).unwrap();
9254 if question {
9255 assert_eq!(before.status, TaskStatus::Blocked);
9256 let q = questions.get(&before.blocked_by[0]).unwrap();
9257 assert_eq!(q.summary, "May the saved data be deleted?");
9258 assert!(q.status.open());
9259 } else {
9260 assert_eq!(before.status, TaskStatus::Held);
9261 let recorded_reason = before.hold_reason.as_deref().unwrap();
9262 assert!(recorded_reason.starts_with(reason));
9263 if held {
9264 assert!(recorded_reason.contains("waiting for separate consent"));
9265 }
9266 }
9267 prerequisite.succeed();
9268 queue.put(&mut prerequisite).unwrap();
9269 resolve_blockers(&queue, &questions);
9270 let after = queue.get(&waiting.id).unwrap();
9271 assert_eq!(after.status, before.status);
9272 assert_eq!(after.blocked_by, before.blocked_by);
9273 assert_eq!(after.hold_reason, before.hold_reason);
9274 assert_eq!(after.instruction, waiting.instruction);
9275 if question {
9276 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9277 }
9278 assert!(
9279 queue.next_runnable().is_none(),
9280 "dependency completion is not consent"
9281 );
9282 }
9283 }
9284 }
9285 }
9286
9287 #[test]
9288 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9289 let dir = tempfile::tempdir().unwrap();
9290 let queue = Queue::at(dir.path().join("queue"));
9291 let questions = ask::Questions::at(dir.path().join("questions"));
9292
9293 let mut dep = task();
9294 dep.id = "20260101-000001-dep0".to_owned();
9295 dep.succeed();
9296 queue.put(&mut dep).unwrap();
9297
9298 let mut still_going = task();
9299 still_going.id = "20260101-000002-dep1".to_owned();
9300 queue.put(&mut still_going).unwrap();
9301
9302 let mut blocked = task();
9303 blocked.id = "20260101-000003-main".to_owned();
9304 blocked.block(
9305 vec![dep.id.clone(), still_going.id.clone()],
9306 Some("waits on both".to_owned()),
9307 );
9308 queue.put(&mut blocked).unwrap();
9309
9310 resolve_blockers(&queue, &questions);
9311
9312 let after = queue.get(&blocked.id).unwrap();
9313 assert_eq!(
9314 after.status,
9315 TaskStatus::Blocked,
9316 "one dependency is still outstanding"
9317 );
9318 assert_eq!(after.blocked_by, [still_going.id.clone()]);
9319 }
9320
9321 #[test]
9322 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9323 let dir = tempfile::tempdir().unwrap();
9324 let queue = Queue::at(dir.path().join("queue"));
9325 let questions = ask::Questions::at(dir.path().join("questions"));
9326
9327 let mut q = crate::ask::Question::new(
9328 "20260101-000001-main".to_owned(),
9329 crate::conduct::NODE.to_owned(),
9330 "conduct".to_owned(),
9331 "Which backend?".to_owned(),
9332 String::new(),
9333 Vec::new(),
9334 );
9335 questions.put(&mut q).unwrap();
9336 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9337 .unwrap();
9338 questions.put(&mut q).unwrap();
9339
9340 let mut blocked = task();
9341 blocked.id = "20260101-000001-main".to_owned();
9342 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9343 queue.put(&mut blocked).unwrap();
9344
9345 resolve_blockers(&queue, &questions);
9346
9347 let after = queue.get(&blocked.id).unwrap();
9348 assert_eq!(
9349 after.status,
9350 TaskStatus::Queued,
9351 "the only blocker resolved"
9352 );
9353 assert_eq!(after.answers.len(), 1);
9354 assert_eq!(after.answers[0].question, "Which backend?");
9355 assert_eq!(after.answers[0].answer, "SQLite");
9356
9357 let instruction = instruction_for(&after);
9359 assert!(instruction.contains("Which backend?"));
9360 assert!(instruction.contains("SQLite"));
9361 }
9362
9363 #[test]
9364 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9365 let dir = tempfile::tempdir().unwrap();
9366 let queue = Queue::at(dir.path().join("queue"));
9367 let questions = ask::Questions::at(dir.path().join("questions"));
9368
9369 let mut q = crate::ask::Question::new(
9370 "20260101-000001-main".to_owned(),
9371 crate::conduct::NODE.to_owned(),
9372 "conduct".to_owned(),
9373 "Is the setup done?".to_owned(),
9374 String::new(),
9375 Vec::new(),
9376 );
9377 q.abandon("no answer within 60s of asking");
9378 questions.put(&mut q).unwrap();
9379
9380 let mut blocked = task();
9381 blocked.id = "20260101-000001-main".to_owned();
9382 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9383 queue.put(&mut blocked).unwrap();
9384
9385 resolve_blockers(&queue, &questions);
9386
9387 let after = queue.get(&blocked.id).unwrap();
9388 assert_eq!(
9389 after.status,
9390 TaskStatus::Held,
9391 "never left blocked on nothing"
9392 );
9393 assert!(!after.operator_held(), "a machine hold, for triage");
9394 assert!(
9395 after
9396 .hold_reason
9397 .as_deref()
9398 .unwrap_or_default()
9399 .contains("went unanswered")
9400 );
9401 }
9402
9403 #[test]
9404 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9405 let dir = tempfile::tempdir().unwrap();
9411 let queue = Queue::at(dir.path().join("queue"));
9412 let questions = ask::Questions::at(dir.path().join("questions"));
9413
9414 let mut q = crate::ask::Question::new(
9415 "20260101-000001-main".to_owned(),
9416 crate::conduct::NODE.to_owned(),
9417 "conduct".to_owned(),
9418 "How should this be handled?".to_owned(),
9419 String::new(),
9420 Vec::new(),
9421 );
9422 questions.put(&mut q).unwrap();
9423 q.answer(crate::ask::Answer::Text(
9424 "leave it held, a human will look at it later".to_owned(),
9425 ))
9426 .unwrap();
9427 questions.put(&mut q).unwrap();
9428
9429 let mut held = task();
9430 held.id = "20260101-000001-main".to_owned();
9431 held.hold_machine(Some("out of attempts".to_owned()));
9432 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
9433 queue.put(&mut held).unwrap();
9434
9435 resolve_blockers(&queue, &questions);
9436
9437 let after = queue.get(&held.id).unwrap();
9438 assert_eq!(after.status, TaskStatus::Held);
9439 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
9440 assert_eq!(
9441 after.answers[0].answer,
9442 "leave it held, a human will look at it later"
9443 );
9444 }
9445
9446 #[test]
9447 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
9448 let dir = tempfile::tempdir().unwrap();
9449 let queue = Queue::at(dir.path().join("queue"));
9450 let questions = ask::Questions::at(dir.path().join("questions"));
9451 let mut dep = task();
9452 dep.id = "20260101-000001-gone".to_owned();
9453 queue.put(&mut dep).unwrap();
9454 let mut blocked = task();
9455 blocked.id = "20260101-000003-main".to_owned();
9456 blocked.block(vec![dep.id.clone()], None);
9457 queue.put(&mut blocked).unwrap();
9458
9459 let claim = queue.claim(&blocked.id).unwrap();
9461 queue.remove(&dep.id, false, &questions).unwrap();
9462 drop(claim);
9463 resolve_blockers(&queue, &questions);
9464
9465 let after = queue.get(&blocked.id).unwrap();
9466 assert_eq!(after.status, TaskStatus::Queued);
9467 assert!(after.blocked_by.is_empty());
9468 }
9469
9470 #[test]
9471 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
9472 let dir = tempfile::tempdir().unwrap();
9478 let queue = Queue::at(dir.path().join("queue"));
9479 let questions = ask::Questions::at(dir.path().join("questions"));
9480
9481 let mut still_going = task();
9482 still_going.id = "20260101-000002-dep1".to_owned();
9483 queue.put(&mut still_going).unwrap();
9484
9485 let mut blocked = task();
9486 blocked.id = "20260101-000003-main".to_owned();
9487 blocked.block(
9488 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
9489 Some("waits on both".to_owned()),
9490 );
9491 queue.put(&mut blocked).unwrap();
9492
9493 resolve_blockers(&queue, &questions);
9494
9495 let after = queue.get(&blocked.id).unwrap();
9496 assert_eq!(
9497 after.status,
9498 TaskStatus::Held,
9499 "a missing dependency must not leave the task blocked forever"
9500 );
9501 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
9502 assert!(after.blocked_by.is_empty());
9503 let reason = after.hold_reason.as_deref().unwrap_or_default();
9504 assert!(
9505 reason.contains("20260101-000001-gone"),
9506 "the missing id must be named so an operator can tell what happened: {reason}"
9507 );
9508 assert!(
9509 reason.contains(&still_going.id),
9510 "the still-valid dependency must not silently vanish from the record: {reason}"
9511 );
9512 }
9513
9514 #[test]
9515 fn instruction_for_is_unchanged_without_any_answers() {
9516 let t = task();
9517 assert_eq!(instruction_for(&t), t.instruction);
9518 }
9519
9520 #[test]
9521 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
9522 let dir = tempfile::tempdir().unwrap();
9523 let q = Queue::at(dir.path().join("queue"));
9524 let src = dir.path().join("shot.png");
9525 std::fs::write(&src, "x").unwrap();
9526 let mut t = task();
9527 q.attach(&mut t, &[src]).unwrap();
9528 let paths = task_attachments(&q, &t).unwrap();
9529 assert_eq!(paths.len(), 1);
9530 assert!(paths[0].is_absolute() && paths[0].is_file());
9531 std::fs::remove_file(&paths[0]).unwrap();
9532 let err = task_attachments(&q, &t).unwrap_err().to_string();
9533 assert!(err.contains("shot.png"), "{err}");
9534 }
9535
9536 #[tokio::test]
9537 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
9538 let dir = tempfile::tempdir().unwrap();
9539 let queue_path = dir.path().join("queue");
9540 let queue = Queue::at(queue_path.clone());
9541 let mut t = task();
9542 t.source = Source::Agent {
9543 run: "originating-chat".into(),
9544 node: crate::queue::CHAT_NODE.into(),
9545 };
9546 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
9547 stage: "config-fetch",
9548 target: "origin/main".into(),
9549 });
9550 record_config_failure(&mut t, &fetch);
9551 t.hold_machine(Some(format!("{fetch:#}")));
9552 let fetch_key = t.chat_notice_due().unwrap();
9553 t.chat_notices.push(fetch_key.clone());
9554 queue.put(&mut t).unwrap();
9555
9556 let queue = Queue::at(queue_path);
9557 let mut t = queue.get(&t.id).unwrap();
9558 let a = dir.path().join("a.toml");
9559 let b = dir.path().join("b.toml");
9560 for (path, text, new_cause) in [
9561 (&a, "[graph", true),
9562 (&a, "[verify", false),
9563 (&a, "[graph]\nimplementers = 'invalid-type'", true),
9564 (&b, "[graph]\nimplementers = 'invalid-type'", true),
9565 ] {
9566 t.release_operator("test", None);
9567 std::fs::write(path, text).unwrap();
9568 let error = Config::discover_fetched(dir.path(), Some(path))
9569 .await
9570 .unwrap_err();
9571 record_config_failure(&mut t, &error);
9572 t.hold_machine(Some(format!("{error:#}")));
9573 let due = t.chat_notice_due();
9574 assert_eq!(due.is_some(), new_cause, "{error:#}");
9575 if let Some(key) = due {
9576 assert_ne!(key, fetch_key);
9577 t.chat_notices.push(key);
9578 }
9579 }
9580 t.succeed();
9581 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
9582 }
9583
9584 #[test]
9585 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
9586 let dir = tempfile::tempdir().unwrap();
9587 let queue_path = dir.path().join("queue");
9588 let queue = Queue::at(queue_path.clone());
9589 let mut t = task();
9590 t.source = crate::queue::Source::Agent {
9591 run: "originating-chat".into(),
9592 node: crate::queue::CHAT_NODE.into(),
9593 };
9594 let a = dir.path().join("a.png");
9595 let b = dir.path().join("b.png");
9596 std::fs::write(&a, "a").unwrap();
9597 std::fs::write(&b, "b").unwrap();
9598 queue.attach(&mut t, &[a, b]).unwrap();
9599 let paths = task_attachments(&queue, &t).unwrap();
9600 for path in &paths {
9601 std::fs::remove_file(path).unwrap();
9602 }
9603 let missing = task_attachments(&queue, &t).unwrap_err();
9604 t.attempts += 1;
9605 let reason = missing.to_string();
9606 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9607 let first = t.chat_notice_due().expect("first attachment notice");
9608 t.chat_notices.push(first.clone());
9609 queue.put(&mut t).unwrap();
9610
9611 let queue = Queue::at(queue_path.clone());
9612 let mut t = queue.get(&t.id).unwrap();
9613 assert!(t.chat_notice_due().is_none(), "restart does not replay");
9614 t.release_operator("test", None);
9615 t.attempts += 1;
9616 let missing = task_attachments(&queue, &t).unwrap_err();
9617 t.fail_startup_target(
9618 "startup-attachments",
9619 missing.name,
9620 "same missing attachment with regenerated wording",
9621 1,
9622 );
9623 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
9624
9625 std::fs::write(&paths[0], "restored").unwrap();
9626 t.release_operator("test", None);
9627 t.attempts += 1;
9628 let missing = task_attachments(&queue, &t).unwrap_err();
9629 let reason = missing.to_string();
9630 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9631 let second = t
9632 .chat_notice_due()
9633 .expect("different attachment must notify");
9634 assert_ne!(first, second);
9635 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
9636 }
9637
9638 #[test]
9639 fn resumed_instruction_is_unchanged_without_any_answers() {
9640 let t = task();
9641 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
9642 }
9643
9644 #[test]
9645 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
9646 let mut t = task();
9647 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9648 let old = t.instruction.clone();
9652
9653 let refreshed = resumed_instruction(&old, &t);
9654 assert!(refreshed.starts_with(&old), "the original text is kept");
9655 assert!(refreshed.contains("Which backend?"));
9656 assert!(refreshed.contains("SQLite"));
9657 }
9658
9659 #[test]
9660 fn resumed_instruction_keeps_an_original_answers_heading() {
9661 let mut t = task();
9662 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
9663 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9664
9665 let refreshed = resumed_instruction(&t.instruction, &t);
9666
9667 assert!(
9668 refreshed.starts_with(&t.instruction),
9669 "an answers heading in the original instruction is not the appended block"
9670 );
9671 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
9672 assert!(refreshed.contains("Which backend?"));
9673 assert!(refreshed.contains("SQLite"));
9674
9675 let repeated = resumed_instruction(&refreshed, &t);
9676 assert_eq!(
9677 repeated, refreshed,
9678 "only the final appended block is refreshed"
9679 );
9680 }
9681
9682 #[test]
9683 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
9684 let mut t = task();
9685 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9686
9687 let once = resumed_instruction(&t.instruction, &t);
9691 let twice = resumed_instruction(&once, &t);
9692 assert_eq!(once, twice);
9693 assert_eq!(once.matches("Which backend?").count(), 1);
9694
9695 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
9697 let refreshed = resumed_instruction(&once, &t);
9698 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
9699 assert!(refreshed.contains("Which backend?"));
9700 assert!(refreshed.contains("Which cache?"));
9701 }
9702
9703 #[test]
9704 fn prepare_instruction_covers_all_three_starters() {
9705 let mut t = task();
9706 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9707
9708 assert_eq!(
9711 prepare_instruction(&Starter::Start, None, &t),
9712 Some(instruction_for(&t))
9713 );
9714
9715 let old = t.instruction.clone();
9718 assert_eq!(
9719 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
9720 Some(resumed_instruction(&old, &t))
9721 );
9722
9723 assert_eq!(
9727 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
9728 None
9729 );
9730 }
9731
9732 #[test]
9733 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
9734 assert_eq!(
9735 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
9736 Starter::Review("magi/eba2/A".to_owned())
9737 );
9738 }
9739
9740 #[test]
9741 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
9742 assert_eq!(
9743 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
9744 Starter::Start,
9745 "a vanished review branch must not fall back to resuming the old run either"
9746 );
9747 }
9748
9749 #[test]
9750 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
9751 let mut t = task();
9752 t.start("old-run".to_owned());
9753 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
9754 t.release();
9755 let branch = t.review_branch.take();
9756 assert_eq!(
9757 choose_starter(branch.as_deref(), true, Some("old-run")),
9758 Starter::Review("magi/eba2/A".to_owned()),
9759 "a review wins over resuming the old run"
9760 );
9761 }
9762
9763 #[test]
9764 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
9765 assert_eq!(
9766 choose_starter(None, false, Some("some-run")),
9767 Starter::Resume("some-run".to_owned())
9768 );
9769 assert_eq!(choose_starter(None, false, None), Starter::Start);
9770 }
9771
9772 #[test]
9773 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
9774 let mut released = task();
9775 released.start("stalled-run".to_owned());
9776 released.requeue();
9777 let unfinished = (!released.fresh_start)
9778 .then(|| Some("stalled-run".to_owned()))
9779 .flatten();
9780 assert_eq!(
9781 choose_starter(None, false, unfinished.as_deref()),
9782 Starter::Start,
9783 "release keeps run history but must not resume it"
9784 );
9785 assert_eq!(released.runs, ["stalled-run"]);
9786 }
9787
9788 #[test]
9789 fn an_ordinary_release_keeps_a_resumable_run_available() {
9790 let mut released = task();
9791 released.start("stalled-run".to_owned());
9792 released.release();
9793 let unfinished = (!released.fresh_start)
9794 .then(|| Some("stalled-run".to_owned()))
9795 .flatten();
9796 assert_eq!(
9797 choose_starter(None, false, unfinished.as_deref()),
9798 Starter::Resume("stalled-run".to_owned()),
9799 "manual release must preserve the normal resume path"
9800 );
9801 }
9802
9803 #[test]
9804 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
9805 let mut state = run_state(RunStatus::Blocked);
9806 state.config.graph.review_rounds = 3;
9807 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
9808 assert!(exhausted_review_budget(&state));
9809
9810 state.reviews.pop();
9812 assert!(!exhausted_review_budget(&state));
9813
9814 let mut stalled = run_state(RunStatus::Stalled);
9817 stalled.config.graph.review_rounds = 1;
9818 stalled.reviews = vec![review_round(1)];
9819 assert!(!exhausted_review_budget(&stalled));
9820 }
9821
9822 fn review_round(round: usize) -> crate::run::ReviewRound {
9823 crate::run::ReviewRound {
9824 round,
9825 head: "deadbeef".to_owned(),
9826 verified_head: None,
9827 verified_at: None,
9828 reviews: Vec::new(),
9829 e2e: Vec::new(),
9830 verify_retried: false,
9831 e2e_deferred: false,
9832 e2e_defer_reason: None,
9833 fix: None,
9834 blocking: 0,
9835 answered: 1,
9836 expected: 1,
9837 clean: false,
9838 progressed: true,
9839 vote_split: false,
9840 reconsideration: Vec::new(),
9841 verdict: None,
9842 }
9843 }
9844
9845 #[test]
9846 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
9847 let mut run = RunState::new(
9848 PathBuf::from("/repo"),
9849 "main".to_owned(),
9850 "abc1234def".to_owned(),
9851 "add retries".to_owned(),
9852 Config::default(),
9853 );
9854 run.status = RunStatus::Judging;
9855 run.parked = true;
9856 let mut task = Task::new(
9857 "add retries".to_owned(),
9858 "add retries".to_owned(),
9859 PathBuf::from("/repo"),
9860 crate::queue::Source::Human,
9861 );
9862 task.status = TaskStatus::Failed;
9863 task.runs = vec![run.id.clone()];
9864 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
9865 assert!(with(&task, &run), "parked after judging is the case");
9866 let mut parked_task = task.clone();
9867 parked_task.status = TaskStatus::Parked;
9868 assert!(with(&parked_task, &run), "the Parked status is the case");
9869
9870 let mut not_parked = run.clone();
9871 not_parked.parked = false;
9872 not_parked.status = RunStatus::Stalled;
9873 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
9874
9875 let mut fresh = task.clone();
9876 fresh.fresh_start = true;
9877 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
9878
9879 let mut review = task.clone();
9880 review.review_branch = Some("magi/x/A".to_owned());
9881 assert!(!with(&review, &run), "review is ranked before resume");
9882
9883 let mut held = task.clone();
9884 held.status = TaskStatus::Held;
9885 assert!(!with(&held, &run), "a hold stays visible to the conductor");
9886
9887 let mut released = run.clone();
9888 released.released_to = Some("20260901-000000-new1".to_owned());
9889 assert!(!with(&task, &released), "nothing left to resume into");
9890
9891 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
9892 "unreadable"
9893 )));
9894 }
9895
9896 #[test]
9897 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
9898 let mut released = RunState::new(
9899 PathBuf::from("/repo"),
9900 "main".to_owned(),
9901 "abc1234def".to_owned(),
9902 "add retries".to_owned(),
9903 Config::default(),
9904 );
9905 released.status = RunStatus::Blocked;
9906 assert_eq!(
9907 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9908 Some(released.id.clone())
9909 );
9910 released.released_to = Some("20260901-000000-new1".to_owned());
9911 assert_eq!(
9912 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9913 None,
9914 "there is nothing left to resume it into"
9915 );
9916 }
9917
9918 #[test]
9919 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
9920 let mut exhausted = RunState::new(
9929 PathBuf::from("/repo"),
9930 "main".to_owned(),
9931 "abc1234def".to_owned(),
9932 "add retries".to_owned(),
9933 Config::default(),
9934 );
9935 exhausted.status = RunStatus::Blocked;
9936 exhausted.config.graph.review_rounds = 1;
9937 exhausted.reviews = vec![review_round(1)];
9938
9939 assert_eq!(
9940 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
9941 None,
9942 "an exhausted `Blocked` run must not be offered as resumable"
9943 );
9944
9945 let mut has_budget_left = RunState::new(
9948 PathBuf::from("/repo"),
9949 "main".to_owned(),
9950 "abc1234def".to_owned(),
9951 "add retries".to_owned(),
9952 Config::default(),
9953 );
9954 has_budget_left.status = RunStatus::Blocked;
9955 has_budget_left.config.graph.review_rounds = 3;
9956 has_budget_left.reviews = vec![review_round(1)];
9957
9958 assert_eq!(
9959 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
9960 Ok(has_budget_left.clone())
9961 }),
9962 Some(has_budget_left.id.clone())
9963 );
9964 }
9965
9966 #[test]
9967 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
9968 let mut run = RunState::new(
9969 PathBuf::from("/repo"),
9970 "main".to_owned(),
9971 "abc1234def".to_owned(),
9972 "add retries".to_owned(),
9973 Config::default(),
9974 );
9975 run.status = RunStatus::Blocked;
9976 run.config.graph.review_rounds = 1;
9977 run.reviews = vec![review_round(1)];
9978 run.pr_publication_pending = true;
9979 assert_eq!(
9980 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
9981 Some(run.id.clone()),
9982 "a spent review budget must not turn a failed publication into a re-competition"
9983 );
9984 }
9985
9986 #[test]
9987 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
9988 let mut older_stalled = RunState::new(
9996 PathBuf::from("/repo"),
9997 "main".to_owned(),
9998 "abc1234def".to_owned(),
9999 "add retries".to_owned(),
10000 Config::default(),
10001 );
10002 older_stalled.status = RunStatus::Stalled;
10003
10004 let mut newest_exhausted = RunState::new(
10005 PathBuf::from("/repo"),
10006 "main".to_owned(),
10007 "abc1234def".to_owned(),
10008 "add retries".to_owned(),
10009 Config::default(),
10010 );
10011 newest_exhausted.status = RunStatus::Blocked;
10012 newest_exhausted.config.graph.review_rounds = 1;
10013 newest_exhausted.reviews = vec![review_round(1)];
10014
10015 assert_eq!(
10016 unfinished_run_with(
10017 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10018 "t",
10019 |_| Ok(newest_exhausted.clone())
10020 ),
10021 None,
10022 "the newest run is exhausted, so nothing here is worth resuming - \
10023 least of all the older, already-superseded run"
10024 );
10025 }
10026
10027 #[test]
10028 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10029 assert_eq!(
10030 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10031 Err(anyhow::anyhow!("fixture is absent"))
10032 }),
10033 None
10034 );
10035 }
10036
10037 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10038 let mut q = ask::Question::new(
10039 run.to_owned(),
10040 "implement".to_owned(),
10041 "impl-A".to_owned(),
10042 "continue?".to_owned(),
10043 String::new(),
10044 vec!["resume で続行する".to_owned(), "other".to_owned()],
10045 );
10046 q.actions.insert("resume で続行する".to_owned(), action);
10047 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10048 .unwrap();
10049 q
10050 }
10051
10052 fn held_task_with(run: &str) -> Task {
10053 let mut t = task();
10054 t.runs = vec![run.to_owned()];
10055 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10056 t
10057 }
10058
10059 fn resume_action(run: &str) -> ask::ChoiceAction {
10060 ask::ChoiceAction::Resume { run: run.into() }
10061 }
10062
10063 #[test]
10064 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10065 for parked in [false, true] {
10066 let mut t = task();
10067 t.start("A".into());
10068 t.start("B".into());
10069 assert_eq!(t.runs, vec!["A", "B"]);
10070 t.start("A".into());
10071 let mut resumed = run_state(RunStatus::Blocked);
10072 resumed.id = "A".into();
10073 resumed.parked = parked;
10074 resumed.driver_exited = true;
10075 t.hold_machine(Some("resumed run stopped".into()));
10076 let q = action_question("A", resume_action("A"));
10077 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10078 assert_eq!(
10079 decide_action(&t, &q, &PHRASES_EN, |id| {
10080 assert_eq!(id, "A");
10081 Ok(resumed.clone())
10082 }),
10083 ActionDecision::Resume("A".into())
10084 );
10085 assert_eq!(
10086 action_standing(&t, &action_question("B", resume_action("B"))),
10087 ActionStanding::Stale
10088 );
10089 t.release_operator("cli", None);
10090 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10091 assert_eq!(id, "A");
10092 Ok(resumed.clone())
10093 });
10094 assert_eq!(
10095 choose_starter(None, false, unfinished.as_deref()),
10096 Starter::Resume("A".into())
10097 );
10098 assert_eq!(t.runs, vec!["B", "A"]);
10099 }
10100 }
10101
10102 #[test]
10103 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10104 let mut state = crate::land::tests::repair_state(true, true);
10105 state.status = RunStatus::Landing;
10106 state.parked = true;
10107 state.driver_exited = true;
10108 let mut q = ask::Question::new(
10109 state.id.clone(),
10110 land::APPROVAL_NODE.into(),
10111 "land".into(),
10112 "Merge?".into(),
10113 String::new(),
10114 vec![land::APPROVE.into(), land::HOLD.into()],
10115 );
10116 q.id = state.id.clone();
10117 state.land_approval = Some(crate::run::LandApproval {
10118 question: q.id.clone(),
10119 head: "current-head".into(),
10120 });
10121 assert!(land::upgrade_repair_choice(&mut q, &state));
10122 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10123 let mut task = held_task_with(&state.id);
10124 task.status = TaskStatus::Parked;
10125 assert_eq!(
10126 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10127 ActionDecision::Resume(state.id.clone())
10128 );
10129 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10130 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10131 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10132 assert_eq!(
10133 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10134 ActionDecision::Resume(state.id.clone()),
10135 "a repair answer newer than the manual hold resumes the existing owner"
10136 );
10137 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10138 for answered_at in [q.answered_at, None] {
10139 let mut older = q.clone();
10140 older.answered_at = answered_at;
10141 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10142 panic!("a later manual hold must prevent dispatch")
10143 });
10144 let ActionDecision::Refuse(reason) = refused else {
10145 panic!("expected an actionable refusal, got {refused:?}");
10146 };
10147 assert!(reason.contains("later operator decision"));
10148 assert!(reason.contains(&format!("magi task release {}", task.id)));
10149 }
10150 task.operator_decided_at = None;
10151 let mut superseded = state.clone();
10152 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10153 assert_eq!(
10154 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10155 ActionDecision::Stale
10156 );
10157 for case in 1..4 {
10158 let mut changed = state.clone();
10159 match case {
10160 1 => changed.status = RunStatus::Blocked,
10161 2 => changed.released_to = Some("new-owner".into()),
10162 _ => changed.land_approval.as_mut().unwrap().head.clear(),
10163 }
10164 assert!(matches!(
10165 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10166 ActionDecision::Refuse(_)
10167 ));
10168 }
10169 assert!(matches!(
10170 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10171 ActionDecision::Refuse(_)
10172 ));
10173 task.runs.push("replacement".into());
10174 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10175 assert_eq!(
10176 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10177 "old owner must not load"
10178 )),
10179 ActionDecision::Stale
10180 );
10181 }
10182
10183 #[test]
10184 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10185 let mut state = crate::land::tests::repair_state(true, true);
10186 state.status = RunStatus::Landing;
10187 state.parked = true;
10188 state.driver_exited = true;
10189 let mut q = ask::Question::new(
10190 state.id.clone(),
10191 land::APPROVAL_NODE.into(),
10192 "land".into(),
10193 "Merge?".into(),
10194 String::new(),
10195 vec![land::APPROVE.into(), land::HOLD.into()],
10196 );
10197 q.id = state.id.clone();
10198 state.land_approval = Some(crate::run::LandApproval {
10199 question: q.id.clone(),
10200 head: "current-head".into(),
10201 });
10202 state.save().unwrap();
10203 land::upgrade_repair_choice(&mut q, &state);
10204 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10205 Questions::open().put(&mut q).unwrap();
10206 let tmp = tempfile::tempdir().unwrap();
10207 let queue = Queue::at(tmp.path().join("queue"));
10208 let mut task = held_task_with(&state.id);
10209 task.status = TaskStatus::Parked;
10210 queue.put(&mut task).unwrap();
10211 let empty = Arc::new(tokio::sync::Semaphore::new(0));
10212 let free = Arc::new(tokio::sync::Semaphore::new(1));
10213 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10214 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10215 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10216 assert!(claim.permit.is_some());
10217 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10218 drop(claim);
10219 Questions::open()
10220 .update(&q.id, |q| {
10221 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10222 Ok(())
10223 })
10224 .unwrap();
10225 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10226 assert!(claim.permit.is_none());
10227 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10228 }
10229
10230 #[test]
10231 fn decide_action_resumes_only_the_latest_resumable_run() {
10232 let t = held_task_with("r1");
10233 let q = action_question("r1", resume_action("r1"));
10234 let load = |s: RunState| move |_: &str| Ok(s);
10235 assert_eq!(
10236 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10237 ActionDecision::Resume("r1".into())
10238 );
10239 let q_other = action_question("r1", resume_action("r0"));
10241 assert!(matches!(
10242 decide_action(
10243 &t,
10244 &q_other,
10245 &PHRASES_EN,
10246 load(run_state(RunStatus::Blocked))
10247 ),
10248 ActionDecision::Refuse(_)
10249 ));
10250 assert!(matches!(
10252 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10253 ActionDecision::Refuse(_)
10254 ));
10255 let mut released = run_state(RunStatus::Blocked);
10257 released.released_to = Some("elsewhere".into());
10258 assert!(matches!(
10259 decide_action(&t, &q, &PHRASES_EN, load(released)),
10260 ActionDecision::Refuse(_)
10261 ));
10262 assert!(matches!(
10264 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10265 ActionDecision::Refuse(_)
10266 ));
10267 }
10268
10269 #[test]
10270 fn decide_action_ignores_a_question_about_an_earlier_run() {
10271 let mut t = held_task_with("r1");
10272 t.runs.push("r2".to_owned());
10273 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10274 assert_eq!(
10275 decide_action(
10276 &t,
10277 &action_question("r1", ask::ChoiceAction::Done),
10278 &PHRASES_EN,
10279 never
10280 ),
10281 ActionDecision::Stale
10282 );
10283 }
10284
10285 #[test]
10286 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10287 let mut t = held_task_with("r1");
10288 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10289 assert_eq!(
10290 decide_action(
10291 &t,
10292 &action_question("r1", ask::ChoiceAction::Requeue),
10293 &PHRASES_EN,
10294 never
10295 ),
10296 ActionDecision::Requeue
10297 );
10298 let done_q = action_question("r1", ask::ChoiceAction::Done);
10299 assert_eq!(
10300 decide_action(&t, &done_q, &PHRASES_EN, never),
10301 ActionDecision::Done
10302 );
10303 t.mark_action_applied(&done_q.id);
10304 assert_eq!(
10305 decide_action(&t, &done_q, &PHRASES_EN, never),
10306 ActionDecision::Skip
10307 );
10308
10309 let mut plain = action_question("r1", ask::ChoiceAction::Done);
10311 plain.actions.clear();
10312 assert_eq!(
10313 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
10314 ActionDecision::Skip
10315 );
10316 let mut running = held_task_with("r1");
10318 running.status = TaskStatus::Running;
10319 assert_eq!(
10320 decide_action(
10321 &running,
10322 &action_question("r1", ask::ChoiceAction::Done),
10323 &PHRASES_EN,
10324 never
10325 ),
10326 ActionDecision::Skip
10327 );
10328 }
10329
10330 #[test]
10331 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
10332 crate::run::pin_test_home();
10333 for legacy in [false, true] {
10334 let dir = tempfile::tempdir().unwrap();
10335 let queue = Queue::at(dir.path().join("queue"));
10336 let questions = Questions::at(dir.path().join("questions"));
10337 let run = "20260101-000000-hold";
10338 let mut task = held_task_with(run);
10339 task.status = TaskStatus::Parked;
10340 let mut q = ask::Question::new(
10341 run.into(),
10342 land::APPROVAL_NODE.into(),
10343 "land".into(),
10344 "Repair?".into(),
10345 String::new(),
10346 vec![land::REPAIR.into()],
10347 );
10348 q.actions.insert(land::REPAIR.into(), resume_action(run));
10349 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10350 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10352 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
10353 questions.put(&mut q).unwrap();
10354 task.hold_manual(Some("Keep this PR paused".into()));
10355 if legacy {
10356 task.hold_source = None;
10357 }
10358 queue.put(&mut task).unwrap();
10359
10360 apply_choice_actions(&queue, &questions, dir.path());
10361 let after = queue.get(&task.id).unwrap();
10362 assert!(after.operator_held());
10363 assert_eq!(after.hold_source, task.hold_source);
10364 assert_eq!(after.operator_decided_at, task.operator_decided_at);
10365 assert_eq!(after.runs, task.runs);
10366 assert_eq!(after.instruction, task.instruction);
10367 assert!(after.resume_override.is_none());
10368 assert!(after.action_applied(&q.id));
10369 let reason = after.hold_reason.as_deref().unwrap();
10370 assert!(reason.starts_with("Keep this PR paused"));
10371 assert!(reason.contains("later operator decision"));
10372 assert!(reason.contains(&format!("magi task release {}", task.id)));
10373
10374 for recovery in [
10375 crate::conduct::Recovery::Review,
10376 crate::conduct::Recovery::Requeue,
10377 ] {
10378 crate::conduct::apply(
10379 &queue,
10380 &questions,
10381 &crate::conduct::Verdict {
10382 decisions: vec![crate::conduct::Decision {
10383 id: task.id.clone(),
10384 recovery: Some(recovery),
10385 ..Default::default()
10386 }],
10387 },
10388 )
10389 .unwrap();
10390 }
10391 apply_choice_actions(&queue, &questions, dir.path());
10394 let still_held = queue.get(&task.id).unwrap();
10395 assert!(still_held.operator_held());
10396 assert_eq!(still_held.hold_reason, after.hold_reason);
10397 assert_eq!(still_held.runs, task.runs);
10398 assert!(still_held.review_branch.is_none());
10399 assert!(!still_held.fresh_start);
10400 assert!(queue.next_runnable().is_none());
10401 }
10402 }
10403
10404 #[test]
10405 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
10406 for held in [false, true] {
10407 for retry in [false, true] {
10408 let dir = tempfile::tempdir().unwrap();
10409 let queue = Queue::at(dir.path().join("queue"));
10410 let questions = Questions::at(dir.path().join("questions"));
10411 let home = dir.path().join("home");
10412 let mut t = task();
10413 if held {
10414 t.hold_machine(Some("driver state unknown".into()));
10415 }
10416 queue.put(&mut t).unwrap();
10417 let verdict = serde_json::from_value(serde_json::json!({
10418 "decisions": [{
10419 "id": t.id,
10420 "question": "Driver state unknown; retry the checks or hold?",
10421 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
10422 "actions": {
10423 "daemon: recheck and retry": {"do": "requeue"},
10424 "daemon: hold the task": {"do": "hold"}
10425 }
10426 }]
10427 }))
10428 .unwrap();
10429 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
10430 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10431 let mut q = questions.list().pop().unwrap();
10432 let choice = if retry {
10433 "daemon: recheck and retry"
10434 } else {
10435 "daemon: hold the task"
10436 };
10437 assert_eq!(q.actions.len(), 2);
10438 q.answer(ask::Answer::Choice(choice.into())).unwrap();
10439 questions.put(&mut q).unwrap();
10440
10441 questions.beat(&q.id, ask::WaiterKind::Deputy);
10443 for _ in 0..2 {
10444 resolve_blockers(&queue, &questions);
10445 apply_choice_actions(&queue, &questions, &home);
10446 let waiting = queue.get(&t.id).unwrap();
10447 assert_eq!(waiting.status, TaskStatus::Blocked);
10448 assert_eq!(waiting.blocked_by, [q.id.clone()]);
10449 assert!(waiting.answers.is_empty());
10450 assert!(!waiting.action_applied(&q.id));
10451 assert!(runnable(&queue).is_empty());
10452 let free = Arc::new(tokio::sync::Semaphore::new(1));
10453 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
10454 }
10455 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10456
10457 resolve_blockers(&queue, &questions);
10459 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10460 apply_choice_actions(&queue, &questions, &home);
10461 let after = queue.get(&t.id).unwrap();
10462 assert_eq!(
10463 after.status,
10464 if retry {
10465 TaskStatus::Queued
10466 } else {
10467 TaskStatus::Held
10468 }
10469 );
10470 assert!(after.action_applied(&q.id));
10471 assert_eq!(after.operator_held(), !retry);
10472 assert_eq!(after.answers.len(), 1);
10473
10474 let mut changed = after;
10476 if retry {
10477 changed.hold_manual(Some("later hold".into()));
10478 } else {
10479 changed.release_operator("test", None);
10480 }
10481 let expected = changed.status;
10482 queue.put(&mut changed).unwrap();
10483 apply_choice_actions(&queue, &questions, &home);
10484 assert_eq!(queue.get(&t.id).unwrap().status, expected);
10485 }
10486 }
10487 }
10488
10489 #[test]
10490 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
10491 let dir = tempfile::tempdir().unwrap();
10492 let queue = Queue::at(dir.path().join("queue"));
10493 let questions = Questions::at(dir.path().join("questions"));
10494 let home = dir.path().join("home");
10495 let mut state = run_state(RunStatus::Blocked);
10496 state.id = "20260101-000000-act1".to_owned();
10497 state.save_under(&home).unwrap();
10498
10499 let mut t = held_task_with(&state.id);
10500 queue.put(&mut t).unwrap();
10501 let mut q = action_question(&state.id, resume_action(&state.id));
10502 questions.put(&mut q).unwrap();
10503
10504 apply_choice_actions(&queue, &questions, &home);
10505 let after = queue.get(&t.id).unwrap();
10506 assert_eq!(after.status, TaskStatus::Queued);
10507 assert!(!after.fresh_start);
10508 assert!(after.action_applied(&q.id));
10509 let pin = after.resume_override.clone().unwrap();
10510 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
10511 assert!(pin.forced);
10512
10513 let mut again = queue.get(&t.id).unwrap();
10515 again.hold_machine(Some("later".into()));
10516 queue.put(&mut again).unwrap();
10517 apply_choice_actions(&queue, &questions, &home);
10518 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10519 }
10520
10521 #[test]
10522 fn a_delivered_answer_is_still_acted_on_exactly_once() {
10523 let dir = tempfile::tempdir().unwrap();
10524 let queue = Queue::at(dir.path().join("queue"));
10525 let questions = Questions::at(dir.path().join("questions"));
10526 let home = dir.path().join("home");
10527 let mut state = run_state(RunStatus::Blocked);
10528 state.id = "20260101-000000-act2".to_owned();
10529 state.save_under(&home).unwrap();
10530
10531 let mut t = held_task_with(&state.id);
10532 queue.put(&mut t).unwrap();
10533 let mut q = action_question(&state.id, resume_action(&state.id));
10534 q.answer_delivered = true;
10535 questions.put(&mut q).unwrap();
10536
10537 apply_choice_actions(&queue, &questions, &home);
10540 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10541 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
10542
10543 let mut again = queue.get(&t.id).unwrap();
10545 again.hold_machine(Some("later".into()));
10546 queue.put(&mut again).unwrap();
10547 apply_choice_actions(&queue, &questions, &home);
10548 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10549 }
10550
10551 #[test]
10552 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
10553 let dir = tempfile::tempdir().unwrap();
10554 let queue = Queue::at(dir.path().join("queue"));
10555 let questions = Questions::at(dir.path().join("questions"));
10556 let home = dir.path().join("home");
10557 let mut state = run_state(RunStatus::Blocked);
10558 state.id = "20260101-000000-act3".to_owned();
10559 state.save_under(&home).unwrap();
10560 let mut t = held_task_with(&state.id);
10561 queue.put(&mut t).unwrap();
10562 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
10563 questions.put(&mut q).unwrap();
10564
10565 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
10566 apply_choice_actions(&queue, &questions, &home);
10567 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10568
10569 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10570 apply_choice_actions(&queue, &questions, &home);
10571 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10572 }
10573
10574 #[test]
10575 fn action_standing_tells_the_reasons_apart() {
10576 let mut t = held_task_with("r1");
10577 let q = action_question("r1", ask::ChoiceAction::Requeue);
10578 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10579 let mut plain = q.clone();
10580 plain.actions.clear();
10581 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
10582
10583 t.mark_action_applied(&q.id);
10585 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
10586
10587 let mut t = held_task_with("r1");
10589 t.start("r2".to_owned());
10590 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
10591 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
10593 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10594 t.status = TaskStatus::Blocked;
10595 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10596
10597 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
10599 c.node = crate::conduct::NODE.to_owned();
10600 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
10601 assert!(!ActionStanding::Busy.daemon_owns());
10602 }
10603
10604 #[test]
10605 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
10606 let dir = tempfile::tempdir().unwrap();
10607 let queue = Queue::at(dir.path().join("queue"));
10608 let questions = Questions::at(dir.path().join("questions"));
10609 let home = dir.path().join("home");
10610 let mut state = run_state(RunStatus::Blocked);
10611 state.id = "20260101-000000-act4".to_owned();
10612 state.save_under(&home).unwrap();
10613 let mut t = held_task_with(&state.id);
10614 t.status = TaskStatus::Running;
10615 queue.put(&mut t).unwrap();
10616 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
10617 q.cwd = Some(dir.path().display().to_string());
10618 questions.put(&mut q).unwrap();
10619
10620 let running = queue.get(&t.id).unwrap();
10623 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
10624 assert!(matches!(
10625 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
10626 crate::waiter::Action::Deliver(_)
10627 ));
10628 apply_choice_actions(&queue, &questions, &home);
10630 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10631 let mut back = queue.get(&t.id).unwrap();
10632 back.hold_machine(Some("later".into()));
10633 queue.put(&mut back).unwrap();
10634 apply_choice_actions(&queue, &questions, &home);
10635 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
10636 let mut again = queue.get(&t.id).unwrap();
10637 again.hold_machine(Some("again".into()));
10638 queue.put(&mut again).unwrap();
10639 apply_choice_actions(&queue, &questions, &home);
10640 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10641 }
10642}