1use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71pub const SCHEMA: u32 = 1;
73
74pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79pub const STALE_SECS: i64 = 30;
88
89pub const POLL: Duration = Duration::from_secs(5);
91
92pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 pub task: String,
123 pub run: String,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 pub schema: u32,
137 pub pid: u32,
139 pub started_at: Timestamp,
141 pub updated_at: Timestamp,
143 pub idle: bool,
145 pub current: Vec<Current>,
151 pub completed: usize,
153 pub polls: u64,
155 #[serde(default)]
157 pub question_recovery: Option<crate::question_delivery::Recovery>,
158}
159
160impl Status {
161 #[must_use]
163 pub fn new() -> Self {
164 let now = Timestamp::now();
165 Self {
166 schema: SCHEMA,
167 pid: std::process::id(),
168 started_at: now,
169 updated_at: now,
170 idle: true,
171 current: Vec::new(),
172 completed: 0,
173 polls: 0,
174 question_recovery: None,
175 }
176 }
177}
178
179impl Default for Status {
180 fn default() -> Self {
181 Self::new()
182 }
183}
184
185#[derive(Debug, Clone)]
187pub struct Opts {
188 pub repo: PathBuf,
190 pub config: Option<PathBuf>,
192 pub poll: Duration,
194 pub max_attempts: usize,
196 pub once: bool,
198 pub merge: Option<String>,
200 pub worktrees_root: Option<PathBuf>,
209}
210
211impl Default for Opts {
212 fn default() -> Self {
213 Self {
214 repo: PathBuf::from("."),
215 config: None,
216 poll: POLL,
217 max_attempts: 2,
218 once: false,
219 merge: None,
220 worktrees_root: None,
221 }
222 }
223}
224
225fn max_concurrent(n: usize) -> usize {
230 n.max(1)
231}
232
233#[must_use]
235pub fn status_path() -> PathBuf {
236 crate::run::home().join("daemon.json")
237}
238
239pub fn write_status(status: &Status) -> Result<()> {
241 write_status_to(&status_path(), status)
242}
243
244pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
249 if let Some(parent) = path.parent() {
250 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
251 }
252 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
253 let tmp = path.with_extension("json.tmp");
254 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
255 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
256 Ok(())
257}
258
259pub fn clear_status() {
262 clear_status_at(&status_path());
263}
264
265fn clear_status_at(path: &Path) {
269 let _ = std::fs::remove_file(path);
270}
271
272#[derive(Debug, Clone, Default)]
285pub struct Stop {
286 stopped: Arc<AtomicBool>,
290 busy: Arc<std::sync::atomic::AtomicUsize>,
296 wake: Arc<Notify>,
300 pause: crate::graph::Pause,
303}
304
305impl Stop {
306 #[must_use]
308 pub fn new() -> Self {
309 Self::default()
310 }
311
312 pub fn stop(&self) {
315 self.stopped.store(true, Ordering::SeqCst);
316 self.wake.notify_one();
320 }
321
322 #[must_use]
324 pub fn stopped(&self) -> bool {
325 self.stopped.load(Ordering::SeqCst)
326 }
327
328 #[must_use]
336 pub fn finishing(&self) -> bool {
337 self.stopped() && self.busy_now()
338 }
339
340 pub fn park(&self, cause: crate::run::ParkCause) {
351 self.pause.park_for(cause);
352 self.stop();
353 }
354
355 #[must_use]
357 pub fn parking(&self) -> bool {
358 self.pause.parked()
359 }
360
361 #[must_use]
363 pub fn pause(&self) -> crate::graph::Pause {
364 self.pause.clone()
365 }
366
367 #[must_use]
373 pub fn busy_now(&self) -> bool {
374 self.busy.load(Ordering::SeqCst) > 0
375 }
376
377 fn enter(&self) {
379 self.busy.fetch_add(1, Ordering::SeqCst);
380 }
381
382 fn exit(&self) {
385 self.busy.fetch_sub(1, Ordering::SeqCst);
386 }
387
388 async fn idle(&self, poll: Duration) {
390 tokio::select! {
391 () = tokio::time::sleep(poll) => {}
392 () = self.wake.notified() => {}
393 }
394 }
395}
396
397#[derive(Debug, Clone, Default, Deserialize)]
404#[serde(default)]
405pub struct Reading {
406 pub schema: u32,
408 pub pid: Option<u32>,
410 pub started_at: Option<Timestamp>,
412 pub updated_at: Option<Timestamp>,
414 pub idle: bool,
416 #[serde(deserialize_with = "de_current")]
428 pub current: Vec<Current>,
429 pub completed: u64,
431 pub polls: u64,
433 #[serde(default)]
435 pub question_recovery: Option<crate::question_delivery::Recovery>,
436}
437
438fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
441where
442 D: serde::Deserializer<'de>,
443{
444 #[derive(Deserialize)]
445 #[serde(untagged)]
446 enum Shape {
447 Many(Vec<Current>),
448 One(Current),
449 }
450 Ok(
451 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
452 Shape::Many(v) => v,
453 Shape::One(c) => vec![c],
454 }),
455 )
456}
457
458impl Reading {
459 #[must_use]
462 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
463 self.updated_at
464 .map(|at| (now.as_second() - at.as_second()).max(0))
465 }
466
467 #[must_use]
471 pub fn running(&self, now: Timestamp) -> bool {
472 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
473 }
474}
475
476#[must_use]
483pub fn read_status(home: &Path) -> Option<Reading> {
484 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
485 serde_json::from_str(&body).ok()
486}
487
488#[must_use]
500pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
501 read_status(home)
502 .filter(|reading| reading.running(now))
503 .map(|reading| reading.current)
504 .unwrap_or_default()
505}
506
507#[must_use]
509pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
510 current_work(home, now).iter().any(|c| c.run == run)
511}
512
513#[must_use]
523pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
524 current_work(home, now)
525 .iter()
526 .any(|c| crate::run::short_of(&c.run) == short)
527}
528
529#[must_use]
531pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
532 current_work(home, now).iter().any(|c| c.task == task)
533}
534
535pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
579 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
580}
581
582fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
586where
587 F: Fn(u32) -> bool,
588{
589 let this_process = std::process::id();
590 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
591 .into_iter()
592 .flatten()
593 .flatten()
594 .map(|e| e.path())
595 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
596 .filter(|p| {
597 match std::fs::read_to_string(p)
598 .ok()
599 .and_then(|body| body.trim().parse::<u32>().ok())
600 {
601 Some(pid) if pid == this_process => false,
605 Some(pid) => !pid_alive(pid),
606 None => p
607 .metadata()
608 .and_then(|m| m.modified())
609 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
610 .is_ok_and(|age| age >= older_than),
611 }
612 })
613 .filter(|p| std::fs::remove_file(p).is_ok())
614 .filter_map(|p| {
615 p.file_stem()
616 .and_then(|s| s.to_str())
617 .map(std::borrow::ToOwned::to_owned)
618 })
619 .collect();
620 swept.sort_unstable();
621 swept
622}
623
624fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
629 task.status == TaskStatus::Running
630 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
631 && !is_working_on_task(home, &task.id, now)
632}
633
634fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
637 queue
638 .list()
639 .into_iter()
640 .filter(|t| is_stalled(t, home, now))
641 .collect()
642}
643
644fn queued_tasks(queue: &Queue) -> Vec<Task> {
650 queue
651 .list()
652 .into_iter()
653 .filter(|t| t.status == TaskStatus::Queued)
654 .collect()
655}
656
657fn finished_tasks(queue: &Queue) -> Vec<Task> {
660 queue
661 .list()
662 .into_iter()
663 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
664 .collect()
665}
666
667fn resolve_blockers(queue: &Queue, questions: &Questions) {
684 for listed in queue.list() {
685 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
686 continue;
687 }
688 let Ok(_claim) = queue.claim(&listed.id) else {
689 continue;
690 };
691 let Ok(mut task) = queue.get(&listed.id) else {
692 continue;
693 };
694 if task.status != TaskStatus::Blocked {
695 continue;
696 }
697 let deleted = queue.apply_deleted_blockers(&mut task, questions);
701 if !deleted.is_empty() {
702 record(queue, &mut task);
703 for id in &deleted {
704 queue.note_dependency_deleted(&task, id);
705 }
706 if task.status != TaskStatus::Blocked {
707 continue;
708 }
709 }
710 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
711 if !missing.is_empty() {
712 let language = language_of(&task, Path::new("."));
713 let mut cause = missing.clone();
714 cause.sort();
715 cause.dedup();
716 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
717 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
718 &task.blocked_by,
719 &missing,
720 &language,
721 )));
722 record(queue, &mut task);
723 continue;
724 }
725 if let Some(q) = task.blocked_by.iter().find_map(|id| {
728 let crate::queue::Dependency::Question(full) =
729 crate::queue::dependency(queue, questions, id)
730 else {
731 return None;
732 };
733 questions.get(&full).ok().filter(|q| {
734 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
735 })
736 }) {
737 let language = language_of(&task, Path::new("."));
738 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
739 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
740 record(queue, &mut task);
741 continue;
742 }
743 let mut changed = false;
744 for id in task.blocked_by.clone() {
745 let resolved = crate::queue::dependency(queue, questions, &id);
746 if let crate::queue::Dependency::Task(full) = &resolved {
747 if queue
748 .get(full)
749 .is_ok_and(|dep| dep.status == TaskStatus::Done)
750 {
751 task.unblock(&id);
752 changed = true;
753 }
754 continue;
755 }
756 if let crate::queue::Dependency::Question(full) = resolved
757 && let Ok(q) = questions.get(&full)
758 && q.status == ask::QuestionStatus::Answered
759 {
760 if q.node == crate::conduct::NODE
764 && q.chosen_action().is_some()
765 && !task.action_applied(&q.id)
766 {
767 continue;
768 }
769 let answer = match &q.answer {
770 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
771 None => String::new(),
772 };
773 task.record_answer(q.summary.clone(), answer);
774 task.unblock(&id);
775 changed = true;
776 }
777 }
778 if changed {
779 record(queue, &mut task);
780 }
781 }
782}
783
784fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
786 if crate::lang::is_japanese(language) {
787 format!(
788 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
789 q.short(),
790 q.summary
791 )
792 } else {
793 format!(
794 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
795 q.short(),
796 q.summary
797 )
798 }
799}
800
801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
804pub(crate) enum ActionStanding {
805 NoAction,
807 Pending,
809 Applied,
812 Stale,
814 Busy,
816}
817
818impl ActionStanding {
819 pub(crate) fn daemon_owns(self) -> bool {
821 matches!(self, Self::Pending | Self::Applied | Self::Stale)
822 }
823}
824
825pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
829 if q.chosen_action().is_none() {
830 ActionStanding::NoAction
831 } else if task.action_applied(&q.id) {
832 ActionStanding::Applied
833 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
834 ActionStanding::Stale
835 } else if matches!(
836 task.status,
837 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
838 ) {
839 ActionStanding::Busy
840 } else {
841 ActionStanding::Pending
842 }
843}
844
845#[derive(Debug, Clone, PartialEq, Eq)]
847enum ActionDecision {
848 Skip,
850 Resume(String),
852 Requeue,
854 Hold,
856 Done,
858 Stale,
861 Refuse(String),
864}
865
866fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
874where
875 F: FnOnce(&str) -> Result<RunState>,
876{
877 let Some(action) = q.chosen_action() else {
878 return ActionDecision::Skip;
879 };
880 if task.action_applied(&q.id)
881 || matches!(
882 task.status,
883 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
884 )
885 {
886 return ActionDecision::Skip;
887 }
888 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891 return ActionDecision::Stale;
892 }
893 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
894 let stopping = q.node == land::APPROVAL_NODE
895 && q.resolution()
896 .as_deref()
897 .is_some_and(crate::merge_decision::stops);
898 let decision_at = if repair || stopping {
902 q.answered_at.unwrap_or(q.asked_at)
903 } else {
904 q.asked_at
905 };
906 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
907 return if repair || stopping {
908 ActionDecision::Refuse(format!(
909 "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
910 if repair { "repair" } else { "stop" },
911 q.id,
912 q.run,
913 task.id
914 ))
915 } else {
916 ActionDecision::Stale
917 };
918 }
919 match action {
920 a if a.maintenance() => ActionDecision::Skip,
921 ask::ChoiceAction::ResumeRun { .. }
922 | ask::ChoiceAction::ReleaseTask { .. }
923 | ask::ChoiceAction::RerunChecks { .. }
924 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
925 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
926 ask::ChoiceAction::Hold => ActionDecision::Hold,
927 ask::ChoiceAction::Done => ActionDecision::Done,
928 ask::ChoiceAction::Resume { run } => {
929 if task.runs.last() != Some(run) {
930 return ActionDecision::Refuse((p.resume_not_latest)(
931 q.short(),
932 ask::short_id(run),
933 ));
934 }
935 match load(run) {
936 Ok(s) if stopping => {
937 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
938 || !s
939 .land_approval
940 .as_ref()
941 .is_some_and(|binding| binding.question == q.id)
942 {
943 ActionDecision::Stale
944 } else if s.liveness(false) == Liveness::Live {
945 ActionDecision::Skip
946 } else if s.status == RunStatus::Landing
947 && !s.released()
948 && s.retired_to.is_none()
949 {
950 ActionDecision::Resume(run.clone())
951 } else {
952 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
953 }
954 }
955 Ok(s)
956 if q.node == land::APPROVAL_NODE
957 && q.resolution().as_deref() == Some(land::REPAIR) =>
958 {
959 if s.merge_repairs.iter().any(|r| r.question == q.id)
960 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
961 {
962 ActionDecision::Stale
965 } else if s.liveness(false) == Liveness::Live {
966 ActionDecision::Skip
967 } else if s.status != RunStatus::Landing
968 || s.released()
969 || s.reviews.is_empty()
970 || !implementers_match(task, &s)
971 || !s
972 .land_approval
973 .as_ref()
974 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
975 {
976 ActionDecision::Refuse(format!(
977 "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
978 q.id, run, run
979 ))
980 } else {
981 ActionDecision::Resume(run.clone())
982 }
983 }
984 Ok(s) if s.liveness(false) == Liveness::Live => {
985 ActionDecision::Refuse("run already has a live driver".into())
986 }
987 Ok(s)
988 if s.status.resumable()
989 && !s.released()
990 && s.retired_to.is_none()
991 && !exhausted_review_budget(&s) =>
992 {
993 ActionDecision::Resume(run.clone())
994 }
995 Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
996 q.short(),
997 ask::short_id(run),
998 )),
999 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1000 q.short(),
1001 ask::short_id(run),
1002 &format!("{e:#}"),
1003 )),
1004 }
1005 }
1006 }
1007}
1008
1009struct Phrases {
1023 graph_stopped: fn(&str, &str) -> String,
1025 quorum_lost: &'static str,
1026 quota_took_out: &'static str,
1028 run_ended: &'static str,
1030 waiting_for_answer: &'static str,
1032 recovered_running: &'static str,
1033 no_run_to_recover: &'static str,
1034 could_not_start: &'static str,
1035 resume_not_latest: fn(&str, &str) -> String,
1036 resume_cannot_progress: fn(&str, &str) -> String,
1037 resume_unreadable: fn(&str, &str, &str) -> String,
1038 handover_refused: fn(&crate::handover::Refused) -> String,
1041 handover_hint: &'static str,
1043 reviewers_never_answered: fn(usize, usize) -> String,
1046}
1047
1048const PHRASES_EN: Phrases = Phrases {
1049 graph_stopped: |status, detail| {
1050 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1051 },
1052 quorum_lost: "the judging panel lost its quorum",
1053 quota_took_out: "; quota took out ",
1054 run_ended: "run ended ",
1055 waiting_for_answer: " - waiting for operator answer to question ",
1056 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1057 no_run_to_recover: "task was `running` with no live daemon and no readable \
1058 run to recover; held for a human to check what happened",
1059 could_not_start: "could not start the run: ",
1060 resume_not_latest: |q, run| {
1061 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1062 },
1063 resume_cannot_progress: |q, run| {
1064 format!("question {q} asked to resume run {run}, which cannot make progress")
1065 },
1066 resume_unreadable: |q, run, e| {
1067 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1068 },
1069 handover_refused: |r| r.to_string(),
1070 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1071 reviewers_never_answered: |missing, rounds| {
1072 format!(
1073 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1074 refusing to call it clean"
1075 )
1076 },
1077};
1078
1079const PHRASES_JA: Phrases = Phrases {
1080 graph_stopped: |status, detail| {
1081 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1082 },
1083 quorum_lost: "審査パネルが定足数を失いました",
1084 quota_took_out: "。クォータで脱落: ",
1085 run_ended: "run 終了: ",
1086 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1087 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1088 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1089 何が起きたか人が確認するため保留にしました",
1090 could_not_start: "run を開始できませんでした: ",
1091 resume_not_latest: |q, run| {
1092 format!(
1093 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1094 )
1095 },
1096 resume_cannot_progress: |q, run| {
1097 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1098 },
1099 resume_unreadable: |q, run, e| {
1100 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1101 },
1102 handover_refused: |r| {
1103 use crate::handover::Refused;
1104 match r {
1105 Refused::Foreign { branch, path, why } => format!(
1106 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1107 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1108 から、やり直してください(詳細: {why})"
1109 ),
1110 Refused::Unsafe { branch, path, why } => format!(
1111 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1112 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1113 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1114 ),
1115 Refused::ReleaseFailed { branch, path, run } => format!(
1116 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1117 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1118 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1119 ),
1120 }
1121 },
1122 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1123 reviewers_never_answered: |missing, rounds| {
1124 format!(
1125 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1126 クリーンとは認めません"
1127 )
1128 },
1129};
1130
1131fn phrases(language: &str) -> &'static Phrases {
1132 if crate::lang::is_japanese(language) {
1133 &PHRASES_JA
1134 } else {
1135 &PHRASES_EN
1136 }
1137}
1138
1139fn language_of(task: &Task, fallback: &Path) -> String {
1143 crate::lang::of_repo(&repo_for(task, fallback))
1144}
1145
1146pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1150 if q.node == crate::conduct::NODE {
1151 return tasks.iter().find(|t| t.id == q.run);
1152 }
1153 tasks.iter().find(|t| t.runs.contains(&q.run))
1154}
1155
1156fn repair_choice_offers(questions: &Questions) {
1159 for q in questions.list().into_iter().filter(|q| {
1160 q.status.open()
1161 && q.node == crate::conduct::NODE
1162 && q.choices
1163 .iter()
1164 .any(|c| crate::choice_effect::describe(q, c).is_none())
1165 }) {
1166 let _ = questions.update(&q.id, |current| {
1167 if current.status.open() {
1168 crate::choice_effect::executable_conductor(current);
1169 if let Some(deputy) = &mut current.deputy {
1170 deputy.brief = crate::deputy::brief(
1171 ¤t.run,
1172 ¤t.detail,
1173 ¤t.choices,
1174 ¤t.actions,
1175 );
1176 }
1177 }
1178 Ok(())
1179 });
1180 }
1181}
1182
1183pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1186 apply_maintenance_choices(queue, questions, home).await;
1187 apply_task_choice_actions(queue, questions, home);
1188}
1189
1190async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1193 use crate::release_watch::{GhForge, ReleaseForge};
1194 for q in questions.list() {
1195 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1196 continue;
1197 };
1198 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1201 continue;
1202 }
1203 let dir = home.join("choice-actions");
1204 if std::fs::create_dir_all(&dir).is_err() {
1205 continue;
1206 }
1207 let Ok(lock) = std::fs::OpenOptions::new()
1208 .create(true)
1209 .truncate(false)
1210 .write(true)
1211 .open(dir.join(format!("{}.lock", q.id)))
1212 else {
1213 continue;
1214 };
1215 if crate::pr_head::try_lock_file(&lock).is_err() {
1216 continue;
1217 }
1218 let fresh = !home
1219 .join("choice-actions")
1220 .join(format!("{}.json", q.id))
1221 .exists();
1222 let result = async {
1223 let receipt = dir.join(format!("{}.json", q.id));
1224 if receipt.exists() {
1225 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1226 anyhow::ensure!(
1227 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1228 "previous maintenance attempt did not confirm completion; inspect its receipt"
1229 );
1230 return Ok::<_, anyhow::Error>(());
1231 }
1232 let record = |status: &str| -> anyhow::Result<()> {
1235 let tmp = receipt.with_extension("tmp");
1236 std::fs::write(
1237 &tmp,
1238 serde_json::to_vec(&serde_json::json!({
1239 "action": action, "status": status,
1240 }))?,
1241 )?;
1242 std::fs::rename(tmp, &receipt)?;
1243 Ok(())
1244 };
1245 let applied = async {
1246 match action {
1247 ask::ChoiceAction::ResumeRun { run } => {
1248 crate::resume::validate(home, run)?;
1249 record("started")?;
1250 if let Some(listed) = queue
1251 .list()
1252 .into_iter()
1253 .find(|t| t.runs.last() == Some(run))
1254 {
1255 let _claim = queue.claim(&listed.id)?;
1256 let mut task = queue.get(&listed.id)?;
1257 anyhow::ensure!(
1258 task.runs.last() == Some(run)
1259 && !matches!(
1260 task.status,
1261 TaskStatus::Running | TaskStatus::Done
1262 ),
1263 "run queue owner changed"
1264 );
1265 anyhow::ensure!(
1266 !task.operator_held()
1267 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1268 "resume was superseded by an operator hold or newer operator decision"
1269 );
1270 task.release_operator("choice", Some(&q.id));
1271 task.resume_override = Some(crate::queue::OperatorResume {
1272 question_id: q.id.clone(),
1273 at: Timestamp::now(),
1274 conductor_rehold: None,
1275 forced: true,
1276 pinned_run: Some(run.clone()),
1277 });
1278 task.mark_action_applied(&q.id);
1279 queue.put(&mut task)?;
1280 } else {
1281 crate::resume::validate_unqueued(home, run)?;
1282 crate::resume::start(run.clone());
1283 }
1284 }
1285 ask::ChoiceAction::ReleaseTask {
1286 task,
1287 held_at,
1288 reason,
1289 } => {
1290 anyhow::ensure!(
1291 queue.resolve_id(task)? == *task,
1292 "task action requires an exact task ID"
1293 );
1294 let _claim = queue.claim(task)?;
1295 let mut task = queue.get(task)?;
1296 if task.action_applied(&q.id) {
1297 return Ok(());
1298 }
1299 if q.node == crate::conduct::NODE
1304 && q.run == task.id
1305 && task.status == TaskStatus::Blocked
1306 && task.blocked_from == Some(TaskStatus::Held)
1307 && task.blocked_by.as_slice() == [q.id.as_str()]
1308 {
1309 task.unblock(&q.id);
1310 }
1311 anyhow::ensure!(
1312 task.status == TaskStatus::Held
1313 && task.held_at == Some(*held_at)
1314 && task.hold_reason.as_deref() == reason.as_deref()
1315 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1316 "task no longer has the hold this question names"
1317 );
1318 task.release_operator("choice", Some(&q.id));
1319 task.mark_action_applied(&q.id);
1320 queue.put(&mut task)?;
1321 }
1322 ask::ChoiceAction::AbandonRun { run } => {
1323 record("started")?;
1324 crate::driver::abandon_proven_dead(home, run)?;
1325 }
1326 ask::ChoiceAction::RerunChecks {
1327 repo,
1328 pr,
1329 head,
1330 runs,
1331 } => {
1332 anyhow::ensure!(
1333 !runs.is_empty()
1334 && runs.len() <= 20
1335 && runs
1336 .iter()
1337 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1338 && !pr.starts_with('-'),
1339 "invalid rerun targets"
1340 );
1341 let snap = GhForge.snapshot(repo, pr).await?;
1342 anyhow::ensure!(
1343 snap.head == *head && snap.state == crate::land::PrLifecycle::Open,
1344 "pull request head or lifecycle changed"
1345 );
1346 anyhow::ensure!(
1347 runs.iter().all(|r| snap
1348 .checks
1349 .iter()
1350 .any(|c| c.run.as_ref() == Some(r)
1351 && crate::release_watch::is_failed(c.verdict))),
1352 "named workflow is no longer failed on this pull request"
1353 );
1354 record("started")?;
1355 let rerun_lock = std::fs::OpenOptions::new()
1356 .create(true)
1357 .truncate(false)
1358 .write(true)
1359 .open(dir.join("reruns.lock"))?;
1360 crate::pr_head::try_lock_file(&rerun_lock)?;
1361 let ledger = dir.join("reruns.json");
1362 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1363 serde_json::from_slice(&std::fs::read(&ledger)?)?
1364 } else {
1365 Default::default()
1366 };
1367 for run in runs {
1368 let key = serde_json::to_string(&(&q.id, repo, pr, head, run))?;
1369 if !recorded.insert(key) {
1370 continue;
1371 }
1372 let tmp = ledger.with_extension("tmp");
1373 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1374 std::fs::rename(tmp, &ledger)?;
1375 GhForge.rerun(repo, run).await?;
1376 }
1377 }
1378 _ => unreachable!(),
1379 }
1380 Ok::<_, anyhow::Error>(())
1381 }
1382 .await;
1383 match applied {
1384 Ok(()) => record("applied"),
1385 Err(e) => {
1386 record(&format!("refused or failed: {e:#}"))?;
1387 Err(e)
1388 }
1389 }
1390 }
1391 .await;
1392 if home
1397 .join("choice-actions")
1398 .join(format!("{}.json", q.id))
1399 .exists()
1400 && let Some(listed) = task_of_question(&queue.list(), &q)
1401 && !listed.action_applied(&q.id)
1402 && let Ok(_claim) = queue.claim(&listed.id)
1403 && let Ok(mut origin) = queue.get(&listed.id)
1404 {
1405 if !origin.operator_held()
1406 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1407 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1408 {
1409 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1410 origin.hold_machine(Some(format!(
1411 "Maintenance choice {} settled; inspect its target before releasing this task",
1412 q.id
1413 )));
1414 } else {
1415 origin.unblock(&q.id);
1416 }
1417 }
1418 origin.mark_action_applied(&q.id);
1419 let _ = queue.put(&mut origin);
1420 }
1421 if let Err(e) = result
1422 && fresh
1423 {
1424 notices::raise_in(
1425 home,
1426 Notice::warn(
1427 &format!("action:{}", q.id),
1428 format!("Choice action {} was not completed: {e:#}", q.id),
1429 ),
1430 );
1431 }
1432 }
1433}
1434
1435pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1444 let tasks = queue.list();
1445 for q in questions.list() {
1446 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1448 continue;
1449 }
1450 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1451 continue;
1452 }
1453 let Some(listed) = task_of_question(&tasks, &q) else {
1454 if q.node == land::APPROVAL_NODE
1455 && q.resolution().as_deref().is_some_and(|choice| {
1456 choice == land::REPAIR || crate::merge_decision::stops(choice)
1457 })
1458 {
1459 notices::raise_in(
1460 home,
1461 Notice::warn(
1462 &format!("repair-owner:{}", q.id),
1463 format!(
1464 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1465 q.run, q.run
1466 ),
1467 ),
1468 );
1469 }
1470 continue;
1471 };
1472 if listed.action_applied(&q.id) {
1473 continue;
1474 }
1475 let Ok(_claim) = queue.claim(&listed.id) else {
1476 continue;
1477 };
1478 let Ok(mut task) = queue.get(&listed.id) else {
1479 continue;
1480 };
1481 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1484 let blockers: Vec<_> = task
1485 .blocked_by
1486 .iter()
1487 .filter(|id| {
1488 crate::queue::dependency(queue, questions, id)
1489 == crate::queue::Dependency::Question(q.id.clone())
1490 })
1491 .cloned()
1492 .collect();
1493 if !blockers.is_empty() {
1494 for id in blockers {
1495 task.unblock(&id);
1496 }
1497 let answer = match &q.answer {
1498 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1499 None => String::new(),
1500 };
1501 task.record_answer(q.summary.clone(), answer);
1502 }
1503 }
1504 let language = language_of(&task, Path::new("."));
1505 let decision = decide_action(&task, &q, phrases(&language), |id| {
1506 RunState::load_under(id, home)
1507 });
1508 let ran = matches!(
1509 decision,
1510 ActionDecision::Resume(_)
1511 | ActionDecision::Requeue
1512 | ActionDecision::Hold
1513 | ActionDecision::Done
1514 );
1515 if ran && asker_may_still_read(questions, &q, home) {
1516 continue;
1525 }
1526 let done = matches!(decision, ActionDecision::Done);
1527 match decision {
1528 ActionDecision::Skip => continue,
1529 ActionDecision::Resume(run) => {
1530 task.release_operator("choice", Some(&q.id));
1531 task.resume_override = Some(crate::queue::OperatorResume {
1532 question_id: q.id.clone(),
1533 at: Timestamp::now(),
1534 conductor_rehold: None,
1535 forced: true,
1536 pinned_run: Some(run),
1537 });
1538 }
1539 ActionDecision::Stale => {}
1540 ActionDecision::Requeue => {
1541 task.release_operator("choice-requeue", Some(&q.id));
1542 task.requeue();
1543 }
1544 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1545 ActionDecision::Done => task.succeed(),
1546 ActionDecision::Refuse(why) => {
1547 if task.operator_held() {
1548 task.hold_reason = Some(match task.hold_reason.take() {
1551 Some(reason) => format!("{reason}\n\n{why}"),
1552 None => why,
1553 });
1554 } else {
1555 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1556 task.hold_machine(Some(why));
1557 }
1558 notices::raise(
1559 Notice::warn(
1560 &format!("action:{}", q.id),
1561 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1562 )
1563 .link(Link::Task {
1564 id: task.id.clone(),
1565 }),
1566 );
1567 }
1568 }
1569 task.mark_action_applied(&q.id);
1570 record(queue, &mut task);
1573 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1574 supersede_prior_runs(&task, home);
1575 }
1576 let _ = questions.update(&q.id, |r| {
1579 r.answer_delivered = true;
1580 Ok(())
1581 });
1582 }
1583}
1584
1585fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1589 let now = Timestamp::now();
1590 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1591 return true;
1592 }
1593 q.node != crate::conduct::NODE
1594 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1595 s.seats_active()
1596 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1597 })
1598}
1599
1600fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1611 let tasks = queue.list();
1612 let by_id: std::collections::BTreeMap<&str, &Task> =
1613 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1614 let referenced: Vec<&str> = tasks
1615 .iter()
1616 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1617 .collect();
1618
1619 for mut question in questions.list() {
1620 if !question.status.open() || question.node != crate::conduct::NODE {
1621 continue;
1622 }
1623 if referenced
1628 .iter()
1629 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1630 {
1631 continue;
1632 }
1633 let Some(task) = by_id.get(question.run.as_str()) else {
1634 continue;
1635 };
1636 question.abandon(format!(
1637 "task {} no longer waits for this answer",
1638 task.short()
1639 ));
1640 if let Err(e) = questions.put(&mut question) {
1641 tracing::warn!(
1642 "could not retire question {} for task {}: {e:#}",
1643 question.short(),
1644 task.short()
1645 );
1646 }
1647 }
1648}
1649
1650#[derive(Debug, Clone, Copy)]
1657pub struct Verdict {
1658 pub status: RunStatus,
1660 pub left_pr: bool,
1662 pub quota_hit: bool,
1664 pub parked: bool,
1666 pub no_viable_candidates: bool,
1673}
1674
1675pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1732 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1733}
1734
1735fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1737 if verdict.parked {
1743 task.park(detail);
1744 return;
1745 }
1746 match verdict.status {
1747 RunStatus::Merged | RunStatus::Ready
1748 if task.pr_recovery.as_ref().is_some_and(|s| {
1749 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1750 }) =>
1751 {
1752 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()));
1753 }
1754 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1755 RunStatus::AlreadyInBase => task.already_landed(detail),
1756 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1757 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1758 task.stall(detail)
1759 }
1760 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1761 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1762 RunStatus::Blocked => task.fail(detail, max_attempts),
1763 RunStatus::VerifiedNoop => task.handed_off(detail),
1764 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1765 }
1766}
1767
1768pub fn supersede_prior_runs(task: &Task, home: &Path) {
1817 let now = Timestamp::now();
1818 let last_run_succeeded = task
1825 .runs
1826 .last()
1827 .and_then(|id| RunState::load_under(id, home).ok())
1828 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1829 for id in task.superseded_attempts(last_run_succeeded) {
1830 let mut state = match RunState::load_under(id, home) {
1831 Ok(s) => s,
1832 Err(e) => {
1833 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1834 continue;
1835 }
1836 };
1837 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1838 continue;
1839 }
1840 let daemon_claims = is_working_on(home, id, now);
1841 if state.liveness(daemon_claims) == Liveness::Live {
1842 continue;
1843 }
1844 state.status = RunStatus::Superseded;
1845 if let Err(e) = state.save_under(home) {
1846 tracing::warn!("could not mark run {id} superseded: {e:#}");
1847 }
1848 }
1849}
1850
1851fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1873 for task in queue.list() {
1874 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1875 continue;
1876 }
1877 supersede_prior_runs(&task, home);
1878 }
1879}
1880
1881fn settle_and_diagnose(
1888 task: &mut Task,
1889 verdict: Verdict,
1890 detail: &str,
1891 max_attempts: usize,
1892 state: &RunState,
1893) {
1894 let p = phrases(&state.config.graph.language);
1895 if let Some(d) = &state.merge_decision {
1898 use crate::merge_decision as md;
1899 if task.runs.last().is_some_and(|id| id != &state.id) {
1900 return;
1901 }
1902 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1903 task.succeed();
1904 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1905 if state.liveness(false) != Liveness::Dead {
1906 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1907 return;
1908 }
1909 let replacement = md::Replacement {
1910 question: d.question.clone(),
1911 run: state.id.clone(),
1912 pr: d.target.pr.clone(),
1913 agent: agent.to_owned(),
1914 context: format!(
1915 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1916 d.target.pr,
1917 state.id,
1918 serde_json::to_string(&state.reviews).unwrap_or_default()
1919 ),
1920 };
1921 task.requeue();
1922 task.pr_recovery = None;
1923 task.review_of = None;
1924 task.replacement = Some(replacement);
1925 } else {
1926 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1927 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1928 } 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())) }));
1929 }
1930 task.mark_action_applied(&d.question);
1931 if let Some(pass) = state.passes.last() {
1932 task.record_pass(&state.id, pass.index, task.attempts, None);
1933 }
1934 return;
1935 }
1936 if let Some(replacement) = &task.replacement
1937 && !state.parked
1938 && state.resource_block.is_none()
1939 && (state.viable().is_empty()
1940 || (state.status == RunStatus::Blocked && state.tally.is_none()))
1941 {
1942 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)));
1943 return;
1944 }
1945 let attempts_before = task.attempts;
1946 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1952 task.notice_cause(
1953 &format!("resource:{}:{}", block.kind, block.node),
1954 None,
1955 None,
1956 );
1957 task.last_error = Some(detail.to_owned());
1958 task.diagnostic = None;
1959 task.attempts = task.attempts.saturating_sub(1);
1960 if block.kind == "disk pressure" {
1961 task.hold_machine(Some(format!(
1962 "{}{}",
1963 crate::disk::RUNNING_PRESSURE,
1964 block.detail
1965 )));
1966 } else {
1967 task.hold_machine(Some(format!(
1968 "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1969 no agent was asked and no attempt was spent",
1970 crate::cache::RESOURCE_HOLD,
1971 block.kind,
1972 block.node
1973 )));
1974 }
1975 if let Some(pass) = state.passes.last() {
1976 task.record_pass(&state.id, pass.index, attempts_before, None);
1977 }
1978 return;
1979 }
1980 let unresolved = task.hold_notice_cause.clone();
1981 if !verdict.parked
1982 && task
1983 .pr_recovery
1984 .as_ref()
1985 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1986 && matches!(
1987 verdict.status,
1988 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1989 )
1990 {
1991 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1992 task.succeed();
1993 } else {
1994 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()));
1995 }
1996 } else if !verdict.parked
1997 && task.pr_recovery.is_some()
1998 && matches!(
1999 verdict.status,
2000 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2001 )
2002 && !verdict.quota_hit
2003 {
2004 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.")));
2005 } else {
2006 settle_in(task, verdict, detail, max_attempts, p);
2007 }
2008 if !verdict.parked
2009 && !verdict.quota_hit
2010 && matches!(
2011 verdict.status,
2012 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2013 )
2014 {
2015 task.recovery_failed(state);
2016 }
2017 if state.prep_failure.is_some() {
2018 task.hold_notice_cause = unresolved;
2021 task.startup_notice_cause("startup-candidates");
2022 }
2023 if let Some(pass) = state.passes.last() {
2026 let parked = match &pass.end {
2027 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2028 _ => None,
2029 };
2030 task.record_pass(&state.id, pass.index, attempts_before, parked);
2031 }
2032 if task.status == TaskStatus::Held {
2033 if state.prep_failure.is_none() {
2034 task.notice_cause(
2035 label(verdict.status),
2036 Some(&state.id),
2037 state.passes.last().map(|p| p.index),
2038 );
2039 }
2040 task.diagnostic = diagnostic(state);
2041 note_open_question(task, &state.id, p);
2042 }
2043}
2044
2045fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2060 let Some(home) = crate::run::try_home() else {
2061 return;
2062 };
2063 let open = Questions::at(home.join("questions")).open_for(run);
2064 let Some(q) = open.first() else {
2065 return;
2066 };
2067 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2068 decisions.sort_unstable();
2069 task.notice_cause(
2070 &format!("questions:{}", decisions.join(",")),
2071 Some(run),
2072 None,
2073 );
2074 let base = task.hold_reason.clone().unwrap_or_default();
2075 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2076}
2077
2078fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2089 match last_run {
2090 Some(state) => {
2091 let verdict = Verdict {
2092 status: state.status,
2093 left_pr: state.pr.is_some(),
2094 quota_hit: !state.quota.is_empty(),
2095 parked: state.parked,
2096 no_viable_candidates: state.viable().is_empty(),
2097 };
2098 let detail = format!(
2099 "{}{}",
2100 phrases(&state.config.graph.language).recovered_running,
2101 describe(&state)
2102 );
2103 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2104 }
2105 None => {
2106 let why = phrases(language).no_run_to_recover;
2109 task.last_error = Some(why.to_owned());
2110 task.notice_cause("missing-run", None, None);
2113 task.hold_machine(Some(why.to_owned()));
2114 }
2115 }
2116}
2117
2118fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2140 let mut reclaimed = Vec::new();
2141 for listed in queue.list() {
2142 if listed.status != TaskStatus::Running {
2143 continue;
2144 }
2145 let Ok(_claim) = queue.claim(&listed.id) else {
2146 continue;
2147 };
2148 let Ok(mut task) = queue.get(&listed.id) else {
2152 continue;
2153 };
2154 if task.status != TaskStatus::Running {
2155 continue;
2156 }
2157 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2158 if let Some(state) = &last_run
2168 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2169 {
2170 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2171 }
2172 let language = if last_run.is_none() {
2173 language_of(&task, Path::new("."))
2174 } else {
2175 String::new()
2176 };
2177 reclaim(&mut task, last_run, max_attempts, &language);
2178 if task.status == TaskStatus::Done {
2179 supersede_prior_runs(&task, &crate::run::home());
2180 }
2181 record(queue, &mut task);
2182 reclaimed.push(task.id.clone());
2183 }
2184 reclaimed
2185}
2186
2187fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2219 reclaim_abandoned_runs_with(
2220 home,
2221 now,
2222 crate::proc::pid_status,
2223 crate::proc::process_started_at,
2224 )
2225}
2226
2227fn reclaim_abandoned_runs_with<F, G>(
2233 home: &Path,
2234 now: Timestamp,
2235 query: F,
2236 identity: G,
2237) -> Vec<String>
2238where
2239 F: Fn(u32) -> Option<bool>,
2240 G: Fn(u32) -> Option<String>,
2241{
2242 let mut abandoned = Vec::new();
2243 for entry in std::fs::read_dir(home.join("runs"))
2244 .into_iter()
2245 .flatten()
2246 .flatten()
2247 {
2248 let id = entry.file_name().to_string_lossy().into_owned();
2249 if !crate::run::is_run_id(&id) {
2250 continue;
2251 }
2252 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2255 continue;
2256 };
2257 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2265 continue;
2266 };
2267 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2268 continue;
2269 };
2270 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2271 continue;
2272 }
2273 let daemon_claims = is_working_on(home, &id, now);
2285 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2286 != crate::run::Liveness::Dead
2287 {
2288 continue;
2289 }
2290 state.abandon("daemon");
2291 if let Err(e) = state.save_under(home) {
2292 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2293 continue;
2294 }
2295 if let Some(notice) = notices::run_ended(&state) {
2298 notices::raise_in(home, notice);
2299 }
2300 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2308 tracing::warn!("abandon questions for {id}: {e:#}");
2309 }
2310 abandoned.push(id);
2311 }
2312 abandoned
2313}
2314
2315pub async fn serve(opts: Opts) -> Result<()> {
2321 serve_until(opts, Stop::new()).await
2322}
2323
2324pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2341 let signal = {
2342 let stop = stop.clone();
2343 tokio::spawn(async move {
2344 if tokio::signal::ctrl_c().await.is_ok() {
2345 stop.stop();
2346 tracing::info!("shutdown requested; a run in flight will be finished first");
2347 }
2348 })
2349 };
2350
2351 let worktrees_root = opts
2352 .worktrees_root
2353 .clone()
2354 .unwrap_or_else(crate::run::default_worktree_root);
2355 let outcome = drive(
2356 &opts,
2357 &Queue::open(),
2358 &status_path(),
2359 &crate::run::home(),
2360 &worktrees_root,
2361 &stop,
2362 )
2363 .await;
2364
2365 signal.abort();
2366 outcome
2367}
2368
2369async fn drive(
2382 opts: &Opts,
2383 queue: &Queue,
2384 status_file: &Path,
2385 home: &Path,
2386 worktrees_root: &Path,
2387 stop: &Stop,
2388) -> Result<()> {
2389 let recovery_cfg = prepare(&opts.repo, opts).ok();
2397 let daemon_cfg = recovery_cfg
2398 .as_ref()
2399 .map(|c| c.daemon.clone())
2400 .unwrap_or_default();
2401 let reconciled = crate::driver::reconcile(home);
2402 if !reconciled.is_empty() {
2403 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2404 }
2405 let mut initial_status = Status::new();
2406 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2407 recovery_cfg.as_ref(),
2408 daemon_cfg.max_deputies,
2409 ));
2410 let status = Arc::new(Mutex::new(initial_status));
2411 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2412 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2413
2414 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2420
2421 let waiter = tokio::spawn(crate::waiter::run(
2426 crate::waiter::Waiter::new(
2427 crate::ask::Questions::at(home.join("questions")),
2428 home.to_path_buf(),
2429 recovery_cfg.clone(),
2430 ),
2431 stop.clone(),
2432 ));
2433
2434 let deputies = tokio::spawn(crate::deputy::run(
2438 crate::deputy::Deputies::new(
2439 crate::ask::Questions::at(home.join("questions")),
2440 home.to_path_buf(),
2441 recovery_cfg.clone(),
2442 opts.repo.clone(),
2443 daemon_cfg.max_deputies,
2444 {
2445 let stop = stop.clone();
2446 Arc::new(move || stop.parking())
2447 },
2448 ),
2449 stop.clone(),
2450 ));
2451
2452 let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2455
2456 let release_watch = tokio::spawn(crate::release_watch::run(
2459 crate::release_watch::Watcher::new(
2460 Box::new(crate::release_watch::GhForge),
2461 home.to_path_buf(),
2462 ),
2463 {
2464 let (repo, opts) = (opts.repo.clone(), opts.clone());
2465 move || release_watch_settings(&repo, &opts)
2466 },
2467 stop.clone(),
2468 ));
2469
2470 tracing::info!(
2471 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2472 queue.root().display(),
2473 opts.poll.as_secs(),
2474 opts.max_attempts,
2475 concurrency,
2476 if daemon_cfg.pause_for_interrupts {
2477 ", interrupts enabled"
2478 } else {
2479 ""
2480 }
2481 );
2482
2483 janitor(&opts.repo, opts, home, worktrees_root).await;
2486 resweep_superseded_attempts(queue, home);
2487
2488 let outcome = poll(
2489 opts,
2490 queue,
2491 &status,
2492 home,
2493 worktrees_root,
2494 stop,
2495 DispatchLimits {
2496 max_concurrent: concurrency,
2497 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2498 },
2499 )
2500 .await;
2501
2502 beat.abort();
2503 waiter.abort();
2504 deputies.abort();
2505 fetcher.abort();
2506 release_watch.abort();
2507 clear_status_at(status_file);
2508 outcome
2509}
2510
2511fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2514 let Ok(cfg) = prepare(repo, opts) else {
2515 return (Vec::new(), 0);
2516 };
2517 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2518 .into_iter()
2519 .map(|r| r.path)
2520 .collect();
2521 let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2524 let runs = crate::run::home().join("runs");
2525 for id in crate::run::list_ids_in(&runs) {
2526 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2527 .ok()
2528 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2529 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2530 known.extend(repo);
2531 }
2532 for k in known {
2533 let k = k.canonicalize().unwrap_or(k);
2534 if k.join(".git").exists() && !paths.contains(&k) {
2535 paths.push(k);
2536 }
2537 }
2538 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2539 if !paths.contains(&own) {
2540 paths.push(own);
2541 }
2542 (paths, cfg.daemon.release_stall_minutes)
2543}
2544
2545const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2547
2548async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2552 while !stop.stopped() {
2553 let (interval, roots) = match prepare(&repo, &opts) {
2554 Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2555 Err(_) => (0, Vec::new()),
2556 };
2557 if interval > 0 && !roots.is_empty() {
2558 let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2559 tracing::debug!("fetch origins: {r:?}");
2560 }
2561 let wait = if interval > 0 { interval } else { 60 };
2563 let mut slept = 0;
2564 while slept < wait && !stop.stopped() {
2565 tokio::time::sleep(Duration::from_secs(1)).await;
2566 slept += 1;
2567 }
2568 }
2569}
2570
2571async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2577 loop {
2578 tokio::time::sleep(HEARTBEAT).await;
2579 let snapshot = {
2580 let mut guard = lock(&status);
2581 guard.updated_at = Timestamp::now();
2582 guard.clone()
2583 };
2584 if let Err(e) = write_status_to(&path, &snapshot) {
2585 tracing::warn!("could not refresh the daemon status file: {e:#}");
2588 }
2589 }
2590}
2591
2592#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2595enum LandResume {
2596 NotLanding,
2599 StillWaiting,
2604 Ready,
2608}
2609
2610fn land_resume_state(task: &Task) -> LandResume {
2614 let Some(run_id) = task.runs.last() else {
2615 return LandResume::NotLanding;
2616 };
2617 let Ok(state) = RunState::load(run_id) else {
2618 return LandResume::NotLanding;
2619 };
2620 if !state.parked {
2621 return LandResume::NotLanding;
2622 }
2623 if state.status == RunStatus::Landing
2624 && state.land_approval.as_ref().is_some_and(|binding| {
2625 ask::Questions::open()
2626 .get(&binding.question)
2627 .is_ok_and(|q| {
2628 q.run == state.id
2629 && q.resolution()
2630 .as_deref()
2631 .is_some_and(crate::merge_decision::stops)
2632 })
2633 })
2634 {
2635 return LandResume::Ready;
2636 }
2637 if !implementers_match(task, &state) {
2638 return LandResume::NotLanding;
2639 }
2640 let node = if state.status == RunStatus::Landing {
2644 land::APPROVAL_NODE
2645 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2646 crate::github_text::ASK_NODE
2647 } else {
2648 return LandResume::NotLanding;
2649 };
2650 let store = ask::Questions::open();
2651 let waiting = store
2652 .list()
2653 .into_iter()
2654 .filter(|q| &q.run == run_id && q.node == node)
2655 .max_by(|a, b| a.id.cmp(&b.id));
2656 let Some(mut q) = waiting else {
2657 return LandResume::Ready;
2658 };
2659 if !q.status.open() {
2660 if q.resolution().as_deref() == Some(land::REPAIR) {
2663 return if state.liveness(false) == Liveness::Live {
2664 LandResume::StillWaiting
2665 } else {
2666 LandResume::NotLanding
2667 };
2668 }
2669 return LandResume::Ready;
2670 }
2671 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2678 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2679 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2680 q.abandon(format!(
2681 "no answer within {}s of asking",
2682 timeout.as_secs().max(1)
2683 ));
2684 if store.put(&mut q).is_ok() {
2687 return LandResume::Ready;
2688 }
2689 }
2690 LandResume::StillWaiting
2691}
2692
2693const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2701
2702const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2714
2715struct InFlightGuard<'a> {
2728 status: &'a Arc<Mutex<Status>>,
2729 stop: &'a Stop,
2730 task_id: &'a str,
2731}
2732
2733impl Drop for InFlightGuard<'_> {
2734 fn drop(&mut self) {
2735 lock(self.status).current.retain(|c| c.task != self.task_id);
2736 self.stop.exit();
2737 }
2738}
2739
2740#[derive(Debug, Clone, PartialEq, Eq)]
2762enum Interrupt {
2763 Idle,
2765 Parking {
2777 parked: Vec<String>,
2778 interrupt_task: String,
2779 },
2780 Running {
2788 parked: Vec<String>,
2789 interrupt_task: String,
2790 },
2791 Resuming { parked: Vec<String> },
2798}
2799
2800fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2821 match state {
2822 Interrupt::Idle => {
2823 if in_flight.len() != 1 {
2835 return Interrupt::Idle;
2836 }
2837 match runnable.iter().find(|t| t.interrupt) {
2838 Some(t) => Interrupt::Parking {
2839 parked: in_flight.to_vec(),
2840 interrupt_task: t.id.clone(),
2841 },
2842 None => Interrupt::Idle,
2843 }
2844 }
2845 Interrupt::Parking {
2846 parked,
2847 interrupt_task,
2848 } => {
2849 if in_flight.iter().any(|id| parked.contains(id)) {
2850 Interrupt::Parking {
2852 parked,
2853 interrupt_task,
2854 }
2855 } else if in_flight.contains(&interrupt_task) {
2856 Interrupt::Running {
2857 parked,
2858 interrupt_task,
2859 }
2860 } else if runnable.iter().any(|t| t.id == interrupt_task) {
2861 Interrupt::Parking {
2865 parked,
2866 interrupt_task,
2867 }
2868 } else {
2869 Interrupt::Resuming { parked }
2874 }
2875 }
2876 Interrupt::Running {
2877 parked,
2878 interrupt_task,
2879 } => {
2880 if in_flight.contains(&interrupt_task) {
2881 Interrupt::Running {
2882 parked,
2883 interrupt_task,
2884 }
2885 } else {
2886 Interrupt::Resuming { parked }
2892 }
2893 }
2894 Interrupt::Resuming { parked } => {
2895 if in_flight.iter().any(|id| parked.contains(id)) {
2896 Interrupt::Idle
2902 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2903 Interrupt::Resuming { parked }
2904 } else {
2905 Interrupt::Idle
2908 }
2909 }
2910 }
2911}
2912
2913fn advance_interrupt_tick(
2919 enabled: bool,
2920 state: Interrupt,
2921 in_flight: &[String],
2922 runnable: &[Task],
2923) -> Interrupt {
2924 if !enabled {
2925 return Interrupt::Idle;
2926 }
2927 advance_interrupt(state, in_flight, runnable)
2928}
2929
2930fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2935 match state {
2936 Interrupt::Idle => candidates,
2937 Interrupt::Parking {
2938 parked,
2939 interrupt_task,
2940 } => {
2941 if in_flight.iter().any(|id| parked.contains(id)) {
2942 Vec::new()
2943 } else {
2944 candidates
2945 .into_iter()
2946 .filter(|t| &t.id == interrupt_task)
2947 .collect()
2948 }
2949 }
2950 Interrupt::Running { .. } => Vec::new(),
2951 Interrupt::Resuming { parked } => candidates
2959 .into_iter()
2960 .find(|t| parked.contains(&t.id))
2961 .into_iter()
2962 .collect(),
2963 }
2964}
2965
2966struct DispatchLimits {
2970 max_concurrent: usize,
2973 pause_for_interrupts: bool,
2975}
2976
2977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2986enum PermitKind {
2987 None,
2992 Urgent,
2999 Ordinary,
3002}
3003
3004fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3007 if priority {
3008 PermitKind::None
3009 } else if urgent {
3010 PermitKind::Urgent
3011 } else {
3012 PermitKind::Ordinary
3013 }
3014}
3015
3016struct DispatchClaim {
3017 task: Task,
3018 claim: crate::queue::Claim,
3019 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3020}
3021
3022fn claim_dispatch(
3025 queue: &Queue,
3026 candidate: &Task,
3027 cooling_down: bool,
3028 ordinary: &Arc<tokio::sync::Semaphore>,
3029 urgent: &Arc<tokio::sync::Semaphore>,
3030) -> Option<DispatchClaim> {
3031 let Ok(claim) = queue.claim(&candidate.id) else {
3032 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3033 return None;
3034 };
3035 let task = match queue.get(&candidate.id) {
3036 Ok(t) if t.status.runnable() => t,
3037 Ok(_) => return None,
3038 Err(e) => {
3039 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3040 return None;
3041 }
3042 };
3043 let resume = land_resume_state(&task);
3044 if resume == LandResume::StillWaiting {
3045 return None;
3046 }
3047 let priority = resume == LandResume::Ready;
3048 if !priority && cooling_down {
3049 return None;
3050 }
3051 let permit = match permit_kind(priority, task.urgent) {
3054 PermitKind::None => None,
3055 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3056 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3057 };
3058 Some(DispatchClaim {
3059 task,
3060 claim,
3061 permit,
3062 })
3063}
3064
3065async fn poll(
3084 opts: &Opts,
3085 queue: &Queue,
3086 status: &Arc<Mutex<Status>>,
3087 home: &Path,
3088 worktrees_root: &Path,
3089 stop: &Stop,
3090 limits: DispatchLimits,
3091) -> Result<()> {
3092 let DispatchLimits {
3093 max_concurrent,
3094 pause_for_interrupts,
3095 } = limits;
3096 let mut attempted: Vec<String> = Vec::new();
3101 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3102 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3110 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3116 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3117 let mut conductor = Conductor::new();
3118 let mut cache_last_checked: Option<Timestamp> = None;
3121 let mut disk_last_checked: Option<Timestamp> = None;
3122 let mut interrupt = Interrupt::Idle;
3124 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3130 std::collections::HashMap::new();
3131
3132 while !stop.stopped() {
3133 lock(status).polls += 1;
3134
3135 while let Some(result) = inflight.try_join_next() {
3140 if let Err(e) = result {
3141 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3142 notices::raise(Notice::error(
3143 "loop:attempt",
3144 "A queued attempt ended abnormally; check the task it was running.",
3145 ));
3146 }
3147 }
3148
3149 let swept = sweep_stale_claims(queue, STALE_CLAIM);
3150 if !swept.is_empty() {
3151 tracing::warn!(
3152 "swept {} stale claim(s) left behind by an earlier daemon: {}",
3153 swept.len(),
3154 swept.join(", ")
3155 );
3156 }
3157 let now = Timestamp::now();
3162
3163 if !stop.busy_now() {
3168 maybe_prune_cache_between_runs(
3169 &opts.repo,
3170 opts,
3171 home,
3172 stop,
3173 &mut cache_last_checked,
3174 now,
3175 )
3176 .await;
3177 }
3178
3179 if cache_check_due(disk_last_checked, now, 30) {
3180 disk_last_checked = Some(now);
3181 if let Ok(cfg) = prepare(&opts.repo, opts) {
3182 crate::retention::sweep(home, &cfg.disk, now).await;
3183 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3186 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3187 }
3188 for current in lock(status).current.clone() {
3189 if let Ok(state) = RunState::load_under(¤t.run, home)
3190 && let Some(reason) = disk_gate(&state.repo, &state.config)
3191 {
3192 if let Some(pause) = interrupt_pauses.get(¤t.task) {
3193 pause.park_because(reason);
3194 }
3195 notices::raise_in(
3196 home,
3197 Notice::warn(
3198 "disk:pressure",
3199 "Disk pressure persists after cleanup; active runs were asked to checkpoint and park. New starts and resumes wait for free space.",
3200 ),
3201 );
3202 }
3203 }
3204 }
3205 }
3206
3207 let stalled = stalled_tasks(queue, home, now);
3208 let stalled_ids: std::collections::BTreeSet<_> =
3209 stalled.iter().map(|task| task.id.clone()).collect();
3210 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3211 if !reclaimed.is_empty() {
3212 tracing::warn!(
3213 "reclaimed {} task(s) left `running` by a daemon that never \
3214 recorded the outcome: {}",
3215 reclaimed.len(),
3216 reclaimed.join(", ")
3217 );
3218 }
3219 let abandoned_runs = reclaim_abandoned_runs(home, now);
3220 if !abandoned_runs.is_empty() {
3221 tracing::warn!(
3222 "failed {} run(s) left behind by a killed process, past every \
3223 active seat's own timeout: {}",
3224 abandoned_runs.len(),
3225 abandoned_runs.join(", ")
3226 );
3227 }
3228
3229 let questions = Questions::at(home.join("questions"));
3234
3235 repair_choice_offers(&questions);
3238 resolve_blockers(queue, &questions);
3239 apply_choice_actions(queue, &questions, home).await;
3240 triage::apply_answers(queue, &questions);
3241 reconcile_task_questions(queue, &questions);
3242 {
3246 let talks = crate::talk::Talks::at(home.join("talks"));
3247 crate::chat_notify::sweep(queue, &talks, home);
3248 crate::chat_watch::sweep(home, &talks);
3249 crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3250 }
3251
3252 let finished: Vec<Task> = finished_tasks(queue)
3258 .into_iter()
3259 .filter(|task| !stalled_ids.contains(&task.id))
3260 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3264 .collect();
3265 let queued = queued_tasks(queue);
3266 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3270 && conductor.worth_a_look(queue, &stalled, &finished)
3271 {
3272 match prepare(&opts.repo, opts) {
3273 Ok(cfg) => {
3274 conductor
3275 .maybe_run(
3276 &cfg,
3277 &opts.repo,
3278 queue,
3279 &questions,
3280 home,
3281 &queued,
3282 &stalled,
3283 &finished,
3284 opts.max_attempts,
3285 )
3286 .await;
3287 }
3288 Err(e) => {
3289 tracing::warn!("conductor: no config: {e:#}");
3290 notices::raise(Notice::warn(
3291 "loop:no-config",
3292 "The loop could not read this repository's config, so held tasks are not being triaged.",
3293 ));
3294 }
3295 }
3296 }
3297
3298 let candidates: Vec<Task> = runnable(queue)
3299 .into_iter()
3300 .filter(|t| !opts.once || !attempted.contains(&t.id))
3301 .collect();
3302
3303 let in_flight: Vec<String> = lock(status)
3308 .current
3309 .iter()
3310 .map(|c| c.task.clone())
3311 .collect();
3312 interrupt_pauses.retain(|id, _| in_flight.contains(id));
3313
3314 interrupt =
3315 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3316 if let Interrupt::Parking {
3317 parked,
3318 interrupt_task,
3319 } = &interrupt
3320 {
3321 let reason = format!(
3322 "task {} asked to run first",
3323 crate::run::short_of(interrupt_task)
3324 );
3325 for id in parked {
3326 if let Some(pause) = interrupt_pauses.get(id) {
3327 pause.park_because(reason.clone());
3328 }
3329 }
3330 }
3331 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3332
3333 let cooling_down =
3334 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3335
3336 let mut started_any = false;
3337 for candidate in candidates {
3338 if stop.stopped() {
3339 break;
3340 }
3341
3342 let Some(DispatchClaim {
3343 mut task,
3344 claim,
3345 permit,
3346 }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3347 else {
3348 continue;
3349 };
3350
3351 let task_id = task.id.clone();
3352 attempted.push(task_id.clone());
3353 lock(status).idle = false;
3354 stop.enter();
3357 started_any = true;
3358
3359 let run_pause = crate::graph::Pause::new();
3363 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3364
3365 let opts = opts.clone();
3366 let queue = queue.clone();
3367 let status = Arc::clone(status);
3368 let stop = stop.clone();
3369 let quota_cooldown_until = Arc::clone("a_cooldown_until);
3370 inflight.spawn(async move {
3371 let _claim = claim;
3375 let _permit = permit;
3376 let _inflight = InFlightGuard {
3378 status: &status,
3379 stop: &stop,
3380 task_id: &task_id,
3381 };
3382 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3383 lock(&status).completed += 1;
3384 let now = Timestamp::now();
3390 if let Some(until) = cooldown_until("a, now) {
3391 let wait = until.as_second() - now.as_second();
3392 *lock("a_cooldown_until) = Some(until);
3393 let hint = quota
3394 .iter()
3395 .find(|q| q.reset.is_some())
3396 .and_then(|q| q.reset.as_deref());
3397 match hint {
3398 Some(h) => tracing::warn!(
3399 "quota hit; waiting {wait}s before taking another ordinary task \
3400 (CLI reported reset: {h})"
3401 ),
3402 None => tracing::warn!(
3403 "quota hit; waiting {wait}s before taking another ordinary task \
3404 (no reset hint reported)"
3405 ),
3406 }
3407 }
3408 });
3409 }
3410
3411 if started_any {
3412 continue;
3413 }
3414
3415 if stop.busy_now() {
3416 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3421 continue;
3422 }
3423
3424 lock(status).idle = true;
3426 if opts.once {
3427 janitor(&opts.repo, opts, home, worktrees_root).await;
3431 resweep_superseded_attempts(queue, home);
3432 triage_held(queue, home, opts).await;
3433 break;
3434 }
3435 stop.idle(opts.poll).await;
3436 if stop.stopped() {
3437 continue;
3438 }
3439 janitor(&opts.repo, opts, home, worktrees_root).await;
3445 resweep_superseded_attempts(queue, home);
3446 triage_held(queue, home, opts).await;
3447 }
3448
3449 while let Some(result) = inflight.join_next().await {
3454 if let Err(e) = result {
3455 tracing::error!("a spawned attempt did not finish cleanly: {e}");
3456 notices::raise(Notice::error(
3457 "loop:attempt",
3458 "A queued attempt ended abnormally; check the task it was running.",
3459 ));
3460 }
3461 }
3462 Ok(())
3463}
3464
3465async fn attempt(
3471 opts: &Opts,
3472 queue: &Queue,
3473 status: &Arc<Mutex<Status>>,
3474 stop: &Stop,
3475 interrupt_pause: crate::graph::Pause,
3476 task: &mut Task,
3477) -> Vec<QuotaLoss> {
3478 let repo = repo_for(task, &opts.repo);
3479 tracing::info!(
3480 "task {} — {} (repo {})",
3481 task.short(),
3482 task.title,
3483 repo.display()
3484 );
3485
3486 if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3490 && previous
3491 .merge_decision
3492 .as_ref()
3493 .is_some_and(|decision| !decision.closed)
3494 && previous.status != RunStatus::Landing
3495 && !crate::merge_decision::resumable_hold(&previous)
3496 {
3497 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)));
3498 record(queue, task);
3499 return Vec::new();
3500 }
3501 let stop_owner = task
3502 .runs
3503 .last()
3504 .and_then(|id| RunState::load(id).ok())
3505 .filter(|state| {
3506 crate::merge_decision::resumable_hold(state)
3507 || state.status == RunStatus::Landing
3508 && state.land_approval.as_ref().is_some_and(|binding| {
3509 Questions::open().get(&binding.question).is_ok_and(|q| {
3510 q.run == state.id
3511 && q.resolution()
3512 .as_deref()
3513 .is_some_and(crate::merge_decision::stops)
3514 })
3515 })
3516 });
3517 if let Some(owner) = stop_owner {
3518 let mut runner = match Runner::resume(&owner.id) {
3519 Ok(runner) => runner,
3520 Err(e) => {
3521 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3522 record(queue, task);
3523 return Vec::new();
3524 }
3525 };
3526 runner.on_pause(stop.pause());
3527 runner.watch_interrupt(interrupt_pause);
3528 let quota_before = runner.state.quota.clone();
3529 task.start(owner.id.clone());
3530 record(queue, task);
3531 lock(status).current.push(Current {
3532 task: task.id.clone(),
3533 run: owner.id,
3534 });
3535 runner.state.next_pass_task_entry = true;
3536 let result = runner.execute().await;
3537 return finish_attempt(
3538 opts.max_attempts,
3539 queue,
3540 task,
3541 &runner.state,
3542 "a_before,
3543 result,
3544 );
3545 }
3546
3547 let unfinished = (!task.fresh_start)
3548 .then(|| unfinished_run(&task.runs, task.short()))
3549 .flatten()
3550 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3551 let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3552 if !task.fresh_start
3553 && task.pr_recovery.is_none()
3554 && task.review_branch.is_none()
3555 && task.resume_override.is_none()
3556 && previous
3557 .as_ref()
3558 .is_some_and(|run| run.retired_to.is_some())
3559 && unfinished.is_none()
3560 {
3561 task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
3562 record(queue, task);
3563 return Vec::new();
3564 }
3565
3566 let saved_recovery = previous.as_ref().filter(|run| {
3567 task.replacement.is_none()
3568 && task.pr_recovery.as_ref().is_some_and(|selected| {
3569 selected.check_task(&task.id, &task.instruction).is_ok()
3570 && selected_starter(selected, Some(run), unfinished.as_deref())
3571 == Starter::Resume(run.id.clone())
3572 })
3573 });
3574
3575 let explicit = match &task.overrides {
3579 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3580 Some(_) => opts.config.as_deref(),
3581 None => opts.config.as_deref(),
3582 };
3583 let (mut config, layers) = if let Some(run) = saved_recovery {
3584 let mut saved = run.clone();
3587 if let Err(e) = saved.configure_recovery_resume() {
3588 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3589 record(queue, task);
3590 return Vec::new();
3591 }
3592 (saved.config, Vec::new())
3593 } else {
3594 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3595 Ok(loaded) => loaded,
3596 Err(e) => {
3597 let reason = format!("[config] {e:#}");
3598 record_config_failure(task, &e);
3599 task.last_error = Some(reason.clone());
3600 task.hold_machine(Some(reason));
3601 record(queue, task);
3602 return Vec::new();
3603 }
3604 };
3605 if let Err(e) = apply_options(&mut config, opts, task) {
3606 task.hold_manual(Some(format!(
3607 "[config] {e:#}; correct the merge override before releasing the task"
3608 )));
3609 record(queue, task);
3610 return Vec::new();
3611 }
3612 if let Some(selected) = &task.pr_recovery
3613 && let Err(e) = selected.configure(&mut config)
3614 {
3615 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3616 record(queue, task);
3617 return Vec::new();
3618 }
3619 (config, layers)
3620 };
3621 let config_evidence = crate::pr_recovery::ConfigEvidence {
3622 layers,
3623 overrides: task.overrides.clone(),
3624 daemon_merge: task
3625 .overrides
3626 .as_ref()
3627 .is_none_or(|o| o.inherit_daemon_options)
3628 .then(|| opts.merge.clone())
3629 .flatten(),
3630 };
3631 apply_task_implementers(&mut config, task);
3632 if let Some(replacement) = &task.replacement {
3633 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3634 old.liveness(false) == Liveness::Dead
3635 && old.merge_decision.as_ref().is_some_and(|d| {
3636 d.closed
3637 && d.question == replacement.question
3638 && d.replacement_run.as_ref().is_none_or(|run| {
3639 task.runs.last() == Some(run)
3640 && RunState::load(run).is_ok_and(|current| {
3641 current.replaces.as_ref().is_some_and(|pin| {
3642 pin.question == replacement.question
3643 && pin.agent == replacement.agent
3644 })
3645 })
3646 })
3647 })
3648 });
3649 if !safe {
3650 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()));
3651 record(queue, task);
3652 return Vec::new();
3653 }
3654 match config.agent(&replacement.agent) {
3655 Ok(agent) if crate::agent::installed(agent) => {}
3656 _ => {
3657 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)));
3658 record(queue, task);
3659 return Vec::new();
3660 }
3661 }
3662 config.graph.implementers = 1;
3663 config.graph.land_approval = true;
3664 config.merge.mode = MergeMode::Pr;
3665 config.graph.selected_implementer = Some(replacement.agent.clone());
3666 }
3667 let p = phrases(&config.graph.language);
3668 let start_failed = p.could_not_start;
3669 if let Ok(base) =
3673 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
3674 .await
3675 && let Ok(head) =
3676 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
3677 {
3678 let seeds = crate::refs::resolve(
3679 &repo,
3680 &head,
3681 &config.merge.remote,
3682 &format!("{}\n{}", task.title, instruction_for(task)),
3683 )
3684 .await;
3685 let mut inputs = crate::queue::recovery_inputs(&seeds);
3686 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
3687 let source = crate::git::rev_parse(&repo, branch)
3688 .await
3689 .unwrap_or_default();
3690 inputs.push_str(&format!(";review:{branch}:{source}"));
3691 }
3692 if let Some(reason) = task.recovery_exhausted(
3693 &head,
3694 &inputs,
3695 task.attempt_limit
3696 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
3697 ) {
3698 task.hold_unrequested_retry(Some(reason));
3699 record(queue, task);
3700 return Vec::new();
3701 }
3702 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
3703 }
3704
3705 if let Some(reason) = disk_gate(&repo, &config) {
3713 task.notice_cause("disk-space", None, None);
3714 task.last_error = Some(reason.clone());
3715 task.hold_machine(Some(reason.clone()));
3716 record(queue, task);
3717 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3718 notices::raise(
3721 Notice::warn(
3722 &format!("disk:{}", repo.display()),
3723 "A task was held for want of free disk space; free some, then release it from the queue.",
3724 )
3725 .link(Link::Task {
3726 id: task.id.clone(),
3727 }),
3728 );
3729 return Vec::new();
3730 }
3731
3732 let review_branch = take_review_branch(task, previous.as_ref());
3757 let branch_exists = match &review_branch {
3758 Some(branch) => crate::git::branch_exists(&repo, branch)
3759 .await
3760 .unwrap_or(false),
3761 None => false,
3762 };
3763 let proposed = match (&review_branch, &unfinished, &task.review_of) {
3767 (None, None, Some(branch)) => Starter::Review(branch.clone()),
3768 _ => choose_starter(
3769 review_branch.as_deref(),
3770 branch_exists,
3771 unfinished.as_deref(),
3772 ),
3773 };
3774 let retry_selected = task.replacement.is_some()
3775 && task.resumption.is_some()
3776 && !task.fresh_start
3777 && previous.as_ref().is_some_and(|run| {
3778 run.replaces.is_some()
3779 && ((run.status == RunStatus::Failed && run.viable().is_empty())
3780 || (run.status == RunStatus::Blocked && run.tally.is_none()))
3781 });
3782 let stop_pin = task
3783 .resume_override
3784 .as_ref()
3785 .filter(|pin| {
3786 Questions::open().get(&pin.question_id).is_ok_and(|q| {
3787 q.node == land::APPROVAL_NODE
3788 && q.resolution()
3789 .as_deref()
3790 .is_some_and(crate::merge_decision::stops)
3791 })
3792 })
3793 .and_then(|pin| pin.pinned_run.clone());
3794 let starter = if let Some(run) = stop_pin {
3795 Starter::Resume(run)
3798 } else if retry_selected {
3799 Starter::Resume(previous.as_ref().unwrap().id.clone())
3800 } else if let Some(selected) = &task.pr_recovery {
3801 if selected.check_task(&task.id, &task.instruction).is_ok() {
3802 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3803 } else {
3804 Starter::Review(selected.branch.clone())
3805 }
3806 } else {
3807 starter_with_implementers(task, previous.as_ref(), proposed)
3808 };
3809 if let Some(pin) = &task.resume_override
3812 && let Some(run) = &pin.pinned_run
3813 && starter != Starter::Resume(run.clone())
3814 {
3815 let run = run.clone();
3816 task.notice_cause("resume-owner", Some(&run), None);
3817 task.hold_machine(Some(format!(
3818 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3819 task.id
3820 )));
3821 record(queue, task);
3822 return Vec::new();
3823 }
3824 if task.replacement.is_some()
3825 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3826 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3827 {
3828 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()));
3829 record(queue, task);
3830 return Vec::new();
3831 }
3832 if let Some(reason) = retained_attempt_hold(
3833 task,
3834 &starter,
3835 config.disk.retained_attempt_limit,
3836 RunState::load,
3837 ) {
3838 if let Starter::Review(branch) = &starter {
3841 task.review_branch = Some(branch.clone());
3842 }
3843 task.hold_unrequested_retry(Some(reason));
3844 record(queue, task);
3845 return Vec::new();
3846 }
3847 let attachments = match task_attachments(queue, task) {
3852 Ok(a) => a,
3853 Err(e) => {
3854 task.attempts += 1;
3855 task.fail_startup_target(
3856 "startup-attachments",
3857 e.name.clone(),
3858 format!("{start_failed}{e:#}"),
3859 opts.max_attempts,
3860 );
3861 record(queue, task);
3862 return Vec::new();
3863 }
3864 };
3865 let startup_pause = stop.pause();
3866 let startup_interrupt = interrupt_pause.clone();
3867 let wait = crate::repo_lock::WaitPolicy::new(
3868 Duration::from_secs(config.graph.timeout_resource_wait),
3869 move || startup_pause.parked() || startup_interrupt.parked(),
3870 );
3871 let started = wait.scope(Box::pin(async { match &starter {
3874 Starter::Review(_) if task.pr_recovery.is_some() => {
3875 let selected = task.pr_recovery.clone().expect("selected recovery");
3876 match selected.check_task(&task.id, &task.instruction) {
3877 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3878 .await
3879 .map(|mut r| {
3880 r.state.attachments = attachments.clone();
3881 r
3882 }),
3883 Err(e) => Err(e),
3884 }
3885 }
3886 Starter::Review(branch) => {
3887 tracing::info!(
3888 "task {} reopens `{branch}` as a review-only pass",
3889 task.short()
3890 );
3891 let takeover = crate::handover::Takeover {
3894 earlier: task.earlier_attempts().to_vec(),
3895 home: crate::run::home(),
3896 choice: take_divergence_answer(branch, &config.merge.remote, task),
3897 task_instruction: Some(instruction_for(task)),
3898 };
3899 Runner::review_taking_over(
3900 &repo,
3901 branch,
3902 config,
3903 Some(takeover),
3904 crate::run::Origin::queue(&task.id),
3905 )
3906 .await
3907 }
3908 Starter::Resume(id) => {
3909 tracing::info!("resuming run {id} rather than competing again");
3910 Runner::resume(id).and_then(|mut r| {
3911 if retry_selected {
3912 for candidate in &mut r.state.candidates {
3915 candidate.failed = None;
3916 candidate.empty = false;
3917 candidate.commits = 0;
3918 }
3919 r.state.status = RunStatus::Implementing;
3920 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3921 }
3922 if r.state.prep_failure.is_some() {
3923 let approval = task
3924 .resumption
3925 .as_ref()
3926 .context("preparation retry requires an explicit task release")?;
3927 r.retry_preparation(approval.at)?;
3928 }
3929 if let Some(instruction) =
3930 prepare_instruction(&starter, Some(&r.state.instruction), task)
3931 {
3932 r.state.instruction = instruction;
3933 }
3934 r.state.attachments = attachments.clone();
3935 if task.replacement.is_some() {
3936 r.state.config.merge.mode = MergeMode::Pr;
3937 r.state.config.graph.land_approval = true;
3938 }
3939 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3943 .overrides
3944 .as_ref()
3945 .and_then(|o| o.merge.as_deref())
3946 .and_then(|m| merge_mode(m).ok())
3947 {
3948 r.state.config.merge.mode = mode;
3949 }
3950 Ok(r)
3951 })
3952 }
3953 Starter::Start => {
3954 if let Some(branch) = &review_branch {
3955 tracing::warn!(
3956 "conductor chose review for task {} but branch `{branch}` no longer \
3957 exists; requeuing as a fresh competition instead",
3958 task.short()
3959 );
3960 }
3961 let instruction = prepare_instruction(&starter, None, task)
3962 .unwrap_or_else(|| task.instruction.clone());
3963 Runner::start_naming(
3964 &repo,
3965 instruction,
3966 &task.title,
3967 config,
3968 crate::run::Origin::queue(&task.id),
3969 )
3970 .await
3971 .map(|mut r| {
3972 r.state.attachments = attachments.clone();
3973 r
3974 })
3975 }
3976 }})).await;
3977 let mut runner = match started {
3978 Ok(r) => r,
3979 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3980 task.last_error = Some(e.to_string());
3981 if stop.parking() || interrupt_pause.parked() {
3982 let attempts = task.attempts;
3983 task.park(e.to_string());
3984 task.attempts = attempts;
3986 } else {
3987 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3988 }
3989 record(queue, task);
3990 return Vec::new();
3991 }
3992 Err(e) if task.pr_recovery.is_some() => {
3996 task.startup_notice_cause("startup-public-head");
3997 task.attempts += 1;
3998 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3999 task.link_run(&partial.run);
4000 task.record_pass(&partial.run, 0, task.attempts, None);
4001 }
4002 task.last_error = Some(format!("{start_failed}{e:#}"));
4003 task.hold_unrequested_retry(Some(format!(
4004 "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."
4005 )));
4006 record(queue, task);
4007 return Vec::new();
4008 }
4009 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4010 let detail = match e.downcast_ref::<crate::handover::Refused>() {
4011 Some(r) => (p.handover_refused)(r),
4012 None => format!("{e:#}"),
4013 };
4014 task.startup_notice_cause("startup-handover");
4015 let reason = format!("{start_failed}{detail}");
4016 task.last_error = Some(reason.clone());
4017 let branch = match &starter {
4020 Starter::Review(branch) => Some(branch.clone()),
4021 _ => None,
4022 };
4023 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4027 record(queue, task);
4028 tracing::warn!(
4029 "holding {} for a branch it cannot take over: {e:#}",
4030 task.short()
4031 );
4032 return Vec::new();
4033 }
4034 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4039 let d = e
4040 .downcast_ref::<crate::reconcile::Diverged>()
4041 .expect("checked by the guard");
4042 let mut q = ask::Question::new(
4043 task.id.clone(),
4044 crate::reconcile::NODE.to_owned(),
4045 crate::reconcile::SEAT.to_owned(),
4046 d.summary(),
4047 d.detail(),
4048 d.choices(),
4049 );
4050 match Questions::open().put(&mut q) {
4051 Ok(()) => {
4052 task.last_error = Some(format!("{e:#}"));
4053 task.review_branch = Some(d.branch.clone());
4056 task.review_instruction = Some(task.instruction.clone());
4057 task.block(vec![q.id.clone()], Some(d.summary()));
4058 }
4059 Err(put) => {
4060 tracing::warn!("could not file the divergence question: {put:#}");
4061 task.attempts += 1;
4062 task.fail_startup(
4063 "startup-question-store",
4064 format!("{start_failed}{e:#}"),
4065 opts.max_attempts,
4066 );
4067 }
4068 }
4069 record(queue, task);
4070 return Vec::new();
4071 }
4072 Err(e) => {
4073 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4079 && let Starter::Review(branch) = &starter
4080 {
4081 task.review_branch = Some(branch.clone());
4082 task.review_instruction = Some(task.instruction.clone());
4083 task.last_error = Some(format!("{start_failed}{e:#}"));
4084 task.status = crate::queue::TaskStatus::Failed;
4085 record(queue, task);
4086 return Vec::new();
4087 }
4088 task.attempts += 1;
4089 task.last_error = Some(format!("{start_failed}{e:#}"));
4090 task.startup_notice_cause("startup-source");
4091 task.hold_unrequested_retry(Some(format!(
4092 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4093 )));
4094 record(queue, task);
4095 return Vec::new();
4096 }
4097 };
4098 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4099 runner.state.recovery_config = Some(config_evidence);
4100 }
4101 if let Some(replacement) = &task.replacement {
4102 if matches!(starter, Starter::Start) {
4103 runner.state.instruction.push_str(&format!(
4104 "\n\n# Replacement review context\n{}",
4105 replacement.context
4106 ));
4107 }
4108 runner.state.replaces = Some(replacement.clone());
4109 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4110 if let Ok(mut old) = RunState::load(&replacement.run)
4111 && let Some(d) = &mut old.merge_decision
4112 {
4113 d.replacement_run = Some(runner.state.id.clone());
4114 old.event(
4115 "replacement",
4116 format!(
4117 "replacement run {} owns the next attempt; old PR remains closed",
4118 runner.state.id
4119 ),
4120 );
4121 if let Err(e) = old.save() {
4122 task.hold_manual(Some(format!(
4123 "Could not link replacement history: {e}; no agents dispatched"
4124 )));
4125 record(queue, task);
4126 return Vec::new();
4127 }
4128 }
4129 }
4130 runner.state.task_instruction = Some(task.instruction.clone());
4131 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4134 if runner.state.origin_chat.is_none() {
4135 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4136 }
4137 runner.on_pause(stop.pause());
4139 runner.watch_interrupt(interrupt_pause);
4143
4144 let run = runner.state.id.clone();
4147 task.start(run.clone());
4148 record(queue, task);
4149 lock(status).current.push(Current {
4150 task: task.id.clone(),
4151 run,
4152 });
4153
4154 let quota_before = runner.state.quota.clone();
4157 runner.state.next_pass_task_entry = true;
4158 let result = runner.execute().await;
4159 finish_attempt(
4160 opts.max_attempts,
4161 queue,
4162 task,
4163 &runner.state,
4164 "a_before,
4165 result,
4166 )
4167}
4168
4169pub fn finish_attempt(
4174 max_attempts: usize,
4175 queue: &Queue,
4176 task: &mut Task,
4177 state: &RunState,
4178 quota_before: &[QuotaLoss],
4179 result: Result<()>,
4180) -> Vec<QuotaLoss> {
4181 let detail = match result {
4182 Ok(()) => describe(state),
4183 Err(e) => format!("{e:#}"),
4184 };
4185 let fresh = losses_this_attempt(quota_before, &state.quota);
4186 let verdict = Verdict {
4187 status: state.status,
4188 left_pr: state.pr.is_some(),
4191 quota_hit: !fresh.is_empty(),
4197 parked: state.parked,
4201 no_viable_candidates: state.viable().is_empty(),
4204 };
4205 if let Some(replacement) = &state.replaces
4206 && let Some(pr) = &state.pr
4207 && let Ok(mut old) = RunState::load(&replacement.run)
4208 && let Some(d) = &mut old.merge_decision
4209 {
4210 d.replacement_pr = Some(pr.url.clone());
4211 let _ = old.save();
4212 }
4213 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4214 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4215 task.hold_unrequested_retry(Some(format!(
4216 "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
4217 )));
4218 }
4219 if task.status == TaskStatus::Done {
4220 supersede_prior_runs(task, &crate::run::home());
4221 }
4222 record(queue, task);
4223 tracing::info!(
4224 "task {} is {} after run {} ({})",
4225 task.short(),
4226 task.status.as_str(),
4227 state.short(),
4228 label(state.status)
4229 );
4230 fresh
4231}
4232
4233pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4237 let waits_on_owner = withheld_text_wait(task).is_some();
4242 if task.status.runnable()
4243 && !waits_on_owner
4244 && !(task.fresh_start && task.replacement.is_some())
4245 {
4246 let why = task.last_error.clone().map_or_else(
4247 || "the run did not finish".to_owned(),
4248 |e| format!("the run did not finish: {e}"),
4249 );
4250 task.hold_unrequested_retry(Some(format!(
4251 "{why}. It was started by hand, so it is not retried \
4252 automatically; `magi task release` retries it."
4253 )));
4254 record(queue, task);
4255 }
4256}
4257
4258#[must_use]
4262pub fn loop_would_resume(run: &str) -> bool {
4263 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4264}
4265
4266#[must_use]
4276pub fn foreign_loop(
4277 reading: Option<&Reading>,
4278 now: Timestamp,
4279 own_pid: u32,
4280) -> Option<Option<u32>> {
4281 let reading = reading.filter(|r| r.running(now))?;
4282 match reading.pid {
4283 Some(pid) if pid == own_pid => None,
4284 pid => Some(pid),
4285 }
4286}
4287
4288pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4303 let status = Arc::new(Mutex::new(Status::new()));
4304 let stop = Stop::new();
4305 Box::pin(attempt(
4308 opts,
4309 queue,
4310 &status,
4311 &stop,
4312 crate::graph::Pause::new(),
4313 task,
4314 ))
4315 .await;
4316 let mut resumes = 0;
4325 while resumes < MAX_WITHHELD_RESUMES {
4326 let Some(timeout) = withheld_text_wait(task) else {
4327 break;
4328 };
4329 eprintln!(
4330 "waiting for the owner's answer on a withheld pull request text \
4331 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4332 );
4333 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4336 let ready = loop {
4337 match land_resume_state(task) {
4338 LandResume::StillWaiting if std::time::Instant::now() < limit => {
4339 tokio::time::sleep(WITHHELD_POLL).await;
4340 }
4341 LandResume::Ready => break true,
4342 _ => break false,
4343 }
4344 };
4345 if !ready {
4346 break;
4347 }
4348 resumes += 1;
4349 Box::pin(attempt(
4350 opts,
4351 queue,
4352 &status,
4353 &stop,
4354 crate::graph::Pause::new(),
4355 task,
4356 ))
4357 .await;
4358 }
4359 hold_if_runnable(queue, task);
4360}
4361
4362const MAX_WITHHELD_RESUMES: u32 = 3;
4365
4366const WITHHELD_POLL: Duration = Duration::from_secs(15);
4368
4369fn withheld_text_wait(task: &Task) -> Option<u64> {
4372 let id = task.runs.last()?;
4373 let s = RunState::load(id).ok()?;
4374 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4375 .then_some(s.config.graph.answer_timeout)
4376}
4377
4378fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4388 after
4389 .iter()
4390 .filter(|q| !before.contains(q))
4391 .cloned()
4392 .collect()
4393}
4394
4395fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4398 if quota.is_empty() {
4399 return None;
4400 }
4401 let with_hint = quota.iter().find(|q| q.reset.is_some());
4402 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4403 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4404 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4405 Some(
4406 now.checked_add(jiff::SignedDuration::from_secs(secs))
4407 .unwrap_or(Timestamp::MAX),
4408 )
4409}
4410
4411fn implementers_match(task: &Task, state: &RunState) -> bool {
4413 task.replacement.as_ref().map_or_else(
4414 || {
4415 task.implementers()
4416 .is_none_or(|n| n == state.config.graph.implementers)
4417 },
4418 |replacement| {
4419 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4420 && state.config.graph.implementers == 1
4421 },
4422 )
4423}
4424
4425fn starter_with_implementers(
4427 task: &Task,
4428 previous: Option<&RunState>,
4429 proposed: Starter,
4430) -> Starter {
4431 if previous.is_some_and(|s| !implementers_match(task, s)) {
4432 task.review_of
4433 .as_ref()
4434 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4435 } else {
4436 proposed
4437 }
4438}
4439
4440fn apply_task_implementers(config: &mut Config, task: &Task) {
4442 if let Some(n) = task.implementers() {
4443 config.graph.implementers = n;
4444 }
4445}
4446
4447#[cfg(test)]
4452fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4453 let explicit = match &task.overrides {
4454 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4455 _ => opts.config.as_deref(),
4456 };
4457 let (mut config, _) = Config::discover(repo, explicit)?;
4458 apply_options(&mut config, opts, task)?;
4459 Ok(config)
4460}
4461
4462fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4463 if task
4464 .overrides
4465 .as_ref()
4466 .is_none_or(|o| o.inherit_daemon_options)
4467 && let Some(mode) = opts.merge.as_deref()
4468 {
4469 config.merge.mode = merge_mode(mode)?;
4470 }
4471 if let Some(o) = &task.overrides {
4472 o.apply(config);
4473 }
4474 Ok(())
4475}
4476
4477fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4479 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4480 if let Some(mode) = &opts.merge {
4481 config.merge.mode = merge_mode(mode)?;
4482 }
4483 Ok(config)
4484}
4485
4486async fn maybe_prune_cache_between_runs(
4517 repo: &Path,
4518 opts: &Opts,
4519 home: &Path,
4520 stop: &Stop,
4521 last_checked: &mut Option<Timestamp>,
4522 now: Timestamp,
4523) {
4524 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4525 return;
4526 }
4527 *last_checked = Some(now);
4528 let cfg = match prepare(repo, opts) {
4529 Ok(cfg) => cfg,
4530 Err(e) => {
4531 tracing::warn!("cache check: no config: {e:#}");
4532 return;
4533 }
4534 };
4535 match clean::prune_cache_if_over_limit(&cfg, home) {
4536 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4537 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4538 pruned.files,
4539 pruned.freed
4540 ),
4541 Ok(_) => {}
4542 Err(e) => {
4543 tracing::warn!("housekeep: prune cache: {e:#}");
4544 notices::raise_in(
4545 home,
4546 Notice::warn(
4547 "housekeep:cache",
4548 "Pruning the shared build cache failed; disk usage may keep growing.",
4549 ),
4550 );
4551 }
4552 }
4553}
4554
4555fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4559 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4560}
4561
4562async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4581 let cfg = match prepare(repo, opts) {
4582 Ok(cfg) => cfg,
4583 Err(e) => {
4584 tracing::warn!("housekeep: no config: {e:#}");
4585 return;
4586 }
4587 };
4588 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4597 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4598 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4603 let mut extra = Vec::new();
4604 if out.unreadable > 0 {
4605 extra.push(format!("{} unreadable", out.unreadable));
4606 }
4607 if out.orphaned_worktrees > 0 {
4608 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4609 }
4610 let detail = if extra.is_empty() {
4611 String::new()
4612 } else {
4613 format!(" ({})", extra.join(", "))
4614 };
4615 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4616 }
4617 if out.external_merges_recorded > 0 {
4618 tracing::info!(
4619 "housekeep: recorded {} run(s) as merged externally",
4620 out.external_merges_recorded
4621 );
4622 }
4623 if out.stale_pr_states_repaired > 0 {
4624 tracing::info!(
4625 "housekeep: rewrote {} run record(s) whose pull request had already settled",
4626 out.stale_pr_states_repaired
4627 );
4628 }
4629 if out.cache_files > 0 {
4630 tracing::info!(
4631 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4632 out.cache_files,
4633 out.cache_freed
4634 );
4635 }
4636 if out.questions_abandoned > 0 {
4637 tracing::info!(
4638 "housekeep: abandoned {} question(s) left open by a finished run",
4639 out.questions_abandoned
4640 );
4641 }
4642}
4643
4644async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4653 let questions = Questions::at(home.join("questions"));
4654 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4655 if report.is_empty() {
4656 return;
4657 }
4658 if !report.quarantined.is_empty() {
4659 tracing::info!(
4660 "triage: held {} blocked task(s) whose blocked-on task or \
4661 question no longer exists: {}",
4662 report.quarantined.len(),
4663 report.quarantined.join(", ")
4664 );
4665 }
4666 if !report.resumed.is_empty() {
4667 tracing::info!(
4668 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4669 report.resumed.len(),
4670 report.resumed.join(", ")
4671 );
4672 }
4673 if !report.asked.is_empty() {
4674 tracing::info!(
4675 "triage: asked about {} held task(s): {}",
4676 report.asked.len(),
4677 report.asked.join(", ")
4678 );
4679 }
4680 if !report.answered.is_empty() {
4681 tracing::info!(
4682 "triage: applied {} operator answer(s): {}",
4683 report.answered.len(),
4684 report.answered.join(", ")
4685 );
4686 }
4687}
4688
4689pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4696 disk_gate_with(repo, config, crate::disk::free_bytes)
4697}
4698
4699fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4703 repo: &Path,
4704 config: &Config,
4705 free_bytes: F,
4706) -> Option<String> {
4707 let min = config.disk.min_free_bytes;
4708 if min == 0 {
4709 return None;
4710 }
4711 let mut paths = vec![repo.to_owned()];
4712 if let Some(cache) = config.cache_dir() {
4713 paths.push(cache);
4714 }
4715 if let Some(root) = &config.graph.worktree_root {
4716 paths.push(root.clone());
4717 }
4718 for path in paths {
4719 let probe = if path == repo {
4720 path.as_path()
4721 } else {
4722 path.ancestors().find(|p| p.exists()).unwrap_or(&path)
4723 };
4724 let reason = match free_bytes(probe) {
4725 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4726 Err(e) => Some(crate::disk::unmeasured_in(
4727 probe,
4728 &e,
4729 &config.graph.language,
4730 )),
4731 };
4732 if reason.is_some() {
4733 return reason;
4734 }
4735 }
4736 None
4737}
4738
4739const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4746
4747const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4751
4752fn quota_wait(
4761 reset_at: Option<Timestamp>,
4762 now: Timestamp,
4763 fallback: Duration,
4764 cap: Duration,
4765) -> Duration {
4766 match reset_at {
4767 Some(at) if at > now => {
4768 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4769 Duration::from_secs(secs).min(cap)
4770 }
4771 _ => fallback,
4772 }
4773}
4774
4775fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4789 parse_reset_hint_zoned(text, now)
4790 .or_else(|| parse_reset_hint_dated(text))
4791 .or_else(|| parse_reset_hint_relative(text, recorded))
4792}
4793
4794fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4798 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4799 let mut rest = rest.trim();
4800 if rest.is_empty() {
4801 return None;
4802 }
4803 let mut total: i64 = 0;
4804 let mut matched = false;
4805 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4806 if let Some((digits, tail)) = rest.split_once(unit)
4807 && !digits.is_empty()
4808 && digits.bytes().all(|b| b.is_ascii_digit())
4809 {
4810 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4811 rest = tail;
4812 matched = true;
4813 }
4814 }
4815 if !rest.is_empty() || !matched {
4816 return None;
4817 }
4818 recorded
4819 .checked_add(jiff::SignedDuration::from_secs(total))
4820 .ok()
4821}
4822
4823fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4827 let clock = clock.trim().to_lowercase();
4828 let (digits, pm) = clock
4829 .strip_suffix("am")
4830 .map(|d| (d, false))
4831 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4832 let (h, m) = digits.trim().split_once(':')?;
4833 let mut hour: i8 = h.trim().parse().ok()?;
4834 let minute: i8 = m.trim().parse().ok()?;
4835 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4836 return None;
4837 }
4838 if pm && hour != 12 {
4839 hour += 12;
4840 } else if !pm && hour == 12 {
4841 hour = 0;
4842 }
4843 Some((hour, minute))
4844}
4845
4846fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4851 let open = text.find('(')?;
4852 let close = text.rfind(')')?;
4853 if close <= open {
4854 return None;
4855 }
4856 let zone = text[open + 1..close].trim();
4857 let (hour, minute) = parse_12h_clock(&text[..open])?;
4858 let tz = jiff::tz::TimeZone::get(zone).ok()?;
4859 let candidate = now
4860 .to_zoned(tz)
4861 .with()
4862 .hour(hour)
4863 .minute(minute)
4864 .second(0)
4865 .millisecond(0)
4866 .microsecond(0)
4867 .nanosecond(0)
4868 .build()
4869 .ok()?;
4870 let mut at = candidate.timestamp();
4871 if at <= now {
4872 at += jiff::SignedDuration::from_hours(24);
4873 }
4874 Some(at)
4875}
4876
4877fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4886 let words: Vec<&str> = text.split_whitespace().collect();
4887 if words.len() < 5 {
4888 return None;
4889 }
4890 (0..=words.len() - 5)
4891 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4892}
4893
4894fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4900 if trailing.is_some_and(|next| next.starts_with('(')) {
4901 return None;
4902 }
4903 let month = month_number(window[0])?;
4904 let day_token = window[1].strip_suffix(',')?.to_lowercase();
4905 let day_digits = ["st", "nd", "rd", "th"]
4906 .iter()
4907 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4908 let day: i8 = day_digits.parse().ok()?;
4909 let year_token = window[2];
4910 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4911 return None;
4912 }
4913 let year: i16 = year_token.parse().ok()?;
4914 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4918 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4919 let date = jiff::civil::Date::new(year, month, day).ok()?;
4920 let candidate = date
4921 .at(hour, minute, 0, 0)
4922 .to_zoned(jiff::tz::TimeZone::UTC)
4923 .ok()?;
4924 Some(candidate.timestamp())
4925}
4926
4927fn month_number(name: &str) -> Option<i8> {
4930 const NAMES: [&str; 12] = [
4931 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4932 ];
4933 let lower = name.to_lowercase();
4934 NAMES
4935 .iter()
4936 .position(|n| *n == lower.as_str())
4937 .map(|i| i as i8 + 1)
4938}
4939
4940fn exhausted_review_budget(state: &RunState) -> bool {
4952 state.status == RunStatus::Blocked
4955 && !state.pr_publication_pending
4956 && state.reviews.len() >= state.config.graph.review_rounds
4957}
4958
4959fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4996 unfinished_run_with(runs, short, RunState::load)
4997}
4998
4999pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5002where
5003 F: FnMut(&str) -> Result<RunState>,
5004{
5005 let mut id = runs.last()?.clone();
5006 let mut visited = std::collections::BTreeSet::new();
5007 let mut repo = None;
5008 loop {
5009 if !runs.contains(&id) || !visited.insert(id.clone()) {
5010 tracing::warn!("invalid or cyclic recovery authority for task {short}");
5011 return None;
5012 }
5013 let state = match load(&id) {
5014 Ok(state) if state.id == id => state,
5015 Ok(_) => return None,
5016 Err(e) => {
5017 tracing::warn!("could not read run {id} for task {short}: {e:#}");
5018 return None;
5019 }
5020 };
5021 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5022 return None;
5023 }
5024 repo = Some(state.repo.clone());
5025 if let Some(authority) = state.retired_to {
5026 id = authority;
5027 continue;
5028 }
5029 return (state.status.resumable()
5030 && !state.released()
5031 && !exhausted_review_budget(&state)
5032 && state.liveness(false) != crate::run::Liveness::Live)
5033 .then_some(id);
5034 }
5035}
5036
5037fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5045where
5046 F: FnOnce(&str) -> Result<RunState>,
5047{
5048 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5050 || task.fresh_start
5051 || task.review_branch.is_some()
5052 {
5053 return false;
5054 }
5055 let Some(id) = task.runs.last() else {
5056 return false;
5057 };
5058 load(id).is_ok_and(|s| {
5059 s.parked
5060 && s.status.resumable()
5061 && !s.released()
5062 && s.retired_to.is_none()
5063 && !exhausted_review_budget(&s)
5064 })
5065}
5066
5067#[derive(Debug, Clone, PartialEq, Eq)]
5070enum Starter {
5071 Review(String),
5074 Resume(String),
5076 Start,
5078}
5079
5080fn retained_attempt_hold(
5084 task: &Task,
5085 starter: &Starter,
5086 limit: usize,
5087 mut load: impl FnMut(&str) -> Result<RunState>,
5088) -> Option<String> {
5089 if limit == 0 || matches!(starter, Starter::Resume(_)) {
5090 return None;
5091 }
5092 let mut retained = 0;
5093 for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5094 let state = match load(id) {
5095 Ok(state) if state.id == *id => state,
5096 _ => {
5097 return Some(format!(
5098 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5099 ));
5100 }
5101 };
5102 if state.retired_to.is_some() || state.released() {
5103 continue;
5104 }
5105 retained += 1;
5108 }
5109 (retained >= limit).then(|| format!(
5110 "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
5111 ))
5112}
5113
5114fn selected_starter(
5116 selected: &crate::pr_recovery::Selection,
5117 previous: Option<&RunState>,
5118 unfinished: Option<&str>,
5119) -> Starter {
5120 if let Some(id) = unfinished
5121 && previous.is_some_and(|r| {
5122 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5123 })
5124 {
5125 Starter::Resume(id.to_owned())
5126 } else {
5127 Starter::Review(selected.branch.clone())
5128 }
5129}
5130
5131fn take_divergence_answer(
5135 branch: &str,
5136 remote: &str,
5137 task: &mut Task,
5138) -> Option<crate::reconcile::Choice> {
5139 let summary = crate::reconcile::summary_for(branch, remote);
5140 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5141 (a.question == summary)
5142 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5143 .flatten()
5144 .map(|c| (i, c))
5145 })?;
5146 task.answers.remove(idx);
5147 Some(choice)
5148}
5149
5150fn choose_starter(
5162 review_branch: Option<&str>,
5163 branch_exists: bool,
5164 unfinished: Option<&str>,
5165) -> Starter {
5166 match review_branch {
5167 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5168 Some(_) => Starter::Start,
5169 None => match unfinished {
5170 Some(id) => Starter::Resume(id.to_owned()),
5171 None => Starter::Start,
5172 },
5173 }
5174}
5175
5176fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5178 let branch = task.review_branch.take();
5179 let instruction = task.review_instruction.take();
5180 branch.filter(|branch| match &instruction {
5181 Some(authored) => *authored == task.instruction,
5182 None => previous.map_or_else(
5185 || task.review_of.as_ref() == Some(branch),
5186 |run| compatible_run_instruction(run, task),
5187 ),
5188 })
5189}
5190
5191fn may_resume_run(run: &RunState, task: &Task) -> bool {
5194 task.resume_override
5195 .as_ref()
5196 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5197 || compatible_run_instruction(run, task)
5198}
5199
5200pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5202 if let Some(authored) = &run.task_instruction {
5203 return compatible_instruction(authored, task);
5204 }
5205 if compatible_instruction(&run.instruction, task) {
5206 return true;
5207 }
5208 if run.reviewed_commits.is_some() {
5211 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5212 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5213 }
5214 if let Some(branch) = &task.review_of {
5215 let canonical = format!(
5216 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5217 );
5218 let generated = format!(
5219 "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"
5220 );
5221 return task.instruction == canonical && run.instruction.starts_with(&generated);
5222 }
5223 }
5224 false
5225}
5226
5227pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5229 strip_answers_block(old, task) == task.instruction
5230}
5231
5232fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5235 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5236 return fallback.to_path_buf();
5237 }
5238 task.repo.clone()
5239}
5240
5241const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5245
5246fn answers_block(task: &Task, count: usize) -> String {
5248 let mut s = ANSWERS_HEADER.to_owned();
5249 for a in &task.answers[..count] {
5250 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5251 }
5252 s
5253}
5254
5255fn resumption_block(r: &crate::queue::Resumption) -> String {
5258 format!(
5259 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5260 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5261 r.generation, r.at, r.instruction, r.answers_through,
5262 )
5263}
5264
5265fn append_answers(base: &str, task: &Task) -> String {
5267 let mut s = base.to_owned();
5268 if !task.answers.is_empty() {
5269 s.push_str(&answers_block(task, task.answers.len()));
5270 }
5271 if let Some(r) = &task.resumption {
5272 s.push_str(&resumption_block(r));
5273 }
5274 s
5275}
5276
5277fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5281 let mut instruction = instruction;
5282 for approval in task
5283 .resumption
5284 .iter()
5285 .chain(task.resumption_history.iter().rev())
5286 {
5287 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5288 instruction = base;
5289 break;
5290 }
5291 }
5292 for count in (1..=task.answers.len()).rev() {
5293 let block = answers_block(task, count);
5294 if let Some(base) = instruction.strip_suffix(&block) {
5295 return base;
5296 }
5297 }
5298 instruction
5299}
5300
5301fn instruction_for(task: &Task) -> String {
5309 append_answers(&task.instruction, task)
5310}
5311
5312fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5324 append_answers(strip_answers_block(old_instruction, task), task)
5325}
5326
5327fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5329 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5330 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5331 if let Some(cause) = task.hold_notice_cause.as_mut() {
5332 cause.target = failure.map(|f| f.target.clone());
5333 }
5334}
5335
5336#[derive(Debug, thiserror::Error)]
5337#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5338struct MissingAttachment {
5339 name: String,
5340 path: PathBuf,
5341}
5342
5343fn task_attachments(
5345 queue: &Queue,
5346 task: &Task,
5347) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5348 let paths = queue.attachment_paths(task);
5349 for (name, path) in task.attachments.iter().zip(&paths) {
5350 if !path.is_file() {
5351 return Err(MissingAttachment {
5352 name: name.clone(),
5353 path: path.clone(),
5354 });
5355 }
5356 }
5357 Ok(paths)
5358}
5359
5360fn prepare_instruction(
5371 starter: &Starter,
5372 old_instruction: Option<&str>,
5373 task: &Task,
5374) -> Option<String> {
5375 match starter {
5376 Starter::Start => Some(instruction_for(task)),
5377 Starter::Resume(_) => Some(resumed_instruction(
5378 old_instruction.expect("a resumed run always has a prior instruction"),
5379 task,
5380 )),
5381 Starter::Review(_) => None,
5382 }
5383}
5384
5385fn record(queue: &Queue, task: &mut Task) {
5389 if let Err(e) = queue.put(task) {
5390 tracing::error!("could not record task {}: {e:#}", task.short());
5391 let notice = Notice::error(
5392 "loop:record",
5393 "The loop could not save a task's state; check the disk.",
5394 )
5395 .link(Link::Task {
5396 id: task.id.clone(),
5397 });
5398 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5400 Some(home) => notices::raise_in(home, notice),
5401 None => notices::raise(notice),
5402 }
5403 }
5404}
5405
5406fn runnable(queue: &Queue) -> Vec<Task> {
5412 let mut tasks: Vec<Task> = queue
5413 .list()
5414 .into_iter()
5415 .filter(|t| t.status.runnable())
5416 .collect();
5417 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5418 tasks
5419}
5420
5421fn describe(state: &RunState) -> String {
5435 let p = phrases(&state.config.graph.language);
5436 let mut detail = if state.status == RunStatus::Stalled {
5437 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5438 seats.sort_unstable();
5439 seats.dedup();
5440 if seats.is_empty() {
5441 p.quorum_lost.to_owned()
5442 } else {
5443 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5444 }
5445 } else {
5446 format!("{}{}", p.run_ended, state.status.display_label())
5447 };
5448 if let Some(last) = state.events.last() {
5449 let unanswered = state
5453 .reviews
5454 .last()
5455 .filter(|r| {
5456 state.status == RunStatus::Blocked
5457 && last.node == "review"
5458 && r.incomplete()
5459 && r.blocking == 0
5460 && r.round == state.config.graph.review_rounds
5461 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5462 })
5463 .map(|r| (r.expected - r.answered, r.round));
5464 match unanswered {
5465 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5466 detail.push_str(&format!(
5467 " ({}: {})",
5468 last.node,
5469 (p.reviewers_never_answered)(missing, rounds)
5470 ));
5471 }
5472 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5473 }
5474 }
5475 detail.push_str(&format!(" [run {}]", state.id));
5476 detail
5477}
5478
5479const DIAGNOSTIC_MAX: usize = 4_000;
5485
5486const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5491
5492fn diagnostic(state: &RunState) -> Option<String> {
5506 let mut parts: Vec<String> = Vec::new();
5507
5508 for o in state.gate.iter().filter(|o| !o.ok()) {
5510 parts.push(format!(
5511 "gate `{}` failed ({}):\n{}",
5512 o.command,
5513 notices::exit_status(o.code),
5514 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5515 ));
5516 }
5517
5518 if let Some(last) = state
5521 .events
5522 .iter()
5523 .rev()
5524 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5525 {
5526 parts.push(last.message.clone());
5527 }
5528
5529 if state.viable().is_empty() {
5536 for c in &state.candidates {
5537 if let Some(evidence) = &c.verified_noop {
5538 parts.push(format!(
5539 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5540 c.label
5541 ));
5542 } else if !c.summary.trim().is_empty() {
5543 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5544 } else if let Some(why) = &c.failed {
5545 parts.push(format!("candidate {}: {why}", c.label));
5546 }
5547 }
5548 }
5549
5550 if parts.is_empty() {
5551 return None;
5552 }
5553 Some(crate::run::tail(
5558 &parts.join("\n\n"),
5559 DIAGNOSTIC_MAX.saturating_sub(100),
5560 ))
5561}
5562
5563fn label(status: RunStatus) -> &'static str {
5571 status.as_str()
5572}
5573
5574pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5576 match mode {
5577 "none" => Ok(MergeMode::None),
5578 "local" => Ok(MergeMode::Local),
5579 "pr" => Ok(MergeMode::Pr),
5580 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5581 }
5582}
5583
5584fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5589 mutex
5590 .lock()
5591 .unwrap_or_else(std::sync::PoisonError::into_inner)
5592}
5593
5594#[cfg(test)]
5595mod tests {
5596 use super::*;
5597 use crate::queue::{Source, TaskStatus};
5598 use crate::run::{Candidate, CommandOutcome};
5599 use pretty_assertions::assert_eq;
5600
5601 fn task() -> Task {
5602 Task::new(
5603 "add retries".to_owned(),
5604 "add retries".to_owned(),
5605 PathBuf::from("/repo"),
5606 Source::Human,
5607 )
5608 }
5609
5610 #[test]
5611 fn selected_public_head_overrides_historical_resume_and_pin() {
5612 let mut t = task();
5613 let mut old = run_state(RunStatus::Blocked);
5614 let selection = crate::pr_recovery::Selection {
5615 url: "url".into(),
5616 branch: format!("magi/task-{}", t.id),
5617 head: "a".repeat(40),
5618 source_head: None,
5619 source_run: None,
5620 source_proof: None,
5621 disposition: Some(crate::pr_recovery::Disposition::Review),
5622 instruction: t.instruction.clone(),
5623 approved_at: Timestamp::now(),
5624 };
5625 t.resume_override = Some(crate::queue::OperatorResume {
5626 pinned_run: Some(old.id.clone()),
5627 question_id: "choice".into(),
5628 at: Timestamp::now(),
5629 conductor_rehold: None,
5630 forced: false,
5631 });
5632 assert_eq!(
5633 selected_starter(&selection, Some(&old), Some(&old.id)),
5634 Starter::Review(selection.branch.clone())
5635 );
5636 old.pr_recovery = Some(selection.clone());
5637 assert_eq!(
5638 selected_starter(&selection, Some(&old), Some(&old.id)),
5639 Starter::Review(selection.branch.clone())
5640 );
5641 old.reviewed_commits = Some(vec!["implementation".into()]);
5642 assert_eq!(
5643 selected_starter(&selection, Some(&old), Some(&old.id)),
5644 Starter::Resume(old.id.clone())
5645 );
5646 let mut changed = selection.clone();
5647 changed.head = "b".repeat(40);
5648 assert_eq!(
5649 selected_starter(&changed, Some(&old), Some(&old.id)),
5650 Starter::Review(changed.branch)
5651 );
5652 }
5653
5654 #[test]
5655 fn candidate_transplant_failure_is_one_actionable_hold() {
5656 let dir = tempfile::tempdir().unwrap();
5657 let q = Queue::at(dir.path().join("queue"));
5658 let mut t = task();
5659 let mut state = run_state(RunStatus::Blocked);
5660 state.event("prep", "cannot apply referenced commit: conflict");
5661 state.prep_failure = Some("conflict".into());
5662 t.start(state.id.clone());
5663 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5664 assert_eq!(t.attempts, 1);
5665 assert_eq!(t.status, TaskStatus::Held);
5666 assert!(t.operator_held());
5667 assert!(!t.status.runnable());
5668 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5669 let first = t.chat_notice_key().unwrap();
5670 t.chat_notices.push(first.clone());
5671 t.release_operator("test", None);
5672 state.id = "another-unprepared-run".into();
5673 t.start(state.id.clone());
5674 finish_attempt(
5675 3,
5676 &q,
5677 &mut t,
5678 &state,
5679 &[],
5680 Err(anyhow::anyhow!("still conflicts")),
5681 );
5682 assert_eq!(
5683 t.chat_notice_key().as_ref(),
5684 Some(&first),
5685 "no work happened"
5686 );
5687 t.release_operator("test", None);
5688 state.prep_failure = None;
5689 state.status = RunStatus::Failed;
5690 state.begin_pass();
5691 t.start(state.id.clone());
5692 finish_attempt(
5693 1,
5694 &q,
5695 &mut t,
5696 &state,
5697 &[],
5698 Err(anyhow::anyhow!("new gate failure")),
5699 );
5700 let failure = t.chat_notice_key().unwrap();
5701 assert_ne!(failure, first, "approved recovery reached a real failure");
5702 t.release_operator("test", None);
5703 state.begin_pass();
5704 t.start(state.id.clone());
5705 finish_attempt(
5706 1,
5707 &q,
5708 &mut t,
5709 &state,
5710 &[],
5711 Err(anyhow::anyhow!("new failure on resume")),
5712 );
5713 assert_ne!(
5714 t.chat_notice_key().as_ref(),
5715 Some(&failure),
5716 "a new settled pass"
5717 );
5718 }
5719
5720 #[test]
5721 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5722 for source in ["cli", "web"] {
5723 let mut t = task();
5724 let mut run = run_state(RunStatus::Blocked);
5725 run.instruction = "Run A original criteria".into();
5726 run.task_instruction = Some(run.instruction.clone());
5727 t.start(run.id.clone());
5728 t.release_operator("choice", Some("resume-question"));
5729 t.resume_override = Some(crate::queue::OperatorResume {
5730 question_id: "resume-question".into(),
5731 at: Timestamp::now(),
5732 conductor_rehold: None,
5733 forced: true,
5734 pinned_run: Some(run.id.clone()),
5735 });
5736 t.hold_machine(Some("not enough free space to start a run".into()));
5737 let mut unchanged = t.clone();
5738 unchanged
5739 .edit("title changed".into(), unchanged.instruction.clone())
5740 .unwrap();
5741 unchanged.release_operator(source, None);
5742 assert_eq!(
5743 unchanged
5744 .resume_override
5745 .as_ref()
5746 .unwrap()
5747 .pinned_run
5748 .as_deref(),
5749 Some(run.id.as_str())
5750 );
5751 assert!(!compatible_run_instruction(&run, &unchanged));
5752 assert!(may_resume_run(&run, &unchanged));
5753
5754 t.edit(
5755 "approved recovery".into(),
5756 "Reuse measured PR head B; fix Clippy; review".into(),
5757 )
5758 .unwrap();
5759 assert!(t.resume_override.is_none());
5760 t.release_operator(source, None);
5761 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5762 assert!(reloaded.resume_override.is_none());
5763 assert!(!may_resume_run(&run, &reloaded));
5764 let unfinished =
5765 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5766 .filter(|_| may_resume_run(&run, &reloaded));
5767 assert_eq!(
5768 choose_starter(None, false, unfinished.as_deref()),
5769 Starter::Start
5770 );
5771 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5772 assert_eq!(
5773 reloaded.resumption_history[0].question_id.as_deref(),
5774 Some("resume-question")
5775 );
5776
5777 unchanged.instruction = "Reuse measured PR head B".into();
5780 unchanged.hold_machine(Some("disk hold".into()));
5781 unchanged.release_operator(source, None);
5782 assert!(unchanged.resume_override.is_none());
5783 assert!(!may_resume_run(&run, &unchanged));
5784 }
5785 }
5786
5787 #[test]
5788 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5789 let mut t = task();
5790 let mut run = run_state(RunStatus::Blocked);
5791 t.review_of = Some("approved-head".into());
5792 t.instruction =
5793 "Review the branch `approved-head` (review-only: no implementation, no judging)."
5794 .into();
5795 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();
5796 run.reviewed_commits = Some(vec!["Commit log".into()]);
5797 t.start(run.id.clone());
5798 t.hold_machine(Some("interrupted review".into()));
5799 t.release_operator("cli", None);
5800 assert!(
5801 compatible_run_instruction(&run, &t),
5802 "legacy explicit review remains resumable"
5803 );
5804 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5805 .filter(|_| compatible_run_instruction(&run, &t));
5806 assert_eq!(
5807 choose_starter(None, false, unfinished.as_deref()),
5808 Starter::Resume(run.id.clone())
5809 );
5810 run.task_instruction = Some(t.instruction.clone());
5811 assert!(compatible_run_instruction(&run, &t));
5812 let reloaded: RunState =
5813 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5814 assert!(compatible_run_instruction(&reloaded, &t));
5815 t.edit(
5816 "new approved head".into(),
5817 "Reuse measured PR head B".into(),
5818 )
5819 .unwrap();
5820 assert!(!compatible_run_instruction(&run, &t));
5821
5822 t.review_of = None;
5824 t.instruction = "Fix Clippy on approved head".into();
5825 run.task_instruction = None;
5826 run.instruction = format!(
5827 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5828 t.instruction
5829 );
5830 assert!(compatible_run_instruction(&run, &t));
5831 t.instruction.push('\n');
5832 assert!(
5833 compatible_run_instruction(&run, &t),
5834 "legacy generated review trimmed the original criteria"
5835 );
5836 t.hold_for_handover(Some("approved-head".into()), "refused".into());
5837 let mut unchanged = t.clone();
5838 assert_eq!(
5839 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5840 Some("approved-head")
5841 );
5842 t.edit("new plan".into(), "Reuse measured PR head B".into())
5843 .unwrap();
5844 assert!(take_review_branch(&mut t, Some(&run)).is_none());
5845 assert!(!compatible_run_instruction(&run, &t));
5846 t.review_branch = Some("approved-head".into());
5847 t.review_instruction = None;
5848 assert!(
5849 take_review_branch(&mut t, Some(&run)).is_none(),
5850 "legacy retained candidate cannot replace a revised approved head"
5851 );
5852 }
5853
5854 #[test]
5855 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5856 crate::run::pin_test_home();
5857 let dir = tempfile::tempdir().unwrap();
5858 let queue = Queue::at(dir.path().join("queue"));
5859 for resume in [true, false] {
5860 let state = run_state(RunStatus::Blocked);
5861 let mut t = task();
5862 t.start(state.id.clone());
5863 let action = if resume {
5864 ask::ChoiceAction::Resume {
5865 run: state.id.clone(),
5866 }
5867 } else {
5868 ask::ChoiceAction::Requeue
5869 };
5870 let mut q = action_question(&state.id, action);
5871 q.status = ask::QuestionStatus::Open;
5872 q.answer = None;
5873 q.answered_at = None;
5874 t.fail("run stopped with a question", 3);
5875 hold_if_runnable(&queue, &mut t);
5876 assert!(t.operator_decided_at.is_none());
5877 assert!(t.operator_held());
5878 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5879 let expected = if resume {
5880 ActionDecision::Resume(state.id.clone())
5881 } else {
5882 ActionDecision::Requeue
5883 };
5884 assert_eq!(
5885 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5886 expected
5887 );
5888 t.hold_manual(Some("later explicit hold".into()));
5889 assert_eq!(
5890 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5891 ActionDecision::Stale
5892 );
5893 }
5894 }
5895
5896 #[test]
5897 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5898 let mut t = task();
5899 t.answers.push(crate::queue::AnsweredQuestion {
5900 question: "Inspect the remote?".into(),
5901 answer: "Inspect then wait".into(),
5902 });
5903 let old = instruction_for(&t);
5904 assert!(compatible_instruction(&old, &t));
5905 t.instruction = "Reuse approved PR head and review".into();
5906 t.release_operator("cli", None);
5907 assert!(!compatible_instruction(&old, &t));
5908 let approved = instruction_for(&t);
5909 assert!(approved.contains("waiting premises are superseded"));
5910 assert!(compatible_instruction(&approved, &t));
5911 assert_eq!(resumed_instruction(&approved, &t), approved);
5912 t.release_operator("web", None);
5913 assert!(compatible_instruction(&approved, &t));
5914 assert_eq!(t.resumption_history.len(), 1);
5915 t.start("run".into());
5916 assert!(instruction_for(&t).contains("Explicit operator resumption"));
5917 }
5918
5919 #[test]
5923 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5924 let mut state = RunState::new(
5925 PathBuf::from("/repo"),
5926 "main".to_owned(),
5927 "abc1234".to_owned(),
5928 "task".to_owned(),
5929 Config::default(),
5930 );
5931 state.status = RunStatus::Blocked;
5932 state.resource_block = Some(crate::run::ResourceBlock {
5933 node: "graft".to_owned(),
5934 kind: "shared build cache".to_owned(),
5935 detail: "timed out".to_owned(),
5936 at: jiff::Timestamp::now(),
5937 });
5938 let mut t = task();
5939 t.start("20260902-000000-aaaa".to_owned());
5940 assert_eq!(t.attempts, 1);
5941 let verdict = Verdict {
5942 status: RunStatus::Blocked,
5943 left_pr: false,
5944 quota_hit: false,
5945 parked: false,
5946 no_viable_candidates: false,
5947 };
5948 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5949 assert_eq!(t.status, TaskStatus::Held);
5950 assert_eq!(t.attempts, 0, "the attempt is refunded");
5951 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5952 assert!(
5953 !t.operator_held(),
5954 "a machine hold, released without a human"
5955 );
5956
5957 let mut selected = task();
5958 selected.start("20260902-000000-cccc".into());
5959 selected.replacement = Some(crate::merge_decision::Replacement {
5960 question: "fixture".into(),
5961 run: "earlier".into(),
5962 pr: "https://example.invalid/pr/1".into(),
5963 agent: "selected".into(),
5964 context: "fixture".into(),
5965 });
5966 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5967 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5968 assert_eq!(selected.attempts, 0);
5969 assert!(
5970 !selected.operator_held(),
5971 "a selected agent also retains a machine resource hold"
5972 );
5973 assert!(
5974 selected
5975 .hold_reason
5976 .as_deref()
5977 .unwrap()
5978 .starts_with("[resource] ")
5979 );
5980
5981 let mut p = task();
5983 p.start("20260902-000000-bbbb".to_owned());
5984 settle_and_diagnose(
5985 &mut p,
5986 Verdict {
5987 parked: true,
5988 ..verdict
5989 },
5990 "parked",
5991 2,
5992 &state,
5993 );
5994 assert_eq!(p.status, TaskStatus::Parked);
5995 }
5996
5997 #[test]
5998 fn record_failure_notice_links_the_task() {
5999 let dir = tempfile::tempdir().unwrap();
6000 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6003 let queue = Queue::at(dir.path().join("queue"));
6004 let mut t = interrupt_task("rec-fail-1");
6005 record(&queue, &mut t);
6006
6007 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6008 assert_eq!(found.len(), 1);
6009 assert_eq!(found[0].key, "loop:record");
6010 assert_eq!(
6011 found[0].link,
6012 Some(Link::Task {
6013 id: "rec-fail-1".to_owned()
6014 })
6015 );
6016 }
6017
6018 fn interrupt_task(id: &str) -> Task {
6021 let mut t = task();
6022 t.id = id.to_owned();
6023 t.interrupt = true;
6024 t
6025 }
6026
6027 fn task_with_id(id: &str) -> Task {
6029 let mut t = task();
6030 t.id = id.to_owned();
6031 t
6032 }
6033
6034 fn urgent_task(id: &str) -> Task {
6036 let mut t = task();
6037 t.id = id.to_owned();
6038 t.urgent = true;
6039 t
6040 }
6041
6042 #[test]
6043 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
6044 let dir = tempfile::tempdir().unwrap();
6045 let queue = Queue::at(dir.path().join("queue"));
6046 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6047 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6048 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
6049 let mut first = task();
6050 queue.put(&mut first).unwrap();
6051 let stale_plain = queue.get(&first.id).unwrap();
6052 first.set_urgent(true).unwrap();
6053 queue.put(&mut first).unwrap();
6054 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
6055 let mut second = urgent_task("second");
6056 queue.put(&mut second).unwrap();
6057 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
6058 drop(queue.claim(&second.id).unwrap());
6059 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
6060 drop(dispatched);
6061 let stale_urgent = queue.get(&first.id).unwrap();
6062 first.set_urgent(false).unwrap();
6063 queue.put(&mut first).unwrap();
6064 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
6065 assert_eq!(urgent.available_permits(), 1);
6066 drop(queue.claim(&first.id).unwrap());
6067 drop(occupied);
6068 }
6069
6070 #[test]
6071 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
6072 let dir = tempfile::tempdir().unwrap();
6073 let queue = Queue::at(dir.path().join("queue"));
6074 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6075 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6076 let mut t = task();
6077 queue.put(&mut t).unwrap();
6078 for enabled in [true, false] {
6079 let stale = queue.get(&t.id).unwrap();
6080 t.set_urgent(enabled).unwrap();
6081 queue.put(&mut t).unwrap();
6082 assert_ne!(stale.urgent, enabled);
6083 let DispatchClaim {
6084 task: fresh,
6085 claim,
6086 permit,
6087 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
6088 assert_eq!(fresh.urgent, enabled);
6089 assert_eq!(ordinary.available_permits(), usize::from(enabled));
6090 assert_eq!(urgent.available_permits(), usize::from(!enabled));
6091 assert!(queue.claim(&t.id).is_err());
6092 assert_eq!(fresh.attempts, stale.attempts);
6093 drop((claim, permit));
6094 assert_eq!(ordinary.available_permits(), 1);
6095 assert_eq!(urgent.available_permits(), 1);
6096 }
6097 t.set_urgent(true).unwrap();
6098 queue.put(&mut t).unwrap();
6099 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
6100 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6101 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
6102 drop(queue.claim(&t.id).unwrap());
6103 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
6104 drop(occupied);
6105 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
6106 drop(queue.claim(&t.id).unwrap());
6107 let held = queue.claim(&t.id).unwrap();
6108 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6109 drop(held);
6110 t.status = TaskStatus::Held;
6111 queue.put(&mut t).unwrap();
6112 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6113 drop(queue.claim(&t.id).unwrap());
6114 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
6115 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6116 drop(queue.claim(&t.id).unwrap());
6117 assert_eq!(urgent.available_permits(), 1);
6118 }
6119
6120 #[test]
6125 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
6126 assert_eq!(permit_kind(true, false), PermitKind::None);
6127 assert_eq!(permit_kind(true, true), PermitKind::None);
6128 }
6129
6130 #[test]
6135 fn permit_kind_separates_urgent_from_ordinary() {
6136 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
6137 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
6138 }
6139
6140 #[test]
6147 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
6148 let cfg = Config::default();
6149 let repo = Path::new("/any/repo/path");
6150
6151 let reason =
6152 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
6153 assert!(reason.contains("1024"), "{reason}");
6154 assert!(
6155 reason.contains(&cfg.disk.min_free_bytes.to_string()),
6156 "{reason}"
6157 );
6158
6159 assert_eq!(
6160 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
6161 None,
6162 "exactly at the floor is open"
6163 );
6164 assert_eq!(
6165 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
6166 None,
6167 "comfortably above the floor is open"
6168 );
6169 }
6170
6171 #[test]
6172 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
6173 let mut cfg = Config::default();
6174 cfg.disk.min_free_bytes = 0;
6175 let repo = Path::new("/any/repo/path");
6176 assert_eq!(
6177 disk_gate_with(repo, &cfg, |_| Ok(0)),
6178 None,
6179 "a zero floor never measures at all"
6180 );
6181 }
6182
6183 #[test]
6184 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
6185 let cfg = Config::default();
6186 let repo = Path::new("/any/repo/path");
6187 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
6188 .expect("a measurement failure must close the gate, not open it");
6189 assert!(reason.contains("could not measure"), "{reason}");
6190 }
6191
6192 #[test]
6193 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
6194 let ordinary = task();
6195 let next = advance_interrupt(
6196 Interrupt::Idle,
6197 std::slice::from_ref(&ordinary.id),
6198 std::slice::from_ref(&ordinary),
6199 );
6200 assert_eq!(next, Interrupt::Idle);
6201 }
6202
6203 #[test]
6204 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6205 let marked = interrupt_task("marked");
6208 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6209 assert_eq!(next, Interrupt::Idle);
6210 }
6211
6212 #[test]
6213 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6214 let marked = interrupt_task("marked");
6215 let next = advance_interrupt(
6216 Interrupt::Idle,
6217 &["running".to_owned()],
6218 std::slice::from_ref(&marked),
6219 );
6220 assert_eq!(
6221 next,
6222 Interrupt::Parking {
6223 parked: vec!["running".to_owned()],
6224 interrupt_task: "marked".to_owned(),
6225 }
6226 );
6227 }
6228
6229 #[test]
6238 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6239 let marked = interrupt_task("marked");
6240
6241 let two = advance_interrupt(
6242 Interrupt::Idle,
6243 &["a".to_owned(), "b".to_owned()],
6244 std::slice::from_ref(&marked),
6245 );
6246 assert_eq!(two, Interrupt::Idle);
6247
6248 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6249 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6250 }
6251
6252 #[test]
6253 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6254 let state = Interrupt::Parking {
6255 parked: vec!["running".to_owned()],
6256 interrupt_task: "marked".to_owned(),
6257 };
6258 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6260 assert_eq!(still_going, state);
6261
6262 let stopped_but_not_yet_dispatched =
6266 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6267 assert_eq!(stopped_but_not_yet_dispatched, state);
6268
6269 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6271 assert_eq!(
6272 dispatched,
6273 Interrupt::Running {
6274 parked: vec!["running".to_owned()],
6275 interrupt_task: "marked".to_owned(),
6276 }
6277 );
6278 }
6279
6280 #[test]
6281 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6282 let state = Interrupt::Running {
6283 parked: vec!["running".to_owned()],
6284 interrupt_task: "marked".to_owned(),
6285 };
6286 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6287 assert_eq!(still_running, state);
6288
6289 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6296 assert_eq!(
6297 ended,
6298 Interrupt::Resuming {
6299 parked: vec!["running".to_owned()]
6300 }
6301 );
6302 }
6303
6304 #[test]
6305 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6306 let state = Interrupt::Resuming {
6307 parked: vec!["running".to_owned()],
6308 };
6309 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6310 assert_eq!(still_waiting, state);
6311
6312 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6313 assert_eq!(dispatched, Interrupt::Idle);
6314 }
6315
6316 #[test]
6322 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6323 {
6324 let state = Interrupt::Parking {
6325 parked: vec!["running".to_owned()],
6326 interrupt_task: "marked".to_owned(),
6327 };
6328 let next = advance_interrupt(state, &[], &[]);
6331 assert_eq!(
6332 next,
6333 Interrupt::Resuming {
6334 parked: vec!["running".to_owned()]
6335 },
6336 "abandoning the interrupt must not abandon the resume it owes"
6337 );
6338 }
6339
6340 #[test]
6343 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6344 let state = Interrupt::Resuming {
6345 parked: vec!["running".to_owned()],
6346 };
6347 let next = advance_interrupt(state, &[], &[]);
6348 assert_eq!(
6349 next,
6350 Interrupt::Idle,
6351 "nothing is left to wait for; the loop must not stay wedged"
6352 );
6353 }
6354
6355 #[test]
6356 fn disabled_by_config_the_sequence_can_never_leave_idle() {
6357 let marked = interrupt_task("marked");
6358 let next = advance_interrupt_tick(
6359 false,
6360 Interrupt::Idle,
6361 &["running".to_owned()],
6362 std::slice::from_ref(&marked),
6363 );
6364 assert_eq!(
6365 next,
6366 Interrupt::Idle,
6367 "an unmarked, unconfigured daemon must behave exactly as before"
6368 );
6369 }
6370
6371 #[test]
6372 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6373 let state = Interrupt::Parking {
6374 parked: vec!["running".to_owned()],
6375 interrupt_task: "marked".to_owned(),
6376 };
6377 let candidates = vec![interrupt_task("marked"), task()];
6378 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6379 assert!(
6380 allowed.is_empty(),
6381 "nothing may dispatch - not even the interrupt task itself - \
6382 until the parked run has actually stopped"
6383 );
6384 }
6385
6386 #[test]
6400 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6401 for state in [
6402 Interrupt::Parking {
6403 parked: vec!["running".to_owned()],
6404 interrupt_task: "marked".to_owned(),
6405 },
6406 Interrupt::Running {
6407 parked: vec!["running".to_owned()],
6408 interrupt_task: "marked".to_owned(),
6409 },
6410 Interrupt::Resuming {
6411 parked: vec!["running".to_owned()],
6412 },
6413 ] {
6414 let candidates = vec![
6415 interrupt_task("marked"),
6416 urgent_task("hot"),
6417 task_with_id("ordinary"),
6418 ];
6419 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6420 assert!(
6421 !allowed.iter().any(|t| t.id == "hot"),
6422 "an urgent candidate must wait out the same gate as anything \
6423 else while the run it would run alongside has not actually \
6424 left flight, for state {state:?}: {allowed:?}"
6425 );
6426 }
6427 }
6428
6429 #[test]
6435 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6436 let state = Interrupt::Resuming {
6437 parked: vec!["hot".to_owned()],
6438 };
6439 let candidates = vec![urgent_task("hot"), task()];
6440 let allowed = interrupt_gate(&state, &[], candidates);
6441 assert_eq!(
6442 allowed.iter().filter(|t| t.id == "hot").count(),
6443 1,
6444 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6445 );
6446 }
6447
6448 #[test]
6449 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6450 let state = Interrupt::Parking {
6451 parked: vec!["running".to_owned()],
6452 interrupt_task: "marked".to_owned(),
6453 };
6454 let other = task();
6455 let candidates = vec![interrupt_task("marked"), other.clone()];
6456 let allowed = interrupt_gate(&state, &[], candidates);
6457 assert_eq!(allowed.len(), 1);
6458 assert_eq!(allowed[0].id, "marked");
6459 }
6460
6461 #[test]
6462 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6463 let state = Interrupt::Running {
6464 parked: vec!["running".to_owned()],
6465 interrupt_task: "marked".to_owned(),
6466 };
6467 let candidates = vec![task(), task()];
6468 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6469 assert!(allowed.is_empty());
6470 }
6471
6472 #[test]
6479 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6480 let state = Interrupt::Resuming {
6481 parked: vec!["a".to_owned(), "c".to_owned()],
6482 };
6483 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6484 let allowed = interrupt_gate(&state, &[], candidates);
6485 assert_eq!(
6486 allowed.len(),
6487 1,
6488 "at most one candidate may be offered while resuming: {allowed:?}"
6489 );
6490 assert_eq!(allowed[0].id, "a");
6491 }
6492
6493 #[test]
6494 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6495 let state = Interrupt::Resuming {
6496 parked: vec!["a".to_owned()],
6497 };
6498 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6499 assert!(allowed.is_empty());
6500 }
6501
6502 #[test]
6508 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6509 let running = task(); let marked = interrupt_task("marked");
6511
6512 let mut state = Interrupt::Idle;
6513 let in_flight = vec![running.id.clone()];
6515 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6516 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6517 assert!(gated.is_empty(), "still waiting on `running` to park");
6518
6519 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6521 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6522 assert_eq!(
6523 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6524 vec!["marked"],
6525 "only the interrupt task may be offered to the dispatcher now"
6526 );
6527
6528 state = advance_interrupt_tick(
6530 true,
6531 state,
6532 &["marked".to_owned()],
6533 std::slice::from_ref(&running),
6534 );
6535 let gated = interrupt_gate(
6536 &state,
6537 &["marked".to_owned()],
6538 vec![marked.clone(), running.clone()],
6539 );
6540 assert!(
6541 gated.is_empty(),
6542 "the parked run must not be offered back while the interrupt \
6543 task is still running"
6544 );
6545
6546 let other = task_with_id("other");
6550 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6551 assert_eq!(
6552 state,
6553 Interrupt::Resuming {
6554 parked: vec![running.id.clone()]
6555 }
6556 );
6557 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6558 assert_eq!(
6559 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6560 vec![running.id.as_str()],
6561 "exactly the parked run resumes - not the unrelated task, even \
6562 though it was offered first"
6563 );
6564
6565 state = advance_interrupt_tick(
6569 true,
6570 state,
6571 std::slice::from_ref(&running.id),
6572 std::slice::from_ref(&other),
6573 );
6574 assert_eq!(state, Interrupt::Idle);
6575 let gated = interrupt_gate(
6576 &state,
6577 std::slice::from_ref(&running.id),
6578 vec![other.clone()],
6579 );
6580 assert_eq!(
6581 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6582 vec![other.id.as_str()],
6583 "ordinary dispatch is unrestricted again"
6584 );
6585 }
6586
6587 #[test]
6588 fn every_run_status_settles_the_task_it_came_from() {
6589 let table = [
6591 (RunStatus::Merged, TaskStatus::Done, 1),
6592 (RunStatus::Ready, TaskStatus::Done, 1),
6593 (RunStatus::Stalled, TaskStatus::Failed, 0),
6594 (RunStatus::Blocked, TaskStatus::Failed, 1),
6595 (RunStatus::Failed, TaskStatus::Failed, 1),
6596 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6597 (RunStatus::Prep, TaskStatus::Failed, 1),
6598 (RunStatus::Implementing, TaskStatus::Failed, 1),
6599 (RunStatus::Judging, TaskStatus::Failed, 1),
6600 (RunStatus::Deliberating, TaskStatus::Failed, 1),
6601 (RunStatus::Voting, TaskStatus::Failed, 1),
6602 (RunStatus::Reviewing, TaskStatus::Failed, 1),
6603 (RunStatus::Gating, TaskStatus::Failed, 1),
6604 ];
6605 for (run, want, attempts) in table {
6606 let mut t = task();
6607 t.start("20260902-000000-aaaa".to_owned());
6608 settle(
6609 &mut t,
6610 Verdict {
6611 status: run,
6612 left_pr: false,
6613 parked: false,
6614 quota_hit: matches!(run, RunStatus::Stalled),
6615 no_viable_candidates: false,
6616 },
6617 "why",
6618 2,
6619 );
6620 assert_eq!(t.status, want, "task status after {}", label(run));
6621 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6622 }
6623 }
6624
6625 #[test]
6626 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6627 let mut stalled = task();
6628 stalled.start("20260902-000000-aaaa".to_owned());
6629 settle(
6630 &mut stalled,
6631 Verdict {
6632 status: RunStatus::Stalled,
6633 left_pr: false,
6634 parked: false,
6635 quota_hit: true,
6636 no_viable_candidates: false,
6637 },
6638 "quota",
6639 1,
6640 );
6641 assert_eq!(stalled.attempts, 0);
6642 assert!(
6643 stalled.status.runnable(),
6644 "a machine problem must leave the task in line"
6645 );
6646
6647 let mut blocked = task();
6648 blocked.start("20260902-000000-aaaa".to_owned());
6649 settle(
6650 &mut blocked,
6651 Verdict {
6652 status: RunStatus::Blocked,
6653 left_pr: false,
6654 parked: false,
6655 quota_hit: false,
6656 no_viable_candidates: false,
6657 },
6658 "findings open",
6659 1,
6660 );
6661 assert_eq!(blocked.attempts, 1);
6662 assert_eq!(
6663 blocked.status,
6664 TaskStatus::Held,
6665 "the last attempt hands the task to a human"
6666 );
6667 }
6668
6669 #[test]
6670 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6671 let mut delivered = task();
6674 delivered.start("20260903-080619-01c2".to_owned());
6675 settle(
6676 &mut delivered,
6677 Verdict {
6678 status: RunStatus::Blocked,
6679 left_pr: true,
6680 parked: false,
6681 quota_hit: false,
6682 no_viable_candidates: false,
6683 },
6684 "no check status",
6685 4,
6686 );
6687 assert_eq!(
6688 delivered.status,
6689 TaskStatus::Held,
6690 "a pull request waiting on CI or a person is not a retryable failure"
6691 );
6692 assert!(
6693 !delivered.status.runnable(),
6694 "the loop must not pick this task up again"
6695 );
6696 assert_eq!(
6697 delivered.last_error.as_deref(),
6698 Some("no check status"),
6699 "the operator needs to be told what the gate was waiting for"
6700 );
6701
6702 let mut empty_handed = task();
6705 empty_handed.start("20260903-080619-01c2".to_owned());
6706 settle(
6707 &mut empty_handed,
6708 Verdict {
6709 status: RunStatus::Blocked,
6710 left_pr: false,
6711 parked: false,
6712 quota_hit: false,
6713 no_viable_candidates: false,
6714 },
6715 "findings open",
6716 4,
6717 );
6718 assert_eq!(empty_handed.status, TaskStatus::Failed);
6719 assert!(empty_handed.status.runnable());
6720 }
6721
6722 #[test]
6723 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6724 let mut noop = task();
6730 noop.start("20260912-131304-391f".to_owned());
6731 settle(
6732 &mut noop,
6733 Verdict {
6734 status: RunStatus::VerifiedNoop,
6735 left_pr: false,
6736 parked: false,
6737 quota_hit: false,
6738 no_viable_candidates: true,
6739 },
6740 "candidate A: already fixed by b32cfc4, on main",
6741 4,
6742 );
6743 assert_eq!(
6744 noop.status,
6745 TaskStatus::Held,
6746 "an unverified claim is a request for a human, not a failure"
6747 );
6748 assert!(
6749 !noop.status.runnable(),
6750 "the loop must not requeue this on the same unverified claim"
6751 );
6752 assert_eq!(noop.attempts, 1);
6757 }
6758
6759 #[test]
6760 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6761 let mut parked = task();
6766 parked.start("20260903-183634-2d98".to_owned());
6767 settle(
6768 &mut parked,
6769 Verdict {
6770 status: RunStatus::Implementing,
6771 left_pr: false,
6772 quota_hit: false,
6773 parked: true,
6774 no_viable_candidates: false,
6775 },
6776 "parked after `implementing`",
6777 2,
6778 );
6779 assert_eq!(parked.attempts, 0, "a park is refunded");
6780 assert!(
6781 parked.status.runnable(),
6782 "and the task stays in line so the next loop resumes its run"
6783 );
6784 assert_eq!(parked.status, TaskStatus::Parked);
6785 assert_eq!(
6786 parked.park_reason.as_deref(),
6787 Some("parked after `implementing`"),
6788 "the card says where it stopped"
6789 );
6790 assert_eq!(parked.last_error, None, "nothing failed");
6791
6792 let mut broken = task();
6796 broken.start("20260903-183634-2d98".to_owned());
6797 settle(
6798 &mut broken,
6799 Verdict {
6800 status: RunStatus::Implementing,
6801 left_pr: false,
6802 quota_hit: false,
6803 parked: false,
6804 no_viable_candidates: false,
6805 },
6806 "returned mid-flight",
6807 2,
6808 );
6809 assert_eq!(broken.attempts, 1);
6810 }
6811
6812 #[test]
6813 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6814 let mut flaky = task();
6819 flaky.start("20260903-123023-e633".to_owned());
6820 settle(
6821 &mut flaky,
6822 Verdict {
6823 status: RunStatus::Stalled,
6824 left_pr: false,
6825 parked: false,
6826 quota_hit: false,
6827 no_viable_candidates: false,
6828 },
6829 "verdict rests on 1 of 3 judges",
6830 2,
6831 );
6832 assert_eq!(
6833 flaky.attempts, 1,
6834 "flakiness spends an attempt, so `max_attempts` still bounds it"
6835 );
6836 assert!(flaky.status.runnable(), "and it is still worth retrying");
6837
6838 let mut limited = task();
6840 limited.start("20260903-123023-e633".to_owned());
6841 settle(
6842 &mut limited,
6843 Verdict {
6844 status: RunStatus::Stalled,
6845 left_pr: false,
6846 parked: false,
6847 quota_hit: true,
6848 no_viable_candidates: false,
6849 },
6850 "judge-2, judge-3 out of quota",
6851 2,
6852 );
6853 assert_eq!(limited.attempts, 0, "a quota window is refunded");
6854 assert!(limited.status.runnable());
6855
6856 let mut worn = task();
6859 for _ in 0..2 {
6860 worn.release();
6861 }
6862 worn.start("20260903-123023-e633".to_owned());
6863 worn.attempts = 2;
6864 settle(
6865 &mut worn,
6866 Verdict {
6867 status: RunStatus::Stalled,
6868 left_pr: false,
6869 parked: false,
6870 quota_hit: false,
6871 no_viable_candidates: false,
6872 },
6873 "no quorum again",
6874 2,
6875 );
6876 assert_eq!(worn.status, TaskStatus::Held);
6877 assert!(!worn.status.runnable());
6878 }
6879
6880 #[test]
6881 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6882 let mut wiped_out = task();
6889 wiped_out.start("20260907-025000-a1b2".to_owned());
6890 settle(
6891 &mut wiped_out,
6892 Verdict {
6893 status: RunStatus::Failed,
6894 left_pr: false,
6895 parked: false,
6896 quota_hit: true,
6897 no_viable_candidates: true,
6898 },
6899 "no candidate produced a change; nothing to judge",
6900 2,
6901 );
6902 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6903 assert!(
6904 wiped_out.status.runnable(),
6905 "a machine problem must leave the task in line"
6906 );
6907
6908 let mut partial_progress = task();
6914 partial_progress.start("20260907-025500-c3d4".to_owned());
6915 settle(
6916 &mut partial_progress,
6917 Verdict {
6918 status: RunStatus::Failed,
6919 left_pr: false,
6920 parked: false,
6921 quota_hit: true,
6922 no_viable_candidates: false,
6923 },
6924 "gate failed on the winning candidate",
6925 2,
6926 );
6927 assert_eq!(
6928 partial_progress.attempts, 1,
6929 "a candidate that actually produced a change spends the attempt \
6930 even though some other seat hit its quota"
6931 );
6932 assert!(partial_progress.status.runnable());
6933 }
6934
6935 #[test]
6936 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6937 let mut t = task();
6943 t.start("20260907-025000-a1b2".to_owned());
6944 let mut state = run_state(RunStatus::Failed);
6945 state.quota.push(QuotaLoss {
6946 seat: "cand-a".to_owned(),
6947 node: "implement".to_owned(),
6948 at: Timestamp::now(),
6949 reset: None,
6950 });
6951 assert!(
6952 state.viable().is_empty(),
6953 "no candidate was added, so nothing is viable"
6954 );
6955 reclaim(&mut t, Some(state), 2, "en");
6956 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6957 assert!(t.status.runnable());
6958 }
6959
6960 #[test]
6961 fn a_held_task_is_never_offered_to_the_loop() {
6962 let dir = tempfile::tempdir().unwrap();
6963 let queue = Queue::at(dir.path().to_path_buf());
6964 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6965 let mut t = task();
6966 t.id = format!("2026090{n}-000000-000{n}");
6967 t.priority = priority;
6968 queue.put(&mut t).unwrap();
6969 }
6970 let mut held = task();
6971 held.id = "20260909-000000-9999".to_owned();
6972 held.priority = 99;
6973 held.hold_machine(None);
6974 queue.put(&mut held).unwrap();
6975
6976 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6977 assert_eq!(order.len(), 3);
6978 assert!(!order.contains(&held.id));
6979 assert_eq!(
6980 order.first().cloned(),
6981 queue.next_runnable().map(|t| t.id),
6982 "the loop's first candidate is exactly what the queue offers"
6983 );
6984 assert_eq!(
6985 order,
6986 vec![
6987 "20260902-000000-0002".to_owned(),
6988 "20260903-000000-0003".to_owned(),
6989 "20260901-000000-0001".to_owned(),
6990 ],
6991 "priority first, then oldest, so nothing starves"
6992 );
6993 }
6994
6995 #[test]
6996 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6997 let dir = tempfile::tempdir().unwrap();
6998 let queue = Queue::at(dir.path().to_path_buf());
6999 let mut old = task();
7000 old.id = "20260101-000000-old0".to_owned();
7001 queue.put(&mut old).unwrap();
7002 let mut fresh = task();
7003 fresh.id = "20260101-000000-new0".to_owned();
7004 queue.put(&mut fresh).unwrap();
7005
7006 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7010 std::thread::sleep(Duration::from_millis(60));
7011 let live = queue.claim(&fresh.id).unwrap();
7012
7013 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7014 assert_eq!(swept, vec![old.id.clone()]);
7015 assert!(
7016 queue.claim(&old.id).is_ok(),
7017 "an unparseable lock older than the threshold is swept"
7018 );
7019 assert!(
7020 queue.claim(&fresh.id).is_err(),
7021 "a live pid protects its lock regardless of age"
7022 );
7023 drop(live);
7024 }
7025
7026 #[test]
7027 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7028 let dir = tempfile::tempdir().unwrap();
7038 let queue = Queue::at(dir.path().to_path_buf());
7039 let mut t = task();
7040 t.id = "20260101-000000-live".to_owned();
7041 queue.put(&mut t).unwrap();
7042
7043 let claim = queue.claim(&t.id).unwrap();
7044 std::thread::sleep(Duration::from_millis(60));
7045
7046 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7047 assert!(
7048 swept.is_empty(),
7049 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
7050 );
7051 assert!(
7052 queue.claim(&t.id).is_err(),
7053 "the lock still protects its task"
7054 );
7055 drop(claim);
7056 }
7057
7058 fn injected_dead_pid() -> u32 {
7061 std::process::id().checked_add(1).unwrap_or(1)
7062 }
7063
7064 #[test]
7065 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
7066 let dir = tempfile::tempdir().unwrap();
7067 let queue = Queue::at(dir.path().to_path_buf());
7068 let mut t = task();
7069 t.id = "20260101-000000-dead".to_owned();
7070 queue.put(&mut t).unwrap();
7071 let dead_pid = injected_dead_pid();
7072
7073 std::fs::write(
7078 dir.path().join(format!("{}.lock", t.id)),
7079 dead_pid.to_string(),
7080 )
7081 .unwrap();
7082
7083 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7084 pid != dead_pid
7085 });
7086 assert_eq!(
7087 swept,
7088 vec![t.id.clone()],
7089 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
7090 );
7091 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
7092 }
7093
7094 #[test]
7095 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
7096 let dir = tempfile::tempdir().unwrap();
7097 let queue = Queue::at(dir.path().to_path_buf());
7098 let mut t = task();
7099 t.id = "20260101-000000-late".to_owned();
7100 queue.put(&mut t).unwrap();
7101 let dead_pid = injected_dead_pid();
7102
7103 assert!(
7106 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
7107 "nothing has claimed the task yet"
7108 );
7109
7110 std::fs::write(
7113 dir.path().join(format!("{}.lock", t.id)),
7114 dead_pid.to_string(),
7115 )
7116 .unwrap();
7117
7118 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7122 pid != dead_pid
7123 });
7124 assert_eq!(swept, vec![t.id.clone()]);
7125 }
7126
7127 #[test]
7128 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
7129 crate::run::pin_test_home();
7134 let dir = tempfile::tempdir().unwrap();
7135 let queue = Queue::at(dir.path().to_path_buf());
7136 let mut t = task();
7137 t.id = "20260101-000000-crsh".to_owned();
7138 t.status = TaskStatus::Running;
7139 t.attempts = 1;
7140 t.runs.push("20260904-000000-4043".to_owned());
7144 queue.put(&mut t).unwrap();
7145 let dead_pid = injected_dead_pid();
7146
7147 std::fs::write(
7150 dir.path().join(format!("{}.lock", t.id)),
7151 dead_pid.to_string(),
7152 )
7153 .unwrap();
7154
7155 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
7161 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7162
7163 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7164 pid != dead_pid
7165 });
7166 assert_eq!(swept, vec![t.id.clone()]);
7167
7168 let reclaimed = reclaim_orphaned_running(&queue, 2);
7169 assert_eq!(reclaimed, vec![t.id.clone()]);
7170 let after = queue.get(&t.id).unwrap();
7171 assert_eq!(
7172 after.status,
7173 TaskStatus::Held,
7174 "no run.json to recover from, so a human is asked"
7175 );
7176 assert_eq!(
7177 after.runs,
7178 vec!["20260904-000000-4043".to_owned()],
7179 "the crashed run's id is kept as evidence, not discarded"
7180 );
7181 }
7182
7183 #[test]
7184 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
7185 let dir = tempfile::tempdir().unwrap();
7186 let queue = Queue::at(dir.path().to_path_buf());
7187 let mut t = task();
7188 t.id = "20260101-000000-unknown".to_owned();
7189 queue.put(&mut t).unwrap();
7190 let dead_pid = injected_dead_pid();
7191 std::fs::write(
7192 dir.path().join(format!("{}.lock", t.id)),
7193 dead_pid.to_string(),
7194 )
7195 .unwrap();
7196
7197 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7198 assert!(swept.is_empty(), "an unknown pid must keep its lock");
7199 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7200 }
7201
7202 fn run_state_in(status: RunStatus, language: &str) -> RunState {
7203 let mut s = run_state(status);
7204 s.config.graph.language = language.to_owned();
7205 s
7206 }
7207
7208 fn unstarted_verdict(status: RunStatus) -> Verdict {
7209 Verdict {
7210 status,
7211 left_pr: false,
7212 quota_hit: false,
7213 parked: false,
7214 no_viable_candidates: false,
7215 }
7216 }
7217
7218 #[test]
7219 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7220 let mut t = task();
7221 t.attempts = 1;
7222 settle_in(
7223 &mut t,
7224 unstarted_verdict(RunStatus::AlreadyInBase),
7225 "already in main",
7226 1,
7227 phrases("en"),
7228 );
7229 assert_eq!(t.status, TaskStatus::Done);
7230 assert_eq!(t.attempts, 0);
7231 }
7232
7233 #[test]
7234 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7235 let reason = |language: &str| {
7236 let mut t = task();
7237 settle_in(
7238 &mut t,
7239 unstarted_verdict(RunStatus::Judging),
7240 "boom",
7241 1,
7242 phrases(language),
7243 );
7244 t.last_error.or(t.hold_reason).unwrap_or_default()
7245 };
7246 assert!(
7247 reason("en").starts_with("the graph stopped at `"),
7248 "{}",
7249 reason("en")
7250 );
7251 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7252 assert!(reason("日本語").contains("boom"));
7253 assert_eq!(reason("fr"), reason("en"));
7254 }
7255
7256 #[test]
7257 fn describe_follows_the_run_language_and_keeps_the_run_id() {
7258 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7259 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7260 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7261 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7262 assert!(ja.contains("[run "), "{ja}");
7263 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7264 assert!(ended.starts_with("run 終了: "), "{ended}");
7265 let mut de = run_state_in(RunStatus::Failed, "de");
7266 let mut en = run_state_in(RunStatus::Failed, "en");
7267 de.id = "same".to_owned();
7268 en.id = "same".to_owned();
7269 assert_eq!(describe(&de), describe(&en));
7270 }
7271
7272 #[test]
7273 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7274 use crate::handover::Refused;
7275 let cases = [
7276 Refused::Foreign {
7277 branch: "b".into(),
7278 path: "/w/x".into(),
7279 why: "made by hand".into(),
7280 },
7281 Refused::Unsafe {
7282 branch: "b".into(),
7283 path: "/w/x".into(),
7284 why: "its worktree has uncommitted changes (a.rs)".into(),
7285 },
7286 Refused::ReleaseFailed {
7287 branch: "b".into(),
7288 path: "/w/x".into(),
7289 run: "ab12".into(),
7290 },
7291 ];
7292 for r in &cases {
7293 let en = (phrases("en").handover_refused)(r);
7294 assert_eq!(en, r.to_string());
7295 let ja = (phrases("ja").handover_refused)(r);
7296 assert!(
7297 !ja.contains("is checked out") && !ja.contains("try again"),
7298 "{ja}"
7299 );
7300 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7301 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7302 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7303 }
7304 }
7305 assert!(phrases("en").handover_hint.contains("release the task"));
7306 assert!(phrases("ja").handover_hint.contains("解放"));
7307 }
7308
7309 #[test]
7310 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7311 let build = |lang: &str| {
7312 let mut s = run_state_in(RunStatus::Blocked, lang);
7313 s.id = "same".to_owned();
7314 s.config.graph.review_rounds = 3;
7315 let mut r = review_round(3);
7316 r.expected = 3;
7317 r.answered = 1;
7318 s.reviews.push(r);
7319 s.event(
7320 "review",
7321 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7322 );
7323 s
7324 };
7325 let en = describe(&build("en"));
7326 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7327 let ja = describe(&build("ja"));
7328 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7329 assert!(!ja.contains("never answered"), "{ja}");
7330 assert!(ja.contains("[run "), "{ja}");
7331
7332 let mut failed = build("ja");
7335 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7336 command: "cargo test".to_owned(),
7337 code: Some(1),
7338 output_tail: String::new(),
7339 duration_ms: 0,
7340 resource_blocked: false,
7341 });
7342 failed.event("review", "stopped; e2e failed: cargo test");
7343 let ja = describe(&failed);
7344 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7345 assert!(!ja.contains("席のレビュアー"), "{ja}");
7346 }
7347
7348 #[test]
7349 fn refusals_and_recovery_prose_follow_the_language() {
7350 let t = held_task_with("r1");
7351 let q = action_question(
7352 "r1",
7353 ask::ChoiceAction::Resume {
7354 run: "r1".to_owned(),
7355 },
7356 );
7357 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7358 ActionDecision::Refuse(s) => s,
7359 other => panic!("{other:?}"),
7360 };
7361 assert!(refuse(phrases("en")).contains("could not be read: gone"));
7362 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7363 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7364
7365 let mut held = task();
7366 reclaim(&mut held, None, 2, "ja");
7367 assert!(held.hold_reason.unwrap().contains("保留にしました"));
7368 let mut held = task();
7369 reclaim(&mut held, None, 2, "xx");
7370 assert!(held.hold_reason.unwrap().contains("held for a human"));
7371 }
7372
7373 fn run_state(status: RunStatus) -> RunState {
7374 let mut state = RunState::new(
7375 PathBuf::from("/repo"),
7376 "main".to_owned(),
7377 "abc1234def".to_owned(),
7378 "add retries".to_owned(),
7379 Config::default(),
7380 );
7381 state.status = status;
7382 state
7383 }
7384
7385 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7386 Candidate {
7387 index: 0,
7388 label,
7389 agent: "claude".to_owned(),
7390 branch: format!("magi/x/{label}"),
7391 worktree: PathBuf::from("/repo"),
7392 summary: summary.to_owned(),
7393 stat: String::new(),
7394 files: 0,
7395 commits: usize::from(!empty),
7396 empty,
7397 failed: failed.map(str::to_owned),
7398 verified_noop: None,
7399 duration_ms: 0,
7400 folded: false,
7401 }
7402 }
7403
7404 #[test]
7405 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7406 let mut state = run_state(RunStatus::Blocked);
7407 state.gate = vec![
7408 CommandOutcome {
7409 command: "cargo make check".to_owned(),
7410 code: Some(0),
7411 output_tail: "ok".to_owned(),
7412 duration_ms: 0,
7413 resource_blocked: false,
7414 },
7415 CommandOutcome {
7416 command: "cargo test".to_owned(),
7417 code: Some(101),
7418 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7419 duration_ms: 0,
7420 resource_blocked: false,
7421 },
7422 ];
7423 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7424 assert!(d.contains("cargo test"), "{d}");
7425 assert!(
7426 !d.contains("cargo make check"),
7427 "a passing check is not a diagnostic: {d}"
7428 );
7429 assert!(d.contains("assertion failed"), "{d}");
7430 }
7431
7432 #[test]
7433 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7434 let mut state = run_state(RunStatus::Blocked);
7435 state.event(
7436 "land",
7437 "stopped: the fixer produced no commit while 2 check(s) were failing \
7438 (build, lint); stopping instead of looping on an unchanged tree",
7439 );
7440 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7441 assert!(d.contains("build"), "{d}");
7442 assert!(d.contains("lint"), "{d}");
7443 assert!(d.contains("fixer produced no commit"), "{d}");
7444 }
7445
7446 #[test]
7447 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7448 let state = run_state(RunStatus::VerifiedNoop);
7453 let d = describe(&state);
7454 assert!(
7455 d.contains("agent-verified no-op"),
7456 "expected the display label, not the wire spelling: {d}"
7457 );
7458 assert!(!d.contains("verified_noop"), "{d}");
7459 }
7460
7461 #[test]
7462 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7463 let mut state = run_state(RunStatus::Failed);
7469 state.candidates = vec![candidate(
7470 'A',
7471 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7472 true,
7473 None,
7474 )];
7475 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7476 assert!(d.contains("candidate A"), "{d}");
7477 assert!(d.contains("tagged v1.2.3"), "{d}");
7478 }
7479
7480 #[test]
7481 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7482 let mut state = run_state(RunStatus::Failed);
7483 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7484 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7485 assert!(d.contains("candidate A"), "{d}");
7486 assert!(d.contains("agent timed out"), "{d}");
7487 }
7488
7489 #[test]
7490 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7491 let mut state = run_state(RunStatus::Failed);
7494 state.candidates = vec![candidate('A', "did the work", false, None)];
7495 assert!(diagnostic(&state).is_none());
7496 }
7497
7498 #[test]
7499 fn diagnostic_is_bounded_however_much_a_run_printed() {
7500 let mut state = run_state(RunStatus::Blocked);
7501 state.gate = vec![
7502 CommandOutcome {
7503 command: "cargo test".to_owned(),
7504 code: Some(101),
7505 output_tail: "x".repeat(50_000),
7506 duration_ms: 0,
7507 resource_blocked: false,
7508 },
7509 CommandOutcome {
7510 command: "cargo clippy".to_owned(),
7511 code: Some(1),
7512 output_tail: "y".repeat(50_000),
7513 duration_ms: 0,
7514 resource_blocked: false,
7515 },
7516 ];
7517 state.candidates = vec![
7518 candidate('A', &"z".repeat(50_000), true, None),
7519 candidate('B', &"w".repeat(50_000), true, None),
7520 ];
7521 let d = diagnostic(&state).expect("plenty here to diagnose");
7522 assert!(
7523 d.len() <= DIAGNOSTIC_MAX,
7524 "diagnostic grew to {} bytes, unbounded",
7525 d.len()
7526 );
7527 }
7528
7529 #[test]
7530 fn selected_delivery_guards_survive_recovery_failure_accounting() {
7531 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
7532 let mut t = task();
7533 let mut state = run_state(status);
7534 t.pr_recovery = Some(crate::pr_recovery::Selection {
7535 url: "url".into(),
7536 branch: format!("magi/task-{}", t.id),
7537 head: "a".repeat(40),
7538 source_head: None,
7539 source_run: None,
7540 source_proof: None,
7541 disposition: Some(crate::pr_recovery::Disposition::Land),
7542 instruction: t.instruction.clone(),
7543 approved_at: Timestamp::now(),
7544 });
7545 state.pr_recovery = t.pr_recovery.clone();
7546 t.start(state.id.clone());
7547 settle_and_diagnose(
7548 &mut t,
7549 Verdict {
7550 status,
7551 left_pr: false,
7552 quota_hit: false,
7553 parked: false,
7554 no_viable_candidates: false,
7555 },
7556 "delivery stopped",
7557 5,
7558 &state,
7559 );
7560 assert_eq!(t.status, TaskStatus::Held);
7561 let reason = t.hold_reason.as_deref().unwrap();
7562 if status == RunStatus::Ready {
7563 assert!(reason.contains("Selected PR delivery is incomplete"));
7564 assert!(t.recovery_budget.is_none());
7565 } else {
7566 assert!(reason.contains("Selected recovery stopped"));
7567 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
7568 }
7569 assert!(t.pr_recovery.is_some());
7570 }
7571 }
7572
7573 #[test]
7574 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7575 let mut state = run_state(RunStatus::Blocked);
7576 state.gate = vec![CommandOutcome {
7577 command: "cargo test".to_owned(),
7578 code: Some(101),
7579 output_tail: "assertion failed".to_owned(),
7580 duration_ms: 0,
7581 resource_blocked: false,
7582 }];
7583 let verdict = Verdict {
7584 status: RunStatus::Blocked,
7585 left_pr: false,
7586 quota_hit: false,
7587 parked: false,
7588 no_viable_candidates: false,
7589 };
7590
7591 let mut t = task();
7594 t.start("run-1".to_owned());
7595 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7596 assert_eq!(t.status, TaskStatus::Failed);
7597 assert!(t.diagnostic.is_none());
7598
7599 t.start("run-2".to_owned());
7602 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7603 assert_eq!(t.status, TaskStatus::Held);
7604 let d = t.diagnostic.expect("a held task must carry its diagnostic");
7605 assert!(d.contains("cargo test"), "{d}");
7606 }
7607
7608 #[test]
7609 fn a_held_task_names_the_open_question_it_is_waiting_on() {
7610 crate::run::pin_test_home();
7615 let home = crate::run::home();
7616 let state = run_state(RunStatus::VerifiedNoop);
7617 let mut q = ask::Question::new(
7618 state.id.clone(),
7619 "implement".to_owned(),
7620 "impl-A".to_owned(),
7621 "is this really a no-op?".to_owned(),
7622 String::new(),
7623 Vec::new(),
7624 );
7625 Questions::at(home.join("questions")).put(&mut q).unwrap();
7626
7627 let verdict = Verdict {
7628 status: RunStatus::VerifiedNoop,
7629 left_pr: false,
7630 quota_hit: false,
7631 parked: false,
7632 no_viable_candidates: false,
7633 };
7634 let mut t = task();
7635 t.start(state.id.clone());
7636 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7637
7638 assert_eq!(t.status, TaskStatus::Held);
7639 let reason = t.hold_reason.expect("a held task must record why");
7640 assert!(
7641 reason.starts_with("run ended agent-verified no-op"),
7642 "the original settle reason must survive unchanged: {reason}"
7643 );
7644 assert!(
7645 reason.contains(q.short()),
7646 "the open question's id must be named so the notice is actionable: {reason}"
7647 );
7648 }
7649
7650 #[test]
7651 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7652 crate::run::pin_test_home();
7653 let state = run_state(RunStatus::VerifiedNoop);
7654
7655 let verdict = Verdict {
7656 status: RunStatus::VerifiedNoop,
7657 left_pr: false,
7658 quota_hit: false,
7659 parked: false,
7660 no_viable_candidates: false,
7661 };
7662 let mut t = task();
7663 t.start(state.id.clone());
7664 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7665
7666 assert_eq!(t.status, TaskStatus::Held);
7667 assert_eq!(
7668 t.hold_reason.as_deref(),
7669 Some("run ended agent-verified no-op"),
7670 "nothing to append when the question was already answered or never asked"
7671 );
7672 }
7673
7674 #[test]
7675 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7676 crate::run::pin_test_home();
7677 let mut first = run_state(RunStatus::Blocked);
7678 first.id = "20260101-000000-sup1".to_owned();
7679 first.save().unwrap();
7680 let mut second = run_state(RunStatus::Merged);
7681 second.id = "20260101-000000-sup2".to_owned();
7682 second.save().unwrap();
7683
7684 let mut t = task();
7685 t.runs = vec![first.id.clone(), second.id.clone()];
7686 t.status = TaskStatus::Done;
7687
7688 supersede_prior_runs(&t, &crate::run::home());
7689
7690 assert_eq!(
7691 RunState::load(&first.id).unwrap().status,
7692 RunStatus::Superseded,
7693 "the first attempt's Blocked no longer needs anyone's attention"
7694 );
7695 assert_eq!(
7696 RunState::load(&second.id).unwrap().status,
7697 RunStatus::Merged,
7698 "the run that actually succeeded is left exactly as it was"
7699 );
7700 }
7701
7702 #[test]
7703 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7704 crate::run::pin_test_home();
7710 let mut first = run_state(RunStatus::Blocked);
7711 first.id = "20260101-000000-sup9".to_owned();
7712 first.driver_pid = Some(std::process::id());
7715 first.driver_started_at = Some(
7716 crate::proc::process_started_at(std::process::id())
7717 .expect("this test process's own start time must be queryable"),
7718 );
7719 first.save().unwrap();
7720 let mut second = run_state(RunStatus::Merged);
7721 second.id = "20260101-000000-supa".to_owned();
7722 second.save().unwrap();
7723
7724 let mut t = task();
7725 t.runs = vec![first.id.clone(), second.id.clone()];
7726 t.status = TaskStatus::Done;
7727
7728 supersede_prior_runs(&t, &crate::run::home());
7729
7730 assert_eq!(
7731 RunState::load(&first.id).unwrap().status,
7732 RunStatus::Blocked,
7733 "a live driver_pid means something is still actually working this run, \
7734 even though no daemon claims it - rewriting under it would just be \
7735 undone the next time that process saves"
7736 );
7737 }
7738
7739 #[test]
7740 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7741 let dir = tempfile::tempdir().unwrap();
7747 let home = dir.path().to_path_buf();
7748 let queue = Queue::at(dir.path().join("queue"));
7749
7750 let mut first = run_state(RunStatus::Blocked);
7751 first.id = "20260101-000000-supd".to_owned();
7752 first.driver_pid = Some(std::process::id());
7753 first.driver_started_at = Some(
7754 crate::proc::process_started_at(std::process::id())
7755 .expect("this test process's own start time must be queryable"),
7756 );
7757 first.save_under(&home).unwrap();
7758 let mut second = run_state(RunStatus::Merged);
7759 second.id = "20260101-000000-supe".to_owned();
7760 second.save_under(&home).unwrap();
7761
7762 let mut t = task();
7763 t.runs = vec![first.id.clone(), second.id.clone()];
7764 t.status = TaskStatus::Done;
7765 queue.put(&mut t).unwrap();
7766
7767 resweep_superseded_attempts(&queue, &home);
7768 assert_eq!(
7769 RunState::load_under(&first.id, &home).unwrap().status,
7770 RunStatus::Blocked,
7771 "still live on the first pass, so still untouched"
7772 );
7773
7774 let mut stale = RunState::load_under(&first.id, &home).unwrap();
7780 stale.driver_started_at = Some("1".to_owned());
7781 stale.save_under(&home).unwrap();
7782
7783 resweep_superseded_attempts(&queue, &home);
7784 assert_eq!(
7785 RunState::load_under(&first.id, &home).unwrap().status,
7786 RunStatus::Superseded,
7787 "the second pass catches up what the first one correctly skipped"
7788 );
7789 }
7790
7791 #[test]
7792 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7793 crate::run::pin_test_home();
7794 let mut first = run_state(RunStatus::Blocked);
7795 first.id = "20260101-000000-sup3".to_owned();
7796 first.save().unwrap();
7797 let mut second = run_state(RunStatus::Blocked);
7798 second.id = "20260101-000000-sup4".to_owned();
7799 second.save().unwrap();
7800
7801 let mut t = task();
7802 t.runs = vec![first.id.clone(), second.id.clone()];
7803 t.status = TaskStatus::Failed;
7807
7808 supersede_prior_runs(&t, &crate::run::home());
7809
7810 assert_eq!(
7811 RunState::load(&first.id).unwrap().status,
7812 RunStatus::Blocked
7813 );
7814 assert_eq!(
7815 RunState::load(&second.id).unwrap().status,
7816 RunStatus::Blocked
7817 );
7818 }
7819
7820 #[test]
7821 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7822 crate::run::pin_test_home();
7826 let mut first = run_state(RunStatus::Blocked);
7827 first.id = "20260101-000000-sup5".to_owned();
7828 first.save().unwrap();
7829
7830 let mut t = task();
7831 t.runs = vec![first.id.clone()];
7832 t.status = TaskStatus::Done;
7833
7834 supersede_prior_runs(&t, &crate::run::home());
7835
7836 assert_eq!(
7837 RunState::load(&first.id).unwrap().status,
7838 RunStatus::Blocked,
7839 "a single-attempt task has no earlier run to supersede"
7840 );
7841 }
7842
7843 #[test]
7844 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7845 crate::run::pin_test_home();
7852 let mut first = run_state(RunStatus::Blocked);
7853 first.id = "20260101-000000-supb".to_owned();
7854 first.save().unwrap();
7855 let mut second = run_state(RunStatus::Failed);
7856 second.id = "20260101-000000-supc".to_owned();
7857 second.save().unwrap();
7858
7859 let mut t = task();
7860 t.runs = vec![first.id.clone(), second.id.clone()];
7861 t.status = TaskStatus::Done;
7862
7863 supersede_prior_runs(&t, &crate::run::home());
7864
7865 assert_eq!(
7866 RunState::load(&first.id).unwrap().status,
7867 RunStatus::Blocked,
7868 "the task's last attempt never landed, so there is nothing here \
7869 actually superseding it"
7870 );
7871 }
7872
7873 #[test]
7874 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7875 crate::run::pin_test_home();
7879 let mut failed = run_state(RunStatus::Failed);
7880 failed.id = "20260101-000000-sup6".to_owned();
7881 failed.save().unwrap();
7882 let mut noop = run_state(RunStatus::VerifiedNoop);
7883 noop.id = "20260101-000000-sup7".to_owned();
7884 noop.save().unwrap();
7885 let mut winner = run_state(RunStatus::Ready);
7886 winner.id = "20260101-000000-sup8".to_owned();
7887 winner.save().unwrap();
7888
7889 let mut t = task();
7890 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7891 t.status = TaskStatus::Done;
7892
7893 supersede_prior_runs(&t, &crate::run::home());
7894
7895 assert_eq!(
7896 RunState::load(&failed.id).unwrap().status,
7897 RunStatus::Failed
7898 );
7899 assert_eq!(
7900 RunState::load(&noop.id).unwrap().status,
7901 RunStatus::VerifiedNoop
7902 );
7903 }
7904
7905 fn approval_question(run: &str) -> ask::Question {
7906 ask::Question::new(
7907 run.to_owned(),
7908 land::APPROVAL_NODE.to_owned(),
7909 "land".to_owned(),
7910 "merge?".to_owned(),
7911 String::new(),
7912 vec!["merge".to_owned(), "hold".to_owned()],
7913 )
7914 }
7915
7916 #[test]
7917 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7918 crate::run::pin_test_home();
7919 let mut state = run_state(RunStatus::Landing);
7920 state.id = "20260101-000000-fre1".to_owned();
7921 state.parked = true;
7922 state.save().unwrap();
7923 ask::Questions::open()
7924 .put(&mut approval_question(&state.id))
7925 .unwrap();
7926
7927 let mut t = task();
7928 t.runs.push(state.id.clone());
7929 assert_eq!(
7930 land_resume_state(&t),
7931 LandResume::StillWaiting,
7932 "nobody has answered and the timeout has not passed"
7933 );
7934 }
7935
7936 #[test]
7937 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7938 crate::run::pin_test_home();
7939 let mut state = run_state(RunStatus::Gating);
7940 state.id = "20260101-000000-gt01".to_owned();
7941 state.parked = true;
7942 state.config.graph.answer_timeout = 60;
7943 state.github_text = Some(crate::run::GithubTextAsk {
7944 rewrite: None,
7945 fingerprint: "f".into(),
7946 title: true,
7947 body: false,
7948 categories: vec!["title-language".into()],
7949 question: None,
7950 asks: 1,
7951 resolved: false,
7952 chosen_title: None,
7953 choice: None,
7954 });
7955 state.save().unwrap();
7956 let store = ask::Questions::open();
7957 let mut q = ask::Question::new(
7958 state.id.clone(),
7959 crate::github_text::ASK_NODE.to_owned(),
7960 crate::github_text::ASK_SEAT.to_owned(),
7961 "s".into(),
7962 String::new(),
7963 vec!["use fallback".into()],
7964 );
7965 store.put(&mut q).unwrap();
7966 let mut t = task();
7967 t.runs.push(state.id.clone());
7968 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7969 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7970 store.put(&mut q).unwrap();
7971 assert_eq!(land_resume_state(&t), LandResume::Ready);
7972 assert!(!store.get(&q.id).unwrap().status.open());
7973 state.github_text.as_mut().unwrap().resolved = true;
7975 state.save().unwrap();
7976 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7977 }
7978
7979 #[test]
7980 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7981 crate::run::pin_test_home();
7986 let mut state = run_state(RunStatus::Landing);
7987 state.id = "20260101-000000-exp1".to_owned();
7988 state.parked = true;
7989 state.config.graph.answer_timeout = 60;
7990 state.save().unwrap();
7991
7992 let store = ask::Questions::open();
7993 let mut q = approval_question(&state.id);
7994 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7995 store.put(&mut q).unwrap();
7996
7997 let mut t = task();
7998 t.runs.push(state.id.clone());
7999 assert_eq!(
8000 land_resume_state(&t),
8001 LandResume::Ready,
8002 "an expired question must not be waited on forever"
8003 );
8004
8005 let after = store.get(&q.id).unwrap();
8006 assert!(
8007 !after.status.open(),
8008 "the question is abandoned, not silently ignored"
8009 );
8010 assert!(
8011 after.resolution().is_none(),
8012 "an abandoned question is not read as a decision"
8013 );
8014 }
8015
8016 #[test]
8017 fn reclaim_settles_a_running_task_against_its_last_run() {
8018 let mut t = task();
8019 t.start("20260904-000000-4043".to_owned());
8020 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8021 assert_eq!(
8022 t.status,
8023 TaskStatus::Done,
8024 "a run that actually finished must not stay `running` forever"
8025 );
8026 }
8027
8028 #[test]
8029 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8030 let mut t = task();
8031 t.start("20260904-000000-4043".to_owned());
8032 t.last_error = Some("earlier trouble".to_owned());
8033 let mut state = run_state(RunStatus::Judging);
8034 state.parked = true;
8035 reclaim(&mut t, Some(state), 1, "en");
8036 assert_eq!(t.status, TaskStatus::Parked);
8037 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8038 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8039 assert!(t.park_reason.is_some());
8040 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8041 assert!(!t.fresh_start);
8042 assert!(t.status.runnable());
8043 }
8044
8045 #[test]
8046 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
8047 let mut t = task();
8048 t.start("20260904-000000-4043".to_owned());
8049 t.last_error = Some("earlier trouble".to_owned());
8050 settle(
8051 &mut t,
8052 Verdict {
8053 status: RunStatus::Judging,
8054 left_pr: false,
8055 quota_hit: false,
8056 parked: true,
8057 no_viable_candidates: false,
8058 },
8059 "parked after `judging`",
8060 1,
8061 );
8062 assert_eq!(t.status, TaskStatus::Parked);
8063 assert_eq!(t.attempts, 0);
8064 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8065 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
8066 assert_eq!(t.schema, crate::queue::SCHEMA);
8067 assert!(
8068 crate::notices::task_held(&t).is_none(),
8069 "a park is not news"
8070 );
8071 t.start("20260904-000000-4043".to_owned());
8072 assert_eq!(t.park_reason, None);
8073 }
8074
8075 #[test]
8076 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
8077 let mut t = task();
8081 t.start("20260904-000000-4043".to_owned());
8082 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
8083 assert_eq!(t.status, TaskStatus::Failed);
8084 assert!(t.status.runnable());
8085 }
8086
8087 #[test]
8088 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
8089 let mut t = task();
8090 t.start("20260904-000000-4043".to_owned());
8091 assert_eq!(t.attempts, 1);
8092 let mut run = run_state(RunStatus::Implementing);
8093 run.id = "20260904-000000-4043".to_owned();
8094 run.begin_pass();
8095 let cause = crate::run::ParkCause::Upgrade {
8096 from: "0.121.0".to_owned(),
8097 to: Some("0.121.1".to_owned()),
8098 };
8099 run.end_pass_parked(cause.clone());
8100 run.parked = true;
8101 let verdict = Verdict {
8102 status: run.status,
8103 left_pr: false,
8104 quota_hit: false,
8105 parked: true,
8106 no_viable_candidates: false,
8107 };
8108 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
8109 assert_eq!(t.attempts, 0);
8110 assert_eq!(t.passes.len(), 1);
8111 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8112 assert_eq!(t.passes[0].parked, Some(cause));
8113 assert_eq!(t.passes[0].pass_index, 0);
8114
8115 t.start("20260904-000000-4043".to_owned());
8118 run.begin_pass();
8119 run.status = RunStatus::Failed;
8120 let verdict = Verdict {
8121 status: RunStatus::Failed,
8122 left_pr: false,
8123 quota_hit: false,
8124 parked: false,
8125 no_viable_candidates: false,
8126 };
8127 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
8128 assert_eq!(t.passes.len(), 2);
8129 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8130 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
8131 assert_eq!(t.passes[1].pass_index, 1);
8132 assert_eq!(t.attempts, 1);
8133 }
8134
8135 #[test]
8136 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
8137 let mut t = task();
8138 t.start("20260904-000000-4043".to_owned());
8139 reclaim(&mut t, None, 2, "en");
8140 assert_eq!(t.status, TaskStatus::Held);
8141 assert!(
8142 t.last_error
8143 .as_deref()
8144 .is_some_and(|e| e.contains("running")),
8145 "the operator needs to know why this task was held"
8146 );
8147 }
8148
8149 #[test]
8150 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
8151 let dir = tempfile::tempdir().unwrap();
8152 let queue = Queue::at(dir.path().to_path_buf());
8153
8154 let mut orphaned = task();
8156 orphaned.id = "20260904-000000-orph".to_owned();
8157 orphaned.status = TaskStatus::Running;
8158 orphaned.attempts = 1;
8159 queue.put(&mut orphaned).unwrap();
8160
8161 let mut alive = task();
8162 alive.id = "20260904-000000-live".to_owned();
8163 alive.status = TaskStatus::Running;
8164 alive.attempts = 1;
8165 queue.put(&mut alive).unwrap();
8166 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
8167
8168 let mut queued = task();
8169 queued.id = "20260904-000000-wait".to_owned();
8170 queue.put(&mut queued).unwrap();
8171
8172 let reclaimed = reclaim_orphaned_running(&queue, 2);
8173 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
8174
8175 assert_eq!(
8176 queue.get(&orphaned.id).unwrap().status,
8177 TaskStatus::Held,
8178 "nothing was driving it and there was no run to recover"
8179 );
8180 assert_eq!(
8181 queue.get(&alive.id).unwrap().status,
8182 TaskStatus::Running,
8183 "a live claim must protect the task it belongs to"
8184 );
8185 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
8186 }
8187
8188 fn read_run_under(home: &Path, id: &str) -> RunState {
8194 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
8195 serde_json::from_str(&body).unwrap()
8196 }
8197
8198 #[test]
8199 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
8200 let dir = tempfile::tempdir().unwrap();
8201 let home = dir.path().to_path_buf();
8202 let now = Timestamp::now();
8203 let overrun_seat = || crate::run::ActiveSeat {
8204 node: "implement".to_owned(),
8205 started_at: now - jiff::SignedDuration::new(21_000, 0),
8206 timeout_secs: 3_600,
8207 attempt: 0,
8208 task: None,
8209 command: None,
8210 index: None,
8211 total: None,
8212 };
8213
8214 let mut dead = run_state(RunStatus::Implementing);
8215 dead.id = "20260101-000000-dead".to_owned();
8216 dead.active.insert("impl-A".to_owned(), overrun_seat());
8217 dead.driver_pid = Some(4242);
8220 dead.save_under(&home).unwrap();
8221
8222 let mut alive = run_state(RunStatus::Implementing);
8225 alive.id = "20260101-000000-aliv".to_owned();
8226 alive.active.insert("impl-A".to_owned(), overrun_seat());
8227 alive.save_under(&home).unwrap();
8228 let mut status = Status::new();
8229 status.current = vec![Current {
8230 task: "20260101-000000-task".to_owned(),
8231 run: alive.id.clone(),
8232 }];
8233 write_status_to(&home.join("daemon.json"), &status).unwrap();
8234
8235 let questions = Questions::at(home.join("questions"));
8239 let mut q = ask::Question::new(
8240 dead.id.clone(),
8241 "implement".to_owned(),
8242 "impl-A".to_owned(),
8243 "Which storage backend?".to_owned(),
8244 String::new(),
8245 vec!["SQLite".to_owned(), "Redis".to_owned()],
8246 );
8247 questions.put(&mut q).unwrap();
8248
8249 let abandoned = reclaim_abandoned_runs_with(
8250 &home,
8251 now,
8252 |pid| if pid == 4242 { Some(false) } else { None },
8253 |_| panic!("a query answering Dead outright needs no identity corroboration"),
8254 );
8255 assert_eq!(abandoned, vec![dead.id.clone()]);
8256
8257 let reloaded = read_run_under(&home, &dead.id);
8258 assert_eq!(reloaded.status, RunStatus::Failed);
8259 assert!(reloaded.active.is_empty());
8260 assert!(
8261 !questions.get(&q.id).unwrap().status.open(),
8262 "the failed run's own open question must be settled in the same pass"
8263 );
8264
8265 let still_alive = read_run_under(&home, &alive.id);
8266 assert_eq!(
8267 still_alive.status,
8268 RunStatus::Implementing,
8269 "a live daemon's claim protects it"
8270 );
8271 assert!(!still_alive.active.is_empty());
8272 }
8273
8274 #[test]
8284 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8285 let dir = tempfile::tempdir().unwrap();
8286 let home = dir.path().to_path_buf();
8287 let now = Timestamp::now();
8288
8289 let mut manual = run_state(RunStatus::Reviewing);
8290 manual.id = "20260101-000000-manl".to_owned();
8291 manual.active.insert(
8292 "review-1".to_owned(),
8293 crate::run::ActiveSeat {
8294 node: "review".to_owned(),
8295 started_at: now - jiff::SignedDuration::new(21_000, 0),
8296 timeout_secs: 3_600,
8297 attempt: 0,
8298 task: None,
8299 command: None,
8300 index: None,
8301 total: None,
8302 },
8303 );
8304 manual.driver_pid = Some(4242);
8308 manual.driver_started_at = Some("1790000000".to_owned());
8309 manual.save_under(&home).unwrap();
8310
8311 let abandoned = reclaim_abandoned_runs_with(
8312 &home,
8313 now,
8314 |pid| if pid == 4242 { Some(true) } else { None },
8315 |pid| {
8316 if pid == 4242 {
8317 Some("1790000000".to_owned())
8318 } else {
8319 None
8320 }
8321 },
8322 );
8323 assert!(
8324 abandoned.is_empty(),
8325 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8326 );
8327
8328 let reloaded = read_run_under(&home, &manual.id);
8329 assert_eq!(reloaded.status, RunStatus::Reviewing);
8330 assert!(!reloaded.active.is_empty());
8331 }
8332
8333 #[test]
8334 fn an_already_claimed_task_is_skipped_rather_than_failed() {
8335 let dir = tempfile::tempdir().unwrap();
8336 let queue = Queue::at(dir.path().to_path_buf());
8337 let mut only = task();
8338 queue.put(&mut only).unwrap();
8339
8340 let _elsewhere = queue.claim(&only.id).unwrap();
8341 let candidates = runnable(&queue);
8342 assert_eq!(candidates.len(), 1, "the task is still runnable");
8343 assert!(
8344 queue.claim(&candidates[0].id).is_err(),
8345 "the loop cannot take a claim somebody else holds"
8346 );
8347
8348 let after = queue.get(&only.id).unwrap();
8349 assert_eq!(after.status, TaskStatus::Queued);
8350 assert_eq!(
8351 after.attempts, 0,
8352 "losing the race is not an attempt at the task"
8353 );
8354 assert_eq!(after.last_error, None);
8355 }
8356
8357 #[test]
8358 fn the_status_file_round_trips_and_its_heartbeat_advances() {
8359 let dir = tempfile::tempdir().unwrap();
8360 let path = dir.path().join("daemon.json");
8361
8362 let mut status = Status::new();
8363 status.idle = false;
8364 status.completed = 7;
8365 status.current = vec![Current {
8366 task: "20260902-000000-t111".to_owned(),
8367 run: "20260902-000001-r111".to_owned(),
8368 }];
8369 write_status_to(&path, &status).unwrap();
8370 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8371 assert_eq!(first.schema, SCHEMA);
8372 assert_eq!(first.pid, std::process::id());
8373 assert!(!first.idle);
8374 assert_eq!(first.completed, 7);
8375 assert_eq!(first.current, status.current);
8376 assert!(
8377 !path.with_extension("json.tmp").exists(),
8378 "the temp file is renamed, not left behind"
8379 );
8380
8381 std::thread::sleep(Duration::from_millis(5));
8382 status.updated_at = Timestamp::now();
8383 status.polls = 3;
8384 write_status_to(&path, &status).unwrap();
8385 let second: Status =
8386 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8387 assert!(
8388 second.updated_at > first.updated_at,
8389 "a reader can only detect staleness if the heartbeat moves"
8390 );
8391 assert_eq!(
8392 second.started_at, first.started_at,
8393 "the start time is not a heartbeat"
8394 );
8395 assert_eq!(second.polls, 3);
8396 }
8397
8398 #[test]
8399 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8400 let dir = tempfile::tempdir().unwrap();
8401
8402 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8403
8404 let mut status = Status::new();
8405 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8406 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8407 let stale = read_status(dir.path()).unwrap();
8408 assert!(
8409 !stale.running(Timestamp::now()),
8410 "a minute without a heartbeat is a dead daemon, not a busy one"
8411 );
8412 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8413
8414 status.updated_at = Timestamp::now();
8415 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8416 let fresh = read_status(dir.path()).unwrap();
8417 assert!(fresh.running(Timestamp::now()));
8418 }
8419
8420 #[test]
8421 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8422 let dir = tempfile::tempdir().unwrap();
8423 let now = Timestamp::now();
8424 let mine = "20260903-080619-01c2";
8425
8426 assert!(
8427 !is_working_on(dir.path(), mine, now),
8428 "no status file means nobody is working on anything"
8429 );
8430
8431 let mut status = Status::new();
8432 status.current = vec![Current {
8433 task: "20260903-080340-0167".to_owned(),
8434 run: mine.to_owned(),
8435 }];
8436 status.updated_at = now;
8437 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8438 assert!(is_working_on(dir.path(), mine, now));
8439 assert!(
8440 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8441 "a daemon busy with one run is not working on another"
8442 );
8443
8444 status.updated_at = now - jiff::SignedDuration::from_secs(600);
8447 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8448 assert!(
8449 !is_working_on(dir.path(), mine, now),
8450 "a stale heartbeat is a dead daemon, so its run is a leftover"
8451 );
8452 }
8453
8454 #[test]
8455 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8456 let dir = tempfile::tempdir().unwrap();
8457 let now = Timestamp::now();
8458
8459 assert!(
8460 !is_working_on_short(dir.path(), "01c2", now),
8461 "no status file means nobody is working on anything"
8462 );
8463
8464 let mut status = Status::new();
8465 status.current = vec![Current {
8466 task: "20260903-080340-0167".to_owned(),
8467 run: "20260903-080619-01c2".to_owned(),
8468 }];
8469 status.updated_at = now;
8470 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8471 assert!(
8472 is_working_on_short(dir.path(), "01c2", now),
8473 "the run's short id is the last block of its full id"
8474 );
8475 assert!(
8476 !is_working_on_short(dir.path(), "3cbf", now),
8477 "a daemon busy with one worktree bay is not working on another"
8478 );
8479 }
8480
8481 #[test]
8482 fn a_newer_status_file_still_yields_a_reading() {
8483 let dir = tempfile::tempdir().unwrap();
8484 std::fs::write(
8487 dir.path().join("daemon.json"),
8488 serde_json::json!({
8489 "schema": 2,
8490 "updated_at": Timestamp::now().to_string(),
8491 "idle": true,
8492 "surprise": { "nested": [1, 2, 3] },
8493 })
8494 .to_string(),
8495 )
8496 .unwrap();
8497
8498 let reading = read_status(dir.path()).expect("a forward-compatible read");
8499 assert!(reading.running(Timestamp::now()));
8500 assert!(reading.idle);
8501 assert!(reading.current.is_empty());
8502 }
8503
8504 #[test]
8505 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8506 let dir = tempfile::tempdir().unwrap();
8512 std::fs::write(
8513 dir.path().join("daemon.json"),
8514 serde_json::json!({
8515 "schema": 1,
8516 "pid": 4242,
8517 "updated_at": Timestamp::now().to_string(),
8518 "idle": false,
8519 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8520 "completed": 3,
8521 "polls": 9,
8522 })
8523 .to_string(),
8524 )
8525 .unwrap();
8526
8527 let reading = read_status(dir.path()).expect("an older shape must still parse");
8528 assert!(reading.running(Timestamp::now()));
8529 assert_eq!(
8530 reading.current,
8531 vec![Current {
8532 task: "20260902-140501-aaaa".to_owned(),
8533 run: "20260902-140502-bbbb".to_owned(),
8534 }]
8535 );
8536 }
8537
8538 #[test]
8539 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8540 let dir = tempfile::tempdir().unwrap();
8541 std::fs::write(
8542 dir.path().join("daemon.json"),
8543 serde_json::json!({
8544 "schema": 1,
8545 "updated_at": Timestamp::now().to_string(),
8546 "idle": true,
8547 "current": null,
8548 })
8549 .to_string(),
8550 )
8551 .unwrap();
8552 let with_null = read_status(dir.path()).expect("null must still parse");
8553 assert!(with_null.current.is_empty());
8554
8555 std::fs::write(
8556 dir.path().join("daemon.json"),
8557 serde_json::json!({
8558 "schema": 1,
8559 "updated_at": Timestamp::now().to_string(),
8560 "idle": true,
8561 })
8562 .to_string(),
8563 )
8564 .unwrap();
8565 let absent = read_status(dir.path()).expect("a missing field must still parse");
8566 assert!(absent.current.is_empty());
8567 }
8568
8569 #[test]
8570 fn a_task_without_a_repository_runs_in_the_daemons_default() {
8571 let fallback = Path::new("/default");
8572 let mut blank = task();
8573 blank.repo = PathBuf::new();
8574 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8575 let mut dot = task();
8576 dot.repo = PathBuf::from(".");
8577 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8578 assert_eq!(
8579 repo_for(&task(), fallback),
8580 PathBuf::from("/repo"),
8581 "a task that names a repository keeps it"
8582 );
8583 }
8584
8585 #[test]
8586 fn task_implementers_edit_inherits_daemon_config_and_merge() {
8587 let dir = tempfile::tempdir().unwrap();
8588 let path = dir.path().join("explicit.toml");
8589 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8590 let opts = Opts {
8591 config: Some(path),
8592 merge: Some("none".into()),
8593 ..Default::default()
8594 };
8595 let mut t = task();
8596 t.set_implementers(
8597 2,
8598 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8599 .unwrap(),
8600 )
8601 .unwrap();
8602 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8603 assert_eq!(cfg.graph.implementers, 2);
8604 assert_eq!(cfg.graph.judges, 1);
8605 assert_eq!(cfg.merge.mode, MergeMode::None);
8606 t.set_implementers(1, &cfg).unwrap();
8607 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8608 apply_task_implementers(&mut cfg, &t);
8609 assert_eq!(cfg.graph.implementers, 1);
8610 assert_eq!(cfg.graph.judges, 1);
8611 assert_eq!(cfg.merge.mode, MergeMode::None);
8612 }
8613
8614 #[test]
8615 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8616 let dir = tempfile::tempdir().unwrap();
8617 let repo = dir.path().join("repo");
8618 std::fs::create_dir(&repo).unwrap();
8619 std::fs::write(
8620 repo.join("magi.toml"),
8621 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8622 )
8623 .unwrap();
8624 let daemon_config = dir.path().join("daemon.toml");
8625 std::fs::write(
8626 &daemon_config,
8627 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8628 )
8629 .unwrap();
8630 let opts = Opts {
8631 config: Some(daemon_config),
8632 merge: Some("pr".into()),
8633 ..Default::default()
8634 };
8635 let q = Queue::at(dir.path().join("queue"));
8636 let validation: Config =
8637 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8638 .unwrap();
8639 for record in ["{}", r#"{"candidates":2}"#] {
8641 let overrides = serde_json::from_str(record).unwrap();
8642 let filing = crate::direct::Filing {
8643 instruction: "work".into(),
8644 title: "direct".into(),
8645 repo: repo.clone(),
8646 source: crate::queue::Source::Human,
8647 solo: false,
8648 overrides,
8649 review_of: None,
8650 };
8651 let filed =
8652 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8653 let crate::direct::Filed::Standalone {
8654 mut task,
8655 claim: _claim,
8656 } = filed
8657 else {
8658 panic!("local filing")
8659 };
8660 let before = prepare_for(&repo, &opts, &task).unwrap();
8661 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8662 assert_eq!(
8663 before.merge.mode,
8664 MergeMode::None,
8665 "daemon --merge must not leak"
8666 );
8667 for n in [2, 1, 2] {
8668 task.set_implementers(n, &validation).unwrap();
8669 q.put(&mut task).unwrap();
8670 task = q.get(&task.id).unwrap();
8671 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8672 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8673 apply_task_implementers(&mut cfg, &task);
8674 assert_eq!(cfg.graph.implementers, usize::from(n));
8675 assert_eq!(cfg.graph.judges, 2);
8676 assert_eq!(cfg.merge.mode, MergeMode::None);
8677 }
8678 }
8679 }
8680
8681 #[test]
8682 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8683 let cfg: Config =
8684 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8685 .unwrap();
8686 let mut t = task();
8687 t.review_of = Some("review-target".into());
8688 t.hold_manual(Some("retry".into()));
8689 let mut previous = RunState::new(
8690 PathBuf::from("/repo"),
8691 "main".into(),
8692 "abc1234".into(),
8693 "review".into(),
8694 cfg.clone(),
8695 );
8696 previous.config.graph.implementers = 2;
8697 for count in [1, 3] {
8698 t.set_implementers(count, &cfg).unwrap();
8699 t.release();
8700 assert_eq!(t.review_of.as_deref(), Some("review-target"));
8701 for proposed in [
8702 Starter::Resume(previous.id.clone()),
8703 Starter::Review("recovery-target".into()),
8704 ] {
8705 assert_eq!(
8706 starter_with_implementers(&t, Some(&previous), proposed),
8707 Starter::Review("review-target".into())
8708 );
8709 }
8710 let mut configured = cfg.clone();
8711 apply_task_implementers(&mut configured, &t);
8712 assert_eq!(configured.graph.implementers, usize::from(count));
8713 assert_eq!(previous.config.graph.implementers, 2);
8714 }
8715 }
8716
8717 #[test]
8718 fn task_implementers_dispatch_and_resume_agree() {
8719 let mut t = task();
8720 let cfg: crate::config::Config =
8721 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8722 .unwrap();
8723 let mut run = RunState::new(
8724 PathBuf::from("/repo"),
8725 "main".into(),
8726 "abc1234".into(),
8727 "work".into(),
8728 cfg.clone(),
8729 );
8730 run.config.graph.implementers = 2;
8731 for n in [2, 1, 3, 2] {
8732 t.set_implementers(n, &cfg).unwrap();
8733 let mut dispatched = cfg.clone();
8734 apply_task_implementers(&mut dispatched, &t);
8735 assert_eq!(dispatched.graph.implementers, usize::from(n));
8736 assert_eq!(implementers_match(&t, &run), n == 2);
8737 for proposed in [
8738 Starter::Resume(run.id.clone()),
8739 Starter::Review("old-branch".into()),
8740 ] {
8741 let expected = if n == 2 {
8742 proposed.clone()
8743 } else {
8744 Starter::Start
8745 };
8746 assert_eq!(
8747 starter_with_implementers(&t, Some(&run), proposed),
8748 expected
8749 );
8750 }
8751 assert_eq!(
8752 run.config.graph.implementers, 2,
8753 "history must not be rewritten"
8754 );
8755 }
8756 t.solo = false;
8757 t.overrides = None;
8758 assert!(implementers_match(&t, &run));
8759 }
8760
8761 #[test]
8762 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8763 let mut solo_cfg = Config::default();
8769 solo_cfg.graph.implementers = 3;
8770 let mut solo_task = task();
8771 solo_task.solo = true;
8772 apply_task_implementers(&mut solo_cfg, &solo_task);
8773 assert_eq!(solo_cfg.graph.implementers, 1);
8774
8775 let mut plain_cfg = Config::default();
8776 plain_cfg.graph.implementers = 3;
8777 let plain_task = task();
8778 assert!(!plain_task.solo);
8779 apply_task_implementers(&mut plain_cfg, &plain_task);
8780 assert_eq!(
8781 plain_cfg.graph.implementers, 3,
8782 "a task that did not ask to run alone keeps the config's candidates"
8783 );
8784 }
8785
8786 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8787 QuotaLoss {
8788 seat: seat.into(),
8789 node: "judge".into(),
8790 at: at.parse().unwrap(),
8791 reset: reset.map(str::to_string),
8792 }
8793 }
8794
8795 #[test]
8796 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8797 let old: Vec<QuotaLoss> = (1..=4)
8798 .map(|i| {
8799 loss(
8800 &format!("judge-{i}"),
8801 "2026-09-23T05:23:00Z",
8802 Some("2:40pm (Asia/Tokyo)"),
8803 )
8804 })
8805 .collect();
8806 let fresh = losses_this_attempt(&old, &old);
8807 assert!(fresh.is_empty());
8808 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8809 }
8811
8812 #[test]
8813 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8814 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8815 let now = Timestamp::now();
8816 let mut after = old.clone();
8817 after.push(loss("judge-2", &now.to_string(), None));
8818 let fresh = losses_this_attempt(&old, &after);
8819 assert_eq!(fresh, vec![after[1].clone()]);
8820 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8821 assert_eq!(
8822 until,
8823 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8824 );
8825 }
8826
8827 #[test]
8828 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8829 let before = vec![
8832 loss("judge-1", "2026-09-23T05:23:00Z", None),
8833 loss("judge-2", "2026-09-23T05:24:00Z", None),
8834 ];
8835 let after = vec![
8836 loss("judge-2", "2026-09-23T05:24:00Z", None),
8837 loss("judge-1", "2026-09-24T01:00:00Z", None),
8838 ];
8839 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8840 }
8841
8842 #[test]
8843 fn merge_overrides_are_parsed_or_refused() {
8844 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8845 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8846 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8847 assert!(merge_mode("squash").is_err());
8848 }
8849
8850 #[test]
8851 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8852 let now = Timestamp::now();
8853 let fallback = Duration::from_secs(300);
8854 let cap = Duration::from_secs(1800);
8855
8856 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8858
8859 let soon = now + jiff::SignedDuration::from_secs(600);
8861 assert_eq!(
8862 quota_wait(Some(soon), now, fallback, cap),
8863 Duration::from_secs(600)
8864 );
8865
8866 let past = now - jiff::SignedDuration::from_secs(60);
8869 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8870
8871 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8874 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8875 }
8876
8877 #[test]
8878 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8879 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8880
8881 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8882 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8883
8884 let already_past =
8888 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8889 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8890
8891 assert!(
8892 parse_reset_hint("session limit reached", now, now).is_none(),
8893 "free text with no recognised shape is not guessed at"
8894 );
8895 assert!(
8896 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8897 "an unresolvable zone name is not guessed at either"
8898 );
8899 }
8900
8901 #[test]
8902 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8903 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8904
8905 let at = parse_reset_hint(
8906 "You've hit your usage limit. Visit \
8907 https://chatgpt.com/codex/settings/usage to purchase more \
8908 credits or try again at Sep 19th, 2026 5:10 PM.",
8909 now,
8910 now,
8911 )
8912 .expect("the codex reset wording is a recognised shape");
8913 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8914
8915 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8920 .expect("an explicit year needs no rollover");
8921 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8922
8923 assert!(
8924 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8925 "a two-digit year is not the documented shape and is not guessed at"
8926 );
8927 assert!(
8928 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8929 "a four-letter month name is not the documented three-letter abbreviation"
8930 );
8931 assert!(
8932 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8933 "an explicit zone on the dated shape is a format nobody has \
8934 documented, and is refused rather than guessed at as UTC"
8935 );
8936 }
8937
8938 #[test]
8939 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8940 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8941 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8942
8943 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8944 assert_eq!(at.as_second() - recorded.as_second(), 3769);
8945
8946 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8947 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8948
8949 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8950 assert!(
8951 parse_reset_hint(bad, now, recorded).is_none(),
8952 "{bad:?} must not be guessed at"
8953 );
8954 }
8955 }
8956
8957 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8961 let config = dir.join("magi.toml");
8962 std::fs::write(
8963 &config,
8964 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8965 )
8966 .unwrap();
8967 let opts = Opts {
8968 poll: Duration::from_secs(30),
8969 config: Some(config),
8970 repo: dir.join("repo"),
8974 ..Opts::default()
8975 };
8976 let home = dir.join("home");
8985 let worktrees = dir.join("wt");
8986 (
8987 opts,
8988 Queue::at(dir.join("queue")),
8989 home.join("daemon.json"),
8990 home,
8991 worktrees,
8992 )
8993 }
8994
8995 #[test]
8996 fn a_stop_is_idempotent_and_once_set_stays_set() {
8997 let stop = Stop::new();
8998 assert!(!stop.stopped());
8999
9000 stop.stop();
9001 assert!(stop.stopped());
9002 stop.stop();
9003 assert!(stop.stopped(), "a second stop is not a toggle");
9004
9005 let shared = stop.clone();
9006 assert!(
9007 shared.stopped(),
9008 "a clone is the same stop; that is how the loop and its caller share one"
9009 );
9010 }
9011
9012 #[test]
9013 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
9014 let stop = Stop::new();
9015 stop.enter();
9016 assert!(
9017 !stop.finishing(),
9018 "a busy loop nobody has asked to stop is just running"
9019 );
9020
9021 stop.stop();
9022 assert!(
9023 stop.finishing(),
9024 "a stop asked for mid-run has not landed until the run is settled"
9025 );
9026
9027 stop.exit();
9028 assert!(
9029 !stop.finishing(),
9030 "once the run is settled the stop has landed and there is nothing to finish"
9031 );
9032 }
9033
9034 #[test]
9035 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
9036 let stop = Stop::new();
9037 stop.enter();
9038 stop.enter();
9039 stop.stop();
9040 assert!(stop.finishing(), "two runs still in flight");
9041
9042 stop.exit();
9043 assert!(
9044 stop.finishing(),
9045 "one run finished, but a sibling is still working"
9046 );
9047
9048 stop.exit();
9049 assert!(
9050 !stop.finishing(),
9051 "the last run out is what actually lands the stop"
9052 );
9053 }
9054
9055 #[tokio::test]
9056 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
9057 let dir = tempfile::tempdir().unwrap();
9058 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9059 let stop = Stop::new();
9060 stop.stop();
9061
9062 let began = std::time::Instant::now();
9063 tokio::time::timeout(
9064 Duration::from_secs(2),
9065 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9066 )
9067 .await
9068 .expect("a stopped loop must return, not sit out its poll interval")
9069 .expect("the loop's own setup and teardown must not fail");
9070 assert!(
9071 began.elapsed() < opts.poll,
9072 "returned only after {:?}, which is a poll interval, not a stop",
9073 began.elapsed()
9074 );
9075 }
9076
9077 #[tokio::test]
9078 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
9079 let dir = tempfile::tempdir().unwrap();
9080 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9081 let stop = Stop::new();
9082
9083 let asker = {
9086 let stop = stop.clone();
9087 tokio::spawn(async move {
9088 tokio::time::sleep(Duration::from_millis(20)).await;
9089 stop.stop();
9090 })
9091 };
9092
9093 let began = std::time::Instant::now();
9094 tokio::time::timeout(
9095 Duration::from_secs(2),
9096 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9097 )
9098 .await
9099 .expect("a stop asked for while idle must wake the wait")
9100 .expect("the loop's own setup and teardown must not fail");
9101 asker.await.unwrap();
9102 assert!(
9103 began.elapsed() < opts.poll,
9104 "returned only after {:?}, so the stop waited on the sleep",
9105 began.elapsed()
9106 );
9107 }
9108
9109 #[tokio::test]
9110 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
9111 let dir = tempfile::tempdir().unwrap();
9112 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9113 let stop = Stop::new();
9114 stop.stop();
9115
9116 tokio::time::timeout(
9117 Duration::from_secs(2),
9118 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9119 )
9120 .await
9121 .expect("a stopped loop must return")
9122 .expect("the loop's own setup and teardown must not fail");
9123
9124 assert!(
9125 home.is_dir(),
9126 "the loop did publish a status file, so its removal is the teardown and not an absence"
9127 );
9128 assert!(
9129 !status_file.exists(),
9130 "a stopped loop clears its status file"
9131 );
9132 assert!(
9133 read_status(&home).is_none(),
9134 "a reader must see no daemon at all, not a heartbeat that merely stopped"
9135 );
9136 }
9137
9138 #[tokio::test]
9139 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
9140 let dir = tempfile::tempdir().unwrap();
9141 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9142 opts.once = true;
9143
9144 let mut settled = RunState::new(
9145 dir.path().join("repo"),
9146 "main".to_owned(),
9147 "abc1234".to_owned(),
9148 "fixture".to_owned(),
9149 Config::default(),
9150 );
9151 settled.status = RunStatus::Ready;
9152 let run_dir = home.join("runs").join(&settled.id);
9153 std::fs::create_dir_all(&run_dir).unwrap();
9154 std::fs::write(
9155 run_dir.join("run.json"),
9156 serde_json::to_string_pretty(&settled).unwrap(),
9157 )
9158 .unwrap();
9159 let questions = Questions::at(home.join("questions"));
9160 let mut question = ask::Question::new(
9161 settled.id.clone(),
9162 "review".to_owned(),
9163 "reviewer-1".to_owned(),
9164 "Continue?".to_owned(),
9165 String::new(),
9166 Vec::new(),
9167 );
9168 questions.put(&mut question).unwrap();
9169
9170 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
9171 .await
9172 .unwrap();
9173
9174 assert_eq!(
9175 questions.get(&question.id).unwrap().status,
9176 ask::QuestionStatus::Abandoned,
9177 "an empty --once drain still performs startup question cleanup"
9178 );
9179 }
9180
9181 #[test]
9182 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
9183 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9184
9185 assert!(
9186 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
9187 "never checked before: due at once"
9188 );
9189
9190 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
9191 assert!(
9192 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
9193 "well inside the interval: not due yet"
9194 );
9195
9196 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
9197 assert!(
9198 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
9199 "exactly at the edge: not yet due, same convention as `clean::due`"
9200 );
9201
9202 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9203 assert!(
9204 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
9205 "past the interval: due again"
9206 );
9207 }
9208
9209 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
9214 let config = dir.join("magi.toml");
9215 std::fs::write(
9221 &config,
9222 format!(
9223 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
9224 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
9225 cache_dir.display()
9226 ),
9227 )
9228 .unwrap();
9229 Opts {
9230 config: Some(config),
9231 repo: dir.join("repo"),
9232 ..Opts::default()
9233 }
9234 }
9235
9236 #[tokio::test]
9237 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
9238 let dir = tempfile::tempdir().unwrap();
9239 let home = dir.path().join("home");
9240 let cache_dir = dir.path().join("cache");
9241 std::fs::create_dir_all(&cache_dir).unwrap();
9242 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9243 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9244
9245 let running = Stop::new();
9248 let mut last_checked = None;
9249 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9250 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9251 .await;
9252 assert_eq!(
9253 crate::disk::dir_size(&cache_dir),
9254 0,
9255 "over the cap on the first check ever: pruned at once, no idle queue required"
9256 );
9257 assert_eq!(last_checked, Some(t0));
9258
9259 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9261 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9262 maybe_prune_cache_between_runs(
9263 &opts.repo,
9264 &opts,
9265 &home,
9266 &running,
9267 &mut last_checked,
9268 too_soon,
9269 )
9270 .await;
9271 assert_eq!(
9272 crate::disk::dir_size(&cache_dir),
9273 10,
9274 "too soon since the last check: left alone rather than rescanned every call"
9275 );
9276 assert_eq!(
9277 last_checked,
9278 Some(t0),
9279 "an idle check does not reset the clock"
9280 );
9281
9282 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9284 maybe_prune_cache_between_runs(
9285 &opts.repo,
9286 &opts,
9287 &home,
9288 &running,
9289 &mut last_checked,
9290 due_again,
9291 )
9292 .await;
9293 assert_eq!(
9294 crate::disk::dir_size(&cache_dir),
9295 0,
9296 "due again: pruned back under the cap"
9297 );
9298 }
9299
9300 #[tokio::test]
9308 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9309 let dir = tempfile::tempdir().unwrap();
9310 let home = dir.path().join("home");
9311 let cache_dir = dir.path().join("cache");
9312 std::fs::create_dir_all(&cache_dir).unwrap();
9313 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9314 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9315
9316 let stop = Stop::new();
9317 stop.stop();
9318 assert!(
9319 !stop.finishing(),
9320 "no run is in flight at a between-runs boundary, so nothing else \
9321 would tell the operator this stop had not taken effect yet"
9322 );
9323
9324 let mut last_checked = None;
9325 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9326 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9327 .await;
9328 assert_eq!(
9329 crate::disk::dir_size(&cache_dir),
9330 10,
9331 "over its cap, and due for the first check ever, but a stop outranks \
9332 it: the cap is a standing policy the next start measures again"
9333 );
9334 assert_eq!(
9335 last_checked, None,
9336 "a check that never happened must not claim the interval"
9337 );
9338 }
9339
9340 #[tokio::test]
9351 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9352 let dir = tempfile::tempdir().unwrap();
9353 let cache_dir = dir.path().join("cache");
9354 std::fs::create_dir_all(&cache_dir).unwrap();
9355 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9356
9357 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9358 opts.poll = Duration::from_millis(20);
9359 opts.max_attempts = 1_000;
9360
9361 let queue = Queue::at(dir.path().join("queue"));
9362 for i in 0..128 {
9363 let mut task = Task::new(
9364 format!("queued work {i}"),
9365 format!("queued work {i}"),
9366 opts.repo.clone(),
9367 Source::Human,
9368 );
9369 queue.put(&mut task).unwrap();
9370 }
9371
9372 let home = dir.path().join("home");
9373 let worktrees = dir.path().join("wt");
9374 let status_file = home.join("daemon.json");
9375 let stop = Stop::new();
9376 let stopper = {
9377 let stop = stop.clone();
9378 let queue = Queue::at(dir.path().join("queue"));
9379 tokio::spawn(async move {
9380 for _ in 0..2_000 {
9384 if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9385 break;
9386 }
9387 tokio::time::sleep(Duration::from_millis(5)).await;
9388 }
9389 stop.stop();
9390 })
9391 };
9392
9393 tokio::time::timeout(
9394 Duration::from_secs(20),
9395 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9396 )
9397 .await
9398 .expect("the loop must not hang on a queue that keeps producing failing work")
9399 .expect("the loop's own setup and teardown must not fail");
9400 stopper.await.unwrap();
9401
9402 let after = queue.list();
9403 let completed = after.iter().filter(|t| t.attempts == 1).count();
9404 assert!(
9405 completed >= 2,
9406 "the harness must have processed multiple tasks to exercise a busy queue \
9407 (got {completed} completed task(s))"
9408 );
9409 assert!(
9410 after.iter().any(|t| t.status.runnable()),
9411 "unprocessed tasks must remain: the external stop, rather than an \
9412 exhausted backlog, must end the test"
9413 );
9414 assert!(
9415 after
9416 .iter()
9417 .filter(|t| t.attempts > 0)
9418 .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9419 "a busy backlog must not retry a task's unchanged startup failure"
9420 );
9421
9422 assert_eq!(
9423 crate::disk::dir_size(&cache_dir),
9424 0,
9425 "an oversized cache must not be left to grow unboundedly just because the \
9426 queue kept the loop busy the whole time"
9427 );
9428 }
9429
9430 #[test]
9431 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9432 let dir = tempfile::tempdir().unwrap();
9433 let queue = Queue::at(dir.path().join("queue"));
9434 let questions = Questions::at(dir.path().join("questions"));
9435 let mut task = task();
9436 queue.put(&mut task).unwrap();
9437
9438 let mut task_question = ask::Question::new(
9439 task.id.clone(),
9440 crate::conduct::NODE.to_owned(),
9441 "conduct".to_owned(),
9442 "Which backend?".to_owned(),
9443 String::new(),
9444 Vec::new(),
9445 );
9446 questions.put(&mut task_question).unwrap();
9447 task.block(vec![task_question.id.clone()], None);
9448 queue.put(&mut task).unwrap();
9449
9450 let mut run_question = ask::Question::new(
9451 "20260101-000000-run1".to_owned(),
9452 "review".to_owned(),
9453 "reviewer-1".to_owned(),
9454 "Run question".to_owned(),
9455 String::new(),
9456 Vec::new(),
9457 );
9458 questions.put(&mut run_question).unwrap();
9459
9460 let mut coincidental = ask::Question::new(
9465 task.id.clone(),
9466 "review".to_owned(),
9467 "reviewer-1".to_owned(),
9468 "Unrelated review question".to_owned(),
9469 String::new(),
9470 Vec::new(),
9471 );
9472 questions.put(&mut coincidental).unwrap();
9473
9474 reconcile_task_questions(&queue, &questions);
9475 assert!(questions.get(&task_question.id).unwrap().status.open());
9476 assert!(questions.get(&run_question.id).unwrap().status.open());
9477 assert!(questions.get(&coincidental.id).unwrap().status.open());
9478
9479 task.release();
9480 queue.put(&mut task).unwrap();
9481 reconcile_task_questions(&queue, &questions);
9482 assert_eq!(
9483 questions.get(&task_question.id).unwrap().status,
9484 ask::QuestionStatus::Abandoned
9485 );
9486 assert!(
9487 questions.get(&run_question.id).unwrap().status.open(),
9488 "run questions remain the run janitor's responsibility"
9489 );
9490 assert!(
9491 questions.get(&coincidental.id).unwrap().status.open(),
9492 "a non-conductor question must not be abandoned just because its \
9493 run id coincides with a task id"
9494 );
9495 }
9496
9497 #[test]
9498 fn a_freshly_started_running_task_is_never_stalled() {
9499 let dir = tempfile::tempdir().unwrap();
9500 let mut t = task();
9501 t.start("run-1".to_owned());
9502 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9505 }
9506
9507 #[test]
9508 fn a_long_running_task_with_no_live_daemon_is_stalled() {
9509 let dir = tempfile::tempdir().unwrap();
9510 let mut t = task();
9511 t.start("run-1".to_owned());
9512 t.updated_at = Timestamp::now()
9513 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9514 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9515 assert_eq!(
9516 stalled_tasks(
9517 &Queue::at(dir.path().join("q")),
9518 dir.path(),
9519 Timestamp::now()
9520 )
9521 .len(),
9522 0,
9523 "the task was never written to this queue"
9524 );
9525 }
9526
9527 #[test]
9528 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9529 let dir = tempfile::tempdir().unwrap();
9530 let mut t = task();
9531 t.id = "20260903-080340-0167".to_owned();
9532 t.start("20260903-080619-01c2".to_owned());
9533 t.updated_at = Timestamp::now()
9534 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9535
9536 let mut status = Status::new();
9537 status.current = vec![Current {
9538 task: t.id.clone(),
9539 run: "20260903-080619-01c2".to_owned(),
9540 }];
9541 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9542
9543 assert!(
9544 !is_stalled(&t, dir.path(), Timestamp::now()),
9545 "a live daemon's own heartbeat rules out stalled, however long the task has run"
9546 );
9547 }
9548
9549 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9553 let path = queue.path_of(id);
9554 let body = std::fs::read_to_string(&path).unwrap();
9555 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9556 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9557 v["updated_at"] = serde_json::Value::String(old.to_string());
9558 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9559 }
9560
9561 #[test]
9562 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9563 let dir = tempfile::tempdir().unwrap();
9576 let queue = Queue::at(dir.path().join("queue"));
9577 let home = dir.path().join("home");
9578
9579 let mut t = task();
9580 t.id = "20260101-000001-lock".to_owned();
9581 t.start("run-1".to_owned());
9582 queue.put(&mut t).unwrap();
9583 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9584 std::fs::write(
9585 dir.path().join("queue").join(format!("{}.lock", t.id)),
9586 "not a pid",
9587 )
9588 .unwrap();
9589
9590 let now = Timestamp::now();
9591 assert!(
9592 reclaim_orphaned_running(&queue, 2).is_empty(),
9593 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9594 and reclaim must leave the task alone"
9595 );
9596 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9597
9598 let stalled = stalled_tasks(&queue, &home, now);
9599 assert_eq!(
9600 stalled.len(),
9601 1,
9602 "reclaim's inability to claim it yet must not hide it from the conductor"
9603 );
9604 assert_eq!(stalled[0].id, t.id);
9605 }
9606
9607 #[test]
9608 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9609 let dir = tempfile::tempdir().unwrap();
9610 crate::run::set_home(dir.path().join("run-home"));
9611 let queue = Queue::at(dir.path().join("queue"));
9612 let home = dir.path().join("home");
9613 let questions = Questions::at(dir.path().join("questions"));
9614
9615 let mut t = task();
9616 t.id = "20260101-000003-dead".to_owned();
9617 t.start("missing-run".to_owned());
9618 queue.put(&mut t).unwrap();
9619 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9620
9621 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9624 assert_eq!(
9625 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9626 [&t.id]
9627 );
9628 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9629 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9630
9631 crate::conduct::apply(
9634 &queue,
9635 &questions,
9636 &crate::conduct::Verdict {
9637 decisions: vec![crate::conduct::Decision {
9638 id: t.id.clone(),
9639 recovery: Some(crate::conduct::Recovery::Requeue),
9640 ..crate::conduct::Decision::default()
9641 }],
9642 },
9643 )
9644 .unwrap();
9645 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9646 }
9647
9648 #[test]
9649 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9650 let dir = tempfile::tempdir().unwrap();
9651 let queue = Queue::at(dir.path().join("queue"));
9652 let home = dir.path().join("home");
9653
9654 let mut fresh = task();
9655 fresh.id = "20260101-000001-aaaa".to_owned();
9656 fresh.start("run-1".to_owned());
9657 queue.put(&mut fresh).unwrap();
9658
9659 let mut old = task();
9660 old.id = "20260101-000002-bbbb".to_owned();
9661 old.start("run-2".to_owned());
9662 queue.put(&mut old).unwrap();
9663 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9664
9665 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9666 assert_eq!(stalled.len(), 1);
9667 assert_eq!(stalled[0].id, old.id);
9668 }
9669
9670 #[test]
9671 fn queued_and_finished_task_views_partition_by_status() {
9672 let dir = tempfile::tempdir().unwrap();
9673 let queue = Queue::at(dir.path().join("queue"));
9674
9675 let mut queued = task();
9676 queued.id = "20260101-000001-aaaa".to_owned();
9677 queue.put(&mut queued).unwrap();
9678
9679 let mut failed = task();
9680 failed.id = "20260101-000002-bbbb".to_owned();
9681 failed.start("run-1".to_owned());
9682 failed.fail("gate red", 5);
9683 queue.put(&mut failed).unwrap();
9684
9685 let mut held = task();
9686 held.id = "20260101-000003-cccc".to_owned();
9687 held.hold_machine(None);
9688 queue.put(&mut held).unwrap();
9689
9690 let mut running = task();
9691 running.id = "20260101-000004-dddd".to_owned();
9692 running.start("run-2".to_owned());
9693 queue.put(&mut running).unwrap();
9694
9695 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9696 assert_eq!(queued_ids, [queued.id.clone()]);
9697
9698 let mut finished_ids: Vec<String> =
9699 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9700 finished_ids.sort_unstable();
9701 let mut want = vec![failed.id.clone(), held.id.clone()];
9702 want.sort_unstable();
9703 assert_eq!(finished_ids, want);
9704 }
9705
9706 #[test]
9707 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9708 for short in [false, true] {
9709 let dir = tempfile::tempdir().unwrap();
9710 let queue = Queue::at(dir.path().join("queue"));
9711 let questions = ask::Questions::at(dir.path().join("questions"));
9712 let mut running = task();
9713 running.id = "20261013-192213-feb2".into();
9714 running.start("existing-run".into());
9715 queue.put(&mut running).unwrap();
9716 let mut middle = task();
9717 middle.id = "20261013-193611-ca5b".into();
9718 middle.block(
9719 vec![if short {
9720 "feb2".into()
9721 } else {
9722 running.id.clone()
9723 }],
9724 None,
9725 );
9726 queue.put(&mut middle).unwrap();
9727 let mut waiting = task();
9728 waiting.id = "20261013-202849-ee37".into();
9729 waiting.block(
9730 vec![if short {
9731 "ca5b".into()
9732 } else {
9733 middle.id.clone()
9734 }],
9735 Some("wait for implementation".into()),
9736 );
9737 queue.put(&mut waiting).unwrap();
9738 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9739 let inv = crate::blockers::Inventory::load(&queue, &questions);
9740 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9741 assert!(inv.stuck().is_empty());
9742 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9743 assert!(report.quarantined.is_empty());
9744 assert!(report.asked.is_empty());
9745 resolve_blockers(&queue, &questions);
9746 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9747 assert!(questions.list().is_empty());
9748 running.succeed();
9751 queue.put(&mut running).unwrap();
9752 resolve_blockers(&queue, &questions);
9753 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9754 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9755 middle = queue.get(&middle.id).unwrap();
9756 middle.succeed();
9757 queue.put(&mut middle).unwrap();
9758 resolve_blockers(&queue, &questions);
9759 let after = queue.get(&waiting.id).unwrap();
9760 assert_eq!(after.status, TaskStatus::Queued);
9761 assert!(after.blocked_by.is_empty());
9762 assert_eq!(after.instruction, waiting.instruction);
9763 }
9764 }
9765
9766 #[test]
9767 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9768 for future_schema in [false, true] {
9769 let name = "20261013-193611-ca5b";
9770 let mut future = task();
9771 future.id = name.into();
9772 future.schema = crate::queue::SCHEMA + 1;
9773 let contents = if future_schema {
9774 serde_json::to_string(&future).unwrap()
9775 } else {
9776 "corrupt".into()
9777 };
9778 let dir = tempfile::tempdir().unwrap();
9779 let queue = Queue::at(dir.path().join("queue"));
9780 let questions = ask::Questions::at(dir.path().join("questions"));
9781 let mut waiting = task();
9782 waiting.id = "20261013-202849-ee37".into();
9783 waiting.block(vec!["ca5b".into()], None);
9784 queue.put(&mut waiting).unwrap();
9785 std::fs::write(queue.path_of(name), contents).unwrap();
9786 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9787 assert!(
9788 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9789 );
9790 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9791 assert!(report.asked.is_empty());
9792 resolve_blockers(&queue, &questions);
9793 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9794 assert!(questions.list().is_empty());
9795 }
9796 let dir = tempfile::tempdir().unwrap();
9797 let queue = Queue::at(dir.path().join("queue"));
9798 let questions = ask::Questions::at(dir.path().join("questions"));
9799 let mut waiting = task();
9800 waiting.id = "20261013-202849-ee37".into();
9801 waiting.block(vec!["ca5b".into()], None);
9802 queue.put(&mut waiting).unwrap();
9803 let mut done = task();
9804 done.id = "20261013-193611-ca5b".into();
9805 done.succeed();
9806 queue.put(&mut done).unwrap();
9807 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9810 assert!(queue.get("ca5b").is_err());
9811 assert_eq!(
9812 crate::queue::dependency(&queue, &questions, "ca5b"),
9813 crate::queue::Dependency::Ambiguous
9814 );
9815 resolve_blockers(&queue, &questions);
9816 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9817 assert!(report.asked.is_empty());
9818 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9819 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9820 }
9821
9822 #[test]
9823 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9824 for held in [false, true] {
9825 for question in [false, true] {
9826 for reference in ["ca5b", "20261013-193611-ca5b"] {
9827 let dir = tempfile::tempdir().unwrap();
9828 let queue = Queue::at(dir.path().join("queue"));
9829 let questions = ask::Questions::at(dir.path().join("questions"));
9830 let mut prerequisite = task();
9831 prerequisite.id = "20261013-193611-ca5b".into();
9832 prerequisite.start("existing-run".into());
9833 queue.put(&mut prerequisite).unwrap();
9834 let mut waiting = task();
9835 waiting.id = "20261013-202849-ee37".into();
9836 if held {
9837 waiting.hold_machine(Some("waiting for separate consent".into()));
9838 }
9839 queue.put(&mut waiting).unwrap();
9840 let reason = "Deleting saved data requires separate owner consent";
9841 crate::conduct::apply(
9842 &queue,
9843 &questions,
9844 &crate::conduct::Verdict {
9845 decisions: vec![crate::conduct::Decision {
9846 id: waiting.id.clone(),
9847 blocked_by: vec![reference.into()],
9848 question: question.then(|| "May the saved data be deleted?".into()),
9849 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9850 reason: Some(reason.into()),
9851 ..crate::conduct::Decision::default()
9852 }],
9853 },
9854 )
9855 .unwrap();
9856 let before = queue.get(&waiting.id).unwrap();
9857 if question {
9858 assert_eq!(before.status, TaskStatus::Blocked);
9859 let q = questions.get(&before.blocked_by[0]).unwrap();
9860 assert_eq!(q.summary, "May the saved data be deleted?");
9861 assert!(q.status.open());
9862 } else {
9863 assert_eq!(before.status, TaskStatus::Held);
9864 let recorded_reason = before.hold_reason.as_deref().unwrap();
9865 assert!(recorded_reason.starts_with(reason));
9866 if held {
9867 assert!(recorded_reason.contains("waiting for separate consent"));
9868 }
9869 }
9870 prerequisite.succeed();
9871 queue.put(&mut prerequisite).unwrap();
9872 resolve_blockers(&queue, &questions);
9873 let after = queue.get(&waiting.id).unwrap();
9874 assert_eq!(after.status, before.status);
9875 assert_eq!(after.blocked_by, before.blocked_by);
9876 assert_eq!(after.hold_reason, before.hold_reason);
9877 assert_eq!(after.instruction, waiting.instruction);
9878 if question {
9879 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9880 }
9881 assert!(
9882 queue.next_runnable().is_none(),
9883 "dependency completion is not consent"
9884 );
9885 }
9886 }
9887 }
9888 }
9889
9890 #[test]
9891 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9892 let dir = tempfile::tempdir().unwrap();
9893 let queue = Queue::at(dir.path().join("queue"));
9894 let questions = ask::Questions::at(dir.path().join("questions"));
9895
9896 let mut dep = task();
9897 dep.id = "20260101-000001-dep0".to_owned();
9898 dep.succeed();
9899 queue.put(&mut dep).unwrap();
9900
9901 let mut still_going = task();
9902 still_going.id = "20260101-000002-dep1".to_owned();
9903 queue.put(&mut still_going).unwrap();
9904
9905 let mut blocked = task();
9906 blocked.id = "20260101-000003-main".to_owned();
9907 blocked.block(
9908 vec![dep.id.clone(), still_going.id.clone()],
9909 Some("waits on both".to_owned()),
9910 );
9911 queue.put(&mut blocked).unwrap();
9912
9913 resolve_blockers(&queue, &questions);
9914
9915 let after = queue.get(&blocked.id).unwrap();
9916 assert_eq!(
9917 after.status,
9918 TaskStatus::Blocked,
9919 "one dependency is still outstanding"
9920 );
9921 assert_eq!(after.blocked_by, [still_going.id.clone()]);
9922 }
9923
9924 #[test]
9925 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9926 let dir = tempfile::tempdir().unwrap();
9927 let queue = Queue::at(dir.path().join("queue"));
9928 let questions = ask::Questions::at(dir.path().join("questions"));
9929
9930 let mut q = crate::ask::Question::new(
9931 "20260101-000001-main".to_owned(),
9932 crate::conduct::NODE.to_owned(),
9933 "conduct".to_owned(),
9934 "Which backend?".to_owned(),
9935 String::new(),
9936 Vec::new(),
9937 );
9938 questions.put(&mut q).unwrap();
9939 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9940 .unwrap();
9941 questions.put(&mut q).unwrap();
9942
9943 let mut blocked = task();
9944 blocked.id = "20260101-000001-main".to_owned();
9945 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9946 queue.put(&mut blocked).unwrap();
9947
9948 resolve_blockers(&queue, &questions);
9949
9950 let after = queue.get(&blocked.id).unwrap();
9951 assert_eq!(
9952 after.status,
9953 TaskStatus::Queued,
9954 "the only blocker resolved"
9955 );
9956 assert_eq!(after.answers.len(), 1);
9957 assert_eq!(after.answers[0].question, "Which backend?");
9958 assert_eq!(after.answers[0].answer, "SQLite");
9959
9960 let instruction = instruction_for(&after);
9962 assert!(instruction.contains("Which backend?"));
9963 assert!(instruction.contains("SQLite"));
9964 }
9965
9966 #[test]
9967 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9968 let dir = tempfile::tempdir().unwrap();
9969 let queue = Queue::at(dir.path().join("queue"));
9970 let questions = ask::Questions::at(dir.path().join("questions"));
9971
9972 let mut q = crate::ask::Question::new(
9973 "20260101-000001-main".to_owned(),
9974 crate::conduct::NODE.to_owned(),
9975 "conduct".to_owned(),
9976 "Is the setup done?".to_owned(),
9977 String::new(),
9978 Vec::new(),
9979 );
9980 q.abandon("no answer within 60s of asking");
9981 questions.put(&mut q).unwrap();
9982
9983 let mut blocked = task();
9984 blocked.id = "20260101-000001-main".to_owned();
9985 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9986 queue.put(&mut blocked).unwrap();
9987
9988 resolve_blockers(&queue, &questions);
9989
9990 let after = queue.get(&blocked.id).unwrap();
9991 assert_eq!(
9992 after.status,
9993 TaskStatus::Held,
9994 "never left blocked on nothing"
9995 );
9996 assert!(!after.operator_held(), "a machine hold, for triage");
9997 assert!(
9998 after
9999 .hold_reason
10000 .as_deref()
10001 .unwrap_or_default()
10002 .contains("went unanswered")
10003 );
10004 }
10005
10006 #[test]
10007 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
10008 let dir = tempfile::tempdir().unwrap();
10014 let queue = Queue::at(dir.path().join("queue"));
10015 let questions = ask::Questions::at(dir.path().join("questions"));
10016
10017 let mut q = crate::ask::Question::new(
10018 "20260101-000001-main".to_owned(),
10019 crate::conduct::NODE.to_owned(),
10020 "conduct".to_owned(),
10021 "How should this be handled?".to_owned(),
10022 String::new(),
10023 Vec::new(),
10024 );
10025 questions.put(&mut q).unwrap();
10026 q.answer(crate::ask::Answer::Text(
10027 "leave it held, a human will look at it later".to_owned(),
10028 ))
10029 .unwrap();
10030 questions.put(&mut q).unwrap();
10031
10032 let mut held = task();
10033 held.id = "20260101-000001-main".to_owned();
10034 held.hold_machine(Some("out of attempts".to_owned()));
10035 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
10036 queue.put(&mut held).unwrap();
10037
10038 resolve_blockers(&queue, &questions);
10039
10040 let after = queue.get(&held.id).unwrap();
10041 assert_eq!(after.status, TaskStatus::Held);
10042 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
10043 assert_eq!(
10044 after.answers[0].answer,
10045 "leave it held, a human will look at it later"
10046 );
10047 }
10048
10049 #[test]
10050 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
10051 let dir = tempfile::tempdir().unwrap();
10052 let queue = Queue::at(dir.path().join("queue"));
10053 let questions = ask::Questions::at(dir.path().join("questions"));
10054 let mut dep = task();
10055 dep.id = "20260101-000001-gone".to_owned();
10056 queue.put(&mut dep).unwrap();
10057 let mut blocked = task();
10058 blocked.id = "20260101-000003-main".to_owned();
10059 blocked.block(vec![dep.id.clone()], None);
10060 queue.put(&mut blocked).unwrap();
10061
10062 let claim = queue.claim(&blocked.id).unwrap();
10064 queue.remove(&dep.id, false, &questions).unwrap();
10065 drop(claim);
10066 resolve_blockers(&queue, &questions);
10067
10068 let after = queue.get(&blocked.id).unwrap();
10069 assert_eq!(after.status, TaskStatus::Queued);
10070 assert!(after.blocked_by.is_empty());
10071 }
10072
10073 #[test]
10074 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
10075 let dir = tempfile::tempdir().unwrap();
10081 let queue = Queue::at(dir.path().join("queue"));
10082 let questions = ask::Questions::at(dir.path().join("questions"));
10083
10084 let mut still_going = task();
10085 still_going.id = "20260101-000002-dep1".to_owned();
10086 queue.put(&mut still_going).unwrap();
10087
10088 let mut blocked = task();
10089 blocked.id = "20260101-000003-main".to_owned();
10090 blocked.block(
10091 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
10092 Some("waits on both".to_owned()),
10093 );
10094 queue.put(&mut blocked).unwrap();
10095
10096 resolve_blockers(&queue, &questions);
10097
10098 let after = queue.get(&blocked.id).unwrap();
10099 assert_eq!(
10100 after.status,
10101 TaskStatus::Held,
10102 "a missing dependency must not leave the task blocked forever"
10103 );
10104 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
10105 assert!(after.blocked_by.is_empty());
10106 let reason = after.hold_reason.as_deref().unwrap_or_default();
10107 assert!(
10108 reason.contains("20260101-000001-gone"),
10109 "the missing id must be named so an operator can tell what happened: {reason}"
10110 );
10111 assert!(
10112 reason.contains(&still_going.id),
10113 "the still-valid dependency must not silently vanish from the record: {reason}"
10114 );
10115 }
10116
10117 #[test]
10118 fn instruction_for_is_unchanged_without_any_answers() {
10119 let t = task();
10120 assert_eq!(instruction_for(&t), t.instruction);
10121 }
10122
10123 #[test]
10124 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
10125 let dir = tempfile::tempdir().unwrap();
10126 let q = Queue::at(dir.path().join("queue"));
10127 let src = dir.path().join("shot.png");
10128 std::fs::write(&src, "x").unwrap();
10129 let mut t = task();
10130 q.attach(&mut t, &[src]).unwrap();
10131 let paths = task_attachments(&q, &t).unwrap();
10132 assert_eq!(paths.len(), 1);
10133 assert!(paths[0].is_absolute() && paths[0].is_file());
10134 std::fs::remove_file(&paths[0]).unwrap();
10135 let err = task_attachments(&q, &t).unwrap_err().to_string();
10136 assert!(err.contains("shot.png"), "{err}");
10137 }
10138
10139 #[tokio::test]
10140 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
10141 let dir = tempfile::tempdir().unwrap();
10142 let queue_path = dir.path().join("queue");
10143 let queue = Queue::at(queue_path.clone());
10144 let mut t = task();
10145 t.source = Source::Agent {
10146 run: "originating-chat".into(),
10147 node: crate::queue::CHAT_NODE.into(),
10148 };
10149 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
10150 stage: "config-fetch",
10151 target: "origin/main".into(),
10152 });
10153 record_config_failure(&mut t, &fetch);
10154 t.hold_machine(Some(format!("{fetch:#}")));
10155 let fetch_key = t.chat_notice_due().unwrap();
10156 t.chat_notices.push(fetch_key.clone());
10157 queue.put(&mut t).unwrap();
10158
10159 let queue = Queue::at(queue_path);
10160 let mut t = queue.get(&t.id).unwrap();
10161 let a = dir.path().join("a.toml");
10162 let b = dir.path().join("b.toml");
10163 for (path, text, new_cause) in [
10164 (&a, "[graph", true),
10165 (&a, "[verify", false),
10166 (&a, "[graph]\nimplementers = 'invalid-type'", true),
10167 (&b, "[graph]\nimplementers = 'invalid-type'", true),
10168 ] {
10169 t.release_operator("test", None);
10170 std::fs::write(path, text).unwrap();
10171 let error = Config::discover_fetched(dir.path(), Some(path))
10172 .await
10173 .unwrap_err();
10174 record_config_failure(&mut t, &error);
10175 t.hold_machine(Some(format!("{error:#}")));
10176 let due = t.chat_notice_due();
10177 assert_eq!(due.is_some(), new_cause, "{error:#}");
10178 if let Some(key) = due {
10179 assert_ne!(key, fetch_key);
10180 t.chat_notices.push(key);
10181 }
10182 }
10183 t.succeed();
10184 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
10185 }
10186
10187 #[test]
10188 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
10189 let dir = tempfile::tempdir().unwrap();
10190 let queue_path = dir.path().join("queue");
10191 let queue = Queue::at(queue_path.clone());
10192 let mut t = task();
10193 t.source = crate::queue::Source::Agent {
10194 run: "originating-chat".into(),
10195 node: crate::queue::CHAT_NODE.into(),
10196 };
10197 let a = dir.path().join("a.png");
10198 let b = dir.path().join("b.png");
10199 std::fs::write(&a, "a").unwrap();
10200 std::fs::write(&b, "b").unwrap();
10201 queue.attach(&mut t, &[a, b]).unwrap();
10202 let paths = task_attachments(&queue, &t).unwrap();
10203 for path in &paths {
10204 std::fs::remove_file(path).unwrap();
10205 }
10206 let missing = task_attachments(&queue, &t).unwrap_err();
10207 t.attempts += 1;
10208 let reason = missing.to_string();
10209 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10210 let first = t.chat_notice_due().expect("first attachment notice");
10211 t.chat_notices.push(first.clone());
10212 queue.put(&mut t).unwrap();
10213
10214 let queue = Queue::at(queue_path.clone());
10215 let mut t = queue.get(&t.id).unwrap();
10216 assert!(t.chat_notice_due().is_none(), "restart does not replay");
10217 t.release_operator("test", None);
10218 t.attempts += 1;
10219 let missing = task_attachments(&queue, &t).unwrap_err();
10220 t.fail_startup_target(
10221 "startup-attachments",
10222 missing.name,
10223 "same missing attachment with regenerated wording",
10224 1,
10225 );
10226 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
10227
10228 std::fs::write(&paths[0], "restored").unwrap();
10229 t.release_operator("test", None);
10230 t.attempts += 1;
10231 let missing = task_attachments(&queue, &t).unwrap_err();
10232 let reason = missing.to_string();
10233 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10234 let second = t
10235 .chat_notice_due()
10236 .expect("different attachment must notify");
10237 assert_ne!(first, second);
10238 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
10239 }
10240
10241 #[test]
10242 fn resumed_instruction_is_unchanged_without_any_answers() {
10243 let t = task();
10244 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10245 }
10246
10247 #[test]
10248 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10249 let mut t = task();
10250 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10251 let old = t.instruction.clone();
10255
10256 let refreshed = resumed_instruction(&old, &t);
10257 assert!(refreshed.starts_with(&old), "the original text is kept");
10258 assert!(refreshed.contains("Which backend?"));
10259 assert!(refreshed.contains("SQLite"));
10260 }
10261
10262 #[test]
10263 fn resumed_instruction_keeps_an_original_answers_heading() {
10264 let mut t = task();
10265 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10266 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10267
10268 let refreshed = resumed_instruction(&t.instruction, &t);
10269
10270 assert!(
10271 refreshed.starts_with(&t.instruction),
10272 "an answers heading in the original instruction is not the appended block"
10273 );
10274 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10275 assert!(refreshed.contains("Which backend?"));
10276 assert!(refreshed.contains("SQLite"));
10277
10278 let repeated = resumed_instruction(&refreshed, &t);
10279 assert_eq!(
10280 repeated, refreshed,
10281 "only the final appended block is refreshed"
10282 );
10283 }
10284
10285 #[test]
10286 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10287 let mut t = task();
10288 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10289
10290 let once = resumed_instruction(&t.instruction, &t);
10294 let twice = resumed_instruction(&once, &t);
10295 assert_eq!(once, twice);
10296 assert_eq!(once.matches("Which backend?").count(), 1);
10297
10298 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10300 let refreshed = resumed_instruction(&once, &t);
10301 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10302 assert!(refreshed.contains("Which backend?"));
10303 assert!(refreshed.contains("Which cache?"));
10304 }
10305
10306 #[test]
10307 fn prepare_instruction_covers_all_three_starters() {
10308 let mut t = task();
10309 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10310
10311 assert_eq!(
10314 prepare_instruction(&Starter::Start, None, &t),
10315 Some(instruction_for(&t))
10316 );
10317
10318 let old = t.instruction.clone();
10321 assert_eq!(
10322 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10323 Some(resumed_instruction(&old, &t))
10324 );
10325
10326 assert_eq!(
10330 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10331 None
10332 );
10333 }
10334
10335 #[test]
10336 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10337 assert_eq!(
10338 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10339 Starter::Review("magi/eba2/A".to_owned())
10340 );
10341 }
10342
10343 #[test]
10344 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10345 assert_eq!(
10346 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10347 Starter::Start,
10348 "a vanished review branch must not fall back to resuming the old run either"
10349 );
10350 }
10351
10352 #[test]
10353 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10354 let mut t = task();
10355 t.start("old-run".to_owned());
10356 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10357 t.release();
10358 let branch = t.review_branch.take();
10359 assert_eq!(
10360 choose_starter(branch.as_deref(), true, Some("old-run")),
10361 Starter::Review("magi/eba2/A".to_owned()),
10362 "a review wins over resuming the old run"
10363 );
10364 }
10365
10366 #[test]
10367 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10368 assert_eq!(
10369 choose_starter(None, false, Some("some-run")),
10370 Starter::Resume("some-run".to_owned())
10371 );
10372 assert_eq!(choose_starter(None, false, None), Starter::Start);
10373 }
10374
10375 #[test]
10376 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10377 let mut released = task();
10378 released.start("stalled-run".to_owned());
10379 released.requeue();
10380 let unfinished = (!released.fresh_start)
10381 .then(|| Some("stalled-run".to_owned()))
10382 .flatten();
10383 assert_eq!(
10384 choose_starter(None, false, unfinished.as_deref()),
10385 Starter::Start,
10386 "release keeps run history but must not resume it"
10387 );
10388 assert_eq!(released.runs, ["stalled-run"]);
10389 }
10390
10391 #[test]
10392 fn an_ordinary_release_keeps_a_resumable_run_available() {
10393 let mut released = task();
10394 released.start("stalled-run".to_owned());
10395 released.release();
10396 let unfinished = (!released.fresh_start)
10397 .then(|| Some("stalled-run".to_owned()))
10398 .flatten();
10399 assert_eq!(
10400 choose_starter(None, false, unfinished.as_deref()),
10401 Starter::Resume("stalled-run".to_owned()),
10402 "manual release must preserve the normal resume path"
10403 );
10404 }
10405
10406 #[test]
10407 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10408 let mut state = run_state(RunStatus::Blocked);
10409 state.config.graph.review_rounds = 3;
10410 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10411 assert!(exhausted_review_budget(&state));
10412
10413 state.reviews.pop();
10415 assert!(!exhausted_review_budget(&state));
10416
10417 let mut stalled = run_state(RunStatus::Stalled);
10420 stalled.config.graph.review_rounds = 1;
10421 stalled.reviews = vec![review_round(1)];
10422 assert!(!exhausted_review_budget(&stalled));
10423 }
10424
10425 fn review_round(round: usize) -> crate::run::ReviewRound {
10426 crate::run::ReviewRound {
10427 round,
10428 head: "deadbeef".to_owned(),
10429 verified_head: None,
10430 verified_at: None,
10431 reviews: Vec::new(),
10432 e2e: Vec::new(),
10433 verify_retried: false,
10434 e2e_deferred: false,
10435 e2e_defer_reason: None,
10436 fix: None,
10437 blocking: 0,
10438 answered: 1,
10439 expected: 1,
10440 clean: false,
10441 progressed: true,
10442 vote_split: false,
10443 reconsideration: Vec::new(),
10444 verdict: None,
10445 }
10446 }
10447
10448 #[test]
10449 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10450 let mut run = RunState::new(
10451 PathBuf::from("/repo"),
10452 "main".to_owned(),
10453 "abc1234def".to_owned(),
10454 "add retries".to_owned(),
10455 Config::default(),
10456 );
10457 run.status = RunStatus::Judging;
10458 run.parked = true;
10459 let mut task = Task::new(
10460 "add retries".to_owned(),
10461 "add retries".to_owned(),
10462 PathBuf::from("/repo"),
10463 crate::queue::Source::Human,
10464 );
10465 task.status = TaskStatus::Failed;
10466 task.runs = vec![run.id.clone()];
10467 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10468 assert!(with(&task, &run), "parked after judging is the case");
10469 let mut parked_task = task.clone();
10470 parked_task.status = TaskStatus::Parked;
10471 assert!(with(&parked_task, &run), "the Parked status is the case");
10472
10473 let mut not_parked = run.clone();
10474 not_parked.parked = false;
10475 not_parked.status = RunStatus::Stalled;
10476 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
10477
10478 let mut fresh = task.clone();
10479 fresh.fresh_start = true;
10480 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10481
10482 let mut review = task.clone();
10483 review.review_branch = Some("magi/x/A".to_owned());
10484 assert!(!with(&review, &run), "review is ranked before resume");
10485
10486 let mut held = task.clone();
10487 held.status = TaskStatus::Held;
10488 assert!(!with(&held, &run), "a hold stays visible to the conductor");
10489
10490 let mut released = run.clone();
10491 released.released_to = Some("20260901-000000-new1".to_owned());
10492 assert!(!with(&task, &released), "nothing left to resume into");
10493
10494 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10495 "unreadable"
10496 )));
10497 }
10498
10499 #[test]
10500 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10501 let mut released = RunState::new(
10502 PathBuf::from("/repo"),
10503 "main".to_owned(),
10504 "abc1234def".to_owned(),
10505 "add retries".to_owned(),
10506 Config::default(),
10507 );
10508 released.status = RunStatus::Blocked;
10509 assert_eq!(
10510 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10511 Some(released.id.clone())
10512 );
10513 released.released_to = Some("20260901-000000-new1".to_owned());
10514 assert_eq!(
10515 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10516 None,
10517 "there is nothing left to resume it into"
10518 );
10519 }
10520
10521 #[test]
10522 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10523 let mut exhausted = RunState::new(
10532 PathBuf::from("/repo"),
10533 "main".to_owned(),
10534 "abc1234def".to_owned(),
10535 "add retries".to_owned(),
10536 Config::default(),
10537 );
10538 exhausted.status = RunStatus::Blocked;
10539 exhausted.config.graph.review_rounds = 1;
10540 exhausted.reviews = vec![review_round(1)];
10541
10542 assert_eq!(
10543 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10544 None,
10545 "an exhausted `Blocked` run must not be offered as resumable"
10546 );
10547
10548 let mut has_budget_left = RunState::new(
10551 PathBuf::from("/repo"),
10552 "main".to_owned(),
10553 "abc1234def".to_owned(),
10554 "add retries".to_owned(),
10555 Config::default(),
10556 );
10557 has_budget_left.status = RunStatus::Blocked;
10558 has_budget_left.config.graph.review_rounds = 3;
10559 has_budget_left.reviews = vec![review_round(1)];
10560
10561 assert_eq!(
10562 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10563 Ok(has_budget_left.clone())
10564 }),
10565 Some(has_budget_left.id.clone())
10566 );
10567 }
10568
10569 #[test]
10570 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10571 let mut run = RunState::new(
10572 PathBuf::from("/repo"),
10573 "main".to_owned(),
10574 "abc1234def".to_owned(),
10575 "add retries".to_owned(),
10576 Config::default(),
10577 );
10578 run.status = RunStatus::Blocked;
10579 run.config.graph.review_rounds = 1;
10580 run.reviews = vec![review_round(1)];
10581 run.pr_publication_pending = true;
10582 assert_eq!(
10583 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10584 Some(run.id.clone()),
10585 "a spent review budget must not turn a failed publication into a re-competition"
10586 );
10587 }
10588
10589 #[test]
10590 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
10591 let mut task = Task::new(
10592 "recover work".into(),
10593 "recover work".into(),
10594 PathBuf::from("/repo"),
10595 crate::queue::Source::Human,
10596 );
10597 let mut history = std::collections::BTreeMap::new();
10598 for index in 0..8 {
10599 let mut run = run_state(RunStatus::Blocked);
10600 run.id = format!("20260101-000000-{index:04}");
10601 run.base_commit = format!("upstream-{index}");
10602 if index > 0 {
10604 run.candidates.clear();
10605 }
10606 task.runs.extend([run.id.clone(), run.id.clone()]);
10607 history.insert(run.id.clone(), run);
10608 task.requeue();
10609 }
10610 let check = |task: &Task, starter: &Starter, limit| {
10611 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
10612 };
10613 assert!(
10614 check(&task, &Starter::Start, 8)
10615 .unwrap()
10616 .contains("8 unretired")
10617 );
10618 assert!(check(&task, &Starter::Start, 9).is_none());
10619 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
10620 task.release_operator("owner", None);
10621 assert_eq!(task.attempts, 0);
10622 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
10623 assert!(check(&restored, &Starter::Start, 8).is_some());
10624 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
10625 assert!(check(&restored, &Starter::Start, 0).is_none());
10626 }
10627
10628 #[test]
10629 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
10630 let mut task = Task::new(
10631 "recover work".into(),
10632 "recover work".into(),
10633 PathBuf::from("/repo"),
10634 crate::queue::Source::Human,
10635 );
10636 let mut run = run_state(RunStatus::Superseded);
10637 run.candidates.clear();
10638 task.runs.push(run.id.clone());
10639 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
10640 run.retired_to = Some("authority".into());
10641 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10642 run.retired_to = None;
10643 run.released_to = Some("authority".into());
10644 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10645 assert!(
10646 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
10647 .unwrap()
10648 .contains("Cannot verify")
10649 );
10650 assert!(
10652 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
10653 panic!("resume must not load historical attempts")
10654 })
10655 .is_none()
10656 );
10657 }
10658
10659 #[test]
10660 fn retired_resume_requires_a_valid_same_repository_authority() {
10661 let mut source = run_state(RunStatus::Blocked);
10662 let mut empty = run_state(RunStatus::Blocked);
10663 empty.retired_to = Some(source.id.clone());
10664 let runs = vec![source.id.clone(), empty.id.clone()];
10665 let resolve = |source: &RunState, empty: &RunState| {
10666 unfinished_run_with(&runs, "fixture", |id| {
10667 if id == source.id {
10668 Ok(source.clone())
10669 } else if id == empty.id {
10670 Ok(empty.clone())
10671 } else {
10672 bail!("unreadable authority")
10673 }
10674 })
10675 };
10676 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
10677 assert_eq!(
10678 choose_starter(None, false, resolve(&source, &empty).as_deref()),
10679 Starter::Resume(source.id.clone())
10680 );
10681 source.retired_to = Some(empty.id.clone());
10682 assert!(
10683 resolve(&source, &empty).is_none(),
10684 "cycles do not revive obsolete runs"
10685 );
10686 source.retired_to = None;
10687 source.repo = PathBuf::from("/another-repository");
10688 assert!(resolve(&source, &empty).is_none());
10689 source.repo = empty.repo.clone();
10690 source.released_to = Some("later".into());
10691 assert!(resolve(&source, &empty).is_none());
10692 empty.retired_to = Some("unlisted-run".into());
10693 assert!(resolve(&source, &empty).is_none());
10694 }
10695
10696 #[test]
10697 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
10698 let mut older_stalled = RunState::new(
10706 PathBuf::from("/repo"),
10707 "main".to_owned(),
10708 "abc1234def".to_owned(),
10709 "add retries".to_owned(),
10710 Config::default(),
10711 );
10712 older_stalled.status = RunStatus::Stalled;
10713
10714 let mut newest_exhausted = RunState::new(
10715 PathBuf::from("/repo"),
10716 "main".to_owned(),
10717 "abc1234def".to_owned(),
10718 "add retries".to_owned(),
10719 Config::default(),
10720 );
10721 newest_exhausted.status = RunStatus::Blocked;
10722 newest_exhausted.config.graph.review_rounds = 1;
10723 newest_exhausted.reviews = vec![review_round(1)];
10724
10725 assert_eq!(
10726 unfinished_run_with(
10727 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10728 "t",
10729 |_| Ok(newest_exhausted.clone())
10730 ),
10731 None,
10732 "the newest run is exhausted, so nothing here is worth resuming - \
10733 least of all the older, already-superseded run"
10734 );
10735 }
10736
10737 #[test]
10738 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10739 assert_eq!(
10740 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10741 Err(anyhow::anyhow!("fixture is absent"))
10742 }),
10743 None
10744 );
10745 }
10746
10747 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10748 let mut q = ask::Question::new(
10749 run.to_owned(),
10750 "implement".to_owned(),
10751 "impl-A".to_owned(),
10752 "continue?".to_owned(),
10753 String::new(),
10754 vec!["resume で続行する".to_owned(), "other".to_owned()],
10755 );
10756 q.actions.insert("resume で続行する".to_owned(), action);
10757 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10758 .unwrap();
10759 q
10760 }
10761
10762 fn held_task_with(run: &str) -> Task {
10763 let mut t = task();
10764 t.runs = vec![run.to_owned()];
10765 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10766 t
10767 }
10768
10769 fn resume_action(run: &str) -> ask::ChoiceAction {
10770 ask::ChoiceAction::Resume { run: run.into() }
10771 }
10772
10773 #[test]
10774 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10775 for parked in [false, true] {
10776 let mut t = task();
10777 t.start("A".into());
10778 t.start("B".into());
10779 assert_eq!(t.runs, vec!["A", "B"]);
10780 t.start("A".into());
10781 let mut resumed = run_state(RunStatus::Blocked);
10782 resumed.id = "A".into();
10783 resumed.parked = parked;
10784 resumed.driver_exited = true;
10785 t.hold_machine(Some("resumed run stopped".into()));
10786 let q = action_question("A", resume_action("A"));
10787 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10788 assert_eq!(
10789 decide_action(&t, &q, &PHRASES_EN, |id| {
10790 assert_eq!(id, "A");
10791 Ok(resumed.clone())
10792 }),
10793 ActionDecision::Resume("A".into())
10794 );
10795 assert_eq!(
10796 action_standing(&t, &action_question("B", resume_action("B"))),
10797 ActionStanding::Stale
10798 );
10799 t.release_operator("cli", None);
10800 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10801 assert_eq!(id, "A");
10802 Ok(resumed.clone())
10803 });
10804 assert_eq!(
10805 choose_starter(None, false, unfinished.as_deref()),
10806 Starter::Resume("A".into())
10807 );
10808 assert_eq!(t.runs, vec!["B", "A"]);
10809 }
10810 }
10811
10812 #[test]
10813 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10814 let mut state = crate::land::tests::repair_state(true, true);
10815 state.status = RunStatus::Landing;
10816 state.parked = true;
10817 state.driver_exited = true;
10818 let mut q = ask::Question::new(
10819 state.id.clone(),
10820 land::APPROVAL_NODE.into(),
10821 "land".into(),
10822 "Merge?".into(),
10823 String::new(),
10824 vec![land::APPROVE.into(), land::HOLD.into()],
10825 );
10826 q.id = state.id.clone();
10827 state.land_approval = Some(crate::run::LandApproval {
10828 question: q.id.clone(),
10829 head: "current-head".into(),
10830 });
10831 assert!(land::upgrade_repair_choice(&mut q, &state));
10832 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10833 let mut task = held_task_with(&state.id);
10834 task.status = TaskStatus::Parked;
10835 assert_eq!(
10836 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10837 ActionDecision::Resume(state.id.clone())
10838 );
10839 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10840 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10841 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10842 assert_eq!(
10843 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10844 ActionDecision::Resume(state.id.clone()),
10845 "a repair answer newer than the manual hold resumes the existing owner"
10846 );
10847 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10848 for answered_at in [q.answered_at, None] {
10849 let mut older = q.clone();
10850 older.answered_at = answered_at;
10851 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10852 panic!("a later manual hold must prevent dispatch")
10853 });
10854 let ActionDecision::Refuse(reason) = refused else {
10855 panic!("expected an actionable refusal, got {refused:?}");
10856 };
10857 assert!(reason.contains("later operator decision"));
10858 assert!(reason.contains(&format!("magi task release {}", task.id)));
10859 }
10860 task.operator_decided_at = None;
10861 let mut superseded = state.clone();
10862 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10863 assert_eq!(
10864 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10865 ActionDecision::Stale
10866 );
10867 for case in 1..4 {
10868 let mut changed = state.clone();
10869 match case {
10870 1 => changed.status = RunStatus::Blocked,
10871 2 => changed.released_to = Some("new-owner".into()),
10872 _ => changed.land_approval.as_mut().unwrap().head.clear(),
10873 }
10874 assert!(matches!(
10875 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10876 ActionDecision::Refuse(_)
10877 ));
10878 }
10879 assert!(matches!(
10880 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10881 ActionDecision::Refuse(_)
10882 ));
10883 task.runs.push("replacement".into());
10884 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10885 assert_eq!(
10886 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10887 "old owner must not load"
10888 )),
10889 ActionDecision::Stale
10890 );
10891 }
10892
10893 #[test]
10894 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10895 let mut state = crate::land::tests::repair_state(true, true);
10896 state.status = RunStatus::Landing;
10897 state.parked = true;
10898 state.driver_exited = true;
10899 let mut q = ask::Question::new(
10900 state.id.clone(),
10901 land::APPROVAL_NODE.into(),
10902 "land".into(),
10903 "Merge?".into(),
10904 String::new(),
10905 vec![land::APPROVE.into(), land::HOLD.into()],
10906 );
10907 q.id = state.id.clone();
10908 state.land_approval = Some(crate::run::LandApproval {
10909 question: q.id.clone(),
10910 head: "current-head".into(),
10911 });
10912 state.save().unwrap();
10913 land::upgrade_repair_choice(&mut q, &state);
10914 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10915 Questions::open().put(&mut q).unwrap();
10916 let tmp = tempfile::tempdir().unwrap();
10917 let queue = Queue::at(tmp.path().join("queue"));
10918 let mut task = held_task_with(&state.id);
10919 task.status = TaskStatus::Parked;
10920 queue.put(&mut task).unwrap();
10921 let empty = Arc::new(tokio::sync::Semaphore::new(0));
10922 let free = Arc::new(tokio::sync::Semaphore::new(1));
10923 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10924 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10925 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10926 assert!(claim.permit.is_some());
10927 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10928 drop(claim);
10929 Questions::open()
10930 .update(&q.id, |q| {
10931 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10932 Ok(())
10933 })
10934 .unwrap();
10935 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10936 assert!(claim.permit.is_none());
10937 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10938 }
10939
10940 #[test]
10941 fn decide_action_resumes_only_the_latest_resumable_run() {
10942 let t = held_task_with("r1");
10943 let q = action_question("r1", resume_action("r1"));
10944 let load = |s: RunState| move |_: &str| Ok(s);
10945 assert_eq!(
10946 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10947 ActionDecision::Resume("r1".into())
10948 );
10949 let q_other = action_question("r1", resume_action("r0"));
10951 assert!(matches!(
10952 decide_action(
10953 &t,
10954 &q_other,
10955 &PHRASES_EN,
10956 load(run_state(RunStatus::Blocked))
10957 ),
10958 ActionDecision::Refuse(_)
10959 ));
10960 assert!(matches!(
10962 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10963 ActionDecision::Refuse(_)
10964 ));
10965 let mut released = run_state(RunStatus::Blocked);
10967 released.released_to = Some("elsewhere".into());
10968 assert!(matches!(
10969 decide_action(&t, &q, &PHRASES_EN, load(released)),
10970 ActionDecision::Refuse(_)
10971 ));
10972 assert!(matches!(
10974 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10975 ActionDecision::Refuse(_)
10976 ));
10977 }
10978
10979 #[test]
10980 fn decide_action_ignores_a_question_about_an_earlier_run() {
10981 let mut t = held_task_with("r1");
10982 t.runs.push("r2".to_owned());
10983 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10984 assert_eq!(
10985 decide_action(
10986 &t,
10987 &action_question("r1", ask::ChoiceAction::Done),
10988 &PHRASES_EN,
10989 never
10990 ),
10991 ActionDecision::Stale
10992 );
10993 }
10994
10995 #[test]
10996 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10997 let mut t = held_task_with("r1");
10998 let never = |_: &str| -> Result<RunState> { bail!("not read") };
10999 assert_eq!(
11000 decide_action(
11001 &t,
11002 &action_question("r1", ask::ChoiceAction::Requeue),
11003 &PHRASES_EN,
11004 never
11005 ),
11006 ActionDecision::Requeue
11007 );
11008 let done_q = action_question("r1", ask::ChoiceAction::Done);
11009 assert_eq!(
11010 decide_action(&t, &done_q, &PHRASES_EN, never),
11011 ActionDecision::Done
11012 );
11013 t.mark_action_applied(&done_q.id);
11014 assert_eq!(
11015 decide_action(&t, &done_q, &PHRASES_EN, never),
11016 ActionDecision::Skip
11017 );
11018
11019 let mut plain = action_question("r1", ask::ChoiceAction::Done);
11021 plain.actions.clear();
11022 assert_eq!(
11023 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
11024 ActionDecision::Skip
11025 );
11026 let mut running = held_task_with("r1");
11028 running.status = TaskStatus::Running;
11029 assert_eq!(
11030 decide_action(
11031 &running,
11032 &action_question("r1", ask::ChoiceAction::Done),
11033 &PHRASES_EN,
11034 never
11035 ),
11036 ActionDecision::Skip
11037 );
11038 }
11039
11040 #[test]
11041 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
11042 crate::run::pin_test_home();
11043 for legacy in [false, true] {
11044 let dir = tempfile::tempdir().unwrap();
11045 let queue = Queue::at(dir.path().join("queue"));
11046 let questions = Questions::at(dir.path().join("questions"));
11047 let run = "20260101-000000-hold";
11048 let mut task = held_task_with(run);
11049 task.status = TaskStatus::Parked;
11050 let mut q = ask::Question::new(
11051 run.into(),
11052 land::APPROVAL_NODE.into(),
11053 "land".into(),
11054 "Repair?".into(),
11055 String::new(),
11056 vec![land::REPAIR.into()],
11057 );
11058 q.actions.insert(land::REPAIR.into(), resume_action(run));
11059 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11060 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
11062 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
11063 questions.put(&mut q).unwrap();
11064 task.hold_manual(Some("Keep this PR paused".into()));
11065 if legacy {
11066 task.hold_source = None;
11067 }
11068 queue.put(&mut task).unwrap();
11069
11070 apply_task_choice_actions(&queue, &questions, dir.path());
11071 let after = queue.get(&task.id).unwrap();
11072 assert!(after.operator_held());
11073 assert_eq!(after.hold_source, task.hold_source);
11074 assert_eq!(after.operator_decided_at, task.operator_decided_at);
11075 assert_eq!(after.runs, task.runs);
11076 assert_eq!(after.instruction, task.instruction);
11077 assert!(after.resume_override.is_none());
11078 assert!(after.action_applied(&q.id));
11079 let reason = after.hold_reason.as_deref().unwrap();
11080 assert!(reason.starts_with("Keep this PR paused"));
11081 assert!(reason.contains("later operator decision"));
11082 assert!(reason.contains(&format!("magi task release {}", task.id)));
11083
11084 for recovery in [
11085 crate::conduct::Recovery::Review,
11086 crate::conduct::Recovery::Requeue,
11087 ] {
11088 crate::conduct::apply(
11089 &queue,
11090 &questions,
11091 &crate::conduct::Verdict {
11092 decisions: vec![crate::conduct::Decision {
11093 id: task.id.clone(),
11094 recovery: Some(recovery),
11095 ..Default::default()
11096 }],
11097 },
11098 )
11099 .unwrap();
11100 }
11101 apply_task_choice_actions(&queue, &questions, dir.path());
11104 let still_held = queue.get(&task.id).unwrap();
11105 assert!(still_held.operator_held());
11106 assert_eq!(still_held.hold_reason, after.hold_reason);
11107 assert_eq!(still_held.runs, task.runs);
11108 assert!(still_held.review_branch.is_none());
11109 assert!(!still_held.fresh_start);
11110 assert!(queue.next_runnable().is_none());
11111 }
11112 }
11113
11114 #[test]
11115 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
11116 for held in [false, true] {
11117 for retry in [false, true] {
11118 let dir = tempfile::tempdir().unwrap();
11119 let queue = Queue::at(dir.path().join("queue"));
11120 let questions = Questions::at(dir.path().join("questions"));
11121 let home = dir.path().join("home");
11122 let mut t = task();
11123 if held {
11124 t.hold_machine(Some("driver state unknown".into()));
11125 }
11126 queue.put(&mut t).unwrap();
11127 let verdict = serde_json::from_value(serde_json::json!({
11128 "decisions": [{
11129 "id": t.id,
11130 "question": "Driver state unknown; retry the checks or hold?",
11131 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
11132 "actions": {
11133 "daemon: recheck and retry": {"do": "requeue"},
11134 "daemon: hold the task": {"do": "hold"}
11135 }
11136 }]
11137 }))
11138 .unwrap();
11139 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
11140 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11141 let mut q = questions.list().pop().unwrap();
11142 let choice = if retry {
11143 "daemon: recheck and retry"
11144 } else {
11145 "daemon: hold the task"
11146 };
11147 assert_eq!(q.actions.len(), 2);
11148 q.answer(ask::Answer::Choice(choice.into())).unwrap();
11149 questions.put(&mut q).unwrap();
11150
11151 questions.beat(&q.id, ask::WaiterKind::Deputy);
11153 for _ in 0..2 {
11154 resolve_blockers(&queue, &questions);
11155 apply_task_choice_actions(&queue, &questions, &home);
11156 let waiting = queue.get(&t.id).unwrap();
11157 assert_eq!(waiting.status, TaskStatus::Blocked);
11158 assert_eq!(waiting.blocked_by, [q.id.clone()]);
11159 assert!(waiting.answers.is_empty());
11160 assert!(!waiting.action_applied(&q.id));
11161 assert!(runnable(&queue).is_empty());
11162 let free = Arc::new(tokio::sync::Semaphore::new(1));
11163 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
11164 }
11165 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11166
11167 resolve_blockers(&queue, &questions);
11169 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11170 apply_task_choice_actions(&queue, &questions, &home);
11171 let after = queue.get(&t.id).unwrap();
11172 assert_eq!(
11173 after.status,
11174 if retry {
11175 TaskStatus::Queued
11176 } else {
11177 TaskStatus::Held
11178 }
11179 );
11180 assert!(after.action_applied(&q.id));
11181 assert_eq!(after.operator_held(), !retry);
11182 assert_eq!(after.answers.len(), 1);
11183
11184 let mut changed = after;
11186 if retry {
11187 changed.hold_manual(Some("later hold".into()));
11188 } else {
11189 changed.release_operator("test", None);
11190 }
11191 let expected = changed.status;
11192 queue.put(&mut changed).unwrap();
11193 apply_task_choice_actions(&queue, &questions, &home);
11194 assert_eq!(queue.get(&t.id).unwrap().status, expected);
11195 }
11196 }
11197 }
11198
11199 #[test]
11200 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
11201 let dir = tempfile::tempdir().unwrap();
11202 let queue = Queue::at(dir.path().join("queue"));
11203 let questions = Questions::at(dir.path().join("questions"));
11204 let home = dir.path().join("home");
11205 let mut state = run_state(RunStatus::Blocked);
11206 state.id = "20260101-000000-act1".to_owned();
11207 state.save_under(&home).unwrap();
11208
11209 let mut t = held_task_with(&state.id);
11210 queue.put(&mut t).unwrap();
11211 let mut q = action_question(&state.id, resume_action(&state.id));
11212 questions.put(&mut q).unwrap();
11213
11214 apply_task_choice_actions(&queue, &questions, &home);
11215 let after = queue.get(&t.id).unwrap();
11216 assert_eq!(after.status, TaskStatus::Queued);
11217 assert!(!after.fresh_start);
11218 assert!(after.action_applied(&q.id));
11219 let pin = after.resume_override.clone().unwrap();
11220 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
11221 assert!(pin.forced);
11222
11223 let mut again = queue.get(&t.id).unwrap();
11225 again.hold_machine(Some("later".into()));
11226 queue.put(&mut again).unwrap();
11227 apply_task_choice_actions(&queue, &questions, &home);
11228 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11229 }
11230
11231 #[test]
11232 fn a_delivered_answer_is_still_acted_on_exactly_once() {
11233 let dir = tempfile::tempdir().unwrap();
11234 let queue = Queue::at(dir.path().join("queue"));
11235 let questions = Questions::at(dir.path().join("questions"));
11236 let home = dir.path().join("home");
11237 let mut state = run_state(RunStatus::Blocked);
11238 state.id = "20260101-000000-act2".to_owned();
11239 state.save_under(&home).unwrap();
11240
11241 let mut t = held_task_with(&state.id);
11242 queue.put(&mut t).unwrap();
11243 let mut q = action_question(&state.id, resume_action(&state.id));
11244 q.answer_delivered = true;
11245 questions.put(&mut q).unwrap();
11246
11247 apply_task_choice_actions(&queue, &questions, &home);
11250 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11251 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
11252
11253 let mut again = queue.get(&t.id).unwrap();
11255 again.hold_machine(Some("later".into()));
11256 queue.put(&mut again).unwrap();
11257 apply_task_choice_actions(&queue, &questions, &home);
11258 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11259 }
11260
11261 #[test]
11262 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
11263 let dir = tempfile::tempdir().unwrap();
11264 let queue = Queue::at(dir.path().join("queue"));
11265 let questions = Questions::at(dir.path().join("questions"));
11266 let home = dir.path().join("home");
11267 let mut state = run_state(RunStatus::Blocked);
11268 state.id = "20260101-000000-act3".to_owned();
11269 state.save_under(&home).unwrap();
11270 let mut t = held_task_with(&state.id);
11271 queue.put(&mut t).unwrap();
11272 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
11273 questions.put(&mut q).unwrap();
11274
11275 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
11276 apply_task_choice_actions(&queue, &questions, &home);
11277 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11278
11279 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11280 apply_task_choice_actions(&queue, &questions, &home);
11281 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11282 }
11283
11284 #[test]
11285 fn action_standing_tells_the_reasons_apart() {
11286 let mut t = held_task_with("r1");
11287 let q = action_question("r1", ask::ChoiceAction::Requeue);
11288 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
11289 let mut plain = q.clone();
11290 plain.actions.clear();
11291 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
11292
11293 t.mark_action_applied(&q.id);
11295 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
11296
11297 let mut t = held_task_with("r1");
11299 t.start("r2".to_owned());
11300 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
11301 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
11303 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11304 t.status = TaskStatus::Blocked;
11305 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11306
11307 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
11309 c.node = crate::conduct::NODE.to_owned();
11310 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
11311 assert!(!ActionStanding::Busy.daemon_owns());
11312 }
11313
11314 #[test]
11315 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
11316 let dir = tempfile::tempdir().unwrap();
11317 let queue = Queue::at(dir.path().join("queue"));
11318 let questions = Questions::at(dir.path().join("questions"));
11319 let home = dir.path().join("home");
11320 let mut state = run_state(RunStatus::Blocked);
11321 state.id = "20260101-000000-act4".to_owned();
11322 state.save_under(&home).unwrap();
11323 let mut t = held_task_with(&state.id);
11324 t.status = TaskStatus::Running;
11325 queue.put(&mut t).unwrap();
11326 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11327 q.cwd = Some(dir.path().display().to_string());
11328 questions.put(&mut q).unwrap();
11329
11330 let running = queue.get(&t.id).unwrap();
11333 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
11334 assert!(matches!(
11335 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
11336 crate::waiter::Action::Deliver(_)
11337 ));
11338 apply_task_choice_actions(&queue, &questions, &home);
11340 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11341 let mut back = queue.get(&t.id).unwrap();
11342 back.hold_machine(Some("later".into()));
11343 queue.put(&mut back).unwrap();
11344 apply_task_choice_actions(&queue, &questions, &home);
11345 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
11346 let mut again = queue.get(&t.id).unwrap();
11347 again.hold_machine(Some("again".into()));
11348 queue.put(&mut again).unwrap();
11349 apply_task_choice_actions(&queue, &questions, &home);
11350 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11351 }
11352}