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 && !s.released() {
947 ActionDecision::Resume(run.clone())
948 } else {
949 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
950 }
951 }
952 Ok(s)
953 if q.node == land::APPROVAL_NODE
954 && q.resolution().as_deref() == Some(land::REPAIR) =>
955 {
956 if s.merge_repairs.iter().any(|r| r.question == q.id)
957 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
958 {
959 ActionDecision::Stale
962 } else if s.liveness(false) == Liveness::Live {
963 ActionDecision::Skip
964 } else if s.status != RunStatus::Landing
965 || s.released()
966 || s.reviews.is_empty()
967 || !implementers_match(task, &s)
968 || !s
969 .land_approval
970 .as_ref()
971 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
972 {
973 ActionDecision::Refuse(format!(
974 "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",
975 q.id, run, run
976 ))
977 } else {
978 ActionDecision::Resume(run.clone())
979 }
980 }
981 Ok(s) if s.liveness(false) == Liveness::Live => {
982 ActionDecision::Refuse("run already has a live driver".into())
983 }
984 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
985 ActionDecision::Resume(run.clone())
986 }
987 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
988 q.short(),
989 ask::short_id(run),
990 )),
991 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
992 q.short(),
993 ask::short_id(run),
994 &format!("{e:#}"),
995 )),
996 }
997 }
998 }
999}
1000
1001struct Phrases {
1015 graph_stopped: fn(&str, &str) -> String,
1017 quorum_lost: &'static str,
1018 quota_took_out: &'static str,
1020 run_ended: &'static str,
1022 waiting_for_answer: &'static str,
1024 recovered_running: &'static str,
1025 no_run_to_recover: &'static str,
1026 could_not_start: &'static str,
1027 resume_not_latest: fn(&str, &str) -> String,
1028 resume_cannot_progress: fn(&str, &str) -> String,
1029 resume_unreadable: fn(&str, &str, &str) -> String,
1030 handover_refused: fn(&crate::handover::Refused) -> String,
1033 handover_hint: &'static str,
1035 reviewers_never_answered: fn(usize, usize) -> String,
1038}
1039
1040const PHRASES_EN: Phrases = Phrases {
1041 graph_stopped: |status, detail| {
1042 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1043 },
1044 quorum_lost: "the judging panel lost its quorum",
1045 quota_took_out: "; quota took out ",
1046 run_ended: "run ended ",
1047 waiting_for_answer: " - waiting for operator answer to question ",
1048 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1049 no_run_to_recover: "task was `running` with no live daemon and no readable \
1050 run to recover; held for a human to check what happened",
1051 could_not_start: "could not start the run: ",
1052 resume_not_latest: |q, run| {
1053 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1054 },
1055 resume_cannot_progress: |q, run| {
1056 format!("question {q} asked to resume run {run}, which cannot make progress")
1057 },
1058 resume_unreadable: |q, run, e| {
1059 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1060 },
1061 handover_refused: |r| r.to_string(),
1062 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1063 reviewers_never_answered: |missing, rounds| {
1064 format!(
1065 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1066 refusing to call it clean"
1067 )
1068 },
1069};
1070
1071const PHRASES_JA: Phrases = Phrases {
1072 graph_stopped: |status, detail| {
1073 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1074 },
1075 quorum_lost: "審査パネルが定足数を失いました",
1076 quota_took_out: "。クォータで脱落: ",
1077 run_ended: "run 終了: ",
1078 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1079 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1080 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1081 何が起きたか人が確認するため保留にしました",
1082 could_not_start: "run を開始できませんでした: ",
1083 resume_not_latest: |q, run| {
1084 format!(
1085 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1086 )
1087 },
1088 resume_cannot_progress: |q, run| {
1089 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1090 },
1091 resume_unreadable: |q, run, e| {
1092 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1093 },
1094 handover_refused: |r| {
1095 use crate::handover::Refused;
1096 match r {
1097 Refused::Foreign { branch, path, why } => format!(
1098 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1099 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1100 から、やり直してください(詳細: {why})"
1101 ),
1102 Refused::Unsafe { branch, path, why } => format!(
1103 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1104 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1105 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1106 ),
1107 Refused::ReleaseFailed { branch, path, run } => format!(
1108 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1109 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1110 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1111 ),
1112 }
1113 },
1114 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1115 reviewers_never_answered: |missing, rounds| {
1116 format!(
1117 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1118 クリーンとは認めません"
1119 )
1120 },
1121};
1122
1123fn phrases(language: &str) -> &'static Phrases {
1124 if crate::lang::is_japanese(language) {
1125 &PHRASES_JA
1126 } else {
1127 &PHRASES_EN
1128 }
1129}
1130
1131fn language_of(task: &Task, fallback: &Path) -> String {
1135 crate::lang::of_repo(&repo_for(task, fallback))
1136}
1137
1138pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1142 if q.node == crate::conduct::NODE {
1143 return tasks.iter().find(|t| t.id == q.run);
1144 }
1145 tasks.iter().find(|t| t.runs.contains(&q.run))
1146}
1147
1148fn repair_choice_offers(questions: &Questions) {
1151 for q in questions.list().into_iter().filter(|q| {
1152 q.status.open()
1153 && q.node == crate::conduct::NODE
1154 && q.choices
1155 .iter()
1156 .any(|c| crate::choice_effect::describe(q, c).is_none())
1157 }) {
1158 let _ = questions.update(&q.id, |current| {
1159 if current.status.open() {
1160 crate::choice_effect::executable_conductor(current);
1161 if let Some(deputy) = &mut current.deputy {
1162 deputy.brief = crate::deputy::brief(
1163 ¤t.run,
1164 ¤t.detail,
1165 ¤t.choices,
1166 ¤t.actions,
1167 );
1168 }
1169 }
1170 Ok(())
1171 });
1172 }
1173}
1174
1175pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1178 apply_maintenance_choices(queue, questions, home).await;
1179 apply_task_choice_actions(queue, questions, home);
1180}
1181
1182async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1185 use crate::release_watch::{GhForge, ReleaseForge};
1186 for q in questions.list() {
1187 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1188 continue;
1189 };
1190 if asker_may_still_read(questions, &q, home) || !crate::run::is_run_id(&q.id) {
1191 continue;
1192 }
1193 let dir = home.join("choice-actions");
1194 if std::fs::create_dir_all(&dir).is_err() {
1195 continue;
1196 }
1197 let Ok(lock) = std::fs::OpenOptions::new()
1198 .create(true)
1199 .truncate(false)
1200 .write(true)
1201 .open(dir.join(format!("{}.lock", q.id)))
1202 else {
1203 continue;
1204 };
1205 if crate::pr_head::try_lock_file(&lock).is_err() {
1206 continue;
1207 }
1208 let fresh = !home
1209 .join("choice-actions")
1210 .join(format!("{}.json", q.id))
1211 .exists();
1212 let result = async {
1213 let receipt = dir.join(format!("{}.json", q.id));
1214 if receipt.exists() {
1215 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1216 anyhow::ensure!(
1217 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1218 "previous maintenance attempt did not confirm completion; inspect its receipt"
1219 );
1220 return Ok::<_, anyhow::Error>(());
1221 }
1222 let record = |status: &str| -> anyhow::Result<()> {
1225 let tmp = receipt.with_extension("tmp");
1226 std::fs::write(
1227 &tmp,
1228 serde_json::to_vec(&serde_json::json!({
1229 "action": action, "status": status,
1230 }))?,
1231 )?;
1232 std::fs::rename(tmp, &receipt)?;
1233 Ok(())
1234 };
1235 let applied = async {
1236 match action {
1237 ask::ChoiceAction::ResumeRun { run } => {
1238 crate::resume::validate(home, run)?;
1239 record("started")?;
1240 if let Some(listed) = queue
1241 .list()
1242 .into_iter()
1243 .find(|t| t.runs.last() == Some(run))
1244 {
1245 let _claim = queue.claim(&listed.id)?;
1246 let mut task = queue.get(&listed.id)?;
1247 anyhow::ensure!(
1248 task.runs.last() == Some(run)
1249 && !matches!(
1250 task.status,
1251 TaskStatus::Running | TaskStatus::Done
1252 ),
1253 "run queue owner changed"
1254 );
1255 anyhow::ensure!(
1256 !task.operator_held()
1257 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1258 "resume was superseded by an operator hold or newer operator decision"
1259 );
1260 task.release_operator("choice", Some(&q.id));
1261 task.resume_override = Some(crate::queue::OperatorResume {
1262 question_id: q.id.clone(),
1263 at: Timestamp::now(),
1264 conductor_rehold: None,
1265 forced: true,
1266 pinned_run: Some(run.clone()),
1267 });
1268 task.mark_action_applied(&q.id);
1269 queue.put(&mut task)?;
1270 } else {
1271 crate::resume::validate_unqueued(home, run)?;
1272 crate::resume::start(run.clone());
1273 }
1274 }
1275 ask::ChoiceAction::ReleaseTask {
1276 task,
1277 held_at,
1278 reason,
1279 } => {
1280 anyhow::ensure!(
1281 queue.resolve_id(task)? == *task,
1282 "task action requires an exact task ID"
1283 );
1284 let _claim = queue.claim(task)?;
1285 let mut task = queue.get(task)?;
1286 if task.action_applied(&q.id) {
1287 return Ok(());
1288 }
1289 if q.node == crate::conduct::NODE
1294 && q.run == task.id
1295 && task.status == TaskStatus::Blocked
1296 && task.blocked_from == Some(TaskStatus::Held)
1297 && task.blocked_by.as_slice() == [q.id.as_str()]
1298 {
1299 task.unblock(&q.id);
1300 }
1301 anyhow::ensure!(
1302 task.status == TaskStatus::Held
1303 && task.held_at == Some(*held_at)
1304 && task.hold_reason.as_deref() == reason.as_deref()
1305 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1306 "task no longer has the hold this question names"
1307 );
1308 task.release_operator("choice", Some(&q.id));
1309 task.mark_action_applied(&q.id);
1310 queue.put(&mut task)?;
1311 }
1312 ask::ChoiceAction::AbandonRun { run } => {
1313 record("started")?;
1314 crate::driver::abandon_proven_dead(home, run)?;
1315 }
1316 ask::ChoiceAction::RerunChecks {
1317 repo,
1318 pr,
1319 head,
1320 runs,
1321 } => {
1322 anyhow::ensure!(
1323 !runs.is_empty()
1324 && runs.len() <= 20
1325 && runs
1326 .iter()
1327 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1328 && !pr.starts_with('-'),
1329 "invalid rerun targets"
1330 );
1331 let snap = GhForge.snapshot(repo, pr).await?;
1332 anyhow::ensure!(
1333 snap.head == *head && snap.state == crate::land::PrLifecycle::Open,
1334 "pull request head or lifecycle changed"
1335 );
1336 anyhow::ensure!(
1337 runs.iter().all(|r| snap
1338 .checks
1339 .iter()
1340 .any(|c| c.run.as_ref() == Some(r)
1341 && crate::release_watch::is_failed(c.verdict))),
1342 "named workflow is no longer failed on this pull request"
1343 );
1344 record("started")?;
1345 let rerun_lock = std::fs::OpenOptions::new()
1346 .create(true)
1347 .truncate(false)
1348 .write(true)
1349 .open(dir.join("reruns.lock"))?;
1350 crate::pr_head::try_lock_file(&rerun_lock)?;
1351 let ledger = dir.join("reruns.json");
1352 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1353 serde_json::from_slice(&std::fs::read(&ledger)?)?
1354 } else {
1355 Default::default()
1356 };
1357 for run in runs {
1358 let key = serde_json::to_string(&(&q.id, repo, pr, head, run))?;
1359 if !recorded.insert(key) {
1360 continue;
1361 }
1362 let tmp = ledger.with_extension("tmp");
1363 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1364 std::fs::rename(tmp, &ledger)?;
1365 GhForge.rerun(repo, run).await?;
1366 }
1367 }
1368 _ => unreachable!(),
1369 }
1370 Ok::<_, anyhow::Error>(())
1371 }
1372 .await;
1373 match applied {
1374 Ok(()) => record("applied"),
1375 Err(e) => {
1376 record(&format!("refused or failed: {e:#}"))?;
1377 Err(e)
1378 }
1379 }
1380 }
1381 .await;
1382 if home
1387 .join("choice-actions")
1388 .join(format!("{}.json", q.id))
1389 .exists()
1390 && let Some(listed) = task_of_question(&queue.list(), &q)
1391 && !listed.action_applied(&q.id)
1392 && let Ok(_claim) = queue.claim(&listed.id)
1393 && let Ok(mut origin) = queue.get(&listed.id)
1394 {
1395 if !origin.operator_held()
1396 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1397 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1398 {
1399 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1400 origin.hold_machine(Some(format!(
1401 "Maintenance choice {} settled; inspect its target before releasing this task",
1402 q.id
1403 )));
1404 } else {
1405 origin.unblock(&q.id);
1406 }
1407 }
1408 origin.mark_action_applied(&q.id);
1409 let _ = queue.put(&mut origin);
1410 }
1411 if let Err(e) = result
1412 && fresh
1413 {
1414 notices::raise_in(
1415 home,
1416 Notice::warn(
1417 &format!("action:{}", q.id),
1418 format!("Choice action {} was not completed: {e:#}", q.id),
1419 ),
1420 );
1421 }
1422 }
1423}
1424
1425pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1434 let tasks = queue.list();
1435 for q in questions.list() {
1436 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1438 continue;
1439 }
1440 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1441 continue;
1442 }
1443 let Some(listed) = task_of_question(&tasks, &q) else {
1444 if q.node == land::APPROVAL_NODE
1445 && q.resolution().as_deref().is_some_and(|choice| {
1446 choice == land::REPAIR || crate::merge_decision::stops(choice)
1447 })
1448 {
1449 notices::raise_in(
1450 home,
1451 Notice::warn(
1452 &format!("repair-owner:{}", q.id),
1453 format!(
1454 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1455 q.run, q.run
1456 ),
1457 ),
1458 );
1459 }
1460 continue;
1461 };
1462 if listed.action_applied(&q.id) {
1463 continue;
1464 }
1465 let Ok(_claim) = queue.claim(&listed.id) else {
1466 continue;
1467 };
1468 let Ok(mut task) = queue.get(&listed.id) else {
1469 continue;
1470 };
1471 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1474 let blockers: Vec<_> = task
1475 .blocked_by
1476 .iter()
1477 .filter(|id| {
1478 crate::queue::dependency(queue, questions, id)
1479 == crate::queue::Dependency::Question(q.id.clone())
1480 })
1481 .cloned()
1482 .collect();
1483 if !blockers.is_empty() {
1484 for id in blockers {
1485 task.unblock(&id);
1486 }
1487 let answer = match &q.answer {
1488 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1489 None => String::new(),
1490 };
1491 task.record_answer(q.summary.clone(), answer);
1492 }
1493 }
1494 let language = language_of(&task, Path::new("."));
1495 let decision = decide_action(&task, &q, phrases(&language), |id| {
1496 RunState::load_under(id, home)
1497 });
1498 let ran = matches!(
1499 decision,
1500 ActionDecision::Resume(_)
1501 | ActionDecision::Requeue
1502 | ActionDecision::Hold
1503 | ActionDecision::Done
1504 );
1505 if ran && asker_may_still_read(questions, &q, home) {
1506 continue;
1515 }
1516 let done = matches!(decision, ActionDecision::Done);
1517 match decision {
1518 ActionDecision::Skip => continue,
1519 ActionDecision::Resume(run) => {
1520 task.release_operator("choice", Some(&q.id));
1521 task.resume_override = Some(crate::queue::OperatorResume {
1522 question_id: q.id.clone(),
1523 at: Timestamp::now(),
1524 conductor_rehold: None,
1525 forced: true,
1526 pinned_run: Some(run),
1527 });
1528 }
1529 ActionDecision::Stale => {}
1530 ActionDecision::Requeue => {
1531 task.release_operator("choice-requeue", Some(&q.id));
1532 task.requeue();
1533 }
1534 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1535 ActionDecision::Done => task.succeed(),
1536 ActionDecision::Refuse(why) => {
1537 if task.operator_held() {
1538 task.hold_reason = Some(match task.hold_reason.take() {
1541 Some(reason) => format!("{reason}\n\n{why}"),
1542 None => why,
1543 });
1544 } else {
1545 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1546 task.hold_machine(Some(why));
1547 }
1548 notices::raise(
1549 Notice::warn(
1550 &format!("action:{}", q.id),
1551 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1552 )
1553 .link(Link::Task {
1554 id: task.id.clone(),
1555 }),
1556 );
1557 }
1558 }
1559 task.mark_action_applied(&q.id);
1560 record(queue, &mut task);
1563 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1564 supersede_prior_runs(&task, home);
1565 }
1566 let _ = questions.update(&q.id, |r| {
1569 r.answer_delivered = true;
1570 Ok(())
1571 });
1572 }
1573}
1574
1575fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1579 let now = Timestamp::now();
1580 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1581 return true;
1582 }
1583 q.node != crate::conduct::NODE
1584 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1585 s.seats_active()
1586 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1587 })
1588}
1589
1590fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1601 let tasks = queue.list();
1602 let by_id: std::collections::BTreeMap<&str, &Task> =
1603 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1604 let referenced: Vec<&str> = tasks
1605 .iter()
1606 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1607 .collect();
1608
1609 for mut question in questions.list() {
1610 if !question.status.open() || question.node != crate::conduct::NODE {
1611 continue;
1612 }
1613 if referenced
1618 .iter()
1619 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1620 {
1621 continue;
1622 }
1623 let Some(task) = by_id.get(question.run.as_str()) else {
1624 continue;
1625 };
1626 question.abandon(format!(
1627 "task {} no longer waits for this answer",
1628 task.short()
1629 ));
1630 if let Err(e) = questions.put(&mut question) {
1631 tracing::warn!(
1632 "could not retire question {} for task {}: {e:#}",
1633 question.short(),
1634 task.short()
1635 );
1636 }
1637 }
1638}
1639
1640#[derive(Debug, Clone, Copy)]
1647pub struct Verdict {
1648 pub status: RunStatus,
1650 pub left_pr: bool,
1652 pub quota_hit: bool,
1654 pub parked: bool,
1656 pub no_viable_candidates: bool,
1663}
1664
1665pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1722 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1723}
1724
1725fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1727 if verdict.parked {
1733 task.park(detail);
1734 return;
1735 }
1736 match verdict.status {
1737 RunStatus::Merged | RunStatus::Ready
1738 if task.pr_recovery.as_ref().is_some_and(|s| {
1739 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1740 }) =>
1741 {
1742 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()));
1743 }
1744 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1745 RunStatus::AlreadyInBase => task.already_landed(detail),
1746 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1747 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1748 task.stall(detail)
1749 }
1750 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1751 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1752 RunStatus::Blocked => task.fail(detail, max_attempts),
1753 RunStatus::VerifiedNoop => task.handed_off(detail),
1754 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1755 }
1756}
1757
1758pub fn supersede_prior_runs(task: &Task, home: &Path) {
1807 let now = Timestamp::now();
1808 let last_run_succeeded = task
1815 .runs
1816 .last()
1817 .and_then(|id| RunState::load_under(id, home).ok())
1818 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1819 for id in task.superseded_attempts(last_run_succeeded) {
1820 let mut state = match RunState::load_under(id, home) {
1821 Ok(s) => s,
1822 Err(e) => {
1823 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1824 continue;
1825 }
1826 };
1827 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1828 continue;
1829 }
1830 let daemon_claims = is_working_on(home, id, now);
1831 if state.liveness(daemon_claims) == Liveness::Live {
1832 continue;
1833 }
1834 state.status = RunStatus::Superseded;
1835 if let Err(e) = state.save_under(home) {
1836 tracing::warn!("could not mark run {id} superseded: {e:#}");
1837 }
1838 }
1839}
1840
1841fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1863 for task in queue.list() {
1864 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1865 continue;
1866 }
1867 supersede_prior_runs(&task, home);
1868 }
1869}
1870
1871fn settle_and_diagnose(
1878 task: &mut Task,
1879 verdict: Verdict,
1880 detail: &str,
1881 max_attempts: usize,
1882 state: &RunState,
1883) {
1884 let p = phrases(&state.config.graph.language);
1885 if let Some(d) = &state.merge_decision {
1888 use crate::merge_decision as md;
1889 if task.runs.last().is_some_and(|id| id != &state.id) {
1890 return;
1891 }
1892 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1893 task.succeed();
1894 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1895 if state.liveness(false) != Liveness::Dead {
1896 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1897 return;
1898 }
1899 let replacement = md::Replacement {
1900 question: d.question.clone(),
1901 run: state.id.clone(),
1902 pr: d.target.pr.clone(),
1903 agent: agent.to_owned(),
1904 context: format!(
1905 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1906 d.target.pr,
1907 state.id,
1908 serde_json::to_string(&state.reviews).unwrap_or_default()
1909 ),
1910 };
1911 task.requeue();
1912 task.pr_recovery = None;
1913 task.review_of = None;
1914 task.replacement = Some(replacement);
1915 } else {
1916 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1917 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1918 } 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())) }));
1919 }
1920 task.mark_action_applied(&d.question);
1921 if let Some(pass) = state.passes.last() {
1922 task.record_pass(&state.id, pass.index, task.attempts, None);
1923 }
1924 return;
1925 }
1926 if let Some(replacement) = &task.replacement
1927 && !state.parked
1928 && state.resource_block.is_none()
1929 && (state.viable().is_empty()
1930 || (state.status == RunStatus::Blocked && state.tally.is_none()))
1931 {
1932 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)));
1933 return;
1934 }
1935 let attempts_before = task.attempts;
1936 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1942 task.notice_cause(
1943 &format!("resource:{}:{}", block.kind, block.node),
1944 None,
1945 None,
1946 );
1947 task.last_error = Some(detail.to_owned());
1948 task.diagnostic = None;
1949 task.attempts = task.attempts.saturating_sub(1);
1950 task.hold_machine(Some(format!(
1951 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1952 no agent was asked and no attempt was spent",
1953 crate::cache::RESOURCE_HOLD,
1954 block.kind,
1955 block.node
1956 )));
1957 if let Some(pass) = state.passes.last() {
1958 task.record_pass(&state.id, pass.index, attempts_before, None);
1959 }
1960 return;
1961 }
1962 let unresolved = task.hold_notice_cause.clone();
1963 if !verdict.parked
1964 && task
1965 .pr_recovery
1966 .as_ref()
1967 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1968 && matches!(
1969 verdict.status,
1970 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1971 )
1972 {
1973 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1974 task.succeed();
1975 } else {
1976 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()));
1977 }
1978 } else if !verdict.parked
1979 && task.pr_recovery.is_some()
1980 && matches!(
1981 verdict.status,
1982 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
1983 )
1984 && !verdict.quota_hit
1985 {
1986 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.")));
1987 } else {
1988 settle_in(task, verdict, detail, max_attempts, p);
1989 }
1990 if state.prep_failure.is_some() {
1991 task.hold_notice_cause = unresolved;
1994 task.startup_notice_cause("startup-candidates");
1995 }
1996 if let Some(pass) = state.passes.last() {
1999 let parked = match &pass.end {
2000 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2001 _ => None,
2002 };
2003 task.record_pass(&state.id, pass.index, attempts_before, parked);
2004 }
2005 if task.status == TaskStatus::Held {
2006 if state.prep_failure.is_none() {
2007 task.notice_cause(
2008 label(verdict.status),
2009 Some(&state.id),
2010 state.passes.last().map(|p| p.index),
2011 );
2012 }
2013 task.diagnostic = diagnostic(state);
2014 note_open_question(task, &state.id, p);
2015 }
2016}
2017
2018fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2033 let Some(home) = crate::run::try_home() else {
2034 return;
2035 };
2036 let open = Questions::at(home.join("questions")).open_for(run);
2037 let Some(q) = open.first() else {
2038 return;
2039 };
2040 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2041 decisions.sort_unstable();
2042 task.notice_cause(
2043 &format!("questions:{}", decisions.join(",")),
2044 Some(run),
2045 None,
2046 );
2047 let base = task.hold_reason.clone().unwrap_or_default();
2048 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2049}
2050
2051fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2062 match last_run {
2063 Some(state) => {
2064 let verdict = Verdict {
2065 status: state.status,
2066 left_pr: state.pr.is_some(),
2067 quota_hit: !state.quota.is_empty(),
2068 parked: state.parked,
2069 no_viable_candidates: state.viable().is_empty(),
2070 };
2071 let detail = format!(
2072 "{}{}",
2073 phrases(&state.config.graph.language).recovered_running,
2074 describe(&state)
2075 );
2076 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2077 }
2078 None => {
2079 let why = phrases(language).no_run_to_recover;
2082 task.last_error = Some(why.to_owned());
2083 task.notice_cause("missing-run", None, None);
2086 task.hold_machine(Some(why.to_owned()));
2087 }
2088 }
2089}
2090
2091fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2113 let mut reclaimed = Vec::new();
2114 for listed in queue.list() {
2115 if listed.status != TaskStatus::Running {
2116 continue;
2117 }
2118 let Ok(_claim) = queue.claim(&listed.id) else {
2119 continue;
2120 };
2121 let Ok(mut task) = queue.get(&listed.id) else {
2125 continue;
2126 };
2127 if task.status != TaskStatus::Running {
2128 continue;
2129 }
2130 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2131 if let Some(state) = &last_run
2141 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2142 {
2143 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2144 }
2145 let language = if last_run.is_none() {
2146 language_of(&task, Path::new("."))
2147 } else {
2148 String::new()
2149 };
2150 reclaim(&mut task, last_run, max_attempts, &language);
2151 if task.status == TaskStatus::Done {
2152 supersede_prior_runs(&task, &crate::run::home());
2153 }
2154 record(queue, &mut task);
2155 reclaimed.push(task.id.clone());
2156 }
2157 reclaimed
2158}
2159
2160fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2192 reclaim_abandoned_runs_with(
2193 home,
2194 now,
2195 crate::proc::pid_status,
2196 crate::proc::process_started_at,
2197 )
2198}
2199
2200fn reclaim_abandoned_runs_with<F, G>(
2206 home: &Path,
2207 now: Timestamp,
2208 query: F,
2209 identity: G,
2210) -> Vec<String>
2211where
2212 F: Fn(u32) -> Option<bool>,
2213 G: Fn(u32) -> Option<String>,
2214{
2215 let mut abandoned = Vec::new();
2216 for entry in std::fs::read_dir(home.join("runs"))
2217 .into_iter()
2218 .flatten()
2219 .flatten()
2220 {
2221 let id = entry.file_name().to_string_lossy().into_owned();
2222 if !crate::run::is_run_id(&id) {
2223 continue;
2224 }
2225 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2228 continue;
2229 };
2230 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2238 continue;
2239 };
2240 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2241 continue;
2242 };
2243 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2244 continue;
2245 }
2246 let daemon_claims = is_working_on(home, &id, now);
2258 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2259 != crate::run::Liveness::Dead
2260 {
2261 continue;
2262 }
2263 state.abandon("daemon");
2264 if let Err(e) = state.save_under(home) {
2265 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2266 continue;
2267 }
2268 if let Some(notice) = notices::run_ended(&state) {
2271 notices::raise_in(home, notice);
2272 }
2273 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2281 tracing::warn!("abandon questions for {id}: {e:#}");
2282 }
2283 abandoned.push(id);
2284 }
2285 abandoned
2286}
2287
2288pub async fn serve(opts: Opts) -> Result<()> {
2294 serve_until(opts, Stop::new()).await
2295}
2296
2297pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2314 let signal = {
2315 let stop = stop.clone();
2316 tokio::spawn(async move {
2317 if tokio::signal::ctrl_c().await.is_ok() {
2318 stop.stop();
2319 tracing::info!("shutdown requested; a run in flight will be finished first");
2320 }
2321 })
2322 };
2323
2324 let worktrees_root = opts
2325 .worktrees_root
2326 .clone()
2327 .unwrap_or_else(crate::run::default_worktree_root);
2328 let outcome = drive(
2329 &opts,
2330 &Queue::open(),
2331 &status_path(),
2332 &crate::run::home(),
2333 &worktrees_root,
2334 &stop,
2335 )
2336 .await;
2337
2338 signal.abort();
2339 outcome
2340}
2341
2342async fn drive(
2355 opts: &Opts,
2356 queue: &Queue,
2357 status_file: &Path,
2358 home: &Path,
2359 worktrees_root: &Path,
2360 stop: &Stop,
2361) -> Result<()> {
2362 let recovery_cfg = prepare(&opts.repo, opts).ok();
2370 let daemon_cfg = recovery_cfg
2371 .as_ref()
2372 .map(|c| c.daemon.clone())
2373 .unwrap_or_default();
2374 let reconciled = crate::driver::reconcile(home);
2375 if !reconciled.is_empty() {
2376 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2377 }
2378 let mut initial_status = Status::new();
2379 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2380 recovery_cfg.as_ref(),
2381 daemon_cfg.max_deputies,
2382 ));
2383 let status = Arc::new(Mutex::new(initial_status));
2384 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2385 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2386
2387 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2393
2394 let waiter = tokio::spawn(crate::waiter::run(
2399 crate::waiter::Waiter::new(
2400 crate::ask::Questions::at(home.join("questions")),
2401 home.to_path_buf(),
2402 recovery_cfg.clone(),
2403 ),
2404 stop.clone(),
2405 ));
2406
2407 let deputies = tokio::spawn(crate::deputy::run(
2411 crate::deputy::Deputies::new(
2412 crate::ask::Questions::at(home.join("questions")),
2413 home.to_path_buf(),
2414 recovery_cfg.clone(),
2415 opts.repo.clone(),
2416 daemon_cfg.max_deputies,
2417 {
2418 let stop = stop.clone();
2419 Arc::new(move || stop.parking())
2420 },
2421 ),
2422 stop.clone(),
2423 ));
2424
2425 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2428
2429 let release_watch = tokio::spawn(crate::release_watch::run(
2432 crate::release_watch::Watcher::new(
2433 Box::new(crate::release_watch::GhForge),
2434 home.to_path_buf(),
2435 ),
2436 {
2437 let (repo, opts) = (opts.repo.clone(), opts.clone());
2438 move || release_watch_settings(&repo, &opts)
2439 },
2440 stop.clone(),
2441 ));
2442
2443 tracing::info!(
2444 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2445 queue.root().display(),
2446 opts.poll.as_secs(),
2447 opts.max_attempts,
2448 concurrency,
2449 if daemon_cfg.pause_for_interrupts {
2450 ", interrupts enabled"
2451 } else {
2452 ""
2453 }
2454 );
2455
2456 janitor(&opts.repo, opts, home, worktrees_root).await;
2459 resweep_superseded_attempts(queue, home);
2460
2461 let outcome = poll(
2462 opts,
2463 queue,
2464 &status,
2465 home,
2466 worktrees_root,
2467 stop,
2468 DispatchLimits {
2469 max_concurrent: concurrency,
2470 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2471 },
2472 )
2473 .await;
2474
2475 beat.abort();
2476 waiter.abort();
2477 deputies.abort();
2478 fetcher.abort();
2479 release_watch.abort();
2480 clear_status_at(status_file);
2481 outcome
2482}
2483
2484fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2487 let Ok(cfg) = prepare(repo, opts) else {
2488 return (Vec::new(), 0);
2489 };
2490 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2491 .into_iter()
2492 .map(|r| r.path)
2493 .collect();
2494 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2497 let runs = crate::run::home().join("runs");
2498 for id in crate::run::list_ids_in(&runs) {
2499 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2500 .ok()
2501 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2502 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2503 known.extend(repo);
2504 }
2505 for k in known {
2506 let k = k.canonicalize().unwrap_or(k);
2507 if k.join(".git").exists() && !paths.contains(&k) {
2508 paths.push(k);
2509 }
2510 }
2511 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2512 if !paths.contains(&own) {
2513 paths.push(own);
2514 }
2515 (paths, cfg.daemon.release_stall_minutes)
2516}
2517
2518const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2520
2521async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2525 while !stop.stopped() {
2526 let (interval, roots) = match prepare(&repo, &opts) {
2527 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2528 Err(_) => (0, Vec::new()),
2529 };
2530 if interval > 0 && !roots.is_empty() {
2531 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2532 tracing::debug!("fetch origins: {r:?}");
2533 }
2534 let wait = if interval > 0 { interval } else { 60 };
2536 let mut slept = 0;
2537 while slept < wait && !stop.stopped() {
2538 tokio::time::sleep(Duration::from_secs(1)).await;
2539 slept += 1;
2540 }
2541 }
2542}
2543
2544async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2550 loop {
2551 tokio::time::sleep(HEARTBEAT).await;
2552 let snapshot = {
2553 let mut guard = lock(&status);
2554 guard.updated_at = Timestamp::now();
2555 guard.clone()
2556 };
2557 if let Err(e) = write_status_to(&path, &snapshot) {
2558 tracing::warn!("could not refresh the daemon status file: {e:#}");
2561 }
2562 }
2563}
2564
2565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2568enum LandResume {
2569 NotLanding,
2572 StillWaiting,
2577 Ready,
2581}
2582
2583fn land_resume_state(task: &Task) -> LandResume {
2587 let Some(run_id) = task.runs.last() else {
2588 return LandResume::NotLanding;
2589 };
2590 let Ok(state) = RunState::load(run_id) else {
2591 return LandResume::NotLanding;
2592 };
2593 if !state.parked {
2594 return LandResume::NotLanding;
2595 }
2596 if state.status == RunStatus::Landing
2597 && state.land_approval.as_ref().is_some_and(|binding| {
2598 ask::Questions::open()
2599 .get(&binding.question)
2600 .is_ok_and(|q| {
2601 q.run == state.id
2602 && q.resolution()
2603 .as_deref()
2604 .is_some_and(crate::merge_decision::stops)
2605 })
2606 })
2607 {
2608 return LandResume::Ready;
2609 }
2610 if !implementers_match(task, &state) {
2611 return LandResume::NotLanding;
2612 }
2613 let node = if state.status == RunStatus::Landing {
2617 land::APPROVAL_NODE
2618 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2619 crate::github_text::ASK_NODE
2620 } else {
2621 return LandResume::NotLanding;
2622 };
2623 let store = ask::Questions::open();
2624 let waiting = store
2625 .list()
2626 .into_iter()
2627 .filter(|q| &q.run == run_id && q.node == node)
2628 .max_by(|a, b| a.id.cmp(&b.id));
2629 let Some(mut q) = waiting else {
2630 return LandResume::Ready;
2631 };
2632 if !q.status.open() {
2633 if q.resolution().as_deref() == Some(land::REPAIR) {
2636 return if state.liveness(false) == Liveness::Live {
2637 LandResume::StillWaiting
2638 } else {
2639 LandResume::NotLanding
2640 };
2641 }
2642 return LandResume::Ready;
2643 }
2644 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2651 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2652 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2653 q.abandon(format!(
2654 "no answer within {}s of asking",
2655 timeout.as_secs().max(1)
2656 ));
2657 if store.put(&mut q).is_ok() {
2660 return LandResume::Ready;
2661 }
2662 }
2663 LandResume::StillWaiting
2664}
2665
2666const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2674
2675const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2687
2688struct InFlightGuard<'a> {
2701 status: &'a Arc<Mutex<Status>>,
2702 stop: &'a Stop,
2703 task_id: &'a str,
2704}
2705
2706impl Drop for InFlightGuard<'_> {
2707 fn drop(&mut self) {
2708 lock(self.status).current.retain(|c| c.task != self.task_id);
2709 self.stop.exit();
2710 }
2711}
2712
2713#[derive(Debug, Clone, PartialEq, Eq)]
2735enum Interrupt {
2736 Idle,
2738 Parking {
2750 parked: Vec<String>,
2751 interrupt_task: String,
2752 },
2753 Running {
2761 parked: Vec<String>,
2762 interrupt_task: String,
2763 },
2764 Resuming { parked: Vec<String> },
2771}
2772
2773fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2794 match state {
2795 Interrupt::Idle => {
2796 if in_flight.len() != 1 {
2808 return Interrupt::Idle;
2809 }
2810 match runnable.iter().find(|t| t.interrupt) {
2811 Some(t) => Interrupt::Parking {
2812 parked: in_flight.to_vec(),
2813 interrupt_task: t.id.clone(),
2814 },
2815 None => Interrupt::Idle,
2816 }
2817 }
2818 Interrupt::Parking {
2819 parked,
2820 interrupt_task,
2821 } => {
2822 if in_flight.iter().any(|id| parked.contains(id)) {
2823 Interrupt::Parking {
2825 parked,
2826 interrupt_task,
2827 }
2828 } else if in_flight.contains(&interrupt_task) {
2829 Interrupt::Running {
2830 parked,
2831 interrupt_task,
2832 }
2833 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2834 Interrupt::Parking {
2838 parked,
2839 interrupt_task,
2840 }
2841 } else {
2842 Interrupt::Resuming { parked }
2847 }
2848 }
2849 Interrupt::Running {
2850 parked,
2851 interrupt_task,
2852 } => {
2853 if in_flight.contains(&interrupt_task) {
2854 Interrupt::Running {
2855 parked,
2856 interrupt_task,
2857 }
2858 } else {
2859 Interrupt::Resuming { parked }
2865 }
2866 }
2867 Interrupt::Resuming { parked } => {
2868 if in_flight.iter().any(|id| parked.contains(id)) {
2869 Interrupt::Idle
2875 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2876 Interrupt::Resuming { parked }
2877 } else {
2878 Interrupt::Idle
2881 }
2882 }
2883 }
2884}
2885
2886fn advance_interrupt_tick(
2892 enabled: bool,
2893 state: Interrupt,
2894 in_flight: &[String],
2895 runnable: &[Task],
2896) -> Interrupt {
2897 if !enabled {
2898 return Interrupt::Idle;
2899 }
2900 advance_interrupt(state, in_flight, runnable)
2901}
2902
2903fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2908 match state {
2909 Interrupt::Idle => candidates,
2910 Interrupt::Parking {
2911 parked,
2912 interrupt_task,
2913 } => {
2914 if in_flight.iter().any(|id| parked.contains(id)) {
2915 Vec::new()
2916 } else {
2917 candidates
2918 .into_iter()
2919 .filter(|t| &t.id == interrupt_task)
2920 .collect()
2921 }
2922 }
2923 Interrupt::Running { .. } => Vec::new(),
2924 Interrupt::Resuming { parked } => candidates
2932 .into_iter()
2933 .find(|t| parked.contains(&t.id))
2934 .into_iter()
2935 .collect(),
2936 }
2937}
2938
2939struct DispatchLimits {
2943 max_concurrent: usize,
2946 pause_for_interrupts: bool,
2948}
2949
2950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2959enum PermitKind {
2960 None,
2965 Urgent,
2972 Ordinary,
2975}
2976
2977fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2980 if priority {
2981 PermitKind::None
2982 } else if urgent {
2983 PermitKind::Urgent
2984 } else {
2985 PermitKind::Ordinary
2986 }
2987}
2988
2989struct DispatchClaim {
2990 task: Task,
2991 claim: crate::queue::Claim,
2992 permit: Option<tokio::sync::OwnedSemaphorePermit>,
2993}
2994
2995fn claim_dispatch(
2998 queue: &Queue,
2999 candidate: &Task,
3000 cooling_down: bool,
3001 ordinary: &Arc<tokio::sync::Semaphore>,
3002 urgent: &Arc<tokio::sync::Semaphore>,
3003) -> Option<DispatchClaim> {
3004 let Ok(claim) = queue.claim(&candidate.id) else {
3005 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3006 return None;
3007 };
3008 let task = match queue.get(&candidate.id) {
3009 Ok(t) if t.status.runnable() => t,
3010 Ok(_) => return None,
3011 Err(e) => {
3012 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3013 return None;
3014 }
3015 };
3016 let resume = land_resume_state(&task);
3017 if resume == LandResume::StillWaiting {
3018 return None;
3019 }
3020 let priority = resume == LandResume::Ready;
3021 if !priority && cooling_down {
3022 return None;
3023 }
3024 let permit = match permit_kind(priority, task.urgent) {
3027 PermitKind::None => None,
3028 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3029 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3030 };
3031 Some(DispatchClaim {
3032 task,
3033 claim,
3034 permit,
3035 })
3036}
3037
3038async fn poll(
3057 opts: &Opts,
3058 queue: &Queue,
3059 status: &Arc<Mutex<Status>>,
3060 home: &Path,
3061 worktrees_root: &Path,
3062 stop: &Stop,
3063 limits: DispatchLimits,
3064) -> Result<()> {
3065 let DispatchLimits {
3066 max_concurrent,
3067 pause_for_interrupts,
3068 } = limits;
3069 let mut attempted: Vec<String> = Vec::new();
3074 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3075 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3083 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3089 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3090 let mut conductor = Conductor::new();
3091 let mut cache_last_checked: Option<Timestamp> = None;
3094 let mut interrupt = Interrupt::Idle;
3096 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3102 std::collections::HashMap::new();
3103
3104 while !stop.stopped() {
3105 lock(status).polls += 1;
3106
3107 while let Some(result) = inflight.try_join_next() {
3112 if let Err(e) = result {
3113 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3114 notices::raise(Notice::error(
3115 "loop:attempt",
3116 "A queued attempt ended abnormally; check the task it was running.",
3117 ));
3118 }
3119 }
3120
3121 let swept = sweep_stale_claims(queue, STALE_CLAIM);
3122 if !swept.is_empty() {
3123 tracing::warn!(
3124 "swept {} stale claim(s) left behind by an earlier daemon: {}",
3125 swept.len(),
3126 swept.join(", ")
3127 );
3128 }
3129 let now = Timestamp::now();
3134
3135 if !stop.busy_now() {
3140 maybe_prune_cache_between_runs(
3141 &opts.repo,
3142 opts,
3143 home,
3144 stop,
3145 &mut cache_last_checked,
3146 now,
3147 )
3148 .await;
3149 }
3150
3151 let stalled = stalled_tasks(queue, home, now);
3152 let stalled_ids: std::collections::BTreeSet<_> =
3153 stalled.iter().map(|task| task.id.clone()).collect();
3154 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3155 if !reclaimed.is_empty() {
3156 tracing::warn!(
3157 "reclaimed {} task(s) left `running` by a daemon that never \
3158 recorded the outcome: {}",
3159 reclaimed.len(),
3160 reclaimed.join(", ")
3161 );
3162 }
3163 let abandoned_runs = reclaim_abandoned_runs(home, now);
3164 if !abandoned_runs.is_empty() {
3165 tracing::warn!(
3166 "failed {} run(s) left behind by a killed process, past every \
3167 active seat's own timeout: {}",
3168 abandoned_runs.len(),
3169 abandoned_runs.join(", ")
3170 );
3171 }
3172
3173 let questions = Questions::at(home.join("questions"));
3178
3179 repair_choice_offers(&questions);
3182 resolve_blockers(queue, &questions);
3183 apply_choice_actions(queue, &questions, home).await;
3184 triage::apply_answers(queue, &questions);
3185 reconcile_task_questions(queue, &questions);
3186 {
3190 let talks = crate::talk::Talks::at(home.join("talks"));
3191 crate::chat_notify::sweep(queue, &talks, home);
3192 crate::chat_watch::sweep(home, &talks);
3193 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3194 }
3195
3196 let finished: Vec<Task> = finished_tasks(queue)
3202 .into_iter()
3203 .filter(|task| !stalled_ids.contains(&task.id))
3204 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3208 .collect();
3209 let queued = queued_tasks(queue);
3210 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3214 && conductor.worth_a_look(queue, &stalled, &finished)
3215 {
3216 match prepare(&opts.repo, opts) {
3217 Ok(cfg) => {
3218 conductor
3219 .maybe_run(
3220 &cfg,
3221 &opts.repo,
3222 queue,
3223 &questions,
3224 home,
3225 &queued,
3226 &stalled,
3227 &finished,
3228 opts.max_attempts,
3229 )
3230 .await;
3231 }
3232 Err(e) => {
3233 tracing::warn!("conductor: no config: {e:#}");
3234 notices::raise(Notice::warn(
3235 "loop:no-config",
3236 "The loop could not read this repository's config, so held tasks are not being triaged.",
3237 ));
3238 }
3239 }
3240 }
3241
3242 let candidates: Vec<Task> = runnable(queue)
3243 .into_iter()
3244 .filter(|t| !opts.once || !attempted.contains(&t.id))
3245 .collect();
3246
3247 let in_flight: Vec<String> = lock(status)
3252 .current
3253 .iter()
3254 .map(|c| c.task.clone())
3255 .collect();
3256 interrupt_pauses.retain(|id, _| in_flight.contains(id));
3257
3258 interrupt =
3259 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3260 if let Interrupt::Parking {
3261 parked,
3262 interrupt_task,
3263 } = &interrupt
3264 {
3265 let reason = format!(
3266 "task {} asked to run first",
3267 crate::run::short_of(interrupt_task)
3268 );
3269 for id in parked {
3270 if let Some(pause) = interrupt_pauses.get(id) {
3271 pause.park_because(reason.clone());
3272 }
3273 }
3274 }
3275 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3276
3277 let cooling_down =
3278 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3279
3280 let mut started_any = false;
3281 for candidate in candidates {
3282 if stop.stopped() {
3283 break;
3284 }
3285
3286 let Some(DispatchClaim {
3287 mut task,
3288 claim,
3289 permit,
3290 }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3291 else {
3292 continue;
3293 };
3294
3295 let task_id = task.id.clone();
3296 attempted.push(task_id.clone());
3297 lock(status).idle = false;
3298 stop.enter();
3301 started_any = true;
3302
3303 let run_pause = crate::graph::Pause::new();
3307 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3308
3309 let opts = opts.clone();
3310 let queue = queue.clone();
3311 let status = Arc::clone(status);
3312 let stop = stop.clone();
3313 let quota_cooldown_until = Arc::clone("a_cooldown_until);
3314 inflight.spawn(async move {
3315 let _claim = claim;
3319 let _permit = permit;
3320 let _inflight = InFlightGuard {
3322 status: &status,
3323 stop: &stop,
3324 task_id: &task_id,
3325 };
3326 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3327 lock(&status).completed += 1;
3328 let now = Timestamp::now();
3334 if let Some(until) = cooldown_until("a, now) {
3335 let wait = until.as_second() - now.as_second();
3336 *lock("a_cooldown_until) = Some(until);
3337 let hint = quota
3338 .iter()
3339 .find(|q| q.reset.is_some())
3340 .and_then(|q| q.reset.as_deref());
3341 match hint {
3342 Some(h) => tracing::warn!(
3343 "quota hit; waiting {wait}s before taking another ordinary task \
3344 (CLI reported reset: {h})"
3345 ),
3346 None => tracing::warn!(
3347 "quota hit; waiting {wait}s before taking another ordinary task \
3348 (no reset hint reported)"
3349 ),
3350 }
3351 }
3352 });
3353 }
3354
3355 if started_any {
3356 continue;
3357 }
3358
3359 if stop.busy_now() {
3360 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3365 continue;
3366 }
3367
3368 lock(status).idle = true;
3370 if opts.once {
3371 janitor(&opts.repo, opts, home, worktrees_root).await;
3375 resweep_superseded_attempts(queue, home);
3376 triage_held(queue, home, opts).await;
3377 break;
3378 }
3379 stop.idle(opts.poll).await;
3380 if stop.stopped() {
3381 continue;
3382 }
3383 janitor(&opts.repo, opts, home, worktrees_root).await;
3389 resweep_superseded_attempts(queue, home);
3390 triage_held(queue, home, opts).await;
3391 }
3392
3393 while let Some(result) = inflight.join_next().await {
3398 if let Err(e) = result {
3399 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3400 notices::raise(Notice::error(
3401 "loop:attempt",
3402 "A queued attempt ended abnormally; check the task it was running.",
3403 ));
3404 }
3405 }
3406 Ok(())
3407}
3408
3409async fn attempt(
3415 opts: &Opts,
3416 queue: &Queue,
3417 status: &Arc<Mutex<Status>>,
3418 stop: &Stop,
3419 interrupt_pause: crate::graph::Pause,
3420 task: &mut Task,
3421) -> Vec<QuotaLoss> {
3422 let repo = repo_for(task, &opts.repo);
3423 tracing::info!(
3424 "task {} — {} (repo {})",
3425 task.short(),
3426 task.title,
3427 repo.display()
3428 );
3429
3430 if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3434 && previous
3435 .merge_decision
3436 .as_ref()
3437 .is_some_and(|decision| !decision.closed)
3438 && previous.status != RunStatus::Landing
3439 && !crate::merge_decision::resumable_hold(&previous)
3440 {
3441 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)));
3442 record(queue, task);
3443 return Vec::new();
3444 }
3445 let stop_owner = task
3446 .runs
3447 .last()
3448 .and_then(|id| RunState::load(id).ok())
3449 .filter(|state| {
3450 crate::merge_decision::resumable_hold(state)
3451 || state.status == RunStatus::Landing
3452 && state.land_approval.as_ref().is_some_and(|binding| {
3453 Questions::open().get(&binding.question).is_ok_and(|q| {
3454 q.run == state.id
3455 && q.resolution()
3456 .as_deref()
3457 .is_some_and(crate::merge_decision::stops)
3458 })
3459 })
3460 });
3461 if let Some(owner) = stop_owner {
3462 let mut runner = match Runner::resume(&owner.id) {
3463 Ok(runner) => runner,
3464 Err(e) => {
3465 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3466 record(queue, task);
3467 return Vec::new();
3468 }
3469 };
3470 runner.on_pause(stop.pause());
3471 runner.watch_interrupt(interrupt_pause);
3472 let quota_before = runner.state.quota.clone();
3473 task.start(owner.id.clone());
3474 record(queue, task);
3475 lock(status).current.push(Current {
3476 task: task.id.clone(),
3477 run: owner.id,
3478 });
3479 runner.state.next_pass_task_entry = true;
3480 let result = runner.execute().await;
3481 return finish_attempt(
3482 opts.max_attempts,
3483 queue,
3484 task,
3485 &runner.state,
3486 "a_before,
3487 result,
3488 );
3489 }
3490
3491 let unfinished = (!task.fresh_start)
3492 .then(|| unfinished_run(&task.runs, task.short()))
3493 .flatten()
3494 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3495 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3496 let saved_recovery = previous.as_ref().filter(|run| {
3497 task.replacement.is_none()
3498 && task.pr_recovery.as_ref().is_some_and(|selected| {
3499 selected.check_task(&task.id, &task.instruction).is_ok()
3500 && selected_starter(selected, Some(run), unfinished.as_deref())
3501 == Starter::Resume(run.id.clone())
3502 })
3503 });
3504
3505 let explicit = match &task.overrides {
3509 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3510 Some(_) => opts.config.as_deref(),
3511 None => opts.config.as_deref(),
3512 };
3513 let (mut config, layers) = if let Some(run) = saved_recovery {
3514 let mut saved = run.clone();
3517 if let Err(e) = saved.configure_recovery_resume() {
3518 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3519 record(queue, task);
3520 return Vec::new();
3521 }
3522 (saved.config, Vec::new())
3523 } else {
3524 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3525 Ok(loaded) => loaded,
3526 Err(e) => {
3527 let reason = format!("[config] {e:#}");
3528 record_config_failure(task, &e);
3529 task.last_error = Some(reason.clone());
3530 task.hold_machine(Some(reason));
3531 record(queue, task);
3532 return Vec::new();
3533 }
3534 };
3535 if let Err(e) = apply_options(&mut config, opts, task) {
3536 task.hold_manual(Some(format!(
3537 "[config] {e:#}; correct the merge override before releasing the task"
3538 )));
3539 record(queue, task);
3540 return Vec::new();
3541 }
3542 if let Some(selected) = &task.pr_recovery
3543 && let Err(e) = selected.configure(&mut config)
3544 {
3545 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3546 record(queue, task);
3547 return Vec::new();
3548 }
3549 (config, layers)
3550 };
3551 let config_evidence = crate::pr_recovery::ConfigEvidence {
3552 layers,
3553 overrides: task.overrides.clone(),
3554 daemon_merge: task
3555 .overrides
3556 .as_ref()
3557 .is_none_or(|o| o.inherit_daemon_options)
3558 .then(|| opts.merge.clone())
3559 .flatten(),
3560 };
3561 apply_task_implementers(&mut config, task);
3562 if let Some(replacement) = &task.replacement {
3563 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3564 old.liveness(false) == Liveness::Dead
3565 && old.merge_decision.as_ref().is_some_and(|d| {
3566 d.closed
3567 && d.question == replacement.question
3568 && d.replacement_run.as_ref().is_none_or(|run| {
3569 task.runs.last() == Some(run)
3570 && RunState::load(run).is_ok_and(|current| {
3571 current.replaces.as_ref().is_some_and(|pin| {
3572 pin.question == replacement.question
3573 && pin.agent == replacement.agent
3574 })
3575 })
3576 })
3577 })
3578 });
3579 if !safe {
3580 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()));
3581 record(queue, task);
3582 return Vec::new();
3583 }
3584 match config.agent(&replacement.agent) {
3585 Ok(agent) if crate::agent::installed(agent) => {}
3586 _ => {
3587 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)));
3588 record(queue, task);
3589 return Vec::new();
3590 }
3591 }
3592 config.graph.implementers = 1;
3593 config.graph.land_approval = true;
3594 config.merge.mode = MergeMode::Pr;
3595 config.graph.selected_implementer = Some(replacement.agent.clone());
3596 }
3597 let p = phrases(&config.graph.language);
3598 let start_failed = p.could_not_start;
3599
3600 if let Some(reason) = disk_gate(&repo, &config) {
3608 task.notice_cause("disk-space", None, None);
3609 task.last_error = Some(reason.clone());
3610 task.hold_machine(Some(reason.clone()));
3611 record(queue, task);
3612 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3613 notices::raise(
3616 Notice::warn(
3617 &format!("disk:{}", repo.display()),
3618 "A task was held for want of free disk space; free some, then release it from the queue.",
3619 )
3620 .link(Link::Task {
3621 id: task.id.clone(),
3622 }),
3623 );
3624 return Vec::new();
3625 }
3626
3627 let review_branch = take_review_branch(task, previous.as_ref());
3652 let branch_exists = match &review_branch {
3653 Some(branch) => crate::git::branch_exists(&repo, branch)
3654 .await
3655 .unwrap_or(false),
3656 None => false,
3657 };
3658 let proposed = match (&review_branch, &unfinished, &task.review_of) {
3662 (None, None, Some(branch)) => Starter::Review(branch.clone()),
3663 _ => choose_starter(
3664 review_branch.as_deref(),
3665 branch_exists,
3666 unfinished.as_deref(),
3667 ),
3668 };
3669 let retry_selected = task.replacement.is_some()
3670 && task.resumption.is_some()
3671 && !task.fresh_start
3672 && previous.as_ref().is_some_and(|run| {
3673 run.replaces.is_some()
3674 && ((run.status == RunStatus::Failed && run.viable().is_empty())
3675 || (run.status == RunStatus::Blocked && run.tally.is_none()))
3676 });
3677 let stop_pin = task
3678 .resume_override
3679 .as_ref()
3680 .filter(|pin| {
3681 Questions::open().get(&pin.question_id).is_ok_and(|q| {
3682 q.node == land::APPROVAL_NODE
3683 && q.resolution()
3684 .as_deref()
3685 .is_some_and(crate::merge_decision::stops)
3686 })
3687 })
3688 .and_then(|pin| pin.pinned_run.clone());
3689 let starter = if let Some(run) = stop_pin {
3690 Starter::Resume(run)
3693 } else if retry_selected {
3694 Starter::Resume(previous.as_ref().unwrap().id.clone())
3695 } else if let Some(selected) = &task.pr_recovery {
3696 if selected.check_task(&task.id, &task.instruction).is_ok() {
3697 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3698 } else {
3699 Starter::Review(selected.branch.clone())
3700 }
3701 } else {
3702 starter_with_implementers(task, previous.as_ref(), proposed)
3703 };
3704 if let Some(pin) = &task.resume_override
3707 && let Some(run) = &pin.pinned_run
3708 && starter != Starter::Resume(run.clone())
3709 {
3710 let run = run.clone();
3711 task.notice_cause("resume-owner", Some(&run), None);
3712 task.hold_machine(Some(format!(
3713 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3714 task.id
3715 )));
3716 record(queue, task);
3717 return Vec::new();
3718 }
3719 if task.replacement.is_some()
3720 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3721 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3722 {
3723 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()));
3724 record(queue, task);
3725 return Vec::new();
3726 }
3727 let attachments = match task_attachments(queue, task) {
3732 Ok(a) => a,
3733 Err(e) => {
3734 task.attempts += 1;
3735 task.fail_startup_target(
3736 "startup-attachments",
3737 e.name.clone(),
3738 format!("{start_failed}{e:#}"),
3739 opts.max_attempts,
3740 );
3741 record(queue, task);
3742 return Vec::new();
3743 }
3744 };
3745 let startup_pause = stop.pause();
3746 let startup_interrupt = interrupt_pause.clone();
3747 let wait = crate::repo_lock::WaitPolicy::new(
3748 Duration::from_secs(config.graph.timeout_resource_wait),
3749 move || startup_pause.parked() || startup_interrupt.parked(),
3750 );
3751 let started = wait.scope(async { match &starter {
3752 Starter::Review(_) if task.pr_recovery.is_some() => {
3753 let selected = task.pr_recovery.clone().expect("selected recovery");
3754 match selected.check_task(&task.id, &task.instruction) {
3755 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3756 .await
3757 .map(|mut r| {
3758 r.state.attachments = attachments.clone();
3759 r
3760 }),
3761 Err(e) => Err(e),
3762 }
3763 }
3764 Starter::Review(branch) => {
3765 tracing::info!(
3766 "task {} reopens `{branch}` as a review-only pass",
3767 task.short()
3768 );
3769 let takeover = crate::handover::Takeover {
3772 earlier: task.earlier_attempts().to_vec(),
3773 home: crate::run::home(),
3774 choice: take_divergence_answer(branch, &config.merge.remote, task),
3775 task_instruction: Some(instruction_for(task)),
3776 };
3777 Runner::review_taking_over(
3778 &repo,
3779 branch,
3780 config,
3781 Some(takeover),
3782 crate::run::Origin::queue(&task.id),
3783 )
3784 .await
3785 }
3786 Starter::Resume(id) => {
3787 tracing::info!("resuming run {id} rather than competing again");
3788 Runner::resume(id).and_then(|mut r| {
3789 if retry_selected {
3790 for candidate in &mut r.state.candidates {
3793 candidate.failed = None;
3794 candidate.empty = false;
3795 candidate.commits = 0;
3796 }
3797 r.state.status = RunStatus::Implementing;
3798 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3799 }
3800 if r.state.prep_failure.is_some() {
3801 let approval = task
3802 .resumption
3803 .as_ref()
3804 .context("preparation retry requires an explicit task release")?;
3805 r.retry_preparation(approval.at)?;
3806 }
3807 if let Some(instruction) =
3808 prepare_instruction(&starter, Some(&r.state.instruction), task)
3809 {
3810 r.state.instruction = instruction;
3811 }
3812 r.state.attachments = attachments.clone();
3813 if task.replacement.is_some() {
3814 r.state.config.merge.mode = MergeMode::Pr;
3815 r.state.config.graph.land_approval = true;
3816 }
3817 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3821 .overrides
3822 .as_ref()
3823 .and_then(|o| o.merge.as_deref())
3824 .and_then(|m| merge_mode(m).ok())
3825 {
3826 r.state.config.merge.mode = mode;
3827 }
3828 Ok(r)
3829 })
3830 }
3831 Starter::Start => {
3832 if let Some(branch) = &review_branch {
3833 tracing::warn!(
3834 "conductor chose review for task {} but branch `{branch}` no longer \
3835 exists; requeuing as a fresh competition instead",
3836 task.short()
3837 );
3838 }
3839 let instruction = prepare_instruction(&starter, None, task)
3840 .unwrap_or_else(|| task.instruction.clone());
3841 Runner::start_naming(
3842 &repo,
3843 instruction,
3844 &task.title,
3845 config,
3846 crate::run::Origin::queue(&task.id),
3847 )
3848 .await
3849 .map(|mut r| {
3850 r.state.attachments = attachments.clone();
3851 r
3852 })
3853 }
3854 }}).await;
3855 let mut runner = match started {
3856 Ok(r) => r,
3857 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3858 task.last_error = Some(e.to_string());
3859 if stop.parking() || interrupt_pause.parked() {
3860 let attempts = task.attempts;
3861 task.park(e.to_string());
3862 task.attempts = attempts;
3864 } else {
3865 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3866 }
3867 record(queue, task);
3868 return Vec::new();
3869 }
3870 Err(e) if task.pr_recovery.is_some() => {
3874 task.startup_notice_cause("startup-public-head");
3875 task.attempts += 1;
3876 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3877 task.link_run(&partial.run);
3878 task.record_pass(&partial.run, 0, task.attempts, None);
3879 }
3880 task.last_error = Some(format!("{start_failed}{e:#}"));
3881 task.hold_unrequested_retry(Some(format!(
3882 "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."
3883 )));
3884 record(queue, task);
3885 return Vec::new();
3886 }
3887 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3888 let detail = match e.downcast_ref::<crate::handover::Refused>() {
3889 Some(r) => (p.handover_refused)(r),
3890 None => format!("{e:#}"),
3891 };
3892 task.startup_notice_cause("startup-handover");
3893 let reason = format!("{start_failed}{detail}");
3894 task.last_error = Some(reason.clone());
3895 let branch = match &starter {
3898 Starter::Review(branch) => Some(branch.clone()),
3899 _ => None,
3900 };
3901 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3905 record(queue, task);
3906 tracing::warn!(
3907 "holding {} for a branch it cannot take over: {e:#}",
3908 task.short()
3909 );
3910 return Vec::new();
3911 }
3912 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3917 let d = e
3918 .downcast_ref::<crate::reconcile::Diverged>()
3919 .expect("checked by the guard");
3920 let mut q = ask::Question::new(
3921 task.id.clone(),
3922 crate::reconcile::NODE.to_owned(),
3923 crate::reconcile::SEAT.to_owned(),
3924 d.summary(),
3925 d.detail(),
3926 d.choices(),
3927 );
3928 match Questions::open().put(&mut q) {
3929 Ok(()) => {
3930 task.last_error = Some(format!("{e:#}"));
3931 task.review_branch = Some(d.branch.clone());
3934 task.review_instruction = Some(task.instruction.clone());
3935 task.block(vec![q.id.clone()], Some(d.summary()));
3936 }
3937 Err(put) => {
3938 tracing::warn!("could not file the divergence question: {put:#}");
3939 task.attempts += 1;
3940 task.fail_startup(
3941 "startup-question-store",
3942 format!("{start_failed}{e:#}"),
3943 opts.max_attempts,
3944 );
3945 }
3946 }
3947 record(queue, task);
3948 return Vec::new();
3949 }
3950 Err(e) => {
3951 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3957 && let Starter::Review(branch) = &starter
3958 {
3959 task.review_branch = Some(branch.clone());
3960 task.review_instruction = Some(task.instruction.clone());
3961 task.last_error = Some(format!("{start_failed}{e:#}"));
3962 task.status = crate::queue::TaskStatus::Failed;
3963 record(queue, task);
3964 return Vec::new();
3965 }
3966 task.attempts += 1;
3967 task.last_error = Some(format!("{start_failed}{e:#}"));
3968 task.startup_notice_cause("startup-source");
3969 task.hold_unrequested_retry(Some(format!(
3970 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3971 )));
3972 record(queue, task);
3973 return Vec::new();
3974 }
3975 };
3976 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
3977 runner.state.recovery_config = Some(config_evidence);
3978 }
3979 if let Some(replacement) = &task.replacement {
3980 if matches!(starter, Starter::Start) {
3981 runner.state.instruction.push_str(&format!(
3982 "\n\n# Replacement review context\n{}",
3983 replacement.context
3984 ));
3985 }
3986 runner.state.replaces = Some(replacement.clone());
3987 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
3988 if let Ok(mut old) = RunState::load(&replacement.run)
3989 && let Some(d) = &mut old.merge_decision
3990 {
3991 d.replacement_run = Some(runner.state.id.clone());
3992 old.event(
3993 "replacement",
3994 format!(
3995 "replacement run {} owns the next attempt; old PR remains closed",
3996 runner.state.id
3997 ),
3998 );
3999 if let Err(e) = old.save() {
4000 task.hold_manual(Some(format!(
4001 "Could not link replacement history: {e}; no agents dispatched"
4002 )));
4003 record(queue, task);
4004 return Vec::new();
4005 }
4006 }
4007 }
4008 runner.state.task_instruction = Some(task.instruction.clone());
4009 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4012 if runner.state.origin_chat.is_none() {
4013 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4014 }
4015 runner.on_pause(stop.pause());
4017 runner.watch_interrupt(interrupt_pause);
4021
4022 let run = runner.state.id.clone();
4025 task.start(run.clone());
4026 record(queue, task);
4027 lock(status).current.push(Current {
4028 task: task.id.clone(),
4029 run,
4030 });
4031
4032 let quota_before = runner.state.quota.clone();
4035 runner.state.next_pass_task_entry = true;
4036 let result = runner.execute().await;
4037 finish_attempt(
4038 opts.max_attempts,
4039 queue,
4040 task,
4041 &runner.state,
4042 "a_before,
4043 result,
4044 )
4045}
4046
4047pub fn finish_attempt(
4052 max_attempts: usize,
4053 queue: &Queue,
4054 task: &mut Task,
4055 state: &RunState,
4056 quota_before: &[QuotaLoss],
4057 result: Result<()>,
4058) -> Vec<QuotaLoss> {
4059 let detail = match result {
4060 Ok(()) => describe(state),
4061 Err(e) => format!("{e:#}"),
4062 };
4063 let fresh = losses_this_attempt(quota_before, &state.quota);
4064 let verdict = Verdict {
4065 status: state.status,
4066 left_pr: state.pr.is_some(),
4069 quota_hit: !fresh.is_empty(),
4075 parked: state.parked,
4079 no_viable_candidates: state.viable().is_empty(),
4082 };
4083 if let Some(replacement) = &state.replaces
4084 && let Some(pr) = &state.pr
4085 && let Ok(mut old) = RunState::load(&replacement.run)
4086 && let Some(d) = &mut old.merge_decision
4087 {
4088 d.replacement_pr = Some(pr.url.clone());
4089 let _ = old.save();
4090 }
4091 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4092 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4093 task.hold_unrequested_retry(Some(format!(
4094 "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
4095 )));
4096 }
4097 if task.status == TaskStatus::Done {
4098 supersede_prior_runs(task, &crate::run::home());
4099 }
4100 record(queue, task);
4101 tracing::info!(
4102 "task {} is {} after run {} ({})",
4103 task.short(),
4104 task.status.as_str(),
4105 state.short(),
4106 label(state.status)
4107 );
4108 fresh
4109}
4110
4111pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4115 let waits_on_owner = withheld_text_wait(task).is_some();
4120 if task.status.runnable()
4121 && !waits_on_owner
4122 && !(task.fresh_start && task.replacement.is_some())
4123 {
4124 let why = task.last_error.clone().map_or_else(
4125 || "the run did not finish".to_owned(),
4126 |e| format!("the run did not finish: {e}"),
4127 );
4128 task.hold_unrequested_retry(Some(format!(
4129 "{why}. It was started by hand, so it is not retried \
4130 automatically; `magi task release` retries it."
4131 )));
4132 record(queue, task);
4133 }
4134}
4135
4136#[must_use]
4140pub fn loop_would_resume(run: &str) -> bool {
4141 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4142}
4143
4144#[must_use]
4154pub fn foreign_loop(
4155 reading: Option<&Reading>,
4156 now: Timestamp,
4157 own_pid: u32,
4158) -> Option<Option<u32>> {
4159 let reading = reading.filter(|r| r.running(now))?;
4160 match reading.pid {
4161 Some(pid) if pid == own_pid => None,
4162 pid => Some(pid),
4163 }
4164}
4165
4166pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4181 let status = Arc::new(Mutex::new(Status::new()));
4182 let stop = Stop::new();
4183 attempt(
4184 opts,
4185 queue,
4186 &status,
4187 &stop,
4188 crate::graph::Pause::new(),
4189 task,
4190 )
4191 .await;
4192 let mut resumes = 0;
4201 while resumes < MAX_WITHHELD_RESUMES {
4202 let Some(timeout) = withheld_text_wait(task) else {
4203 break;
4204 };
4205 eprintln!(
4206 "waiting for the owner's answer on a withheld pull request text \
4207 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4208 );
4209 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4212 let ready = loop {
4213 match land_resume_state(task) {
4214 LandResume::StillWaiting if std::time::Instant::now() < limit => {
4215 tokio::time::sleep(WITHHELD_POLL).await;
4216 }
4217 LandResume::Ready => break true,
4218 _ => break false,
4219 }
4220 };
4221 if !ready {
4222 break;
4223 }
4224 resumes += 1;
4225 attempt(
4226 opts,
4227 queue,
4228 &status,
4229 &stop,
4230 crate::graph::Pause::new(),
4231 task,
4232 )
4233 .await;
4234 }
4235 hold_if_runnable(queue, task);
4236}
4237
4238const MAX_WITHHELD_RESUMES: u32 = 3;
4241
4242const WITHHELD_POLL: Duration = Duration::from_secs(15);
4244
4245fn withheld_text_wait(task: &Task) -> Option<u64> {
4248 let id = task.runs.last()?;
4249 let s = RunState::load(id).ok()?;
4250 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4251 .then_some(s.config.graph.answer_timeout)
4252}
4253
4254fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4264 after
4265 .iter()
4266 .filter(|q| !before.contains(q))
4267 .cloned()
4268 .collect()
4269}
4270
4271fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4274 if quota.is_empty() {
4275 return None;
4276 }
4277 let with_hint = quota.iter().find(|q| q.reset.is_some());
4278 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4279 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4280 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4281 Some(
4282 now.checked_add(jiff::SignedDuration::from_secs(secs))
4283 .unwrap_or(Timestamp::MAX),
4284 )
4285}
4286
4287fn implementers_match(task: &Task, state: &RunState) -> bool {
4289 task.replacement.as_ref().map_or_else(
4290 || {
4291 task.implementers()
4292 .is_none_or(|n| n == state.config.graph.implementers)
4293 },
4294 |replacement| {
4295 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4296 && state.config.graph.implementers == 1
4297 },
4298 )
4299}
4300
4301fn starter_with_implementers(
4303 task: &Task,
4304 previous: Option<&RunState>,
4305 proposed: Starter,
4306) -> Starter {
4307 if previous.is_some_and(|s| !implementers_match(task, s)) {
4308 task.review_of
4309 .as_ref()
4310 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4311 } else {
4312 proposed
4313 }
4314}
4315
4316fn apply_task_implementers(config: &mut Config, task: &Task) {
4318 if let Some(n) = task.implementers() {
4319 config.graph.implementers = n;
4320 }
4321}
4322
4323#[cfg(test)]
4328fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4329 let explicit = match &task.overrides {
4330 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4331 _ => opts.config.as_deref(),
4332 };
4333 let (mut config, _) = Config::discover(repo, explicit)?;
4334 apply_options(&mut config, opts, task)?;
4335 Ok(config)
4336}
4337
4338fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4339 if task
4340 .overrides
4341 .as_ref()
4342 .is_none_or(|o| o.inherit_daemon_options)
4343 && let Some(mode) = opts.merge.as_deref()
4344 {
4345 config.merge.mode = merge_mode(mode)?;
4346 }
4347 if let Some(o) = &task.overrides {
4348 o.apply(config);
4349 }
4350 Ok(())
4351}
4352
4353fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4355 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4356 if let Some(mode) = &opts.merge {
4357 config.merge.mode = merge_mode(mode)?;
4358 }
4359 Ok(config)
4360}
4361
4362async fn maybe_prune_cache_between_runs(
4393 repo: &Path,
4394 opts: &Opts,
4395 home: &Path,
4396 stop: &Stop,
4397 last_checked: &mut Option<Timestamp>,
4398 now: Timestamp,
4399) {
4400 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4401 return;
4402 }
4403 *last_checked = Some(now);
4404 let cfg = match prepare(repo, opts) {
4405 Ok(cfg) => cfg,
4406 Err(e) => {
4407 tracing::warn!("cache check: no config: {e:#}");
4408 return;
4409 }
4410 };
4411 match clean::prune_cache_if_over_limit(&cfg, home) {
4412 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4413 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4414 pruned.files,
4415 pruned.freed
4416 ),
4417 Ok(_) => {}
4418 Err(e) => {
4419 tracing::warn!("housekeep: prune cache: {e:#}");
4420 notices::raise_in(
4421 home,
4422 Notice::warn(
4423 "housekeep:cache",
4424 "Pruning the shared build cache failed; disk usage may keep growing.",
4425 ),
4426 );
4427 }
4428 }
4429}
4430
4431fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4435 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4436}
4437
4438async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4457 let cfg = match prepare(repo, opts) {
4458 Ok(cfg) => cfg,
4459 Err(e) => {
4460 tracing::warn!("housekeep: no config: {e:#}");
4461 return;
4462 }
4463 };
4464 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4473 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4474 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4479 let mut extra = Vec::new();
4480 if out.unreadable > 0 {
4481 extra.push(format!("{} unreadable", out.unreadable));
4482 }
4483 if out.orphaned_worktrees > 0 {
4484 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4485 }
4486 let detail = if extra.is_empty() {
4487 String::new()
4488 } else {
4489 format!(" ({})", extra.join(", "))
4490 };
4491 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4492 }
4493 if out.external_merges_recorded > 0 {
4494 tracing::info!(
4495 "housekeep: recorded {} run(s) as merged externally",
4496 out.external_merges_recorded
4497 );
4498 }
4499 if out.stale_pr_states_repaired > 0 {
4500 tracing::info!(
4501 "housekeep: rewrote {} run record(s) whose pull request had already settled",
4502 out.stale_pr_states_repaired
4503 );
4504 }
4505 if out.cache_files > 0 {
4506 tracing::info!(
4507 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4508 out.cache_files,
4509 out.cache_freed
4510 );
4511 }
4512 if out.questions_abandoned > 0 {
4513 tracing::info!(
4514 "housekeep: abandoned {} question(s) left open by a finished run",
4515 out.questions_abandoned
4516 );
4517 }
4518}
4519
4520async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4529 let questions = Questions::at(home.join("questions"));
4530 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4531 if report.is_empty() {
4532 return;
4533 }
4534 if !report.quarantined.is_empty() {
4535 tracing::info!(
4536 "triage: held {} blocked task(s) whose blocked-on task or \
4537 question no longer exists: {}",
4538 report.quarantined.len(),
4539 report.quarantined.join(", ")
4540 );
4541 }
4542 if !report.resumed.is_empty() {
4543 tracing::info!(
4544 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4545 report.resumed.len(),
4546 report.resumed.join(", ")
4547 );
4548 }
4549 if !report.asked.is_empty() {
4550 tracing::info!(
4551 "triage: asked about {} held task(s): {}",
4552 report.asked.len(),
4553 report.asked.join(", ")
4554 );
4555 }
4556 if !report.answered.is_empty() {
4557 tracing::info!(
4558 "triage: applied {} operator answer(s): {}",
4559 report.answered.len(),
4560 report.answered.join(", ")
4561 );
4562 }
4563}
4564
4565fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4572 disk_gate_with(repo, config, crate::disk::free_bytes)
4573}
4574
4575fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4579 repo: &Path,
4580 config: &Config,
4581 free_bytes: F,
4582) -> Option<String> {
4583 let min = config.disk.min_free_bytes;
4584 if min == 0 {
4585 return None;
4586 }
4587 match free_bytes(repo) {
4588 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4589 Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
4590 }
4591}
4592
4593const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4600
4601const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4605
4606fn quota_wait(
4615 reset_at: Option<Timestamp>,
4616 now: Timestamp,
4617 fallback: Duration,
4618 cap: Duration,
4619) -> Duration {
4620 match reset_at {
4621 Some(at) if at > now => {
4622 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4623 Duration::from_secs(secs).min(cap)
4624 }
4625 _ => fallback,
4626 }
4627}
4628
4629fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4643 parse_reset_hint_zoned(text, now)
4644 .or_else(|| parse_reset_hint_dated(text))
4645 .or_else(|| parse_reset_hint_relative(text, recorded))
4646}
4647
4648fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4652 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4653 let mut rest = rest.trim();
4654 if rest.is_empty() {
4655 return None;
4656 }
4657 let mut total: i64 = 0;
4658 let mut matched = false;
4659 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4660 if let Some((digits, tail)) = rest.split_once(unit)
4661 && !digits.is_empty()
4662 && digits.bytes().all(|b| b.is_ascii_digit())
4663 {
4664 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4665 rest = tail;
4666 matched = true;
4667 }
4668 }
4669 if !rest.is_empty() || !matched {
4670 return None;
4671 }
4672 recorded
4673 .checked_add(jiff::SignedDuration::from_secs(total))
4674 .ok()
4675}
4676
4677fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4681 let clock = clock.trim().to_lowercase();
4682 let (digits, pm) = clock
4683 .strip_suffix("am")
4684 .map(|d| (d, false))
4685 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4686 let (h, m) = digits.trim().split_once(':')?;
4687 let mut hour: i8 = h.trim().parse().ok()?;
4688 let minute: i8 = m.trim().parse().ok()?;
4689 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4690 return None;
4691 }
4692 if pm && hour != 12 {
4693 hour += 12;
4694 } else if !pm && hour == 12 {
4695 hour = 0;
4696 }
4697 Some((hour, minute))
4698}
4699
4700fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4705 let open = text.find('(')?;
4706 let close = text.rfind(')')?;
4707 if close <= open {
4708 return None;
4709 }
4710 let zone = text[open + 1..close].trim();
4711 let (hour, minute) = parse_12h_clock(&text[..open])?;
4712 let tz = jiff::tz::TimeZone::get(zone).ok()?;
4713 let candidate = now
4714 .to_zoned(tz)
4715 .with()
4716 .hour(hour)
4717 .minute(minute)
4718 .second(0)
4719 .millisecond(0)
4720 .microsecond(0)
4721 .nanosecond(0)
4722 .build()
4723 .ok()?;
4724 let mut at = candidate.timestamp();
4725 if at <= now {
4726 at += jiff::SignedDuration::from_hours(24);
4727 }
4728 Some(at)
4729}
4730
4731fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4740 let words: Vec<&str> = text.split_whitespace().collect();
4741 if words.len() < 5 {
4742 return None;
4743 }
4744 (0..=words.len() - 5)
4745 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4746}
4747
4748fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4754 if trailing.is_some_and(|next| next.starts_with('(')) {
4755 return None;
4756 }
4757 let month = month_number(window[0])?;
4758 let day_token = window[1].strip_suffix(',')?.to_lowercase();
4759 let day_digits = ["st", "nd", "rd", "th"]
4760 .iter()
4761 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4762 let day: i8 = day_digits.parse().ok()?;
4763 let year_token = window[2];
4764 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4765 return None;
4766 }
4767 let year: i16 = year_token.parse().ok()?;
4768 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4772 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4773 let date = jiff::civil::Date::new(year, month, day).ok()?;
4774 let candidate = date
4775 .at(hour, minute, 0, 0)
4776 .to_zoned(jiff::tz::TimeZone::UTC)
4777 .ok()?;
4778 Some(candidate.timestamp())
4779}
4780
4781fn month_number(name: &str) -> Option<i8> {
4784 const NAMES: [&str; 12] = [
4785 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4786 ];
4787 let lower = name.to_lowercase();
4788 NAMES
4789 .iter()
4790 .position(|n| *n == lower.as_str())
4791 .map(|i| i as i8 + 1)
4792}
4793
4794fn exhausted_review_budget(state: &RunState) -> bool {
4806 state.status == RunStatus::Blocked
4809 && !state.pr_publication_pending
4810 && state.reviews.len() >= state.config.graph.review_rounds
4811}
4812
4813fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4850 unfinished_run_with(runs, short, RunState::load)
4851}
4852
4853fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
4856where
4857 F: FnOnce(&str) -> Result<RunState>,
4858{
4859 let id = runs.last()?;
4860 match load(id) {
4861 Ok(s)
4866 if s.status.resumable()
4867 && !s.released()
4868 && !exhausted_review_budget(&s)
4869 && s.liveness(false) != crate::run::Liveness::Live =>
4870 {
4871 Some(id.clone())
4872 }
4873 Ok(_) => None,
4874 Err(e) => {
4875 tracing::warn!("could not read run {id} for task {short}: {e:#}");
4876 None
4877 }
4878 }
4879}
4880
4881fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
4889where
4890 F: FnOnce(&str) -> Result<RunState>,
4891{
4892 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4894 || task.fresh_start
4895 || task.review_branch.is_some()
4896 {
4897 return false;
4898 }
4899 let Some(id) = task.runs.last() else {
4900 return false;
4901 };
4902 load(id).is_ok_and(|s| {
4903 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4904 })
4905}
4906
4907#[derive(Debug, Clone, PartialEq, Eq)]
4910enum Starter {
4911 Review(String),
4914 Resume(String),
4916 Start,
4918}
4919
4920fn selected_starter(
4922 selected: &crate::pr_recovery::Selection,
4923 previous: Option<&RunState>,
4924 unfinished: Option<&str>,
4925) -> Starter {
4926 if let Some(id) = unfinished
4927 && previous.is_some_and(|r| {
4928 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4929 })
4930 {
4931 Starter::Resume(id.to_owned())
4932 } else {
4933 Starter::Review(selected.branch.clone())
4934 }
4935}
4936
4937fn take_divergence_answer(
4941 branch: &str,
4942 remote: &str,
4943 task: &mut Task,
4944) -> Option<crate::reconcile::Choice> {
4945 let summary = crate::reconcile::summary_for(branch, remote);
4946 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4947 (a.question == summary)
4948 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4949 .flatten()
4950 .map(|c| (i, c))
4951 })?;
4952 task.answers.remove(idx);
4953 Some(choice)
4954}
4955
4956fn choose_starter(
4968 review_branch: Option<&str>,
4969 branch_exists: bool,
4970 unfinished: Option<&str>,
4971) -> Starter {
4972 match review_branch {
4973 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4974 Some(_) => Starter::Start,
4975 None => match unfinished {
4976 Some(id) => Starter::Resume(id.to_owned()),
4977 None => Starter::Start,
4978 },
4979 }
4980}
4981
4982fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4984 let branch = task.review_branch.take();
4985 let instruction = task.review_instruction.take();
4986 branch.filter(|branch| match &instruction {
4987 Some(authored) => *authored == task.instruction,
4988 None => previous.map_or_else(
4991 || task.review_of.as_ref() == Some(branch),
4992 |run| compatible_run_instruction(run, task),
4993 ),
4994 })
4995}
4996
4997fn may_resume_run(run: &RunState, task: &Task) -> bool {
5000 task.resume_override
5001 .as_ref()
5002 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5003 || compatible_run_instruction(run, task)
5004}
5005
5006pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5008 if let Some(authored) = &run.task_instruction {
5009 return compatible_instruction(authored, task);
5010 }
5011 if compatible_instruction(&run.instruction, task) {
5012 return true;
5013 }
5014 if run.reviewed_commits.is_some() {
5017 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5018 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5019 }
5020 if let Some(branch) = &task.review_of {
5021 let canonical = format!(
5022 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5023 );
5024 let generated = format!(
5025 "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"
5026 );
5027 return task.instruction == canonical && run.instruction.starts_with(&generated);
5028 }
5029 }
5030 false
5031}
5032
5033pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5035 strip_answers_block(old, task) == task.instruction
5036}
5037
5038fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5041 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5042 return fallback.to_path_buf();
5043 }
5044 task.repo.clone()
5045}
5046
5047const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5051
5052fn answers_block(task: &Task, count: usize) -> String {
5054 let mut s = ANSWERS_HEADER.to_owned();
5055 for a in &task.answers[..count] {
5056 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5057 }
5058 s
5059}
5060
5061fn resumption_block(r: &crate::queue::Resumption) -> String {
5064 format!(
5065 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5066 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5067 r.generation, r.at, r.instruction, r.answers_through,
5068 )
5069}
5070
5071fn append_answers(base: &str, task: &Task) -> String {
5073 let mut s = base.to_owned();
5074 if !task.answers.is_empty() {
5075 s.push_str(&answers_block(task, task.answers.len()));
5076 }
5077 if let Some(r) = &task.resumption {
5078 s.push_str(&resumption_block(r));
5079 }
5080 s
5081}
5082
5083fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5087 let mut instruction = instruction;
5088 for approval in task
5089 .resumption
5090 .iter()
5091 .chain(task.resumption_history.iter().rev())
5092 {
5093 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5094 instruction = base;
5095 break;
5096 }
5097 }
5098 for count in (1..=task.answers.len()).rev() {
5099 let block = answers_block(task, count);
5100 if let Some(base) = instruction.strip_suffix(&block) {
5101 return base;
5102 }
5103 }
5104 instruction
5105}
5106
5107fn instruction_for(task: &Task) -> String {
5115 append_answers(&task.instruction, task)
5116}
5117
5118fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5130 append_answers(strip_answers_block(old_instruction, task), task)
5131}
5132
5133fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5135 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5136 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5137 if let Some(cause) = task.hold_notice_cause.as_mut() {
5138 cause.target = failure.map(|f| f.target.clone());
5139 }
5140}
5141
5142#[derive(Debug, thiserror::Error)]
5143#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5144struct MissingAttachment {
5145 name: String,
5146 path: PathBuf,
5147}
5148
5149fn task_attachments(
5151 queue: &Queue,
5152 task: &Task,
5153) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5154 let paths = queue.attachment_paths(task);
5155 for (name, path) in task.attachments.iter().zip(&paths) {
5156 if !path.is_file() {
5157 return Err(MissingAttachment {
5158 name: name.clone(),
5159 path: path.clone(),
5160 });
5161 }
5162 }
5163 Ok(paths)
5164}
5165
5166fn prepare_instruction(
5177 starter: &Starter,
5178 old_instruction: Option<&str>,
5179 task: &Task,
5180) -> Option<String> {
5181 match starter {
5182 Starter::Start => Some(instruction_for(task)),
5183 Starter::Resume(_) => Some(resumed_instruction(
5184 old_instruction.expect("a resumed run always has a prior instruction"),
5185 task,
5186 )),
5187 Starter::Review(_) => None,
5188 }
5189}
5190
5191fn record(queue: &Queue, task: &mut Task) {
5195 if let Err(e) = queue.put(task) {
5196 tracing::error!("could not record task {}: {e:#}", task.short());
5197 let notice = Notice::error(
5198 "loop:record",
5199 "The loop could not save a task's state; check the disk.",
5200 )
5201 .link(Link::Task {
5202 id: task.id.clone(),
5203 });
5204 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5206 Some(home) => notices::raise_in(home, notice),
5207 None => notices::raise(notice),
5208 }
5209 }
5210}
5211
5212fn runnable(queue: &Queue) -> Vec<Task> {
5218 let mut tasks: Vec<Task> = queue
5219 .list()
5220 .into_iter()
5221 .filter(|t| t.status.runnable())
5222 .collect();
5223 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5224 tasks
5225}
5226
5227fn describe(state: &RunState) -> String {
5241 let p = phrases(&state.config.graph.language);
5242 let mut detail = if state.status == RunStatus::Stalled {
5243 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5244 seats.sort_unstable();
5245 seats.dedup();
5246 if seats.is_empty() {
5247 p.quorum_lost.to_owned()
5248 } else {
5249 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5250 }
5251 } else {
5252 format!("{}{}", p.run_ended, state.status.display_label())
5253 };
5254 if let Some(last) = state.events.last() {
5255 let unanswered = state
5259 .reviews
5260 .last()
5261 .filter(|r| {
5262 state.status == RunStatus::Blocked
5263 && last.node == "review"
5264 && r.incomplete()
5265 && r.blocking == 0
5266 && r.round == state.config.graph.review_rounds
5267 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5268 })
5269 .map(|r| (r.expected - r.answered, r.round));
5270 match unanswered {
5271 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5272 detail.push_str(&format!(
5273 " ({}: {})",
5274 last.node,
5275 (p.reviewers_never_answered)(missing, rounds)
5276 ));
5277 }
5278 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5279 }
5280 }
5281 detail.push_str(&format!(" [run {}]", state.id));
5282 detail
5283}
5284
5285const DIAGNOSTIC_MAX: usize = 4_000;
5291
5292const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5297
5298fn diagnostic(state: &RunState) -> Option<String> {
5312 let mut parts: Vec<String> = Vec::new();
5313
5314 for o in state.gate.iter().filter(|o| !o.ok()) {
5316 parts.push(format!(
5317 "gate `{}` failed ({}):\n{}",
5318 o.command,
5319 notices::exit_status(o.code),
5320 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5321 ));
5322 }
5323
5324 if let Some(last) = state
5327 .events
5328 .iter()
5329 .rev()
5330 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5331 {
5332 parts.push(last.message.clone());
5333 }
5334
5335 if state.viable().is_empty() {
5342 for c in &state.candidates {
5343 if let Some(evidence) = &c.verified_noop {
5344 parts.push(format!(
5345 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5346 c.label
5347 ));
5348 } else if !c.summary.trim().is_empty() {
5349 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5350 } else if let Some(why) = &c.failed {
5351 parts.push(format!("candidate {}: {why}", c.label));
5352 }
5353 }
5354 }
5355
5356 if parts.is_empty() {
5357 return None;
5358 }
5359 Some(crate::run::tail(
5364 &parts.join("\n\n"),
5365 DIAGNOSTIC_MAX.saturating_sub(100),
5366 ))
5367}
5368
5369fn label(status: RunStatus) -> &'static str {
5377 status.as_str()
5378}
5379
5380pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5382 match mode {
5383 "none" => Ok(MergeMode::None),
5384 "local" => Ok(MergeMode::Local),
5385 "pr" => Ok(MergeMode::Pr),
5386 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5387 }
5388}
5389
5390fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5395 mutex
5396 .lock()
5397 .unwrap_or_else(std::sync::PoisonError::into_inner)
5398}
5399
5400#[cfg(test)]
5401mod tests {
5402 use super::*;
5403 use crate::queue::{Source, TaskStatus};
5404 use crate::run::{Candidate, CommandOutcome};
5405 use pretty_assertions::assert_eq;
5406
5407 fn task() -> Task {
5408 Task::new(
5409 "add retries".to_owned(),
5410 "add retries".to_owned(),
5411 PathBuf::from("/repo"),
5412 Source::Human,
5413 )
5414 }
5415
5416 #[test]
5417 fn selected_public_head_overrides_historical_resume_and_pin() {
5418 let mut t = task();
5419 let mut old = run_state(RunStatus::Blocked);
5420 let selection = crate::pr_recovery::Selection {
5421 url: "url".into(),
5422 branch: format!("magi/task-{}", t.id),
5423 head: "a".repeat(40),
5424 source_head: None,
5425 disposition: Some(crate::pr_recovery::Disposition::Review),
5426 instruction: t.instruction.clone(),
5427 approved_at: Timestamp::now(),
5428 };
5429 t.resume_override = Some(crate::queue::OperatorResume {
5430 pinned_run: Some(old.id.clone()),
5431 question_id: "choice".into(),
5432 at: Timestamp::now(),
5433 conductor_rehold: None,
5434 forced: false,
5435 });
5436 assert_eq!(
5437 selected_starter(&selection, Some(&old), Some(&old.id)),
5438 Starter::Review(selection.branch.clone())
5439 );
5440 old.pr_recovery = Some(selection.clone());
5441 assert_eq!(
5442 selected_starter(&selection, Some(&old), Some(&old.id)),
5443 Starter::Review(selection.branch.clone())
5444 );
5445 old.reviewed_commits = Some(vec!["implementation".into()]);
5446 assert_eq!(
5447 selected_starter(&selection, Some(&old), Some(&old.id)),
5448 Starter::Resume(old.id.clone())
5449 );
5450 let mut changed = selection.clone();
5451 changed.head = "b".repeat(40);
5452 assert_eq!(
5453 selected_starter(&changed, Some(&old), Some(&old.id)),
5454 Starter::Review(changed.branch)
5455 );
5456 }
5457
5458 #[test]
5459 fn candidate_transplant_failure_is_one_actionable_hold() {
5460 let dir = tempfile::tempdir().unwrap();
5461 let q = Queue::at(dir.path().join("queue"));
5462 let mut t = task();
5463 let mut state = run_state(RunStatus::Blocked);
5464 state.event("prep", "cannot apply referenced commit: conflict");
5465 state.prep_failure = Some("conflict".into());
5466 t.start(state.id.clone());
5467 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5468 assert_eq!(t.attempts, 1);
5469 assert_eq!(t.status, TaskStatus::Held);
5470 assert!(t.operator_held());
5471 assert!(!t.status.runnable());
5472 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5473 let first = t.chat_notice_key().unwrap();
5474 t.chat_notices.push(first.clone());
5475 t.release_operator("test", None);
5476 state.id = "another-unprepared-run".into();
5477 t.start(state.id.clone());
5478 finish_attempt(
5479 3,
5480 &q,
5481 &mut t,
5482 &state,
5483 &[],
5484 Err(anyhow::anyhow!("still conflicts")),
5485 );
5486 assert_eq!(
5487 t.chat_notice_key().as_ref(),
5488 Some(&first),
5489 "no work happened"
5490 );
5491 t.release_operator("test", None);
5492 state.prep_failure = None;
5493 state.status = RunStatus::Failed;
5494 state.begin_pass();
5495 t.start(state.id.clone());
5496 finish_attempt(
5497 1,
5498 &q,
5499 &mut t,
5500 &state,
5501 &[],
5502 Err(anyhow::anyhow!("new gate failure")),
5503 );
5504 let failure = t.chat_notice_key().unwrap();
5505 assert_ne!(failure, first, "approved recovery reached a real failure");
5506 t.release_operator("test", None);
5507 state.begin_pass();
5508 t.start(state.id.clone());
5509 finish_attempt(
5510 1,
5511 &q,
5512 &mut t,
5513 &state,
5514 &[],
5515 Err(anyhow::anyhow!("new failure on resume")),
5516 );
5517 assert_ne!(
5518 t.chat_notice_key().as_ref(),
5519 Some(&failure),
5520 "a new settled pass"
5521 );
5522 }
5523
5524 #[test]
5525 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5526 for source in ["cli", "web"] {
5527 let mut t = task();
5528 let mut run = run_state(RunStatus::Blocked);
5529 run.instruction = "Run A original criteria".into();
5530 run.task_instruction = Some(run.instruction.clone());
5531 t.start(run.id.clone());
5532 t.release_operator("choice", Some("resume-question"));
5533 t.resume_override = Some(crate::queue::OperatorResume {
5534 question_id: "resume-question".into(),
5535 at: Timestamp::now(),
5536 conductor_rehold: None,
5537 forced: true,
5538 pinned_run: Some(run.id.clone()),
5539 });
5540 t.hold_machine(Some("not enough free space to start a run".into()));
5541 let mut unchanged = t.clone();
5542 unchanged
5543 .edit("title changed".into(), unchanged.instruction.clone())
5544 .unwrap();
5545 unchanged.release_operator(source, None);
5546 assert_eq!(
5547 unchanged
5548 .resume_override
5549 .as_ref()
5550 .unwrap()
5551 .pinned_run
5552 .as_deref(),
5553 Some(run.id.as_str())
5554 );
5555 assert!(!compatible_run_instruction(&run, &unchanged));
5556 assert!(may_resume_run(&run, &unchanged));
5557
5558 t.edit(
5559 "approved recovery".into(),
5560 "Reuse measured PR head B; fix Clippy; review".into(),
5561 )
5562 .unwrap();
5563 assert!(t.resume_override.is_none());
5564 t.release_operator(source, None);
5565 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5566 assert!(reloaded.resume_override.is_none());
5567 assert!(!may_resume_run(&run, &reloaded));
5568 let unfinished =
5569 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5570 .filter(|_| may_resume_run(&run, &reloaded));
5571 assert_eq!(
5572 choose_starter(None, false, unfinished.as_deref()),
5573 Starter::Start
5574 );
5575 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5576 assert_eq!(
5577 reloaded.resumption_history[0].question_id.as_deref(),
5578 Some("resume-question")
5579 );
5580
5581 unchanged.instruction = "Reuse measured PR head B".into();
5584 unchanged.hold_machine(Some("disk hold".into()));
5585 unchanged.release_operator(source, None);
5586 assert!(unchanged.resume_override.is_none());
5587 assert!(!may_resume_run(&run, &unchanged));
5588 }
5589 }
5590
5591 #[test]
5592 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5593 let mut t = task();
5594 let mut run = run_state(RunStatus::Blocked);
5595 t.review_of = Some("approved-head".into());
5596 t.instruction =
5597 "Review the branch `approved-head` (review-only: no implementation, no judging)."
5598 .into();
5599 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();
5600 run.reviewed_commits = Some(vec!["Commit log".into()]);
5601 t.start(run.id.clone());
5602 t.hold_machine(Some("interrupted review".into()));
5603 t.release_operator("cli", None);
5604 assert!(
5605 compatible_run_instruction(&run, &t),
5606 "legacy explicit review remains resumable"
5607 );
5608 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5609 .filter(|_| compatible_run_instruction(&run, &t));
5610 assert_eq!(
5611 choose_starter(None, false, unfinished.as_deref()),
5612 Starter::Resume(run.id.clone())
5613 );
5614 run.task_instruction = Some(t.instruction.clone());
5615 assert!(compatible_run_instruction(&run, &t));
5616 let reloaded: RunState =
5617 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5618 assert!(compatible_run_instruction(&reloaded, &t));
5619 t.edit(
5620 "new approved head".into(),
5621 "Reuse measured PR head B".into(),
5622 )
5623 .unwrap();
5624 assert!(!compatible_run_instruction(&run, &t));
5625
5626 t.review_of = None;
5628 t.instruction = "Fix Clippy on approved head".into();
5629 run.task_instruction = None;
5630 run.instruction = format!(
5631 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5632 t.instruction
5633 );
5634 assert!(compatible_run_instruction(&run, &t));
5635 t.instruction.push('\n');
5636 assert!(
5637 compatible_run_instruction(&run, &t),
5638 "legacy generated review trimmed the original criteria"
5639 );
5640 t.hold_for_handover(Some("approved-head".into()), "refused".into());
5641 let mut unchanged = t.clone();
5642 assert_eq!(
5643 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5644 Some("approved-head")
5645 );
5646 t.edit("new plan".into(), "Reuse measured PR head B".into())
5647 .unwrap();
5648 assert!(take_review_branch(&mut t, Some(&run)).is_none());
5649 assert!(!compatible_run_instruction(&run, &t));
5650 t.review_branch = Some("approved-head".into());
5651 t.review_instruction = None;
5652 assert!(
5653 take_review_branch(&mut t, Some(&run)).is_none(),
5654 "legacy retained candidate cannot replace a revised approved head"
5655 );
5656 }
5657
5658 #[test]
5659 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5660 crate::run::pin_test_home();
5661 let dir = tempfile::tempdir().unwrap();
5662 let queue = Queue::at(dir.path().join("queue"));
5663 for resume in [true, false] {
5664 let state = run_state(RunStatus::Blocked);
5665 let mut t = task();
5666 t.start(state.id.clone());
5667 let action = if resume {
5668 ask::ChoiceAction::Resume {
5669 run: state.id.clone(),
5670 }
5671 } else {
5672 ask::ChoiceAction::Requeue
5673 };
5674 let mut q = action_question(&state.id, action);
5675 q.status = ask::QuestionStatus::Open;
5676 q.answer = None;
5677 q.answered_at = None;
5678 t.fail("run stopped with a question", 3);
5679 hold_if_runnable(&queue, &mut t);
5680 assert!(t.operator_decided_at.is_none());
5681 assert!(t.operator_held());
5682 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5683 let expected = if resume {
5684 ActionDecision::Resume(state.id.clone())
5685 } else {
5686 ActionDecision::Requeue
5687 };
5688 assert_eq!(
5689 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5690 expected
5691 );
5692 t.hold_manual(Some("later explicit hold".into()));
5693 assert_eq!(
5694 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5695 ActionDecision::Stale
5696 );
5697 }
5698 }
5699
5700 #[test]
5701 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5702 let mut t = task();
5703 t.answers.push(crate::queue::AnsweredQuestion {
5704 question: "Inspect the remote?".into(),
5705 answer: "Inspect then wait".into(),
5706 });
5707 let old = instruction_for(&t);
5708 assert!(compatible_instruction(&old, &t));
5709 t.instruction = "Reuse approved PR head and review".into();
5710 t.release_operator("cli", None);
5711 assert!(!compatible_instruction(&old, &t));
5712 let approved = instruction_for(&t);
5713 assert!(approved.contains("waiting premises are superseded"));
5714 assert!(compatible_instruction(&approved, &t));
5715 assert_eq!(resumed_instruction(&approved, &t), approved);
5716 t.release_operator("web", None);
5717 assert!(compatible_instruction(&approved, &t));
5718 assert_eq!(t.resumption_history.len(), 1);
5719 t.start("run".into());
5720 assert!(instruction_for(&t).contains("Explicit operator resumption"));
5721 }
5722
5723 #[test]
5727 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5728 let mut state = RunState::new(
5729 PathBuf::from("/repo"),
5730 "main".to_owned(),
5731 "abc1234".to_owned(),
5732 "task".to_owned(),
5733 Config::default(),
5734 );
5735 state.status = RunStatus::Blocked;
5736 state.resource_block = Some(crate::run::ResourceBlock {
5737 node: "graft".to_owned(),
5738 kind: "shared build cache".to_owned(),
5739 detail: "timed out".to_owned(),
5740 at: jiff::Timestamp::now(),
5741 });
5742 let mut t = task();
5743 t.start("20260902-000000-aaaa".to_owned());
5744 assert_eq!(t.attempts, 1);
5745 let verdict = Verdict {
5746 status: RunStatus::Blocked,
5747 left_pr: false,
5748 quota_hit: false,
5749 parked: false,
5750 no_viable_candidates: false,
5751 };
5752 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5753 assert_eq!(t.status, TaskStatus::Held);
5754 assert_eq!(t.attempts, 0, "the attempt is refunded");
5755 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5756 assert!(
5757 !t.operator_held(),
5758 "a machine hold, released without a human"
5759 );
5760
5761 let mut selected = task();
5762 selected.start("20260902-000000-cccc".into());
5763 selected.replacement = Some(crate::merge_decision::Replacement {
5764 question: "fixture".into(),
5765 run: "earlier".into(),
5766 pr: "https://example.invalid/pr/1".into(),
5767 agent: "selected".into(),
5768 context: "fixture".into(),
5769 });
5770 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5771 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5772 assert_eq!(selected.attempts, 0);
5773 assert!(
5774 !selected.operator_held(),
5775 "a selected agent also retains a machine resource hold"
5776 );
5777 assert!(
5778 selected
5779 .hold_reason
5780 .as_deref()
5781 .unwrap()
5782 .starts_with("[resource] ")
5783 );
5784
5785 let mut p = task();
5787 p.start("20260902-000000-bbbb".to_owned());
5788 settle_and_diagnose(
5789 &mut p,
5790 Verdict {
5791 parked: true,
5792 ..verdict
5793 },
5794 "parked",
5795 2,
5796 &state,
5797 );
5798 assert_eq!(p.status, TaskStatus::Parked);
5799 }
5800
5801 #[test]
5802 fn record_failure_notice_links_the_task() {
5803 let dir = tempfile::tempdir().unwrap();
5804 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5807 let queue = Queue::at(dir.path().join("queue"));
5808 let mut t = interrupt_task("rec-fail-1");
5809 record(&queue, &mut t);
5810
5811 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5812 assert_eq!(found.len(), 1);
5813 assert_eq!(found[0].key, "loop:record");
5814 assert_eq!(
5815 found[0].link,
5816 Some(Link::Task {
5817 id: "rec-fail-1".to_owned()
5818 })
5819 );
5820 }
5821
5822 fn interrupt_task(id: &str) -> Task {
5825 let mut t = task();
5826 t.id = id.to_owned();
5827 t.interrupt = true;
5828 t
5829 }
5830
5831 fn task_with_id(id: &str) -> Task {
5833 let mut t = task();
5834 t.id = id.to_owned();
5835 t
5836 }
5837
5838 fn urgent_task(id: &str) -> Task {
5840 let mut t = task();
5841 t.id = id.to_owned();
5842 t.urgent = true;
5843 t
5844 }
5845
5846 #[test]
5847 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
5848 let dir = tempfile::tempdir().unwrap();
5849 let queue = Queue::at(dir.path().join("queue"));
5850 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5851 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5852 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
5853 let mut first = task();
5854 queue.put(&mut first).unwrap();
5855 let stale_plain = queue.get(&first.id).unwrap();
5856 first.set_urgent(true).unwrap();
5857 queue.put(&mut first).unwrap();
5858 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
5859 let mut second = urgent_task("second");
5860 queue.put(&mut second).unwrap();
5861 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
5862 drop(queue.claim(&second.id).unwrap());
5863 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
5864 drop(dispatched);
5865 let stale_urgent = queue.get(&first.id).unwrap();
5866 first.set_urgent(false).unwrap();
5867 queue.put(&mut first).unwrap();
5868 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
5869 assert_eq!(urgent.available_permits(), 1);
5870 drop(queue.claim(&first.id).unwrap());
5871 drop(occupied);
5872 }
5873
5874 #[test]
5875 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
5876 let dir = tempfile::tempdir().unwrap();
5877 let queue = Queue::at(dir.path().join("queue"));
5878 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5879 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5880 let mut t = task();
5881 queue.put(&mut t).unwrap();
5882 for enabled in [true, false] {
5883 let stale = queue.get(&t.id).unwrap();
5884 t.set_urgent(enabled).unwrap();
5885 queue.put(&mut t).unwrap();
5886 assert_ne!(stale.urgent, enabled);
5887 let DispatchClaim {
5888 task: fresh,
5889 claim,
5890 permit,
5891 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
5892 assert_eq!(fresh.urgent, enabled);
5893 assert_eq!(ordinary.available_permits(), usize::from(enabled));
5894 assert_eq!(urgent.available_permits(), usize::from(!enabled));
5895 assert!(queue.claim(&t.id).is_err());
5896 assert_eq!(fresh.attempts, stale.attempts);
5897 drop((claim, permit));
5898 assert_eq!(ordinary.available_permits(), 1);
5899 assert_eq!(urgent.available_permits(), 1);
5900 }
5901 t.set_urgent(true).unwrap();
5902 queue.put(&mut t).unwrap();
5903 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
5904 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5905 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
5906 drop(queue.claim(&t.id).unwrap());
5907 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
5908 drop(occupied);
5909 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
5910 drop(queue.claim(&t.id).unwrap());
5911 let held = queue.claim(&t.id).unwrap();
5912 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5913 drop(held);
5914 t.status = TaskStatus::Held;
5915 queue.put(&mut t).unwrap();
5916 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5917 drop(queue.claim(&t.id).unwrap());
5918 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
5919 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5920 drop(queue.claim(&t.id).unwrap());
5921 assert_eq!(urgent.available_permits(), 1);
5922 }
5923
5924 #[test]
5929 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
5930 assert_eq!(permit_kind(true, false), PermitKind::None);
5931 assert_eq!(permit_kind(true, true), PermitKind::None);
5932 }
5933
5934 #[test]
5939 fn permit_kind_separates_urgent_from_ordinary() {
5940 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
5941 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
5942 }
5943
5944 #[test]
5951 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
5952 let cfg = Config::default();
5953 let repo = Path::new("/any/repo/path");
5954
5955 let reason =
5956 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
5957 assert!(reason.contains("1024"), "{reason}");
5958 assert!(
5959 reason.contains(&cfg.disk.min_free_bytes.to_string()),
5960 "{reason}"
5961 );
5962
5963 assert_eq!(
5964 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
5965 None,
5966 "exactly at the floor is open"
5967 );
5968 assert_eq!(
5969 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
5970 None,
5971 "comfortably above the floor is open"
5972 );
5973 }
5974
5975 #[test]
5976 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
5977 let mut cfg = Config::default();
5978 cfg.disk.min_free_bytes = 0;
5979 let repo = Path::new("/any/repo/path");
5980 assert_eq!(
5981 disk_gate_with(repo, &cfg, |_| Ok(0)),
5982 None,
5983 "a zero floor never measures at all"
5984 );
5985 }
5986
5987 #[test]
5988 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5989 let cfg = Config::default();
5990 let repo = Path::new("/any/repo/path");
5991 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5992 .expect("a measurement failure must close the gate, not open it");
5993 assert!(reason.contains("could not measure"), "{reason}");
5994 }
5995
5996 #[test]
5997 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5998 let ordinary = task();
5999 let next = advance_interrupt(
6000 Interrupt::Idle,
6001 std::slice::from_ref(&ordinary.id),
6002 std::slice::from_ref(&ordinary),
6003 );
6004 assert_eq!(next, Interrupt::Idle);
6005 }
6006
6007 #[test]
6008 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6009 let marked = interrupt_task("marked");
6012 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6013 assert_eq!(next, Interrupt::Idle);
6014 }
6015
6016 #[test]
6017 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6018 let marked = interrupt_task("marked");
6019 let next = advance_interrupt(
6020 Interrupt::Idle,
6021 &["running".to_owned()],
6022 std::slice::from_ref(&marked),
6023 );
6024 assert_eq!(
6025 next,
6026 Interrupt::Parking {
6027 parked: vec!["running".to_owned()],
6028 interrupt_task: "marked".to_owned(),
6029 }
6030 );
6031 }
6032
6033 #[test]
6042 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6043 let marked = interrupt_task("marked");
6044
6045 let two = advance_interrupt(
6046 Interrupt::Idle,
6047 &["a".to_owned(), "b".to_owned()],
6048 std::slice::from_ref(&marked),
6049 );
6050 assert_eq!(two, Interrupt::Idle);
6051
6052 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6053 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6054 }
6055
6056 #[test]
6057 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6058 let state = Interrupt::Parking {
6059 parked: vec!["running".to_owned()],
6060 interrupt_task: "marked".to_owned(),
6061 };
6062 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6064 assert_eq!(still_going, state);
6065
6066 let stopped_but_not_yet_dispatched =
6070 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6071 assert_eq!(stopped_but_not_yet_dispatched, state);
6072
6073 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6075 assert_eq!(
6076 dispatched,
6077 Interrupt::Running {
6078 parked: vec!["running".to_owned()],
6079 interrupt_task: "marked".to_owned(),
6080 }
6081 );
6082 }
6083
6084 #[test]
6085 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6086 let state = Interrupt::Running {
6087 parked: vec!["running".to_owned()],
6088 interrupt_task: "marked".to_owned(),
6089 };
6090 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6091 assert_eq!(still_running, state);
6092
6093 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6100 assert_eq!(
6101 ended,
6102 Interrupt::Resuming {
6103 parked: vec!["running".to_owned()]
6104 }
6105 );
6106 }
6107
6108 #[test]
6109 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6110 let state = Interrupt::Resuming {
6111 parked: vec!["running".to_owned()],
6112 };
6113 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6114 assert_eq!(still_waiting, state);
6115
6116 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6117 assert_eq!(dispatched, Interrupt::Idle);
6118 }
6119
6120 #[test]
6126 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6127 {
6128 let state = Interrupt::Parking {
6129 parked: vec!["running".to_owned()],
6130 interrupt_task: "marked".to_owned(),
6131 };
6132 let next = advance_interrupt(state, &[], &[]);
6135 assert_eq!(
6136 next,
6137 Interrupt::Resuming {
6138 parked: vec!["running".to_owned()]
6139 },
6140 "abandoning the interrupt must not abandon the resume it owes"
6141 );
6142 }
6143
6144 #[test]
6147 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6148 let state = Interrupt::Resuming {
6149 parked: vec!["running".to_owned()],
6150 };
6151 let next = advance_interrupt(state, &[], &[]);
6152 assert_eq!(
6153 next,
6154 Interrupt::Idle,
6155 "nothing is left to wait for; the loop must not stay wedged"
6156 );
6157 }
6158
6159 #[test]
6160 fn disabled_by_config_the_sequence_can_never_leave_idle() {
6161 let marked = interrupt_task("marked");
6162 let next = advance_interrupt_tick(
6163 false,
6164 Interrupt::Idle,
6165 &["running".to_owned()],
6166 std::slice::from_ref(&marked),
6167 );
6168 assert_eq!(
6169 next,
6170 Interrupt::Idle,
6171 "an unmarked, unconfigured daemon must behave exactly as before"
6172 );
6173 }
6174
6175 #[test]
6176 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6177 let state = Interrupt::Parking {
6178 parked: vec!["running".to_owned()],
6179 interrupt_task: "marked".to_owned(),
6180 };
6181 let candidates = vec![interrupt_task("marked"), task()];
6182 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6183 assert!(
6184 allowed.is_empty(),
6185 "nothing may dispatch - not even the interrupt task itself - \
6186 until the parked run has actually stopped"
6187 );
6188 }
6189
6190 #[test]
6204 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6205 for state in [
6206 Interrupt::Parking {
6207 parked: vec!["running".to_owned()],
6208 interrupt_task: "marked".to_owned(),
6209 },
6210 Interrupt::Running {
6211 parked: vec!["running".to_owned()],
6212 interrupt_task: "marked".to_owned(),
6213 },
6214 Interrupt::Resuming {
6215 parked: vec!["running".to_owned()],
6216 },
6217 ] {
6218 let candidates = vec![
6219 interrupt_task("marked"),
6220 urgent_task("hot"),
6221 task_with_id("ordinary"),
6222 ];
6223 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6224 assert!(
6225 !allowed.iter().any(|t| t.id == "hot"),
6226 "an urgent candidate must wait out the same gate as anything \
6227 else while the run it would run alongside has not actually \
6228 left flight, for state {state:?}: {allowed:?}"
6229 );
6230 }
6231 }
6232
6233 #[test]
6239 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6240 let state = Interrupt::Resuming {
6241 parked: vec!["hot".to_owned()],
6242 };
6243 let candidates = vec![urgent_task("hot"), task()];
6244 let allowed = interrupt_gate(&state, &[], candidates);
6245 assert_eq!(
6246 allowed.iter().filter(|t| t.id == "hot").count(),
6247 1,
6248 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6249 );
6250 }
6251
6252 #[test]
6253 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6254 let state = Interrupt::Parking {
6255 parked: vec!["running".to_owned()],
6256 interrupt_task: "marked".to_owned(),
6257 };
6258 let other = task();
6259 let candidates = vec![interrupt_task("marked"), other.clone()];
6260 let allowed = interrupt_gate(&state, &[], candidates);
6261 assert_eq!(allowed.len(), 1);
6262 assert_eq!(allowed[0].id, "marked");
6263 }
6264
6265 #[test]
6266 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6267 let state = Interrupt::Running {
6268 parked: vec!["running".to_owned()],
6269 interrupt_task: "marked".to_owned(),
6270 };
6271 let candidates = vec![task(), task()];
6272 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6273 assert!(allowed.is_empty());
6274 }
6275
6276 #[test]
6283 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6284 let state = Interrupt::Resuming {
6285 parked: vec!["a".to_owned(), "c".to_owned()],
6286 };
6287 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6288 let allowed = interrupt_gate(&state, &[], candidates);
6289 assert_eq!(
6290 allowed.len(),
6291 1,
6292 "at most one candidate may be offered while resuming: {allowed:?}"
6293 );
6294 assert_eq!(allowed[0].id, "a");
6295 }
6296
6297 #[test]
6298 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6299 let state = Interrupt::Resuming {
6300 parked: vec!["a".to_owned()],
6301 };
6302 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6303 assert!(allowed.is_empty());
6304 }
6305
6306 #[test]
6312 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6313 let running = task(); let marked = interrupt_task("marked");
6315
6316 let mut state = Interrupt::Idle;
6317 let in_flight = vec![running.id.clone()];
6319 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6320 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6321 assert!(gated.is_empty(), "still waiting on `running` to park");
6322
6323 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6325 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6326 assert_eq!(
6327 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6328 vec!["marked"],
6329 "only the interrupt task may be offered to the dispatcher now"
6330 );
6331
6332 state = advance_interrupt_tick(
6334 true,
6335 state,
6336 &["marked".to_owned()],
6337 std::slice::from_ref(&running),
6338 );
6339 let gated = interrupt_gate(
6340 &state,
6341 &["marked".to_owned()],
6342 vec![marked.clone(), running.clone()],
6343 );
6344 assert!(
6345 gated.is_empty(),
6346 "the parked run must not be offered back while the interrupt \
6347 task is still running"
6348 );
6349
6350 let other = task_with_id("other");
6354 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6355 assert_eq!(
6356 state,
6357 Interrupt::Resuming {
6358 parked: vec![running.id.clone()]
6359 }
6360 );
6361 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6362 assert_eq!(
6363 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6364 vec![running.id.as_str()],
6365 "exactly the parked run resumes - not the unrelated task, even \
6366 though it was offered first"
6367 );
6368
6369 state = advance_interrupt_tick(
6373 true,
6374 state,
6375 std::slice::from_ref(&running.id),
6376 std::slice::from_ref(&other),
6377 );
6378 assert_eq!(state, Interrupt::Idle);
6379 let gated = interrupt_gate(
6380 &state,
6381 std::slice::from_ref(&running.id),
6382 vec![other.clone()],
6383 );
6384 assert_eq!(
6385 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6386 vec![other.id.as_str()],
6387 "ordinary dispatch is unrestricted again"
6388 );
6389 }
6390
6391 #[test]
6392 fn every_run_status_settles_the_task_it_came_from() {
6393 let table = [
6395 (RunStatus::Merged, TaskStatus::Done, 1),
6396 (RunStatus::Ready, TaskStatus::Done, 1),
6397 (RunStatus::Stalled, TaskStatus::Failed, 0),
6398 (RunStatus::Blocked, TaskStatus::Failed, 1),
6399 (RunStatus::Failed, TaskStatus::Failed, 1),
6400 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6401 (RunStatus::Prep, TaskStatus::Failed, 1),
6402 (RunStatus::Implementing, TaskStatus::Failed, 1),
6403 (RunStatus::Judging, TaskStatus::Failed, 1),
6404 (RunStatus::Deliberating, TaskStatus::Failed, 1),
6405 (RunStatus::Voting, TaskStatus::Failed, 1),
6406 (RunStatus::Reviewing, TaskStatus::Failed, 1),
6407 (RunStatus::Gating, TaskStatus::Failed, 1),
6408 ];
6409 for (run, want, attempts) in table {
6410 let mut t = task();
6411 t.start("20260902-000000-aaaa".to_owned());
6412 settle(
6413 &mut t,
6414 Verdict {
6415 status: run,
6416 left_pr: false,
6417 parked: false,
6418 quota_hit: matches!(run, RunStatus::Stalled),
6419 no_viable_candidates: false,
6420 },
6421 "why",
6422 2,
6423 );
6424 assert_eq!(t.status, want, "task status after {}", label(run));
6425 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6426 }
6427 }
6428
6429 #[test]
6430 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6431 let mut stalled = task();
6432 stalled.start("20260902-000000-aaaa".to_owned());
6433 settle(
6434 &mut stalled,
6435 Verdict {
6436 status: RunStatus::Stalled,
6437 left_pr: false,
6438 parked: false,
6439 quota_hit: true,
6440 no_viable_candidates: false,
6441 },
6442 "quota",
6443 1,
6444 );
6445 assert_eq!(stalled.attempts, 0);
6446 assert!(
6447 stalled.status.runnable(),
6448 "a machine problem must leave the task in line"
6449 );
6450
6451 let mut blocked = task();
6452 blocked.start("20260902-000000-aaaa".to_owned());
6453 settle(
6454 &mut blocked,
6455 Verdict {
6456 status: RunStatus::Blocked,
6457 left_pr: false,
6458 parked: false,
6459 quota_hit: false,
6460 no_viable_candidates: false,
6461 },
6462 "findings open",
6463 1,
6464 );
6465 assert_eq!(blocked.attempts, 1);
6466 assert_eq!(
6467 blocked.status,
6468 TaskStatus::Held,
6469 "the last attempt hands the task to a human"
6470 );
6471 }
6472
6473 #[test]
6474 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6475 let mut delivered = task();
6478 delivered.start("20260903-080619-01c2".to_owned());
6479 settle(
6480 &mut delivered,
6481 Verdict {
6482 status: RunStatus::Blocked,
6483 left_pr: true,
6484 parked: false,
6485 quota_hit: false,
6486 no_viable_candidates: false,
6487 },
6488 "no check status",
6489 4,
6490 );
6491 assert_eq!(
6492 delivered.status,
6493 TaskStatus::Held,
6494 "a pull request waiting on CI or a person is not a retryable failure"
6495 );
6496 assert!(
6497 !delivered.status.runnable(),
6498 "the loop must not pick this task up again"
6499 );
6500 assert_eq!(
6501 delivered.last_error.as_deref(),
6502 Some("no check status"),
6503 "the operator needs to be told what the gate was waiting for"
6504 );
6505
6506 let mut empty_handed = task();
6509 empty_handed.start("20260903-080619-01c2".to_owned());
6510 settle(
6511 &mut empty_handed,
6512 Verdict {
6513 status: RunStatus::Blocked,
6514 left_pr: false,
6515 parked: false,
6516 quota_hit: false,
6517 no_viable_candidates: false,
6518 },
6519 "findings open",
6520 4,
6521 );
6522 assert_eq!(empty_handed.status, TaskStatus::Failed);
6523 assert!(empty_handed.status.runnable());
6524 }
6525
6526 #[test]
6527 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6528 let mut noop = task();
6534 noop.start("20260912-131304-391f".to_owned());
6535 settle(
6536 &mut noop,
6537 Verdict {
6538 status: RunStatus::VerifiedNoop,
6539 left_pr: false,
6540 parked: false,
6541 quota_hit: false,
6542 no_viable_candidates: true,
6543 },
6544 "candidate A: already fixed by b32cfc4, on main",
6545 4,
6546 );
6547 assert_eq!(
6548 noop.status,
6549 TaskStatus::Held,
6550 "an unverified claim is a request for a human, not a failure"
6551 );
6552 assert!(
6553 !noop.status.runnable(),
6554 "the loop must not requeue this on the same unverified claim"
6555 );
6556 assert_eq!(noop.attempts, 1);
6561 }
6562
6563 #[test]
6564 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6565 let mut parked = task();
6570 parked.start("20260903-183634-2d98".to_owned());
6571 settle(
6572 &mut parked,
6573 Verdict {
6574 status: RunStatus::Implementing,
6575 left_pr: false,
6576 quota_hit: false,
6577 parked: true,
6578 no_viable_candidates: false,
6579 },
6580 "parked after `implementing`",
6581 2,
6582 );
6583 assert_eq!(parked.attempts, 0, "a park is refunded");
6584 assert!(
6585 parked.status.runnable(),
6586 "and the task stays in line so the next loop resumes its run"
6587 );
6588 assert_eq!(parked.status, TaskStatus::Parked);
6589 assert_eq!(
6590 parked.park_reason.as_deref(),
6591 Some("parked after `implementing`"),
6592 "the card says where it stopped"
6593 );
6594 assert_eq!(parked.last_error, None, "nothing failed");
6595
6596 let mut broken = task();
6600 broken.start("20260903-183634-2d98".to_owned());
6601 settle(
6602 &mut broken,
6603 Verdict {
6604 status: RunStatus::Implementing,
6605 left_pr: false,
6606 quota_hit: false,
6607 parked: false,
6608 no_viable_candidates: false,
6609 },
6610 "returned mid-flight",
6611 2,
6612 );
6613 assert_eq!(broken.attempts, 1);
6614 }
6615
6616 #[test]
6617 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6618 let mut flaky = task();
6623 flaky.start("20260903-123023-e633".to_owned());
6624 settle(
6625 &mut flaky,
6626 Verdict {
6627 status: RunStatus::Stalled,
6628 left_pr: false,
6629 parked: false,
6630 quota_hit: false,
6631 no_viable_candidates: false,
6632 },
6633 "verdict rests on 1 of 3 judges",
6634 2,
6635 );
6636 assert_eq!(
6637 flaky.attempts, 1,
6638 "flakiness spends an attempt, so `max_attempts` still bounds it"
6639 );
6640 assert!(flaky.status.runnable(), "and it is still worth retrying");
6641
6642 let mut limited = task();
6644 limited.start("20260903-123023-e633".to_owned());
6645 settle(
6646 &mut limited,
6647 Verdict {
6648 status: RunStatus::Stalled,
6649 left_pr: false,
6650 parked: false,
6651 quota_hit: true,
6652 no_viable_candidates: false,
6653 },
6654 "judge-2, judge-3 out of quota",
6655 2,
6656 );
6657 assert_eq!(limited.attempts, 0, "a quota window is refunded");
6658 assert!(limited.status.runnable());
6659
6660 let mut worn = task();
6663 for _ in 0..2 {
6664 worn.release();
6665 }
6666 worn.start("20260903-123023-e633".to_owned());
6667 worn.attempts = 2;
6668 settle(
6669 &mut worn,
6670 Verdict {
6671 status: RunStatus::Stalled,
6672 left_pr: false,
6673 parked: false,
6674 quota_hit: false,
6675 no_viable_candidates: false,
6676 },
6677 "no quorum again",
6678 2,
6679 );
6680 assert_eq!(worn.status, TaskStatus::Held);
6681 assert!(!worn.status.runnable());
6682 }
6683
6684 #[test]
6685 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6686 let mut wiped_out = task();
6693 wiped_out.start("20260907-025000-a1b2".to_owned());
6694 settle(
6695 &mut wiped_out,
6696 Verdict {
6697 status: RunStatus::Failed,
6698 left_pr: false,
6699 parked: false,
6700 quota_hit: true,
6701 no_viable_candidates: true,
6702 },
6703 "no candidate produced a change; nothing to judge",
6704 2,
6705 );
6706 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6707 assert!(
6708 wiped_out.status.runnable(),
6709 "a machine problem must leave the task in line"
6710 );
6711
6712 let mut partial_progress = task();
6718 partial_progress.start("20260907-025500-c3d4".to_owned());
6719 settle(
6720 &mut partial_progress,
6721 Verdict {
6722 status: RunStatus::Failed,
6723 left_pr: false,
6724 parked: false,
6725 quota_hit: true,
6726 no_viable_candidates: false,
6727 },
6728 "gate failed on the winning candidate",
6729 2,
6730 );
6731 assert_eq!(
6732 partial_progress.attempts, 1,
6733 "a candidate that actually produced a change spends the attempt \
6734 even though some other seat hit its quota"
6735 );
6736 assert!(partial_progress.status.runnable());
6737 }
6738
6739 #[test]
6740 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6741 let mut t = task();
6747 t.start("20260907-025000-a1b2".to_owned());
6748 let mut state = run_state(RunStatus::Failed);
6749 state.quota.push(QuotaLoss {
6750 seat: "cand-a".to_owned(),
6751 node: "implement".to_owned(),
6752 at: Timestamp::now(),
6753 reset: None,
6754 });
6755 assert!(
6756 state.viable().is_empty(),
6757 "no candidate was added, so nothing is viable"
6758 );
6759 reclaim(&mut t, Some(state), 2, "en");
6760 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6761 assert!(t.status.runnable());
6762 }
6763
6764 #[test]
6765 fn a_held_task_is_never_offered_to_the_loop() {
6766 let dir = tempfile::tempdir().unwrap();
6767 let queue = Queue::at(dir.path().to_path_buf());
6768 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6769 let mut t = task();
6770 t.id = format!("2026090{n}-000000-000{n}");
6771 t.priority = priority;
6772 queue.put(&mut t).unwrap();
6773 }
6774 let mut held = task();
6775 held.id = "20260909-000000-9999".to_owned();
6776 held.priority = 99;
6777 held.hold_machine(None);
6778 queue.put(&mut held).unwrap();
6779
6780 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6781 assert_eq!(order.len(), 3);
6782 assert!(!order.contains(&held.id));
6783 assert_eq!(
6784 order.first().cloned(),
6785 queue.next_runnable().map(|t| t.id),
6786 "the loop's first candidate is exactly what the queue offers"
6787 );
6788 assert_eq!(
6789 order,
6790 vec![
6791 "20260902-000000-0002".to_owned(),
6792 "20260903-000000-0003".to_owned(),
6793 "20260901-000000-0001".to_owned(),
6794 ],
6795 "priority first, then oldest, so nothing starves"
6796 );
6797 }
6798
6799 #[test]
6800 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6801 let dir = tempfile::tempdir().unwrap();
6802 let queue = Queue::at(dir.path().to_path_buf());
6803 let mut old = task();
6804 old.id = "20260101-000000-old0".to_owned();
6805 queue.put(&mut old).unwrap();
6806 let mut fresh = task();
6807 fresh.id = "20260101-000000-new0".to_owned();
6808 queue.put(&mut fresh).unwrap();
6809
6810 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
6814 std::thread::sleep(Duration::from_millis(60));
6815 let live = queue.claim(&fresh.id).unwrap();
6816
6817 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6818 assert_eq!(swept, vec![old.id.clone()]);
6819 assert!(
6820 queue.claim(&old.id).is_ok(),
6821 "an unparseable lock older than the threshold is swept"
6822 );
6823 assert!(
6824 queue.claim(&fresh.id).is_err(),
6825 "a live pid protects its lock regardless of age"
6826 );
6827 drop(live);
6828 }
6829
6830 #[test]
6831 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
6832 let dir = tempfile::tempdir().unwrap();
6842 let queue = Queue::at(dir.path().to_path_buf());
6843 let mut t = task();
6844 t.id = "20260101-000000-live".to_owned();
6845 queue.put(&mut t).unwrap();
6846
6847 let claim = queue.claim(&t.id).unwrap();
6848 std::thread::sleep(Duration::from_millis(60));
6849
6850 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6851 assert!(
6852 swept.is_empty(),
6853 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
6854 );
6855 assert!(
6856 queue.claim(&t.id).is_err(),
6857 "the lock still protects its task"
6858 );
6859 drop(claim);
6860 }
6861
6862 fn injected_dead_pid() -> u32 {
6865 std::process::id().checked_add(1).unwrap_or(1)
6866 }
6867
6868 #[test]
6869 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
6870 let dir = tempfile::tempdir().unwrap();
6871 let queue = Queue::at(dir.path().to_path_buf());
6872 let mut t = task();
6873 t.id = "20260101-000000-dead".to_owned();
6874 queue.put(&mut t).unwrap();
6875 let dead_pid = injected_dead_pid();
6876
6877 std::fs::write(
6882 dir.path().join(format!("{}.lock", t.id)),
6883 dead_pid.to_string(),
6884 )
6885 .unwrap();
6886
6887 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6888 pid != dead_pid
6889 });
6890 assert_eq!(
6891 swept,
6892 vec![t.id.clone()],
6893 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
6894 );
6895 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
6896 }
6897
6898 #[test]
6899 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
6900 let dir = tempfile::tempdir().unwrap();
6901 let queue = Queue::at(dir.path().to_path_buf());
6902 let mut t = task();
6903 t.id = "20260101-000000-late".to_owned();
6904 queue.put(&mut t).unwrap();
6905 let dead_pid = injected_dead_pid();
6906
6907 assert!(
6910 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
6911 "nothing has claimed the task yet"
6912 );
6913
6914 std::fs::write(
6917 dir.path().join(format!("{}.lock", t.id)),
6918 dead_pid.to_string(),
6919 )
6920 .unwrap();
6921
6922 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6926 pid != dead_pid
6927 });
6928 assert_eq!(swept, vec![t.id.clone()]);
6929 }
6930
6931 #[test]
6932 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
6933 crate::run::pin_test_home();
6938 let dir = tempfile::tempdir().unwrap();
6939 let queue = Queue::at(dir.path().to_path_buf());
6940 let mut t = task();
6941 t.id = "20260101-000000-crsh".to_owned();
6942 t.status = TaskStatus::Running;
6943 t.attempts = 1;
6944 t.runs.push("20260904-000000-4043".to_owned());
6948 queue.put(&mut t).unwrap();
6949 let dead_pid = injected_dead_pid();
6950
6951 std::fs::write(
6954 dir.path().join(format!("{}.lock", t.id)),
6955 dead_pid.to_string(),
6956 )
6957 .unwrap();
6958
6959 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
6965 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6966
6967 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6968 pid != dead_pid
6969 });
6970 assert_eq!(swept, vec![t.id.clone()]);
6971
6972 let reclaimed = reclaim_orphaned_running(&queue, 2);
6973 assert_eq!(reclaimed, vec![t.id.clone()]);
6974 let after = queue.get(&t.id).unwrap();
6975 assert_eq!(
6976 after.status,
6977 TaskStatus::Held,
6978 "no run.json to recover from, so a human is asked"
6979 );
6980 assert_eq!(
6981 after.runs,
6982 vec!["20260904-000000-4043".to_owned()],
6983 "the crashed run's id is kept as evidence, not discarded"
6984 );
6985 }
6986
6987 #[test]
6988 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6989 let dir = tempfile::tempdir().unwrap();
6990 let queue = Queue::at(dir.path().to_path_buf());
6991 let mut t = task();
6992 t.id = "20260101-000000-unknown".to_owned();
6993 queue.put(&mut t).unwrap();
6994 let dead_pid = injected_dead_pid();
6995 std::fs::write(
6996 dir.path().join(format!("{}.lock", t.id)),
6997 dead_pid.to_string(),
6998 )
6999 .unwrap();
7000
7001 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7002 assert!(swept.is_empty(), "an unknown pid must keep its lock");
7003 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7004 }
7005
7006 fn run_state_in(status: RunStatus, language: &str) -> RunState {
7007 let mut s = run_state(status);
7008 s.config.graph.language = language.to_owned();
7009 s
7010 }
7011
7012 fn unstarted_verdict(status: RunStatus) -> Verdict {
7013 Verdict {
7014 status,
7015 left_pr: false,
7016 quota_hit: false,
7017 parked: false,
7018 no_viable_candidates: false,
7019 }
7020 }
7021
7022 #[test]
7023 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7024 let mut t = task();
7025 t.attempts = 1;
7026 settle_in(
7027 &mut t,
7028 unstarted_verdict(RunStatus::AlreadyInBase),
7029 "already in main",
7030 1,
7031 phrases("en"),
7032 );
7033 assert_eq!(t.status, TaskStatus::Done);
7034 assert_eq!(t.attempts, 0);
7035 }
7036
7037 #[test]
7038 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7039 let reason = |language: &str| {
7040 let mut t = task();
7041 settle_in(
7042 &mut t,
7043 unstarted_verdict(RunStatus::Judging),
7044 "boom",
7045 1,
7046 phrases(language),
7047 );
7048 t.last_error.or(t.hold_reason).unwrap_or_default()
7049 };
7050 assert!(
7051 reason("en").starts_with("the graph stopped at `"),
7052 "{}",
7053 reason("en")
7054 );
7055 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7056 assert!(reason("日本語").contains("boom"));
7057 assert_eq!(reason("fr"), reason("en"));
7058 }
7059
7060 #[test]
7061 fn describe_follows_the_run_language_and_keeps_the_run_id() {
7062 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7063 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7064 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7065 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7066 assert!(ja.contains("[run "), "{ja}");
7067 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7068 assert!(ended.starts_with("run 終了: "), "{ended}");
7069 let mut de = run_state_in(RunStatus::Failed, "de");
7070 let mut en = run_state_in(RunStatus::Failed, "en");
7071 de.id = "same".to_owned();
7072 en.id = "same".to_owned();
7073 assert_eq!(describe(&de), describe(&en));
7074 }
7075
7076 #[test]
7077 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7078 use crate::handover::Refused;
7079 let cases = [
7080 Refused::Foreign {
7081 branch: "b".into(),
7082 path: "/w/x".into(),
7083 why: "made by hand".into(),
7084 },
7085 Refused::Unsafe {
7086 branch: "b".into(),
7087 path: "/w/x".into(),
7088 why: "its worktree has uncommitted changes (a.rs)".into(),
7089 },
7090 Refused::ReleaseFailed {
7091 branch: "b".into(),
7092 path: "/w/x".into(),
7093 run: "ab12".into(),
7094 },
7095 ];
7096 for r in &cases {
7097 let en = (phrases("en").handover_refused)(r);
7098 assert_eq!(en, r.to_string());
7099 let ja = (phrases("ja").handover_refused)(r);
7100 assert!(
7101 !ja.contains("is checked out") && !ja.contains("try again"),
7102 "{ja}"
7103 );
7104 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7105 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7106 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7107 }
7108 }
7109 assert!(phrases("en").handover_hint.contains("release the task"));
7110 assert!(phrases("ja").handover_hint.contains("解放"));
7111 }
7112
7113 #[test]
7114 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7115 let build = |lang: &str| {
7116 let mut s = run_state_in(RunStatus::Blocked, lang);
7117 s.id = "same".to_owned();
7118 s.config.graph.review_rounds = 3;
7119 let mut r = review_round(3);
7120 r.expected = 3;
7121 r.answered = 1;
7122 s.reviews.push(r);
7123 s.event(
7124 "review",
7125 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7126 );
7127 s
7128 };
7129 let en = describe(&build("en"));
7130 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7131 let ja = describe(&build("ja"));
7132 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7133 assert!(!ja.contains("never answered"), "{ja}");
7134 assert!(ja.contains("[run "), "{ja}");
7135
7136 let mut failed = build("ja");
7139 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7140 command: "cargo test".to_owned(),
7141 code: Some(1),
7142 output_tail: String::new(),
7143 duration_ms: 0,
7144 resource_blocked: false,
7145 });
7146 failed.event("review", "stopped; e2e failed: cargo test");
7147 let ja = describe(&failed);
7148 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7149 assert!(!ja.contains("席のレビュアー"), "{ja}");
7150 }
7151
7152 #[test]
7153 fn refusals_and_recovery_prose_follow_the_language() {
7154 let t = held_task_with("r1");
7155 let q = action_question(
7156 "r1",
7157 ask::ChoiceAction::Resume {
7158 run: "r1".to_owned(),
7159 },
7160 );
7161 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7162 ActionDecision::Refuse(s) => s,
7163 other => panic!("{other:?}"),
7164 };
7165 assert!(refuse(phrases("en")).contains("could not be read: gone"));
7166 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7167 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7168
7169 let mut held = task();
7170 reclaim(&mut held, None, 2, "ja");
7171 assert!(held.hold_reason.unwrap().contains("保留にしました"));
7172 let mut held = task();
7173 reclaim(&mut held, None, 2, "xx");
7174 assert!(held.hold_reason.unwrap().contains("held for a human"));
7175 }
7176
7177 fn run_state(status: RunStatus) -> RunState {
7178 let mut state = RunState::new(
7179 PathBuf::from("/repo"),
7180 "main".to_owned(),
7181 "abc1234def".to_owned(),
7182 "add retries".to_owned(),
7183 Config::default(),
7184 );
7185 state.status = status;
7186 state
7187 }
7188
7189 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7190 Candidate {
7191 index: 0,
7192 label,
7193 agent: "claude".to_owned(),
7194 branch: format!("magi/x/{label}"),
7195 worktree: PathBuf::from("/repo"),
7196 summary: summary.to_owned(),
7197 stat: String::new(),
7198 files: 0,
7199 commits: usize::from(!empty),
7200 empty,
7201 failed: failed.map(str::to_owned),
7202 verified_noop: None,
7203 duration_ms: 0,
7204 folded: false,
7205 }
7206 }
7207
7208 #[test]
7209 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7210 let mut state = run_state(RunStatus::Blocked);
7211 state.gate = vec![
7212 CommandOutcome {
7213 command: "cargo make check".to_owned(),
7214 code: Some(0),
7215 output_tail: "ok".to_owned(),
7216 duration_ms: 0,
7217 resource_blocked: false,
7218 },
7219 CommandOutcome {
7220 command: "cargo test".to_owned(),
7221 code: Some(101),
7222 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7223 duration_ms: 0,
7224 resource_blocked: false,
7225 },
7226 ];
7227 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7228 assert!(d.contains("cargo test"), "{d}");
7229 assert!(
7230 !d.contains("cargo make check"),
7231 "a passing check is not a diagnostic: {d}"
7232 );
7233 assert!(d.contains("assertion failed"), "{d}");
7234 }
7235
7236 #[test]
7237 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7238 let mut state = run_state(RunStatus::Blocked);
7239 state.event(
7240 "land",
7241 "stopped: the fixer produced no commit while 2 check(s) were failing \
7242 (build, lint); stopping instead of looping on an unchanged tree",
7243 );
7244 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7245 assert!(d.contains("build"), "{d}");
7246 assert!(d.contains("lint"), "{d}");
7247 assert!(d.contains("fixer produced no commit"), "{d}");
7248 }
7249
7250 #[test]
7251 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7252 let state = run_state(RunStatus::VerifiedNoop);
7257 let d = describe(&state);
7258 assert!(
7259 d.contains("agent-verified no-op"),
7260 "expected the display label, not the wire spelling: {d}"
7261 );
7262 assert!(!d.contains("verified_noop"), "{d}");
7263 }
7264
7265 #[test]
7266 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7267 let mut state = run_state(RunStatus::Failed);
7273 state.candidates = vec![candidate(
7274 'A',
7275 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7276 true,
7277 None,
7278 )];
7279 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7280 assert!(d.contains("candidate A"), "{d}");
7281 assert!(d.contains("tagged v1.2.3"), "{d}");
7282 }
7283
7284 #[test]
7285 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7286 let mut state = run_state(RunStatus::Failed);
7287 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7288 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7289 assert!(d.contains("candidate A"), "{d}");
7290 assert!(d.contains("agent timed out"), "{d}");
7291 }
7292
7293 #[test]
7294 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7295 let mut state = run_state(RunStatus::Failed);
7298 state.candidates = vec![candidate('A', "did the work", false, None)];
7299 assert!(diagnostic(&state).is_none());
7300 }
7301
7302 #[test]
7303 fn diagnostic_is_bounded_however_much_a_run_printed() {
7304 let mut state = run_state(RunStatus::Blocked);
7305 state.gate = vec![
7306 CommandOutcome {
7307 command: "cargo test".to_owned(),
7308 code: Some(101),
7309 output_tail: "x".repeat(50_000),
7310 duration_ms: 0,
7311 resource_blocked: false,
7312 },
7313 CommandOutcome {
7314 command: "cargo clippy".to_owned(),
7315 code: Some(1),
7316 output_tail: "y".repeat(50_000),
7317 duration_ms: 0,
7318 resource_blocked: false,
7319 },
7320 ];
7321 state.candidates = vec![
7322 candidate('A', &"z".repeat(50_000), true, None),
7323 candidate('B', &"w".repeat(50_000), true, None),
7324 ];
7325 let d = diagnostic(&state).expect("plenty here to diagnose");
7326 assert!(
7327 d.len() <= DIAGNOSTIC_MAX,
7328 "diagnostic grew to {} bytes, unbounded",
7329 d.len()
7330 );
7331 }
7332
7333 #[test]
7334 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7335 let mut state = run_state(RunStatus::Blocked);
7336 state.gate = vec![CommandOutcome {
7337 command: "cargo test".to_owned(),
7338 code: Some(101),
7339 output_tail: "assertion failed".to_owned(),
7340 duration_ms: 0,
7341 resource_blocked: false,
7342 }];
7343 let verdict = Verdict {
7344 status: RunStatus::Blocked,
7345 left_pr: false,
7346 quota_hit: false,
7347 parked: false,
7348 no_viable_candidates: false,
7349 };
7350
7351 let mut t = task();
7354 t.start("run-1".to_owned());
7355 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7356 assert_eq!(t.status, TaskStatus::Failed);
7357 assert!(t.diagnostic.is_none());
7358
7359 t.start("run-2".to_owned());
7362 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7363 assert_eq!(t.status, TaskStatus::Held);
7364 let d = t.diagnostic.expect("a held task must carry its diagnostic");
7365 assert!(d.contains("cargo test"), "{d}");
7366 }
7367
7368 #[test]
7369 fn a_held_task_names_the_open_question_it_is_waiting_on() {
7370 crate::run::pin_test_home();
7375 let home = crate::run::home();
7376 let state = run_state(RunStatus::VerifiedNoop);
7377 let mut q = ask::Question::new(
7378 state.id.clone(),
7379 "implement".to_owned(),
7380 "impl-A".to_owned(),
7381 "is this really a no-op?".to_owned(),
7382 String::new(),
7383 Vec::new(),
7384 );
7385 Questions::at(home.join("questions")).put(&mut q).unwrap();
7386
7387 let verdict = Verdict {
7388 status: RunStatus::VerifiedNoop,
7389 left_pr: false,
7390 quota_hit: false,
7391 parked: false,
7392 no_viable_candidates: false,
7393 };
7394 let mut t = task();
7395 t.start(state.id.clone());
7396 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7397
7398 assert_eq!(t.status, TaskStatus::Held);
7399 let reason = t.hold_reason.expect("a held task must record why");
7400 assert!(
7401 reason.starts_with("run ended agent-verified no-op"),
7402 "the original settle reason must survive unchanged: {reason}"
7403 );
7404 assert!(
7405 reason.contains(q.short()),
7406 "the open question's id must be named so the notice is actionable: {reason}"
7407 );
7408 }
7409
7410 #[test]
7411 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7412 crate::run::pin_test_home();
7413 let state = run_state(RunStatus::VerifiedNoop);
7414
7415 let verdict = Verdict {
7416 status: RunStatus::VerifiedNoop,
7417 left_pr: false,
7418 quota_hit: false,
7419 parked: false,
7420 no_viable_candidates: false,
7421 };
7422 let mut t = task();
7423 t.start(state.id.clone());
7424 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7425
7426 assert_eq!(t.status, TaskStatus::Held);
7427 assert_eq!(
7428 t.hold_reason.as_deref(),
7429 Some("run ended agent-verified no-op"),
7430 "nothing to append when the question was already answered or never asked"
7431 );
7432 }
7433
7434 #[test]
7435 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7436 crate::run::pin_test_home();
7437 let mut first = run_state(RunStatus::Blocked);
7438 first.id = "20260101-000000-sup1".to_owned();
7439 first.save().unwrap();
7440 let mut second = run_state(RunStatus::Merged);
7441 second.id = "20260101-000000-sup2".to_owned();
7442 second.save().unwrap();
7443
7444 let mut t = task();
7445 t.runs = vec![first.id.clone(), second.id.clone()];
7446 t.status = TaskStatus::Done;
7447
7448 supersede_prior_runs(&t, &crate::run::home());
7449
7450 assert_eq!(
7451 RunState::load(&first.id).unwrap().status,
7452 RunStatus::Superseded,
7453 "the first attempt's Blocked no longer needs anyone's attention"
7454 );
7455 assert_eq!(
7456 RunState::load(&second.id).unwrap().status,
7457 RunStatus::Merged,
7458 "the run that actually succeeded is left exactly as it was"
7459 );
7460 }
7461
7462 #[test]
7463 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7464 crate::run::pin_test_home();
7470 let mut first = run_state(RunStatus::Blocked);
7471 first.id = "20260101-000000-sup9".to_owned();
7472 first.driver_pid = Some(std::process::id());
7475 first.driver_started_at = Some(
7476 crate::proc::process_started_at(std::process::id())
7477 .expect("this test process's own start time must be queryable"),
7478 );
7479 first.save().unwrap();
7480 let mut second = run_state(RunStatus::Merged);
7481 second.id = "20260101-000000-supa".to_owned();
7482 second.save().unwrap();
7483
7484 let mut t = task();
7485 t.runs = vec![first.id.clone(), second.id.clone()];
7486 t.status = TaskStatus::Done;
7487
7488 supersede_prior_runs(&t, &crate::run::home());
7489
7490 assert_eq!(
7491 RunState::load(&first.id).unwrap().status,
7492 RunStatus::Blocked,
7493 "a live driver_pid means something is still actually working this run, \
7494 even though no daemon claims it - rewriting under it would just be \
7495 undone the next time that process saves"
7496 );
7497 }
7498
7499 #[test]
7500 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7501 let dir = tempfile::tempdir().unwrap();
7507 let home = dir.path().to_path_buf();
7508 let queue = Queue::at(dir.path().join("queue"));
7509
7510 let mut first = run_state(RunStatus::Blocked);
7511 first.id = "20260101-000000-supd".to_owned();
7512 first.driver_pid = Some(std::process::id());
7513 first.driver_started_at = Some(
7514 crate::proc::process_started_at(std::process::id())
7515 .expect("this test process's own start time must be queryable"),
7516 );
7517 first.save_under(&home).unwrap();
7518 let mut second = run_state(RunStatus::Merged);
7519 second.id = "20260101-000000-supe".to_owned();
7520 second.save_under(&home).unwrap();
7521
7522 let mut t = task();
7523 t.runs = vec![first.id.clone(), second.id.clone()];
7524 t.status = TaskStatus::Done;
7525 queue.put(&mut t).unwrap();
7526
7527 resweep_superseded_attempts(&queue, &home);
7528 assert_eq!(
7529 RunState::load_under(&first.id, &home).unwrap().status,
7530 RunStatus::Blocked,
7531 "still live on the first pass, so still untouched"
7532 );
7533
7534 let mut stale = RunState::load_under(&first.id, &home).unwrap();
7540 stale.driver_started_at = Some("1".to_owned());
7541 stale.save_under(&home).unwrap();
7542
7543 resweep_superseded_attempts(&queue, &home);
7544 assert_eq!(
7545 RunState::load_under(&first.id, &home).unwrap().status,
7546 RunStatus::Superseded,
7547 "the second pass catches up what the first one correctly skipped"
7548 );
7549 }
7550
7551 #[test]
7552 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7553 crate::run::pin_test_home();
7554 let mut first = run_state(RunStatus::Blocked);
7555 first.id = "20260101-000000-sup3".to_owned();
7556 first.save().unwrap();
7557 let mut second = run_state(RunStatus::Blocked);
7558 second.id = "20260101-000000-sup4".to_owned();
7559 second.save().unwrap();
7560
7561 let mut t = task();
7562 t.runs = vec![first.id.clone(), second.id.clone()];
7563 t.status = TaskStatus::Failed;
7567
7568 supersede_prior_runs(&t, &crate::run::home());
7569
7570 assert_eq!(
7571 RunState::load(&first.id).unwrap().status,
7572 RunStatus::Blocked
7573 );
7574 assert_eq!(
7575 RunState::load(&second.id).unwrap().status,
7576 RunStatus::Blocked
7577 );
7578 }
7579
7580 #[test]
7581 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7582 crate::run::pin_test_home();
7586 let mut first = run_state(RunStatus::Blocked);
7587 first.id = "20260101-000000-sup5".to_owned();
7588 first.save().unwrap();
7589
7590 let mut t = task();
7591 t.runs = vec![first.id.clone()];
7592 t.status = TaskStatus::Done;
7593
7594 supersede_prior_runs(&t, &crate::run::home());
7595
7596 assert_eq!(
7597 RunState::load(&first.id).unwrap().status,
7598 RunStatus::Blocked,
7599 "a single-attempt task has no earlier run to supersede"
7600 );
7601 }
7602
7603 #[test]
7604 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7605 crate::run::pin_test_home();
7612 let mut first = run_state(RunStatus::Blocked);
7613 first.id = "20260101-000000-supb".to_owned();
7614 first.save().unwrap();
7615 let mut second = run_state(RunStatus::Failed);
7616 second.id = "20260101-000000-supc".to_owned();
7617 second.save().unwrap();
7618
7619 let mut t = task();
7620 t.runs = vec![first.id.clone(), second.id.clone()];
7621 t.status = TaskStatus::Done;
7622
7623 supersede_prior_runs(&t, &crate::run::home());
7624
7625 assert_eq!(
7626 RunState::load(&first.id).unwrap().status,
7627 RunStatus::Blocked,
7628 "the task's last attempt never landed, so there is nothing here \
7629 actually superseding it"
7630 );
7631 }
7632
7633 #[test]
7634 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7635 crate::run::pin_test_home();
7639 let mut failed = run_state(RunStatus::Failed);
7640 failed.id = "20260101-000000-sup6".to_owned();
7641 failed.save().unwrap();
7642 let mut noop = run_state(RunStatus::VerifiedNoop);
7643 noop.id = "20260101-000000-sup7".to_owned();
7644 noop.save().unwrap();
7645 let mut winner = run_state(RunStatus::Ready);
7646 winner.id = "20260101-000000-sup8".to_owned();
7647 winner.save().unwrap();
7648
7649 let mut t = task();
7650 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7651 t.status = TaskStatus::Done;
7652
7653 supersede_prior_runs(&t, &crate::run::home());
7654
7655 assert_eq!(
7656 RunState::load(&failed.id).unwrap().status,
7657 RunStatus::Failed
7658 );
7659 assert_eq!(
7660 RunState::load(&noop.id).unwrap().status,
7661 RunStatus::VerifiedNoop
7662 );
7663 }
7664
7665 fn approval_question(run: &str) -> ask::Question {
7666 ask::Question::new(
7667 run.to_owned(),
7668 land::APPROVAL_NODE.to_owned(),
7669 "land".to_owned(),
7670 "merge?".to_owned(),
7671 String::new(),
7672 vec!["merge".to_owned(), "hold".to_owned()],
7673 )
7674 }
7675
7676 #[test]
7677 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7678 crate::run::pin_test_home();
7679 let mut state = run_state(RunStatus::Landing);
7680 state.id = "20260101-000000-fre1".to_owned();
7681 state.parked = true;
7682 state.save().unwrap();
7683 ask::Questions::open()
7684 .put(&mut approval_question(&state.id))
7685 .unwrap();
7686
7687 let mut t = task();
7688 t.runs.push(state.id.clone());
7689 assert_eq!(
7690 land_resume_state(&t),
7691 LandResume::StillWaiting,
7692 "nobody has answered and the timeout has not passed"
7693 );
7694 }
7695
7696 #[test]
7697 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7698 crate::run::pin_test_home();
7699 let mut state = run_state(RunStatus::Gating);
7700 state.id = "20260101-000000-gt01".to_owned();
7701 state.parked = true;
7702 state.config.graph.answer_timeout = 60;
7703 state.github_text = Some(crate::run::GithubTextAsk {
7704 rewrite: None,
7705 fingerprint: "f".into(),
7706 title: true,
7707 body: false,
7708 categories: vec!["title-language".into()],
7709 question: None,
7710 asks: 1,
7711 resolved: false,
7712 chosen_title: None,
7713 choice: None,
7714 });
7715 state.save().unwrap();
7716 let store = ask::Questions::open();
7717 let mut q = ask::Question::new(
7718 state.id.clone(),
7719 crate::github_text::ASK_NODE.to_owned(),
7720 crate::github_text::ASK_SEAT.to_owned(),
7721 "s".into(),
7722 String::new(),
7723 vec!["use fallback".into()],
7724 );
7725 store.put(&mut q).unwrap();
7726 let mut t = task();
7727 t.runs.push(state.id.clone());
7728 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7729 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7730 store.put(&mut q).unwrap();
7731 assert_eq!(land_resume_state(&t), LandResume::Ready);
7732 assert!(!store.get(&q.id).unwrap().status.open());
7733 state.github_text.as_mut().unwrap().resolved = true;
7735 state.save().unwrap();
7736 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7737 }
7738
7739 #[test]
7740 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7741 crate::run::pin_test_home();
7746 let mut state = run_state(RunStatus::Landing);
7747 state.id = "20260101-000000-exp1".to_owned();
7748 state.parked = true;
7749 state.config.graph.answer_timeout = 60;
7750 state.save().unwrap();
7751
7752 let store = ask::Questions::open();
7753 let mut q = approval_question(&state.id);
7754 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7755 store.put(&mut q).unwrap();
7756
7757 let mut t = task();
7758 t.runs.push(state.id.clone());
7759 assert_eq!(
7760 land_resume_state(&t),
7761 LandResume::Ready,
7762 "an expired question must not be waited on forever"
7763 );
7764
7765 let after = store.get(&q.id).unwrap();
7766 assert!(
7767 !after.status.open(),
7768 "the question is abandoned, not silently ignored"
7769 );
7770 assert!(
7771 after.resolution().is_none(),
7772 "an abandoned question is not read as a decision"
7773 );
7774 }
7775
7776 #[test]
7777 fn reclaim_settles_a_running_task_against_its_last_run() {
7778 let mut t = task();
7779 t.start("20260904-000000-4043".to_owned());
7780 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
7781 assert_eq!(
7782 t.status,
7783 TaskStatus::Done,
7784 "a run that actually finished must not stay `running` forever"
7785 );
7786 }
7787
7788 #[test]
7789 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
7790 let mut t = task();
7791 t.start("20260904-000000-4043".to_owned());
7792 t.last_error = Some("earlier trouble".to_owned());
7793 let mut state = run_state(RunStatus::Judging);
7794 state.parked = true;
7795 reclaim(&mut t, Some(state), 1, "en");
7796 assert_eq!(t.status, TaskStatus::Parked);
7797 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
7798 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7799 assert!(t.park_reason.is_some());
7800 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
7801 assert!(!t.fresh_start);
7802 assert!(t.status.runnable());
7803 }
7804
7805 #[test]
7806 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
7807 let mut t = task();
7808 t.start("20260904-000000-4043".to_owned());
7809 t.last_error = Some("earlier trouble".to_owned());
7810 settle(
7811 &mut t,
7812 Verdict {
7813 status: RunStatus::Judging,
7814 left_pr: false,
7815 quota_hit: false,
7816 parked: true,
7817 no_viable_candidates: false,
7818 },
7819 "parked after `judging`",
7820 1,
7821 );
7822 assert_eq!(t.status, TaskStatus::Parked);
7823 assert_eq!(t.attempts, 0);
7824 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7825 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
7826 assert_eq!(t.schema, crate::queue::SCHEMA);
7827 assert!(
7828 crate::notices::task_held(&t).is_none(),
7829 "a park is not news"
7830 );
7831 t.start("20260904-000000-4043".to_owned());
7832 assert_eq!(t.park_reason, None);
7833 }
7834
7835 #[test]
7836 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
7837 let mut t = task();
7841 t.start("20260904-000000-4043".to_owned());
7842 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
7843 assert_eq!(t.status, TaskStatus::Failed);
7844 assert!(t.status.runnable());
7845 }
7846
7847 #[test]
7848 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
7849 let mut t = task();
7850 t.start("20260904-000000-4043".to_owned());
7851 assert_eq!(t.attempts, 1);
7852 let mut run = run_state(RunStatus::Implementing);
7853 run.id = "20260904-000000-4043".to_owned();
7854 run.begin_pass();
7855 let cause = crate::run::ParkCause::Upgrade {
7856 from: "0.121.0".to_owned(),
7857 to: Some("0.121.1".to_owned()),
7858 };
7859 run.end_pass_parked(cause.clone());
7860 run.parked = true;
7861 let verdict = Verdict {
7862 status: run.status,
7863 left_pr: false,
7864 quota_hit: false,
7865 parked: true,
7866 no_viable_candidates: false,
7867 };
7868 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
7869 assert_eq!(t.attempts, 0);
7870 assert_eq!(t.passes.len(), 1);
7871 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7872 assert_eq!(t.passes[0].parked, Some(cause));
7873 assert_eq!(t.passes[0].pass_index, 0);
7874
7875 t.start("20260904-000000-4043".to_owned());
7878 run.begin_pass();
7879 run.status = RunStatus::Failed;
7880 let verdict = Verdict {
7881 status: RunStatus::Failed,
7882 left_pr: false,
7883 quota_hit: false,
7884 parked: false,
7885 no_viable_candidates: false,
7886 };
7887 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
7888 assert_eq!(t.passes.len(), 2);
7889 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7890 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
7891 assert_eq!(t.passes[1].pass_index, 1);
7892 assert_eq!(t.attempts, 1);
7893 }
7894
7895 #[test]
7896 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
7897 let mut t = task();
7898 t.start("20260904-000000-4043".to_owned());
7899 reclaim(&mut t, None, 2, "en");
7900 assert_eq!(t.status, TaskStatus::Held);
7901 assert!(
7902 t.last_error
7903 .as_deref()
7904 .is_some_and(|e| e.contains("running")),
7905 "the operator needs to know why this task was held"
7906 );
7907 }
7908
7909 #[test]
7910 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
7911 let dir = tempfile::tempdir().unwrap();
7912 let queue = Queue::at(dir.path().to_path_buf());
7913
7914 let mut orphaned = task();
7916 orphaned.id = "20260904-000000-orph".to_owned();
7917 orphaned.status = TaskStatus::Running;
7918 orphaned.attempts = 1;
7919 queue.put(&mut orphaned).unwrap();
7920
7921 let mut alive = task();
7922 alive.id = "20260904-000000-live".to_owned();
7923 alive.status = TaskStatus::Running;
7924 alive.attempts = 1;
7925 queue.put(&mut alive).unwrap();
7926 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
7927
7928 let mut queued = task();
7929 queued.id = "20260904-000000-wait".to_owned();
7930 queue.put(&mut queued).unwrap();
7931
7932 let reclaimed = reclaim_orphaned_running(&queue, 2);
7933 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
7934
7935 assert_eq!(
7936 queue.get(&orphaned.id).unwrap().status,
7937 TaskStatus::Held,
7938 "nothing was driving it and there was no run to recover"
7939 );
7940 assert_eq!(
7941 queue.get(&alive.id).unwrap().status,
7942 TaskStatus::Running,
7943 "a live claim must protect the task it belongs to"
7944 );
7945 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
7946 }
7947
7948 fn read_run_under(home: &Path, id: &str) -> RunState {
7954 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
7955 serde_json::from_str(&body).unwrap()
7956 }
7957
7958 #[test]
7959 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
7960 let dir = tempfile::tempdir().unwrap();
7961 let home = dir.path().to_path_buf();
7962 let now = Timestamp::now();
7963 let overrun_seat = || crate::run::ActiveSeat {
7964 node: "implement".to_owned(),
7965 started_at: now - jiff::SignedDuration::new(21_000, 0),
7966 timeout_secs: 3_600,
7967 attempt: 0,
7968 task: None,
7969 command: None,
7970 index: None,
7971 total: None,
7972 };
7973
7974 let mut dead = run_state(RunStatus::Implementing);
7975 dead.id = "20260101-000000-dead".to_owned();
7976 dead.active.insert("impl-A".to_owned(), overrun_seat());
7977 dead.driver_pid = Some(4242);
7980 dead.save_under(&home).unwrap();
7981
7982 let mut alive = run_state(RunStatus::Implementing);
7985 alive.id = "20260101-000000-aliv".to_owned();
7986 alive.active.insert("impl-A".to_owned(), overrun_seat());
7987 alive.save_under(&home).unwrap();
7988 let mut status = Status::new();
7989 status.current = vec![Current {
7990 task: "20260101-000000-task".to_owned(),
7991 run: alive.id.clone(),
7992 }];
7993 write_status_to(&home.join("daemon.json"), &status).unwrap();
7994
7995 let questions = Questions::at(home.join("questions"));
7999 let mut q = ask::Question::new(
8000 dead.id.clone(),
8001 "implement".to_owned(),
8002 "impl-A".to_owned(),
8003 "Which storage backend?".to_owned(),
8004 String::new(),
8005 vec!["SQLite".to_owned(), "Redis".to_owned()],
8006 );
8007 questions.put(&mut q).unwrap();
8008
8009 let abandoned = reclaim_abandoned_runs_with(
8010 &home,
8011 now,
8012 |pid| if pid == 4242 { Some(false) } else { None },
8013 |_| panic!("a query answering Dead outright needs no identity corroboration"),
8014 );
8015 assert_eq!(abandoned, vec![dead.id.clone()]);
8016
8017 let reloaded = read_run_under(&home, &dead.id);
8018 assert_eq!(reloaded.status, RunStatus::Failed);
8019 assert!(reloaded.active.is_empty());
8020 assert!(
8021 !questions.get(&q.id).unwrap().status.open(),
8022 "the failed run's own open question must be settled in the same pass"
8023 );
8024
8025 let still_alive = read_run_under(&home, &alive.id);
8026 assert_eq!(
8027 still_alive.status,
8028 RunStatus::Implementing,
8029 "a live daemon's claim protects it"
8030 );
8031 assert!(!still_alive.active.is_empty());
8032 }
8033
8034 #[test]
8044 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8045 let dir = tempfile::tempdir().unwrap();
8046 let home = dir.path().to_path_buf();
8047 let now = Timestamp::now();
8048
8049 let mut manual = run_state(RunStatus::Reviewing);
8050 manual.id = "20260101-000000-manl".to_owned();
8051 manual.active.insert(
8052 "review-1".to_owned(),
8053 crate::run::ActiveSeat {
8054 node: "review".to_owned(),
8055 started_at: now - jiff::SignedDuration::new(21_000, 0),
8056 timeout_secs: 3_600,
8057 attempt: 0,
8058 task: None,
8059 command: None,
8060 index: None,
8061 total: None,
8062 },
8063 );
8064 manual.driver_pid = Some(4242);
8068 manual.driver_started_at = Some("1790000000".to_owned());
8069 manual.save_under(&home).unwrap();
8070
8071 let abandoned = reclaim_abandoned_runs_with(
8072 &home,
8073 now,
8074 |pid| if pid == 4242 { Some(true) } else { None },
8075 |pid| {
8076 if pid == 4242 {
8077 Some("1790000000".to_owned())
8078 } else {
8079 None
8080 }
8081 },
8082 );
8083 assert!(
8084 abandoned.is_empty(),
8085 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8086 );
8087
8088 let reloaded = read_run_under(&home, &manual.id);
8089 assert_eq!(reloaded.status, RunStatus::Reviewing);
8090 assert!(!reloaded.active.is_empty());
8091 }
8092
8093 #[test]
8094 fn an_already_claimed_task_is_skipped_rather_than_failed() {
8095 let dir = tempfile::tempdir().unwrap();
8096 let queue = Queue::at(dir.path().to_path_buf());
8097 let mut only = task();
8098 queue.put(&mut only).unwrap();
8099
8100 let _elsewhere = queue.claim(&only.id).unwrap();
8101 let candidates = runnable(&queue);
8102 assert_eq!(candidates.len(), 1, "the task is still runnable");
8103 assert!(
8104 queue.claim(&candidates[0].id).is_err(),
8105 "the loop cannot take a claim somebody else holds"
8106 );
8107
8108 let after = queue.get(&only.id).unwrap();
8109 assert_eq!(after.status, TaskStatus::Queued);
8110 assert_eq!(
8111 after.attempts, 0,
8112 "losing the race is not an attempt at the task"
8113 );
8114 assert_eq!(after.last_error, None);
8115 }
8116
8117 #[test]
8118 fn the_status_file_round_trips_and_its_heartbeat_advances() {
8119 let dir = tempfile::tempdir().unwrap();
8120 let path = dir.path().join("daemon.json");
8121
8122 let mut status = Status::new();
8123 status.idle = false;
8124 status.completed = 7;
8125 status.current = vec![Current {
8126 task: "20260902-000000-t111".to_owned(),
8127 run: "20260902-000001-r111".to_owned(),
8128 }];
8129 write_status_to(&path, &status).unwrap();
8130 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8131 assert_eq!(first.schema, SCHEMA);
8132 assert_eq!(first.pid, std::process::id());
8133 assert!(!first.idle);
8134 assert_eq!(first.completed, 7);
8135 assert_eq!(first.current, status.current);
8136 assert!(
8137 !path.with_extension("json.tmp").exists(),
8138 "the temp file is renamed, not left behind"
8139 );
8140
8141 std::thread::sleep(Duration::from_millis(5));
8142 status.updated_at = Timestamp::now();
8143 status.polls = 3;
8144 write_status_to(&path, &status).unwrap();
8145 let second: Status =
8146 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8147 assert!(
8148 second.updated_at > first.updated_at,
8149 "a reader can only detect staleness if the heartbeat moves"
8150 );
8151 assert_eq!(
8152 second.started_at, first.started_at,
8153 "the start time is not a heartbeat"
8154 );
8155 assert_eq!(second.polls, 3);
8156 }
8157
8158 #[test]
8159 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8160 let dir = tempfile::tempdir().unwrap();
8161
8162 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8163
8164 let mut status = Status::new();
8165 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8166 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8167 let stale = read_status(dir.path()).unwrap();
8168 assert!(
8169 !stale.running(Timestamp::now()),
8170 "a minute without a heartbeat is a dead daemon, not a busy one"
8171 );
8172 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8173
8174 status.updated_at = Timestamp::now();
8175 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8176 let fresh = read_status(dir.path()).unwrap();
8177 assert!(fresh.running(Timestamp::now()));
8178 }
8179
8180 #[test]
8181 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8182 let dir = tempfile::tempdir().unwrap();
8183 let now = Timestamp::now();
8184 let mine = "20260903-080619-01c2";
8185
8186 assert!(
8187 !is_working_on(dir.path(), mine, now),
8188 "no status file means nobody is working on anything"
8189 );
8190
8191 let mut status = Status::new();
8192 status.current = vec![Current {
8193 task: "20260903-080340-0167".to_owned(),
8194 run: mine.to_owned(),
8195 }];
8196 status.updated_at = now;
8197 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8198 assert!(is_working_on(dir.path(), mine, now));
8199 assert!(
8200 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8201 "a daemon busy with one run is not working on another"
8202 );
8203
8204 status.updated_at = now - jiff::SignedDuration::from_secs(600);
8207 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8208 assert!(
8209 !is_working_on(dir.path(), mine, now),
8210 "a stale heartbeat is a dead daemon, so its run is a leftover"
8211 );
8212 }
8213
8214 #[test]
8215 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8216 let dir = tempfile::tempdir().unwrap();
8217 let now = Timestamp::now();
8218
8219 assert!(
8220 !is_working_on_short(dir.path(), "01c2", now),
8221 "no status file means nobody is working on anything"
8222 );
8223
8224 let mut status = Status::new();
8225 status.current = vec![Current {
8226 task: "20260903-080340-0167".to_owned(),
8227 run: "20260903-080619-01c2".to_owned(),
8228 }];
8229 status.updated_at = now;
8230 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8231 assert!(
8232 is_working_on_short(dir.path(), "01c2", now),
8233 "the run's short id is the last block of its full id"
8234 );
8235 assert!(
8236 !is_working_on_short(dir.path(), "3cbf", now),
8237 "a daemon busy with one worktree bay is not working on another"
8238 );
8239 }
8240
8241 #[test]
8242 fn a_newer_status_file_still_yields_a_reading() {
8243 let dir = tempfile::tempdir().unwrap();
8244 std::fs::write(
8247 dir.path().join("daemon.json"),
8248 serde_json::json!({
8249 "schema": 2,
8250 "updated_at": Timestamp::now().to_string(),
8251 "idle": true,
8252 "surprise": { "nested": [1, 2, 3] },
8253 })
8254 .to_string(),
8255 )
8256 .unwrap();
8257
8258 let reading = read_status(dir.path()).expect("a forward-compatible read");
8259 assert!(reading.running(Timestamp::now()));
8260 assert!(reading.idle);
8261 assert!(reading.current.is_empty());
8262 }
8263
8264 #[test]
8265 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8266 let dir = tempfile::tempdir().unwrap();
8272 std::fs::write(
8273 dir.path().join("daemon.json"),
8274 serde_json::json!({
8275 "schema": 1,
8276 "pid": 4242,
8277 "updated_at": Timestamp::now().to_string(),
8278 "idle": false,
8279 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8280 "completed": 3,
8281 "polls": 9,
8282 })
8283 .to_string(),
8284 )
8285 .unwrap();
8286
8287 let reading = read_status(dir.path()).expect("an older shape must still parse");
8288 assert!(reading.running(Timestamp::now()));
8289 assert_eq!(
8290 reading.current,
8291 vec![Current {
8292 task: "20260902-140501-aaaa".to_owned(),
8293 run: "20260902-140502-bbbb".to_owned(),
8294 }]
8295 );
8296 }
8297
8298 #[test]
8299 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8300 let dir = tempfile::tempdir().unwrap();
8301 std::fs::write(
8302 dir.path().join("daemon.json"),
8303 serde_json::json!({
8304 "schema": 1,
8305 "updated_at": Timestamp::now().to_string(),
8306 "idle": true,
8307 "current": null,
8308 })
8309 .to_string(),
8310 )
8311 .unwrap();
8312 let with_null = read_status(dir.path()).expect("null must still parse");
8313 assert!(with_null.current.is_empty());
8314
8315 std::fs::write(
8316 dir.path().join("daemon.json"),
8317 serde_json::json!({
8318 "schema": 1,
8319 "updated_at": Timestamp::now().to_string(),
8320 "idle": true,
8321 })
8322 .to_string(),
8323 )
8324 .unwrap();
8325 let absent = read_status(dir.path()).expect("a missing field must still parse");
8326 assert!(absent.current.is_empty());
8327 }
8328
8329 #[test]
8330 fn a_task_without_a_repository_runs_in_the_daemons_default() {
8331 let fallback = Path::new("/default");
8332 let mut blank = task();
8333 blank.repo = PathBuf::new();
8334 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8335 let mut dot = task();
8336 dot.repo = PathBuf::from(".");
8337 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8338 assert_eq!(
8339 repo_for(&task(), fallback),
8340 PathBuf::from("/repo"),
8341 "a task that names a repository keeps it"
8342 );
8343 }
8344
8345 #[test]
8346 fn task_implementers_edit_inherits_daemon_config_and_merge() {
8347 let dir = tempfile::tempdir().unwrap();
8348 let path = dir.path().join("explicit.toml");
8349 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8350 let opts = Opts {
8351 config: Some(path),
8352 merge: Some("none".into()),
8353 ..Default::default()
8354 };
8355 let mut t = task();
8356 t.set_implementers(
8357 2,
8358 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8359 .unwrap(),
8360 )
8361 .unwrap();
8362 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8363 assert_eq!(cfg.graph.implementers, 2);
8364 assert_eq!(cfg.graph.judges, 1);
8365 assert_eq!(cfg.merge.mode, MergeMode::None);
8366 t.set_implementers(1, &cfg).unwrap();
8367 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8368 apply_task_implementers(&mut cfg, &t);
8369 assert_eq!(cfg.graph.implementers, 1);
8370 assert_eq!(cfg.graph.judges, 1);
8371 assert_eq!(cfg.merge.mode, MergeMode::None);
8372 }
8373
8374 #[test]
8375 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8376 let dir = tempfile::tempdir().unwrap();
8377 let repo = dir.path().join("repo");
8378 std::fs::create_dir(&repo).unwrap();
8379 std::fs::write(
8380 repo.join("magi.toml"),
8381 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8382 )
8383 .unwrap();
8384 let daemon_config = dir.path().join("daemon.toml");
8385 std::fs::write(
8386 &daemon_config,
8387 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8388 )
8389 .unwrap();
8390 let opts = Opts {
8391 config: Some(daemon_config),
8392 merge: Some("pr".into()),
8393 ..Default::default()
8394 };
8395 let q = Queue::at(dir.path().join("queue"));
8396 let validation: Config =
8397 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8398 .unwrap();
8399 for record in ["{}", r#"{"candidates":2}"#] {
8401 let overrides = serde_json::from_str(record).unwrap();
8402 let filing = crate::direct::Filing {
8403 instruction: "work".into(),
8404 title: "direct".into(),
8405 repo: repo.clone(),
8406 source: crate::queue::Source::Human,
8407 solo: false,
8408 overrides,
8409 review_of: None,
8410 };
8411 let filed =
8412 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8413 let crate::direct::Filed::Standalone {
8414 mut task,
8415 claim: _claim,
8416 } = filed
8417 else {
8418 panic!("local filing")
8419 };
8420 let before = prepare_for(&repo, &opts, &task).unwrap();
8421 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8422 assert_eq!(
8423 before.merge.mode,
8424 MergeMode::None,
8425 "daemon --merge must not leak"
8426 );
8427 for n in [2, 1, 2] {
8428 task.set_implementers(n, &validation).unwrap();
8429 q.put(&mut task).unwrap();
8430 task = q.get(&task.id).unwrap();
8431 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8432 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8433 apply_task_implementers(&mut cfg, &task);
8434 assert_eq!(cfg.graph.implementers, usize::from(n));
8435 assert_eq!(cfg.graph.judges, 2);
8436 assert_eq!(cfg.merge.mode, MergeMode::None);
8437 }
8438 }
8439 }
8440
8441 #[test]
8442 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8443 let cfg: Config =
8444 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8445 .unwrap();
8446 let mut t = task();
8447 t.review_of = Some("review-target".into());
8448 t.hold_manual(Some("retry".into()));
8449 let mut previous = RunState::new(
8450 PathBuf::from("/repo"),
8451 "main".into(),
8452 "abc1234".into(),
8453 "review".into(),
8454 cfg.clone(),
8455 );
8456 previous.config.graph.implementers = 2;
8457 for count in [1, 3] {
8458 t.set_implementers(count, &cfg).unwrap();
8459 t.release();
8460 assert_eq!(t.review_of.as_deref(), Some("review-target"));
8461 for proposed in [
8462 Starter::Resume(previous.id.clone()),
8463 Starter::Review("recovery-target".into()),
8464 ] {
8465 assert_eq!(
8466 starter_with_implementers(&t, Some(&previous), proposed),
8467 Starter::Review("review-target".into())
8468 );
8469 }
8470 let mut configured = cfg.clone();
8471 apply_task_implementers(&mut configured, &t);
8472 assert_eq!(configured.graph.implementers, usize::from(count));
8473 assert_eq!(previous.config.graph.implementers, 2);
8474 }
8475 }
8476
8477 #[test]
8478 fn task_implementers_dispatch_and_resume_agree() {
8479 let mut t = task();
8480 let cfg: crate::config::Config =
8481 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8482 .unwrap();
8483 let mut run = RunState::new(
8484 PathBuf::from("/repo"),
8485 "main".into(),
8486 "abc1234".into(),
8487 "work".into(),
8488 cfg.clone(),
8489 );
8490 run.config.graph.implementers = 2;
8491 for n in [2, 1, 3, 2] {
8492 t.set_implementers(n, &cfg).unwrap();
8493 let mut dispatched = cfg.clone();
8494 apply_task_implementers(&mut dispatched, &t);
8495 assert_eq!(dispatched.graph.implementers, usize::from(n));
8496 assert_eq!(implementers_match(&t, &run), n == 2);
8497 for proposed in [
8498 Starter::Resume(run.id.clone()),
8499 Starter::Review("old-branch".into()),
8500 ] {
8501 let expected = if n == 2 {
8502 proposed.clone()
8503 } else {
8504 Starter::Start
8505 };
8506 assert_eq!(
8507 starter_with_implementers(&t, Some(&run), proposed),
8508 expected
8509 );
8510 }
8511 assert_eq!(
8512 run.config.graph.implementers, 2,
8513 "history must not be rewritten"
8514 );
8515 }
8516 t.solo = false;
8517 t.overrides = None;
8518 assert!(implementers_match(&t, &run));
8519 }
8520
8521 #[test]
8522 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8523 let mut solo_cfg = Config::default();
8529 solo_cfg.graph.implementers = 3;
8530 let mut solo_task = task();
8531 solo_task.solo = true;
8532 apply_task_implementers(&mut solo_cfg, &solo_task);
8533 assert_eq!(solo_cfg.graph.implementers, 1);
8534
8535 let mut plain_cfg = Config::default();
8536 plain_cfg.graph.implementers = 3;
8537 let plain_task = task();
8538 assert!(!plain_task.solo);
8539 apply_task_implementers(&mut plain_cfg, &plain_task);
8540 assert_eq!(
8541 plain_cfg.graph.implementers, 3,
8542 "a task that did not ask to run alone keeps the config's candidates"
8543 );
8544 }
8545
8546 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8547 QuotaLoss {
8548 seat: seat.into(),
8549 node: "judge".into(),
8550 at: at.parse().unwrap(),
8551 reset: reset.map(str::to_string),
8552 }
8553 }
8554
8555 #[test]
8556 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8557 let old: Vec<QuotaLoss> = (1..=4)
8558 .map(|i| {
8559 loss(
8560 &format!("judge-{i}"),
8561 "2026-09-23T05:23:00Z",
8562 Some("2:40pm (Asia/Tokyo)"),
8563 )
8564 })
8565 .collect();
8566 let fresh = losses_this_attempt(&old, &old);
8567 assert!(fresh.is_empty());
8568 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8569 }
8571
8572 #[test]
8573 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8574 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8575 let now = Timestamp::now();
8576 let mut after = old.clone();
8577 after.push(loss("judge-2", &now.to_string(), None));
8578 let fresh = losses_this_attempt(&old, &after);
8579 assert_eq!(fresh, vec![after[1].clone()]);
8580 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8581 assert_eq!(
8582 until,
8583 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8584 );
8585 }
8586
8587 #[test]
8588 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8589 let before = vec![
8592 loss("judge-1", "2026-09-23T05:23:00Z", None),
8593 loss("judge-2", "2026-09-23T05:24:00Z", None),
8594 ];
8595 let after = vec![
8596 loss("judge-2", "2026-09-23T05:24:00Z", None),
8597 loss("judge-1", "2026-09-24T01:00:00Z", None),
8598 ];
8599 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8600 }
8601
8602 #[test]
8603 fn merge_overrides_are_parsed_or_refused() {
8604 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8605 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8606 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8607 assert!(merge_mode("squash").is_err());
8608 }
8609
8610 #[test]
8611 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8612 let now = Timestamp::now();
8613 let fallback = Duration::from_secs(300);
8614 let cap = Duration::from_secs(1800);
8615
8616 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8618
8619 let soon = now + jiff::SignedDuration::from_secs(600);
8621 assert_eq!(
8622 quota_wait(Some(soon), now, fallback, cap),
8623 Duration::from_secs(600)
8624 );
8625
8626 let past = now - jiff::SignedDuration::from_secs(60);
8629 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8630
8631 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8634 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8635 }
8636
8637 #[test]
8638 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8639 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8640
8641 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8642 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8643
8644 let already_past =
8648 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8649 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8650
8651 assert!(
8652 parse_reset_hint("session limit reached", now, now).is_none(),
8653 "free text with no recognised shape is not guessed at"
8654 );
8655 assert!(
8656 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8657 "an unresolvable zone name is not guessed at either"
8658 );
8659 }
8660
8661 #[test]
8662 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8663 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8664
8665 let at = parse_reset_hint(
8666 "You've hit your usage limit. Visit \
8667 https://chatgpt.com/codex/settings/usage to purchase more \
8668 credits or try again at Sep 19th, 2026 5:10 PM.",
8669 now,
8670 now,
8671 )
8672 .expect("the codex reset wording is a recognised shape");
8673 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8674
8675 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8680 .expect("an explicit year needs no rollover");
8681 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8682
8683 assert!(
8684 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8685 "a two-digit year is not the documented shape and is not guessed at"
8686 );
8687 assert!(
8688 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8689 "a four-letter month name is not the documented three-letter abbreviation"
8690 );
8691 assert!(
8692 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8693 "an explicit zone on the dated shape is a format nobody has \
8694 documented, and is refused rather than guessed at as UTC"
8695 );
8696 }
8697
8698 #[test]
8699 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8700 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8701 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8702
8703 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8704 assert_eq!(at.as_second() - recorded.as_second(), 3769);
8705
8706 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8707 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8708
8709 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8710 assert!(
8711 parse_reset_hint(bad, now, recorded).is_none(),
8712 "{bad:?} must not be guessed at"
8713 );
8714 }
8715 }
8716
8717 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8721 let config = dir.join("magi.toml");
8722 std::fs::write(
8723 &config,
8724 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8725 )
8726 .unwrap();
8727 let opts = Opts {
8728 poll: Duration::from_secs(30),
8729 config: Some(config),
8730 repo: dir.join("repo"),
8734 ..Opts::default()
8735 };
8736 let home = dir.join("home");
8745 let worktrees = dir.join("wt");
8746 (
8747 opts,
8748 Queue::at(dir.join("queue")),
8749 home.join("daemon.json"),
8750 home,
8751 worktrees,
8752 )
8753 }
8754
8755 #[test]
8756 fn a_stop_is_idempotent_and_once_set_stays_set() {
8757 let stop = Stop::new();
8758 assert!(!stop.stopped());
8759
8760 stop.stop();
8761 assert!(stop.stopped());
8762 stop.stop();
8763 assert!(stop.stopped(), "a second stop is not a toggle");
8764
8765 let shared = stop.clone();
8766 assert!(
8767 shared.stopped(),
8768 "a clone is the same stop; that is how the loop and its caller share one"
8769 );
8770 }
8771
8772 #[test]
8773 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
8774 let stop = Stop::new();
8775 stop.enter();
8776 assert!(
8777 !stop.finishing(),
8778 "a busy loop nobody has asked to stop is just running"
8779 );
8780
8781 stop.stop();
8782 assert!(
8783 stop.finishing(),
8784 "a stop asked for mid-run has not landed until the run is settled"
8785 );
8786
8787 stop.exit();
8788 assert!(
8789 !stop.finishing(),
8790 "once the run is settled the stop has landed and there is nothing to finish"
8791 );
8792 }
8793
8794 #[test]
8795 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
8796 let stop = Stop::new();
8797 stop.enter();
8798 stop.enter();
8799 stop.stop();
8800 assert!(stop.finishing(), "two runs still in flight");
8801
8802 stop.exit();
8803 assert!(
8804 stop.finishing(),
8805 "one run finished, but a sibling is still working"
8806 );
8807
8808 stop.exit();
8809 assert!(
8810 !stop.finishing(),
8811 "the last run out is what actually lands the stop"
8812 );
8813 }
8814
8815 #[tokio::test]
8816 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
8817 let dir = tempfile::tempdir().unwrap();
8818 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8819 let stop = Stop::new();
8820 stop.stop();
8821
8822 let began = std::time::Instant::now();
8823 tokio::time::timeout(
8824 Duration::from_secs(2),
8825 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8826 )
8827 .await
8828 .expect("a stopped loop must return, not sit out its poll interval")
8829 .expect("the loop's own setup and teardown must not fail");
8830 assert!(
8831 began.elapsed() < opts.poll,
8832 "returned only after {:?}, which is a poll interval, not a stop",
8833 began.elapsed()
8834 );
8835 }
8836
8837 #[tokio::test]
8838 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
8839 let dir = tempfile::tempdir().unwrap();
8840 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8841 let stop = Stop::new();
8842
8843 let asker = {
8846 let stop = stop.clone();
8847 tokio::spawn(async move {
8848 tokio::time::sleep(Duration::from_millis(20)).await;
8849 stop.stop();
8850 })
8851 };
8852
8853 let began = std::time::Instant::now();
8854 tokio::time::timeout(
8855 Duration::from_secs(2),
8856 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8857 )
8858 .await
8859 .expect("a stop asked for while idle must wake the wait")
8860 .expect("the loop's own setup and teardown must not fail");
8861 asker.await.unwrap();
8862 assert!(
8863 began.elapsed() < opts.poll,
8864 "returned only after {:?}, so the stop waited on the sleep",
8865 began.elapsed()
8866 );
8867 }
8868
8869 #[tokio::test]
8870 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
8871 let dir = tempfile::tempdir().unwrap();
8872 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8873 let stop = Stop::new();
8874 stop.stop();
8875
8876 tokio::time::timeout(
8877 Duration::from_secs(2),
8878 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8879 )
8880 .await
8881 .expect("a stopped loop must return")
8882 .expect("the loop's own setup and teardown must not fail");
8883
8884 assert!(
8885 home.is_dir(),
8886 "the loop did publish a status file, so its removal is the teardown and not an absence"
8887 );
8888 assert!(
8889 !status_file.exists(),
8890 "a stopped loop clears its status file"
8891 );
8892 assert!(
8893 read_status(&home).is_none(),
8894 "a reader must see no daemon at all, not a heartbeat that merely stopped"
8895 );
8896 }
8897
8898 #[tokio::test]
8899 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
8900 let dir = tempfile::tempdir().unwrap();
8901 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8902 opts.once = true;
8903
8904 let mut settled = RunState::new(
8905 dir.path().join("repo"),
8906 "main".to_owned(),
8907 "abc1234".to_owned(),
8908 "fixture".to_owned(),
8909 Config::default(),
8910 );
8911 settled.status = RunStatus::Ready;
8912 let run_dir = home.join("runs").join(&settled.id);
8913 std::fs::create_dir_all(&run_dir).unwrap();
8914 std::fs::write(
8915 run_dir.join("run.json"),
8916 serde_json::to_string_pretty(&settled).unwrap(),
8917 )
8918 .unwrap();
8919 let questions = Questions::at(home.join("questions"));
8920 let mut question = ask::Question::new(
8921 settled.id.clone(),
8922 "review".to_owned(),
8923 "reviewer-1".to_owned(),
8924 "Continue?".to_owned(),
8925 String::new(),
8926 Vec::new(),
8927 );
8928 questions.put(&mut question).unwrap();
8929
8930 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
8931 .await
8932 .unwrap();
8933
8934 assert_eq!(
8935 questions.get(&question.id).unwrap().status,
8936 ask::QuestionStatus::Abandoned,
8937 "an empty --once drain still performs startup question cleanup"
8938 );
8939 }
8940
8941 #[test]
8942 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
8943 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8944
8945 assert!(
8946 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
8947 "never checked before: due at once"
8948 );
8949
8950 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
8951 assert!(
8952 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
8953 "well inside the interval: not due yet"
8954 );
8955
8956 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
8957 assert!(
8958 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
8959 "exactly at the edge: not yet due, same convention as `clean::due`"
8960 );
8961
8962 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8963 assert!(
8964 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
8965 "past the interval: due again"
8966 );
8967 }
8968
8969 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
8974 let config = dir.join("magi.toml");
8975 std::fs::write(
8981 &config,
8982 format!(
8983 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
8984 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
8985 cache_dir.display()
8986 ),
8987 )
8988 .unwrap();
8989 Opts {
8990 config: Some(config),
8991 repo: dir.join("repo"),
8992 ..Opts::default()
8993 }
8994 }
8995
8996 #[tokio::test]
8997 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8998 let dir = tempfile::tempdir().unwrap();
8999 let home = dir.path().join("home");
9000 let cache_dir = dir.path().join("cache");
9001 std::fs::create_dir_all(&cache_dir).unwrap();
9002 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9003 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9004
9005 let running = Stop::new();
9008 let mut last_checked = None;
9009 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9010 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9011 .await;
9012 assert_eq!(
9013 crate::disk::dir_size(&cache_dir),
9014 0,
9015 "over the cap on the first check ever: pruned at once, no idle queue required"
9016 );
9017 assert_eq!(last_checked, Some(t0));
9018
9019 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9021 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9022 maybe_prune_cache_between_runs(
9023 &opts.repo,
9024 &opts,
9025 &home,
9026 &running,
9027 &mut last_checked,
9028 too_soon,
9029 )
9030 .await;
9031 assert_eq!(
9032 crate::disk::dir_size(&cache_dir),
9033 10,
9034 "too soon since the last check: left alone rather than rescanned every call"
9035 );
9036 assert_eq!(
9037 last_checked,
9038 Some(t0),
9039 "an idle check does not reset the clock"
9040 );
9041
9042 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9044 maybe_prune_cache_between_runs(
9045 &opts.repo,
9046 &opts,
9047 &home,
9048 &running,
9049 &mut last_checked,
9050 due_again,
9051 )
9052 .await;
9053 assert_eq!(
9054 crate::disk::dir_size(&cache_dir),
9055 0,
9056 "due again: pruned back under the cap"
9057 );
9058 }
9059
9060 #[tokio::test]
9068 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9069 let dir = tempfile::tempdir().unwrap();
9070 let home = dir.path().join("home");
9071 let cache_dir = dir.path().join("cache");
9072 std::fs::create_dir_all(&cache_dir).unwrap();
9073 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9074 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9075
9076 let stop = Stop::new();
9077 stop.stop();
9078 assert!(
9079 !stop.finishing(),
9080 "no run is in flight at a between-runs boundary, so nothing else \
9081 would tell the operator this stop had not taken effect yet"
9082 );
9083
9084 let mut last_checked = None;
9085 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9086 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9087 .await;
9088 assert_eq!(
9089 crate::disk::dir_size(&cache_dir),
9090 10,
9091 "over its cap, and due for the first check ever, but a stop outranks \
9092 it: the cap is a standing policy the next start measures again"
9093 );
9094 assert_eq!(
9095 last_checked, None,
9096 "a check that never happened must not claim the interval"
9097 );
9098 }
9099
9100 #[tokio::test]
9111 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9112 let dir = tempfile::tempdir().unwrap();
9113 let cache_dir = dir.path().join("cache");
9114 std::fs::create_dir_all(&cache_dir).unwrap();
9115 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9116
9117 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9118 opts.poll = Duration::from_millis(20);
9119 opts.max_attempts = 1_000;
9120
9121 let queue = Queue::at(dir.path().join("queue"));
9122 for i in 0..128 {
9123 let mut task = Task::new(
9124 format!("queued work {i}"),
9125 format!("queued work {i}"),
9126 opts.repo.clone(),
9127 Source::Human,
9128 );
9129 queue.put(&mut task).unwrap();
9130 }
9131
9132 let home = dir.path().join("home");
9133 let worktrees = dir.path().join("wt");
9134 let status_file = home.join("daemon.json");
9135 let stop = Stop::new();
9136 let stopper = {
9137 let stop = stop.clone();
9138 let queue = Queue::at(dir.path().join("queue"));
9139 tokio::spawn(async move {
9140 for _ in 0..2_000 {
9144 if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9145 break;
9146 }
9147 tokio::time::sleep(Duration::from_millis(5)).await;
9148 }
9149 stop.stop();
9150 })
9151 };
9152
9153 tokio::time::timeout(
9154 Duration::from_secs(20),
9155 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9156 )
9157 .await
9158 .expect("the loop must not hang on a queue that keeps producing failing work")
9159 .expect("the loop's own setup and teardown must not fail");
9160 stopper.await.unwrap();
9161
9162 let after = queue.list();
9163 let completed = after.iter().filter(|t| t.attempts == 1).count();
9164 assert!(
9165 completed >= 2,
9166 "the harness must have processed multiple tasks to exercise a busy queue \
9167 (got {completed} completed task(s))"
9168 );
9169 assert!(
9170 after.iter().any(|t| t.status.runnable()),
9171 "unprocessed tasks must remain: the external stop, rather than an \
9172 exhausted backlog, must end the test"
9173 );
9174 assert!(
9175 after
9176 .iter()
9177 .filter(|t| t.attempts > 0)
9178 .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9179 "a busy backlog must not retry a task's unchanged startup failure"
9180 );
9181
9182 assert_eq!(
9183 crate::disk::dir_size(&cache_dir),
9184 0,
9185 "an oversized cache must not be left to grow unboundedly just because the \
9186 queue kept the loop busy the whole time"
9187 );
9188 }
9189
9190 #[test]
9191 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9192 let dir = tempfile::tempdir().unwrap();
9193 let queue = Queue::at(dir.path().join("queue"));
9194 let questions = Questions::at(dir.path().join("questions"));
9195 let mut task = task();
9196 queue.put(&mut task).unwrap();
9197
9198 let mut task_question = ask::Question::new(
9199 task.id.clone(),
9200 crate::conduct::NODE.to_owned(),
9201 "conduct".to_owned(),
9202 "Which backend?".to_owned(),
9203 String::new(),
9204 Vec::new(),
9205 );
9206 questions.put(&mut task_question).unwrap();
9207 task.block(vec![task_question.id.clone()], None);
9208 queue.put(&mut task).unwrap();
9209
9210 let mut run_question = ask::Question::new(
9211 "20260101-000000-run1".to_owned(),
9212 "review".to_owned(),
9213 "reviewer-1".to_owned(),
9214 "Run question".to_owned(),
9215 String::new(),
9216 Vec::new(),
9217 );
9218 questions.put(&mut run_question).unwrap();
9219
9220 let mut coincidental = ask::Question::new(
9225 task.id.clone(),
9226 "review".to_owned(),
9227 "reviewer-1".to_owned(),
9228 "Unrelated review question".to_owned(),
9229 String::new(),
9230 Vec::new(),
9231 );
9232 questions.put(&mut coincidental).unwrap();
9233
9234 reconcile_task_questions(&queue, &questions);
9235 assert!(questions.get(&task_question.id).unwrap().status.open());
9236 assert!(questions.get(&run_question.id).unwrap().status.open());
9237 assert!(questions.get(&coincidental.id).unwrap().status.open());
9238
9239 task.release();
9240 queue.put(&mut task).unwrap();
9241 reconcile_task_questions(&queue, &questions);
9242 assert_eq!(
9243 questions.get(&task_question.id).unwrap().status,
9244 ask::QuestionStatus::Abandoned
9245 );
9246 assert!(
9247 questions.get(&run_question.id).unwrap().status.open(),
9248 "run questions remain the run janitor's responsibility"
9249 );
9250 assert!(
9251 questions.get(&coincidental.id).unwrap().status.open(),
9252 "a non-conductor question must not be abandoned just because its \
9253 run id coincides with a task id"
9254 );
9255 }
9256
9257 #[test]
9258 fn a_freshly_started_running_task_is_never_stalled() {
9259 let dir = tempfile::tempdir().unwrap();
9260 let mut t = task();
9261 t.start("run-1".to_owned());
9262 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9265 }
9266
9267 #[test]
9268 fn a_long_running_task_with_no_live_daemon_is_stalled() {
9269 let dir = tempfile::tempdir().unwrap();
9270 let mut t = task();
9271 t.start("run-1".to_owned());
9272 t.updated_at = Timestamp::now()
9273 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9274 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9275 assert_eq!(
9276 stalled_tasks(
9277 &Queue::at(dir.path().join("q")),
9278 dir.path(),
9279 Timestamp::now()
9280 )
9281 .len(),
9282 0,
9283 "the task was never written to this queue"
9284 );
9285 }
9286
9287 #[test]
9288 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9289 let dir = tempfile::tempdir().unwrap();
9290 let mut t = task();
9291 t.id = "20260903-080340-0167".to_owned();
9292 t.start("20260903-080619-01c2".to_owned());
9293 t.updated_at = Timestamp::now()
9294 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9295
9296 let mut status = Status::new();
9297 status.current = vec![Current {
9298 task: t.id.clone(),
9299 run: "20260903-080619-01c2".to_owned(),
9300 }];
9301 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9302
9303 assert!(
9304 !is_stalled(&t, dir.path(), Timestamp::now()),
9305 "a live daemon's own heartbeat rules out stalled, however long the task has run"
9306 );
9307 }
9308
9309 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9313 let path = queue.path_of(id);
9314 let body = std::fs::read_to_string(&path).unwrap();
9315 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9316 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9317 v["updated_at"] = serde_json::Value::String(old.to_string());
9318 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9319 }
9320
9321 #[test]
9322 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9323 let dir = tempfile::tempdir().unwrap();
9336 let queue = Queue::at(dir.path().join("queue"));
9337 let home = dir.path().join("home");
9338
9339 let mut t = task();
9340 t.id = "20260101-000001-lock".to_owned();
9341 t.start("run-1".to_owned());
9342 queue.put(&mut t).unwrap();
9343 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9344 std::fs::write(
9345 dir.path().join("queue").join(format!("{}.lock", t.id)),
9346 "not a pid",
9347 )
9348 .unwrap();
9349
9350 let now = Timestamp::now();
9351 assert!(
9352 reclaim_orphaned_running(&queue, 2).is_empty(),
9353 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9354 and reclaim must leave the task alone"
9355 );
9356 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9357
9358 let stalled = stalled_tasks(&queue, &home, now);
9359 assert_eq!(
9360 stalled.len(),
9361 1,
9362 "reclaim's inability to claim it yet must not hide it from the conductor"
9363 );
9364 assert_eq!(stalled[0].id, t.id);
9365 }
9366
9367 #[test]
9368 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9369 let dir = tempfile::tempdir().unwrap();
9370 crate::run::set_home(dir.path().join("run-home"));
9371 let queue = Queue::at(dir.path().join("queue"));
9372 let home = dir.path().join("home");
9373 let questions = Questions::at(dir.path().join("questions"));
9374
9375 let mut t = task();
9376 t.id = "20260101-000003-dead".to_owned();
9377 t.start("missing-run".to_owned());
9378 queue.put(&mut t).unwrap();
9379 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9380
9381 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9384 assert_eq!(
9385 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9386 [&t.id]
9387 );
9388 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9389 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9390
9391 crate::conduct::apply(
9394 &queue,
9395 &questions,
9396 &crate::conduct::Verdict {
9397 decisions: vec![crate::conduct::Decision {
9398 id: t.id.clone(),
9399 recovery: Some(crate::conduct::Recovery::Requeue),
9400 ..crate::conduct::Decision::default()
9401 }],
9402 },
9403 )
9404 .unwrap();
9405 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9406 }
9407
9408 #[test]
9409 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9410 let dir = tempfile::tempdir().unwrap();
9411 let queue = Queue::at(dir.path().join("queue"));
9412 let home = dir.path().join("home");
9413
9414 let mut fresh = task();
9415 fresh.id = "20260101-000001-aaaa".to_owned();
9416 fresh.start("run-1".to_owned());
9417 queue.put(&mut fresh).unwrap();
9418
9419 let mut old = task();
9420 old.id = "20260101-000002-bbbb".to_owned();
9421 old.start("run-2".to_owned());
9422 queue.put(&mut old).unwrap();
9423 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9424
9425 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9426 assert_eq!(stalled.len(), 1);
9427 assert_eq!(stalled[0].id, old.id);
9428 }
9429
9430 #[test]
9431 fn queued_and_finished_task_views_partition_by_status() {
9432 let dir = tempfile::tempdir().unwrap();
9433 let queue = Queue::at(dir.path().join("queue"));
9434
9435 let mut queued = task();
9436 queued.id = "20260101-000001-aaaa".to_owned();
9437 queue.put(&mut queued).unwrap();
9438
9439 let mut failed = task();
9440 failed.id = "20260101-000002-bbbb".to_owned();
9441 failed.start("run-1".to_owned());
9442 failed.fail("gate red", 5);
9443 queue.put(&mut failed).unwrap();
9444
9445 let mut held = task();
9446 held.id = "20260101-000003-cccc".to_owned();
9447 held.hold_machine(None);
9448 queue.put(&mut held).unwrap();
9449
9450 let mut running = task();
9451 running.id = "20260101-000004-dddd".to_owned();
9452 running.start("run-2".to_owned());
9453 queue.put(&mut running).unwrap();
9454
9455 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9456 assert_eq!(queued_ids, [queued.id.clone()]);
9457
9458 let mut finished_ids: Vec<String> =
9459 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9460 finished_ids.sort_unstable();
9461 let mut want = vec![failed.id.clone(), held.id.clone()];
9462 want.sort_unstable();
9463 assert_eq!(finished_ids, want);
9464 }
9465
9466 #[test]
9467 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9468 for short in [false, true] {
9469 let dir = tempfile::tempdir().unwrap();
9470 let queue = Queue::at(dir.path().join("queue"));
9471 let questions = ask::Questions::at(dir.path().join("questions"));
9472 let mut running = task();
9473 running.id = "20261013-192213-feb2".into();
9474 running.start("existing-run".into());
9475 queue.put(&mut running).unwrap();
9476 let mut middle = task();
9477 middle.id = "20261013-193611-ca5b".into();
9478 middle.block(
9479 vec![if short {
9480 "feb2".into()
9481 } else {
9482 running.id.clone()
9483 }],
9484 None,
9485 );
9486 queue.put(&mut middle).unwrap();
9487 let mut waiting = task();
9488 waiting.id = "20261013-202849-ee37".into();
9489 waiting.block(
9490 vec![if short {
9491 "ca5b".into()
9492 } else {
9493 middle.id.clone()
9494 }],
9495 Some("wait for implementation".into()),
9496 );
9497 queue.put(&mut waiting).unwrap();
9498 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9499 let inv = crate::blockers::Inventory::load(&queue, &questions);
9500 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9501 assert!(inv.stuck().is_empty());
9502 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9503 assert!(report.quarantined.is_empty());
9504 assert!(report.asked.is_empty());
9505 resolve_blockers(&queue, &questions);
9506 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9507 assert!(questions.list().is_empty());
9508 running.succeed();
9511 queue.put(&mut running).unwrap();
9512 resolve_blockers(&queue, &questions);
9513 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9514 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9515 middle = queue.get(&middle.id).unwrap();
9516 middle.succeed();
9517 queue.put(&mut middle).unwrap();
9518 resolve_blockers(&queue, &questions);
9519 let after = queue.get(&waiting.id).unwrap();
9520 assert_eq!(after.status, TaskStatus::Queued);
9521 assert!(after.blocked_by.is_empty());
9522 assert_eq!(after.instruction, waiting.instruction);
9523 }
9524 }
9525
9526 #[test]
9527 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9528 for future_schema in [false, true] {
9529 let name = "20261013-193611-ca5b";
9530 let mut future = task();
9531 future.id = name.into();
9532 future.schema = crate::queue::SCHEMA + 1;
9533 let contents = if future_schema {
9534 serde_json::to_string(&future).unwrap()
9535 } else {
9536 "corrupt".into()
9537 };
9538 let dir = tempfile::tempdir().unwrap();
9539 let queue = Queue::at(dir.path().join("queue"));
9540 let questions = ask::Questions::at(dir.path().join("questions"));
9541 let mut waiting = task();
9542 waiting.id = "20261013-202849-ee37".into();
9543 waiting.block(vec!["ca5b".into()], None);
9544 queue.put(&mut waiting).unwrap();
9545 std::fs::write(queue.path_of(name), contents).unwrap();
9546 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9547 assert!(
9548 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9549 );
9550 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9551 assert!(report.asked.is_empty());
9552 resolve_blockers(&queue, &questions);
9553 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9554 assert!(questions.list().is_empty());
9555 }
9556 let dir = tempfile::tempdir().unwrap();
9557 let queue = Queue::at(dir.path().join("queue"));
9558 let questions = ask::Questions::at(dir.path().join("questions"));
9559 let mut waiting = task();
9560 waiting.id = "20261013-202849-ee37".into();
9561 waiting.block(vec!["ca5b".into()], None);
9562 queue.put(&mut waiting).unwrap();
9563 let mut done = task();
9564 done.id = "20261013-193611-ca5b".into();
9565 done.succeed();
9566 queue.put(&mut done).unwrap();
9567 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9570 assert!(queue.get("ca5b").is_err());
9571 assert_eq!(
9572 crate::queue::dependency(&queue, &questions, "ca5b"),
9573 crate::queue::Dependency::Ambiguous
9574 );
9575 resolve_blockers(&queue, &questions);
9576 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9577 assert!(report.asked.is_empty());
9578 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9579 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9580 }
9581
9582 #[test]
9583 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9584 for held in [false, true] {
9585 for question in [false, true] {
9586 for reference in ["ca5b", "20261013-193611-ca5b"] {
9587 let dir = tempfile::tempdir().unwrap();
9588 let queue = Queue::at(dir.path().join("queue"));
9589 let questions = ask::Questions::at(dir.path().join("questions"));
9590 let mut prerequisite = task();
9591 prerequisite.id = "20261013-193611-ca5b".into();
9592 prerequisite.start("existing-run".into());
9593 queue.put(&mut prerequisite).unwrap();
9594 let mut waiting = task();
9595 waiting.id = "20261013-202849-ee37".into();
9596 if held {
9597 waiting.hold_machine(Some("waiting for separate consent".into()));
9598 }
9599 queue.put(&mut waiting).unwrap();
9600 let reason = "Deleting saved data requires separate owner consent";
9601 crate::conduct::apply(
9602 &queue,
9603 &questions,
9604 &crate::conduct::Verdict {
9605 decisions: vec![crate::conduct::Decision {
9606 id: waiting.id.clone(),
9607 blocked_by: vec![reference.into()],
9608 question: question.then(|| "May the saved data be deleted?".into()),
9609 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9610 reason: Some(reason.into()),
9611 ..crate::conduct::Decision::default()
9612 }],
9613 },
9614 )
9615 .unwrap();
9616 let before = queue.get(&waiting.id).unwrap();
9617 if question {
9618 assert_eq!(before.status, TaskStatus::Blocked);
9619 let q = questions.get(&before.blocked_by[0]).unwrap();
9620 assert_eq!(q.summary, "May the saved data be deleted?");
9621 assert!(q.status.open());
9622 } else {
9623 assert_eq!(before.status, TaskStatus::Held);
9624 let recorded_reason = before.hold_reason.as_deref().unwrap();
9625 assert!(recorded_reason.starts_with(reason));
9626 if held {
9627 assert!(recorded_reason.contains("waiting for separate consent"));
9628 }
9629 }
9630 prerequisite.succeed();
9631 queue.put(&mut prerequisite).unwrap();
9632 resolve_blockers(&queue, &questions);
9633 let after = queue.get(&waiting.id).unwrap();
9634 assert_eq!(after.status, before.status);
9635 assert_eq!(after.blocked_by, before.blocked_by);
9636 assert_eq!(after.hold_reason, before.hold_reason);
9637 assert_eq!(after.instruction, waiting.instruction);
9638 if question {
9639 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9640 }
9641 assert!(
9642 queue.next_runnable().is_none(),
9643 "dependency completion is not consent"
9644 );
9645 }
9646 }
9647 }
9648 }
9649
9650 #[test]
9651 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9652 let dir = tempfile::tempdir().unwrap();
9653 let queue = Queue::at(dir.path().join("queue"));
9654 let questions = ask::Questions::at(dir.path().join("questions"));
9655
9656 let mut dep = task();
9657 dep.id = "20260101-000001-dep0".to_owned();
9658 dep.succeed();
9659 queue.put(&mut dep).unwrap();
9660
9661 let mut still_going = task();
9662 still_going.id = "20260101-000002-dep1".to_owned();
9663 queue.put(&mut still_going).unwrap();
9664
9665 let mut blocked = task();
9666 blocked.id = "20260101-000003-main".to_owned();
9667 blocked.block(
9668 vec![dep.id.clone(), still_going.id.clone()],
9669 Some("waits on both".to_owned()),
9670 );
9671 queue.put(&mut blocked).unwrap();
9672
9673 resolve_blockers(&queue, &questions);
9674
9675 let after = queue.get(&blocked.id).unwrap();
9676 assert_eq!(
9677 after.status,
9678 TaskStatus::Blocked,
9679 "one dependency is still outstanding"
9680 );
9681 assert_eq!(after.blocked_by, [still_going.id.clone()]);
9682 }
9683
9684 #[test]
9685 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9686 let dir = tempfile::tempdir().unwrap();
9687 let queue = Queue::at(dir.path().join("queue"));
9688 let questions = ask::Questions::at(dir.path().join("questions"));
9689
9690 let mut q = crate::ask::Question::new(
9691 "20260101-000001-main".to_owned(),
9692 crate::conduct::NODE.to_owned(),
9693 "conduct".to_owned(),
9694 "Which backend?".to_owned(),
9695 String::new(),
9696 Vec::new(),
9697 );
9698 questions.put(&mut q).unwrap();
9699 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9700 .unwrap();
9701 questions.put(&mut q).unwrap();
9702
9703 let mut blocked = task();
9704 blocked.id = "20260101-000001-main".to_owned();
9705 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9706 queue.put(&mut blocked).unwrap();
9707
9708 resolve_blockers(&queue, &questions);
9709
9710 let after = queue.get(&blocked.id).unwrap();
9711 assert_eq!(
9712 after.status,
9713 TaskStatus::Queued,
9714 "the only blocker resolved"
9715 );
9716 assert_eq!(after.answers.len(), 1);
9717 assert_eq!(after.answers[0].question, "Which backend?");
9718 assert_eq!(after.answers[0].answer, "SQLite");
9719
9720 let instruction = instruction_for(&after);
9722 assert!(instruction.contains("Which backend?"));
9723 assert!(instruction.contains("SQLite"));
9724 }
9725
9726 #[test]
9727 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9728 let dir = tempfile::tempdir().unwrap();
9729 let queue = Queue::at(dir.path().join("queue"));
9730 let questions = ask::Questions::at(dir.path().join("questions"));
9731
9732 let mut q = crate::ask::Question::new(
9733 "20260101-000001-main".to_owned(),
9734 crate::conduct::NODE.to_owned(),
9735 "conduct".to_owned(),
9736 "Is the setup done?".to_owned(),
9737 String::new(),
9738 Vec::new(),
9739 );
9740 q.abandon("no answer within 60s of asking");
9741 questions.put(&mut q).unwrap();
9742
9743 let mut blocked = task();
9744 blocked.id = "20260101-000001-main".to_owned();
9745 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9746 queue.put(&mut blocked).unwrap();
9747
9748 resolve_blockers(&queue, &questions);
9749
9750 let after = queue.get(&blocked.id).unwrap();
9751 assert_eq!(
9752 after.status,
9753 TaskStatus::Held,
9754 "never left blocked on nothing"
9755 );
9756 assert!(!after.operator_held(), "a machine hold, for triage");
9757 assert!(
9758 after
9759 .hold_reason
9760 .as_deref()
9761 .unwrap_or_default()
9762 .contains("went unanswered")
9763 );
9764 }
9765
9766 #[test]
9767 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9768 let dir = tempfile::tempdir().unwrap();
9774 let queue = Queue::at(dir.path().join("queue"));
9775 let questions = ask::Questions::at(dir.path().join("questions"));
9776
9777 let mut q = crate::ask::Question::new(
9778 "20260101-000001-main".to_owned(),
9779 crate::conduct::NODE.to_owned(),
9780 "conduct".to_owned(),
9781 "How should this be handled?".to_owned(),
9782 String::new(),
9783 Vec::new(),
9784 );
9785 questions.put(&mut q).unwrap();
9786 q.answer(crate::ask::Answer::Text(
9787 "leave it held, a human will look at it later".to_owned(),
9788 ))
9789 .unwrap();
9790 questions.put(&mut q).unwrap();
9791
9792 let mut held = task();
9793 held.id = "20260101-000001-main".to_owned();
9794 held.hold_machine(Some("out of attempts".to_owned()));
9795 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
9796 queue.put(&mut held).unwrap();
9797
9798 resolve_blockers(&queue, &questions);
9799
9800 let after = queue.get(&held.id).unwrap();
9801 assert_eq!(after.status, TaskStatus::Held);
9802 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
9803 assert_eq!(
9804 after.answers[0].answer,
9805 "leave it held, a human will look at it later"
9806 );
9807 }
9808
9809 #[test]
9810 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
9811 let dir = tempfile::tempdir().unwrap();
9812 let queue = Queue::at(dir.path().join("queue"));
9813 let questions = ask::Questions::at(dir.path().join("questions"));
9814 let mut dep = task();
9815 dep.id = "20260101-000001-gone".to_owned();
9816 queue.put(&mut dep).unwrap();
9817 let mut blocked = task();
9818 blocked.id = "20260101-000003-main".to_owned();
9819 blocked.block(vec![dep.id.clone()], None);
9820 queue.put(&mut blocked).unwrap();
9821
9822 let claim = queue.claim(&blocked.id).unwrap();
9824 queue.remove(&dep.id, false, &questions).unwrap();
9825 drop(claim);
9826 resolve_blockers(&queue, &questions);
9827
9828 let after = queue.get(&blocked.id).unwrap();
9829 assert_eq!(after.status, TaskStatus::Queued);
9830 assert!(after.blocked_by.is_empty());
9831 }
9832
9833 #[test]
9834 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
9835 let dir = tempfile::tempdir().unwrap();
9841 let queue = Queue::at(dir.path().join("queue"));
9842 let questions = ask::Questions::at(dir.path().join("questions"));
9843
9844 let mut still_going = task();
9845 still_going.id = "20260101-000002-dep1".to_owned();
9846 queue.put(&mut still_going).unwrap();
9847
9848 let mut blocked = task();
9849 blocked.id = "20260101-000003-main".to_owned();
9850 blocked.block(
9851 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
9852 Some("waits on both".to_owned()),
9853 );
9854 queue.put(&mut blocked).unwrap();
9855
9856 resolve_blockers(&queue, &questions);
9857
9858 let after = queue.get(&blocked.id).unwrap();
9859 assert_eq!(
9860 after.status,
9861 TaskStatus::Held,
9862 "a missing dependency must not leave the task blocked forever"
9863 );
9864 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
9865 assert!(after.blocked_by.is_empty());
9866 let reason = after.hold_reason.as_deref().unwrap_or_default();
9867 assert!(
9868 reason.contains("20260101-000001-gone"),
9869 "the missing id must be named so an operator can tell what happened: {reason}"
9870 );
9871 assert!(
9872 reason.contains(&still_going.id),
9873 "the still-valid dependency must not silently vanish from the record: {reason}"
9874 );
9875 }
9876
9877 #[test]
9878 fn instruction_for_is_unchanged_without_any_answers() {
9879 let t = task();
9880 assert_eq!(instruction_for(&t), t.instruction);
9881 }
9882
9883 #[test]
9884 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
9885 let dir = tempfile::tempdir().unwrap();
9886 let q = Queue::at(dir.path().join("queue"));
9887 let src = dir.path().join("shot.png");
9888 std::fs::write(&src, "x").unwrap();
9889 let mut t = task();
9890 q.attach(&mut t, &[src]).unwrap();
9891 let paths = task_attachments(&q, &t).unwrap();
9892 assert_eq!(paths.len(), 1);
9893 assert!(paths[0].is_absolute() && paths[0].is_file());
9894 std::fs::remove_file(&paths[0]).unwrap();
9895 let err = task_attachments(&q, &t).unwrap_err().to_string();
9896 assert!(err.contains("shot.png"), "{err}");
9897 }
9898
9899 #[tokio::test]
9900 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
9901 let dir = tempfile::tempdir().unwrap();
9902 let queue_path = dir.path().join("queue");
9903 let queue = Queue::at(queue_path.clone());
9904 let mut t = task();
9905 t.source = Source::Agent {
9906 run: "originating-chat".into(),
9907 node: crate::queue::CHAT_NODE.into(),
9908 };
9909 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
9910 stage: "config-fetch",
9911 target: "origin/main".into(),
9912 });
9913 record_config_failure(&mut t, &fetch);
9914 t.hold_machine(Some(format!("{fetch:#}")));
9915 let fetch_key = t.chat_notice_due().unwrap();
9916 t.chat_notices.push(fetch_key.clone());
9917 queue.put(&mut t).unwrap();
9918
9919 let queue = Queue::at(queue_path);
9920 let mut t = queue.get(&t.id).unwrap();
9921 let a = dir.path().join("a.toml");
9922 let b = dir.path().join("b.toml");
9923 for (path, text, new_cause) in [
9924 (&a, "[graph", true),
9925 (&a, "[verify", false),
9926 (&a, "[graph]\nimplementers = 'invalid-type'", true),
9927 (&b, "[graph]\nimplementers = 'invalid-type'", true),
9928 ] {
9929 t.release_operator("test", None);
9930 std::fs::write(path, text).unwrap();
9931 let error = Config::discover_fetched(dir.path(), Some(path))
9932 .await
9933 .unwrap_err();
9934 record_config_failure(&mut t, &error);
9935 t.hold_machine(Some(format!("{error:#}")));
9936 let due = t.chat_notice_due();
9937 assert_eq!(due.is_some(), new_cause, "{error:#}");
9938 if let Some(key) = due {
9939 assert_ne!(key, fetch_key);
9940 t.chat_notices.push(key);
9941 }
9942 }
9943 t.succeed();
9944 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
9945 }
9946
9947 #[test]
9948 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
9949 let dir = tempfile::tempdir().unwrap();
9950 let queue_path = dir.path().join("queue");
9951 let queue = Queue::at(queue_path.clone());
9952 let mut t = task();
9953 t.source = crate::queue::Source::Agent {
9954 run: "originating-chat".into(),
9955 node: crate::queue::CHAT_NODE.into(),
9956 };
9957 let a = dir.path().join("a.png");
9958 let b = dir.path().join("b.png");
9959 std::fs::write(&a, "a").unwrap();
9960 std::fs::write(&b, "b").unwrap();
9961 queue.attach(&mut t, &[a, b]).unwrap();
9962 let paths = task_attachments(&queue, &t).unwrap();
9963 for path in &paths {
9964 std::fs::remove_file(path).unwrap();
9965 }
9966 let missing = task_attachments(&queue, &t).unwrap_err();
9967 t.attempts += 1;
9968 let reason = missing.to_string();
9969 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9970 let first = t.chat_notice_due().expect("first attachment notice");
9971 t.chat_notices.push(first.clone());
9972 queue.put(&mut t).unwrap();
9973
9974 let queue = Queue::at(queue_path.clone());
9975 let mut t = queue.get(&t.id).unwrap();
9976 assert!(t.chat_notice_due().is_none(), "restart does not replay");
9977 t.release_operator("test", None);
9978 t.attempts += 1;
9979 let missing = task_attachments(&queue, &t).unwrap_err();
9980 t.fail_startup_target(
9981 "startup-attachments",
9982 missing.name,
9983 "same missing attachment with regenerated wording",
9984 1,
9985 );
9986 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
9987
9988 std::fs::write(&paths[0], "restored").unwrap();
9989 t.release_operator("test", None);
9990 t.attempts += 1;
9991 let missing = task_attachments(&queue, &t).unwrap_err();
9992 let reason = missing.to_string();
9993 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9994 let second = t
9995 .chat_notice_due()
9996 .expect("different attachment must notify");
9997 assert_ne!(first, second);
9998 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
9999 }
10000
10001 #[test]
10002 fn resumed_instruction_is_unchanged_without_any_answers() {
10003 let t = task();
10004 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10005 }
10006
10007 #[test]
10008 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10009 let mut t = task();
10010 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10011 let old = t.instruction.clone();
10015
10016 let refreshed = resumed_instruction(&old, &t);
10017 assert!(refreshed.starts_with(&old), "the original text is kept");
10018 assert!(refreshed.contains("Which backend?"));
10019 assert!(refreshed.contains("SQLite"));
10020 }
10021
10022 #[test]
10023 fn resumed_instruction_keeps_an_original_answers_heading() {
10024 let mut t = task();
10025 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10026 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10027
10028 let refreshed = resumed_instruction(&t.instruction, &t);
10029
10030 assert!(
10031 refreshed.starts_with(&t.instruction),
10032 "an answers heading in the original instruction is not the appended block"
10033 );
10034 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10035 assert!(refreshed.contains("Which backend?"));
10036 assert!(refreshed.contains("SQLite"));
10037
10038 let repeated = resumed_instruction(&refreshed, &t);
10039 assert_eq!(
10040 repeated, refreshed,
10041 "only the final appended block is refreshed"
10042 );
10043 }
10044
10045 #[test]
10046 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10047 let mut t = task();
10048 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10049
10050 let once = resumed_instruction(&t.instruction, &t);
10054 let twice = resumed_instruction(&once, &t);
10055 assert_eq!(once, twice);
10056 assert_eq!(once.matches("Which backend?").count(), 1);
10057
10058 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10060 let refreshed = resumed_instruction(&once, &t);
10061 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10062 assert!(refreshed.contains("Which backend?"));
10063 assert!(refreshed.contains("Which cache?"));
10064 }
10065
10066 #[test]
10067 fn prepare_instruction_covers_all_three_starters() {
10068 let mut t = task();
10069 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10070
10071 assert_eq!(
10074 prepare_instruction(&Starter::Start, None, &t),
10075 Some(instruction_for(&t))
10076 );
10077
10078 let old = t.instruction.clone();
10081 assert_eq!(
10082 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10083 Some(resumed_instruction(&old, &t))
10084 );
10085
10086 assert_eq!(
10090 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10091 None
10092 );
10093 }
10094
10095 #[test]
10096 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10097 assert_eq!(
10098 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10099 Starter::Review("magi/eba2/A".to_owned())
10100 );
10101 }
10102
10103 #[test]
10104 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10105 assert_eq!(
10106 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10107 Starter::Start,
10108 "a vanished review branch must not fall back to resuming the old run either"
10109 );
10110 }
10111
10112 #[test]
10113 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10114 let mut t = task();
10115 t.start("old-run".to_owned());
10116 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10117 t.release();
10118 let branch = t.review_branch.take();
10119 assert_eq!(
10120 choose_starter(branch.as_deref(), true, Some("old-run")),
10121 Starter::Review("magi/eba2/A".to_owned()),
10122 "a review wins over resuming the old run"
10123 );
10124 }
10125
10126 #[test]
10127 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10128 assert_eq!(
10129 choose_starter(None, false, Some("some-run")),
10130 Starter::Resume("some-run".to_owned())
10131 );
10132 assert_eq!(choose_starter(None, false, None), Starter::Start);
10133 }
10134
10135 #[test]
10136 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10137 let mut released = task();
10138 released.start("stalled-run".to_owned());
10139 released.requeue();
10140 let unfinished = (!released.fresh_start)
10141 .then(|| Some("stalled-run".to_owned()))
10142 .flatten();
10143 assert_eq!(
10144 choose_starter(None, false, unfinished.as_deref()),
10145 Starter::Start,
10146 "release keeps run history but must not resume it"
10147 );
10148 assert_eq!(released.runs, ["stalled-run"]);
10149 }
10150
10151 #[test]
10152 fn an_ordinary_release_keeps_a_resumable_run_available() {
10153 let mut released = task();
10154 released.start("stalled-run".to_owned());
10155 released.release();
10156 let unfinished = (!released.fresh_start)
10157 .then(|| Some("stalled-run".to_owned()))
10158 .flatten();
10159 assert_eq!(
10160 choose_starter(None, false, unfinished.as_deref()),
10161 Starter::Resume("stalled-run".to_owned()),
10162 "manual release must preserve the normal resume path"
10163 );
10164 }
10165
10166 #[test]
10167 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10168 let mut state = run_state(RunStatus::Blocked);
10169 state.config.graph.review_rounds = 3;
10170 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10171 assert!(exhausted_review_budget(&state));
10172
10173 state.reviews.pop();
10175 assert!(!exhausted_review_budget(&state));
10176
10177 let mut stalled = run_state(RunStatus::Stalled);
10180 stalled.config.graph.review_rounds = 1;
10181 stalled.reviews = vec![review_round(1)];
10182 assert!(!exhausted_review_budget(&stalled));
10183 }
10184
10185 fn review_round(round: usize) -> crate::run::ReviewRound {
10186 crate::run::ReviewRound {
10187 round,
10188 head: "deadbeef".to_owned(),
10189 verified_head: None,
10190 verified_at: None,
10191 reviews: Vec::new(),
10192 e2e: Vec::new(),
10193 verify_retried: false,
10194 e2e_deferred: false,
10195 e2e_defer_reason: None,
10196 fix: None,
10197 blocking: 0,
10198 answered: 1,
10199 expected: 1,
10200 clean: false,
10201 progressed: true,
10202 vote_split: false,
10203 reconsideration: Vec::new(),
10204 verdict: None,
10205 }
10206 }
10207
10208 #[test]
10209 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10210 let mut run = RunState::new(
10211 PathBuf::from("/repo"),
10212 "main".to_owned(),
10213 "abc1234def".to_owned(),
10214 "add retries".to_owned(),
10215 Config::default(),
10216 );
10217 run.status = RunStatus::Judging;
10218 run.parked = true;
10219 let mut task = Task::new(
10220 "add retries".to_owned(),
10221 "add retries".to_owned(),
10222 PathBuf::from("/repo"),
10223 crate::queue::Source::Human,
10224 );
10225 task.status = TaskStatus::Failed;
10226 task.runs = vec![run.id.clone()];
10227 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10228 assert!(with(&task, &run), "parked after judging is the case");
10229 let mut parked_task = task.clone();
10230 parked_task.status = TaskStatus::Parked;
10231 assert!(with(&parked_task, &run), "the Parked status is the case");
10232
10233 let mut not_parked = run.clone();
10234 not_parked.parked = false;
10235 not_parked.status = RunStatus::Stalled;
10236 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
10237
10238 let mut fresh = task.clone();
10239 fresh.fresh_start = true;
10240 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10241
10242 let mut review = task.clone();
10243 review.review_branch = Some("magi/x/A".to_owned());
10244 assert!(!with(&review, &run), "review is ranked before resume");
10245
10246 let mut held = task.clone();
10247 held.status = TaskStatus::Held;
10248 assert!(!with(&held, &run), "a hold stays visible to the conductor");
10249
10250 let mut released = run.clone();
10251 released.released_to = Some("20260901-000000-new1".to_owned());
10252 assert!(!with(&task, &released), "nothing left to resume into");
10253
10254 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10255 "unreadable"
10256 )));
10257 }
10258
10259 #[test]
10260 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10261 let mut released = RunState::new(
10262 PathBuf::from("/repo"),
10263 "main".to_owned(),
10264 "abc1234def".to_owned(),
10265 "add retries".to_owned(),
10266 Config::default(),
10267 );
10268 released.status = RunStatus::Blocked;
10269 assert_eq!(
10270 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10271 Some(released.id.clone())
10272 );
10273 released.released_to = Some("20260901-000000-new1".to_owned());
10274 assert_eq!(
10275 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10276 None,
10277 "there is nothing left to resume it into"
10278 );
10279 }
10280
10281 #[test]
10282 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10283 let mut exhausted = RunState::new(
10292 PathBuf::from("/repo"),
10293 "main".to_owned(),
10294 "abc1234def".to_owned(),
10295 "add retries".to_owned(),
10296 Config::default(),
10297 );
10298 exhausted.status = RunStatus::Blocked;
10299 exhausted.config.graph.review_rounds = 1;
10300 exhausted.reviews = vec![review_round(1)];
10301
10302 assert_eq!(
10303 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10304 None,
10305 "an exhausted `Blocked` run must not be offered as resumable"
10306 );
10307
10308 let mut has_budget_left = RunState::new(
10311 PathBuf::from("/repo"),
10312 "main".to_owned(),
10313 "abc1234def".to_owned(),
10314 "add retries".to_owned(),
10315 Config::default(),
10316 );
10317 has_budget_left.status = RunStatus::Blocked;
10318 has_budget_left.config.graph.review_rounds = 3;
10319 has_budget_left.reviews = vec![review_round(1)];
10320
10321 assert_eq!(
10322 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10323 Ok(has_budget_left.clone())
10324 }),
10325 Some(has_budget_left.id.clone())
10326 );
10327 }
10328
10329 #[test]
10330 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10331 let mut run = RunState::new(
10332 PathBuf::from("/repo"),
10333 "main".to_owned(),
10334 "abc1234def".to_owned(),
10335 "add retries".to_owned(),
10336 Config::default(),
10337 );
10338 run.status = RunStatus::Blocked;
10339 run.config.graph.review_rounds = 1;
10340 run.reviews = vec![review_round(1)];
10341 run.pr_publication_pending = true;
10342 assert_eq!(
10343 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10344 Some(run.id.clone()),
10345 "a spent review budget must not turn a failed publication into a re-competition"
10346 );
10347 }
10348
10349 #[test]
10350 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
10351 let mut older_stalled = RunState::new(
10359 PathBuf::from("/repo"),
10360 "main".to_owned(),
10361 "abc1234def".to_owned(),
10362 "add retries".to_owned(),
10363 Config::default(),
10364 );
10365 older_stalled.status = RunStatus::Stalled;
10366
10367 let mut newest_exhausted = RunState::new(
10368 PathBuf::from("/repo"),
10369 "main".to_owned(),
10370 "abc1234def".to_owned(),
10371 "add retries".to_owned(),
10372 Config::default(),
10373 );
10374 newest_exhausted.status = RunStatus::Blocked;
10375 newest_exhausted.config.graph.review_rounds = 1;
10376 newest_exhausted.reviews = vec![review_round(1)];
10377
10378 assert_eq!(
10379 unfinished_run_with(
10380 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10381 "t",
10382 |_| Ok(newest_exhausted.clone())
10383 ),
10384 None,
10385 "the newest run is exhausted, so nothing here is worth resuming - \
10386 least of all the older, already-superseded run"
10387 );
10388 }
10389
10390 #[test]
10391 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10392 assert_eq!(
10393 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10394 Err(anyhow::anyhow!("fixture is absent"))
10395 }),
10396 None
10397 );
10398 }
10399
10400 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10401 let mut q = ask::Question::new(
10402 run.to_owned(),
10403 "implement".to_owned(),
10404 "impl-A".to_owned(),
10405 "continue?".to_owned(),
10406 String::new(),
10407 vec!["resume で続行する".to_owned(), "other".to_owned()],
10408 );
10409 q.actions.insert("resume で続行する".to_owned(), action);
10410 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10411 .unwrap();
10412 q
10413 }
10414
10415 fn held_task_with(run: &str) -> Task {
10416 let mut t = task();
10417 t.runs = vec![run.to_owned()];
10418 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10419 t
10420 }
10421
10422 fn resume_action(run: &str) -> ask::ChoiceAction {
10423 ask::ChoiceAction::Resume { run: run.into() }
10424 }
10425
10426 #[test]
10427 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10428 for parked in [false, true] {
10429 let mut t = task();
10430 t.start("A".into());
10431 t.start("B".into());
10432 assert_eq!(t.runs, vec!["A", "B"]);
10433 t.start("A".into());
10434 let mut resumed = run_state(RunStatus::Blocked);
10435 resumed.id = "A".into();
10436 resumed.parked = parked;
10437 resumed.driver_exited = true;
10438 t.hold_machine(Some("resumed run stopped".into()));
10439 let q = action_question("A", resume_action("A"));
10440 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10441 assert_eq!(
10442 decide_action(&t, &q, &PHRASES_EN, |id| {
10443 assert_eq!(id, "A");
10444 Ok(resumed.clone())
10445 }),
10446 ActionDecision::Resume("A".into())
10447 );
10448 assert_eq!(
10449 action_standing(&t, &action_question("B", resume_action("B"))),
10450 ActionStanding::Stale
10451 );
10452 t.release_operator("cli", None);
10453 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10454 assert_eq!(id, "A");
10455 Ok(resumed.clone())
10456 });
10457 assert_eq!(
10458 choose_starter(None, false, unfinished.as_deref()),
10459 Starter::Resume("A".into())
10460 );
10461 assert_eq!(t.runs, vec!["B", "A"]);
10462 }
10463 }
10464
10465 #[test]
10466 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10467 let mut state = crate::land::tests::repair_state(true, true);
10468 state.status = RunStatus::Landing;
10469 state.parked = true;
10470 state.driver_exited = true;
10471 let mut q = ask::Question::new(
10472 state.id.clone(),
10473 land::APPROVAL_NODE.into(),
10474 "land".into(),
10475 "Merge?".into(),
10476 String::new(),
10477 vec![land::APPROVE.into(), land::HOLD.into()],
10478 );
10479 q.id = state.id.clone();
10480 state.land_approval = Some(crate::run::LandApproval {
10481 question: q.id.clone(),
10482 head: "current-head".into(),
10483 });
10484 assert!(land::upgrade_repair_choice(&mut q, &state));
10485 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10486 let mut task = held_task_with(&state.id);
10487 task.status = TaskStatus::Parked;
10488 assert_eq!(
10489 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10490 ActionDecision::Resume(state.id.clone())
10491 );
10492 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10493 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10494 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10495 assert_eq!(
10496 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10497 ActionDecision::Resume(state.id.clone()),
10498 "a repair answer newer than the manual hold resumes the existing owner"
10499 );
10500 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10501 for answered_at in [q.answered_at, None] {
10502 let mut older = q.clone();
10503 older.answered_at = answered_at;
10504 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10505 panic!("a later manual hold must prevent dispatch")
10506 });
10507 let ActionDecision::Refuse(reason) = refused else {
10508 panic!("expected an actionable refusal, got {refused:?}");
10509 };
10510 assert!(reason.contains("later operator decision"));
10511 assert!(reason.contains(&format!("magi task release {}", task.id)));
10512 }
10513 task.operator_decided_at = None;
10514 let mut superseded = state.clone();
10515 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10516 assert_eq!(
10517 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10518 ActionDecision::Stale
10519 );
10520 for case in 1..4 {
10521 let mut changed = state.clone();
10522 match case {
10523 1 => changed.status = RunStatus::Blocked,
10524 2 => changed.released_to = Some("new-owner".into()),
10525 _ => changed.land_approval.as_mut().unwrap().head.clear(),
10526 }
10527 assert!(matches!(
10528 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10529 ActionDecision::Refuse(_)
10530 ));
10531 }
10532 assert!(matches!(
10533 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10534 ActionDecision::Refuse(_)
10535 ));
10536 task.runs.push("replacement".into());
10537 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10538 assert_eq!(
10539 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10540 "old owner must not load"
10541 )),
10542 ActionDecision::Stale
10543 );
10544 }
10545
10546 #[test]
10547 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10548 let mut state = crate::land::tests::repair_state(true, true);
10549 state.status = RunStatus::Landing;
10550 state.parked = true;
10551 state.driver_exited = true;
10552 let mut q = ask::Question::new(
10553 state.id.clone(),
10554 land::APPROVAL_NODE.into(),
10555 "land".into(),
10556 "Merge?".into(),
10557 String::new(),
10558 vec![land::APPROVE.into(), land::HOLD.into()],
10559 );
10560 q.id = state.id.clone();
10561 state.land_approval = Some(crate::run::LandApproval {
10562 question: q.id.clone(),
10563 head: "current-head".into(),
10564 });
10565 state.save().unwrap();
10566 land::upgrade_repair_choice(&mut q, &state);
10567 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10568 Questions::open().put(&mut q).unwrap();
10569 let tmp = tempfile::tempdir().unwrap();
10570 let queue = Queue::at(tmp.path().join("queue"));
10571 let mut task = held_task_with(&state.id);
10572 task.status = TaskStatus::Parked;
10573 queue.put(&mut task).unwrap();
10574 let empty = Arc::new(tokio::sync::Semaphore::new(0));
10575 let free = Arc::new(tokio::sync::Semaphore::new(1));
10576 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10577 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10578 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10579 assert!(claim.permit.is_some());
10580 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10581 drop(claim);
10582 Questions::open()
10583 .update(&q.id, |q| {
10584 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10585 Ok(())
10586 })
10587 .unwrap();
10588 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10589 assert!(claim.permit.is_none());
10590 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10591 }
10592
10593 #[test]
10594 fn decide_action_resumes_only_the_latest_resumable_run() {
10595 let t = held_task_with("r1");
10596 let q = action_question("r1", resume_action("r1"));
10597 let load = |s: RunState| move |_: &str| Ok(s);
10598 assert_eq!(
10599 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10600 ActionDecision::Resume("r1".into())
10601 );
10602 let q_other = action_question("r1", resume_action("r0"));
10604 assert!(matches!(
10605 decide_action(
10606 &t,
10607 &q_other,
10608 &PHRASES_EN,
10609 load(run_state(RunStatus::Blocked))
10610 ),
10611 ActionDecision::Refuse(_)
10612 ));
10613 assert!(matches!(
10615 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10616 ActionDecision::Refuse(_)
10617 ));
10618 let mut released = run_state(RunStatus::Blocked);
10620 released.released_to = Some("elsewhere".into());
10621 assert!(matches!(
10622 decide_action(&t, &q, &PHRASES_EN, load(released)),
10623 ActionDecision::Refuse(_)
10624 ));
10625 assert!(matches!(
10627 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10628 ActionDecision::Refuse(_)
10629 ));
10630 }
10631
10632 #[test]
10633 fn decide_action_ignores_a_question_about_an_earlier_run() {
10634 let mut t = held_task_with("r1");
10635 t.runs.push("r2".to_owned());
10636 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10637 assert_eq!(
10638 decide_action(
10639 &t,
10640 &action_question("r1", ask::ChoiceAction::Done),
10641 &PHRASES_EN,
10642 never
10643 ),
10644 ActionDecision::Stale
10645 );
10646 }
10647
10648 #[test]
10649 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10650 let mut t = held_task_with("r1");
10651 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10652 assert_eq!(
10653 decide_action(
10654 &t,
10655 &action_question("r1", ask::ChoiceAction::Requeue),
10656 &PHRASES_EN,
10657 never
10658 ),
10659 ActionDecision::Requeue
10660 );
10661 let done_q = action_question("r1", ask::ChoiceAction::Done);
10662 assert_eq!(
10663 decide_action(&t, &done_q, &PHRASES_EN, never),
10664 ActionDecision::Done
10665 );
10666 t.mark_action_applied(&done_q.id);
10667 assert_eq!(
10668 decide_action(&t, &done_q, &PHRASES_EN, never),
10669 ActionDecision::Skip
10670 );
10671
10672 let mut plain = action_question("r1", ask::ChoiceAction::Done);
10674 plain.actions.clear();
10675 assert_eq!(
10676 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
10677 ActionDecision::Skip
10678 );
10679 let mut running = held_task_with("r1");
10681 running.status = TaskStatus::Running;
10682 assert_eq!(
10683 decide_action(
10684 &running,
10685 &action_question("r1", ask::ChoiceAction::Done),
10686 &PHRASES_EN,
10687 never
10688 ),
10689 ActionDecision::Skip
10690 );
10691 }
10692
10693 #[test]
10694 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
10695 crate::run::pin_test_home();
10696 for legacy in [false, true] {
10697 let dir = tempfile::tempdir().unwrap();
10698 let queue = Queue::at(dir.path().join("queue"));
10699 let questions = Questions::at(dir.path().join("questions"));
10700 let run = "20260101-000000-hold";
10701 let mut task = held_task_with(run);
10702 task.status = TaskStatus::Parked;
10703 let mut q = ask::Question::new(
10704 run.into(),
10705 land::APPROVAL_NODE.into(),
10706 "land".into(),
10707 "Repair?".into(),
10708 String::new(),
10709 vec![land::REPAIR.into()],
10710 );
10711 q.actions.insert(land::REPAIR.into(), resume_action(run));
10712 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10713 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10715 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
10716 questions.put(&mut q).unwrap();
10717 task.hold_manual(Some("Keep this PR paused".into()));
10718 if legacy {
10719 task.hold_source = None;
10720 }
10721 queue.put(&mut task).unwrap();
10722
10723 apply_task_choice_actions(&queue, &questions, dir.path());
10724 let after = queue.get(&task.id).unwrap();
10725 assert!(after.operator_held());
10726 assert_eq!(after.hold_source, task.hold_source);
10727 assert_eq!(after.operator_decided_at, task.operator_decided_at);
10728 assert_eq!(after.runs, task.runs);
10729 assert_eq!(after.instruction, task.instruction);
10730 assert!(after.resume_override.is_none());
10731 assert!(after.action_applied(&q.id));
10732 let reason = after.hold_reason.as_deref().unwrap();
10733 assert!(reason.starts_with("Keep this PR paused"));
10734 assert!(reason.contains("later operator decision"));
10735 assert!(reason.contains(&format!("magi task release {}", task.id)));
10736
10737 for recovery in [
10738 crate::conduct::Recovery::Review,
10739 crate::conduct::Recovery::Requeue,
10740 ] {
10741 crate::conduct::apply(
10742 &queue,
10743 &questions,
10744 &crate::conduct::Verdict {
10745 decisions: vec![crate::conduct::Decision {
10746 id: task.id.clone(),
10747 recovery: Some(recovery),
10748 ..Default::default()
10749 }],
10750 },
10751 )
10752 .unwrap();
10753 }
10754 apply_task_choice_actions(&queue, &questions, dir.path());
10757 let still_held = queue.get(&task.id).unwrap();
10758 assert!(still_held.operator_held());
10759 assert_eq!(still_held.hold_reason, after.hold_reason);
10760 assert_eq!(still_held.runs, task.runs);
10761 assert!(still_held.review_branch.is_none());
10762 assert!(!still_held.fresh_start);
10763 assert!(queue.next_runnable().is_none());
10764 }
10765 }
10766
10767 #[test]
10768 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
10769 for held in [false, true] {
10770 for retry in [false, true] {
10771 let dir = tempfile::tempdir().unwrap();
10772 let queue = Queue::at(dir.path().join("queue"));
10773 let questions = Questions::at(dir.path().join("questions"));
10774 let home = dir.path().join("home");
10775 let mut t = task();
10776 if held {
10777 t.hold_machine(Some("driver state unknown".into()));
10778 }
10779 queue.put(&mut t).unwrap();
10780 let verdict = serde_json::from_value(serde_json::json!({
10781 "decisions": [{
10782 "id": t.id,
10783 "question": "Driver state unknown; retry the checks or hold?",
10784 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
10785 "actions": {
10786 "daemon: recheck and retry": {"do": "requeue"},
10787 "daemon: hold the task": {"do": "hold"}
10788 }
10789 }]
10790 }))
10791 .unwrap();
10792 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
10793 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10794 let mut q = questions.list().pop().unwrap();
10795 let choice = if retry {
10796 "daemon: recheck and retry"
10797 } else {
10798 "daemon: hold the task"
10799 };
10800 assert_eq!(q.actions.len(), 2);
10801 q.answer(ask::Answer::Choice(choice.into())).unwrap();
10802 questions.put(&mut q).unwrap();
10803
10804 questions.beat(&q.id, ask::WaiterKind::Deputy);
10806 for _ in 0..2 {
10807 resolve_blockers(&queue, &questions);
10808 apply_task_choice_actions(&queue, &questions, &home);
10809 let waiting = queue.get(&t.id).unwrap();
10810 assert_eq!(waiting.status, TaskStatus::Blocked);
10811 assert_eq!(waiting.blocked_by, [q.id.clone()]);
10812 assert!(waiting.answers.is_empty());
10813 assert!(!waiting.action_applied(&q.id));
10814 assert!(runnable(&queue).is_empty());
10815 let free = Arc::new(tokio::sync::Semaphore::new(1));
10816 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
10817 }
10818 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10819
10820 resolve_blockers(&queue, &questions);
10822 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10823 apply_task_choice_actions(&queue, &questions, &home);
10824 let after = queue.get(&t.id).unwrap();
10825 assert_eq!(
10826 after.status,
10827 if retry {
10828 TaskStatus::Queued
10829 } else {
10830 TaskStatus::Held
10831 }
10832 );
10833 assert!(after.action_applied(&q.id));
10834 assert_eq!(after.operator_held(), !retry);
10835 assert_eq!(after.answers.len(), 1);
10836
10837 let mut changed = after;
10839 if retry {
10840 changed.hold_manual(Some("later hold".into()));
10841 } else {
10842 changed.release_operator("test", None);
10843 }
10844 let expected = changed.status;
10845 queue.put(&mut changed).unwrap();
10846 apply_task_choice_actions(&queue, &questions, &home);
10847 assert_eq!(queue.get(&t.id).unwrap().status, expected);
10848 }
10849 }
10850 }
10851
10852 #[test]
10853 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
10854 let dir = tempfile::tempdir().unwrap();
10855 let queue = Queue::at(dir.path().join("queue"));
10856 let questions = Questions::at(dir.path().join("questions"));
10857 let home = dir.path().join("home");
10858 let mut state = run_state(RunStatus::Blocked);
10859 state.id = "20260101-000000-act1".to_owned();
10860 state.save_under(&home).unwrap();
10861
10862 let mut t = held_task_with(&state.id);
10863 queue.put(&mut t).unwrap();
10864 let mut q = action_question(&state.id, resume_action(&state.id));
10865 questions.put(&mut q).unwrap();
10866
10867 apply_task_choice_actions(&queue, &questions, &home);
10868 let after = queue.get(&t.id).unwrap();
10869 assert_eq!(after.status, TaskStatus::Queued);
10870 assert!(!after.fresh_start);
10871 assert!(after.action_applied(&q.id));
10872 let pin = after.resume_override.clone().unwrap();
10873 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
10874 assert!(pin.forced);
10875
10876 let mut again = queue.get(&t.id).unwrap();
10878 again.hold_machine(Some("later".into()));
10879 queue.put(&mut again).unwrap();
10880 apply_task_choice_actions(&queue, &questions, &home);
10881 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10882 }
10883
10884 #[test]
10885 fn a_delivered_answer_is_still_acted_on_exactly_once() {
10886 let dir = tempfile::tempdir().unwrap();
10887 let queue = Queue::at(dir.path().join("queue"));
10888 let questions = Questions::at(dir.path().join("questions"));
10889 let home = dir.path().join("home");
10890 let mut state = run_state(RunStatus::Blocked);
10891 state.id = "20260101-000000-act2".to_owned();
10892 state.save_under(&home).unwrap();
10893
10894 let mut t = held_task_with(&state.id);
10895 queue.put(&mut t).unwrap();
10896 let mut q = action_question(&state.id, resume_action(&state.id));
10897 q.answer_delivered = true;
10898 questions.put(&mut q).unwrap();
10899
10900 apply_task_choice_actions(&queue, &questions, &home);
10903 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10904 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
10905
10906 let mut again = queue.get(&t.id).unwrap();
10908 again.hold_machine(Some("later".into()));
10909 queue.put(&mut again).unwrap();
10910 apply_task_choice_actions(&queue, &questions, &home);
10911 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10912 }
10913
10914 #[test]
10915 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
10916 let dir = tempfile::tempdir().unwrap();
10917 let queue = Queue::at(dir.path().join("queue"));
10918 let questions = Questions::at(dir.path().join("questions"));
10919 let home = dir.path().join("home");
10920 let mut state = run_state(RunStatus::Blocked);
10921 state.id = "20260101-000000-act3".to_owned();
10922 state.save_under(&home).unwrap();
10923 let mut t = held_task_with(&state.id);
10924 queue.put(&mut t).unwrap();
10925 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
10926 questions.put(&mut q).unwrap();
10927
10928 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
10929 apply_task_choice_actions(&queue, &questions, &home);
10930 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10931
10932 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10933 apply_task_choice_actions(&queue, &questions, &home);
10934 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10935 }
10936
10937 #[test]
10938 fn action_standing_tells_the_reasons_apart() {
10939 let mut t = held_task_with("r1");
10940 let q = action_question("r1", ask::ChoiceAction::Requeue);
10941 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10942 let mut plain = q.clone();
10943 plain.actions.clear();
10944 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
10945
10946 t.mark_action_applied(&q.id);
10948 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
10949
10950 let mut t = held_task_with("r1");
10952 t.start("r2".to_owned());
10953 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
10954 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
10956 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10957 t.status = TaskStatus::Blocked;
10958 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10959
10960 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
10962 c.node = crate::conduct::NODE.to_owned();
10963 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
10964 assert!(!ActionStanding::Busy.daemon_owns());
10965 }
10966
10967 #[test]
10968 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
10969 let dir = tempfile::tempdir().unwrap();
10970 let queue = Queue::at(dir.path().join("queue"));
10971 let questions = Questions::at(dir.path().join("questions"));
10972 let home = dir.path().join("home");
10973 let mut state = run_state(RunStatus::Blocked);
10974 state.id = "20260101-000000-act4".to_owned();
10975 state.save_under(&home).unwrap();
10976 let mut t = held_task_with(&state.id);
10977 t.status = TaskStatus::Running;
10978 queue.put(&mut t).unwrap();
10979 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
10980 q.cwd = Some(dir.path().display().to_string());
10981 questions.put(&mut q).unwrap();
10982
10983 let running = queue.get(&t.id).unwrap();
10986 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
10987 assert!(matches!(
10988 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
10989 crate::waiter::Action::Deliver(_)
10990 ));
10991 apply_task_choice_actions(&queue, &questions, &home);
10993 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10994 let mut back = queue.get(&t.id).unwrap();
10995 back.hold_machine(Some("later".into()));
10996 queue.put(&mut back).unwrap();
10997 apply_task_choice_actions(&queue, &questions, &home);
10998 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
10999 let mut again = queue.get(&t.id).unwrap();
11000 again.hold_machine(Some("again".into()));
11001 queue.put(&mut again).unwrap();
11002 apply_task_choice_actions(&queue, &questions, &home);
11003 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11004 }
11005}