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 a if a.maintenance() => ActionDecision::Skip,
921 ask::ChoiceAction::ResumeRun { .. }
922 | ask::ChoiceAction::ReleaseTask { .. }
923 | ask::ChoiceAction::RerunChecks { .. }
924 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
925 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
926 ask::ChoiceAction::Hold => ActionDecision::Hold,
927 ask::ChoiceAction::Done => ActionDecision::Done,
928 ask::ChoiceAction::Resume { run } => {
929 if task.runs.last() != Some(run) {
930 return ActionDecision::Refuse((p.resume_not_latest)(
931 q.short(),
932 ask::short_id(run),
933 ));
934 }
935 match load(run) {
936 Ok(s) if stopping => {
937 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
938 || !s
939 .land_approval
940 .as_ref()
941 .is_some_and(|binding| binding.question == q.id)
942 {
943 ActionDecision::Stale
944 } else if s.liveness(false) == Liveness::Live {
945 ActionDecision::Skip
946 } else if s.status == RunStatus::Landing
947 && !s.released()
948 && s.retired_to.is_none()
949 {
950 ActionDecision::Resume(run.clone())
951 } else {
952 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
953 }
954 }
955 Ok(s)
956 if q.node == land::APPROVAL_NODE
957 && q.resolution().as_deref() == Some(land::REPAIR) =>
958 {
959 if s.merge_repairs.iter().any(|r| r.question == q.id)
960 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
961 {
962 ActionDecision::Stale
965 } else if s.liveness(false) == Liveness::Live {
966 ActionDecision::Skip
967 } else if s.status != RunStatus::Landing
968 || s.released()
969 || s.reviews.is_empty()
970 || !implementers_match(task, &s)
971 || !s
972 .land_approval
973 .as_ref()
974 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
975 {
976 ActionDecision::Refuse(format!(
977 "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",
978 q.id, run, run
979 ))
980 } else {
981 ActionDecision::Resume(run.clone())
982 }
983 }
984 Ok(s) if s.liveness(false) == Liveness::Live => {
985 ActionDecision::Refuse("run already has a live driver".into())
986 }
987 Ok(s)
988 if s.status.resumable()
989 && !s.released()
990 && s.retired_to.is_none()
991 && !exhausted_review_budget(&s) =>
992 {
993 ActionDecision::Resume(run.clone())
994 }
995 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
996 q.short(),
997 ask::short_id(run),
998 )),
999 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1000 q.short(),
1001 ask::short_id(run),
1002 &format!("{e:#}"),
1003 )),
1004 }
1005 }
1006 }
1007}
1008
1009struct Phrases {
1023 graph_stopped: fn(&str, &str) -> String,
1025 quorum_lost: &'static str,
1026 quota_took_out: &'static str,
1028 run_ended: &'static str,
1030 waiting_for_answer: &'static str,
1032 recovered_running: &'static str,
1033 no_run_to_recover: &'static str,
1034 could_not_start: &'static str,
1035 resume_not_latest: fn(&str, &str) -> String,
1036 resume_cannot_progress: fn(&str, &str) -> String,
1037 resume_unreadable: fn(&str, &str, &str) -> String,
1038 handover_refused: fn(&crate::handover::Refused) -> String,
1041 handover_hint: &'static str,
1043 reviewers_never_answered: fn(usize, usize) -> String,
1046}
1047
1048const PHRASES_EN: Phrases = Phrases {
1049 graph_stopped: |status, detail| {
1050 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1051 },
1052 quorum_lost: "the judging panel lost its quorum",
1053 quota_took_out: "; quota took out ",
1054 run_ended: "run ended ",
1055 waiting_for_answer: " - waiting for operator answer to question ",
1056 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1057 no_run_to_recover: "task was `running` with no live daemon and no readable \
1058 run to recover; held for a human to check what happened",
1059 could_not_start: "could not start the run: ",
1060 resume_not_latest: |q, run| {
1061 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1062 },
1063 resume_cannot_progress: |q, run| {
1064 format!("question {q} asked to resume run {run}, which cannot make progress")
1065 },
1066 resume_unreadable: |q, run, e| {
1067 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1068 },
1069 handover_refused: |r| r.to_string(),
1070 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1071 reviewers_never_answered: |missing, rounds| {
1072 format!(
1073 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1074 refusing to call it clean"
1075 )
1076 },
1077};
1078
1079const PHRASES_JA: Phrases = Phrases {
1080 graph_stopped: |status, detail| {
1081 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1082 },
1083 quorum_lost: "審査パネルが定足数を失いました",
1084 quota_took_out: "。クォータで脱落: ",
1085 run_ended: "run 終了: ",
1086 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1087 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1088 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1089 何が起きたか人が確認するため保留にしました",
1090 could_not_start: "run を開始できませんでした: ",
1091 resume_not_latest: |q, run| {
1092 format!(
1093 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1094 )
1095 },
1096 resume_cannot_progress: |q, run| {
1097 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1098 },
1099 resume_unreadable: |q, run, e| {
1100 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1101 },
1102 handover_refused: |r| {
1103 use crate::handover::Refused;
1104 match r {
1105 Refused::Foreign { branch, path, why } => format!(
1106 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1107 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1108 から、やり直してください(詳細: {why})"
1109 ),
1110 Refused::Unsafe { branch, path, why } => format!(
1111 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1112 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1113 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1114 ),
1115 Refused::ReleaseFailed { branch, path, run } => format!(
1116 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1117 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1118 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1119 ),
1120 }
1121 },
1122 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1123 reviewers_never_answered: |missing, rounds| {
1124 format!(
1125 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1126 クリーンとは認めません"
1127 )
1128 },
1129};
1130
1131fn phrases(language: &str) -> &'static Phrases {
1132 if crate::lang::is_japanese(language) {
1133 &PHRASES_JA
1134 } else {
1135 &PHRASES_EN
1136 }
1137}
1138
1139fn language_of(task: &Task, fallback: &Path) -> String {
1143 crate::lang::of_repo(&repo_for(task, fallback))
1144}
1145
1146pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1150 if q.node == crate::conduct::NODE {
1151 return tasks.iter().find(|t| t.id == q.run);
1152 }
1153 tasks.iter().find(|t| t.runs.contains(&q.run))
1154}
1155
1156fn repair_choice_offers(questions: &Questions) {
1159 for q in questions.list().into_iter().filter(|q| {
1160 q.status.open()
1161 && q.node == crate::conduct::NODE
1162 && q.choices
1163 .iter()
1164 .any(|c| crate::choice_effect::describe(q, c).is_none())
1165 }) {
1166 let _ = questions.update(&q.id, |current| {
1167 if current.status.open() {
1168 crate::choice_effect::executable_conductor(current);
1169 if let Some(deputy) = &mut current.deputy {
1170 deputy.brief = crate::deputy::brief(
1171 ¤t.run,
1172 ¤t.detail,
1173 ¤t.choices,
1174 ¤t.actions,
1175 );
1176 }
1177 }
1178 Ok(())
1179 });
1180 }
1181}
1182
1183pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1186 apply_maintenance_choices(queue, questions, home).await;
1187 apply_task_choice_actions(queue, questions, home);
1188}
1189
1190async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1193 for q in questions.list() {
1194 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1195 continue;
1196 };
1197 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1200 continue;
1201 }
1202 let dir = home.join("choice-actions");
1203 if std::fs::create_dir_all(&dir).is_err() {
1204 continue;
1205 }
1206 let Ok(lock) = std::fs::OpenOptions::new()
1207 .create(true)
1208 .truncate(false)
1209 .write(true)
1210 .open(dir.join(format!("{}.lock", q.id)))
1211 else {
1212 continue;
1213 };
1214 if crate::pr_head::try_lock_file(&lock).is_err() {
1215 continue;
1216 }
1217 let fresh = !home
1218 .join("choice-actions")
1219 .join(format!("{}.json", q.id))
1220 .exists();
1221 let result = async {
1222 let receipt = dir.join(format!("{}.json", q.id));
1223 if receipt.exists() {
1224 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1225 anyhow::ensure!(
1226 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1227 "previous maintenance attempt did not confirm completion; inspect its receipt"
1228 );
1229 return Ok::<_, anyhow::Error>(());
1230 }
1231 let record = |status: &str| -> anyhow::Result<()> {
1234 let tmp = receipt.with_extension("tmp");
1235 std::fs::write(
1236 &tmp,
1237 serde_json::to_vec(&serde_json::json!({
1238 "action": action, "status": status,
1239 }))?,
1240 )?;
1241 std::fs::rename(tmp, &receipt)?;
1242 Ok(())
1243 };
1244 let applied = async {
1245 match action {
1246 ask::ChoiceAction::ResumeRun { run } => {
1247 crate::resume::validate(home, run)?;
1248 record("started")?;
1249 if !crate::resume::pin_queued(queue, run, Some(q.asked_at), Some(&q.id))? {
1250 crate::resume::validate_unqueued(home, run)?;
1251 crate::resume::start(run.clone());
1252 }
1253 }
1254 ask::ChoiceAction::ReleaseTask {
1255 task,
1256 held_at,
1257 reason,
1258 } => {
1259 anyhow::ensure!(
1260 queue.resolve_id(task)? == *task,
1261 "task action requires an exact task ID"
1262 );
1263 let _claim = queue.claim(task)?;
1264 let mut task = queue.get(task)?;
1265 if task.action_applied(&q.id) {
1266 return Ok(());
1267 }
1268 if q.node == crate::conduct::NODE
1273 && q.run == task.id
1274 && task.status == TaskStatus::Blocked
1275 && task.blocked_from == Some(TaskStatus::Held)
1276 && task.blocked_by.as_slice() == [q.id.as_str()]
1277 {
1278 task.unblock(&q.id);
1279 }
1280 anyhow::ensure!(
1281 task.status == TaskStatus::Held
1282 && task.held_at == Some(*held_at)
1283 && task.hold_reason.as_deref() == reason.as_deref()
1284 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1285 "task no longer has the hold this question names"
1286 );
1287 task.release_operator("choice", Some(&q.id));
1288 task.mark_action_applied(&q.id);
1289 queue.put(&mut task)?;
1290 }
1291 ask::ChoiceAction::AbandonRun { run } => {
1292 record("started")?;
1293 crate::driver::abandon_proven_dead(home, run)?;
1294 }
1295 ask::ChoiceAction::RerunChecks {
1296 repo,
1297 pr,
1298 head,
1299 runs,
1300 } => {
1301 rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1302 .await?;
1303 }
1304 _ => unreachable!(),
1305 }
1306 Ok::<_, anyhow::Error>(())
1307 }
1308 .await;
1309 match applied {
1310 Ok(()) => record("applied"),
1311 Err(e) => {
1312 record(&format!("refused or failed: {e:#}"))?;
1313 Err(e)
1314 }
1315 }
1316 }
1317 .await;
1318 if home
1323 .join("choice-actions")
1324 .join(format!("{}.json", q.id))
1325 .exists()
1326 && let Some(listed) = task_of_question(&queue.list(), &q)
1327 && !listed.action_applied(&q.id)
1328 && let Ok(_claim) = queue.claim(&listed.id)
1329 && let Ok(mut origin) = queue.get(&listed.id)
1330 {
1331 if !origin.operator_held()
1332 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1333 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1334 {
1335 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1336 origin.hold_machine(Some(format!(
1337 "Maintenance choice {} settled; inspect its target before releasing this task",
1338 q.id
1339 )));
1340 } else {
1341 origin.unblock(&q.id);
1342 }
1343 }
1344 origin.mark_action_applied(&q.id);
1345 let _ = queue.put(&mut origin);
1346 }
1347 if let Err(e) = result
1348 && fresh
1349 {
1350 notices::raise_in(
1351 home,
1352 Notice::warn(
1353 &format!("action:{}", q.id),
1354 format!("Choice action {} was not completed: {e:#}", q.id),
1355 ),
1356 );
1357 }
1358 }
1359}
1360
1361pub(crate) async fn rerun_checks_once(
1368 home: &Path,
1369 request: &str,
1370 repo: &Path,
1371 pr: &str,
1372 head: &str,
1373 runs: &[String],
1374 started: impl FnOnce() -> anyhow::Result<()>,
1375) -> anyhow::Result<()> {
1376 use crate::release_watch::{GhForge, ReleaseForge};
1377 anyhow::ensure!(
1378 !runs.is_empty()
1379 && runs.len() <= 20
1380 && runs
1381 .iter()
1382 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1383 && !pr.starts_with('-'),
1384 "invalid rerun targets"
1385 );
1386 let snap = GhForge.snapshot(repo, pr).await?;
1387 anyhow::ensure!(
1388 snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1389 "pull request head or lifecycle changed"
1390 );
1391 anyhow::ensure!(
1392 runs.iter().all(|r| snap
1393 .checks
1394 .iter()
1395 .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1396 "named workflow is no longer failed on this pull request"
1397 );
1398 started()?;
1399 let dir = home.join("choice-actions");
1400 std::fs::create_dir_all(&dir)?;
1401 let rerun_lock = std::fs::OpenOptions::new()
1402 .create(true)
1403 .truncate(false)
1404 .write(true)
1405 .open(dir.join("reruns.lock"))?;
1406 crate::pr_head::try_lock_file(&rerun_lock)?;
1407 let ledger = dir.join("reruns.json");
1408 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1409 serde_json::from_slice(&std::fs::read(&ledger)?)?
1410 } else {
1411 Default::default()
1412 };
1413 for run in runs {
1414 let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1415 if !recorded.insert(key) {
1416 continue;
1417 }
1418 let tmp = ledger.with_extension("tmp");
1419 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1420 std::fs::rename(tmp, &ledger)?;
1421 GhForge.rerun(repo, run).await?;
1422 }
1423 Ok(())
1424}
1425
1426pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1435 let tasks = queue.list();
1436 for q in questions.list() {
1437 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1439 continue;
1440 }
1441 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1442 continue;
1443 }
1444 let Some(listed) = task_of_question(&tasks, &q) else {
1445 if q.node == land::APPROVAL_NODE
1446 && q.resolution().as_deref().is_some_and(|choice| {
1447 choice == land::REPAIR || crate::merge_decision::stops(choice)
1448 })
1449 {
1450 notices::raise_in(
1451 home,
1452 Notice::warn(
1453 &format!("repair-owner:{}", q.id),
1454 format!(
1455 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1456 q.run, q.run
1457 ),
1458 ),
1459 );
1460 }
1461 continue;
1462 };
1463 if listed.action_applied(&q.id) {
1464 continue;
1465 }
1466 let Ok(_claim) = queue.claim(&listed.id) else {
1467 continue;
1468 };
1469 let Ok(mut task) = queue.get(&listed.id) else {
1470 continue;
1471 };
1472 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1475 let blockers: Vec<_> = task
1476 .blocked_by
1477 .iter()
1478 .filter(|id| {
1479 crate::queue::dependency(queue, questions, id)
1480 == crate::queue::Dependency::Question(q.id.clone())
1481 })
1482 .cloned()
1483 .collect();
1484 if !blockers.is_empty() {
1485 for id in blockers {
1486 task.unblock(&id);
1487 }
1488 let answer = match &q.answer {
1489 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1490 None => String::new(),
1491 };
1492 task.record_answer(q.summary.clone(), answer);
1493 }
1494 }
1495 let language = language_of(&task, Path::new("."));
1496 let decision = decide_action(&task, &q, phrases(&language), |id| {
1497 RunState::load_under(id, home)
1498 });
1499 let ran = matches!(
1500 decision,
1501 ActionDecision::Resume(_)
1502 | ActionDecision::Requeue
1503 | ActionDecision::Hold
1504 | ActionDecision::Done
1505 );
1506 if ran && asker_may_still_read(questions, &q, home) {
1507 continue;
1516 }
1517 let done = matches!(decision, ActionDecision::Done);
1518 match decision {
1519 ActionDecision::Skip => continue,
1520 ActionDecision::Resume(run) => {
1521 task.release_operator("choice", Some(&q.id));
1522 task.resume_override = Some(crate::queue::OperatorResume {
1523 question_id: q.id.clone(),
1524 at: Timestamp::now(),
1525 conductor_rehold: None,
1526 forced: true,
1527 pinned_run: Some(run),
1528 });
1529 }
1530 ActionDecision::Stale => {}
1531 ActionDecision::Requeue => {
1532 task.release_operator("choice-requeue", Some(&q.id));
1533 task.requeue();
1534 }
1535 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1536 ActionDecision::Done => task.succeed(),
1537 ActionDecision::Refuse(why) => {
1538 if task.operator_held() {
1539 task.hold_reason = Some(match task.hold_reason.take() {
1542 Some(reason) => format!("{reason}\n\n{why}"),
1543 None => why,
1544 });
1545 } else {
1546 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1547 task.hold_machine(Some(why));
1548 }
1549 notices::raise(
1550 Notice::warn(
1551 &format!("action:{}", q.id),
1552 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1553 )
1554 .link(Link::Task {
1555 id: task.id.clone(),
1556 }),
1557 );
1558 }
1559 }
1560 task.mark_action_applied(&q.id);
1561 record(queue, &mut task);
1564 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1565 supersede_prior_runs(&task, home);
1566 }
1567 let _ = questions.update(&q.id, |r| {
1570 r.answer_delivered = true;
1571 Ok(())
1572 });
1573 }
1574}
1575
1576fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1580 let now = Timestamp::now();
1581 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1582 return true;
1583 }
1584 q.node != crate::conduct::NODE
1585 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1586 s.seats_active()
1587 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1588 })
1589}
1590
1591fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1602 let tasks = queue.list();
1603 let by_id: std::collections::BTreeMap<&str, &Task> =
1604 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1605 let referenced: Vec<&str> = tasks
1606 .iter()
1607 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1608 .collect();
1609
1610 for mut question in questions.list() {
1611 if !question.status.open() || question.node != crate::conduct::NODE {
1612 continue;
1613 }
1614 if referenced
1619 .iter()
1620 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1621 {
1622 continue;
1623 }
1624 let Some(task) = by_id.get(question.run.as_str()) else {
1625 continue;
1626 };
1627 question.abandon(format!(
1628 "task {} no longer waits for this answer",
1629 task.short()
1630 ));
1631 if let Err(e) = questions.put(&mut question) {
1632 tracing::warn!(
1633 "could not retire question {} for task {}: {e:#}",
1634 question.short(),
1635 task.short()
1636 );
1637 }
1638 }
1639}
1640
1641#[derive(Debug, Clone, Copy)]
1648pub struct Verdict {
1649 pub status: RunStatus,
1651 pub left_pr: bool,
1653 pub quota_hit: bool,
1655 pub parked: bool,
1657 pub no_viable_candidates: bool,
1664}
1665
1666pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1723 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1724}
1725
1726fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1728 if verdict.parked {
1734 task.park(detail);
1735 return;
1736 }
1737 match verdict.status {
1738 RunStatus::Merged | RunStatus::Ready
1739 if task.pr_recovery.as_ref().is_some_and(|s| {
1740 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1741 }) =>
1742 {
1743 task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1744 }
1745 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1746 RunStatus::AlreadyInBase => task.already_landed(detail),
1747 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1748 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1749 task.stall(detail)
1750 }
1751 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1752 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1753 RunStatus::Blocked => task.fail(detail, max_attempts),
1754 RunStatus::VerifiedNoop => task.handed_off(detail),
1755 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1756 }
1757}
1758
1759pub fn supersede_prior_runs(task: &Task, home: &Path) {
1808 let now = Timestamp::now();
1809 let last_run_succeeded = task
1816 .runs
1817 .last()
1818 .and_then(|id| RunState::load_under(id, home).ok())
1819 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1820 for id in task.superseded_attempts(last_run_succeeded) {
1821 let mut state = match RunState::load_under(id, home) {
1822 Ok(s) => s,
1823 Err(e) => {
1824 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1825 continue;
1826 }
1827 };
1828 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1829 continue;
1830 }
1831 let daemon_claims = is_working_on(home, id, now);
1832 if state.liveness(daemon_claims) == Liveness::Live {
1833 continue;
1834 }
1835 state.status = RunStatus::Superseded;
1836 if let Err(e) = state.save_under(home) {
1837 tracing::warn!("could not mark run {id} superseded: {e:#}");
1838 }
1839 }
1840}
1841
1842fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1864 for task in queue.list() {
1865 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1866 continue;
1867 }
1868 supersede_prior_runs(&task, home);
1869 }
1870}
1871
1872fn settle_and_diagnose(
1879 task: &mut Task,
1880 verdict: Verdict,
1881 detail: &str,
1882 max_attempts: usize,
1883 state: &RunState,
1884) {
1885 let p = phrases(&state.config.graph.language);
1886 if let Some(d) = &state.merge_decision {
1889 use crate::merge_decision as md;
1890 if task.runs.last().is_some_and(|id| id != &state.id) {
1891 return;
1892 }
1893 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1894 task.succeed();
1895 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1896 if state.liveness(false) != Liveness::Dead {
1897 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1898 return;
1899 }
1900 let replacement = md::Replacement {
1901 question: d.question.clone(),
1902 run: state.id.clone(),
1903 pr: d.target.pr.clone(),
1904 agent: agent.to_owned(),
1905 context: format!(
1906 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1907 d.target.pr,
1908 state.id,
1909 serde_json::to_string(&state.reviews).unwrap_or_default()
1910 ),
1911 };
1912 task.requeue();
1913 task.pr_recovery = None;
1914 task.review_of = None;
1915 task.replacement = Some(replacement);
1916 } else {
1917 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1918 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1919 } 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())) }));
1920 }
1921 task.mark_action_applied(&d.question);
1922 if let Some(pass) = state.passes.last() {
1923 task.record_pass(&state.id, pass.index, task.attempts, None);
1924 }
1925 return;
1926 }
1927 if let Some(replacement) = &task.replacement
1928 && !state.parked
1929 && state.resource_block.is_none()
1930 && (state.viable().is_empty()
1931 || (state.status == RunStatus::Blocked && state.tally.is_none()))
1932 {
1933 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)));
1934 return;
1935 }
1936 let attempts_before = task.attempts;
1937 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1943 task.notice_cause(
1944 &format!("resource:{}:{}", block.kind, block.node),
1945 None,
1946 None,
1947 );
1948 task.last_error = Some(detail.to_owned());
1949 task.diagnostic = None;
1950 task.attempts = task.attempts.saturating_sub(1);
1951 if block.kind == "disk pressure" {
1952 task.hold_machine(Some(format!(
1953 "{}{}",
1954 crate::disk::RUNNING_PRESSURE,
1955 block.detail
1956 )));
1957 } else {
1958 task.hold_machine(Some(format!(
1959 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1960 no agent was asked and no attempt was spent",
1961 crate::cache::RESOURCE_HOLD,
1962 block.kind,
1963 block.node
1964 )));
1965 }
1966 if let Some(pass) = state.passes.last() {
1967 task.record_pass(&state.id, pass.index, attempts_before, None);
1968 }
1969 return;
1970 }
1971 let unresolved = task.hold_notice_cause.clone();
1972 if !verdict.parked
1973 && task
1974 .pr_recovery
1975 .as_ref()
1976 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1977 && matches!(
1978 verdict.status,
1979 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1980 )
1981 {
1982 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1983 task.succeed();
1984 } else {
1985 task.hold_manual(Some("Selected PR delivery is incomplete: local review or publication is not a confirmed public merge. Inspect the run and PR; use recover-pr --disposition land with --source-head <reviewed-full-SHA> and the required verification configuration. No automatic new attempt will start.".into()));
1986 }
1987 } else if !verdict.parked
1988 && task.pr_recovery.is_some()
1989 && matches!(
1990 verdict.status,
1991 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
1992 )
1993 && !verdict.quota_hit
1994 {
1995 task.hold_unrequested_retry(Some(format!("Selected recovery stopped: {detail}. Inspect the retained source and run; correct the cause before explicitly releasing or selecting again. No automatic replacement will start.")));
1996 } else {
1997 settle_in(task, verdict, detail, max_attempts, p);
1998 }
1999 if !verdict.parked
2000 && !verdict.quota_hit
2001 && matches!(
2002 verdict.status,
2003 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2004 )
2005 {
2006 task.recovery_failed(state);
2007 }
2008 if state.prep_failure.is_some() {
2009 task.hold_notice_cause = unresolved;
2012 task.startup_notice_cause("startup-candidates");
2013 }
2014 if let Some(pass) = state.passes.last() {
2017 let parked = match &pass.end {
2018 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2019 _ => None,
2020 };
2021 task.record_pass(&state.id, pass.index, attempts_before, parked);
2022 }
2023 if task.status == TaskStatus::Held {
2024 if state.prep_failure.is_none() {
2025 task.notice_cause(
2026 label(verdict.status),
2027 Some(&state.id),
2028 state.passes.last().map(|p| p.index),
2029 );
2030 }
2031 task.diagnostic = diagnostic(state);
2032 note_open_question(task, &state.id, p);
2033 }
2034}
2035
2036fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2051 let Some(home) = crate::run::try_home() else {
2052 return;
2053 };
2054 let open = Questions::at(home.join("questions")).open_for(run);
2055 let Some(q) = open.first() else {
2056 return;
2057 };
2058 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2059 decisions.sort_unstable();
2060 task.notice_cause(
2061 &format!("questions:{}", decisions.join(",")),
2062 Some(run),
2063 None,
2064 );
2065 let base = task.hold_reason.clone().unwrap_or_default();
2066 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2067}
2068
2069fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2080 match last_run {
2081 Some(state) => {
2082 let verdict = Verdict {
2083 status: state.status,
2084 left_pr: state.pr.is_some(),
2085 quota_hit: !state.quota.is_empty(),
2086 parked: state.parked,
2087 no_viable_candidates: state.viable().is_empty(),
2088 };
2089 let detail = format!(
2090 "{}{}",
2091 phrases(&state.config.graph.language).recovered_running,
2092 describe(&state)
2093 );
2094 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2095 }
2096 None => {
2097 let why = phrases(language).no_run_to_recover;
2100 task.last_error = Some(why.to_owned());
2101 task.notice_cause("missing-run", None, None);
2104 task.hold_machine(Some(why.to_owned()));
2105 }
2106 }
2107}
2108
2109fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2131 let mut reclaimed = Vec::new();
2132 for listed in queue.list() {
2133 if listed.status != TaskStatus::Running {
2134 continue;
2135 }
2136 let Ok(_claim) = queue.claim(&listed.id) else {
2137 continue;
2138 };
2139 let Ok(mut task) = queue.get(&listed.id) else {
2143 continue;
2144 };
2145 if task.status != TaskStatus::Running {
2146 continue;
2147 }
2148 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2149 if let Some(state) = &last_run
2159 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2160 {
2161 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2162 }
2163 let language = if last_run.is_none() {
2164 language_of(&task, Path::new("."))
2165 } else {
2166 String::new()
2167 };
2168 reclaim(&mut task, last_run, max_attempts, &language);
2169 if task.status == TaskStatus::Done {
2170 supersede_prior_runs(&task, &crate::run::home());
2171 }
2172 record(queue, &mut task);
2173 reclaimed.push(task.id.clone());
2174 }
2175 reclaimed
2176}
2177
2178fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2210 reclaim_abandoned_runs_with(
2211 home,
2212 now,
2213 crate::proc::pid_status,
2214 crate::proc::process_started_at,
2215 )
2216}
2217
2218fn reclaim_abandoned_runs_with<F, G>(
2224 home: &Path,
2225 now: Timestamp,
2226 query: F,
2227 identity: G,
2228) -> Vec<String>
2229where
2230 F: Fn(u32) -> Option<bool>,
2231 G: Fn(u32) -> Option<String>,
2232{
2233 let mut abandoned = Vec::new();
2234 for entry in std::fs::read_dir(home.join("runs"))
2235 .into_iter()
2236 .flatten()
2237 .flatten()
2238 {
2239 let id = entry.file_name().to_string_lossy().into_owned();
2240 if !crate::run::is_run_id(&id) {
2241 continue;
2242 }
2243 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2246 continue;
2247 };
2248 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2256 continue;
2257 };
2258 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2259 continue;
2260 };
2261 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2262 continue;
2263 }
2264 let daemon_claims = is_working_on(home, &id, now);
2276 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2277 != crate::run::Liveness::Dead
2278 {
2279 continue;
2280 }
2281 state.abandon("daemon");
2282 if let Err(e) = state.save_under(home) {
2283 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2284 continue;
2285 }
2286 if let Some(notice) = notices::run_ended(&state) {
2289 notices::raise_in(home, notice);
2290 }
2291 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2299 tracing::warn!("abandon questions for {id}: {e:#}");
2300 }
2301 abandoned.push(id);
2302 }
2303 abandoned
2304}
2305
2306pub async fn serve(opts: Opts) -> Result<()> {
2312 serve_until(opts, Stop::new()).await
2313}
2314
2315pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2332 let signal = {
2333 let stop = stop.clone();
2334 tokio::spawn(async move {
2335 if tokio::signal::ctrl_c().await.is_ok() {
2336 stop.stop();
2337 tracing::info!("shutdown requested; a run in flight will be finished first");
2338 }
2339 })
2340 };
2341
2342 let worktrees_root = opts
2343 .worktrees_root
2344 .clone()
2345 .unwrap_or_else(crate::run::default_worktree_root);
2346 let outcome = drive(
2347 &opts,
2348 &Queue::open(),
2349 &status_path(),
2350 &crate::run::home(),
2351 &worktrees_root,
2352 &stop,
2353 )
2354 .await;
2355
2356 signal.abort();
2357 outcome
2358}
2359
2360async fn drive(
2373 opts: &Opts,
2374 queue: &Queue,
2375 status_file: &Path,
2376 home: &Path,
2377 worktrees_root: &Path,
2378 stop: &Stop,
2379) -> Result<()> {
2380 let recovery_cfg = prepare(&opts.repo, opts).ok();
2388 let daemon_cfg = recovery_cfg
2389 .as_ref()
2390 .map(|c| c.daemon.clone())
2391 .unwrap_or_default();
2392 let reconciled = crate::driver::reconcile(home);
2393 if !reconciled.is_empty() {
2394 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2395 }
2396 let mut initial_status = Status::new();
2397 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2398 recovery_cfg.as_ref(),
2399 daemon_cfg.max_deputies,
2400 ));
2401 let status = Arc::new(Mutex::new(initial_status));
2402 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2403 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2404
2405 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2411
2412 let waiter = tokio::spawn(crate::waiter::run(
2417 crate::waiter::Waiter::new(
2418 crate::ask::Questions::at(home.join("questions")),
2419 home.to_path_buf(),
2420 recovery_cfg.clone(),
2421 ),
2422 stop.clone(),
2423 ));
2424
2425 let deputies = tokio::spawn(crate::deputy::run(
2429 crate::deputy::Deputies::new(
2430 crate::ask::Questions::at(home.join("questions")),
2431 home.to_path_buf(),
2432 recovery_cfg.clone(),
2433 opts.repo.clone(),
2434 daemon_cfg.max_deputies,
2435 {
2436 let stop = stop.clone();
2437 Arc::new(move || stop.parking())
2438 },
2439 ),
2440 stop.clone(),
2441 ));
2442
2443 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2446
2447 let release_watch = tokio::spawn(crate::release_watch::run(
2450 crate::release_watch::Watcher::new(
2451 Box::new(crate::release_watch::GhForge),
2452 home.to_path_buf(),
2453 ),
2454 {
2455 let (repo, opts) = (opts.repo.clone(), opts.clone());
2456 move || release_watch_settings(&repo, &opts)
2457 },
2458 stop.clone(),
2459 ));
2460
2461 tracing::info!(
2462 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2463 queue.root().display(),
2464 opts.poll.as_secs(),
2465 opts.max_attempts,
2466 concurrency,
2467 if daemon_cfg.pause_for_interrupts {
2468 ", interrupts enabled"
2469 } else {
2470 ""
2471 }
2472 );
2473
2474 janitor(&opts.repo, opts, home, worktrees_root).await;
2477 resweep_superseded_attempts(queue, home);
2478
2479 let outcome = poll(
2480 opts,
2481 queue,
2482 &status,
2483 home,
2484 worktrees_root,
2485 stop,
2486 DispatchLimits {
2487 max_concurrent: concurrency,
2488 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2489 },
2490 )
2491 .await;
2492
2493 beat.abort();
2494 waiter.abort();
2495 deputies.abort();
2496 fetcher.abort();
2497 release_watch.abort();
2498 clear_status_at(status_file);
2499 outcome
2500}
2501
2502fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2505 let Ok(cfg) = prepare(repo, opts) else {
2506 return (Vec::new(), 0);
2507 };
2508 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2509 .into_iter()
2510 .map(|r| r.path)
2511 .collect();
2512 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2515 let runs = crate::run::home().join("runs");
2516 for id in crate::run::list_ids_in(&runs) {
2517 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2518 .ok()
2519 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2520 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2521 known.extend(repo);
2522 }
2523 for k in known {
2524 let k = k.canonicalize().unwrap_or(k);
2525 if k.join(".git").exists() && !paths.contains(&k) {
2526 paths.push(k);
2527 }
2528 }
2529 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2530 if !paths.contains(&own) {
2531 paths.push(own);
2532 }
2533 (paths, cfg.daemon.release_stall_minutes)
2534}
2535
2536const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2538
2539async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2543 while !stop.stopped() {
2544 let (interval, roots) = match prepare(&repo, &opts) {
2545 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2546 Err(_) => (0, Vec::new()),
2547 };
2548 if interval > 0 && !roots.is_empty() {
2549 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2550 tracing::debug!("fetch origins: {r:?}");
2551 }
2552 let wait = if interval > 0 { interval } else { 60 };
2554 let mut slept = 0;
2555 while slept < wait && !stop.stopped() {
2556 tokio::time::sleep(Duration::from_secs(1)).await;
2557 slept += 1;
2558 }
2559 }
2560}
2561
2562async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2568 loop {
2569 tokio::time::sleep(HEARTBEAT).await;
2570 let snapshot = {
2571 let mut guard = lock(&status);
2572 guard.updated_at = Timestamp::now();
2573 guard.clone()
2574 };
2575 if let Err(e) = write_status_to(&path, &snapshot) {
2576 tracing::warn!("could not refresh the daemon status file: {e:#}");
2579 }
2580 }
2581}
2582
2583#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2586enum LandResume {
2587 NotLanding,
2590 StillWaiting,
2595 Ready,
2599}
2600
2601fn land_resume_state(task: &Task) -> LandResume {
2605 let Some(run_id) = task.runs.last() else {
2606 return LandResume::NotLanding;
2607 };
2608 let Ok(state) = RunState::load(run_id) else {
2609 return LandResume::NotLanding;
2610 };
2611 if !state.parked {
2612 return LandResume::NotLanding;
2613 }
2614 if state.status == RunStatus::Landing
2615 && state.land_approval.as_ref().is_some_and(|binding| {
2616 ask::Questions::open()
2617 .get(&binding.question)
2618 .is_ok_and(|q| {
2619 q.run == state.id
2620 && q.resolution()
2621 .as_deref()
2622 .is_some_and(crate::merge_decision::stops)
2623 })
2624 })
2625 {
2626 return LandResume::Ready;
2627 }
2628 if !implementers_match(task, &state) {
2629 return LandResume::NotLanding;
2630 }
2631 let node = if state.status == RunStatus::Landing {
2635 land::APPROVAL_NODE
2636 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2637 crate::github_text::ASK_NODE
2638 } else {
2639 return LandResume::NotLanding;
2640 };
2641 let store = ask::Questions::open();
2642 let waiting = store
2643 .list()
2644 .into_iter()
2645 .filter(|q| &q.run == run_id && q.node == node)
2646 .max_by(|a, b| a.id.cmp(&b.id));
2647 let Some(mut q) = waiting else {
2648 return LandResume::Ready;
2649 };
2650 if !q.status.open() {
2651 if q.resolution().as_deref() == Some(land::REPAIR) {
2654 return if state.liveness(false) == Liveness::Live {
2655 LandResume::StillWaiting
2656 } else {
2657 LandResume::NotLanding
2658 };
2659 }
2660 return LandResume::Ready;
2661 }
2662 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2669 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2670 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2671 q.abandon(format!(
2672 "no answer within {}s of asking",
2673 timeout.as_secs().max(1)
2674 ));
2675 if store.put(&mut q).is_ok() {
2678 return LandResume::Ready;
2679 }
2680 }
2681 LandResume::StillWaiting
2682}
2683
2684const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2692
2693const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2705
2706struct InFlightGuard<'a> {
2719 status: &'a Arc<Mutex<Status>>,
2720 stop: &'a Stop,
2721 task_id: &'a str,
2722}
2723
2724impl Drop for InFlightGuard<'_> {
2725 fn drop(&mut self) {
2726 lock(self.status).current.retain(|c| c.task != self.task_id);
2727 self.stop.exit();
2728 }
2729}
2730
2731#[derive(Debug, Clone, PartialEq, Eq)]
2753enum Interrupt {
2754 Idle,
2756 Parking {
2768 parked: Vec<String>,
2769 interrupt_task: String,
2770 },
2771 Running {
2779 parked: Vec<String>,
2780 interrupt_task: String,
2781 },
2782 Resuming { parked: Vec<String> },
2789}
2790
2791fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2812 match state {
2813 Interrupt::Idle => {
2814 if in_flight.len() != 1 {
2826 return Interrupt::Idle;
2827 }
2828 match runnable.iter().find(|t| t.interrupt) {
2829 Some(t) => Interrupt::Parking {
2830 parked: in_flight.to_vec(),
2831 interrupt_task: t.id.clone(),
2832 },
2833 None => Interrupt::Idle,
2834 }
2835 }
2836 Interrupt::Parking {
2837 parked,
2838 interrupt_task,
2839 } => {
2840 if in_flight.iter().any(|id| parked.contains(id)) {
2841 Interrupt::Parking {
2843 parked,
2844 interrupt_task,
2845 }
2846 } else if in_flight.contains(&interrupt_task) {
2847 Interrupt::Running {
2848 parked,
2849 interrupt_task,
2850 }
2851 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2852 Interrupt::Parking {
2856 parked,
2857 interrupt_task,
2858 }
2859 } else {
2860 Interrupt::Resuming { parked }
2865 }
2866 }
2867 Interrupt::Running {
2868 parked,
2869 interrupt_task,
2870 } => {
2871 if in_flight.contains(&interrupt_task) {
2872 Interrupt::Running {
2873 parked,
2874 interrupt_task,
2875 }
2876 } else {
2877 Interrupt::Resuming { parked }
2883 }
2884 }
2885 Interrupt::Resuming { parked } => {
2886 if in_flight.iter().any(|id| parked.contains(id)) {
2887 Interrupt::Idle
2893 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2894 Interrupt::Resuming { parked }
2895 } else {
2896 Interrupt::Idle
2899 }
2900 }
2901 }
2902}
2903
2904fn advance_interrupt_tick(
2910 enabled: bool,
2911 state: Interrupt,
2912 in_flight: &[String],
2913 runnable: &[Task],
2914) -> Interrupt {
2915 if !enabled {
2916 return Interrupt::Idle;
2917 }
2918 advance_interrupt(state, in_flight, runnable)
2919}
2920
2921fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2926 match state {
2927 Interrupt::Idle => candidates,
2928 Interrupt::Parking {
2929 parked,
2930 interrupt_task,
2931 } => {
2932 if in_flight.iter().any(|id| parked.contains(id)) {
2933 Vec::new()
2934 } else {
2935 candidates
2936 .into_iter()
2937 .filter(|t| &t.id == interrupt_task)
2938 .collect()
2939 }
2940 }
2941 Interrupt::Running { .. } => Vec::new(),
2942 Interrupt::Resuming { parked } => candidates
2950 .into_iter()
2951 .find(|t| parked.contains(&t.id))
2952 .into_iter()
2953 .collect(),
2954 }
2955}
2956
2957struct DispatchLimits {
2961 max_concurrent: usize,
2964 pause_for_interrupts: bool,
2966}
2967
2968#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2977enum PermitKind {
2978 None,
2983 Urgent,
2990 Ordinary,
2993}
2994
2995fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2998 if priority {
2999 PermitKind::None
3000 } else if urgent {
3001 PermitKind::Urgent
3002 } else {
3003 PermitKind::Ordinary
3004 }
3005}
3006
3007struct DispatchClaim {
3008 task: Task,
3009 claim: crate::queue::Claim,
3010 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3011}
3012
3013fn claim_dispatch(
3016 queue: &Queue,
3017 candidate: &Task,
3018 cooling_down: bool,
3019 ordinary: &Arc<tokio::sync::Semaphore>,
3020 urgent: &Arc<tokio::sync::Semaphore>,
3021) -> Option<DispatchClaim> {
3022 let Ok(claim) = queue.claim(&candidate.id) else {
3023 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3024 return None;
3025 };
3026 let task = match queue.get(&candidate.id) {
3027 Ok(t) if t.status.runnable() => t,
3028 Ok(_) => return None,
3029 Err(e) => {
3030 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3031 return None;
3032 }
3033 };
3034 let resume = land_resume_state(&task);
3035 if resume == LandResume::StillWaiting {
3036 return None;
3037 }
3038 let priority = resume == LandResume::Ready;
3039 if !priority && cooling_down {
3040 return None;
3041 }
3042 let permit = match permit_kind(priority, task.urgent) {
3045 PermitKind::None => None,
3046 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3047 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3048 };
3049 Some(DispatchClaim {
3050 task,
3051 claim,
3052 permit,
3053 })
3054}
3055
3056async fn poll(
3075 opts: &Opts,
3076 queue: &Queue,
3077 status: &Arc<Mutex<Status>>,
3078 home: &Path,
3079 worktrees_root: &Path,
3080 stop: &Stop,
3081 limits: DispatchLimits,
3082) -> Result<()> {
3083 let DispatchLimits {
3084 max_concurrent,
3085 pause_for_interrupts,
3086 } = limits;
3087 let mut attempted: Vec<String> = Vec::new();
3092 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3093 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3101 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3107 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3108 let mut conductor = Conductor::new();
3109 let mut cache_last_checked: Option<Timestamp> = None;
3112 let mut disk_last_checked: Option<Timestamp> = None;
3113 let mut interrupt = Interrupt::Idle;
3115 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3121 std::collections::HashMap::new();
3122
3123 while !stop.stopped() {
3124 lock(status).polls += 1;
3125
3126 while let Some(result) = inflight.try_join_next() {
3131 if let Err(e) = result {
3132 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3133 notices::raise(Notice::error(
3134 "loop:attempt",
3135 "A queued attempt ended abnormally; check the task it was running.",
3136 ));
3137 }
3138 }
3139
3140 let swept = sweep_stale_claims(queue, STALE_CLAIM);
3141 if !swept.is_empty() {
3142 tracing::warn!(
3143 "swept {} stale claim(s) left behind by an earlier daemon: {}",
3144 swept.len(),
3145 swept.join(", ")
3146 );
3147 }
3148 let now = Timestamp::now();
3153
3154 if !stop.busy_now() {
3159 maybe_prune_cache_between_runs(
3160 &opts.repo,
3161 opts,
3162 home,
3163 stop,
3164 &mut cache_last_checked,
3165 now,
3166 )
3167 .await;
3168 }
3169
3170 if cache_check_due(disk_last_checked, now, 30) {
3171 disk_last_checked = Some(now);
3172 if let Ok(cfg) = prepare(&opts.repo, opts) {
3173 crate::retention::sweep(home, &cfg.disk, now).await;
3174 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3177 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3178 }
3179 for current in lock(status).current.clone() {
3180 if let Ok(state) = RunState::load_under(¤t.run, home)
3181 && let Some(reason) = disk_gate(&state.repo, &state.config)
3182 {
3183 if let Some(pause) = interrupt_pauses.get(¤t.task) {
3184 pause.park_because(reason);
3185 }
3186 notices::raise_in(
3187 home,
3188 Notice::warn(
3189 "disk:pressure",
3190 "Disk pressure persists after cleanup; active runs were asked to checkpoint and park. New starts and resumes wait for free space.",
3191 ),
3192 );
3193 }
3194 }
3195 }
3196 }
3197
3198 let stalled = stalled_tasks(queue, home, now);
3199 let stalled_ids: std::collections::BTreeSet<_> =
3200 stalled.iter().map(|task| task.id.clone()).collect();
3201 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3202 if !reclaimed.is_empty() {
3203 tracing::warn!(
3204 "reclaimed {} task(s) left `running` by a daemon that never \
3205 recorded the outcome: {}",
3206 reclaimed.len(),
3207 reclaimed.join(", ")
3208 );
3209 }
3210 let abandoned_runs = reclaim_abandoned_runs(home, now);
3211 if !abandoned_runs.is_empty() {
3212 tracing::warn!(
3213 "failed {} run(s) left behind by a killed process, past every \
3214 active seat's own timeout: {}",
3215 abandoned_runs.len(),
3216 abandoned_runs.join(", ")
3217 );
3218 }
3219
3220 let questions = Questions::at(home.join("questions"));
3225
3226 repair_choice_offers(&questions);
3229 resolve_blockers(queue, &questions);
3230 apply_choice_actions(queue, &questions, home).await;
3231 triage::apply_answers(queue, &questions);
3232 reconcile_task_questions(queue, &questions);
3233 {
3237 let talks = crate::talk::Talks::at(home.join("talks"));
3238 crate::chat_notify::sweep(queue, &talks, home);
3239 crate::chat_watch::sweep(home, &talks);
3240 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3241 }
3242
3243 let finished: Vec<Task> = finished_tasks(queue)
3249 .into_iter()
3250 .filter(|task| !stalled_ids.contains(&task.id))
3251 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3255 .collect();
3256 let queued = queued_tasks(queue);
3257 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3261 && conductor.worth_a_look(queue, &stalled, &finished)
3262 {
3263 match prepare(&opts.repo, opts) {
3264 Ok(cfg) => {
3265 conductor
3266 .maybe_run(
3267 &cfg,
3268 &opts.repo,
3269 queue,
3270 &questions,
3271 home,
3272 &queued,
3273 &stalled,
3274 &finished,
3275 opts.max_attempts,
3276 )
3277 .await;
3278 }
3279 Err(e) => {
3280 tracing::warn!("conductor: no config: {e:#}");
3281 notices::raise(Notice::warn(
3282 "loop:no-config",
3283 "The loop could not read this repository's config, so held tasks are not being triaged.",
3284 ));
3285 }
3286 }
3287 }
3288
3289 let candidates: Vec<Task> = runnable(queue)
3290 .into_iter()
3291 .filter(|t| !opts.once || !attempted.contains(&t.id))
3292 .collect();
3293
3294 let in_flight: Vec<String> = lock(status)
3299 .current
3300 .iter()
3301 .map(|c| c.task.clone())
3302 .collect();
3303 interrupt_pauses.retain(|id, _| in_flight.contains(id));
3304
3305 interrupt =
3306 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3307 if let Interrupt::Parking {
3308 parked,
3309 interrupt_task,
3310 } = &interrupt
3311 {
3312 let reason = format!(
3313 "task {} asked to run first",
3314 crate::run::short_of(interrupt_task)
3315 );
3316 for id in parked {
3317 if let Some(pause) = interrupt_pauses.get(id) {
3318 pause.park_because(reason.clone());
3319 }
3320 }
3321 }
3322 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3323
3324 let cooling_down =
3325 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3326
3327 let mut started_any = false;
3328 for candidate in candidates {
3329 if stop.stopped() {
3330 break;
3331 }
3332
3333 let Some(DispatchClaim {
3334 mut task,
3335 claim,
3336 permit,
3337 }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3338 else {
3339 continue;
3340 };
3341
3342 let task_id = task.id.clone();
3343 attempted.push(task_id.clone());
3344 lock(status).idle = false;
3345 stop.enter();
3348 started_any = true;
3349
3350 let run_pause = crate::graph::Pause::new();
3354 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3355
3356 let opts = opts.clone();
3357 let queue = queue.clone();
3358 let status = Arc::clone(status);
3359 let stop = stop.clone();
3360 let quota_cooldown_until = Arc::clone("a_cooldown_until);
3361 inflight.spawn(async move {
3362 let _claim = claim;
3366 let _permit = permit;
3367 let _inflight = InFlightGuard {
3369 status: &status,
3370 stop: &stop,
3371 task_id: &task_id,
3372 };
3373 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3374 lock(&status).completed += 1;
3375 let now = Timestamp::now();
3381 if let Some(until) = cooldown_until("a, now) {
3382 let wait = until.as_second() - now.as_second();
3383 *lock("a_cooldown_until) = Some(until);
3384 let hint = quota
3385 .iter()
3386 .find(|q| q.reset.is_some())
3387 .and_then(|q| q.reset.as_deref());
3388 match hint {
3389 Some(h) => tracing::warn!(
3390 "quota hit; waiting {wait}s before taking another ordinary task \
3391 (CLI reported reset: {h})"
3392 ),
3393 None => tracing::warn!(
3394 "quota hit; waiting {wait}s before taking another ordinary task \
3395 (no reset hint reported)"
3396 ),
3397 }
3398 }
3399 });
3400 }
3401
3402 if started_any {
3403 continue;
3404 }
3405
3406 if stop.busy_now() {
3407 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3412 continue;
3413 }
3414
3415 lock(status).idle = true;
3417 if opts.once {
3418 janitor(&opts.repo, opts, home, worktrees_root).await;
3422 resweep_superseded_attempts(queue, home);
3423 triage_held(queue, home, opts).await;
3424 break;
3425 }
3426 stop.idle(opts.poll).await;
3427 if stop.stopped() {
3428 continue;
3429 }
3430 janitor(&opts.repo, opts, home, worktrees_root).await;
3436 resweep_superseded_attempts(queue, home);
3437 triage_held(queue, home, opts).await;
3438 }
3439
3440 while let Some(result) = inflight.join_next().await {
3445 if let Err(e) = result {
3446 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3447 notices::raise(Notice::error(
3448 "loop:attempt",
3449 "A queued attempt ended abnormally; check the task it was running.",
3450 ));
3451 }
3452 }
3453 Ok(())
3454}
3455
3456async fn attempt(
3462 opts: &Opts,
3463 queue: &Queue,
3464 status: &Arc<Mutex<Status>>,
3465 stop: &Stop,
3466 interrupt_pause: crate::graph::Pause,
3467 task: &mut Task,
3468) -> Vec<QuotaLoss> {
3469 let repo = repo_for(task, &opts.repo);
3470 tracing::info!(
3471 "task {} — {} (repo {})",
3472 task.short(),
3473 task.title,
3474 repo.display()
3475 );
3476
3477 if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3481 && previous
3482 .merge_decision
3483 .as_ref()
3484 .is_some_and(|decision| !decision.closed)
3485 && previous.status != RunStatus::Landing
3486 && !crate::merge_decision::resumable_hold(&previous)
3487 {
3488 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)));
3489 record(queue, task);
3490 return Vec::new();
3491 }
3492 let stop_owner = task
3493 .runs
3494 .last()
3495 .and_then(|id| RunState::load(id).ok())
3496 .filter(|state| {
3497 crate::merge_decision::resumable_hold(state)
3498 || state.status == RunStatus::Landing
3499 && state.land_approval.as_ref().is_some_and(|binding| {
3500 Questions::open().get(&binding.question).is_ok_and(|q| {
3501 q.run == state.id
3502 && q.resolution()
3503 .as_deref()
3504 .is_some_and(crate::merge_decision::stops)
3505 })
3506 })
3507 });
3508 if let Some(owner) = stop_owner {
3509 let mut runner = match Runner::resume(&owner.id) {
3510 Ok(runner) => runner,
3511 Err(e) => {
3512 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3513 record(queue, task);
3514 return Vec::new();
3515 }
3516 };
3517 runner.on_pause(stop.pause());
3518 runner.watch_interrupt(interrupt_pause);
3519 let quota_before = runner.state.quota.clone();
3520 task.start(owner.id.clone());
3521 record(queue, task);
3522 lock(status).current.push(Current {
3523 task: task.id.clone(),
3524 run: owner.id,
3525 });
3526 runner.state.next_pass_task_entry = true;
3527 let result = runner.execute().await;
3528 return finish_attempt(
3529 opts.max_attempts,
3530 queue,
3531 task,
3532 &runner.state,
3533 "a_before,
3534 result,
3535 );
3536 }
3537
3538 let unfinished = (!task.fresh_start)
3539 .then(|| unfinished_run(&task.runs, task.short()))
3540 .flatten()
3541 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3542 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3543 if !task.fresh_start
3544 && task.pr_recovery.is_none()
3545 && task.review_branch.is_none()
3546 && task.resume_override.is_none()
3547 && previous
3548 .as_ref()
3549 .is_some_and(|run| run.retired_to.is_some())
3550 && unfinished.is_none()
3551 {
3552 task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
3553 record(queue, task);
3554 return Vec::new();
3555 }
3556
3557 let saved_recovery = previous.as_ref().filter(|run| {
3558 task.replacement.is_none()
3559 && task.pr_recovery.as_ref().is_some_and(|selected| {
3560 selected.check_task(&task.id, &task.instruction).is_ok()
3561 && selected_starter(selected, Some(run), unfinished.as_deref())
3562 == Starter::Resume(run.id.clone())
3563 })
3564 });
3565
3566 let explicit = match &task.overrides {
3570 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3571 Some(_) => opts.config.as_deref(),
3572 None => opts.config.as_deref(),
3573 };
3574 let (mut config, layers) = if let Some(run) = saved_recovery {
3575 let mut saved = run.clone();
3578 if let Err(e) = saved.configure_recovery_resume() {
3579 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3580 record(queue, task);
3581 return Vec::new();
3582 }
3583 (saved.config, Vec::new())
3584 } else {
3585 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3586 Ok(loaded) => loaded,
3587 Err(e) => {
3588 let reason = format!("[config] {e:#}");
3589 record_config_failure(task, &e);
3590 task.last_error = Some(reason.clone());
3591 task.hold_machine(Some(reason));
3592 record(queue, task);
3593 return Vec::new();
3594 }
3595 };
3596 if let Err(e) = apply_options(&mut config, opts, task) {
3597 task.hold_manual(Some(format!(
3598 "[config] {e:#}; correct the merge override before releasing the task"
3599 )));
3600 record(queue, task);
3601 return Vec::new();
3602 }
3603 if let Some(selected) = &task.pr_recovery
3604 && let Err(e) = selected.configure(&mut config)
3605 {
3606 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3607 record(queue, task);
3608 return Vec::new();
3609 }
3610 (config, layers)
3611 };
3612 let config_evidence = crate::pr_recovery::ConfigEvidence {
3613 layers,
3614 overrides: task.overrides.clone(),
3615 daemon_merge: task
3616 .overrides
3617 .as_ref()
3618 .is_none_or(|o| o.inherit_daemon_options)
3619 .then(|| opts.merge.clone())
3620 .flatten(),
3621 };
3622 apply_task_implementers(&mut config, task);
3623 if let Some(replacement) = &task.replacement {
3624 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3625 old.liveness(false) == Liveness::Dead
3626 && old.merge_decision.as_ref().is_some_and(|d| {
3627 d.closed
3628 && d.question == replacement.question
3629 && d.replacement_run.as_ref().is_none_or(|run| {
3630 task.runs.last() == Some(run)
3631 && RunState::load(run).is_ok_and(|current| {
3632 current.replaces.as_ref().is_some_and(|pin| {
3633 pin.question == replacement.question
3634 && pin.agent == replacement.agent
3635 })
3636 })
3637 })
3638 })
3639 });
3640 if !safe {
3641 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()));
3642 record(queue, task);
3643 return Vec::new();
3644 }
3645 match config.agent(&replacement.agent) {
3646 Ok(agent) if crate::agent::installed(agent) => {}
3647 _ => {
3648 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)));
3649 record(queue, task);
3650 return Vec::new();
3651 }
3652 }
3653 config.graph.implementers = 1;
3654 config.graph.land_approval = true;
3655 config.merge.mode = MergeMode::Pr;
3656 config.graph.selected_implementer = Some(replacement.agent.clone());
3657 }
3658 let p = phrases(&config.graph.language);
3659 let start_failed = p.could_not_start;
3660 if let Ok(base) =
3664 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
3665 .await
3666 && let Ok(head) =
3667 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
3668 {
3669 let seeds = crate::refs::resolve(
3670 &repo,
3671 &head,
3672 &config.merge.remote,
3673 &format!("{}\n{}", task.title, instruction_for(task)),
3674 )
3675 .await;
3676 let mut inputs = crate::queue::recovery_inputs(&seeds);
3677 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
3678 let source = crate::git::rev_parse(&repo, branch)
3679 .await
3680 .unwrap_or_default();
3681 inputs.push_str(&format!(";review:{branch}:{source}"));
3682 }
3683 if let Some(reason) = task.recovery_exhausted(
3684 &head,
3685 &inputs,
3686 task.attempt_limit
3687 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
3688 ) {
3689 task.hold_unrequested_retry(Some(reason));
3690 record(queue, task);
3691 return Vec::new();
3692 }
3693 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
3694 }
3695
3696 if let Some(reason) = disk_gate(&repo, &config) {
3704 task.notice_cause("disk-space", None, None);
3705 task.last_error = Some(reason.clone());
3706 task.hold_machine(Some(reason.clone()));
3707 record(queue, task);
3708 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3709 notices::raise(
3712 Notice::warn(
3713 &format!("disk:{}", repo.display()),
3714 "A task was held for want of free disk space; free some, then release it from the queue.",
3715 )
3716 .link(Link::Task {
3717 id: task.id.clone(),
3718 }),
3719 );
3720 return Vec::new();
3721 }
3722
3723 let review_branch = take_review_branch(task, previous.as_ref());
3748 let branch_exists = match &review_branch {
3749 Some(branch) => crate::git::branch_exists(&repo, branch)
3750 .await
3751 .unwrap_or(false),
3752 None => false,
3753 };
3754 let proposed = match (&review_branch, &unfinished, &task.review_of) {
3758 (None, None, Some(branch)) => Starter::Review(branch.clone()),
3759 _ => choose_starter(
3760 review_branch.as_deref(),
3761 branch_exists,
3762 unfinished.as_deref(),
3763 ),
3764 };
3765 let retry_selected = task.replacement.is_some()
3766 && task.resumption.is_some()
3767 && !task.fresh_start
3768 && previous.as_ref().is_some_and(|run| {
3769 run.replaces.is_some()
3770 && ((run.status == RunStatus::Failed && run.viable().is_empty())
3771 || (run.status == RunStatus::Blocked && run.tally.is_none()))
3772 });
3773 let stop_pin = task
3774 .resume_override
3775 .as_ref()
3776 .filter(|pin| {
3777 Questions::open().get(&pin.question_id).is_ok_and(|q| {
3778 q.node == land::APPROVAL_NODE
3779 && q.resolution()
3780 .as_deref()
3781 .is_some_and(crate::merge_decision::stops)
3782 })
3783 })
3784 .and_then(|pin| pin.pinned_run.clone());
3785 let starter = if let Some(run) = stop_pin {
3786 Starter::Resume(run)
3789 } else if retry_selected {
3790 Starter::Resume(previous.as_ref().unwrap().id.clone())
3791 } else if let Some(selected) = &task.pr_recovery {
3792 if selected.check_task(&task.id, &task.instruction).is_ok() {
3793 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3794 } else {
3795 Starter::Review(selected.branch.clone())
3796 }
3797 } else {
3798 starter_with_implementers(task, previous.as_ref(), proposed)
3799 };
3800 if let Some(pin) = &task.resume_override
3803 && let Some(run) = &pin.pinned_run
3804 && starter != Starter::Resume(run.clone())
3805 {
3806 let run = run.clone();
3807 task.notice_cause("resume-owner", Some(&run), None);
3808 task.hold_machine(Some(format!(
3809 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3810 task.id
3811 )));
3812 record(queue, task);
3813 return Vec::new();
3814 }
3815 if task.replacement.is_some()
3816 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3817 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3818 {
3819 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()));
3820 record(queue, task);
3821 return Vec::new();
3822 }
3823 if let Some(reason) = retained_attempt_hold(
3824 task,
3825 &starter,
3826 config.disk.retained_attempt_limit,
3827 RunState::load,
3828 ) {
3829 if let Starter::Review(branch) = &starter {
3832 task.review_branch = Some(branch.clone());
3833 }
3834 task.hold_unrequested_retry(Some(reason));
3835 record(queue, task);
3836 return Vec::new();
3837 }
3838 let attachments = match task_attachments(queue, task) {
3843 Ok(a) => a,
3844 Err(e) => {
3845 task.attempts += 1;
3846 task.fail_startup_target(
3847 "startup-attachments",
3848 e.name.clone(),
3849 format!("{start_failed}{e:#}"),
3850 opts.max_attempts,
3851 );
3852 record(queue, task);
3853 return Vec::new();
3854 }
3855 };
3856 let startup_pause = stop.pause();
3857 let startup_interrupt = interrupt_pause.clone();
3858 let wait = crate::repo_lock::WaitPolicy::new(
3859 Duration::from_secs(config.graph.timeout_resource_wait),
3860 move || startup_pause.parked() || startup_interrupt.parked(),
3861 );
3862 let started = wait.scope(Box::pin(async { match &starter {
3865 Starter::Review(_) if task.pr_recovery.is_some() => {
3866 let selected = task.pr_recovery.clone().expect("selected recovery");
3867 match selected.check_task(&task.id, &task.instruction) {
3868 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3869 .await
3870 .map(|mut r| {
3871 r.state.attachments = attachments.clone();
3872 r
3873 }),
3874 Err(e) => Err(e),
3875 }
3876 }
3877 Starter::Review(branch) => {
3878 tracing::info!(
3879 "task {} reopens `{branch}` as a review-only pass",
3880 task.short()
3881 );
3882 let takeover = crate::handover::Takeover {
3885 earlier: task.earlier_attempts().to_vec(),
3886 home: crate::run::home(),
3887 choice: take_divergence_answer(branch, &config.merge.remote, task),
3888 task_instruction: Some(instruction_for(task)),
3889 };
3890 Runner::review_taking_over(
3891 &repo,
3892 branch,
3893 config,
3894 Some(takeover),
3895 crate::run::Origin::queue(&task.id),
3896 )
3897 .await
3898 }
3899 Starter::Resume(id) => {
3900 tracing::info!("resuming run {id} rather than competing again");
3901 Runner::resume(id).and_then(|mut r| {
3902 if retry_selected {
3903 for candidate in &mut r.state.candidates {
3906 candidate.failed = None;
3907 candidate.empty = false;
3908 candidate.commits = 0;
3909 }
3910 r.state.status = RunStatus::Implementing;
3911 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3912 }
3913 if r.state.prep_failure.is_some() {
3914 let approval = task
3915 .resumption
3916 .as_ref()
3917 .context("preparation retry requires an explicit task release")?;
3918 r.retry_preparation(approval.at)?;
3919 }
3920 if let Some(instruction) =
3921 prepare_instruction(&starter, Some(&r.state.instruction), task)
3922 {
3923 r.state.instruction = instruction;
3924 }
3925 r.state.attachments = attachments.clone();
3926 if task.replacement.is_some() {
3927 r.state.config.merge.mode = MergeMode::Pr;
3928 r.state.config.graph.land_approval = true;
3929 }
3930 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3934 .overrides
3935 .as_ref()
3936 .and_then(|o| o.merge.as_deref())
3937 .and_then(|m| merge_mode(m).ok())
3938 {
3939 r.state.config.merge.mode = mode;
3940 }
3941 Ok(r)
3942 })
3943 }
3944 Starter::Start => {
3945 if let Some(branch) = &review_branch {
3946 tracing::warn!(
3947 "conductor chose review for task {} but branch `{branch}` no longer \
3948 exists; requeuing as a fresh competition instead",
3949 task.short()
3950 );
3951 }
3952 let instruction = prepare_instruction(&starter, None, task)
3953 .unwrap_or_else(|| task.instruction.clone());
3954 Runner::start_naming(
3955 &repo,
3956 instruction,
3957 &task.title,
3958 config,
3959 crate::run::Origin::queue(&task.id),
3960 )
3961 .await
3962 .map(|mut r| {
3963 r.state.attachments = attachments.clone();
3964 r
3965 })
3966 }
3967 }})).await;
3968 let mut runner = match started {
3969 Ok(r) => r,
3970 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3971 task.last_error = Some(e.to_string());
3972 if stop.parking() || interrupt_pause.parked() {
3973 let attempts = task.attempts;
3974 task.park(e.to_string());
3975 task.attempts = attempts;
3977 } else {
3978 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3979 }
3980 record(queue, task);
3981 return Vec::new();
3982 }
3983 Err(e) if task.pr_recovery.is_some() => {
3987 task.startup_notice_cause("startup-public-head");
3988 task.attempts += 1;
3989 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3990 task.link_run(&partial.run);
3991 task.record_pass(&partial.run, 0, task.attempts, None);
3992 }
3993 task.last_error = Some(format!("{start_failed}{e:#}"));
3994 task.hold_unrequested_retry(Some(format!(
3995 "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."
3996 )));
3997 record(queue, task);
3998 return Vec::new();
3999 }
4000 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4001 let detail = match e.downcast_ref::<crate::handover::Refused>() {
4002 Some(r) => (p.handover_refused)(r),
4003 None => format!("{e:#}"),
4004 };
4005 task.startup_notice_cause("startup-handover");
4006 let reason = format!("{start_failed}{detail}");
4007 task.last_error = Some(reason.clone());
4008 let branch = match &starter {
4011 Starter::Review(branch) => Some(branch.clone()),
4012 _ => None,
4013 };
4014 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4018 record(queue, task);
4019 tracing::warn!(
4020 "holding {} for a branch it cannot take over: {e:#}",
4021 task.short()
4022 );
4023 return Vec::new();
4024 }
4025 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4030 let d = e
4031 .downcast_ref::<crate::reconcile::Diverged>()
4032 .expect("checked by the guard");
4033 let mut q = ask::Question::new(
4034 task.id.clone(),
4035 crate::reconcile::NODE.to_owned(),
4036 crate::reconcile::SEAT.to_owned(),
4037 d.summary(),
4038 d.detail(),
4039 d.choices(),
4040 );
4041 match Questions::open().put(&mut q) {
4042 Ok(()) => {
4043 task.last_error = Some(format!("{e:#}"));
4044 task.review_branch = Some(d.branch.clone());
4047 task.review_instruction = Some(task.instruction.clone());
4048 task.block(vec![q.id.clone()], Some(d.summary()));
4049 }
4050 Err(put) => {
4051 tracing::warn!("could not file the divergence question: {put:#}");
4052 task.attempts += 1;
4053 task.fail_startup(
4054 "startup-question-store",
4055 format!("{start_failed}{e:#}"),
4056 opts.max_attempts,
4057 );
4058 }
4059 }
4060 record(queue, task);
4061 return Vec::new();
4062 }
4063 Err(e) => {
4064 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4070 && let Starter::Review(branch) = &starter
4071 {
4072 task.review_branch = Some(branch.clone());
4073 task.review_instruction = Some(task.instruction.clone());
4074 task.last_error = Some(format!("{start_failed}{e:#}"));
4075 task.status = crate::queue::TaskStatus::Failed;
4076 record(queue, task);
4077 return Vec::new();
4078 }
4079 task.attempts += 1;
4080 task.last_error = Some(format!("{start_failed}{e:#}"));
4081 task.startup_notice_cause("startup-source");
4082 task.hold_unrequested_retry(Some(format!(
4083 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4084 )));
4085 record(queue, task);
4086 return Vec::new();
4087 }
4088 };
4089 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4090 runner.state.recovery_config = Some(config_evidence);
4091 }
4092 if let Some(replacement) = &task.replacement {
4093 if matches!(starter, Starter::Start) {
4094 runner.state.instruction.push_str(&format!(
4095 "\n\n# Replacement review context\n{}",
4096 replacement.context
4097 ));
4098 }
4099 runner.state.replaces = Some(replacement.clone());
4100 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4101 if let Ok(mut old) = RunState::load(&replacement.run)
4102 && let Some(d) = &mut old.merge_decision
4103 {
4104 d.replacement_run = Some(runner.state.id.clone());
4105 old.event(
4106 "replacement",
4107 format!(
4108 "replacement run {} owns the next attempt; old PR remains closed",
4109 runner.state.id
4110 ),
4111 );
4112 if let Err(e) = old.save() {
4113 task.hold_manual(Some(format!(
4114 "Could not link replacement history: {e}; no agents dispatched"
4115 )));
4116 record(queue, task);
4117 return Vec::new();
4118 }
4119 }
4120 }
4121 runner.state.task_instruction = Some(task.instruction.clone());
4122 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4125 if runner.state.origin_chat.is_none() {
4126 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4127 }
4128 runner.on_pause(stop.pause());
4130 runner.watch_interrupt(interrupt_pause);
4134
4135 let run = runner.state.id.clone();
4138 task.start(run.clone());
4139 record(queue, task);
4140 lock(status).current.push(Current {
4141 task: task.id.clone(),
4142 run,
4143 });
4144
4145 let quota_before = runner.state.quota.clone();
4148 runner.state.next_pass_task_entry = true;
4149 let result = runner.execute().await;
4150 finish_attempt(
4151 opts.max_attempts,
4152 queue,
4153 task,
4154 &runner.state,
4155 "a_before,
4156 result,
4157 )
4158}
4159
4160pub fn finish_attempt(
4165 max_attempts: usize,
4166 queue: &Queue,
4167 task: &mut Task,
4168 state: &RunState,
4169 quota_before: &[QuotaLoss],
4170 result: Result<()>,
4171) -> Vec<QuotaLoss> {
4172 let detail = match result {
4173 Ok(()) => describe(state),
4174 Err(e) => format!("{e:#}"),
4175 };
4176 let fresh = losses_this_attempt(quota_before, &state.quota);
4177 let verdict = Verdict {
4178 status: state.status,
4179 left_pr: state.pr.is_some(),
4182 quota_hit: !fresh.is_empty(),
4188 parked: state.parked,
4192 no_viable_candidates: state.viable().is_empty(),
4195 };
4196 if let Some(replacement) = &state.replaces
4197 && let Some(pr) = &state.pr
4198 && let Ok(mut old) = RunState::load(&replacement.run)
4199 && let Some(d) = &mut old.merge_decision
4200 {
4201 d.replacement_pr = Some(pr.url.clone());
4202 let _ = old.save();
4203 }
4204 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4205 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4206 task.hold_unrequested_retry(Some(format!(
4207 "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
4208 )));
4209 }
4210 if task.status == TaskStatus::Done {
4211 supersede_prior_runs(task, &crate::run::home());
4212 }
4213 record(queue, task);
4214 tracing::info!(
4215 "task {} is {} after run {} ({})",
4216 task.short(),
4217 task.status.as_str(),
4218 state.short(),
4219 label(state.status)
4220 );
4221 fresh
4222}
4223
4224pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4228 let waits_on_owner = withheld_text_wait(task).is_some();
4233 if task.status.runnable()
4234 && !waits_on_owner
4235 && !(task.fresh_start && task.replacement.is_some())
4236 {
4237 let why = task.last_error.clone().map_or_else(
4238 || "the run did not finish".to_owned(),
4239 |e| format!("the run did not finish: {e}"),
4240 );
4241 task.hold_unrequested_retry(Some(format!(
4242 "{why}. It was started by hand, so it is not retried \
4243 automatically; `magi task release` retries it."
4244 )));
4245 record(queue, task);
4246 }
4247}
4248
4249#[must_use]
4253pub fn loop_would_resume(run: &str) -> bool {
4254 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4255}
4256
4257#[must_use]
4267pub fn foreign_loop(
4268 reading: Option<&Reading>,
4269 now: Timestamp,
4270 own_pid: u32,
4271) -> Option<Option<u32>> {
4272 let reading = reading.filter(|r| r.running(now))?;
4273 match reading.pid {
4274 Some(pid) if pid == own_pid => None,
4275 pid => Some(pid),
4276 }
4277}
4278
4279pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4294 let status = Arc::new(Mutex::new(Status::new()));
4295 let stop = Stop::new();
4296 Box::pin(attempt(
4299 opts,
4300 queue,
4301 &status,
4302 &stop,
4303 crate::graph::Pause::new(),
4304 task,
4305 ))
4306 .await;
4307 let mut resumes = 0;
4316 while resumes < MAX_WITHHELD_RESUMES {
4317 let Some(timeout) = withheld_text_wait(task) else {
4318 break;
4319 };
4320 eprintln!(
4321 "waiting for the owner's answer on a withheld pull request text \
4322 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4323 );
4324 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4327 let ready = loop {
4328 match land_resume_state(task) {
4329 LandResume::StillWaiting if std::time::Instant::now() < limit => {
4330 tokio::time::sleep(WITHHELD_POLL).await;
4331 }
4332 LandResume::Ready => break true,
4333 _ => break false,
4334 }
4335 };
4336 if !ready {
4337 break;
4338 }
4339 resumes += 1;
4340 Box::pin(attempt(
4341 opts,
4342 queue,
4343 &status,
4344 &stop,
4345 crate::graph::Pause::new(),
4346 task,
4347 ))
4348 .await;
4349 }
4350 hold_if_runnable(queue, task);
4351}
4352
4353const MAX_WITHHELD_RESUMES: u32 = 3;
4356
4357const WITHHELD_POLL: Duration = Duration::from_secs(15);
4359
4360fn withheld_text_wait(task: &Task) -> Option<u64> {
4363 let id = task.runs.last()?;
4364 let s = RunState::load(id).ok()?;
4365 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4366 .then_some(s.config.graph.answer_timeout)
4367}
4368
4369fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4379 after
4380 .iter()
4381 .filter(|q| !before.contains(q))
4382 .cloned()
4383 .collect()
4384}
4385
4386fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4389 if quota.is_empty() {
4390 return None;
4391 }
4392 let with_hint = quota.iter().find(|q| q.reset.is_some());
4393 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4394 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4395 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4396 Some(
4397 now.checked_add(jiff::SignedDuration::from_secs(secs))
4398 .unwrap_or(Timestamp::MAX),
4399 )
4400}
4401
4402fn implementers_match(task: &Task, state: &RunState) -> bool {
4404 task.replacement.as_ref().map_or_else(
4405 || {
4406 task.implementers()
4407 .is_none_or(|n| n == state.config.graph.implementers)
4408 },
4409 |replacement| {
4410 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4411 && state.config.graph.implementers == 1
4412 },
4413 )
4414}
4415
4416fn starter_with_implementers(
4418 task: &Task,
4419 previous: Option<&RunState>,
4420 proposed: Starter,
4421) -> Starter {
4422 if previous.is_some_and(|s| !implementers_match(task, s)) {
4423 task.review_of
4424 .as_ref()
4425 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4426 } else {
4427 proposed
4428 }
4429}
4430
4431fn apply_task_implementers(config: &mut Config, task: &Task) {
4433 if let Some(n) = task.implementers() {
4434 config.graph.implementers = n;
4435 }
4436}
4437
4438#[cfg(test)]
4443fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4444 let explicit = match &task.overrides {
4445 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4446 _ => opts.config.as_deref(),
4447 };
4448 let (mut config, _) = Config::discover(repo, explicit)?;
4449 apply_options(&mut config, opts, task)?;
4450 Ok(config)
4451}
4452
4453fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4454 if task
4455 .overrides
4456 .as_ref()
4457 .is_none_or(|o| o.inherit_daemon_options)
4458 && let Some(mode) = opts.merge.as_deref()
4459 {
4460 config.merge.mode = merge_mode(mode)?;
4461 }
4462 if let Some(o) = &task.overrides {
4463 o.apply(config);
4464 }
4465 Ok(())
4466}
4467
4468fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4470 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4471 if let Some(mode) = &opts.merge {
4472 config.merge.mode = merge_mode(mode)?;
4473 }
4474 Ok(config)
4475}
4476
4477async fn maybe_prune_cache_between_runs(
4508 repo: &Path,
4509 opts: &Opts,
4510 home: &Path,
4511 stop: &Stop,
4512 last_checked: &mut Option<Timestamp>,
4513 now: Timestamp,
4514) {
4515 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4516 return;
4517 }
4518 *last_checked = Some(now);
4519 let cfg = match prepare(repo, opts) {
4520 Ok(cfg) => cfg,
4521 Err(e) => {
4522 tracing::warn!("cache check: no config: {e:#}");
4523 return;
4524 }
4525 };
4526 match clean::prune_cache_if_over_limit(&cfg, home) {
4527 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4528 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4529 pruned.files,
4530 pruned.freed
4531 ),
4532 Ok(_) => {}
4533 Err(e) => {
4534 tracing::warn!("housekeep: prune cache: {e:#}");
4535 notices::raise_in(
4536 home,
4537 Notice::warn(
4538 "housekeep:cache",
4539 "Pruning the shared build cache failed; disk usage may keep growing.",
4540 ),
4541 );
4542 }
4543 }
4544}
4545
4546fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4550 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4551}
4552
4553async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4572 let cfg = match prepare(repo, opts) {
4573 Ok(cfg) => cfg,
4574 Err(e) => {
4575 tracing::warn!("housekeep: no config: {e:#}");
4576 return;
4577 }
4578 };
4579 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4588 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4589 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4594 let mut extra = Vec::new();
4595 if out.unreadable > 0 {
4596 extra.push(format!("{} unreadable", out.unreadable));
4597 }
4598 if out.orphaned_worktrees > 0 {
4599 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4600 }
4601 let detail = if extra.is_empty() {
4602 String::new()
4603 } else {
4604 format!(" ({})", extra.join(", "))
4605 };
4606 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4607 }
4608 if out.external_merges_recorded > 0 {
4609 tracing::info!(
4610 "housekeep: recorded {} run(s) as merged externally",
4611 out.external_merges_recorded
4612 );
4613 }
4614 if out.stale_pr_states_repaired > 0 {
4615 tracing::info!(
4616 "housekeep: rewrote {} run record(s) whose pull request had already settled",
4617 out.stale_pr_states_repaired
4618 );
4619 }
4620 if out.cache_files > 0 {
4621 tracing::info!(
4622 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4623 out.cache_files,
4624 out.cache_freed
4625 );
4626 }
4627 if out.questions_abandoned > 0 {
4628 tracing::info!(
4629 "housekeep: abandoned {} question(s) left open by a finished run",
4630 out.questions_abandoned
4631 );
4632 }
4633}
4634
4635async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4644 let questions = Questions::at(home.join("questions"));
4645 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4646 if report.is_empty() {
4647 return;
4648 }
4649 if !report.quarantined.is_empty() {
4650 tracing::info!(
4651 "triage: held {} blocked task(s) whose blocked-on task or \
4652 question no longer exists: {}",
4653 report.quarantined.len(),
4654 report.quarantined.join(", ")
4655 );
4656 }
4657 if !report.resumed.is_empty() {
4658 tracing::info!(
4659 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4660 report.resumed.len(),
4661 report.resumed.join(", ")
4662 );
4663 }
4664 if !report.asked.is_empty() {
4665 tracing::info!(
4666 "triage: asked about {} held task(s): {}",
4667 report.asked.len(),
4668 report.asked.join(", ")
4669 );
4670 }
4671 if !report.answered.is_empty() {
4672 tracing::info!(
4673 "triage: applied {} operator answer(s): {}",
4674 report.answered.len(),
4675 report.answered.join(", ")
4676 );
4677 }
4678}
4679
4680pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4687 disk_gate_with(repo, config, crate::disk::free_bytes)
4688}
4689
4690fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4694 repo: &Path,
4695 config: &Config,
4696 free_bytes: F,
4697) -> Option<String> {
4698 let min = config.disk.min_free_bytes;
4699 if min == 0 {
4700 return None;
4701 }
4702 let mut paths = vec![repo.to_owned()];
4703 if let Some(cache) = config.cache_dir() {
4704 paths.push(cache);
4705 }
4706 if let Some(root) = &config.graph.worktree_root {
4707 paths.push(root.clone());
4708 }
4709 for path in paths {
4710 let probe = if path == repo {
4711 path.as_path()
4712 } else {
4713 path.ancestors().find(|p| p.exists()).unwrap_or(&path)
4714 };
4715 let reason = match free_bytes(probe) {
4716 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4717 Err(e) => Some(crate::disk::unmeasured_in(
4718 probe,
4719 &e,
4720 &config.graph.language,
4721 )),
4722 };
4723 if reason.is_some() {
4724 return reason;
4725 }
4726 }
4727 None
4728}
4729
4730const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4737
4738const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4742
4743fn quota_wait(
4752 reset_at: Option<Timestamp>,
4753 now: Timestamp,
4754 fallback: Duration,
4755 cap: Duration,
4756) -> Duration {
4757 match reset_at {
4758 Some(at) if at > now => {
4759 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4760 Duration::from_secs(secs).min(cap)
4761 }
4762 _ => fallback,
4763 }
4764}
4765
4766fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4780 parse_reset_hint_zoned(text, now)
4781 .or_else(|| parse_reset_hint_dated(text))
4782 .or_else(|| parse_reset_hint_relative(text, recorded))
4783}
4784
4785fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4789 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4790 let mut rest = rest.trim();
4791 if rest.is_empty() {
4792 return None;
4793 }
4794 let mut total: i64 = 0;
4795 let mut matched = false;
4796 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4797 if let Some((digits, tail)) = rest.split_once(unit)
4798 && !digits.is_empty()
4799 && digits.bytes().all(|b| b.is_ascii_digit())
4800 {
4801 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4802 rest = tail;
4803 matched = true;
4804 }
4805 }
4806 if !rest.is_empty() || !matched {
4807 return None;
4808 }
4809 recorded
4810 .checked_add(jiff::SignedDuration::from_secs(total))
4811 .ok()
4812}
4813
4814fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4818 let clock = clock.trim().to_lowercase();
4819 let (digits, pm) = clock
4820 .strip_suffix("am")
4821 .map(|d| (d, false))
4822 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4823 let (h, m) = digits.trim().split_once(':')?;
4824 let mut hour: i8 = h.trim().parse().ok()?;
4825 let minute: i8 = m.trim().parse().ok()?;
4826 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4827 return None;
4828 }
4829 if pm && hour != 12 {
4830 hour += 12;
4831 } else if !pm && hour == 12 {
4832 hour = 0;
4833 }
4834 Some((hour, minute))
4835}
4836
4837fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4842 let open = text.find('(')?;
4843 let close = text.rfind(')')?;
4844 if close <= open {
4845 return None;
4846 }
4847 let zone = text[open + 1..close].trim();
4848 let (hour, minute) = parse_12h_clock(&text[..open])?;
4849 let tz = jiff::tz::TimeZone::get(zone).ok()?;
4850 let candidate = now
4851 .to_zoned(tz)
4852 .with()
4853 .hour(hour)
4854 .minute(minute)
4855 .second(0)
4856 .millisecond(0)
4857 .microsecond(0)
4858 .nanosecond(0)
4859 .build()
4860 .ok()?;
4861 let mut at = candidate.timestamp();
4862 if at <= now {
4863 at += jiff::SignedDuration::from_hours(24);
4864 }
4865 Some(at)
4866}
4867
4868fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4877 let words: Vec<&str> = text.split_whitespace().collect();
4878 if words.len() < 5 {
4879 return None;
4880 }
4881 (0..=words.len() - 5)
4882 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4883}
4884
4885fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4891 if trailing.is_some_and(|next| next.starts_with('(')) {
4892 return None;
4893 }
4894 let month = month_number(window[0])?;
4895 let day_token = window[1].strip_suffix(',')?.to_lowercase();
4896 let day_digits = ["st", "nd", "rd", "th"]
4897 .iter()
4898 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4899 let day: i8 = day_digits.parse().ok()?;
4900 let year_token = window[2];
4901 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4902 return None;
4903 }
4904 let year: i16 = year_token.parse().ok()?;
4905 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4909 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4910 let date = jiff::civil::Date::new(year, month, day).ok()?;
4911 let candidate = date
4912 .at(hour, minute, 0, 0)
4913 .to_zoned(jiff::tz::TimeZone::UTC)
4914 .ok()?;
4915 Some(candidate.timestamp())
4916}
4917
4918fn month_number(name: &str) -> Option<i8> {
4921 const NAMES: [&str; 12] = [
4922 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4923 ];
4924 let lower = name.to_lowercase();
4925 NAMES
4926 .iter()
4927 .position(|n| *n == lower.as_str())
4928 .map(|i| i as i8 + 1)
4929}
4930
4931fn exhausted_review_budget(state: &RunState) -> bool {
4943 state.status == RunStatus::Blocked
4946 && !state.pr_publication_pending
4947 && state.reviews.len() >= state.config.graph.review_rounds
4948}
4949
4950fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4987 unfinished_run_with(runs, short, RunState::load)
4988}
4989
4990pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
4993where
4994 F: FnMut(&str) -> Result<RunState>,
4995{
4996 let mut id = runs.last()?.clone();
4997 let mut visited = std::collections::BTreeSet::new();
4998 let mut repo = None;
4999 loop {
5000 if !runs.contains(&id) || !visited.insert(id.clone()) {
5001 tracing::warn!("invalid or cyclic recovery authority for task {short}");
5002 return None;
5003 }
5004 let state = match load(&id) {
5005 Ok(state) if state.id == id => state,
5006 Ok(_) => return None,
5007 Err(e) => {
5008 tracing::warn!("could not read run {id} for task {short}: {e:#}");
5009 return None;
5010 }
5011 };
5012 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5013 return None;
5014 }
5015 repo = Some(state.repo.clone());
5016 if let Some(authority) = state.retired_to {
5017 id = authority;
5018 continue;
5019 }
5020 return (state.status.resumable()
5021 && !state.released()
5022 && !exhausted_review_budget(&state)
5023 && state.liveness(false) != crate::run::Liveness::Live)
5024 .then_some(id);
5025 }
5026}
5027
5028fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5036where
5037 F: FnOnce(&str) -> Result<RunState>,
5038{
5039 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5041 || task.fresh_start
5042 || task.review_branch.is_some()
5043 {
5044 return false;
5045 }
5046 let Some(id) = task.runs.last() else {
5047 return false;
5048 };
5049 load(id).is_ok_and(|s| {
5050 s.parked
5051 && s.status.resumable()
5052 && !s.released()
5053 && s.retired_to.is_none()
5054 && !exhausted_review_budget(&s)
5055 })
5056}
5057
5058#[derive(Debug, Clone, PartialEq, Eq)]
5061enum Starter {
5062 Review(String),
5065 Resume(String),
5067 Start,
5069}
5070
5071fn retained_attempt_hold(
5075 task: &Task,
5076 starter: &Starter,
5077 limit: usize,
5078 mut load: impl FnMut(&str) -> Result<RunState>,
5079) -> Option<String> {
5080 if limit == 0 || matches!(starter, Starter::Resume(_)) {
5081 return None;
5082 }
5083 let mut retained = 0;
5084 for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5085 let state = match load(id) {
5086 Ok(state) if state.id == *id => state,
5087 _ => {
5088 return Some(format!(
5089 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5090 ));
5091 }
5092 };
5093 if state.retired_to.is_some() || state.released() {
5094 continue;
5095 }
5096 retained += 1;
5099 }
5100 (retained >= limit).then(|| format!(
5101 "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
5102 ))
5103}
5104
5105fn selected_starter(
5107 selected: &crate::pr_recovery::Selection,
5108 previous: Option<&RunState>,
5109 unfinished: Option<&str>,
5110) -> Starter {
5111 if let Some(id) = unfinished
5112 && previous.is_some_and(|r| {
5113 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5114 })
5115 {
5116 Starter::Resume(id.to_owned())
5117 } else {
5118 Starter::Review(selected.branch.clone())
5119 }
5120}
5121
5122fn take_divergence_answer(
5126 branch: &str,
5127 remote: &str,
5128 task: &mut Task,
5129) -> Option<crate::reconcile::Choice> {
5130 let summary = crate::reconcile::summary_for(branch, remote);
5131 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5132 (a.question == summary)
5133 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5134 .flatten()
5135 .map(|c| (i, c))
5136 })?;
5137 task.answers.remove(idx);
5138 Some(choice)
5139}
5140
5141fn choose_starter(
5153 review_branch: Option<&str>,
5154 branch_exists: bool,
5155 unfinished: Option<&str>,
5156) -> Starter {
5157 match review_branch {
5158 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5159 Some(_) => Starter::Start,
5160 None => match unfinished {
5161 Some(id) => Starter::Resume(id.to_owned()),
5162 None => Starter::Start,
5163 },
5164 }
5165}
5166
5167fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5169 let branch = task.review_branch.take();
5170 let instruction = task.review_instruction.take();
5171 branch.filter(|branch| match &instruction {
5172 Some(authored) => *authored == task.instruction,
5173 None => previous.map_or_else(
5176 || task.review_of.as_ref() == Some(branch),
5177 |run| compatible_run_instruction(run, task),
5178 ),
5179 })
5180}
5181
5182fn may_resume_run(run: &RunState, task: &Task) -> bool {
5185 task.resume_override
5186 .as_ref()
5187 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5188 || compatible_run_instruction(run, task)
5189}
5190
5191pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5193 if let Some(authored) = &run.task_instruction {
5194 return compatible_instruction(authored, task);
5195 }
5196 if compatible_instruction(&run.instruction, task) {
5197 return true;
5198 }
5199 if run.reviewed_commits.is_some() {
5202 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5203 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5204 }
5205 if let Some(branch) = &task.review_of {
5206 let canonical = format!(
5207 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5208 );
5209 let generated = format!(
5210 "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"
5211 );
5212 return task.instruction == canonical && run.instruction.starts_with(&generated);
5213 }
5214 }
5215 false
5216}
5217
5218pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5220 strip_answers_block(old, task) == task.instruction
5221}
5222
5223fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5226 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5227 return fallback.to_path_buf();
5228 }
5229 task.repo.clone()
5230}
5231
5232const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5236
5237fn answers_block(task: &Task, count: usize) -> String {
5239 let mut s = ANSWERS_HEADER.to_owned();
5240 for a in &task.answers[..count] {
5241 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5242 }
5243 s
5244}
5245
5246fn resumption_block(r: &crate::queue::Resumption) -> String {
5249 format!(
5250 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5251 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5252 r.generation, r.at, r.instruction, r.answers_through,
5253 )
5254}
5255
5256fn append_answers(base: &str, task: &Task) -> String {
5258 let mut s = base.to_owned();
5259 if !task.answers.is_empty() {
5260 s.push_str(&answers_block(task, task.answers.len()));
5261 }
5262 if let Some(r) = &task.resumption {
5263 s.push_str(&resumption_block(r));
5264 }
5265 s
5266}
5267
5268fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5272 let mut instruction = instruction;
5273 for approval in task
5274 .resumption
5275 .iter()
5276 .chain(task.resumption_history.iter().rev())
5277 {
5278 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5279 instruction = base;
5280 break;
5281 }
5282 }
5283 for count in (1..=task.answers.len()).rev() {
5284 let block = answers_block(task, count);
5285 if let Some(base) = instruction.strip_suffix(&block) {
5286 return base;
5287 }
5288 }
5289 instruction
5290}
5291
5292fn instruction_for(task: &Task) -> String {
5300 append_answers(&task.instruction, task)
5301}
5302
5303fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5315 append_answers(strip_answers_block(old_instruction, task), task)
5316}
5317
5318fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5320 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5321 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5322 if let Some(cause) = task.hold_notice_cause.as_mut() {
5323 cause.target = failure.map(|f| f.target.clone());
5324 }
5325}
5326
5327#[derive(Debug, thiserror::Error)]
5328#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5329struct MissingAttachment {
5330 name: String,
5331 path: PathBuf,
5332}
5333
5334fn task_attachments(
5336 queue: &Queue,
5337 task: &Task,
5338) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5339 let paths = queue.attachment_paths(task);
5340 for (name, path) in task.attachments.iter().zip(&paths) {
5341 if !path.is_file() {
5342 return Err(MissingAttachment {
5343 name: name.clone(),
5344 path: path.clone(),
5345 });
5346 }
5347 }
5348 Ok(paths)
5349}
5350
5351fn prepare_instruction(
5362 starter: &Starter,
5363 old_instruction: Option<&str>,
5364 task: &Task,
5365) -> Option<String> {
5366 match starter {
5367 Starter::Start => Some(instruction_for(task)),
5368 Starter::Resume(_) => Some(resumed_instruction(
5369 old_instruction.expect("a resumed run always has a prior instruction"),
5370 task,
5371 )),
5372 Starter::Review(_) => None,
5373 }
5374}
5375
5376fn record(queue: &Queue, task: &mut Task) {
5380 if let Err(e) = queue.put(task) {
5381 tracing::error!("could not record task {}: {e:#}", task.short());
5382 let notice = Notice::error(
5383 "loop:record",
5384 "The loop could not save a task's state; check the disk.",
5385 )
5386 .link(Link::Task {
5387 id: task.id.clone(),
5388 });
5389 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5391 Some(home) => notices::raise_in(home, notice),
5392 None => notices::raise(notice),
5393 }
5394 }
5395}
5396
5397fn runnable(queue: &Queue) -> Vec<Task> {
5403 let mut tasks: Vec<Task> = queue
5404 .list()
5405 .into_iter()
5406 .filter(|t| t.status.runnable())
5407 .collect();
5408 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5409 tasks
5410}
5411
5412fn describe(state: &RunState) -> String {
5426 let p = phrases(&state.config.graph.language);
5427 let mut detail = if state.status == RunStatus::Stalled {
5428 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5429 seats.sort_unstable();
5430 seats.dedup();
5431 if seats.is_empty() {
5432 p.quorum_lost.to_owned()
5433 } else {
5434 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5435 }
5436 } else {
5437 format!("{}{}", p.run_ended, state.status.display_label())
5438 };
5439 if let Some(last) = state.events.last() {
5440 let unanswered = state
5444 .reviews
5445 .last()
5446 .filter(|r| {
5447 state.status == RunStatus::Blocked
5448 && last.node == "review"
5449 && r.incomplete()
5450 && r.blocking == 0
5451 && r.round == state.config.graph.review_rounds
5452 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5453 })
5454 .map(|r| (r.expected - r.answered, r.round));
5455 match unanswered {
5456 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5457 detail.push_str(&format!(
5458 " ({}: {})",
5459 last.node,
5460 (p.reviewers_never_answered)(missing, rounds)
5461 ));
5462 }
5463 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5464 }
5465 }
5466 detail.push_str(&format!(" [run {}]", state.id));
5467 detail
5468}
5469
5470const DIAGNOSTIC_MAX: usize = 4_000;
5476
5477const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5482
5483fn diagnostic(state: &RunState) -> Option<String> {
5497 let mut parts: Vec<String> = Vec::new();
5498
5499 for o in state.gate.iter().filter(|o| !o.ok()) {
5501 parts.push(format!(
5502 "gate `{}` failed ({}):\n{}",
5503 o.command,
5504 notices::exit_status(o.code),
5505 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5506 ));
5507 }
5508
5509 if let Some(last) = state
5512 .events
5513 .iter()
5514 .rev()
5515 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5516 {
5517 parts.push(last.message.clone());
5518 }
5519
5520 if state.viable().is_empty() {
5527 for c in &state.candidates {
5528 if let Some(evidence) = &c.verified_noop {
5529 parts.push(format!(
5530 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5531 c.label
5532 ));
5533 } else if !c.summary.trim().is_empty() {
5534 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5535 } else if let Some(why) = &c.failed {
5536 parts.push(format!("candidate {}: {why}", c.label));
5537 }
5538 }
5539 }
5540
5541 if parts.is_empty() {
5542 return None;
5543 }
5544 Some(crate::run::tail(
5549 &parts.join("\n\n"),
5550 DIAGNOSTIC_MAX.saturating_sub(100),
5551 ))
5552}
5553
5554fn label(status: RunStatus) -> &'static str {
5562 status.as_str()
5563}
5564
5565pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5567 match mode {
5568 "none" => Ok(MergeMode::None),
5569 "local" => Ok(MergeMode::Local),
5570 "pr" => Ok(MergeMode::Pr),
5571 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5572 }
5573}
5574
5575fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5580 mutex
5581 .lock()
5582 .unwrap_or_else(std::sync::PoisonError::into_inner)
5583}
5584
5585#[cfg(test)]
5586mod tests {
5587 use super::*;
5588 use crate::queue::{Source, TaskStatus};
5589 use crate::run::{Candidate, CommandOutcome};
5590 use pretty_assertions::assert_eq;
5591
5592 fn task() -> Task {
5593 Task::new(
5594 "add retries".to_owned(),
5595 "add retries".to_owned(),
5596 PathBuf::from("/repo"),
5597 Source::Human,
5598 )
5599 }
5600
5601 #[test]
5602 fn selected_public_head_overrides_historical_resume_and_pin() {
5603 let mut t = task();
5604 let mut old = run_state(RunStatus::Blocked);
5605 let selection = crate::pr_recovery::Selection {
5606 url: "url".into(),
5607 branch: format!("magi/task-{}", t.id),
5608 head: "a".repeat(40),
5609 source_head: None,
5610 source_run: None,
5611 source_proof: None,
5612 disposition: Some(crate::pr_recovery::Disposition::Review),
5613 instruction: t.instruction.clone(),
5614 approved_at: Timestamp::now(),
5615 };
5616 t.resume_override = Some(crate::queue::OperatorResume {
5617 pinned_run: Some(old.id.clone()),
5618 question_id: "choice".into(),
5619 at: Timestamp::now(),
5620 conductor_rehold: None,
5621 forced: false,
5622 });
5623 assert_eq!(
5624 selected_starter(&selection, Some(&old), Some(&old.id)),
5625 Starter::Review(selection.branch.clone())
5626 );
5627 old.pr_recovery = Some(selection.clone());
5628 assert_eq!(
5629 selected_starter(&selection, Some(&old), Some(&old.id)),
5630 Starter::Review(selection.branch.clone())
5631 );
5632 old.reviewed_commits = Some(vec!["implementation".into()]);
5633 assert_eq!(
5634 selected_starter(&selection, Some(&old), Some(&old.id)),
5635 Starter::Resume(old.id.clone())
5636 );
5637 let mut changed = selection.clone();
5638 changed.head = "b".repeat(40);
5639 assert_eq!(
5640 selected_starter(&changed, Some(&old), Some(&old.id)),
5641 Starter::Review(changed.branch)
5642 );
5643 }
5644
5645 #[test]
5646 fn candidate_transplant_failure_is_one_actionable_hold() {
5647 let dir = tempfile::tempdir().unwrap();
5648 let q = Queue::at(dir.path().join("queue"));
5649 let mut t = task();
5650 let mut state = run_state(RunStatus::Blocked);
5651 state.event("prep", "cannot apply referenced commit: conflict");
5652 state.prep_failure = Some("conflict".into());
5653 t.start(state.id.clone());
5654 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5655 assert_eq!(t.attempts, 1);
5656 assert_eq!(t.status, TaskStatus::Held);
5657 assert!(t.operator_held());
5658 assert!(!t.status.runnable());
5659 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5660 let first = t.chat_notice_key().unwrap();
5661 t.chat_notices.push(first.clone());
5662 t.release_operator("test", None);
5663 state.id = "another-unprepared-run".into();
5664 t.start(state.id.clone());
5665 finish_attempt(
5666 3,
5667 &q,
5668 &mut t,
5669 &state,
5670 &[],
5671 Err(anyhow::anyhow!("still conflicts")),
5672 );
5673 assert_eq!(
5674 t.chat_notice_key().as_ref(),
5675 Some(&first),
5676 "no work happened"
5677 );
5678 t.release_operator("test", None);
5679 state.prep_failure = None;
5680 state.status = RunStatus::Failed;
5681 state.begin_pass();
5682 t.start(state.id.clone());
5683 finish_attempt(
5684 1,
5685 &q,
5686 &mut t,
5687 &state,
5688 &[],
5689 Err(anyhow::anyhow!("new gate failure")),
5690 );
5691 let failure = t.chat_notice_key().unwrap();
5692 assert_ne!(failure, first, "approved recovery reached a real failure");
5693 t.release_operator("test", None);
5694 state.begin_pass();
5695 t.start(state.id.clone());
5696 finish_attempt(
5697 1,
5698 &q,
5699 &mut t,
5700 &state,
5701 &[],
5702 Err(anyhow::anyhow!("new failure on resume")),
5703 );
5704 assert_ne!(
5705 t.chat_notice_key().as_ref(),
5706 Some(&failure),
5707 "a new settled pass"
5708 );
5709 }
5710
5711 #[test]
5712 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5713 for source in ["cli", "web"] {
5714 let mut t = task();
5715 let mut run = run_state(RunStatus::Blocked);
5716 run.instruction = "Run A original criteria".into();
5717 run.task_instruction = Some(run.instruction.clone());
5718 t.start(run.id.clone());
5719 t.release_operator("choice", Some("resume-question"));
5720 t.resume_override = Some(crate::queue::OperatorResume {
5721 question_id: "resume-question".into(),
5722 at: Timestamp::now(),
5723 conductor_rehold: None,
5724 forced: true,
5725 pinned_run: Some(run.id.clone()),
5726 });
5727 t.hold_machine(Some("not enough free space to start a run".into()));
5728 let mut unchanged = t.clone();
5729 unchanged
5730 .edit("title changed".into(), unchanged.instruction.clone())
5731 .unwrap();
5732 unchanged.release_operator(source, None);
5733 assert_eq!(
5734 unchanged
5735 .resume_override
5736 .as_ref()
5737 .unwrap()
5738 .pinned_run
5739 .as_deref(),
5740 Some(run.id.as_str())
5741 );
5742 assert!(!compatible_run_instruction(&run, &unchanged));
5743 assert!(may_resume_run(&run, &unchanged));
5744
5745 t.edit(
5746 "approved recovery".into(),
5747 "Reuse measured PR head B; fix Clippy; review".into(),
5748 )
5749 .unwrap();
5750 assert!(t.resume_override.is_none());
5751 t.release_operator(source, None);
5752 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5753 assert!(reloaded.resume_override.is_none());
5754 assert!(!may_resume_run(&run, &reloaded));
5755 let unfinished =
5756 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5757 .filter(|_| may_resume_run(&run, &reloaded));
5758 assert_eq!(
5759 choose_starter(None, false, unfinished.as_deref()),
5760 Starter::Start
5761 );
5762 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5763 assert_eq!(
5764 reloaded.resumption_history[0].question_id.as_deref(),
5765 Some("resume-question")
5766 );
5767
5768 unchanged.instruction = "Reuse measured PR head B".into();
5771 unchanged.hold_machine(Some("disk hold".into()));
5772 unchanged.release_operator(source, None);
5773 assert!(unchanged.resume_override.is_none());
5774 assert!(!may_resume_run(&run, &unchanged));
5775 }
5776 }
5777
5778 #[test]
5779 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5780 let mut t = task();
5781 let mut run = run_state(RunStatus::Blocked);
5782 t.review_of = Some("approved-head".into());
5783 t.instruction =
5784 "Review the branch `approved-head` (review-only: no implementation, no judging)."
5785 .into();
5786 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();
5787 run.reviewed_commits = Some(vec!["Commit log".into()]);
5788 t.start(run.id.clone());
5789 t.hold_machine(Some("interrupted review".into()));
5790 t.release_operator("cli", None);
5791 assert!(
5792 compatible_run_instruction(&run, &t),
5793 "legacy explicit review remains resumable"
5794 );
5795 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5796 .filter(|_| compatible_run_instruction(&run, &t));
5797 assert_eq!(
5798 choose_starter(None, false, unfinished.as_deref()),
5799 Starter::Resume(run.id.clone())
5800 );
5801 run.task_instruction = Some(t.instruction.clone());
5802 assert!(compatible_run_instruction(&run, &t));
5803 let reloaded: RunState =
5804 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5805 assert!(compatible_run_instruction(&reloaded, &t));
5806 t.edit(
5807 "new approved head".into(),
5808 "Reuse measured PR head B".into(),
5809 )
5810 .unwrap();
5811 assert!(!compatible_run_instruction(&run, &t));
5812
5813 t.review_of = None;
5815 t.instruction = "Fix Clippy on approved head".into();
5816 run.task_instruction = None;
5817 run.instruction = format!(
5818 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5819 t.instruction
5820 );
5821 assert!(compatible_run_instruction(&run, &t));
5822 t.instruction.push('\n');
5823 assert!(
5824 compatible_run_instruction(&run, &t),
5825 "legacy generated review trimmed the original criteria"
5826 );
5827 t.hold_for_handover(Some("approved-head".into()), "refused".into());
5828 let mut unchanged = t.clone();
5829 assert_eq!(
5830 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5831 Some("approved-head")
5832 );
5833 t.edit("new plan".into(), "Reuse measured PR head B".into())
5834 .unwrap();
5835 assert!(take_review_branch(&mut t, Some(&run)).is_none());
5836 assert!(!compatible_run_instruction(&run, &t));
5837 t.review_branch = Some("approved-head".into());
5838 t.review_instruction = None;
5839 assert!(
5840 take_review_branch(&mut t, Some(&run)).is_none(),
5841 "legacy retained candidate cannot replace a revised approved head"
5842 );
5843 }
5844
5845 #[test]
5846 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5847 crate::run::pin_test_home();
5848 let dir = tempfile::tempdir().unwrap();
5849 let queue = Queue::at(dir.path().join("queue"));
5850 for resume in [true, false] {
5851 let state = run_state(RunStatus::Blocked);
5852 let mut t = task();
5853 t.start(state.id.clone());
5854 let action = if resume {
5855 ask::ChoiceAction::Resume {
5856 run: state.id.clone(),
5857 }
5858 } else {
5859 ask::ChoiceAction::Requeue
5860 };
5861 let mut q = action_question(&state.id, action);
5862 q.status = ask::QuestionStatus::Open;
5863 q.answer = None;
5864 q.answered_at = None;
5865 t.fail("run stopped with a question", 3);
5866 hold_if_runnable(&queue, &mut t);
5867 assert!(t.operator_decided_at.is_none());
5868 assert!(t.operator_held());
5869 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5870 let expected = if resume {
5871 ActionDecision::Resume(state.id.clone())
5872 } else {
5873 ActionDecision::Requeue
5874 };
5875 assert_eq!(
5876 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5877 expected
5878 );
5879 t.hold_manual(Some("later explicit hold".into()));
5880 assert_eq!(
5881 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5882 ActionDecision::Stale
5883 );
5884 }
5885 }
5886
5887 #[test]
5888 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5889 let mut t = task();
5890 t.answers.push(crate::queue::AnsweredQuestion {
5891 question: "Inspect the remote?".into(),
5892 answer: "Inspect then wait".into(),
5893 });
5894 let old = instruction_for(&t);
5895 assert!(compatible_instruction(&old, &t));
5896 t.instruction = "Reuse approved PR head and review".into();
5897 t.release_operator("cli", None);
5898 assert!(!compatible_instruction(&old, &t));
5899 let approved = instruction_for(&t);
5900 assert!(approved.contains("waiting premises are superseded"));
5901 assert!(compatible_instruction(&approved, &t));
5902 assert_eq!(resumed_instruction(&approved, &t), approved);
5903 t.release_operator("web", None);
5904 assert!(compatible_instruction(&approved, &t));
5905 assert_eq!(t.resumption_history.len(), 1);
5906 t.start("run".into());
5907 assert!(instruction_for(&t).contains("Explicit operator resumption"));
5908 }
5909
5910 #[test]
5914 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5915 let mut state = RunState::new(
5916 PathBuf::from("/repo"),
5917 "main".to_owned(),
5918 "abc1234".to_owned(),
5919 "task".to_owned(),
5920 Config::default(),
5921 );
5922 state.status = RunStatus::Blocked;
5923 state.resource_block = Some(crate::run::ResourceBlock {
5924 node: "graft".to_owned(),
5925 kind: "shared build cache".to_owned(),
5926 detail: "timed out".to_owned(),
5927 at: jiff::Timestamp::now(),
5928 });
5929 let mut t = task();
5930 t.start("20260902-000000-aaaa".to_owned());
5931 assert_eq!(t.attempts, 1);
5932 let verdict = Verdict {
5933 status: RunStatus::Blocked,
5934 left_pr: false,
5935 quota_hit: false,
5936 parked: false,
5937 no_viable_candidates: false,
5938 };
5939 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5940 assert_eq!(t.status, TaskStatus::Held);
5941 assert_eq!(t.attempts, 0, "the attempt is refunded");
5942 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5943 assert!(
5944 !t.operator_held(),
5945 "a machine hold, released without a human"
5946 );
5947
5948 let mut selected = task();
5949 selected.start("20260902-000000-cccc".into());
5950 selected.replacement = Some(crate::merge_decision::Replacement {
5951 question: "fixture".into(),
5952 run: "earlier".into(),
5953 pr: "https://example.invalid/pr/1".into(),
5954 agent: "selected".into(),
5955 context: "fixture".into(),
5956 });
5957 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5958 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5959 assert_eq!(selected.attempts, 0);
5960 assert!(
5961 !selected.operator_held(),
5962 "a selected agent also retains a machine resource hold"
5963 );
5964 assert!(
5965 selected
5966 .hold_reason
5967 .as_deref()
5968 .unwrap()
5969 .starts_with("[resource] ")
5970 );
5971
5972 let mut p = task();
5974 p.start("20260902-000000-bbbb".to_owned());
5975 settle_and_diagnose(
5976 &mut p,
5977 Verdict {
5978 parked: true,
5979 ..verdict
5980 },
5981 "parked",
5982 2,
5983 &state,
5984 );
5985 assert_eq!(p.status, TaskStatus::Parked);
5986 }
5987
5988 #[test]
5989 fn record_failure_notice_links_the_task() {
5990 let dir = tempfile::tempdir().unwrap();
5991 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5994 let queue = Queue::at(dir.path().join("queue"));
5995 let mut t = interrupt_task("rec-fail-1");
5996 record(&queue, &mut t);
5997
5998 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5999 assert_eq!(found.len(), 1);
6000 assert_eq!(found[0].key, "loop:record");
6001 assert_eq!(
6002 found[0].link,
6003 Some(Link::Task {
6004 id: "rec-fail-1".to_owned()
6005 })
6006 );
6007 }
6008
6009 fn interrupt_task(id: &str) -> Task {
6012 let mut t = task();
6013 t.id = id.to_owned();
6014 t.interrupt = true;
6015 t
6016 }
6017
6018 fn task_with_id(id: &str) -> Task {
6020 let mut t = task();
6021 t.id = id.to_owned();
6022 t
6023 }
6024
6025 fn urgent_task(id: &str) -> Task {
6027 let mut t = task();
6028 t.id = id.to_owned();
6029 t.urgent = true;
6030 t
6031 }
6032
6033 #[test]
6034 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
6035 let dir = tempfile::tempdir().unwrap();
6036 let queue = Queue::at(dir.path().join("queue"));
6037 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6038 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6039 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
6040 let mut first = task();
6041 queue.put(&mut first).unwrap();
6042 let stale_plain = queue.get(&first.id).unwrap();
6043 first.set_urgent(true).unwrap();
6044 queue.put(&mut first).unwrap();
6045 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
6046 let mut second = urgent_task("second");
6047 queue.put(&mut second).unwrap();
6048 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
6049 drop(queue.claim(&second.id).unwrap());
6050 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
6051 drop(dispatched);
6052 let stale_urgent = queue.get(&first.id).unwrap();
6053 first.set_urgent(false).unwrap();
6054 queue.put(&mut first).unwrap();
6055 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
6056 assert_eq!(urgent.available_permits(), 1);
6057 drop(queue.claim(&first.id).unwrap());
6058 drop(occupied);
6059 }
6060
6061 #[test]
6062 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
6063 let dir = tempfile::tempdir().unwrap();
6064 let queue = Queue::at(dir.path().join("queue"));
6065 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6066 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6067 let mut t = task();
6068 queue.put(&mut t).unwrap();
6069 for enabled in [true, false] {
6070 let stale = queue.get(&t.id).unwrap();
6071 t.set_urgent(enabled).unwrap();
6072 queue.put(&mut t).unwrap();
6073 assert_ne!(stale.urgent, enabled);
6074 let DispatchClaim {
6075 task: fresh,
6076 claim,
6077 permit,
6078 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
6079 assert_eq!(fresh.urgent, enabled);
6080 assert_eq!(ordinary.available_permits(), usize::from(enabled));
6081 assert_eq!(urgent.available_permits(), usize::from(!enabled));
6082 assert!(queue.claim(&t.id).is_err());
6083 assert_eq!(fresh.attempts, stale.attempts);
6084 drop((claim, permit));
6085 assert_eq!(ordinary.available_permits(), 1);
6086 assert_eq!(urgent.available_permits(), 1);
6087 }
6088 t.set_urgent(true).unwrap();
6089 queue.put(&mut t).unwrap();
6090 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
6091 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6092 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
6093 drop(queue.claim(&t.id).unwrap());
6094 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
6095 drop(occupied);
6096 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
6097 drop(queue.claim(&t.id).unwrap());
6098 let held = queue.claim(&t.id).unwrap();
6099 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6100 drop(held);
6101 t.status = TaskStatus::Held;
6102 queue.put(&mut t).unwrap();
6103 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6104 drop(queue.claim(&t.id).unwrap());
6105 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
6106 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6107 drop(queue.claim(&t.id).unwrap());
6108 assert_eq!(urgent.available_permits(), 1);
6109 }
6110
6111 #[test]
6116 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
6117 assert_eq!(permit_kind(true, false), PermitKind::None);
6118 assert_eq!(permit_kind(true, true), PermitKind::None);
6119 }
6120
6121 #[test]
6126 fn permit_kind_separates_urgent_from_ordinary() {
6127 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
6128 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
6129 }
6130
6131 #[test]
6138 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
6139 let cfg = Config::default();
6140 let repo = Path::new("/any/repo/path");
6141
6142 let reason =
6143 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
6144 assert!(reason.contains("1024"), "{reason}");
6145 assert!(
6146 reason.contains(&cfg.disk.min_free_bytes.to_string()),
6147 "{reason}"
6148 );
6149
6150 assert_eq!(
6151 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
6152 None,
6153 "exactly at the floor is open"
6154 );
6155 assert_eq!(
6156 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
6157 None,
6158 "comfortably above the floor is open"
6159 );
6160 }
6161
6162 #[test]
6163 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
6164 let mut cfg = Config::default();
6165 cfg.disk.min_free_bytes = 0;
6166 let repo = Path::new("/any/repo/path");
6167 assert_eq!(
6168 disk_gate_with(repo, &cfg, |_| Ok(0)),
6169 None,
6170 "a zero floor never measures at all"
6171 );
6172 }
6173
6174 #[test]
6175 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
6176 let cfg = Config::default();
6177 let repo = Path::new("/any/repo/path");
6178 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
6179 .expect("a measurement failure must close the gate, not open it");
6180 assert!(reason.contains("could not measure"), "{reason}");
6181 }
6182
6183 #[test]
6184 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
6185 let ordinary = task();
6186 let next = advance_interrupt(
6187 Interrupt::Idle,
6188 std::slice::from_ref(&ordinary.id),
6189 std::slice::from_ref(&ordinary),
6190 );
6191 assert_eq!(next, Interrupt::Idle);
6192 }
6193
6194 #[test]
6195 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6196 let marked = interrupt_task("marked");
6199 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6200 assert_eq!(next, Interrupt::Idle);
6201 }
6202
6203 #[test]
6204 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6205 let marked = interrupt_task("marked");
6206 let next = advance_interrupt(
6207 Interrupt::Idle,
6208 &["running".to_owned()],
6209 std::slice::from_ref(&marked),
6210 );
6211 assert_eq!(
6212 next,
6213 Interrupt::Parking {
6214 parked: vec!["running".to_owned()],
6215 interrupt_task: "marked".to_owned(),
6216 }
6217 );
6218 }
6219
6220 #[test]
6229 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6230 let marked = interrupt_task("marked");
6231
6232 let two = advance_interrupt(
6233 Interrupt::Idle,
6234 &["a".to_owned(), "b".to_owned()],
6235 std::slice::from_ref(&marked),
6236 );
6237 assert_eq!(two, Interrupt::Idle);
6238
6239 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6240 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6241 }
6242
6243 #[test]
6244 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6245 let state = Interrupt::Parking {
6246 parked: vec!["running".to_owned()],
6247 interrupt_task: "marked".to_owned(),
6248 };
6249 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6251 assert_eq!(still_going, state);
6252
6253 let stopped_but_not_yet_dispatched =
6257 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6258 assert_eq!(stopped_but_not_yet_dispatched, state);
6259
6260 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6262 assert_eq!(
6263 dispatched,
6264 Interrupt::Running {
6265 parked: vec!["running".to_owned()],
6266 interrupt_task: "marked".to_owned(),
6267 }
6268 );
6269 }
6270
6271 #[test]
6272 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6273 let state = Interrupt::Running {
6274 parked: vec!["running".to_owned()],
6275 interrupt_task: "marked".to_owned(),
6276 };
6277 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6278 assert_eq!(still_running, state);
6279
6280 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6287 assert_eq!(
6288 ended,
6289 Interrupt::Resuming {
6290 parked: vec!["running".to_owned()]
6291 }
6292 );
6293 }
6294
6295 #[test]
6296 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6297 let state = Interrupt::Resuming {
6298 parked: vec!["running".to_owned()],
6299 };
6300 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6301 assert_eq!(still_waiting, state);
6302
6303 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6304 assert_eq!(dispatched, Interrupt::Idle);
6305 }
6306
6307 #[test]
6313 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6314 {
6315 let state = Interrupt::Parking {
6316 parked: vec!["running".to_owned()],
6317 interrupt_task: "marked".to_owned(),
6318 };
6319 let next = advance_interrupt(state, &[], &[]);
6322 assert_eq!(
6323 next,
6324 Interrupt::Resuming {
6325 parked: vec!["running".to_owned()]
6326 },
6327 "abandoning the interrupt must not abandon the resume it owes"
6328 );
6329 }
6330
6331 #[test]
6334 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6335 let state = Interrupt::Resuming {
6336 parked: vec!["running".to_owned()],
6337 };
6338 let next = advance_interrupt(state, &[], &[]);
6339 assert_eq!(
6340 next,
6341 Interrupt::Idle,
6342 "nothing is left to wait for; the loop must not stay wedged"
6343 );
6344 }
6345
6346 #[test]
6347 fn disabled_by_config_the_sequence_can_never_leave_idle() {
6348 let marked = interrupt_task("marked");
6349 let next = advance_interrupt_tick(
6350 false,
6351 Interrupt::Idle,
6352 &["running".to_owned()],
6353 std::slice::from_ref(&marked),
6354 );
6355 assert_eq!(
6356 next,
6357 Interrupt::Idle,
6358 "an unmarked, unconfigured daemon must behave exactly as before"
6359 );
6360 }
6361
6362 #[test]
6363 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6364 let state = Interrupt::Parking {
6365 parked: vec!["running".to_owned()],
6366 interrupt_task: "marked".to_owned(),
6367 };
6368 let candidates = vec![interrupt_task("marked"), task()];
6369 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6370 assert!(
6371 allowed.is_empty(),
6372 "nothing may dispatch - not even the interrupt task itself - \
6373 until the parked run has actually stopped"
6374 );
6375 }
6376
6377 #[test]
6391 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6392 for state in [
6393 Interrupt::Parking {
6394 parked: vec!["running".to_owned()],
6395 interrupt_task: "marked".to_owned(),
6396 },
6397 Interrupt::Running {
6398 parked: vec!["running".to_owned()],
6399 interrupt_task: "marked".to_owned(),
6400 },
6401 Interrupt::Resuming {
6402 parked: vec!["running".to_owned()],
6403 },
6404 ] {
6405 let candidates = vec![
6406 interrupt_task("marked"),
6407 urgent_task("hot"),
6408 task_with_id("ordinary"),
6409 ];
6410 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6411 assert!(
6412 !allowed.iter().any(|t| t.id == "hot"),
6413 "an urgent candidate must wait out the same gate as anything \
6414 else while the run it would run alongside has not actually \
6415 left flight, for state {state:?}: {allowed:?}"
6416 );
6417 }
6418 }
6419
6420 #[test]
6426 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6427 let state = Interrupt::Resuming {
6428 parked: vec!["hot".to_owned()],
6429 };
6430 let candidates = vec![urgent_task("hot"), task()];
6431 let allowed = interrupt_gate(&state, &[], candidates);
6432 assert_eq!(
6433 allowed.iter().filter(|t| t.id == "hot").count(),
6434 1,
6435 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6436 );
6437 }
6438
6439 #[test]
6440 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6441 let state = Interrupt::Parking {
6442 parked: vec!["running".to_owned()],
6443 interrupt_task: "marked".to_owned(),
6444 };
6445 let other = task();
6446 let candidates = vec![interrupt_task("marked"), other.clone()];
6447 let allowed = interrupt_gate(&state, &[], candidates);
6448 assert_eq!(allowed.len(), 1);
6449 assert_eq!(allowed[0].id, "marked");
6450 }
6451
6452 #[test]
6453 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6454 let state = Interrupt::Running {
6455 parked: vec!["running".to_owned()],
6456 interrupt_task: "marked".to_owned(),
6457 };
6458 let candidates = vec![task(), task()];
6459 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6460 assert!(allowed.is_empty());
6461 }
6462
6463 #[test]
6470 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6471 let state = Interrupt::Resuming {
6472 parked: vec!["a".to_owned(), "c".to_owned()],
6473 };
6474 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6475 let allowed = interrupt_gate(&state, &[], candidates);
6476 assert_eq!(
6477 allowed.len(),
6478 1,
6479 "at most one candidate may be offered while resuming: {allowed:?}"
6480 );
6481 assert_eq!(allowed[0].id, "a");
6482 }
6483
6484 #[test]
6485 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6486 let state = Interrupt::Resuming {
6487 parked: vec!["a".to_owned()],
6488 };
6489 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6490 assert!(allowed.is_empty());
6491 }
6492
6493 #[test]
6499 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6500 let running = task(); let marked = interrupt_task("marked");
6502
6503 let mut state = Interrupt::Idle;
6504 let in_flight = vec![running.id.clone()];
6506 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6507 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6508 assert!(gated.is_empty(), "still waiting on `running` to park");
6509
6510 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6512 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6513 assert_eq!(
6514 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6515 vec!["marked"],
6516 "only the interrupt task may be offered to the dispatcher now"
6517 );
6518
6519 state = advance_interrupt_tick(
6521 true,
6522 state,
6523 &["marked".to_owned()],
6524 std::slice::from_ref(&running),
6525 );
6526 let gated = interrupt_gate(
6527 &state,
6528 &["marked".to_owned()],
6529 vec![marked.clone(), running.clone()],
6530 );
6531 assert!(
6532 gated.is_empty(),
6533 "the parked run must not be offered back while the interrupt \
6534 task is still running"
6535 );
6536
6537 let other = task_with_id("other");
6541 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6542 assert_eq!(
6543 state,
6544 Interrupt::Resuming {
6545 parked: vec![running.id.clone()]
6546 }
6547 );
6548 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6549 assert_eq!(
6550 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6551 vec![running.id.as_str()],
6552 "exactly the parked run resumes - not the unrelated task, even \
6553 though it was offered first"
6554 );
6555
6556 state = advance_interrupt_tick(
6560 true,
6561 state,
6562 std::slice::from_ref(&running.id),
6563 std::slice::from_ref(&other),
6564 );
6565 assert_eq!(state, Interrupt::Idle);
6566 let gated = interrupt_gate(
6567 &state,
6568 std::slice::from_ref(&running.id),
6569 vec![other.clone()],
6570 );
6571 assert_eq!(
6572 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6573 vec![other.id.as_str()],
6574 "ordinary dispatch is unrestricted again"
6575 );
6576 }
6577
6578 #[test]
6579 fn every_run_status_settles_the_task_it_came_from() {
6580 let table = [
6582 (RunStatus::Merged, TaskStatus::Done, 1),
6583 (RunStatus::Ready, TaskStatus::Done, 1),
6584 (RunStatus::Stalled, TaskStatus::Failed, 0),
6585 (RunStatus::Blocked, TaskStatus::Failed, 1),
6586 (RunStatus::Failed, TaskStatus::Failed, 1),
6587 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6588 (RunStatus::Prep, TaskStatus::Failed, 1),
6589 (RunStatus::Implementing, TaskStatus::Failed, 1),
6590 (RunStatus::Judging, TaskStatus::Failed, 1),
6591 (RunStatus::Deliberating, TaskStatus::Failed, 1),
6592 (RunStatus::Voting, TaskStatus::Failed, 1),
6593 (RunStatus::Reviewing, TaskStatus::Failed, 1),
6594 (RunStatus::Gating, TaskStatus::Failed, 1),
6595 ];
6596 for (run, want, attempts) in table {
6597 let mut t = task();
6598 t.start("20260902-000000-aaaa".to_owned());
6599 settle(
6600 &mut t,
6601 Verdict {
6602 status: run,
6603 left_pr: false,
6604 parked: false,
6605 quota_hit: matches!(run, RunStatus::Stalled),
6606 no_viable_candidates: false,
6607 },
6608 "why",
6609 2,
6610 );
6611 assert_eq!(t.status, want, "task status after {}", label(run));
6612 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6613 }
6614 }
6615
6616 #[test]
6617 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6618 let mut stalled = task();
6619 stalled.start("20260902-000000-aaaa".to_owned());
6620 settle(
6621 &mut stalled,
6622 Verdict {
6623 status: RunStatus::Stalled,
6624 left_pr: false,
6625 parked: false,
6626 quota_hit: true,
6627 no_viable_candidates: false,
6628 },
6629 "quota",
6630 1,
6631 );
6632 assert_eq!(stalled.attempts, 0);
6633 assert!(
6634 stalled.status.runnable(),
6635 "a machine problem must leave the task in line"
6636 );
6637
6638 let mut blocked = task();
6639 blocked.start("20260902-000000-aaaa".to_owned());
6640 settle(
6641 &mut blocked,
6642 Verdict {
6643 status: RunStatus::Blocked,
6644 left_pr: false,
6645 parked: false,
6646 quota_hit: false,
6647 no_viable_candidates: false,
6648 },
6649 "findings open",
6650 1,
6651 );
6652 assert_eq!(blocked.attempts, 1);
6653 assert_eq!(
6654 blocked.status,
6655 TaskStatus::Held,
6656 "the last attempt hands the task to a human"
6657 );
6658 }
6659
6660 #[test]
6661 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6662 let mut delivered = task();
6665 delivered.start("20260903-080619-01c2".to_owned());
6666 settle(
6667 &mut delivered,
6668 Verdict {
6669 status: RunStatus::Blocked,
6670 left_pr: true,
6671 parked: false,
6672 quota_hit: false,
6673 no_viable_candidates: false,
6674 },
6675 "no check status",
6676 4,
6677 );
6678 assert_eq!(
6679 delivered.status,
6680 TaskStatus::Held,
6681 "a pull request waiting on CI or a person is not a retryable failure"
6682 );
6683 assert!(
6684 !delivered.status.runnable(),
6685 "the loop must not pick this task up again"
6686 );
6687 assert_eq!(
6688 delivered.last_error.as_deref(),
6689 Some("no check status"),
6690 "the operator needs to be told what the gate was waiting for"
6691 );
6692
6693 let mut empty_handed = task();
6696 empty_handed.start("20260903-080619-01c2".to_owned());
6697 settle(
6698 &mut empty_handed,
6699 Verdict {
6700 status: RunStatus::Blocked,
6701 left_pr: false,
6702 parked: false,
6703 quota_hit: false,
6704 no_viable_candidates: false,
6705 },
6706 "findings open",
6707 4,
6708 );
6709 assert_eq!(empty_handed.status, TaskStatus::Failed);
6710 assert!(empty_handed.status.runnable());
6711 }
6712
6713 #[test]
6714 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6715 let mut noop = task();
6721 noop.start("20260912-131304-391f".to_owned());
6722 settle(
6723 &mut noop,
6724 Verdict {
6725 status: RunStatus::VerifiedNoop,
6726 left_pr: false,
6727 parked: false,
6728 quota_hit: false,
6729 no_viable_candidates: true,
6730 },
6731 "candidate A: already fixed by b32cfc4, on main",
6732 4,
6733 );
6734 assert_eq!(
6735 noop.status,
6736 TaskStatus::Held,
6737 "an unverified claim is a request for a human, not a failure"
6738 );
6739 assert!(
6740 !noop.status.runnable(),
6741 "the loop must not requeue this on the same unverified claim"
6742 );
6743 assert_eq!(noop.attempts, 1);
6748 }
6749
6750 #[test]
6751 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6752 let mut parked = task();
6757 parked.start("20260903-183634-2d98".to_owned());
6758 settle(
6759 &mut parked,
6760 Verdict {
6761 status: RunStatus::Implementing,
6762 left_pr: false,
6763 quota_hit: false,
6764 parked: true,
6765 no_viable_candidates: false,
6766 },
6767 "parked after `implementing`",
6768 2,
6769 );
6770 assert_eq!(parked.attempts, 0, "a park is refunded");
6771 assert!(
6772 parked.status.runnable(),
6773 "and the task stays in line so the next loop resumes its run"
6774 );
6775 assert_eq!(parked.status, TaskStatus::Parked);
6776 assert_eq!(
6777 parked.park_reason.as_deref(),
6778 Some("parked after `implementing`"),
6779 "the card says where it stopped"
6780 );
6781 assert_eq!(parked.last_error, None, "nothing failed");
6782
6783 let mut broken = task();
6787 broken.start("20260903-183634-2d98".to_owned());
6788 settle(
6789 &mut broken,
6790 Verdict {
6791 status: RunStatus::Implementing,
6792 left_pr: false,
6793 quota_hit: false,
6794 parked: false,
6795 no_viable_candidates: false,
6796 },
6797 "returned mid-flight",
6798 2,
6799 );
6800 assert_eq!(broken.attempts, 1);
6801 }
6802
6803 #[test]
6804 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6805 let mut flaky = task();
6810 flaky.start("20260903-123023-e633".to_owned());
6811 settle(
6812 &mut flaky,
6813 Verdict {
6814 status: RunStatus::Stalled,
6815 left_pr: false,
6816 parked: false,
6817 quota_hit: false,
6818 no_viable_candidates: false,
6819 },
6820 "verdict rests on 1 of 3 judges",
6821 2,
6822 );
6823 assert_eq!(
6824 flaky.attempts, 1,
6825 "flakiness spends an attempt, so `max_attempts` still bounds it"
6826 );
6827 assert!(flaky.status.runnable(), "and it is still worth retrying");
6828
6829 let mut limited = task();
6831 limited.start("20260903-123023-e633".to_owned());
6832 settle(
6833 &mut limited,
6834 Verdict {
6835 status: RunStatus::Stalled,
6836 left_pr: false,
6837 parked: false,
6838 quota_hit: true,
6839 no_viable_candidates: false,
6840 },
6841 "judge-2, judge-3 out of quota",
6842 2,
6843 );
6844 assert_eq!(limited.attempts, 0, "a quota window is refunded");
6845 assert!(limited.status.runnable());
6846
6847 let mut worn = task();
6850 for _ in 0..2 {
6851 worn.release();
6852 }
6853 worn.start("20260903-123023-e633".to_owned());
6854 worn.attempts = 2;
6855 settle(
6856 &mut worn,
6857 Verdict {
6858 status: RunStatus::Stalled,
6859 left_pr: false,
6860 parked: false,
6861 quota_hit: false,
6862 no_viable_candidates: false,
6863 },
6864 "no quorum again",
6865 2,
6866 );
6867 assert_eq!(worn.status, TaskStatus::Held);
6868 assert!(!worn.status.runnable());
6869 }
6870
6871 #[test]
6872 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6873 let mut wiped_out = task();
6880 wiped_out.start("20260907-025000-a1b2".to_owned());
6881 settle(
6882 &mut wiped_out,
6883 Verdict {
6884 status: RunStatus::Failed,
6885 left_pr: false,
6886 parked: false,
6887 quota_hit: true,
6888 no_viable_candidates: true,
6889 },
6890 "no candidate produced a change; nothing to judge",
6891 2,
6892 );
6893 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6894 assert!(
6895 wiped_out.status.runnable(),
6896 "a machine problem must leave the task in line"
6897 );
6898
6899 let mut partial_progress = task();
6905 partial_progress.start("20260907-025500-c3d4".to_owned());
6906 settle(
6907 &mut partial_progress,
6908 Verdict {
6909 status: RunStatus::Failed,
6910 left_pr: false,
6911 parked: false,
6912 quota_hit: true,
6913 no_viable_candidates: false,
6914 },
6915 "gate failed on the winning candidate",
6916 2,
6917 );
6918 assert_eq!(
6919 partial_progress.attempts, 1,
6920 "a candidate that actually produced a change spends the attempt \
6921 even though some other seat hit its quota"
6922 );
6923 assert!(partial_progress.status.runnable());
6924 }
6925
6926 #[test]
6927 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6928 let mut t = task();
6934 t.start("20260907-025000-a1b2".to_owned());
6935 let mut state = run_state(RunStatus::Failed);
6936 state.quota.push(QuotaLoss {
6937 seat: "cand-a".to_owned(),
6938 node: "implement".to_owned(),
6939 at: Timestamp::now(),
6940 reset: None,
6941 });
6942 assert!(
6943 state.viable().is_empty(),
6944 "no candidate was added, so nothing is viable"
6945 );
6946 reclaim(&mut t, Some(state), 2, "en");
6947 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6948 assert!(t.status.runnable());
6949 }
6950
6951 #[test]
6952 fn a_held_task_is_never_offered_to_the_loop() {
6953 let dir = tempfile::tempdir().unwrap();
6954 let queue = Queue::at(dir.path().to_path_buf());
6955 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6956 let mut t = task();
6957 t.id = format!("2026090{n}-000000-000{n}");
6958 t.priority = priority;
6959 queue.put(&mut t).unwrap();
6960 }
6961 let mut held = task();
6962 held.id = "20260909-000000-9999".to_owned();
6963 held.priority = 99;
6964 held.hold_machine(None);
6965 queue.put(&mut held).unwrap();
6966
6967 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6968 assert_eq!(order.len(), 3);
6969 assert!(!order.contains(&held.id));
6970 assert_eq!(
6971 order.first().cloned(),
6972 queue.next_runnable().map(|t| t.id),
6973 "the loop's first candidate is exactly what the queue offers"
6974 );
6975 assert_eq!(
6976 order,
6977 vec![
6978 "20260902-000000-0002".to_owned(),
6979 "20260903-000000-0003".to_owned(),
6980 "20260901-000000-0001".to_owned(),
6981 ],
6982 "priority first, then oldest, so nothing starves"
6983 );
6984 }
6985
6986 #[test]
6987 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6988 let dir = tempfile::tempdir().unwrap();
6989 let queue = Queue::at(dir.path().to_path_buf());
6990 let mut old = task();
6991 old.id = "20260101-000000-old0".to_owned();
6992 queue.put(&mut old).unwrap();
6993 let mut fresh = task();
6994 fresh.id = "20260101-000000-new0".to_owned();
6995 queue.put(&mut fresh).unwrap();
6996
6997 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7001 std::thread::sleep(Duration::from_millis(60));
7002 let live = queue.claim(&fresh.id).unwrap();
7003
7004 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7005 assert_eq!(swept, vec![old.id.clone()]);
7006 assert!(
7007 queue.claim(&old.id).is_ok(),
7008 "an unparseable lock older than the threshold is swept"
7009 );
7010 assert!(
7011 queue.claim(&fresh.id).is_err(),
7012 "a live pid protects its lock regardless of age"
7013 );
7014 drop(live);
7015 }
7016
7017 #[test]
7018 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7019 let dir = tempfile::tempdir().unwrap();
7029 let queue = Queue::at(dir.path().to_path_buf());
7030 let mut t = task();
7031 t.id = "20260101-000000-live".to_owned();
7032 queue.put(&mut t).unwrap();
7033
7034 let claim = queue.claim(&t.id).unwrap();
7035 std::thread::sleep(Duration::from_millis(60));
7036
7037 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7038 assert!(
7039 swept.is_empty(),
7040 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
7041 );
7042 assert!(
7043 queue.claim(&t.id).is_err(),
7044 "the lock still protects its task"
7045 );
7046 drop(claim);
7047 }
7048
7049 fn injected_dead_pid() -> u32 {
7052 std::process::id().checked_add(1).unwrap_or(1)
7053 }
7054
7055 #[test]
7056 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
7057 let dir = tempfile::tempdir().unwrap();
7058 let queue = Queue::at(dir.path().to_path_buf());
7059 let mut t = task();
7060 t.id = "20260101-000000-dead".to_owned();
7061 queue.put(&mut t).unwrap();
7062 let dead_pid = injected_dead_pid();
7063
7064 std::fs::write(
7069 dir.path().join(format!("{}.lock", t.id)),
7070 dead_pid.to_string(),
7071 )
7072 .unwrap();
7073
7074 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7075 pid != dead_pid
7076 });
7077 assert_eq!(
7078 swept,
7079 vec![t.id.clone()],
7080 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
7081 );
7082 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
7083 }
7084
7085 #[test]
7086 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
7087 let dir = tempfile::tempdir().unwrap();
7088 let queue = Queue::at(dir.path().to_path_buf());
7089 let mut t = task();
7090 t.id = "20260101-000000-late".to_owned();
7091 queue.put(&mut t).unwrap();
7092 let dead_pid = injected_dead_pid();
7093
7094 assert!(
7097 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
7098 "nothing has claimed the task yet"
7099 );
7100
7101 std::fs::write(
7104 dir.path().join(format!("{}.lock", t.id)),
7105 dead_pid.to_string(),
7106 )
7107 .unwrap();
7108
7109 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7113 pid != dead_pid
7114 });
7115 assert_eq!(swept, vec![t.id.clone()]);
7116 }
7117
7118 #[test]
7119 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
7120 crate::run::pin_test_home();
7125 let dir = tempfile::tempdir().unwrap();
7126 let queue = Queue::at(dir.path().to_path_buf());
7127 let mut t = task();
7128 t.id = "20260101-000000-crsh".to_owned();
7129 t.status = TaskStatus::Running;
7130 t.attempts = 1;
7131 t.runs.push("20260904-000000-4043".to_owned());
7135 queue.put(&mut t).unwrap();
7136 let dead_pid = injected_dead_pid();
7137
7138 std::fs::write(
7141 dir.path().join(format!("{}.lock", t.id)),
7142 dead_pid.to_string(),
7143 )
7144 .unwrap();
7145
7146 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
7152 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7153
7154 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7155 pid != dead_pid
7156 });
7157 assert_eq!(swept, vec![t.id.clone()]);
7158
7159 let reclaimed = reclaim_orphaned_running(&queue, 2);
7160 assert_eq!(reclaimed, vec![t.id.clone()]);
7161 let after = queue.get(&t.id).unwrap();
7162 assert_eq!(
7163 after.status,
7164 TaskStatus::Held,
7165 "no run.json to recover from, so a human is asked"
7166 );
7167 assert_eq!(
7168 after.runs,
7169 vec!["20260904-000000-4043".to_owned()],
7170 "the crashed run's id is kept as evidence, not discarded"
7171 );
7172 }
7173
7174 #[test]
7175 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
7176 let dir = tempfile::tempdir().unwrap();
7177 let queue = Queue::at(dir.path().to_path_buf());
7178 let mut t = task();
7179 t.id = "20260101-000000-unknown".to_owned();
7180 queue.put(&mut t).unwrap();
7181 let dead_pid = injected_dead_pid();
7182 std::fs::write(
7183 dir.path().join(format!("{}.lock", t.id)),
7184 dead_pid.to_string(),
7185 )
7186 .unwrap();
7187
7188 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7189 assert!(swept.is_empty(), "an unknown pid must keep its lock");
7190 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7191 }
7192
7193 fn run_state_in(status: RunStatus, language: &str) -> RunState {
7194 let mut s = run_state(status);
7195 s.config.graph.language = language.to_owned();
7196 s
7197 }
7198
7199 fn unstarted_verdict(status: RunStatus) -> Verdict {
7200 Verdict {
7201 status,
7202 left_pr: false,
7203 quota_hit: false,
7204 parked: false,
7205 no_viable_candidates: false,
7206 }
7207 }
7208
7209 #[test]
7210 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7211 let mut t = task();
7212 t.attempts = 1;
7213 settle_in(
7214 &mut t,
7215 unstarted_verdict(RunStatus::AlreadyInBase),
7216 "already in main",
7217 1,
7218 phrases("en"),
7219 );
7220 assert_eq!(t.status, TaskStatus::Done);
7221 assert_eq!(t.attempts, 0);
7222 }
7223
7224 #[test]
7225 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7226 let reason = |language: &str| {
7227 let mut t = task();
7228 settle_in(
7229 &mut t,
7230 unstarted_verdict(RunStatus::Judging),
7231 "boom",
7232 1,
7233 phrases(language),
7234 );
7235 t.last_error.or(t.hold_reason).unwrap_or_default()
7236 };
7237 assert!(
7238 reason("en").starts_with("the graph stopped at `"),
7239 "{}",
7240 reason("en")
7241 );
7242 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7243 assert!(reason("日本語").contains("boom"));
7244 assert_eq!(reason("fr"), reason("en"));
7245 }
7246
7247 #[test]
7248 fn describe_follows_the_run_language_and_keeps_the_run_id() {
7249 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7250 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7251 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7252 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7253 assert!(ja.contains("[run "), "{ja}");
7254 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7255 assert!(ended.starts_with("run 終了: "), "{ended}");
7256 let mut de = run_state_in(RunStatus::Failed, "de");
7257 let mut en = run_state_in(RunStatus::Failed, "en");
7258 de.id = "same".to_owned();
7259 en.id = "same".to_owned();
7260 assert_eq!(describe(&de), describe(&en));
7261 }
7262
7263 #[test]
7264 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7265 use crate::handover::Refused;
7266 let cases = [
7267 Refused::Foreign {
7268 branch: "b".into(),
7269 path: "/w/x".into(),
7270 why: "made by hand".into(),
7271 },
7272 Refused::Unsafe {
7273 branch: "b".into(),
7274 path: "/w/x".into(),
7275 why: "its worktree has uncommitted changes (a.rs)".into(),
7276 },
7277 Refused::ReleaseFailed {
7278 branch: "b".into(),
7279 path: "/w/x".into(),
7280 run: "ab12".into(),
7281 },
7282 ];
7283 for r in &cases {
7284 let en = (phrases("en").handover_refused)(r);
7285 assert_eq!(en, r.to_string());
7286 let ja = (phrases("ja").handover_refused)(r);
7287 assert!(
7288 !ja.contains("is checked out") && !ja.contains("try again"),
7289 "{ja}"
7290 );
7291 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7292 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7293 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7294 }
7295 }
7296 assert!(phrases("en").handover_hint.contains("release the task"));
7297 assert!(phrases("ja").handover_hint.contains("解放"));
7298 }
7299
7300 #[test]
7301 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7302 let build = |lang: &str| {
7303 let mut s = run_state_in(RunStatus::Blocked, lang);
7304 s.id = "same".to_owned();
7305 s.config.graph.review_rounds = 3;
7306 let mut r = review_round(3);
7307 r.expected = 3;
7308 r.answered = 1;
7309 s.reviews.push(r);
7310 s.event(
7311 "review",
7312 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7313 );
7314 s
7315 };
7316 let en = describe(&build("en"));
7317 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7318 let ja = describe(&build("ja"));
7319 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7320 assert!(!ja.contains("never answered"), "{ja}");
7321 assert!(ja.contains("[run "), "{ja}");
7322
7323 let mut failed = build("ja");
7326 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7327 command: "cargo test".to_owned(),
7328 code: Some(1),
7329 output_tail: String::new(),
7330 duration_ms: 0,
7331 resource_blocked: false,
7332 });
7333 failed.event("review", "stopped; e2e failed: cargo test");
7334 let ja = describe(&failed);
7335 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7336 assert!(!ja.contains("席のレビュアー"), "{ja}");
7337 }
7338
7339 #[test]
7340 fn refusals_and_recovery_prose_follow_the_language() {
7341 let t = held_task_with("r1");
7342 let q = action_question(
7343 "r1",
7344 ask::ChoiceAction::Resume {
7345 run: "r1".to_owned(),
7346 },
7347 );
7348 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7349 ActionDecision::Refuse(s) => s,
7350 other => panic!("{other:?}"),
7351 };
7352 assert!(refuse(phrases("en")).contains("could not be read: gone"));
7353 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7354 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7355
7356 let mut held = task();
7357 reclaim(&mut held, None, 2, "ja");
7358 assert!(held.hold_reason.unwrap().contains("保留にしました"));
7359 let mut held = task();
7360 reclaim(&mut held, None, 2, "xx");
7361 assert!(held.hold_reason.unwrap().contains("held for a human"));
7362 }
7363
7364 fn run_state(status: RunStatus) -> RunState {
7365 let mut state = RunState::new(
7366 PathBuf::from("/repo"),
7367 "main".to_owned(),
7368 "abc1234def".to_owned(),
7369 "add retries".to_owned(),
7370 Config::default(),
7371 );
7372 state.status = status;
7373 state
7374 }
7375
7376 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7377 Candidate {
7378 index: 0,
7379 label,
7380 agent: "claude".to_owned(),
7381 branch: format!("magi/x/{label}"),
7382 worktree: PathBuf::from("/repo"),
7383 summary: summary.to_owned(),
7384 stat: String::new(),
7385 files: 0,
7386 commits: usize::from(!empty),
7387 empty,
7388 failed: failed.map(str::to_owned),
7389 verified_noop: None,
7390 duration_ms: 0,
7391 folded: false,
7392 }
7393 }
7394
7395 #[test]
7396 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7397 let mut state = run_state(RunStatus::Blocked);
7398 state.gate = vec![
7399 CommandOutcome {
7400 command: "cargo make check".to_owned(),
7401 code: Some(0),
7402 output_tail: "ok".to_owned(),
7403 duration_ms: 0,
7404 resource_blocked: false,
7405 },
7406 CommandOutcome {
7407 command: "cargo test".to_owned(),
7408 code: Some(101),
7409 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7410 duration_ms: 0,
7411 resource_blocked: false,
7412 },
7413 ];
7414 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7415 assert!(d.contains("cargo test"), "{d}");
7416 assert!(
7417 !d.contains("cargo make check"),
7418 "a passing check is not a diagnostic: {d}"
7419 );
7420 assert!(d.contains("assertion failed"), "{d}");
7421 }
7422
7423 #[test]
7424 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7425 let mut state = run_state(RunStatus::Blocked);
7426 state.event(
7427 "land",
7428 "stopped: the fixer produced no commit while 2 check(s) were failing \
7429 (build, lint); stopping instead of looping on an unchanged tree",
7430 );
7431 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7432 assert!(d.contains("build"), "{d}");
7433 assert!(d.contains("lint"), "{d}");
7434 assert!(d.contains("fixer produced no commit"), "{d}");
7435 }
7436
7437 #[test]
7438 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7439 let state = run_state(RunStatus::VerifiedNoop);
7444 let d = describe(&state);
7445 assert!(
7446 d.contains("agent-verified no-op"),
7447 "expected the display label, not the wire spelling: {d}"
7448 );
7449 assert!(!d.contains("verified_noop"), "{d}");
7450 }
7451
7452 #[test]
7453 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7454 let mut state = run_state(RunStatus::Failed);
7460 state.candidates = vec![candidate(
7461 'A',
7462 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7463 true,
7464 None,
7465 )];
7466 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7467 assert!(d.contains("candidate A"), "{d}");
7468 assert!(d.contains("tagged v1.2.3"), "{d}");
7469 }
7470
7471 #[test]
7472 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7473 let mut state = run_state(RunStatus::Failed);
7474 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7475 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7476 assert!(d.contains("candidate A"), "{d}");
7477 assert!(d.contains("agent timed out"), "{d}");
7478 }
7479
7480 #[test]
7481 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7482 let mut state = run_state(RunStatus::Failed);
7485 state.candidates = vec![candidate('A', "did the work", false, None)];
7486 assert!(diagnostic(&state).is_none());
7487 }
7488
7489 #[test]
7490 fn diagnostic_is_bounded_however_much_a_run_printed() {
7491 let mut state = run_state(RunStatus::Blocked);
7492 state.gate = vec![
7493 CommandOutcome {
7494 command: "cargo test".to_owned(),
7495 code: Some(101),
7496 output_tail: "x".repeat(50_000),
7497 duration_ms: 0,
7498 resource_blocked: false,
7499 },
7500 CommandOutcome {
7501 command: "cargo clippy".to_owned(),
7502 code: Some(1),
7503 output_tail: "y".repeat(50_000),
7504 duration_ms: 0,
7505 resource_blocked: false,
7506 },
7507 ];
7508 state.candidates = vec![
7509 candidate('A', &"z".repeat(50_000), true, None),
7510 candidate('B', &"w".repeat(50_000), true, None),
7511 ];
7512 let d = diagnostic(&state).expect("plenty here to diagnose");
7513 assert!(
7514 d.len() <= DIAGNOSTIC_MAX,
7515 "diagnostic grew to {} bytes, unbounded",
7516 d.len()
7517 );
7518 }
7519
7520 #[test]
7521 fn selected_delivery_guards_survive_recovery_failure_accounting() {
7522 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
7523 let mut t = task();
7524 let mut state = run_state(status);
7525 t.pr_recovery = Some(crate::pr_recovery::Selection {
7526 url: "url".into(),
7527 branch: format!("magi/task-{}", t.id),
7528 head: "a".repeat(40),
7529 source_head: None,
7530 source_run: None,
7531 source_proof: None,
7532 disposition: Some(crate::pr_recovery::Disposition::Land),
7533 instruction: t.instruction.clone(),
7534 approved_at: Timestamp::now(),
7535 });
7536 state.pr_recovery = t.pr_recovery.clone();
7537 t.start(state.id.clone());
7538 settle_and_diagnose(
7539 &mut t,
7540 Verdict {
7541 status,
7542 left_pr: false,
7543 quota_hit: false,
7544 parked: false,
7545 no_viable_candidates: false,
7546 },
7547 "delivery stopped",
7548 5,
7549 &state,
7550 );
7551 assert_eq!(t.status, TaskStatus::Held);
7552 let reason = t.hold_reason.as_deref().unwrap();
7553 if status == RunStatus::Ready {
7554 assert!(reason.contains("Selected PR delivery is incomplete"));
7555 assert!(t.recovery_budget.is_none());
7556 } else {
7557 assert!(reason.contains("Selected recovery stopped"));
7558 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
7559 }
7560 assert!(t.pr_recovery.is_some());
7561 }
7562 }
7563
7564 #[test]
7565 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7566 let mut state = run_state(RunStatus::Blocked);
7567 state.gate = vec![CommandOutcome {
7568 command: "cargo test".to_owned(),
7569 code: Some(101),
7570 output_tail: "assertion failed".to_owned(),
7571 duration_ms: 0,
7572 resource_blocked: false,
7573 }];
7574 let verdict = Verdict {
7575 status: RunStatus::Blocked,
7576 left_pr: false,
7577 quota_hit: false,
7578 parked: false,
7579 no_viable_candidates: false,
7580 };
7581
7582 let mut t = task();
7585 t.start("run-1".to_owned());
7586 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7587 assert_eq!(t.status, TaskStatus::Failed);
7588 assert!(t.diagnostic.is_none());
7589
7590 t.start("run-2".to_owned());
7593 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7594 assert_eq!(t.status, TaskStatus::Held);
7595 let d = t.diagnostic.expect("a held task must carry its diagnostic");
7596 assert!(d.contains("cargo test"), "{d}");
7597 }
7598
7599 #[test]
7600 fn a_held_task_names_the_open_question_it_is_waiting_on() {
7601 crate::run::pin_test_home();
7606 let home = crate::run::home();
7607 let state = run_state(RunStatus::VerifiedNoop);
7608 let mut q = ask::Question::new(
7609 state.id.clone(),
7610 "implement".to_owned(),
7611 "impl-A".to_owned(),
7612 "is this really a no-op?".to_owned(),
7613 String::new(),
7614 Vec::new(),
7615 );
7616 Questions::at(home.join("questions")).put(&mut q).unwrap();
7617
7618 let verdict = Verdict {
7619 status: RunStatus::VerifiedNoop,
7620 left_pr: false,
7621 quota_hit: false,
7622 parked: false,
7623 no_viable_candidates: false,
7624 };
7625 let mut t = task();
7626 t.start(state.id.clone());
7627 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7628
7629 assert_eq!(t.status, TaskStatus::Held);
7630 let reason = t.hold_reason.expect("a held task must record why");
7631 assert!(
7632 reason.starts_with("run ended agent-verified no-op"),
7633 "the original settle reason must survive unchanged: {reason}"
7634 );
7635 assert!(
7636 reason.contains(q.short()),
7637 "the open question's id must be named so the notice is actionable: {reason}"
7638 );
7639 }
7640
7641 #[test]
7642 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7643 crate::run::pin_test_home();
7644 let state = run_state(RunStatus::VerifiedNoop);
7645
7646 let verdict = Verdict {
7647 status: RunStatus::VerifiedNoop,
7648 left_pr: false,
7649 quota_hit: false,
7650 parked: false,
7651 no_viable_candidates: false,
7652 };
7653 let mut t = task();
7654 t.start(state.id.clone());
7655 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7656
7657 assert_eq!(t.status, TaskStatus::Held);
7658 assert_eq!(
7659 t.hold_reason.as_deref(),
7660 Some("run ended agent-verified no-op"),
7661 "nothing to append when the question was already answered or never asked"
7662 );
7663 }
7664
7665 #[test]
7666 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7667 crate::run::pin_test_home();
7668 let mut first = run_state(RunStatus::Blocked);
7669 first.id = "20260101-000000-sup1".to_owned();
7670 first.save().unwrap();
7671 let mut second = run_state(RunStatus::Merged);
7672 second.id = "20260101-000000-sup2".to_owned();
7673 second.save().unwrap();
7674
7675 let mut t = task();
7676 t.runs = vec![first.id.clone(), second.id.clone()];
7677 t.status = TaskStatus::Done;
7678
7679 supersede_prior_runs(&t, &crate::run::home());
7680
7681 assert_eq!(
7682 RunState::load(&first.id).unwrap().status,
7683 RunStatus::Superseded,
7684 "the first attempt's Blocked no longer needs anyone's attention"
7685 );
7686 assert_eq!(
7687 RunState::load(&second.id).unwrap().status,
7688 RunStatus::Merged,
7689 "the run that actually succeeded is left exactly as it was"
7690 );
7691 }
7692
7693 #[test]
7694 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7695 crate::run::pin_test_home();
7701 let mut first = run_state(RunStatus::Blocked);
7702 first.id = "20260101-000000-sup9".to_owned();
7703 first.driver_pid = Some(std::process::id());
7706 first.driver_started_at = Some(
7707 crate::proc::process_started_at(std::process::id())
7708 .expect("this test process's own start time must be queryable"),
7709 );
7710 first.save().unwrap();
7711 let mut second = run_state(RunStatus::Merged);
7712 second.id = "20260101-000000-supa".to_owned();
7713 second.save().unwrap();
7714
7715 let mut t = task();
7716 t.runs = vec![first.id.clone(), second.id.clone()];
7717 t.status = TaskStatus::Done;
7718
7719 supersede_prior_runs(&t, &crate::run::home());
7720
7721 assert_eq!(
7722 RunState::load(&first.id).unwrap().status,
7723 RunStatus::Blocked,
7724 "a live driver_pid means something is still actually working this run, \
7725 even though no daemon claims it - rewriting under it would just be \
7726 undone the next time that process saves"
7727 );
7728 }
7729
7730 #[test]
7731 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7732 let dir = tempfile::tempdir().unwrap();
7738 let home = dir.path().to_path_buf();
7739 let queue = Queue::at(dir.path().join("queue"));
7740
7741 let mut first = run_state(RunStatus::Blocked);
7742 first.id = "20260101-000000-supd".to_owned();
7743 first.driver_pid = Some(std::process::id());
7744 first.driver_started_at = Some(
7745 crate::proc::process_started_at(std::process::id())
7746 .expect("this test process's own start time must be queryable"),
7747 );
7748 first.save_under(&home).unwrap();
7749 let mut second = run_state(RunStatus::Merged);
7750 second.id = "20260101-000000-supe".to_owned();
7751 second.save_under(&home).unwrap();
7752
7753 let mut t = task();
7754 t.runs = vec![first.id.clone(), second.id.clone()];
7755 t.status = TaskStatus::Done;
7756 queue.put(&mut t).unwrap();
7757
7758 resweep_superseded_attempts(&queue, &home);
7759 assert_eq!(
7760 RunState::load_under(&first.id, &home).unwrap().status,
7761 RunStatus::Blocked,
7762 "still live on the first pass, so still untouched"
7763 );
7764
7765 let mut stale = RunState::load_under(&first.id, &home).unwrap();
7771 stale.driver_started_at = Some("1".to_owned());
7772 stale.save_under(&home).unwrap();
7773
7774 resweep_superseded_attempts(&queue, &home);
7775 assert_eq!(
7776 RunState::load_under(&first.id, &home).unwrap().status,
7777 RunStatus::Superseded,
7778 "the second pass catches up what the first one correctly skipped"
7779 );
7780 }
7781
7782 #[test]
7783 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7784 crate::run::pin_test_home();
7785 let mut first = run_state(RunStatus::Blocked);
7786 first.id = "20260101-000000-sup3".to_owned();
7787 first.save().unwrap();
7788 let mut second = run_state(RunStatus::Blocked);
7789 second.id = "20260101-000000-sup4".to_owned();
7790 second.save().unwrap();
7791
7792 let mut t = task();
7793 t.runs = vec![first.id.clone(), second.id.clone()];
7794 t.status = TaskStatus::Failed;
7798
7799 supersede_prior_runs(&t, &crate::run::home());
7800
7801 assert_eq!(
7802 RunState::load(&first.id).unwrap().status,
7803 RunStatus::Blocked
7804 );
7805 assert_eq!(
7806 RunState::load(&second.id).unwrap().status,
7807 RunStatus::Blocked
7808 );
7809 }
7810
7811 #[test]
7812 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7813 crate::run::pin_test_home();
7817 let mut first = run_state(RunStatus::Blocked);
7818 first.id = "20260101-000000-sup5".to_owned();
7819 first.save().unwrap();
7820
7821 let mut t = task();
7822 t.runs = vec![first.id.clone()];
7823 t.status = TaskStatus::Done;
7824
7825 supersede_prior_runs(&t, &crate::run::home());
7826
7827 assert_eq!(
7828 RunState::load(&first.id).unwrap().status,
7829 RunStatus::Blocked,
7830 "a single-attempt task has no earlier run to supersede"
7831 );
7832 }
7833
7834 #[test]
7835 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7836 crate::run::pin_test_home();
7843 let mut first = run_state(RunStatus::Blocked);
7844 first.id = "20260101-000000-supb".to_owned();
7845 first.save().unwrap();
7846 let mut second = run_state(RunStatus::Failed);
7847 second.id = "20260101-000000-supc".to_owned();
7848 second.save().unwrap();
7849
7850 let mut t = task();
7851 t.runs = vec![first.id.clone(), second.id.clone()];
7852 t.status = TaskStatus::Done;
7853
7854 supersede_prior_runs(&t, &crate::run::home());
7855
7856 assert_eq!(
7857 RunState::load(&first.id).unwrap().status,
7858 RunStatus::Blocked,
7859 "the task's last attempt never landed, so there is nothing here \
7860 actually superseding it"
7861 );
7862 }
7863
7864 #[test]
7865 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7866 crate::run::pin_test_home();
7870 let mut failed = run_state(RunStatus::Failed);
7871 failed.id = "20260101-000000-sup6".to_owned();
7872 failed.save().unwrap();
7873 let mut noop = run_state(RunStatus::VerifiedNoop);
7874 noop.id = "20260101-000000-sup7".to_owned();
7875 noop.save().unwrap();
7876 let mut winner = run_state(RunStatus::Ready);
7877 winner.id = "20260101-000000-sup8".to_owned();
7878 winner.save().unwrap();
7879
7880 let mut t = task();
7881 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7882 t.status = TaskStatus::Done;
7883
7884 supersede_prior_runs(&t, &crate::run::home());
7885
7886 assert_eq!(
7887 RunState::load(&failed.id).unwrap().status,
7888 RunStatus::Failed
7889 );
7890 assert_eq!(
7891 RunState::load(&noop.id).unwrap().status,
7892 RunStatus::VerifiedNoop
7893 );
7894 }
7895
7896 fn approval_question(run: &str) -> ask::Question {
7897 ask::Question::new(
7898 run.to_owned(),
7899 land::APPROVAL_NODE.to_owned(),
7900 "land".to_owned(),
7901 "merge?".to_owned(),
7902 String::new(),
7903 vec!["merge".to_owned(), "hold".to_owned()],
7904 )
7905 }
7906
7907 #[test]
7908 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7909 crate::run::pin_test_home();
7910 let mut state = run_state(RunStatus::Landing);
7911 state.id = "20260101-000000-fre1".to_owned();
7912 state.parked = true;
7913 state.save().unwrap();
7914 ask::Questions::open()
7915 .put(&mut approval_question(&state.id))
7916 .unwrap();
7917
7918 let mut t = task();
7919 t.runs.push(state.id.clone());
7920 assert_eq!(
7921 land_resume_state(&t),
7922 LandResume::StillWaiting,
7923 "nobody has answered and the timeout has not passed"
7924 );
7925 }
7926
7927 #[test]
7928 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7929 crate::run::pin_test_home();
7930 let mut state = run_state(RunStatus::Gating);
7931 state.id = "20260101-000000-gt01".to_owned();
7932 state.parked = true;
7933 state.config.graph.answer_timeout = 60;
7934 state.github_text = Some(crate::run::GithubTextAsk {
7935 rewrite: None,
7936 fingerprint: "f".into(),
7937 title: true,
7938 body: false,
7939 categories: vec!["title-language".into()],
7940 question: None,
7941 asks: 1,
7942 resolved: false,
7943 chosen_title: None,
7944 choice: None,
7945 });
7946 state.save().unwrap();
7947 let store = ask::Questions::open();
7948 let mut q = ask::Question::new(
7949 state.id.clone(),
7950 crate::github_text::ASK_NODE.to_owned(),
7951 crate::github_text::ASK_SEAT.to_owned(),
7952 "s".into(),
7953 String::new(),
7954 vec!["use fallback".into()],
7955 );
7956 store.put(&mut q).unwrap();
7957 let mut t = task();
7958 t.runs.push(state.id.clone());
7959 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7960 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7961 store.put(&mut q).unwrap();
7962 assert_eq!(land_resume_state(&t), LandResume::Ready);
7963 assert!(!store.get(&q.id).unwrap().status.open());
7964 state.github_text.as_mut().unwrap().resolved = true;
7966 state.save().unwrap();
7967 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7968 }
7969
7970 #[test]
7971 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7972 crate::run::pin_test_home();
7977 let mut state = run_state(RunStatus::Landing);
7978 state.id = "20260101-000000-exp1".to_owned();
7979 state.parked = true;
7980 state.config.graph.answer_timeout = 60;
7981 state.save().unwrap();
7982
7983 let store = ask::Questions::open();
7984 let mut q = approval_question(&state.id);
7985 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7986 store.put(&mut q).unwrap();
7987
7988 let mut t = task();
7989 t.runs.push(state.id.clone());
7990 assert_eq!(
7991 land_resume_state(&t),
7992 LandResume::Ready,
7993 "an expired question must not be waited on forever"
7994 );
7995
7996 let after = store.get(&q.id).unwrap();
7997 assert!(
7998 !after.status.open(),
7999 "the question is abandoned, not silently ignored"
8000 );
8001 assert!(
8002 after.resolution().is_none(),
8003 "an abandoned question is not read as a decision"
8004 );
8005 }
8006
8007 #[test]
8008 fn reclaim_settles_a_running_task_against_its_last_run() {
8009 let mut t = task();
8010 t.start("20260904-000000-4043".to_owned());
8011 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8012 assert_eq!(
8013 t.status,
8014 TaskStatus::Done,
8015 "a run that actually finished must not stay `running` forever"
8016 );
8017 }
8018
8019 #[test]
8020 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8021 let mut t = task();
8022 t.start("20260904-000000-4043".to_owned());
8023 t.last_error = Some("earlier trouble".to_owned());
8024 let mut state = run_state(RunStatus::Judging);
8025 state.parked = true;
8026 reclaim(&mut t, Some(state), 1, "en");
8027 assert_eq!(t.status, TaskStatus::Parked);
8028 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8029 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8030 assert!(t.park_reason.is_some());
8031 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8032 assert!(!t.fresh_start);
8033 assert!(t.status.runnable());
8034 }
8035
8036 #[test]
8037 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
8038 let mut t = task();
8039 t.start("20260904-000000-4043".to_owned());
8040 t.last_error = Some("earlier trouble".to_owned());
8041 settle(
8042 &mut t,
8043 Verdict {
8044 status: RunStatus::Judging,
8045 left_pr: false,
8046 quota_hit: false,
8047 parked: true,
8048 no_viable_candidates: false,
8049 },
8050 "parked after `judging`",
8051 1,
8052 );
8053 assert_eq!(t.status, TaskStatus::Parked);
8054 assert_eq!(t.attempts, 0);
8055 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8056 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
8057 assert_eq!(t.schema, crate::queue::SCHEMA);
8058 assert!(
8059 crate::notices::task_held(&t).is_none(),
8060 "a park is not news"
8061 );
8062 t.start("20260904-000000-4043".to_owned());
8063 assert_eq!(t.park_reason, None);
8064 }
8065
8066 #[test]
8067 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
8068 let mut t = task();
8072 t.start("20260904-000000-4043".to_owned());
8073 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
8074 assert_eq!(t.status, TaskStatus::Failed);
8075 assert!(t.status.runnable());
8076 }
8077
8078 #[test]
8079 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
8080 let mut t = task();
8081 t.start("20260904-000000-4043".to_owned());
8082 assert_eq!(t.attempts, 1);
8083 let mut run = run_state(RunStatus::Implementing);
8084 run.id = "20260904-000000-4043".to_owned();
8085 run.begin_pass();
8086 let cause = crate::run::ParkCause::Upgrade {
8087 from: "0.121.0".to_owned(),
8088 to: Some("0.121.1".to_owned()),
8089 };
8090 run.end_pass_parked(cause.clone());
8091 run.parked = true;
8092 let verdict = Verdict {
8093 status: run.status,
8094 left_pr: false,
8095 quota_hit: false,
8096 parked: true,
8097 no_viable_candidates: false,
8098 };
8099 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
8100 assert_eq!(t.attempts, 0);
8101 assert_eq!(t.passes.len(), 1);
8102 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8103 assert_eq!(t.passes[0].parked, Some(cause));
8104 assert_eq!(t.passes[0].pass_index, 0);
8105
8106 t.start("20260904-000000-4043".to_owned());
8109 run.begin_pass();
8110 run.status = RunStatus::Failed;
8111 let verdict = Verdict {
8112 status: RunStatus::Failed,
8113 left_pr: false,
8114 quota_hit: false,
8115 parked: false,
8116 no_viable_candidates: false,
8117 };
8118 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
8119 assert_eq!(t.passes.len(), 2);
8120 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8121 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
8122 assert_eq!(t.passes[1].pass_index, 1);
8123 assert_eq!(t.attempts, 1);
8124 }
8125
8126 #[test]
8127 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
8128 let mut t = task();
8129 t.start("20260904-000000-4043".to_owned());
8130 reclaim(&mut t, None, 2, "en");
8131 assert_eq!(t.status, TaskStatus::Held);
8132 assert!(
8133 t.last_error
8134 .as_deref()
8135 .is_some_and(|e| e.contains("running")),
8136 "the operator needs to know why this task was held"
8137 );
8138 }
8139
8140 #[test]
8141 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
8142 let dir = tempfile::tempdir().unwrap();
8143 let queue = Queue::at(dir.path().to_path_buf());
8144
8145 let mut orphaned = task();
8147 orphaned.id = "20260904-000000-orph".to_owned();
8148 orphaned.status = TaskStatus::Running;
8149 orphaned.attempts = 1;
8150 queue.put(&mut orphaned).unwrap();
8151
8152 let mut alive = task();
8153 alive.id = "20260904-000000-live".to_owned();
8154 alive.status = TaskStatus::Running;
8155 alive.attempts = 1;
8156 queue.put(&mut alive).unwrap();
8157 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
8158
8159 let mut queued = task();
8160 queued.id = "20260904-000000-wait".to_owned();
8161 queue.put(&mut queued).unwrap();
8162
8163 let reclaimed = reclaim_orphaned_running(&queue, 2);
8164 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
8165
8166 assert_eq!(
8167 queue.get(&orphaned.id).unwrap().status,
8168 TaskStatus::Held,
8169 "nothing was driving it and there was no run to recover"
8170 );
8171 assert_eq!(
8172 queue.get(&alive.id).unwrap().status,
8173 TaskStatus::Running,
8174 "a live claim must protect the task it belongs to"
8175 );
8176 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
8177 }
8178
8179 fn read_run_under(home: &Path, id: &str) -> RunState {
8185 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
8186 serde_json::from_str(&body).unwrap()
8187 }
8188
8189 #[test]
8190 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
8191 let dir = tempfile::tempdir().unwrap();
8192 let home = dir.path().to_path_buf();
8193 let now = Timestamp::now();
8194 let overrun_seat = || crate::run::ActiveSeat {
8195 node: "implement".to_owned(),
8196 started_at: now - jiff::SignedDuration::new(21_000, 0),
8197 timeout_secs: 3_600,
8198 attempt: 0,
8199 task: None,
8200 command: None,
8201 index: None,
8202 total: None,
8203 };
8204
8205 let mut dead = run_state(RunStatus::Implementing);
8206 dead.id = "20260101-000000-dead".to_owned();
8207 dead.active.insert("impl-A".to_owned(), overrun_seat());
8208 dead.driver_pid = Some(4242);
8211 dead.save_under(&home).unwrap();
8212
8213 let mut alive = run_state(RunStatus::Implementing);
8216 alive.id = "20260101-000000-aliv".to_owned();
8217 alive.active.insert("impl-A".to_owned(), overrun_seat());
8218 alive.save_under(&home).unwrap();
8219 let mut status = Status::new();
8220 status.current = vec![Current {
8221 task: "20260101-000000-task".to_owned(),
8222 run: alive.id.clone(),
8223 }];
8224 write_status_to(&home.join("daemon.json"), &status).unwrap();
8225
8226 let questions = Questions::at(home.join("questions"));
8230 let mut q = ask::Question::new(
8231 dead.id.clone(),
8232 "implement".to_owned(),
8233 "impl-A".to_owned(),
8234 "Which storage backend?".to_owned(),
8235 String::new(),
8236 vec!["SQLite".to_owned(), "Redis".to_owned()],
8237 );
8238 questions.put(&mut q).unwrap();
8239
8240 let abandoned = reclaim_abandoned_runs_with(
8241 &home,
8242 now,
8243 |pid| if pid == 4242 { Some(false) } else { None },
8244 |_| panic!("a query answering Dead outright needs no identity corroboration"),
8245 );
8246 assert_eq!(abandoned, vec![dead.id.clone()]);
8247
8248 let reloaded = read_run_under(&home, &dead.id);
8249 assert_eq!(reloaded.status, RunStatus::Failed);
8250 assert!(reloaded.active.is_empty());
8251 assert!(
8252 !questions.get(&q.id).unwrap().status.open(),
8253 "the failed run's own open question must be settled in the same pass"
8254 );
8255
8256 let still_alive = read_run_under(&home, &alive.id);
8257 assert_eq!(
8258 still_alive.status,
8259 RunStatus::Implementing,
8260 "a live daemon's claim protects it"
8261 );
8262 assert!(!still_alive.active.is_empty());
8263 }
8264
8265 #[test]
8275 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8276 let dir = tempfile::tempdir().unwrap();
8277 let home = dir.path().to_path_buf();
8278 let now = Timestamp::now();
8279
8280 let mut manual = run_state(RunStatus::Reviewing);
8281 manual.id = "20260101-000000-manl".to_owned();
8282 manual.active.insert(
8283 "review-1".to_owned(),
8284 crate::run::ActiveSeat {
8285 node: "review".to_owned(),
8286 started_at: now - jiff::SignedDuration::new(21_000, 0),
8287 timeout_secs: 3_600,
8288 attempt: 0,
8289 task: None,
8290 command: None,
8291 index: None,
8292 total: None,
8293 },
8294 );
8295 manual.driver_pid = Some(4242);
8299 manual.driver_started_at = Some("1790000000".to_owned());
8300 manual.save_under(&home).unwrap();
8301
8302 let abandoned = reclaim_abandoned_runs_with(
8303 &home,
8304 now,
8305 |pid| if pid == 4242 { Some(true) } else { None },
8306 |pid| {
8307 if pid == 4242 {
8308 Some("1790000000".to_owned())
8309 } else {
8310 None
8311 }
8312 },
8313 );
8314 assert!(
8315 abandoned.is_empty(),
8316 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8317 );
8318
8319 let reloaded = read_run_under(&home, &manual.id);
8320 assert_eq!(reloaded.status, RunStatus::Reviewing);
8321 assert!(!reloaded.active.is_empty());
8322 }
8323
8324 #[test]
8325 fn an_already_claimed_task_is_skipped_rather_than_failed() {
8326 let dir = tempfile::tempdir().unwrap();
8327 let queue = Queue::at(dir.path().to_path_buf());
8328 let mut only = task();
8329 queue.put(&mut only).unwrap();
8330
8331 let _elsewhere = queue.claim(&only.id).unwrap();
8332 let candidates = runnable(&queue);
8333 assert_eq!(candidates.len(), 1, "the task is still runnable");
8334 assert!(
8335 queue.claim(&candidates[0].id).is_err(),
8336 "the loop cannot take a claim somebody else holds"
8337 );
8338
8339 let after = queue.get(&only.id).unwrap();
8340 assert_eq!(after.status, TaskStatus::Queued);
8341 assert_eq!(
8342 after.attempts, 0,
8343 "losing the race is not an attempt at the task"
8344 );
8345 assert_eq!(after.last_error, None);
8346 }
8347
8348 #[test]
8349 fn the_status_file_round_trips_and_its_heartbeat_advances() {
8350 let dir = tempfile::tempdir().unwrap();
8351 let path = dir.path().join("daemon.json");
8352
8353 let mut status = Status::new();
8354 status.idle = false;
8355 status.completed = 7;
8356 status.current = vec![Current {
8357 task: "20260902-000000-t111".to_owned(),
8358 run: "20260902-000001-r111".to_owned(),
8359 }];
8360 write_status_to(&path, &status).unwrap();
8361 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8362 assert_eq!(first.schema, SCHEMA);
8363 assert_eq!(first.pid, std::process::id());
8364 assert!(!first.idle);
8365 assert_eq!(first.completed, 7);
8366 assert_eq!(first.current, status.current);
8367 assert!(
8368 !path.with_extension("json.tmp").exists(),
8369 "the temp file is renamed, not left behind"
8370 );
8371
8372 std::thread::sleep(Duration::from_millis(5));
8373 status.updated_at = Timestamp::now();
8374 status.polls = 3;
8375 write_status_to(&path, &status).unwrap();
8376 let second: Status =
8377 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8378 assert!(
8379 second.updated_at > first.updated_at,
8380 "a reader can only detect staleness if the heartbeat moves"
8381 );
8382 assert_eq!(
8383 second.started_at, first.started_at,
8384 "the start time is not a heartbeat"
8385 );
8386 assert_eq!(second.polls, 3);
8387 }
8388
8389 #[test]
8390 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8391 let dir = tempfile::tempdir().unwrap();
8392
8393 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8394
8395 let mut status = Status::new();
8396 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8397 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8398 let stale = read_status(dir.path()).unwrap();
8399 assert!(
8400 !stale.running(Timestamp::now()),
8401 "a minute without a heartbeat is a dead daemon, not a busy one"
8402 );
8403 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8404
8405 status.updated_at = Timestamp::now();
8406 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8407 let fresh = read_status(dir.path()).unwrap();
8408 assert!(fresh.running(Timestamp::now()));
8409 }
8410
8411 #[test]
8412 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8413 let dir = tempfile::tempdir().unwrap();
8414 let now = Timestamp::now();
8415 let mine = "20260903-080619-01c2";
8416
8417 assert!(
8418 !is_working_on(dir.path(), mine, now),
8419 "no status file means nobody is working on anything"
8420 );
8421
8422 let mut status = Status::new();
8423 status.current = vec![Current {
8424 task: "20260903-080340-0167".to_owned(),
8425 run: mine.to_owned(),
8426 }];
8427 status.updated_at = now;
8428 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8429 assert!(is_working_on(dir.path(), mine, now));
8430 assert!(
8431 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8432 "a daemon busy with one run is not working on another"
8433 );
8434
8435 status.updated_at = now - jiff::SignedDuration::from_secs(600);
8438 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8439 assert!(
8440 !is_working_on(dir.path(), mine, now),
8441 "a stale heartbeat is a dead daemon, so its run is a leftover"
8442 );
8443 }
8444
8445 #[test]
8446 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8447 let dir = tempfile::tempdir().unwrap();
8448 let now = Timestamp::now();
8449
8450 assert!(
8451 !is_working_on_short(dir.path(), "01c2", now),
8452 "no status file means nobody is working on anything"
8453 );
8454
8455 let mut status = Status::new();
8456 status.current = vec![Current {
8457 task: "20260903-080340-0167".to_owned(),
8458 run: "20260903-080619-01c2".to_owned(),
8459 }];
8460 status.updated_at = now;
8461 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8462 assert!(
8463 is_working_on_short(dir.path(), "01c2", now),
8464 "the run's short id is the last block of its full id"
8465 );
8466 assert!(
8467 !is_working_on_short(dir.path(), "3cbf", now),
8468 "a daemon busy with one worktree bay is not working on another"
8469 );
8470 }
8471
8472 #[test]
8473 fn a_newer_status_file_still_yields_a_reading() {
8474 let dir = tempfile::tempdir().unwrap();
8475 std::fs::write(
8478 dir.path().join("daemon.json"),
8479 serde_json::json!({
8480 "schema": 2,
8481 "updated_at": Timestamp::now().to_string(),
8482 "idle": true,
8483 "surprise": { "nested": [1, 2, 3] },
8484 })
8485 .to_string(),
8486 )
8487 .unwrap();
8488
8489 let reading = read_status(dir.path()).expect("a forward-compatible read");
8490 assert!(reading.running(Timestamp::now()));
8491 assert!(reading.idle);
8492 assert!(reading.current.is_empty());
8493 }
8494
8495 #[test]
8496 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8497 let dir = tempfile::tempdir().unwrap();
8503 std::fs::write(
8504 dir.path().join("daemon.json"),
8505 serde_json::json!({
8506 "schema": 1,
8507 "pid": 4242,
8508 "updated_at": Timestamp::now().to_string(),
8509 "idle": false,
8510 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8511 "completed": 3,
8512 "polls": 9,
8513 })
8514 .to_string(),
8515 )
8516 .unwrap();
8517
8518 let reading = read_status(dir.path()).expect("an older shape must still parse");
8519 assert!(reading.running(Timestamp::now()));
8520 assert_eq!(
8521 reading.current,
8522 vec![Current {
8523 task: "20260902-140501-aaaa".to_owned(),
8524 run: "20260902-140502-bbbb".to_owned(),
8525 }]
8526 );
8527 }
8528
8529 #[test]
8530 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8531 let dir = tempfile::tempdir().unwrap();
8532 std::fs::write(
8533 dir.path().join("daemon.json"),
8534 serde_json::json!({
8535 "schema": 1,
8536 "updated_at": Timestamp::now().to_string(),
8537 "idle": true,
8538 "current": null,
8539 })
8540 .to_string(),
8541 )
8542 .unwrap();
8543 let with_null = read_status(dir.path()).expect("null must still parse");
8544 assert!(with_null.current.is_empty());
8545
8546 std::fs::write(
8547 dir.path().join("daemon.json"),
8548 serde_json::json!({
8549 "schema": 1,
8550 "updated_at": Timestamp::now().to_string(),
8551 "idle": true,
8552 })
8553 .to_string(),
8554 )
8555 .unwrap();
8556 let absent = read_status(dir.path()).expect("a missing field must still parse");
8557 assert!(absent.current.is_empty());
8558 }
8559
8560 #[test]
8561 fn a_task_without_a_repository_runs_in_the_daemons_default() {
8562 let fallback = Path::new("/default");
8563 let mut blank = task();
8564 blank.repo = PathBuf::new();
8565 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8566 let mut dot = task();
8567 dot.repo = PathBuf::from(".");
8568 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8569 assert_eq!(
8570 repo_for(&task(), fallback),
8571 PathBuf::from("/repo"),
8572 "a task that names a repository keeps it"
8573 );
8574 }
8575
8576 #[test]
8577 fn task_implementers_edit_inherits_daemon_config_and_merge() {
8578 let dir = tempfile::tempdir().unwrap();
8579 let path = dir.path().join("explicit.toml");
8580 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8581 let opts = Opts {
8582 config: Some(path),
8583 merge: Some("none".into()),
8584 ..Default::default()
8585 };
8586 let mut t = task();
8587 t.set_implementers(
8588 2,
8589 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8590 .unwrap(),
8591 )
8592 .unwrap();
8593 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8594 assert_eq!(cfg.graph.implementers, 2);
8595 assert_eq!(cfg.graph.judges, 1);
8596 assert_eq!(cfg.merge.mode, MergeMode::None);
8597 t.set_implementers(1, &cfg).unwrap();
8598 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8599 apply_task_implementers(&mut cfg, &t);
8600 assert_eq!(cfg.graph.implementers, 1);
8601 assert_eq!(cfg.graph.judges, 1);
8602 assert_eq!(cfg.merge.mode, MergeMode::None);
8603 }
8604
8605 #[test]
8606 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8607 let dir = tempfile::tempdir().unwrap();
8608 let repo = dir.path().join("repo");
8609 std::fs::create_dir(&repo).unwrap();
8610 std::fs::write(
8611 repo.join("magi.toml"),
8612 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8613 )
8614 .unwrap();
8615 let daemon_config = dir.path().join("daemon.toml");
8616 std::fs::write(
8617 &daemon_config,
8618 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8619 )
8620 .unwrap();
8621 let opts = Opts {
8622 config: Some(daemon_config),
8623 merge: Some("pr".into()),
8624 ..Default::default()
8625 };
8626 let q = Queue::at(dir.path().join("queue"));
8627 let validation: Config =
8628 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8629 .unwrap();
8630 for record in ["{}", r#"{"candidates":2}"#] {
8632 let overrides = serde_json::from_str(record).unwrap();
8633 let filing = crate::direct::Filing {
8634 instruction: "work".into(),
8635 title: "direct".into(),
8636 repo: repo.clone(),
8637 source: crate::queue::Source::Human,
8638 solo: false,
8639 overrides,
8640 review_of: None,
8641 };
8642 let filed =
8643 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8644 let crate::direct::Filed::Standalone {
8645 mut task,
8646 claim: _claim,
8647 } = filed
8648 else {
8649 panic!("local filing")
8650 };
8651 let before = prepare_for(&repo, &opts, &task).unwrap();
8652 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8653 assert_eq!(
8654 before.merge.mode,
8655 MergeMode::None,
8656 "daemon --merge must not leak"
8657 );
8658 for n in [2, 1, 2] {
8659 task.set_implementers(n, &validation).unwrap();
8660 q.put(&mut task).unwrap();
8661 task = q.get(&task.id).unwrap();
8662 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8663 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8664 apply_task_implementers(&mut cfg, &task);
8665 assert_eq!(cfg.graph.implementers, usize::from(n));
8666 assert_eq!(cfg.graph.judges, 2);
8667 assert_eq!(cfg.merge.mode, MergeMode::None);
8668 }
8669 }
8670 }
8671
8672 #[test]
8673 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8674 let cfg: Config =
8675 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8676 .unwrap();
8677 let mut t = task();
8678 t.review_of = Some("review-target".into());
8679 t.hold_manual(Some("retry".into()));
8680 let mut previous = RunState::new(
8681 PathBuf::from("/repo"),
8682 "main".into(),
8683 "abc1234".into(),
8684 "review".into(),
8685 cfg.clone(),
8686 );
8687 previous.config.graph.implementers = 2;
8688 for count in [1, 3] {
8689 t.set_implementers(count, &cfg).unwrap();
8690 t.release();
8691 assert_eq!(t.review_of.as_deref(), Some("review-target"));
8692 for proposed in [
8693 Starter::Resume(previous.id.clone()),
8694 Starter::Review("recovery-target".into()),
8695 ] {
8696 assert_eq!(
8697 starter_with_implementers(&t, Some(&previous), proposed),
8698 Starter::Review("review-target".into())
8699 );
8700 }
8701 let mut configured = cfg.clone();
8702 apply_task_implementers(&mut configured, &t);
8703 assert_eq!(configured.graph.implementers, usize::from(count));
8704 assert_eq!(previous.config.graph.implementers, 2);
8705 }
8706 }
8707
8708 #[test]
8709 fn task_implementers_dispatch_and_resume_agree() {
8710 let mut t = task();
8711 let cfg: crate::config::Config =
8712 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8713 .unwrap();
8714 let mut run = RunState::new(
8715 PathBuf::from("/repo"),
8716 "main".into(),
8717 "abc1234".into(),
8718 "work".into(),
8719 cfg.clone(),
8720 );
8721 run.config.graph.implementers = 2;
8722 for n in [2, 1, 3, 2] {
8723 t.set_implementers(n, &cfg).unwrap();
8724 let mut dispatched = cfg.clone();
8725 apply_task_implementers(&mut dispatched, &t);
8726 assert_eq!(dispatched.graph.implementers, usize::from(n));
8727 assert_eq!(implementers_match(&t, &run), n == 2);
8728 for proposed in [
8729 Starter::Resume(run.id.clone()),
8730 Starter::Review("old-branch".into()),
8731 ] {
8732 let expected = if n == 2 {
8733 proposed.clone()
8734 } else {
8735 Starter::Start
8736 };
8737 assert_eq!(
8738 starter_with_implementers(&t, Some(&run), proposed),
8739 expected
8740 );
8741 }
8742 assert_eq!(
8743 run.config.graph.implementers, 2,
8744 "history must not be rewritten"
8745 );
8746 }
8747 t.solo = false;
8748 t.overrides = None;
8749 assert!(implementers_match(&t, &run));
8750 }
8751
8752 #[test]
8753 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8754 let mut solo_cfg = Config::default();
8760 solo_cfg.graph.implementers = 3;
8761 let mut solo_task = task();
8762 solo_task.solo = true;
8763 apply_task_implementers(&mut solo_cfg, &solo_task);
8764 assert_eq!(solo_cfg.graph.implementers, 1);
8765
8766 let mut plain_cfg = Config::default();
8767 plain_cfg.graph.implementers = 3;
8768 let plain_task = task();
8769 assert!(!plain_task.solo);
8770 apply_task_implementers(&mut plain_cfg, &plain_task);
8771 assert_eq!(
8772 plain_cfg.graph.implementers, 3,
8773 "a task that did not ask to run alone keeps the config's candidates"
8774 );
8775 }
8776
8777 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8778 QuotaLoss {
8779 seat: seat.into(),
8780 node: "judge".into(),
8781 at: at.parse().unwrap(),
8782 reset: reset.map(str::to_string),
8783 }
8784 }
8785
8786 #[test]
8787 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8788 let old: Vec<QuotaLoss> = (1..=4)
8789 .map(|i| {
8790 loss(
8791 &format!("judge-{i}"),
8792 "2026-09-23T05:23:00Z",
8793 Some("2:40pm (Asia/Tokyo)"),
8794 )
8795 })
8796 .collect();
8797 let fresh = losses_this_attempt(&old, &old);
8798 assert!(fresh.is_empty());
8799 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8800 }
8802
8803 #[test]
8804 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8805 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8806 let now = Timestamp::now();
8807 let mut after = old.clone();
8808 after.push(loss("judge-2", &now.to_string(), None));
8809 let fresh = losses_this_attempt(&old, &after);
8810 assert_eq!(fresh, vec![after[1].clone()]);
8811 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8812 assert_eq!(
8813 until,
8814 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8815 );
8816 }
8817
8818 #[test]
8819 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8820 let before = vec![
8823 loss("judge-1", "2026-09-23T05:23:00Z", None),
8824 loss("judge-2", "2026-09-23T05:24:00Z", None),
8825 ];
8826 let after = vec![
8827 loss("judge-2", "2026-09-23T05:24:00Z", None),
8828 loss("judge-1", "2026-09-24T01:00:00Z", None),
8829 ];
8830 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8831 }
8832
8833 #[test]
8834 fn merge_overrides_are_parsed_or_refused() {
8835 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8836 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8837 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8838 assert!(merge_mode("squash").is_err());
8839 }
8840
8841 #[test]
8842 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8843 let now = Timestamp::now();
8844 let fallback = Duration::from_secs(300);
8845 let cap = Duration::from_secs(1800);
8846
8847 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8849
8850 let soon = now + jiff::SignedDuration::from_secs(600);
8852 assert_eq!(
8853 quota_wait(Some(soon), now, fallback, cap),
8854 Duration::from_secs(600)
8855 );
8856
8857 let past = now - jiff::SignedDuration::from_secs(60);
8860 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8861
8862 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8865 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8866 }
8867
8868 #[test]
8869 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8870 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8871
8872 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8873 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8874
8875 let already_past =
8879 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8880 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8881
8882 assert!(
8883 parse_reset_hint("session limit reached", now, now).is_none(),
8884 "free text with no recognised shape is not guessed at"
8885 );
8886 assert!(
8887 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8888 "an unresolvable zone name is not guessed at either"
8889 );
8890 }
8891
8892 #[test]
8893 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8894 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8895
8896 let at = parse_reset_hint(
8897 "You've hit your usage limit. Visit \
8898 https://chatgpt.com/codex/settings/usage to purchase more \
8899 credits or try again at Sep 19th, 2026 5:10 PM.",
8900 now,
8901 now,
8902 )
8903 .expect("the codex reset wording is a recognised shape");
8904 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8905
8906 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8911 .expect("an explicit year needs no rollover");
8912 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8913
8914 assert!(
8915 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8916 "a two-digit year is not the documented shape and is not guessed at"
8917 );
8918 assert!(
8919 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8920 "a four-letter month name is not the documented three-letter abbreviation"
8921 );
8922 assert!(
8923 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8924 "an explicit zone on the dated shape is a format nobody has \
8925 documented, and is refused rather than guessed at as UTC"
8926 );
8927 }
8928
8929 #[test]
8930 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8931 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8932 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8933
8934 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8935 assert_eq!(at.as_second() - recorded.as_second(), 3769);
8936
8937 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8938 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8939
8940 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8941 assert!(
8942 parse_reset_hint(bad, now, recorded).is_none(),
8943 "{bad:?} must not be guessed at"
8944 );
8945 }
8946 }
8947
8948 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8952 let config = dir.join("magi.toml");
8953 std::fs::write(
8954 &config,
8955 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8956 )
8957 .unwrap();
8958 let opts = Opts {
8959 poll: Duration::from_secs(30),
8960 config: Some(config),
8961 repo: dir.join("repo"),
8965 ..Opts::default()
8966 };
8967 let home = dir.join("home");
8976 let worktrees = dir.join("wt");
8977 (
8978 opts,
8979 Queue::at(dir.join("queue")),
8980 home.join("daemon.json"),
8981 home,
8982 worktrees,
8983 )
8984 }
8985
8986 #[test]
8987 fn a_stop_is_idempotent_and_once_set_stays_set() {
8988 let stop = Stop::new();
8989 assert!(!stop.stopped());
8990
8991 stop.stop();
8992 assert!(stop.stopped());
8993 stop.stop();
8994 assert!(stop.stopped(), "a second stop is not a toggle");
8995
8996 let shared = stop.clone();
8997 assert!(
8998 shared.stopped(),
8999 "a clone is the same stop; that is how the loop and its caller share one"
9000 );
9001 }
9002
9003 #[test]
9004 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
9005 let stop = Stop::new();
9006 stop.enter();
9007 assert!(
9008 !stop.finishing(),
9009 "a busy loop nobody has asked to stop is just running"
9010 );
9011
9012 stop.stop();
9013 assert!(
9014 stop.finishing(),
9015 "a stop asked for mid-run has not landed until the run is settled"
9016 );
9017
9018 stop.exit();
9019 assert!(
9020 !stop.finishing(),
9021 "once the run is settled the stop has landed and there is nothing to finish"
9022 );
9023 }
9024
9025 #[test]
9026 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
9027 let stop = Stop::new();
9028 stop.enter();
9029 stop.enter();
9030 stop.stop();
9031 assert!(stop.finishing(), "two runs still in flight");
9032
9033 stop.exit();
9034 assert!(
9035 stop.finishing(),
9036 "one run finished, but a sibling is still working"
9037 );
9038
9039 stop.exit();
9040 assert!(
9041 !stop.finishing(),
9042 "the last run out is what actually lands the stop"
9043 );
9044 }
9045
9046 #[tokio::test]
9047 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
9048 let dir = tempfile::tempdir().unwrap();
9049 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9050 let stop = Stop::new();
9051 stop.stop();
9052
9053 let began = std::time::Instant::now();
9054 tokio::time::timeout(
9055 Duration::from_secs(2),
9056 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9057 )
9058 .await
9059 .expect("a stopped loop must return, not sit out its poll interval")
9060 .expect("the loop's own setup and teardown must not fail");
9061 assert!(
9062 began.elapsed() < opts.poll,
9063 "returned only after {:?}, which is a poll interval, not a stop",
9064 began.elapsed()
9065 );
9066 }
9067
9068 #[tokio::test]
9069 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
9070 let dir = tempfile::tempdir().unwrap();
9071 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9072 let stop = Stop::new();
9073
9074 let asker = {
9077 let stop = stop.clone();
9078 tokio::spawn(async move {
9079 tokio::time::sleep(Duration::from_millis(20)).await;
9080 stop.stop();
9081 })
9082 };
9083
9084 let began = std::time::Instant::now();
9085 tokio::time::timeout(
9086 Duration::from_secs(2),
9087 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9088 )
9089 .await
9090 .expect("a stop asked for while idle must wake the wait")
9091 .expect("the loop's own setup and teardown must not fail");
9092 asker.await.unwrap();
9093 assert!(
9094 began.elapsed() < opts.poll,
9095 "returned only after {:?}, so the stop waited on the sleep",
9096 began.elapsed()
9097 );
9098 }
9099
9100 #[tokio::test]
9101 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
9102 let dir = tempfile::tempdir().unwrap();
9103 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9104 let stop = Stop::new();
9105 stop.stop();
9106
9107 tokio::time::timeout(
9108 Duration::from_secs(2),
9109 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9110 )
9111 .await
9112 .expect("a stopped loop must return")
9113 .expect("the loop's own setup and teardown must not fail");
9114
9115 assert!(
9116 home.is_dir(),
9117 "the loop did publish a status file, so its removal is the teardown and not an absence"
9118 );
9119 assert!(
9120 !status_file.exists(),
9121 "a stopped loop clears its status file"
9122 );
9123 assert!(
9124 read_status(&home).is_none(),
9125 "a reader must see no daemon at all, not a heartbeat that merely stopped"
9126 );
9127 }
9128
9129 #[tokio::test]
9130 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
9131 let dir = tempfile::tempdir().unwrap();
9132 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9133 opts.once = true;
9134
9135 let mut settled = RunState::new(
9136 dir.path().join("repo"),
9137 "main".to_owned(),
9138 "abc1234".to_owned(),
9139 "fixture".to_owned(),
9140 Config::default(),
9141 );
9142 settled.status = RunStatus::Ready;
9143 let run_dir = home.join("runs").join(&settled.id);
9144 std::fs::create_dir_all(&run_dir).unwrap();
9145 std::fs::write(
9146 run_dir.join("run.json"),
9147 serde_json::to_string_pretty(&settled).unwrap(),
9148 )
9149 .unwrap();
9150 let questions = Questions::at(home.join("questions"));
9151 let mut question = ask::Question::new(
9152 settled.id.clone(),
9153 "review".to_owned(),
9154 "reviewer-1".to_owned(),
9155 "Continue?".to_owned(),
9156 String::new(),
9157 Vec::new(),
9158 );
9159 questions.put(&mut question).unwrap();
9160
9161 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
9162 .await
9163 .unwrap();
9164
9165 assert_eq!(
9166 questions.get(&question.id).unwrap().status,
9167 ask::QuestionStatus::Abandoned,
9168 "an empty --once drain still performs startup question cleanup"
9169 );
9170 }
9171
9172 #[test]
9173 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
9174 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9175
9176 assert!(
9177 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
9178 "never checked before: due at once"
9179 );
9180
9181 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
9182 assert!(
9183 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
9184 "well inside the interval: not due yet"
9185 );
9186
9187 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
9188 assert!(
9189 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
9190 "exactly at the edge: not yet due, same convention as `clean::due`"
9191 );
9192
9193 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9194 assert!(
9195 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
9196 "past the interval: due again"
9197 );
9198 }
9199
9200 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
9205 let config = dir.join("magi.toml");
9206 std::fs::write(
9212 &config,
9213 format!(
9214 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
9215 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
9216 cache_dir.display()
9217 ),
9218 )
9219 .unwrap();
9220 Opts {
9221 config: Some(config),
9222 repo: dir.join("repo"),
9223 ..Opts::default()
9224 }
9225 }
9226
9227 #[tokio::test]
9228 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
9229 let dir = tempfile::tempdir().unwrap();
9230 let home = dir.path().join("home");
9231 let cache_dir = dir.path().join("cache");
9232 std::fs::create_dir_all(&cache_dir).unwrap();
9233 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9234 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9235
9236 let running = Stop::new();
9239 let mut last_checked = None;
9240 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9241 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9242 .await;
9243 assert_eq!(
9244 crate::disk::dir_size(&cache_dir),
9245 0,
9246 "over the cap on the first check ever: pruned at once, no idle queue required"
9247 );
9248 assert_eq!(last_checked, Some(t0));
9249
9250 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9252 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9253 maybe_prune_cache_between_runs(
9254 &opts.repo,
9255 &opts,
9256 &home,
9257 &running,
9258 &mut last_checked,
9259 too_soon,
9260 )
9261 .await;
9262 assert_eq!(
9263 crate::disk::dir_size(&cache_dir),
9264 10,
9265 "too soon since the last check: left alone rather than rescanned every call"
9266 );
9267 assert_eq!(
9268 last_checked,
9269 Some(t0),
9270 "an idle check does not reset the clock"
9271 );
9272
9273 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9275 maybe_prune_cache_between_runs(
9276 &opts.repo,
9277 &opts,
9278 &home,
9279 &running,
9280 &mut last_checked,
9281 due_again,
9282 )
9283 .await;
9284 assert_eq!(
9285 crate::disk::dir_size(&cache_dir),
9286 0,
9287 "due again: pruned back under the cap"
9288 );
9289 }
9290
9291 #[tokio::test]
9299 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9300 let dir = tempfile::tempdir().unwrap();
9301 let home = dir.path().join("home");
9302 let cache_dir = dir.path().join("cache");
9303 std::fs::create_dir_all(&cache_dir).unwrap();
9304 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9305 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9306
9307 let stop = Stop::new();
9308 stop.stop();
9309 assert!(
9310 !stop.finishing(),
9311 "no run is in flight at a between-runs boundary, so nothing else \
9312 would tell the operator this stop had not taken effect yet"
9313 );
9314
9315 let mut last_checked = None;
9316 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9317 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9318 .await;
9319 assert_eq!(
9320 crate::disk::dir_size(&cache_dir),
9321 10,
9322 "over its cap, and due for the first check ever, but a stop outranks \
9323 it: the cap is a standing policy the next start measures again"
9324 );
9325 assert_eq!(
9326 last_checked, None,
9327 "a check that never happened must not claim the interval"
9328 );
9329 }
9330
9331 #[tokio::test]
9342 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9343 let dir = tempfile::tempdir().unwrap();
9344 let cache_dir = dir.path().join("cache");
9345 std::fs::create_dir_all(&cache_dir).unwrap();
9346 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9347
9348 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9349 opts.poll = Duration::from_millis(20);
9350 opts.max_attempts = 1_000;
9351
9352 let queue = Queue::at(dir.path().join("queue"));
9353 for i in 0..128 {
9354 let mut task = Task::new(
9355 format!("queued work {i}"),
9356 format!("queued work {i}"),
9357 opts.repo.clone(),
9358 Source::Human,
9359 );
9360 queue.put(&mut task).unwrap();
9361 }
9362
9363 let home = dir.path().join("home");
9364 let worktrees = dir.path().join("wt");
9365 let status_file = home.join("daemon.json");
9366 let stop = Stop::new();
9367 let stopper = {
9368 let stop = stop.clone();
9369 let queue = Queue::at(dir.path().join("queue"));
9370 tokio::spawn(async move {
9371 for _ in 0..2_000 {
9375 if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9376 break;
9377 }
9378 tokio::time::sleep(Duration::from_millis(5)).await;
9379 }
9380 stop.stop();
9381 })
9382 };
9383
9384 tokio::time::timeout(
9385 Duration::from_secs(20),
9386 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9387 )
9388 .await
9389 .expect("the loop must not hang on a queue that keeps producing failing work")
9390 .expect("the loop's own setup and teardown must not fail");
9391 stopper.await.unwrap();
9392
9393 let after = queue.list();
9394 let completed = after.iter().filter(|t| t.attempts == 1).count();
9395 assert!(
9396 completed >= 2,
9397 "the harness must have processed multiple tasks to exercise a busy queue \
9398 (got {completed} completed task(s))"
9399 );
9400 assert!(
9401 after.iter().any(|t| t.status.runnable()),
9402 "unprocessed tasks must remain: the external stop, rather than an \
9403 exhausted backlog, must end the test"
9404 );
9405 assert!(
9406 after
9407 .iter()
9408 .filter(|t| t.attempts > 0)
9409 .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9410 "a busy backlog must not retry a task's unchanged startup failure"
9411 );
9412
9413 assert_eq!(
9414 crate::disk::dir_size(&cache_dir),
9415 0,
9416 "an oversized cache must not be left to grow unboundedly just because the \
9417 queue kept the loop busy the whole time"
9418 );
9419 }
9420
9421 #[test]
9422 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9423 let dir = tempfile::tempdir().unwrap();
9424 let queue = Queue::at(dir.path().join("queue"));
9425 let questions = Questions::at(dir.path().join("questions"));
9426 let mut task = task();
9427 queue.put(&mut task).unwrap();
9428
9429 let mut task_question = ask::Question::new(
9430 task.id.clone(),
9431 crate::conduct::NODE.to_owned(),
9432 "conduct".to_owned(),
9433 "Which backend?".to_owned(),
9434 String::new(),
9435 Vec::new(),
9436 );
9437 questions.put(&mut task_question).unwrap();
9438 task.block(vec![task_question.id.clone()], None);
9439 queue.put(&mut task).unwrap();
9440
9441 let mut run_question = ask::Question::new(
9442 "20260101-000000-run1".to_owned(),
9443 "review".to_owned(),
9444 "reviewer-1".to_owned(),
9445 "Run question".to_owned(),
9446 String::new(),
9447 Vec::new(),
9448 );
9449 questions.put(&mut run_question).unwrap();
9450
9451 let mut coincidental = ask::Question::new(
9456 task.id.clone(),
9457 "review".to_owned(),
9458 "reviewer-1".to_owned(),
9459 "Unrelated review question".to_owned(),
9460 String::new(),
9461 Vec::new(),
9462 );
9463 questions.put(&mut coincidental).unwrap();
9464
9465 reconcile_task_questions(&queue, &questions);
9466 assert!(questions.get(&task_question.id).unwrap().status.open());
9467 assert!(questions.get(&run_question.id).unwrap().status.open());
9468 assert!(questions.get(&coincidental.id).unwrap().status.open());
9469
9470 task.release();
9471 queue.put(&mut task).unwrap();
9472 reconcile_task_questions(&queue, &questions);
9473 assert_eq!(
9474 questions.get(&task_question.id).unwrap().status,
9475 ask::QuestionStatus::Abandoned
9476 );
9477 assert!(
9478 questions.get(&run_question.id).unwrap().status.open(),
9479 "run questions remain the run janitor's responsibility"
9480 );
9481 assert!(
9482 questions.get(&coincidental.id).unwrap().status.open(),
9483 "a non-conductor question must not be abandoned just because its \
9484 run id coincides with a task id"
9485 );
9486 }
9487
9488 #[test]
9489 fn a_freshly_started_running_task_is_never_stalled() {
9490 let dir = tempfile::tempdir().unwrap();
9491 let mut t = task();
9492 t.start("run-1".to_owned());
9493 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9496 }
9497
9498 #[test]
9499 fn a_long_running_task_with_no_live_daemon_is_stalled() {
9500 let dir = tempfile::tempdir().unwrap();
9501 let mut t = task();
9502 t.start("run-1".to_owned());
9503 t.updated_at = Timestamp::now()
9504 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9505 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9506 assert_eq!(
9507 stalled_tasks(
9508 &Queue::at(dir.path().join("q")),
9509 dir.path(),
9510 Timestamp::now()
9511 )
9512 .len(),
9513 0,
9514 "the task was never written to this queue"
9515 );
9516 }
9517
9518 #[test]
9519 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9520 let dir = tempfile::tempdir().unwrap();
9521 let mut t = task();
9522 t.id = "20260903-080340-0167".to_owned();
9523 t.start("20260903-080619-01c2".to_owned());
9524 t.updated_at = Timestamp::now()
9525 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9526
9527 let mut status = Status::new();
9528 status.current = vec![Current {
9529 task: t.id.clone(),
9530 run: "20260903-080619-01c2".to_owned(),
9531 }];
9532 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9533
9534 assert!(
9535 !is_stalled(&t, dir.path(), Timestamp::now()),
9536 "a live daemon's own heartbeat rules out stalled, however long the task has run"
9537 );
9538 }
9539
9540 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9544 let path = queue.path_of(id);
9545 let body = std::fs::read_to_string(&path).unwrap();
9546 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9547 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9548 v["updated_at"] = serde_json::Value::String(old.to_string());
9549 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9550 }
9551
9552 #[test]
9553 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9554 let dir = tempfile::tempdir().unwrap();
9567 let queue = Queue::at(dir.path().join("queue"));
9568 let home = dir.path().join("home");
9569
9570 let mut t = task();
9571 t.id = "20260101-000001-lock".to_owned();
9572 t.start("run-1".to_owned());
9573 queue.put(&mut t).unwrap();
9574 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9575 std::fs::write(
9576 dir.path().join("queue").join(format!("{}.lock", t.id)),
9577 "not a pid",
9578 )
9579 .unwrap();
9580
9581 let now = Timestamp::now();
9582 assert!(
9583 reclaim_orphaned_running(&queue, 2).is_empty(),
9584 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9585 and reclaim must leave the task alone"
9586 );
9587 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9588
9589 let stalled = stalled_tasks(&queue, &home, now);
9590 assert_eq!(
9591 stalled.len(),
9592 1,
9593 "reclaim's inability to claim it yet must not hide it from the conductor"
9594 );
9595 assert_eq!(stalled[0].id, t.id);
9596 }
9597
9598 #[test]
9599 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9600 let dir = tempfile::tempdir().unwrap();
9601 crate::run::set_home(dir.path().join("run-home"));
9602 let queue = Queue::at(dir.path().join("queue"));
9603 let home = dir.path().join("home");
9604 let questions = Questions::at(dir.path().join("questions"));
9605
9606 let mut t = task();
9607 t.id = "20260101-000003-dead".to_owned();
9608 t.start("missing-run".to_owned());
9609 queue.put(&mut t).unwrap();
9610 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9611
9612 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9615 assert_eq!(
9616 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9617 [&t.id]
9618 );
9619 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9620 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9621
9622 crate::conduct::apply(
9625 &queue,
9626 &questions,
9627 &crate::conduct::Verdict {
9628 decisions: vec![crate::conduct::Decision {
9629 id: t.id.clone(),
9630 recovery: Some(crate::conduct::Recovery::Requeue),
9631 ..crate::conduct::Decision::default()
9632 }],
9633 },
9634 )
9635 .unwrap();
9636 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9637 }
9638
9639 #[test]
9640 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9641 let dir = tempfile::tempdir().unwrap();
9642 let queue = Queue::at(dir.path().join("queue"));
9643 let home = dir.path().join("home");
9644
9645 let mut fresh = task();
9646 fresh.id = "20260101-000001-aaaa".to_owned();
9647 fresh.start("run-1".to_owned());
9648 queue.put(&mut fresh).unwrap();
9649
9650 let mut old = task();
9651 old.id = "20260101-000002-bbbb".to_owned();
9652 old.start("run-2".to_owned());
9653 queue.put(&mut old).unwrap();
9654 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9655
9656 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9657 assert_eq!(stalled.len(), 1);
9658 assert_eq!(stalled[0].id, old.id);
9659 }
9660
9661 #[test]
9662 fn queued_and_finished_task_views_partition_by_status() {
9663 let dir = tempfile::tempdir().unwrap();
9664 let queue = Queue::at(dir.path().join("queue"));
9665
9666 let mut queued = task();
9667 queued.id = "20260101-000001-aaaa".to_owned();
9668 queue.put(&mut queued).unwrap();
9669
9670 let mut failed = task();
9671 failed.id = "20260101-000002-bbbb".to_owned();
9672 failed.start("run-1".to_owned());
9673 failed.fail("gate red", 5);
9674 queue.put(&mut failed).unwrap();
9675
9676 let mut held = task();
9677 held.id = "20260101-000003-cccc".to_owned();
9678 held.hold_machine(None);
9679 queue.put(&mut held).unwrap();
9680
9681 let mut running = task();
9682 running.id = "20260101-000004-dddd".to_owned();
9683 running.start("run-2".to_owned());
9684 queue.put(&mut running).unwrap();
9685
9686 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9687 assert_eq!(queued_ids, [queued.id.clone()]);
9688
9689 let mut finished_ids: Vec<String> =
9690 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9691 finished_ids.sort_unstable();
9692 let mut want = vec![failed.id.clone(), held.id.clone()];
9693 want.sort_unstable();
9694 assert_eq!(finished_ids, want);
9695 }
9696
9697 #[test]
9698 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9699 for short in [false, true] {
9700 let dir = tempfile::tempdir().unwrap();
9701 let queue = Queue::at(dir.path().join("queue"));
9702 let questions = ask::Questions::at(dir.path().join("questions"));
9703 let mut running = task();
9704 running.id = "20261013-192213-feb2".into();
9705 running.start("existing-run".into());
9706 queue.put(&mut running).unwrap();
9707 let mut middle = task();
9708 middle.id = "20261013-193611-ca5b".into();
9709 middle.block(
9710 vec![if short {
9711 "feb2".into()
9712 } else {
9713 running.id.clone()
9714 }],
9715 None,
9716 );
9717 queue.put(&mut middle).unwrap();
9718 let mut waiting = task();
9719 waiting.id = "20261013-202849-ee37".into();
9720 waiting.block(
9721 vec![if short {
9722 "ca5b".into()
9723 } else {
9724 middle.id.clone()
9725 }],
9726 Some("wait for implementation".into()),
9727 );
9728 queue.put(&mut waiting).unwrap();
9729 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9730 let inv = crate::blockers::Inventory::load(&queue, &questions);
9731 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9732 assert!(inv.stuck().is_empty());
9733 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9734 assert!(report.quarantined.is_empty());
9735 assert!(report.asked.is_empty());
9736 resolve_blockers(&queue, &questions);
9737 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9738 assert!(questions.list().is_empty());
9739 running.succeed();
9742 queue.put(&mut running).unwrap();
9743 resolve_blockers(&queue, &questions);
9744 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9745 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9746 middle = queue.get(&middle.id).unwrap();
9747 middle.succeed();
9748 queue.put(&mut middle).unwrap();
9749 resolve_blockers(&queue, &questions);
9750 let after = queue.get(&waiting.id).unwrap();
9751 assert_eq!(after.status, TaskStatus::Queued);
9752 assert!(after.blocked_by.is_empty());
9753 assert_eq!(after.instruction, waiting.instruction);
9754 }
9755 }
9756
9757 #[test]
9758 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9759 for future_schema in [false, true] {
9760 let name = "20261013-193611-ca5b";
9761 let mut future = task();
9762 future.id = name.into();
9763 future.schema = crate::queue::SCHEMA + 1;
9764 let contents = if future_schema {
9765 serde_json::to_string(&future).unwrap()
9766 } else {
9767 "corrupt".into()
9768 };
9769 let dir = tempfile::tempdir().unwrap();
9770 let queue = Queue::at(dir.path().join("queue"));
9771 let questions = ask::Questions::at(dir.path().join("questions"));
9772 let mut waiting = task();
9773 waiting.id = "20261013-202849-ee37".into();
9774 waiting.block(vec!["ca5b".into()], None);
9775 queue.put(&mut waiting).unwrap();
9776 std::fs::write(queue.path_of(name), contents).unwrap();
9777 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9778 assert!(
9779 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9780 );
9781 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9782 assert!(report.asked.is_empty());
9783 resolve_blockers(&queue, &questions);
9784 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9785 assert!(questions.list().is_empty());
9786 }
9787 let dir = tempfile::tempdir().unwrap();
9788 let queue = Queue::at(dir.path().join("queue"));
9789 let questions = ask::Questions::at(dir.path().join("questions"));
9790 let mut waiting = task();
9791 waiting.id = "20261013-202849-ee37".into();
9792 waiting.block(vec!["ca5b".into()], None);
9793 queue.put(&mut waiting).unwrap();
9794 let mut done = task();
9795 done.id = "20261013-193611-ca5b".into();
9796 done.succeed();
9797 queue.put(&mut done).unwrap();
9798 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9801 assert!(queue.get("ca5b").is_err());
9802 assert_eq!(
9803 crate::queue::dependency(&queue, &questions, "ca5b"),
9804 crate::queue::Dependency::Ambiguous
9805 );
9806 resolve_blockers(&queue, &questions);
9807 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9808 assert!(report.asked.is_empty());
9809 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9810 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9811 }
9812
9813 #[test]
9814 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9815 for held in [false, true] {
9816 for question in [false, true] {
9817 for reference in ["ca5b", "20261013-193611-ca5b"] {
9818 let dir = tempfile::tempdir().unwrap();
9819 let queue = Queue::at(dir.path().join("queue"));
9820 let questions = ask::Questions::at(dir.path().join("questions"));
9821 let mut prerequisite = task();
9822 prerequisite.id = "20261013-193611-ca5b".into();
9823 prerequisite.start("existing-run".into());
9824 queue.put(&mut prerequisite).unwrap();
9825 let mut waiting = task();
9826 waiting.id = "20261013-202849-ee37".into();
9827 if held {
9828 waiting.hold_machine(Some("waiting for separate consent".into()));
9829 }
9830 queue.put(&mut waiting).unwrap();
9831 let reason = "Deleting saved data requires separate owner consent";
9832 crate::conduct::apply(
9833 &queue,
9834 &questions,
9835 &crate::conduct::Verdict {
9836 decisions: vec![crate::conduct::Decision {
9837 id: waiting.id.clone(),
9838 blocked_by: vec![reference.into()],
9839 question: question.then(|| "May the saved data be deleted?".into()),
9840 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9841 reason: Some(reason.into()),
9842 ..crate::conduct::Decision::default()
9843 }],
9844 },
9845 )
9846 .unwrap();
9847 let before = queue.get(&waiting.id).unwrap();
9848 if question {
9849 assert_eq!(before.status, TaskStatus::Blocked);
9850 let q = questions.get(&before.blocked_by[0]).unwrap();
9851 assert_eq!(q.summary, "May the saved data be deleted?");
9852 assert!(q.status.open());
9853 } else {
9854 assert_eq!(before.status, TaskStatus::Held);
9855 let recorded_reason = before.hold_reason.as_deref().unwrap();
9856 assert!(recorded_reason.starts_with(reason));
9857 if held {
9858 assert!(recorded_reason.contains("waiting for separate consent"));
9859 }
9860 }
9861 prerequisite.succeed();
9862 queue.put(&mut prerequisite).unwrap();
9863 resolve_blockers(&queue, &questions);
9864 let after = queue.get(&waiting.id).unwrap();
9865 assert_eq!(after.status, before.status);
9866 assert_eq!(after.blocked_by, before.blocked_by);
9867 assert_eq!(after.hold_reason, before.hold_reason);
9868 assert_eq!(after.instruction, waiting.instruction);
9869 if question {
9870 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9871 }
9872 assert!(
9873 queue.next_runnable().is_none(),
9874 "dependency completion is not consent"
9875 );
9876 }
9877 }
9878 }
9879 }
9880
9881 #[test]
9882 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9883 let dir = tempfile::tempdir().unwrap();
9884 let queue = Queue::at(dir.path().join("queue"));
9885 let questions = ask::Questions::at(dir.path().join("questions"));
9886
9887 let mut dep = task();
9888 dep.id = "20260101-000001-dep0".to_owned();
9889 dep.succeed();
9890 queue.put(&mut dep).unwrap();
9891
9892 let mut still_going = task();
9893 still_going.id = "20260101-000002-dep1".to_owned();
9894 queue.put(&mut still_going).unwrap();
9895
9896 let mut blocked = task();
9897 blocked.id = "20260101-000003-main".to_owned();
9898 blocked.block(
9899 vec![dep.id.clone(), still_going.id.clone()],
9900 Some("waits on both".to_owned()),
9901 );
9902 queue.put(&mut blocked).unwrap();
9903
9904 resolve_blockers(&queue, &questions);
9905
9906 let after = queue.get(&blocked.id).unwrap();
9907 assert_eq!(
9908 after.status,
9909 TaskStatus::Blocked,
9910 "one dependency is still outstanding"
9911 );
9912 assert_eq!(after.blocked_by, [still_going.id.clone()]);
9913 }
9914
9915 #[test]
9916 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9917 let dir = tempfile::tempdir().unwrap();
9918 let queue = Queue::at(dir.path().join("queue"));
9919 let questions = ask::Questions::at(dir.path().join("questions"));
9920
9921 let mut q = crate::ask::Question::new(
9922 "20260101-000001-main".to_owned(),
9923 crate::conduct::NODE.to_owned(),
9924 "conduct".to_owned(),
9925 "Which backend?".to_owned(),
9926 String::new(),
9927 Vec::new(),
9928 );
9929 questions.put(&mut q).unwrap();
9930 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9931 .unwrap();
9932 questions.put(&mut q).unwrap();
9933
9934 let mut blocked = task();
9935 blocked.id = "20260101-000001-main".to_owned();
9936 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9937 queue.put(&mut blocked).unwrap();
9938
9939 resolve_blockers(&queue, &questions);
9940
9941 let after = queue.get(&blocked.id).unwrap();
9942 assert_eq!(
9943 after.status,
9944 TaskStatus::Queued,
9945 "the only blocker resolved"
9946 );
9947 assert_eq!(after.answers.len(), 1);
9948 assert_eq!(after.answers[0].question, "Which backend?");
9949 assert_eq!(after.answers[0].answer, "SQLite");
9950
9951 let instruction = instruction_for(&after);
9953 assert!(instruction.contains("Which backend?"));
9954 assert!(instruction.contains("SQLite"));
9955 }
9956
9957 #[test]
9958 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9959 let dir = tempfile::tempdir().unwrap();
9960 let queue = Queue::at(dir.path().join("queue"));
9961 let questions = ask::Questions::at(dir.path().join("questions"));
9962
9963 let mut q = crate::ask::Question::new(
9964 "20260101-000001-main".to_owned(),
9965 crate::conduct::NODE.to_owned(),
9966 "conduct".to_owned(),
9967 "Is the setup done?".to_owned(),
9968 String::new(),
9969 Vec::new(),
9970 );
9971 q.abandon("no answer within 60s of asking");
9972 questions.put(&mut q).unwrap();
9973
9974 let mut blocked = task();
9975 blocked.id = "20260101-000001-main".to_owned();
9976 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9977 queue.put(&mut blocked).unwrap();
9978
9979 resolve_blockers(&queue, &questions);
9980
9981 let after = queue.get(&blocked.id).unwrap();
9982 assert_eq!(
9983 after.status,
9984 TaskStatus::Held,
9985 "never left blocked on nothing"
9986 );
9987 assert!(!after.operator_held(), "a machine hold, for triage");
9988 assert!(
9989 after
9990 .hold_reason
9991 .as_deref()
9992 .unwrap_or_default()
9993 .contains("went unanswered")
9994 );
9995 }
9996
9997 #[test]
9998 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9999 let dir = tempfile::tempdir().unwrap();
10005 let queue = Queue::at(dir.path().join("queue"));
10006 let questions = ask::Questions::at(dir.path().join("questions"));
10007
10008 let mut q = crate::ask::Question::new(
10009 "20260101-000001-main".to_owned(),
10010 crate::conduct::NODE.to_owned(),
10011 "conduct".to_owned(),
10012 "How should this be handled?".to_owned(),
10013 String::new(),
10014 Vec::new(),
10015 );
10016 questions.put(&mut q).unwrap();
10017 q.answer(crate::ask::Answer::Text(
10018 "leave it held, a human will look at it later".to_owned(),
10019 ))
10020 .unwrap();
10021 questions.put(&mut q).unwrap();
10022
10023 let mut held = task();
10024 held.id = "20260101-000001-main".to_owned();
10025 held.hold_machine(Some("out of attempts".to_owned()));
10026 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
10027 queue.put(&mut held).unwrap();
10028
10029 resolve_blockers(&queue, &questions);
10030
10031 let after = queue.get(&held.id).unwrap();
10032 assert_eq!(after.status, TaskStatus::Held);
10033 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
10034 assert_eq!(
10035 after.answers[0].answer,
10036 "leave it held, a human will look at it later"
10037 );
10038 }
10039
10040 #[test]
10041 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
10042 let dir = tempfile::tempdir().unwrap();
10043 let queue = Queue::at(dir.path().join("queue"));
10044 let questions = ask::Questions::at(dir.path().join("questions"));
10045 let mut dep = task();
10046 dep.id = "20260101-000001-gone".to_owned();
10047 queue.put(&mut dep).unwrap();
10048 let mut blocked = task();
10049 blocked.id = "20260101-000003-main".to_owned();
10050 blocked.block(vec![dep.id.clone()], None);
10051 queue.put(&mut blocked).unwrap();
10052
10053 let claim = queue.claim(&blocked.id).unwrap();
10055 queue.remove(&dep.id, false, &questions).unwrap();
10056 drop(claim);
10057 resolve_blockers(&queue, &questions);
10058
10059 let after = queue.get(&blocked.id).unwrap();
10060 assert_eq!(after.status, TaskStatus::Queued);
10061 assert!(after.blocked_by.is_empty());
10062 }
10063
10064 #[test]
10065 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
10066 let dir = tempfile::tempdir().unwrap();
10072 let queue = Queue::at(dir.path().join("queue"));
10073 let questions = ask::Questions::at(dir.path().join("questions"));
10074
10075 let mut still_going = task();
10076 still_going.id = "20260101-000002-dep1".to_owned();
10077 queue.put(&mut still_going).unwrap();
10078
10079 let mut blocked = task();
10080 blocked.id = "20260101-000003-main".to_owned();
10081 blocked.block(
10082 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
10083 Some("waits on both".to_owned()),
10084 );
10085 queue.put(&mut blocked).unwrap();
10086
10087 resolve_blockers(&queue, &questions);
10088
10089 let after = queue.get(&blocked.id).unwrap();
10090 assert_eq!(
10091 after.status,
10092 TaskStatus::Held,
10093 "a missing dependency must not leave the task blocked forever"
10094 );
10095 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
10096 assert!(after.blocked_by.is_empty());
10097 let reason = after.hold_reason.as_deref().unwrap_or_default();
10098 assert!(
10099 reason.contains("20260101-000001-gone"),
10100 "the missing id must be named so an operator can tell what happened: {reason}"
10101 );
10102 assert!(
10103 reason.contains(&still_going.id),
10104 "the still-valid dependency must not silently vanish from the record: {reason}"
10105 );
10106 }
10107
10108 #[test]
10109 fn instruction_for_is_unchanged_without_any_answers() {
10110 let t = task();
10111 assert_eq!(instruction_for(&t), t.instruction);
10112 }
10113
10114 #[test]
10115 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
10116 let dir = tempfile::tempdir().unwrap();
10117 let q = Queue::at(dir.path().join("queue"));
10118 let src = dir.path().join("shot.png");
10119 std::fs::write(&src, "x").unwrap();
10120 let mut t = task();
10121 q.attach(&mut t, &[src]).unwrap();
10122 let paths = task_attachments(&q, &t).unwrap();
10123 assert_eq!(paths.len(), 1);
10124 assert!(paths[0].is_absolute() && paths[0].is_file());
10125 std::fs::remove_file(&paths[0]).unwrap();
10126 let err = task_attachments(&q, &t).unwrap_err().to_string();
10127 assert!(err.contains("shot.png"), "{err}");
10128 }
10129
10130 #[tokio::test]
10131 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
10132 let dir = tempfile::tempdir().unwrap();
10133 let queue_path = dir.path().join("queue");
10134 let queue = Queue::at(queue_path.clone());
10135 let mut t = task();
10136 t.source = Source::Agent {
10137 run: "originating-chat".into(),
10138 node: crate::queue::CHAT_NODE.into(),
10139 };
10140 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
10141 stage: "config-fetch",
10142 target: "origin/main".into(),
10143 });
10144 record_config_failure(&mut t, &fetch);
10145 t.hold_machine(Some(format!("{fetch:#}")));
10146 let fetch_key = t.chat_notice_due().unwrap();
10147 t.chat_notices.push(fetch_key.clone());
10148 queue.put(&mut t).unwrap();
10149
10150 let queue = Queue::at(queue_path);
10151 let mut t = queue.get(&t.id).unwrap();
10152 let a = dir.path().join("a.toml");
10153 let b = dir.path().join("b.toml");
10154 for (path, text, new_cause) in [
10155 (&a, "[graph", true),
10156 (&a, "[verify", false),
10157 (&a, "[graph]\nimplementers = 'invalid-type'", true),
10158 (&b, "[graph]\nimplementers = 'invalid-type'", true),
10159 ] {
10160 t.release_operator("test", None);
10161 std::fs::write(path, text).unwrap();
10162 let error = Config::discover_fetched(dir.path(), Some(path))
10163 .await
10164 .unwrap_err();
10165 record_config_failure(&mut t, &error);
10166 t.hold_machine(Some(format!("{error:#}")));
10167 let due = t.chat_notice_due();
10168 assert_eq!(due.is_some(), new_cause, "{error:#}");
10169 if let Some(key) = due {
10170 assert_ne!(key, fetch_key);
10171 t.chat_notices.push(key);
10172 }
10173 }
10174 t.succeed();
10175 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
10176 }
10177
10178 #[test]
10179 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
10180 let dir = tempfile::tempdir().unwrap();
10181 let queue_path = dir.path().join("queue");
10182 let queue = Queue::at(queue_path.clone());
10183 let mut t = task();
10184 t.source = crate::queue::Source::Agent {
10185 run: "originating-chat".into(),
10186 node: crate::queue::CHAT_NODE.into(),
10187 };
10188 let a = dir.path().join("a.png");
10189 let b = dir.path().join("b.png");
10190 std::fs::write(&a, "a").unwrap();
10191 std::fs::write(&b, "b").unwrap();
10192 queue.attach(&mut t, &[a, b]).unwrap();
10193 let paths = task_attachments(&queue, &t).unwrap();
10194 for path in &paths {
10195 std::fs::remove_file(path).unwrap();
10196 }
10197 let missing = task_attachments(&queue, &t).unwrap_err();
10198 t.attempts += 1;
10199 let reason = missing.to_string();
10200 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10201 let first = t.chat_notice_due().expect("first attachment notice");
10202 t.chat_notices.push(first.clone());
10203 queue.put(&mut t).unwrap();
10204
10205 let queue = Queue::at(queue_path.clone());
10206 let mut t = queue.get(&t.id).unwrap();
10207 assert!(t.chat_notice_due().is_none(), "restart does not replay");
10208 t.release_operator("test", None);
10209 t.attempts += 1;
10210 let missing = task_attachments(&queue, &t).unwrap_err();
10211 t.fail_startup_target(
10212 "startup-attachments",
10213 missing.name,
10214 "same missing attachment with regenerated wording",
10215 1,
10216 );
10217 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
10218
10219 std::fs::write(&paths[0], "restored").unwrap();
10220 t.release_operator("test", None);
10221 t.attempts += 1;
10222 let missing = task_attachments(&queue, &t).unwrap_err();
10223 let reason = missing.to_string();
10224 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10225 let second = t
10226 .chat_notice_due()
10227 .expect("different attachment must notify");
10228 assert_ne!(first, second);
10229 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
10230 }
10231
10232 #[test]
10233 fn resumed_instruction_is_unchanged_without_any_answers() {
10234 let t = task();
10235 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10236 }
10237
10238 #[test]
10239 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10240 let mut t = task();
10241 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10242 let old = t.instruction.clone();
10246
10247 let refreshed = resumed_instruction(&old, &t);
10248 assert!(refreshed.starts_with(&old), "the original text is kept");
10249 assert!(refreshed.contains("Which backend?"));
10250 assert!(refreshed.contains("SQLite"));
10251 }
10252
10253 #[test]
10254 fn resumed_instruction_keeps_an_original_answers_heading() {
10255 let mut t = task();
10256 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10257 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10258
10259 let refreshed = resumed_instruction(&t.instruction, &t);
10260
10261 assert!(
10262 refreshed.starts_with(&t.instruction),
10263 "an answers heading in the original instruction is not the appended block"
10264 );
10265 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10266 assert!(refreshed.contains("Which backend?"));
10267 assert!(refreshed.contains("SQLite"));
10268
10269 let repeated = resumed_instruction(&refreshed, &t);
10270 assert_eq!(
10271 repeated, refreshed,
10272 "only the final appended block is refreshed"
10273 );
10274 }
10275
10276 #[test]
10277 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10278 let mut t = task();
10279 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10280
10281 let once = resumed_instruction(&t.instruction, &t);
10285 let twice = resumed_instruction(&once, &t);
10286 assert_eq!(once, twice);
10287 assert_eq!(once.matches("Which backend?").count(), 1);
10288
10289 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10291 let refreshed = resumed_instruction(&once, &t);
10292 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10293 assert!(refreshed.contains("Which backend?"));
10294 assert!(refreshed.contains("Which cache?"));
10295 }
10296
10297 #[test]
10298 fn prepare_instruction_covers_all_three_starters() {
10299 let mut t = task();
10300 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10301
10302 assert_eq!(
10305 prepare_instruction(&Starter::Start, None, &t),
10306 Some(instruction_for(&t))
10307 );
10308
10309 let old = t.instruction.clone();
10312 assert_eq!(
10313 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10314 Some(resumed_instruction(&old, &t))
10315 );
10316
10317 assert_eq!(
10321 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10322 None
10323 );
10324 }
10325
10326 #[test]
10327 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10328 assert_eq!(
10329 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10330 Starter::Review("magi/eba2/A".to_owned())
10331 );
10332 }
10333
10334 #[test]
10335 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10336 assert_eq!(
10337 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10338 Starter::Start,
10339 "a vanished review branch must not fall back to resuming the old run either"
10340 );
10341 }
10342
10343 #[test]
10344 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10345 let mut t = task();
10346 t.start("old-run".to_owned());
10347 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10348 t.release();
10349 let branch = t.review_branch.take();
10350 assert_eq!(
10351 choose_starter(branch.as_deref(), true, Some("old-run")),
10352 Starter::Review("magi/eba2/A".to_owned()),
10353 "a review wins over resuming the old run"
10354 );
10355 }
10356
10357 #[test]
10358 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10359 assert_eq!(
10360 choose_starter(None, false, Some("some-run")),
10361 Starter::Resume("some-run".to_owned())
10362 );
10363 assert_eq!(choose_starter(None, false, None), Starter::Start);
10364 }
10365
10366 #[test]
10367 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10368 let mut released = task();
10369 released.start("stalled-run".to_owned());
10370 released.requeue();
10371 let unfinished = (!released.fresh_start)
10372 .then(|| Some("stalled-run".to_owned()))
10373 .flatten();
10374 assert_eq!(
10375 choose_starter(None, false, unfinished.as_deref()),
10376 Starter::Start,
10377 "release keeps run history but must not resume it"
10378 );
10379 assert_eq!(released.runs, ["stalled-run"]);
10380 }
10381
10382 #[test]
10383 fn an_ordinary_release_keeps_a_resumable_run_available() {
10384 let mut released = task();
10385 released.start("stalled-run".to_owned());
10386 released.release();
10387 let unfinished = (!released.fresh_start)
10388 .then(|| Some("stalled-run".to_owned()))
10389 .flatten();
10390 assert_eq!(
10391 choose_starter(None, false, unfinished.as_deref()),
10392 Starter::Resume("stalled-run".to_owned()),
10393 "manual release must preserve the normal resume path"
10394 );
10395 }
10396
10397 #[test]
10398 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10399 let mut state = run_state(RunStatus::Blocked);
10400 state.config.graph.review_rounds = 3;
10401 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10402 assert!(exhausted_review_budget(&state));
10403
10404 state.reviews.pop();
10406 assert!(!exhausted_review_budget(&state));
10407
10408 let mut stalled = run_state(RunStatus::Stalled);
10411 stalled.config.graph.review_rounds = 1;
10412 stalled.reviews = vec![review_round(1)];
10413 assert!(!exhausted_review_budget(&stalled));
10414 }
10415
10416 fn review_round(round: usize) -> crate::run::ReviewRound {
10417 crate::run::ReviewRound {
10418 round,
10419 head: "deadbeef".to_owned(),
10420 verified_head: None,
10421 verified_at: None,
10422 reviews: Vec::new(),
10423 e2e: Vec::new(),
10424 verify_retried: false,
10425 e2e_deferred: false,
10426 e2e_defer_reason: None,
10427 fix: None,
10428 blocking: 0,
10429 answered: 1,
10430 expected: 1,
10431 clean: false,
10432 progressed: true,
10433 vote_split: false,
10434 reconsideration: Vec::new(),
10435 verdict: None,
10436 }
10437 }
10438
10439 #[test]
10440 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10441 let mut run = RunState::new(
10442 PathBuf::from("/repo"),
10443 "main".to_owned(),
10444 "abc1234def".to_owned(),
10445 "add retries".to_owned(),
10446 Config::default(),
10447 );
10448 run.status = RunStatus::Judging;
10449 run.parked = true;
10450 let mut task = Task::new(
10451 "add retries".to_owned(),
10452 "add retries".to_owned(),
10453 PathBuf::from("/repo"),
10454 crate::queue::Source::Human,
10455 );
10456 task.status = TaskStatus::Failed;
10457 task.runs = vec![run.id.clone()];
10458 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10459 assert!(with(&task, &run), "parked after judging is the case");
10460 let mut parked_task = task.clone();
10461 parked_task.status = TaskStatus::Parked;
10462 assert!(with(&parked_task, &run), "the Parked status is the case");
10463
10464 let mut not_parked = run.clone();
10465 not_parked.parked = false;
10466 not_parked.status = RunStatus::Stalled;
10467 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
10468
10469 let mut fresh = task.clone();
10470 fresh.fresh_start = true;
10471 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10472
10473 let mut review = task.clone();
10474 review.review_branch = Some("magi/x/A".to_owned());
10475 assert!(!with(&review, &run), "review is ranked before resume");
10476
10477 let mut held = task.clone();
10478 held.status = TaskStatus::Held;
10479 assert!(!with(&held, &run), "a hold stays visible to the conductor");
10480
10481 let mut released = run.clone();
10482 released.released_to = Some("20260901-000000-new1".to_owned());
10483 assert!(!with(&task, &released), "nothing left to resume into");
10484
10485 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10486 "unreadable"
10487 )));
10488 }
10489
10490 #[test]
10491 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10492 let mut released = RunState::new(
10493 PathBuf::from("/repo"),
10494 "main".to_owned(),
10495 "abc1234def".to_owned(),
10496 "add retries".to_owned(),
10497 Config::default(),
10498 );
10499 released.status = RunStatus::Blocked;
10500 assert_eq!(
10501 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10502 Some(released.id.clone())
10503 );
10504 released.released_to = Some("20260901-000000-new1".to_owned());
10505 assert_eq!(
10506 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10507 None,
10508 "there is nothing left to resume it into"
10509 );
10510 }
10511
10512 #[test]
10513 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10514 let mut exhausted = RunState::new(
10523 PathBuf::from("/repo"),
10524 "main".to_owned(),
10525 "abc1234def".to_owned(),
10526 "add retries".to_owned(),
10527 Config::default(),
10528 );
10529 exhausted.status = RunStatus::Blocked;
10530 exhausted.config.graph.review_rounds = 1;
10531 exhausted.reviews = vec![review_round(1)];
10532
10533 assert_eq!(
10534 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10535 None,
10536 "an exhausted `Blocked` run must not be offered as resumable"
10537 );
10538
10539 let mut has_budget_left = RunState::new(
10542 PathBuf::from("/repo"),
10543 "main".to_owned(),
10544 "abc1234def".to_owned(),
10545 "add retries".to_owned(),
10546 Config::default(),
10547 );
10548 has_budget_left.status = RunStatus::Blocked;
10549 has_budget_left.config.graph.review_rounds = 3;
10550 has_budget_left.reviews = vec![review_round(1)];
10551
10552 assert_eq!(
10553 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10554 Ok(has_budget_left.clone())
10555 }),
10556 Some(has_budget_left.id.clone())
10557 );
10558 }
10559
10560 #[test]
10561 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10562 let mut run = RunState::new(
10563 PathBuf::from("/repo"),
10564 "main".to_owned(),
10565 "abc1234def".to_owned(),
10566 "add retries".to_owned(),
10567 Config::default(),
10568 );
10569 run.status = RunStatus::Blocked;
10570 run.config.graph.review_rounds = 1;
10571 run.reviews = vec![review_round(1)];
10572 run.pr_publication_pending = true;
10573 assert_eq!(
10574 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10575 Some(run.id.clone()),
10576 "a spent review budget must not turn a failed publication into a re-competition"
10577 );
10578 }
10579
10580 #[test]
10581 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
10582 let mut task = Task::new(
10583 "recover work".into(),
10584 "recover work".into(),
10585 PathBuf::from("/repo"),
10586 crate::queue::Source::Human,
10587 );
10588 let mut history = std::collections::BTreeMap::new();
10589 for index in 0..8 {
10590 let mut run = run_state(RunStatus::Blocked);
10591 run.id = format!("20260101-000000-{index:04}");
10592 run.base_commit = format!("upstream-{index}");
10593 if index > 0 {
10595 run.candidates.clear();
10596 }
10597 task.runs.extend([run.id.clone(), run.id.clone()]);
10598 history.insert(run.id.clone(), run);
10599 task.requeue();
10600 }
10601 let check = |task: &Task, starter: &Starter, limit| {
10602 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
10603 };
10604 assert!(
10605 check(&task, &Starter::Start, 8)
10606 .unwrap()
10607 .contains("8 unretired")
10608 );
10609 assert!(check(&task, &Starter::Start, 9).is_none());
10610 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
10611 task.release_operator("owner", None);
10612 assert_eq!(task.attempts, 0);
10613 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
10614 assert!(check(&restored, &Starter::Start, 8).is_some());
10615 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
10616 assert!(check(&restored, &Starter::Start, 0).is_none());
10617 }
10618
10619 #[test]
10620 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
10621 let mut task = Task::new(
10622 "recover work".into(),
10623 "recover work".into(),
10624 PathBuf::from("/repo"),
10625 crate::queue::Source::Human,
10626 );
10627 let mut run = run_state(RunStatus::Superseded);
10628 run.candidates.clear();
10629 task.runs.push(run.id.clone());
10630 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
10631 run.retired_to = Some("authority".into());
10632 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10633 run.retired_to = None;
10634 run.released_to = Some("authority".into());
10635 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10636 assert!(
10637 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
10638 .unwrap()
10639 .contains("Cannot verify")
10640 );
10641 assert!(
10643 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
10644 panic!("resume must not load historical attempts")
10645 })
10646 .is_none()
10647 );
10648 }
10649
10650 #[test]
10651 fn retired_resume_requires_a_valid_same_repository_authority() {
10652 let mut source = run_state(RunStatus::Blocked);
10653 let mut empty = run_state(RunStatus::Blocked);
10654 empty.retired_to = Some(source.id.clone());
10655 let runs = vec![source.id.clone(), empty.id.clone()];
10656 let resolve = |source: &RunState, empty: &RunState| {
10657 unfinished_run_with(&runs, "fixture", |id| {
10658 if id == source.id {
10659 Ok(source.clone())
10660 } else if id == empty.id {
10661 Ok(empty.clone())
10662 } else {
10663 bail!("unreadable authority")
10664 }
10665 })
10666 };
10667 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
10668 assert_eq!(
10669 choose_starter(None, false, resolve(&source, &empty).as_deref()),
10670 Starter::Resume(source.id.clone())
10671 );
10672 source.retired_to = Some(empty.id.clone());
10673 assert!(
10674 resolve(&source, &empty).is_none(),
10675 "cycles do not revive obsolete runs"
10676 );
10677 source.retired_to = None;
10678 source.repo = PathBuf::from("/another-repository");
10679 assert!(resolve(&source, &empty).is_none());
10680 source.repo = empty.repo.clone();
10681 source.released_to = Some("later".into());
10682 assert!(resolve(&source, &empty).is_none());
10683 empty.retired_to = Some("unlisted-run".into());
10684 assert!(resolve(&source, &empty).is_none());
10685 }
10686
10687 #[test]
10688 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
10689 let mut older_stalled = RunState::new(
10697 PathBuf::from("/repo"),
10698 "main".to_owned(),
10699 "abc1234def".to_owned(),
10700 "add retries".to_owned(),
10701 Config::default(),
10702 );
10703 older_stalled.status = RunStatus::Stalled;
10704
10705 let mut newest_exhausted = RunState::new(
10706 PathBuf::from("/repo"),
10707 "main".to_owned(),
10708 "abc1234def".to_owned(),
10709 "add retries".to_owned(),
10710 Config::default(),
10711 );
10712 newest_exhausted.status = RunStatus::Blocked;
10713 newest_exhausted.config.graph.review_rounds = 1;
10714 newest_exhausted.reviews = vec![review_round(1)];
10715
10716 assert_eq!(
10717 unfinished_run_with(
10718 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10719 "t",
10720 |_| Ok(newest_exhausted.clone())
10721 ),
10722 None,
10723 "the newest run is exhausted, so nothing here is worth resuming - \
10724 least of all the older, already-superseded run"
10725 );
10726 }
10727
10728 #[test]
10729 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10730 assert_eq!(
10731 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10732 Err(anyhow::anyhow!("fixture is absent"))
10733 }),
10734 None
10735 );
10736 }
10737
10738 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10739 let mut q = ask::Question::new(
10740 run.to_owned(),
10741 "implement".to_owned(),
10742 "impl-A".to_owned(),
10743 "continue?".to_owned(),
10744 String::new(),
10745 vec!["resume で続行する".to_owned(), "other".to_owned()],
10746 );
10747 q.actions.insert("resume で続行する".to_owned(), action);
10748 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10749 .unwrap();
10750 q
10751 }
10752
10753 fn held_task_with(run: &str) -> Task {
10754 let mut t = task();
10755 t.runs = vec![run.to_owned()];
10756 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10757 t
10758 }
10759
10760 fn resume_action(run: &str) -> ask::ChoiceAction {
10761 ask::ChoiceAction::Resume { run: run.into() }
10762 }
10763
10764 #[test]
10765 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10766 for parked in [false, true] {
10767 let mut t = task();
10768 t.start("A".into());
10769 t.start("B".into());
10770 assert_eq!(t.runs, vec!["A", "B"]);
10771 t.start("A".into());
10772 let mut resumed = run_state(RunStatus::Blocked);
10773 resumed.id = "A".into();
10774 resumed.parked = parked;
10775 resumed.driver_exited = true;
10776 t.hold_machine(Some("resumed run stopped".into()));
10777 let q = action_question("A", resume_action("A"));
10778 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10779 assert_eq!(
10780 decide_action(&t, &q, &PHRASES_EN, |id| {
10781 assert_eq!(id, "A");
10782 Ok(resumed.clone())
10783 }),
10784 ActionDecision::Resume("A".into())
10785 );
10786 assert_eq!(
10787 action_standing(&t, &action_question("B", resume_action("B"))),
10788 ActionStanding::Stale
10789 );
10790 t.release_operator("cli", None);
10791 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10792 assert_eq!(id, "A");
10793 Ok(resumed.clone())
10794 });
10795 assert_eq!(
10796 choose_starter(None, false, unfinished.as_deref()),
10797 Starter::Resume("A".into())
10798 );
10799 assert_eq!(t.runs, vec!["B", "A"]);
10800 }
10801 }
10802
10803 #[test]
10804 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10805 let mut state = crate::land::tests::repair_state(true, true);
10806 state.status = RunStatus::Landing;
10807 state.parked = true;
10808 state.driver_exited = true;
10809 let mut q = ask::Question::new(
10810 state.id.clone(),
10811 land::APPROVAL_NODE.into(),
10812 "land".into(),
10813 "Merge?".into(),
10814 String::new(),
10815 vec![land::APPROVE.into(), land::HOLD.into()],
10816 );
10817 q.id = state.id.clone();
10818 state.land_approval = Some(crate::run::LandApproval {
10819 question: q.id.clone(),
10820 head: "current-head".into(),
10821 });
10822 assert!(land::upgrade_repair_choice(&mut q, &state));
10823 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10824 let mut task = held_task_with(&state.id);
10825 task.status = TaskStatus::Parked;
10826 assert_eq!(
10827 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10828 ActionDecision::Resume(state.id.clone())
10829 );
10830 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10831 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10832 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10833 assert_eq!(
10834 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10835 ActionDecision::Resume(state.id.clone()),
10836 "a repair answer newer than the manual hold resumes the existing owner"
10837 );
10838 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10839 for answered_at in [q.answered_at, None] {
10840 let mut older = q.clone();
10841 older.answered_at = answered_at;
10842 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10843 panic!("a later manual hold must prevent dispatch")
10844 });
10845 let ActionDecision::Refuse(reason) = refused else {
10846 panic!("expected an actionable refusal, got {refused:?}");
10847 };
10848 assert!(reason.contains("later operator decision"));
10849 assert!(reason.contains(&format!("magi task release {}", task.id)));
10850 }
10851 task.operator_decided_at = None;
10852 let mut superseded = state.clone();
10853 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10854 assert_eq!(
10855 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10856 ActionDecision::Stale
10857 );
10858 for case in 1..4 {
10859 let mut changed = state.clone();
10860 match case {
10861 1 => changed.status = RunStatus::Blocked,
10862 2 => changed.released_to = Some("new-owner".into()),
10863 _ => changed.land_approval.as_mut().unwrap().head.clear(),
10864 }
10865 assert!(matches!(
10866 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10867 ActionDecision::Refuse(_)
10868 ));
10869 }
10870 assert!(matches!(
10871 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10872 ActionDecision::Refuse(_)
10873 ));
10874 task.runs.push("replacement".into());
10875 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10876 assert_eq!(
10877 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10878 "old owner must not load"
10879 )),
10880 ActionDecision::Stale
10881 );
10882 }
10883
10884 #[test]
10885 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10886 let mut state = crate::land::tests::repair_state(true, true);
10887 state.status = RunStatus::Landing;
10888 state.parked = true;
10889 state.driver_exited = true;
10890 let mut q = ask::Question::new(
10891 state.id.clone(),
10892 land::APPROVAL_NODE.into(),
10893 "land".into(),
10894 "Merge?".into(),
10895 String::new(),
10896 vec![land::APPROVE.into(), land::HOLD.into()],
10897 );
10898 q.id = state.id.clone();
10899 state.land_approval = Some(crate::run::LandApproval {
10900 question: q.id.clone(),
10901 head: "current-head".into(),
10902 });
10903 state.save().unwrap();
10904 land::upgrade_repair_choice(&mut q, &state);
10905 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10906 Questions::open().put(&mut q).unwrap();
10907 let tmp = tempfile::tempdir().unwrap();
10908 let queue = Queue::at(tmp.path().join("queue"));
10909 let mut task = held_task_with(&state.id);
10910 task.status = TaskStatus::Parked;
10911 queue.put(&mut task).unwrap();
10912 let empty = Arc::new(tokio::sync::Semaphore::new(0));
10913 let free = Arc::new(tokio::sync::Semaphore::new(1));
10914 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10915 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10916 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10917 assert!(claim.permit.is_some());
10918 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10919 drop(claim);
10920 Questions::open()
10921 .update(&q.id, |q| {
10922 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10923 Ok(())
10924 })
10925 .unwrap();
10926 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10927 assert!(claim.permit.is_none());
10928 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10929 }
10930
10931 #[test]
10932 fn decide_action_resumes_only_the_latest_resumable_run() {
10933 let t = held_task_with("r1");
10934 let q = action_question("r1", resume_action("r1"));
10935 let load = |s: RunState| move |_: &str| Ok(s);
10936 assert_eq!(
10937 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10938 ActionDecision::Resume("r1".into())
10939 );
10940 let q_other = action_question("r1", resume_action("r0"));
10942 assert!(matches!(
10943 decide_action(
10944 &t,
10945 &q_other,
10946 &PHRASES_EN,
10947 load(run_state(RunStatus::Blocked))
10948 ),
10949 ActionDecision::Refuse(_)
10950 ));
10951 assert!(matches!(
10953 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10954 ActionDecision::Refuse(_)
10955 ));
10956 let mut released = run_state(RunStatus::Blocked);
10958 released.released_to = Some("elsewhere".into());
10959 assert!(matches!(
10960 decide_action(&t, &q, &PHRASES_EN, load(released)),
10961 ActionDecision::Refuse(_)
10962 ));
10963 assert!(matches!(
10965 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10966 ActionDecision::Refuse(_)
10967 ));
10968 }
10969
10970 #[test]
10971 fn decide_action_ignores_a_question_about_an_earlier_run() {
10972 let mut t = held_task_with("r1");
10973 t.runs.push("r2".to_owned());
10974 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10975 assert_eq!(
10976 decide_action(
10977 &t,
10978 &action_question("r1", ask::ChoiceAction::Done),
10979 &PHRASES_EN,
10980 never
10981 ),
10982 ActionDecision::Stale
10983 );
10984 }
10985
10986 #[test]
10987 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10988 let mut t = held_task_with("r1");
10989 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10990 assert_eq!(
10991 decide_action(
10992 &t,
10993 &action_question("r1", ask::ChoiceAction::Requeue),
10994 &PHRASES_EN,
10995 never
10996 ),
10997 ActionDecision::Requeue
10998 );
10999 let done_q = action_question("r1", ask::ChoiceAction::Done);
11000 assert_eq!(
11001 decide_action(&t, &done_q, &PHRASES_EN, never),
11002 ActionDecision::Done
11003 );
11004 t.mark_action_applied(&done_q.id);
11005 assert_eq!(
11006 decide_action(&t, &done_q, &PHRASES_EN, never),
11007 ActionDecision::Skip
11008 );
11009
11010 let mut plain = action_question("r1", ask::ChoiceAction::Done);
11012 plain.actions.clear();
11013 assert_eq!(
11014 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
11015 ActionDecision::Skip
11016 );
11017 let mut running = held_task_with("r1");
11019 running.status = TaskStatus::Running;
11020 assert_eq!(
11021 decide_action(
11022 &running,
11023 &action_question("r1", ask::ChoiceAction::Done),
11024 &PHRASES_EN,
11025 never
11026 ),
11027 ActionDecision::Skip
11028 );
11029 }
11030
11031 #[test]
11032 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
11033 crate::run::pin_test_home();
11034 for legacy in [false, true] {
11035 let dir = tempfile::tempdir().unwrap();
11036 let queue = Queue::at(dir.path().join("queue"));
11037 let questions = Questions::at(dir.path().join("questions"));
11038 let run = "20260101-000000-hold";
11039 let mut task = held_task_with(run);
11040 task.status = TaskStatus::Parked;
11041 let mut q = ask::Question::new(
11042 run.into(),
11043 land::APPROVAL_NODE.into(),
11044 "land".into(),
11045 "Repair?".into(),
11046 String::new(),
11047 vec![land::REPAIR.into()],
11048 );
11049 q.actions.insert(land::REPAIR.into(), resume_action(run));
11050 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11051 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
11053 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
11054 questions.put(&mut q).unwrap();
11055 task.hold_manual(Some("Keep this PR paused".into()));
11056 if legacy {
11057 task.hold_source = None;
11058 }
11059 queue.put(&mut task).unwrap();
11060
11061 apply_task_choice_actions(&queue, &questions, dir.path());
11062 let after = queue.get(&task.id).unwrap();
11063 assert!(after.operator_held());
11064 assert_eq!(after.hold_source, task.hold_source);
11065 assert_eq!(after.operator_decided_at, task.operator_decided_at);
11066 assert_eq!(after.runs, task.runs);
11067 assert_eq!(after.instruction, task.instruction);
11068 assert!(after.resume_override.is_none());
11069 assert!(after.action_applied(&q.id));
11070 let reason = after.hold_reason.as_deref().unwrap();
11071 assert!(reason.starts_with("Keep this PR paused"));
11072 assert!(reason.contains("later operator decision"));
11073 assert!(reason.contains(&format!("magi task release {}", task.id)));
11074
11075 for recovery in [
11076 crate::conduct::Recovery::Review,
11077 crate::conduct::Recovery::Requeue,
11078 ] {
11079 crate::conduct::apply(
11080 &queue,
11081 &questions,
11082 &crate::conduct::Verdict {
11083 decisions: vec![crate::conduct::Decision {
11084 id: task.id.clone(),
11085 recovery: Some(recovery),
11086 ..Default::default()
11087 }],
11088 },
11089 )
11090 .unwrap();
11091 }
11092 apply_task_choice_actions(&queue, &questions, dir.path());
11095 let still_held = queue.get(&task.id).unwrap();
11096 assert!(still_held.operator_held());
11097 assert_eq!(still_held.hold_reason, after.hold_reason);
11098 assert_eq!(still_held.runs, task.runs);
11099 assert!(still_held.review_branch.is_none());
11100 assert!(!still_held.fresh_start);
11101 assert!(queue.next_runnable().is_none());
11102 }
11103 }
11104
11105 #[test]
11106 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
11107 for held in [false, true] {
11108 for retry in [false, true] {
11109 let dir = tempfile::tempdir().unwrap();
11110 let queue = Queue::at(dir.path().join("queue"));
11111 let questions = Questions::at(dir.path().join("questions"));
11112 let home = dir.path().join("home");
11113 let mut t = task();
11114 if held {
11115 t.hold_machine(Some("driver state unknown".into()));
11116 }
11117 queue.put(&mut t).unwrap();
11118 let verdict = serde_json::from_value(serde_json::json!({
11119 "decisions": [{
11120 "id": t.id,
11121 "question": "Driver state unknown; retry the checks or hold?",
11122 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
11123 "actions": {
11124 "daemon: recheck and retry": {"do": "requeue"},
11125 "daemon: hold the task": {"do": "hold"}
11126 }
11127 }]
11128 }))
11129 .unwrap();
11130 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
11131 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11132 let mut q = questions.list().pop().unwrap();
11133 let choice = if retry {
11134 "daemon: recheck and retry"
11135 } else {
11136 "daemon: hold the task"
11137 };
11138 assert_eq!(q.actions.len(), 2);
11139 q.answer(ask::Answer::Choice(choice.into())).unwrap();
11140 questions.put(&mut q).unwrap();
11141
11142 questions.beat(&q.id, ask::WaiterKind::Deputy);
11144 for _ in 0..2 {
11145 resolve_blockers(&queue, &questions);
11146 apply_task_choice_actions(&queue, &questions, &home);
11147 let waiting = queue.get(&t.id).unwrap();
11148 assert_eq!(waiting.status, TaskStatus::Blocked);
11149 assert_eq!(waiting.blocked_by, [q.id.clone()]);
11150 assert!(waiting.answers.is_empty());
11151 assert!(!waiting.action_applied(&q.id));
11152 assert!(runnable(&queue).is_empty());
11153 let free = Arc::new(tokio::sync::Semaphore::new(1));
11154 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
11155 }
11156 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11157
11158 resolve_blockers(&queue, &questions);
11160 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11161 apply_task_choice_actions(&queue, &questions, &home);
11162 let after = queue.get(&t.id).unwrap();
11163 assert_eq!(
11164 after.status,
11165 if retry {
11166 TaskStatus::Queued
11167 } else {
11168 TaskStatus::Held
11169 }
11170 );
11171 assert!(after.action_applied(&q.id));
11172 assert_eq!(after.operator_held(), !retry);
11173 assert_eq!(after.answers.len(), 1);
11174
11175 let mut changed = after;
11177 if retry {
11178 changed.hold_manual(Some("later hold".into()));
11179 } else {
11180 changed.release_operator("test", None);
11181 }
11182 let expected = changed.status;
11183 queue.put(&mut changed).unwrap();
11184 apply_task_choice_actions(&queue, &questions, &home);
11185 assert_eq!(queue.get(&t.id).unwrap().status, expected);
11186 }
11187 }
11188 }
11189
11190 #[test]
11191 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
11192 let dir = tempfile::tempdir().unwrap();
11193 let queue = Queue::at(dir.path().join("queue"));
11194 let questions = Questions::at(dir.path().join("questions"));
11195 let home = dir.path().join("home");
11196 let mut state = run_state(RunStatus::Blocked);
11197 state.id = "20260101-000000-act1".to_owned();
11198 state.save_under(&home).unwrap();
11199
11200 let mut t = held_task_with(&state.id);
11201 queue.put(&mut t).unwrap();
11202 let mut q = action_question(&state.id, resume_action(&state.id));
11203 questions.put(&mut q).unwrap();
11204
11205 apply_task_choice_actions(&queue, &questions, &home);
11206 let after = queue.get(&t.id).unwrap();
11207 assert_eq!(after.status, TaskStatus::Queued);
11208 assert!(!after.fresh_start);
11209 assert!(after.action_applied(&q.id));
11210 let pin = after.resume_override.clone().unwrap();
11211 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
11212 assert!(pin.forced);
11213
11214 let mut again = queue.get(&t.id).unwrap();
11216 again.hold_machine(Some("later".into()));
11217 queue.put(&mut again).unwrap();
11218 apply_task_choice_actions(&queue, &questions, &home);
11219 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11220 }
11221
11222 #[test]
11223 fn a_delivered_answer_is_still_acted_on_exactly_once() {
11224 let dir = tempfile::tempdir().unwrap();
11225 let queue = Queue::at(dir.path().join("queue"));
11226 let questions = Questions::at(dir.path().join("questions"));
11227 let home = dir.path().join("home");
11228 let mut state = run_state(RunStatus::Blocked);
11229 state.id = "20260101-000000-act2".to_owned();
11230 state.save_under(&home).unwrap();
11231
11232 let mut t = held_task_with(&state.id);
11233 queue.put(&mut t).unwrap();
11234 let mut q = action_question(&state.id, resume_action(&state.id));
11235 q.answer_delivered = true;
11236 questions.put(&mut q).unwrap();
11237
11238 apply_task_choice_actions(&queue, &questions, &home);
11241 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11242 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
11243
11244 let mut again = queue.get(&t.id).unwrap();
11246 again.hold_machine(Some("later".into()));
11247 queue.put(&mut again).unwrap();
11248 apply_task_choice_actions(&queue, &questions, &home);
11249 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11250 }
11251
11252 #[test]
11253 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
11254 let dir = tempfile::tempdir().unwrap();
11255 let queue = Queue::at(dir.path().join("queue"));
11256 let questions = Questions::at(dir.path().join("questions"));
11257 let home = dir.path().join("home");
11258 let mut state = run_state(RunStatus::Blocked);
11259 state.id = "20260101-000000-act3".to_owned();
11260 state.save_under(&home).unwrap();
11261 let mut t = held_task_with(&state.id);
11262 queue.put(&mut t).unwrap();
11263 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
11264 questions.put(&mut q).unwrap();
11265
11266 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
11267 apply_task_choice_actions(&queue, &questions, &home);
11268 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11269
11270 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11271 apply_task_choice_actions(&queue, &questions, &home);
11272 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11273 }
11274
11275 #[test]
11276 fn action_standing_tells_the_reasons_apart() {
11277 let mut t = held_task_with("r1");
11278 let q = action_question("r1", ask::ChoiceAction::Requeue);
11279 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
11280 let mut plain = q.clone();
11281 plain.actions.clear();
11282 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
11283
11284 t.mark_action_applied(&q.id);
11286 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
11287
11288 let mut t = held_task_with("r1");
11290 t.start("r2".to_owned());
11291 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
11292 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
11294 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11295 t.status = TaskStatus::Blocked;
11296 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11297
11298 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
11300 c.node = crate::conduct::NODE.to_owned();
11301 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
11302 assert!(!ActionStanding::Busy.daemon_owns());
11303 }
11304
11305 #[test]
11306 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
11307 let dir = tempfile::tempdir().unwrap();
11308 let queue = Queue::at(dir.path().join("queue"));
11309 let questions = Questions::at(dir.path().join("questions"));
11310 let home = dir.path().join("home");
11311 let mut state = run_state(RunStatus::Blocked);
11312 state.id = "20260101-000000-act4".to_owned();
11313 state.save_under(&home).unwrap();
11314 let mut t = held_task_with(&state.id);
11315 t.status = TaskStatus::Running;
11316 queue.put(&mut t).unwrap();
11317 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11318 q.cwd = Some(dir.path().display().to_string());
11319 questions.put(&mut q).unwrap();
11320
11321 let running = queue.get(&t.id).unwrap();
11324 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
11325 assert!(matches!(
11326 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
11327 crate::waiter::Action::Deliver(_)
11328 ));
11329 apply_task_choice_actions(&queue, &questions, &home);
11331 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11332 let mut back = queue.get(&t.id).unwrap();
11333 back.hold_machine(Some("later".into()));
11334 queue.put(&mut back).unwrap();
11335 apply_task_choice_actions(&queue, &questions, &home);
11336 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
11337 let mut again = queue.get(&t.id).unwrap();
11338 again.hold_machine(Some("again".into()));
11339 queue.put(&mut again).unwrap();
11340 apply_task_choice_actions(&queue, &questions, &home);
11341 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11342 }
11343}