1use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49pub const SCHEMA: u32 = 1;
51
52pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57pub const STALE_SECS: i64 = 30;
66
67pub const POLL: Duration = Duration::from_secs(5);
69
70pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub worker: Option<String>,
102 pub task: String,
104 pub run: String,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116 pub schema: u32,
118 pub pid: u32,
120 pub started_at: Timestamp,
122 pub updated_at: Timestamp,
124 pub idle: bool,
126 pub current: Vec<Current>,
132 pub completed: usize,
134 pub polls: u64,
136 #[serde(default)]
138 pub question_recovery: Option<crate::question_delivery::Recovery>,
139 #[serde(default)]
141 pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145 #[must_use]
147 pub fn new() -> Self {
148 let now = Timestamp::now();
149 Self {
150 schema: SCHEMA,
151 pid: std::process::id(),
152 started_at: now,
153 updated_at: now,
154 idle: true,
155 current: Vec::new(),
156 completed: 0,
157 polls: 0,
158 question_recovery: None,
159 worker_protocol: Some(1),
160 }
161 }
162}
163
164impl Default for Status {
165 fn default() -> Self {
166 Self::new()
167 }
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174 pub repo: PathBuf,
176 pub config: Option<PathBuf>,
178 pub poll: Duration,
180 pub max_attempts: usize,
182 pub once: bool,
184 pub merge: Option<String>,
186 pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198 fn default() -> Self {
199 Self {
200 repo: PathBuf::from("."),
201 config: None,
202 poll: POLL,
203 max_attempts: 2,
204 once: false,
205 merge: None,
206 worktrees_root: None,
207 }
208 }
209}
210
211impl Opts {
212 fn absolute(&self) -> Result<Self> {
213 let mut opts = self.clone();
214 opts.repo = std::path::absolute(&opts.repo)?;
215 opts.config = opts
216 .config
217 .as_deref()
218 .map(std::path::absolute)
219 .transpose()?;
220 opts.worktrees_root = opts
221 .worktrees_root
222 .as_deref()
223 .map(std::path::absolute)
224 .transpose()?;
225 Ok(opts)
226 }
227}
228
229fn max_concurrent(n: usize) -> usize {
234 n.max(1)
235}
236
237#[must_use]
239pub fn status_path() -> PathBuf {
240 crate::run::home().join("daemon.json")
241}
242
243pub fn write_status(status: &Status) -> Result<()> {
245 write_status_to(&status_path(), status)
246}
247
248pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253 if let Some(parent) = path.parent() {
254 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255 }
256 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257 let tmp = path.with_extension("json.tmp");
258 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260 Ok(())
261}
262
263pub fn clear_status() {
266 clear_status_at(&status_path());
267}
268
269fn clear_status_at(path: &Path) {
273 let _ = std::fs::remove_file(path);
274}
275
276#[derive(Debug, Clone, Default)]
288pub struct Stop {
289 stopped: Arc<AtomicBool>,
293 busy: Arc<std::sync::atomic::AtomicUsize>,
295 wake: Arc<Notify>,
299 pause: crate::graph::Pause,
302}
303
304impl Stop {
305 #[must_use]
307 pub fn new() -> Self {
308 Self::default()
309 }
310
311 pub fn stop(&self) {
314 self.stopped.store(true, Ordering::SeqCst);
315 self.wake.notify_one();
319 }
320
321 #[must_use]
323 pub fn stopped(&self) -> bool {
324 self.stopped.load(Ordering::SeqCst)
325 }
326
327 #[must_use]
330 pub fn finishing(&self) -> bool {
331 self.stopped() && self.busy_now()
332 }
333
334 pub fn park(&self, cause: crate::run::ParkCause) {
340 self.pause.park_for(cause);
341 self.stop();
342 }
343
344 #[must_use]
346 pub fn parking(&self) -> bool {
347 self.pause.parked()
348 }
349
350 #[must_use]
352 pub fn pause(&self) -> crate::graph::Pause {
353 self.pause.clone()
354 }
355
356 #[must_use]
358 pub fn busy_now(&self) -> bool {
359 self.busy.load(Ordering::SeqCst) > 0
360 }
361
362 async fn idle(&self, poll: Duration) {
364 tokio::select! {
365 () = tokio::time::sleep(poll) => {}
366 () = self.wake.notified() => {}
367 }
368 }
369}
370
371#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380 pub schema: u32,
382 pub pid: Option<u32>,
384 pub started_at: Option<Timestamp>,
386 pub updated_at: Option<Timestamp>,
388 pub idle: bool,
390 #[serde(deserialize_with = "de_current")]
402 pub current: Vec<Current>,
403 pub completed: u64,
405 pub polls: u64,
407 #[serde(default)]
409 pub question_recovery: Option<crate::question_delivery::Recovery>,
410 pub worker_protocol: Option<u32>,
412}
413
414fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418 D: serde::Deserializer<'de>,
419{
420 #[derive(Deserialize)]
421 #[serde(untagged)]
422 enum Shape {
423 Many(Vec<Current>),
424 One(Current),
425 }
426 Ok(
427 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428 Shape::Many(v) => v,
429 Shape::One(c) => vec![c],
430 }),
431 )
432}
433
434impl Reading {
435 #[must_use]
438 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439 self.updated_at
440 .map(|at| (now.as_second() - at.as_second()).max(0))
441 }
442
443 #[must_use]
447 pub fn running(&self, now: Timestamp) -> bool {
448 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449 }
450}
451
452#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461 serde_json::from_str(&body).ok()
462}
463
464#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474 let mut current = read_status(home)
475 .filter(|reading| reading.running(now))
476 .map(|reading| reading.current)
477 .unwrap_or_default();
478 let workers = crate::worker::observe_active(home).and_then(|jobs| {
479 jobs.into_iter()
480 .filter(|job| job.kind == "task")
481 .map(|job| {
482 let request: TaskWorker = serde_json::from_value(job.payload)?;
483 let run = Queue::at(request.queue)
484 .get(&request.task)
485 .ok()
486 .and_then(|task| task.runs.last().cloned())
487 .unwrap_or_default();
488 Ok(Current {
489 worker: Some(job.id),
490 task: request.task,
491 run,
492 })
493 })
494 .collect::<Result<Vec<_>>>()
495 });
496 match workers {
497 Ok(workers) => {
498 for worker in workers {
499 if !current.iter().any(|claim| {
500 claim.task == worker.task
501 && claim.run == worker.run
502 && claim.worker == worker.worker
503 }) {
504 current.push(worker);
505 }
506 }
507 }
508 Err(error) => {
509 tracing::error!("cannot determine active workers: {error:#}");
512 current.extend(
513 Queue::at(home.join("queue"))
514 .list()
515 .into_iter()
516 .map(|task| Current {
517 worker: None,
518 task: task.id,
519 run: task.runs.last().cloned().unwrap_or_default(),
520 }),
521 );
522 current.extend(
523 crate::run::list_ids_in(&home.join("runs"))
524 .into_iter()
525 .map(|run| Current {
526 worker: None,
527 task: String::new(),
528 run,
529 }),
530 );
531 }
532 }
533 current
534}
535
536#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539 current_work(home, now).iter().any(|c| c.run == run)
540}
541
542pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547 let same_home = std::env::var_os("MAGI_WORKER_HOME")
550 .is_some_and(|worker_home| Path::new(&worker_home) == home);
551 let caller = if same_home {
552 crate::worker::current_job(home)?
553 } else {
554 None
555 }
556 .filter(|job| {
557 job.kind == "task"
558 && job.status == crate::worker::Status::Running
559 && job.pid == Some(std::process::id())
560 });
561 Ok(other_claims_run(
562 ¤t_work(home, now),
563 run,
564 caller.as_ref().map(|job| job.id.as_str()),
565 ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569 claims
570 .iter()
571 .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585 current_work(home, now)
586 .iter()
587 .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593 current_work(home, now).iter().any(|c| c.task == task)
594}
595
596pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644 F: Fn(u32) -> bool,
645{
646 let this_process = std::process::id();
647 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648 .into_iter()
649 .flatten()
650 .flatten()
651 .map(|e| e.path())
652 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653 .filter(|p| {
654 match std::fs::read_to_string(p)
655 .ok()
656 .and_then(|body| body.trim().parse::<u32>().ok())
657 {
658 Some(pid) if pid == this_process => false,
662 Some(pid) => !pid_alive(pid),
663 None => p
664 .metadata()
665 .and_then(|m| m.modified())
666 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667 .is_ok_and(|age| age >= older_than),
668 }
669 })
670 .filter(|p| std::fs::remove_file(p).is_ok())
671 .filter_map(|p| {
672 p.file_stem()
673 .and_then(|s| s.to_str())
674 .map(std::borrow::ToOwned::to_owned)
675 })
676 .collect();
677 swept.sort_unstable();
678 swept
679}
680
681fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686 task.status == TaskStatus::Running
687 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688 && !is_working_on_task(home, &task.id, now)
689}
690
691fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694 queue
695 .list()
696 .into_iter()
697 .filter(|t| is_stalled(t, home, now))
698 .collect()
699}
700
701fn queued_tasks(queue: &Queue) -> Vec<Task> {
707 queue
708 .list()
709 .into_iter()
710 .filter(|t| t.status == TaskStatus::Queued)
711 .collect()
712}
713
714fn finished_tasks(queue: &Queue) -> Vec<Task> {
717 queue
718 .list()
719 .into_iter()
720 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721 .collect()
722}
723
724fn resolve_blockers(queue: &Queue, questions: &Questions) {
741 for listed in queue.list() {
742 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743 continue;
744 }
745 let Ok(_claim) = queue.claim(&listed.id) else {
746 continue;
747 };
748 let Ok(mut task) = queue.get(&listed.id) else {
749 continue;
750 };
751 if task.status != TaskStatus::Blocked {
752 continue;
753 }
754 let deleted = queue.apply_deleted_blockers(&mut task, questions);
758 if !deleted.is_empty() {
759 record(queue, &mut task);
760 for id in &deleted {
761 queue.note_dependency_deleted(&task, id);
762 }
763 if task.status != TaskStatus::Blocked {
764 continue;
765 }
766 }
767 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768 if !missing.is_empty() {
769 let language = language_of(&task, Path::new("."));
770 let mut cause = missing.clone();
771 cause.sort();
772 cause.dedup();
773 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775 &task.blocked_by,
776 &missing,
777 &language,
778 )));
779 record(queue, &mut task);
780 continue;
781 }
782 if let Some(q) = task.blocked_by.iter().find_map(|id| {
785 let crate::queue::Dependency::Question(full) =
786 crate::queue::dependency(queue, questions, id)
787 else {
788 return None;
789 };
790 questions.get(&full).ok().filter(|q| {
791 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792 })
793 }) {
794 let language = language_of(&task, Path::new("."));
795 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797 record(queue, &mut task);
798 continue;
799 }
800 let mut changed = false;
801 for id in task.blocked_by.clone() {
802 let resolved = crate::queue::dependency(queue, questions, &id);
803 if let crate::queue::Dependency::Task(full) = &resolved {
804 if queue
805 .get(full)
806 .is_ok_and(|dep| dep.status == TaskStatus::Done)
807 {
808 task.unblock(&id);
809 changed = true;
810 }
811 continue;
812 }
813 if let crate::queue::Dependency::Question(full) = resolved
814 && let Ok(q) = questions.get(&full)
815 && q.status == ask::QuestionStatus::Answered
816 {
817 if q.node == crate::conduct::NODE
821 && q.chosen_action().is_some()
822 && !task.action_applied(&q.id)
823 {
824 continue;
825 }
826 let answer = match &q.answer {
827 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828 None => String::new(),
829 };
830 task.record_answer(q.summary.clone(), answer);
831 task.unblock(&id);
832 changed = true;
833 }
834 }
835 if changed {
836 record(queue, &mut task);
837 }
838 }
839}
840
841fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843 if crate::lang::is_japanese(language) {
844 format!(
845 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846 q.short(),
847 q.summary
848 )
849 } else {
850 format!(
851 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852 q.short(),
853 q.summary
854 )
855 }
856}
857
858#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862 NoAction,
864 Pending,
866 Applied,
869 Stale,
871 Busy,
873}
874
875impl ActionStanding {
876 pub(crate) fn daemon_owns(self) -> bool {
878 matches!(self, Self::Pending | Self::Applied | Self::Stale)
879 }
880}
881
882pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886 if q.chosen_action().is_none() {
887 ActionStanding::NoAction
888 } else if task.action_applied(&q.id) {
889 ActionStanding::Applied
890 } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891 ActionStanding::Stale
892 } else if matches!(
893 task.status,
894 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895 ) {
896 ActionStanding::Busy
897 } else {
898 ActionStanding::Pending
899 }
900}
901
902#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905 Skip,
907 Resume(String),
909 Requeue,
911 Hold,
913 Done,
915 Stale,
918 Refuse(String),
921}
922
923fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
931where
932 F: FnOnce(&str) -> Result<RunState>,
933{
934 let Some(action) = q.chosen_action() else {
935 return ActionDecision::Skip;
936 };
937 if task.action_applied(&q.id)
938 || matches!(
939 task.status,
940 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
941 )
942 {
943 return ActionDecision::Skip;
944 }
945 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
948 return ActionDecision::Stale;
949 }
950 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
951 let stopping = q.node == land::APPROVAL_NODE
952 && q.resolution()
953 .as_deref()
954 .is_some_and(crate::merge_decision::stops);
955 let decision_at = q.answered_at.unwrap_or(q.asked_at);
959 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
960 return if repair || stopping {
961 ActionDecision::Refuse(format!(
962 "{} 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 {}`",
963 if repair { "repair" } else { "stop" },
964 q.id,
965 q.run,
966 task.id
967 ))
968 } else {
969 ActionDecision::Stale
970 };
971 }
972 match action {
973 a if a.maintenance() => ActionDecision::Skip,
974 ask::ChoiceAction::ResumeRun { .. }
975 | ask::ChoiceAction::ReleaseTask { .. }
976 | ask::ChoiceAction::RerunChecks { .. }
977 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
978 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
979 ask::ChoiceAction::Hold => ActionDecision::Hold,
980 ask::ChoiceAction::Done => ActionDecision::Done,
981 ask::ChoiceAction::Resume { run } => {
982 if task.runs.last() != Some(run) {
983 return ActionDecision::Refuse((p.resume_not_latest)(
984 q.short(),
985 ask::short_id(run),
986 ));
987 }
988 match load(run) {
989 Ok(s) if stopping => {
990 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
991 || !s
992 .land_approval
993 .as_ref()
994 .is_some_and(|binding| binding.question == q.id)
995 {
996 ActionDecision::Stale
997 } else if s.liveness(false) == Liveness::Live {
998 ActionDecision::Skip
999 } else if s.status == RunStatus::Landing
1000 && !s.released()
1001 && s.retired_to.is_none()
1002 {
1003 ActionDecision::Resume(run.clone())
1004 } else {
1005 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1006 }
1007 }
1008 Ok(s)
1009 if q.node == land::APPROVAL_NODE
1010 && q.resolution().as_deref() == Some(land::REPAIR) =>
1011 {
1012 if s.merge_repairs.iter().any(|r| r.question == q.id)
1013 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1014 {
1015 ActionDecision::Stale
1018 } else if s.liveness(false) == Liveness::Live {
1019 ActionDecision::Skip
1020 } else if s.status != RunStatus::Landing
1021 || s.released()
1022 || s.reviews.is_empty()
1023 || !implementers_match(task, &s)
1024 || !s
1025 .land_approval
1026 .as_ref()
1027 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1028 {
1029 ActionDecision::Refuse(format!(
1030 "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",
1031 q.id, run, run
1032 ))
1033 } else {
1034 ActionDecision::Resume(run.clone())
1035 }
1036 }
1037 Ok(s) if s.liveness(false) == Liveness::Live => {
1038 ActionDecision::Refuse("run already has a live driver".into())
1039 }
1040 Ok(s) => match crate::handover::resume_refusal(&s) {
1041 None => ActionDecision::Resume(run.clone()),
1042 Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1043 q.short(),
1044 ask::short_id(run),
1045 &reason.diagnostic(&s),
1046 )),
1047 },
1048 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1049 q.short(),
1050 ask::short_id(run),
1051 &format!("{e:#}"),
1052 )),
1053 }
1054 }
1055 }
1056}
1057
1058struct Phrases {
1072 graph_stopped: fn(&str, &str) -> String,
1074 quorum_lost: &'static str,
1075 quota_took_out: &'static str,
1077 run_ended: &'static str,
1079 waiting_for_answer: &'static str,
1081 recovered_running: &'static str,
1082 no_run_to_recover: &'static str,
1083 could_not_start: &'static str,
1084 resume_not_latest: fn(&str, &str) -> String,
1085 resume_cannot_progress: fn(&str, &str, &str) -> String,
1086 resume_unreadable: fn(&str, &str, &str) -> String,
1087 handover_refused: fn(&crate::handover::Refused) -> String,
1090 handover_hint: &'static str,
1092 reviewers_never_answered: fn(usize, usize) -> String,
1095}
1096
1097const PHRASES_EN: Phrases = Phrases {
1098 graph_stopped: |status, detail| {
1099 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1100 },
1101 quorum_lost: "the judging panel lost its quorum",
1102 quota_took_out: "; quota took out ",
1103 run_ended: "run ended ",
1104 waiting_for_answer: " - waiting for operator answer to question ",
1105 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1106 no_run_to_recover: "task was `running` with no live daemon and no readable \
1107 run to recover; held for a human to check what happened",
1108 could_not_start: "could not start the run: ",
1109 resume_not_latest: |q, run| {
1110 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1111 },
1112 resume_cannot_progress: |q, run, reason| {
1113 format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1114 },
1115 resume_unreadable: |q, run, e| {
1116 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1117 },
1118 handover_refused: |r| r.to_string(),
1119 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1120 reviewers_never_answered: |missing, rounds| {
1121 format!(
1122 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1123 refusing to call it clean"
1124 )
1125 },
1126};
1127
1128const PHRASES_JA: Phrases = Phrases {
1129 graph_stopped: |status, detail| {
1130 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1131 },
1132 quorum_lost: "審査パネルが定足数を失いました",
1133 quota_took_out: "。クォータで脱落: ",
1134 run_ended: "run 終了: ",
1135 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1136 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1137 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1138 何が起きたか人が確認するため保留にしました",
1139 could_not_start: "run を開始できませんでした: ",
1140 resume_not_latest: |q, run| {
1141 format!(
1142 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1143 )
1144 },
1145 resume_cannot_progress: |q, run, reason| {
1146 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1147 },
1148 resume_unreadable: |q, run, e| {
1149 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1150 },
1151 handover_refused: |r| {
1152 use crate::handover::Refused;
1153 match r {
1154 Refused::Foreign { branch, path, why } => format!(
1155 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1156 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1157 から、やり直してください(詳細: {why})"
1158 ),
1159 Refused::Unsafe { branch, path, why } => format!(
1160 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1161 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1162 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1163 ),
1164 Refused::ReleaseFailed { branch, path, run } => format!(
1165 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1166 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1167 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1168 ),
1169 }
1170 },
1171 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1172 reviewers_never_answered: |missing, rounds| {
1173 format!(
1174 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1175 クリーンとは認めません"
1176 )
1177 },
1178};
1179
1180fn phrases(language: &str) -> &'static Phrases {
1181 if crate::lang::is_japanese(language) {
1182 &PHRASES_JA
1183 } else {
1184 &PHRASES_EN
1185 }
1186}
1187
1188fn language_of(task: &Task, fallback: &Path) -> String {
1192 crate::lang::of_repo(&repo_for(task, fallback))
1193}
1194
1195pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1199 if q.node == crate::conduct::NODE {
1200 return tasks.iter().find(|t| t.id == q.run);
1201 }
1202 tasks.iter().find(|t| t.runs.contains(&q.run))
1203}
1204
1205fn repair_choice_offers(questions: &Questions) {
1208 for q in questions.list().into_iter().filter(|q| {
1209 q.status.open()
1210 && q.node == crate::conduct::NODE
1211 && q.choices
1212 .iter()
1213 .any(|c| crate::choice_effect::describe(q, c).is_none())
1214 }) {
1215 let _ = questions.update(&q.id, |current| {
1216 if current.status.open() {
1217 crate::choice_effect::executable_conductor(current);
1218 if let Some(deputy) = &mut current.deputy {
1219 deputy.brief = crate::deputy::brief(
1220 ¤t.run,
1221 ¤t.detail,
1222 ¤t.choices,
1223 ¤t.actions,
1224 );
1225 }
1226 }
1227 Ok(())
1228 });
1229 }
1230}
1231
1232pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1235 apply_maintenance_choices(queue, questions, home).await;
1236 apply_task_choice_actions(queue, questions, home);
1237}
1238
1239async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1242 for q in questions.list() {
1243 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1244 continue;
1245 };
1246 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1249 continue;
1250 }
1251 let dir = home.join("choice-actions");
1252 if std::fs::create_dir_all(&dir).is_err() {
1253 continue;
1254 }
1255 let Ok(lock) = std::fs::OpenOptions::new()
1256 .create(true)
1257 .truncate(false)
1258 .write(true)
1259 .open(dir.join(format!("{}.lock", q.id)))
1260 else {
1261 continue;
1262 };
1263 if crate::pr_head::try_lock_file(&lock).is_err() {
1264 continue;
1265 }
1266 let fresh = !home
1267 .join("choice-actions")
1268 .join(format!("{}.json", q.id))
1269 .exists();
1270 let result = async {
1271 let receipt = dir.join(format!("{}.json", q.id));
1272 if receipt.exists() {
1273 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1274 anyhow::ensure!(
1275 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1276 "previous maintenance attempt did not confirm completion; inspect its receipt"
1277 );
1278 return Ok::<_, anyhow::Error>(());
1279 }
1280 let record = |status: &str| -> anyhow::Result<()> {
1283 let tmp = receipt.with_extension("tmp");
1284 std::fs::write(
1285 &tmp,
1286 serde_json::to_vec(&serde_json::json!({
1287 "action": action, "status": status,
1288 }))?,
1289 )?;
1290 std::fs::rename(tmp, &receipt)?;
1291 Ok(())
1292 };
1293 let applied = async {
1294 match action {
1295 ask::ChoiceAction::ResumeRun { run } => {
1296 crate::resume::validate(home, run)?;
1297 record("started")?;
1298 let decided = q.answered_at.unwrap_or(q.asked_at);
1299 if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1300 crate::resume::validate_unqueued(home, run)?;
1301 crate::resume::start(home, run.clone()).await?;
1302 }
1303 }
1304 ask::ChoiceAction::ReleaseTask {
1305 task,
1306 held_at,
1307 reason,
1308 } => {
1309 anyhow::ensure!(
1310 queue.resolve_id(task)? == *task,
1311 "task action requires an exact task ID"
1312 );
1313 let _claim = queue.claim(task)?;
1314 let mut task = queue.get(task)?;
1315 if task.action_applied(&q.id) {
1316 return Ok(());
1317 }
1318 if q.node == crate::conduct::NODE
1323 && q.run == task.id
1324 && task.status == TaskStatus::Blocked
1325 && task.blocked_from == Some(TaskStatus::Held)
1326 && task.blocked_by.as_slice() == [q.id.as_str()]
1327 {
1328 task.unblock(&q.id);
1329 }
1330 anyhow::ensure!(
1331 task.status == TaskStatus::Held
1332 && task.held_at == Some(*held_at)
1333 && task.hold_reason.as_deref() == reason.as_deref()
1334 && task
1335 .operator_decided_at
1336 .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1337 "task no longer has the hold this question names"
1338 );
1339 task.release_operator("choice", Some(&q.id));
1340 task.mark_action_applied(&q.id);
1341 queue.put(&mut task)?;
1342 }
1343 ask::ChoiceAction::AbandonRun { run } => {
1344 record("started")?;
1345 crate::driver::abandon_proven_dead(home, run)?;
1346 }
1347 ask::ChoiceAction::RerunChecks {
1348 repo,
1349 pr,
1350 head,
1351 runs,
1352 } => {
1353 rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1354 .await?;
1355 }
1356 _ => unreachable!(),
1357 }
1358 Ok::<_, anyhow::Error>(())
1359 }
1360 .await;
1361 match applied {
1362 Ok(()) => record("applied"),
1363 Err(e) => {
1364 record(&format!("refused or failed: {e:#}"))?;
1365 Err(e)
1366 }
1367 }
1368 }
1369 .await;
1370 if home
1375 .join("choice-actions")
1376 .join(format!("{}.json", q.id))
1377 .exists()
1378 && let Some(listed) = task_of_question(&queue.list(), &q)
1379 && !listed.action_applied(&q.id)
1380 && let Ok(_claim) = queue.claim(&listed.id)
1381 && let Ok(mut origin) = queue.get(&listed.id)
1382 {
1383 if !origin.operator_held()
1384 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1385 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1386 {
1387 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1388 origin.hold_machine(Some(format!(
1389 "Maintenance choice {} settled; inspect its target before releasing this task",
1390 q.id
1391 )));
1392 } else {
1393 origin.unblock(&q.id);
1394 }
1395 }
1396 origin.mark_action_applied(&q.id);
1397 let _ = queue.put(&mut origin);
1398 }
1399 if let Err(e) = result
1400 && fresh
1401 {
1402 notices::raise_in(
1403 home,
1404 Notice::warn(
1405 &format!("action:{}", q.id),
1406 format!("Choice action {} was not completed: {e:#}", q.id),
1407 )
1408 .link(if q.run_names_task() {
1409 Link::Task { id: q.run.clone() }
1410 } else {
1411 Link::Run { id: q.run.clone() }
1412 }),
1413 );
1414 }
1415 }
1416}
1417
1418pub(crate) async fn rerun_checks_once(
1425 home: &Path,
1426 request: &str,
1427 repo: &Path,
1428 pr: &str,
1429 head: &str,
1430 runs: &[String],
1431 started: impl FnOnce() -> anyhow::Result<()>,
1432) -> anyhow::Result<()> {
1433 use crate::release_watch::{GhForge, ReleaseForge};
1434 anyhow::ensure!(
1435 !runs.is_empty()
1436 && runs.len() <= 20
1437 && runs
1438 .iter()
1439 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1440 && !pr.starts_with('-'),
1441 "invalid rerun targets"
1442 );
1443 let snap = GhForge.snapshot(repo, pr).await?;
1444 anyhow::ensure!(
1445 snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1446 "pull request head or lifecycle changed"
1447 );
1448 anyhow::ensure!(
1449 runs.iter().all(|r| snap
1450 .checks
1451 .iter()
1452 .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1453 "named workflow is no longer failed on this pull request"
1454 );
1455 started()?;
1456 let dir = home.join("choice-actions");
1457 std::fs::create_dir_all(&dir)?;
1458 let rerun_lock = std::fs::OpenOptions::new()
1459 .create(true)
1460 .truncate(false)
1461 .write(true)
1462 .open(dir.join("reruns.lock"))?;
1463 crate::pr_head::try_lock_file(&rerun_lock)?;
1464 let ledger = dir.join("reruns.json");
1465 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1466 serde_json::from_slice(&std::fs::read(&ledger)?)?
1467 } else {
1468 Default::default()
1469 };
1470 for run in runs {
1471 let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1472 if !recorded.insert(key) {
1473 continue;
1474 }
1475 let tmp = ledger.with_extension("tmp");
1476 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1477 std::fs::rename(tmp, &ledger)?;
1478 GhForge.rerun(repo, run).await?;
1479 }
1480 Ok(())
1481}
1482
1483pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1492 let tasks = queue.list();
1493 for q in questions.list() {
1494 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1496 continue;
1497 }
1498 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1499 continue;
1500 }
1501 let Some(listed) = task_of_question(&tasks, &q) else {
1502 if q.node == land::APPROVAL_NODE
1503 && q.resolution().as_deref().is_some_and(|choice| {
1504 choice == land::REPAIR || crate::merge_decision::stops(choice)
1505 })
1506 {
1507 notices::raise_in(
1508 home,
1509 Notice::warn(
1510 &format!("repair-owner:{}", q.id),
1511 format!(
1512 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1513 q.run, q.run
1514 ),
1515 ).link(Link::Run { id: q.run.clone() }),
1516 );
1517 }
1518 continue;
1519 };
1520 if listed.action_applied(&q.id) {
1521 continue;
1522 }
1523 let Ok(_claim) = queue.claim(&listed.id) else {
1524 continue;
1525 };
1526 let Ok(mut task) = queue.get(&listed.id) else {
1527 continue;
1528 };
1529 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1532 let blockers: Vec<_> = task
1533 .blocked_by
1534 .iter()
1535 .filter(|id| {
1536 crate::queue::dependency(queue, questions, id)
1537 == crate::queue::Dependency::Question(q.id.clone())
1538 })
1539 .cloned()
1540 .collect();
1541 if !blockers.is_empty() {
1542 for id in blockers {
1543 task.unblock(&id);
1544 }
1545 let answer = match &q.answer {
1546 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1547 None => String::new(),
1548 };
1549 task.record_answer(q.summary.clone(), answer);
1550 }
1551 }
1552 let language = language_of(&task, Path::new("."));
1553 let decision = decide_action(&task, &q, phrases(&language), |id| {
1554 RunState::load_under(id, home)
1555 });
1556 let ran = matches!(
1557 decision,
1558 ActionDecision::Resume(_)
1559 | ActionDecision::Requeue
1560 | ActionDecision::Hold
1561 | ActionDecision::Done
1562 );
1563 if ran && asker_may_still_read(questions, &q, home) {
1564 continue;
1573 }
1574 let done = matches!(decision, ActionDecision::Done);
1575 match decision {
1576 ActionDecision::Skip => continue,
1577 ActionDecision::Resume(run) => {
1578 task.release_operator("choice", Some(&q.id));
1579 task.resume_override = Some(crate::queue::OperatorResume {
1580 question_id: q.id.clone(),
1581 at: Timestamp::now(),
1582 conductor_rehold: None,
1583 forced: true,
1584 pinned_run: Some(run),
1585 });
1586 }
1587 ActionDecision::Stale => {}
1588 ActionDecision::Requeue => {
1589 task.release_operator("choice-requeue", Some(&q.id));
1590 task.requeue();
1591 }
1592 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1593 ActionDecision::Done => task.succeed(),
1594 ActionDecision::Refuse(why) => {
1595 if task.operator_held() {
1596 task.hold_reason = Some(match task.hold_reason.take() {
1599 Some(reason) => format!("{reason}\n\n{why}"),
1600 None => why,
1601 });
1602 } else {
1603 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1604 task.hold_machine(Some(why));
1605 }
1606 notices::raise(
1607 Notice::warn(
1608 &format!("action:{}", q.id),
1609 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1610 )
1611 .link(Link::Task {
1612 id: task.id.clone(),
1613 }),
1614 );
1615 }
1616 }
1617 task.mark_action_applied(&q.id);
1618 record(queue, &mut task);
1621 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1622 supersede_prior_runs(&task, home);
1623 }
1624 let _ = questions.update(&q.id, |r| {
1627 r.answer_delivered = true;
1628 Ok(())
1629 });
1630 }
1631}
1632
1633fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1637 let now = Timestamp::now();
1638 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1639 return true;
1640 }
1641 q.node != crate::conduct::NODE
1642 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1643 s.seats_active()
1644 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1645 })
1646}
1647
1648fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1659 let tasks = queue.list();
1660 let by_id: std::collections::BTreeMap<&str, &Task> =
1661 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1662 let referenced: Vec<&str> = tasks
1663 .iter()
1664 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1665 .collect();
1666
1667 for mut question in questions.list() {
1668 if !question.status.open() || question.node != crate::conduct::NODE {
1669 continue;
1670 }
1671 if referenced
1676 .iter()
1677 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1678 {
1679 continue;
1680 }
1681 let Some(task) = by_id.get(question.run.as_str()) else {
1682 continue;
1683 };
1684 question.abandon(format!(
1685 "task {} no longer waits for this answer",
1686 task.short()
1687 ));
1688 if let Err(e) = questions.put(&mut question) {
1689 tracing::warn!(
1690 "could not retire question {} for task {}: {e:#}",
1691 question.short(),
1692 task.short()
1693 );
1694 }
1695 }
1696}
1697
1698#[derive(Debug, Clone, Copy)]
1705pub struct Verdict {
1706 pub status: RunStatus,
1708 pub left_pr: bool,
1710 pub quota_hit: bool,
1712 pub parked: bool,
1714 pub no_viable_candidates: bool,
1721}
1722
1723pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1782 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1783}
1784
1785fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1787 if verdict.parked {
1793 task.park(detail);
1794 return;
1795 }
1796 match verdict.status {
1797 RunStatus::Merged | RunStatus::Ready
1798 if task.pr_recovery.as_ref().is_some_and(|s| {
1799 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1800 }) =>
1801 {
1802 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()));
1803 }
1804 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1805 RunStatus::AlreadyInBase => task.already_landed(detail),
1806 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1807 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1808 task.stall(detail)
1809 }
1810 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1811 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1812 RunStatus::Blocked => task.fail(detail, max_attempts),
1813 RunStatus::VerifiedNoop => task.handed_off(detail),
1814 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1815 }
1816}
1817
1818pub fn supersede_prior_runs(task: &Task, home: &Path) {
1867 let now = Timestamp::now();
1868 let last_run_succeeded = task
1875 .runs
1876 .last()
1877 .and_then(|id| RunState::load_under(id, home).ok())
1878 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1879 for id in task.superseded_attempts(last_run_succeeded) {
1880 let mut state = match RunState::load_under(id, home) {
1881 Ok(s) => s,
1882 Err(e) => {
1883 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1884 continue;
1885 }
1886 };
1887 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1888 continue;
1889 }
1890 let daemon_claims = is_working_on(home, id, now);
1891 if state.liveness(daemon_claims) == Liveness::Live {
1892 continue;
1893 }
1894 state.status = RunStatus::Superseded;
1895 if let Err(e) = state.save_under(home) {
1896 tracing::warn!("could not mark run {id} superseded: {e:#}");
1897 }
1898 }
1899}
1900
1901fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1923 for task in queue.list() {
1924 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1925 continue;
1926 }
1927 supersede_prior_runs(&task, home);
1928 }
1929}
1930
1931fn settle_and_diagnose(
1938 task: &mut Task,
1939 verdict: Verdict,
1940 detail: &str,
1941 max_attempts: usize,
1942 state: &RunState,
1943) {
1944 let p = phrases(&state.config.graph.language);
1945 if let Some(d) = &state.merge_decision {
1948 use crate::merge_decision as md;
1949 if task.runs.last().is_some_and(|id| id != &state.id) {
1950 return;
1951 }
1952 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1953 task.succeed();
1954 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1955 if state.liveness(false) != Liveness::Dead {
1956 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1957 return;
1958 }
1959 let replacement = md::Replacement {
1960 question: d.question.clone(),
1961 run: state.id.clone(),
1962 pr: d.target.pr.clone(),
1963 agent: agent.to_owned(),
1964 context: format!(
1965 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1966 d.target.pr,
1967 state.id,
1968 serde_json::to_string(&state.reviews).unwrap_or_default()
1969 ),
1970 };
1971 task.requeue();
1972 task.pr_recovery = None;
1973 task.review_of = None;
1974 task.replacement = Some(replacement);
1975 } else {
1976 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1977 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1978 } 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())) }));
1979 }
1980 task.mark_action_applied(&d.question);
1981 if let Some(pass) = state.passes.last() {
1982 task.record_pass_at(
1983 &state.id,
1984 pass.index,
1985 Some(pass.started_at),
1986 task.attempts,
1987 None,
1988 );
1989 }
1990 return;
1991 }
1992 if let Some(replacement) = &task.replacement
1993 && !state.parked
1994 && state.resource_block.is_none()
1995 && (state.viable().is_empty()
1996 || (state.status == RunStatus::Blocked && state.tally.is_none()))
1997 {
1998 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)));
1999 return;
2000 }
2001 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2002 let mut agents: Vec<_> = state
2003 .quota
2004 .iter()
2005 .filter(|q| {
2006 q.cause == crate::agent::QuotaCause::Authentication
2007 && state
2008 .passes
2009 .last()
2010 .is_none_or(|pass| q.at >= pass.started_at)
2011 })
2012 .map(|q| q.agent.as_str())
2013 .collect();
2014 agents.sort_unstable();
2015 agents.dedup();
2016 if !agents.is_empty() {
2017 task.stall(detail);
2018 task.notice_cause("agent-authentication", None, None);
2019 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2020 return;
2021 }
2022 }
2023 let attempts_before = task.attempts;
2024 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2031 task.notice_cause(
2032 &format!("resource:{}:{}", block.kind, block.node),
2033 None,
2034 None,
2035 );
2036 task.last_error = Some(detail.to_owned());
2037 task.diagnostic = None;
2038 task.attempts = task.attempts.saturating_sub(1);
2039 if block.kind == "agent authentication" {
2040 task.hold_machine(Some(format!(
2041 "[authentication] {}; no attempt was spent",
2042 block.detail
2043 )));
2044 } else if block.kind == "agent usage limit" {
2045 if let Some(agent) = &state.config.graph.selected_implementer {
2047 task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2048 } else {
2049 task.status = TaskStatus::Failed;
2050 task.last_error = Some(block.detail.clone());
2051 }
2052 } else if block.kind == "disk pressure" {
2053 task.hold_machine(Some(format!(
2054 "{}{}",
2055 crate::disk::RUNNING_PRESSURE,
2056 block.detail
2057 )));
2058 } else {
2059 task.hold_machine(Some(format!(
2060 "{}{}; no attempt was spent; resume to retry the affected operation",
2061 crate::cache::RESOURCE_HOLD,
2062 block.description()
2063 )));
2064 }
2065 if let Some(pass) = state.passes.last() {
2066 task.record_pass_at(
2067 &state.id,
2068 pass.index,
2069 Some(pass.started_at),
2070 attempts_before,
2071 None,
2072 );
2073 }
2074 return;
2075 }
2076 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2077 state.parked
2078 && state.status == RunStatus::Landing
2079 && state
2080 .pr_pushed_head
2081 .as_ref()
2082 .is_none_or(|h| h == &hold.head)
2083 && task.runs.last() == Some(&state.id)
2084 }) {
2085 let pass = state.passes.last().map_or(0, |p| p.index);
2088 if !task
2089 .passes
2090 .iter()
2091 .any(|p| p.run == state.id && p.pass_index == pass)
2092 {
2093 task.attempts = task.attempts.saturating_sub(1);
2094 }
2095 task.hold_machine(Some(format!(
2096 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2097 hold.question
2098 )));
2099 task.last_error = Some(detail.to_owned());
2100 task.diagnostic = None;
2101 task.record_pass_at(
2102 &state.id,
2103 pass,
2104 state.passes.last().map(|p| p.started_at),
2105 attempts_before,
2106 Some(crate::run::ParkCause::Question),
2107 );
2108 return;
2109 }
2110 let unresolved = task.hold_notice_cause.clone();
2111 if state.base_sync_blocked() {
2112 task.hold_machine(Some(detail.to_owned()));
2114 task.last_error = Some(detail.to_owned());
2115 } else if !verdict.parked
2116 && task
2117 .pr_recovery
2118 .as_ref()
2119 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2120 && matches!(
2121 verdict.status,
2122 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2123 )
2124 {
2125 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2126 task.succeed();
2127 } else {
2128 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()));
2129 }
2130 } else if !verdict.parked
2131 && task.pr_recovery.is_some()
2132 && matches!(
2133 verdict.status,
2134 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2135 )
2136 && !verdict.quota_hit
2137 {
2138 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.")));
2139 } else {
2140 settle_in(task, verdict, detail, max_attempts, p);
2141 }
2142 if !verdict.parked
2143 && !verdict.quota_hit
2144 && matches!(
2145 verdict.status,
2146 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2147 )
2148 {
2149 task.recovery_failed(state);
2150 }
2151 if state.prep_failure.is_some() {
2152 task.hold_notice_cause = unresolved;
2155 task.startup_notice_cause("startup-candidates");
2156 }
2157 if let Some(pass) = state.passes.last() {
2160 let parked = match &pass.end {
2161 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2162 _ => None,
2163 };
2164 task.record_pass_at(
2165 &state.id,
2166 pass.index,
2167 Some(pass.started_at),
2168 attempts_before,
2169 parked,
2170 );
2171 }
2172 if task.status == TaskStatus::Held {
2173 if state.base_sync_blocked() {
2174 task.base_sync_notice(state);
2175 } else if state.prep_failure.is_none() {
2176 task.notice_cause(
2177 label(verdict.status),
2178 Some(&state.id),
2179 state.passes.last().map(|p| p.index),
2180 );
2181 }
2182 task.diagnostic = diagnostic(state);
2183 note_open_question(task, &state.id, p);
2184 }
2185}
2186
2187fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2202 let Some(home) = crate::run::try_home() else {
2203 return;
2204 };
2205 let open = Questions::at(home.join("questions")).open_for(run);
2206 let Some(q) = open.first() else {
2207 return;
2208 };
2209 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2210 decisions.sort_unstable();
2211 task.notice_cause(
2212 &format!("questions:{}", decisions.join(",")),
2213 Some(run),
2214 None,
2215 );
2216 let base = task.hold_reason.clone().unwrap_or_default();
2217 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2218}
2219
2220fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2231 match last_run {
2232 Some(state) => {
2233 let verdict = Verdict {
2234 status: state.status,
2235 left_pr: state.pr.is_some(),
2236 quota_hit: state.quota.iter().any(|loss| {
2237 state
2238 .passes
2239 .last()
2240 .is_none_or(|pass| loss.at >= pass.started_at)
2241 }),
2242 parked: state.parked,
2243 no_viable_candidates: state.viable().is_empty(),
2244 };
2245 let detail = format!(
2246 "{}{}",
2247 phrases(&state.config.graph.language).recovered_running,
2248 describe(&state)
2249 );
2250 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2251 }
2252 None => {
2253 let why = phrases(language).no_run_to_recover;
2256 task.last_error = Some(why.to_owned());
2257 task.notice_cause("missing-run", None, None);
2260 task.hold_machine(Some(why.to_owned()));
2261 }
2262 }
2263}
2264
2265fn reclaim_orphaned_running(
2287 queue: &Queue,
2288 max_attempts: usize,
2289 live_workers: &std::collections::BTreeSet<String>,
2290) -> Vec<String> {
2291 let mut reclaimed = Vec::new();
2292 for listed in queue.list() {
2293 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2294 continue;
2295 }
2296 let Ok(_claim) = queue.claim(&listed.id) else {
2297 continue;
2298 };
2299 let Ok(mut task) = queue.get(&listed.id) else {
2303 continue;
2304 };
2305 if task.status != TaskStatus::Running {
2306 continue;
2307 }
2308 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2309 if let Some(state) = &last_run
2319 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2320 {
2321 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2322 }
2323 let language = if last_run.is_none() {
2324 language_of(&task, Path::new("."))
2325 } else {
2326 String::new()
2327 };
2328 reclaim(&mut task, last_run, max_attempts, &language);
2329 if task.status == TaskStatus::Done {
2330 supersede_prior_runs(&task, &crate::run::home());
2331 }
2332 record(queue, &mut task);
2333 reclaimed.push(task.id.clone());
2334 }
2335 reclaimed
2336}
2337
2338fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2370 reclaim_abandoned_runs_with(
2371 home,
2372 now,
2373 crate::proc::pid_status,
2374 crate::proc::process_started_at,
2375 )
2376}
2377
2378fn reclaim_abandoned_runs_with<F, G>(
2384 home: &Path,
2385 now: Timestamp,
2386 query: F,
2387 identity: G,
2388) -> Vec<String>
2389where
2390 F: Fn(u32) -> Option<bool>,
2391 G: Fn(u32) -> Option<String>,
2392{
2393 let mut abandoned = Vec::new();
2394 for entry in std::fs::read_dir(home.join("runs"))
2395 .into_iter()
2396 .flatten()
2397 .flatten()
2398 {
2399 let id = entry.file_name().to_string_lossy().into_owned();
2400 if !crate::run::is_run_id(&id) {
2401 continue;
2402 }
2403 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2406 continue;
2407 };
2408 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2416 continue;
2417 };
2418 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2419 continue;
2420 };
2421 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2422 continue;
2423 }
2424 let daemon_claims = is_working_on(home, &id, now);
2436 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2437 != crate::run::Liveness::Dead
2438 {
2439 continue;
2440 }
2441 state.abandon("daemon");
2442 if let Err(e) = state.save_under(home) {
2443 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2444 continue;
2445 }
2446 if let Some(notice) = notices::run_ended(&state) {
2449 notices::raise_in(home, notice);
2450 }
2451 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2459 tracing::warn!("abandon questions for {id}: {e:#}");
2460 }
2461 abandoned.push(id);
2462 }
2463 abandoned
2464}
2465
2466#[derive(Debug, Clone, Serialize, Deserialize)]
2467struct TaskWorker {
2468 opts: Opts,
2469 queue: PathBuf,
2470 task: String,
2471 #[serde(default)]
2472 lane: PermitKind,
2473 #[serde(default)]
2474 standalone: bool,
2475}
2476
2477fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2478 Ok(crate::worker::active(home)?
2479 .into_iter()
2480 .filter(|job| job.kind == "task")
2481 .collect())
2482}
2483
2484fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2485 task_jobs(home)?
2486 .into_iter()
2487 .filter_map(
2488 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2489 Ok(request) if !request.standalone => Some(Ok(job)),
2490 Ok(_) => None,
2491 Err(error) => Some(Err(error.into())),
2492 },
2493 )
2494 .collect()
2495}
2496
2497#[must_use]
2499pub fn managed(home: &Path) -> bool {
2500 match crate::worker::active(home) {
2501 Err(error) => {
2502 tracing::error!("cannot determine scheduler ownership: {error:#}");
2503 true
2504 }
2505 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2506 Ok(_) => {
2507 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2508 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2509 }
2510 }
2511}
2512
2513pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2515 anyhow::ensure!(
2516 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2517 "the scheduler is stopping; wait for retirement before starting it again"
2518 );
2519 crate::worker::spawn(
2520 home,
2521 "scheduler",
2522 "scheduler",
2523 serde_json::to_value(opts.absolute()?)?,
2524 )
2525 .await
2526}
2527
2528fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2529 home.join("worker-parks").join(format!("{}.json", job.id))
2530}
2531
2532fn request_task_park(
2533 home: &Path,
2534 job: &crate::worker::Job,
2535 cause: crate::run::ParkCause,
2536) -> Result<()> {
2537 let path = park_request_path(home, job);
2538 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2539 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2540 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2541}
2542
2543pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2545 if control == crate::worker::Control::Park {
2546 for job in owned_task_jobs(home)? {
2547 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2548 }
2549 }
2550 crate::worker::request(home, "scheduler", control)
2551}
2552
2553pub async fn restart_detached(home: &Path) -> Result<()> {
2555 let active = crate::worker::active(home)?;
2556 let prior = active.into_iter().find(|job| job.kind == "scheduler");
2557 if prior.is_none() && !managed(home) {
2558 return Ok(());
2559 }
2560 let opts: Opts = match prior {
2561 Some(job) => serde_json::from_value(job.payload)?,
2562 None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2563 };
2564 request_control(home, crate::worker::Control::Stop)?;
2565 loop {
2566 let reserved = crate::worker::active(home)?
2567 .iter()
2568 .any(|job| job.kind == "scheduler");
2569 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2570 break;
2571 }
2572 tokio::time::sleep(Duration::from_millis(100)).await;
2573 }
2574 spawn_detached(home, &opts).await?;
2575 Ok(())
2576}
2577
2578pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2580 let opts: Opts = serde_json::from_value(payload)?;
2581 let _ = home;
2582 serve_until(opts, Stop::new()).await
2583}
2584
2585pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2587 let request: TaskWorker = serde_json::from_value(payload)?;
2588 let queue = Queue::at(request.queue);
2589 let key = format!("task:{}", request.task);
2590 let job = task_jobs(home)?
2591 .into_iter()
2592 .find(|job| job.key == key)
2593 .context("task worker reservation is missing")?;
2594 let park_path = park_request_path(home, &job);
2595 let _claim = loop {
2598 match queue.claim(&request.task) {
2599 Ok(claim) => break claim,
2600 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2603 return Err(e.context("claim the task for its worker"));
2604 }
2605 Err(_) => {
2606 sweep_stale_claims(&queue, STALE_CLAIM);
2607 tokio::time::sleep(Duration::from_millis(50)).await;
2608 }
2609 }
2610 };
2611 let mut task = queue.get(&request.task)?;
2612 if !task.status.runnable()
2613 || (!request.standalone
2614 && request.lane
2615 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2616 {
2617 return Ok(());
2618 }
2619 let stop = Stop::new();
2620 let watcher = {
2621 let home = home.to_path_buf();
2622 let stop = stop.clone();
2623 let park_path = park_path.clone();
2624 tokio::spawn(async move {
2625 loop {
2626 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2627 let cause = std::fs::read(&park_path)
2628 .ok()
2629 .and_then(|body| serde_json::from_slice(&body).ok())
2630 .unwrap_or(crate::run::ParkCause::Operator);
2631 stop.park(cause);
2632 return;
2633 }
2634 tokio::time::sleep(Duration::from_millis(200)).await;
2635 }
2636 })
2637 };
2638 let quota = if request.standalone {
2639 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2640 } else {
2641 let status = Arc::new(Mutex::new(Status::new()));
2642 Box::pin(attempt(
2643 &request.opts,
2644 &queue,
2645 &status,
2646 &stop,
2647 crate::graph::Pause::new(),
2648 &mut task,
2649 ))
2650 .await
2651 };
2652 watcher.abort();
2653 let _ = std::fs::remove_file(park_path);
2654 persist_cooldown(home, "a).await?;
2655 Ok(())
2656}
2657
2658pub async fn spawn_claimed(
2661 home: &Path,
2662 opts: &Opts,
2663 queue: &Queue,
2664 task: &Task,
2665 claim: crate::queue::Claim,
2666) -> Result<crate::worker::Job> {
2667 let request = TaskWorker {
2668 opts: opts.absolute()?,
2669 queue: std::path::absolute(queue.root())?,
2670 task: task.id.clone(),
2671 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2672 standalone: true,
2673 };
2674 let job = crate::worker::spawn(
2675 home,
2676 "task",
2677 &format!("task:{}", task.id),
2678 serde_json::to_value(request)?,
2679 )
2680 .await?;
2681 drop(claim);
2682 Ok(job)
2683}
2684
2685pub async fn run_detached_claimed(
2688 opts: &Opts,
2689 queue: &Queue,
2690 task: &mut Task,
2691 claim: crate::queue::Claim,
2692) -> Result<()> {
2693 let home = crate::run::home();
2694 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2695 loop {
2696 crate::worker::active(&home)?;
2699 let current = crate::worker::get(&home, &job.id)?;
2700 if matches!(
2701 current.status,
2702 crate::worker::Status::Finished | crate::worker::Status::Failed
2703 ) {
2704 *task = queue.get(&task.id)?;
2705 anyhow::ensure!(
2706 current.status != crate::worker::Status::Failed,
2707 "task worker failed: {}",
2708 current.result.as_deref().unwrap_or("unknown failure")
2709 );
2710 return Ok(());
2711 }
2712 tokio::time::sleep(Duration::from_millis(200)).await;
2713 }
2714}
2715
2716async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2717 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2718 let _lease = loop {
2719 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2720 break lease;
2721 }
2722 tokio::time::sleep(Duration::from_millis(10)).await;
2723 };
2724 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2725 let path = home.join("task-quota-cooldown.json");
2726 let temporary = path.with_extension("json.tmp");
2727 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2728 std::fs::rename(temporary, path)?;
2729 }
2730 }
2731 Ok(())
2732}
2733
2734fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2735 match std::fs::read(home.join("task-quota-cooldown.json")) {
2736 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2737 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2738 Err(error) => Err(error.into()),
2739 }
2740}
2741
2742pub async fn serve(opts: Opts) -> Result<()> {
2748 tracing::info!(
2749 "automatic update and restart requires magi web; standalone serve does not restart"
2750 );
2751 serve_until(opts, Stop::new()).await
2752}
2753
2754pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2765 let opts = opts.absolute()?;
2766 let home = crate::run::home();
2767 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2768 .context("another scheduler already owns this home")?;
2769 if let Some(reading) = read_status(&home)
2770 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2771 {
2772 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2773 }
2774 if !crate::worker::active(&home)?
2775 .iter()
2776 .any(|job| job.kind == "scheduler")
2777 {
2778 crate::worker::clear_control(&home, "scheduler")?;
2779 }
2780 std::fs::write(
2781 home.join("scheduler-options.json"),
2782 serde_json::to_vec(&opts)?,
2783 )?;
2784 let control = {
2785 let home = home.clone();
2786 let stop = stop.clone();
2787 tokio::spawn(async move {
2788 loop {
2789 match crate::worker::control(&home, "scheduler").ok().flatten() {
2790 Some(crate::worker::Control::Park) => {
2791 let _ = request_control(&home, crate::worker::Control::Park);
2792 stop.park(crate::run::ParkCause::Operator);
2793 break;
2794 }
2795 Some(crate::worker::Control::Stop) => {
2796 stop.stop();
2797 break;
2798 }
2799 None => {}
2800 }
2801 tokio::time::sleep(Duration::from_millis(100)).await;
2802 }
2803 })
2804 };
2805 let signal = {
2806 let stop = stop.clone();
2807 tokio::spawn(async move {
2808 if tokio::signal::ctrl_c().await.is_ok() {
2809 stop.stop();
2810 tracing::info!("scheduler shutdown requested; independent workers continue");
2811 }
2812 })
2813 };
2814
2815 let worktrees_root = opts
2816 .worktrees_root
2817 .clone()
2818 .unwrap_or_else(crate::run::default_worktree_root);
2819 let outcome = drive(
2820 &opts,
2821 &Queue::open(),
2822 &status_path(),
2823 &crate::run::home(),
2824 &worktrees_root,
2825 &stop,
2826 )
2827 .await;
2828
2829 signal.abort();
2830 control.abort();
2831 outcome
2832}
2833
2834async fn drive(
2847 opts: &Opts,
2848 queue: &Queue,
2849 status_file: &Path,
2850 home: &Path,
2851 worktrees_root: &Path,
2852 stop: &Stop,
2853) -> Result<()> {
2854 let recovery_cfg = prepare(&opts.repo, opts).ok();
2862 let daemon_cfg = recovery_cfg
2863 .as_ref()
2864 .map(|c| c.daemon.clone())
2865 .unwrap_or_default();
2866 let reconciled = crate::driver::reconcile(home);
2867 if !reconciled.is_empty() {
2868 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2869 }
2870 let mut initial_status = Status::new();
2871 let owned = owned_task_jobs(home)?;
2872 initial_status.current = current_work(home, Timestamp::now())
2873 .into_iter()
2874 .filter(|current| {
2875 owned
2876 .iter()
2877 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2878 })
2879 .collect();
2880 initial_status.idle = initial_status.current.is_empty();
2881 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2882 recovery_cfg.as_ref(),
2883 daemon_cfg.max_deputies,
2884 ));
2885 let status = Arc::new(Mutex::new(initial_status));
2886 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2887 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2888
2889 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2895
2896 tracing::info!(
2897 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2898 queue.root().display(),
2899 opts.poll.as_secs(),
2900 opts.max_attempts,
2901 concurrency,
2902 if daemon_cfg.pause_for_interrupts {
2903 ", interrupts enabled"
2904 } else {
2905 ""
2906 }
2907 );
2908
2909 let outcome = tokio::select! {
2910 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2911 max_concurrent: concurrency,
2912 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2913 recovery_cfg,
2914 }) => outcome,
2915 () = async {
2916 while !stop.stopped() {
2917 tokio::time::sleep(Duration::from_millis(25)).await;
2918 }
2919 } => {
2920 if stop.parking() {
2921 request_control(home, crate::worker::Control::Park)?;
2922 }
2923 Ok(())
2924 }
2925 };
2926
2927 stop.busy.store(0, Ordering::SeqCst);
2928 beat.abort();
2929 clear_status_at(status_file);
2930 outcome
2931}
2932
2933pub(crate) fn release_watch_settings_from_config(
2936 home: &Path,
2937 repo: &Path,
2938 cfg: &Config,
2939) -> (Vec<PathBuf>, u64) {
2940 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2941 .into_iter()
2942 .map(|r| r.path)
2943 .collect();
2944 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2947 .list()
2948 .into_iter()
2949 .map(|t| t.repo)
2950 .collect();
2951 let runs = home.join("runs");
2952 for id in crate::run::list_ids_in(&runs) {
2953 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2954 .ok()
2955 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2956 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2957 known.extend(repo);
2958 }
2959 for k in known {
2960 let k = k.canonicalize().unwrap_or(k);
2961 if k.join(".git").exists() && !paths.contains(&k) {
2962 paths.push(k);
2963 }
2964 }
2965 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2966 if !paths.contains(&own) {
2967 paths.push(own);
2968 }
2969 (paths, cfg.daemon.release_stall_minutes)
2970}
2971
2972const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2974
2975async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2981 loop {
2982 tokio::time::sleep(HEARTBEAT).await;
2983 let snapshot = {
2984 let mut guard = lock(&status);
2985 guard.updated_at = Timestamp::now();
2986 guard.clone()
2987 };
2988 if let Err(e) = write_status_to(&path, &snapshot) {
2989 tracing::warn!("could not refresh the daemon status file: {e:#}");
2992 }
2993 }
2994}
2995
2996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2999enum LandResume {
3000 NotLanding,
3003 StillWaiting,
3008 Ready,
3012}
3013
3014fn land_resume_state(task: &Task) -> LandResume {
3018 let Some(run_id) = task.runs.last() else {
3019 return LandResume::NotLanding;
3020 };
3021 let Ok(state) = RunState::load(run_id) else {
3022 return LandResume::NotLanding;
3023 };
3024 if !state.parked {
3025 return LandResume::NotLanding;
3026 }
3027 if state.status == RunStatus::Landing
3028 && state.land_approval.as_ref().is_some_and(|binding| {
3029 ask::Questions::open()
3030 .get(&binding.question)
3031 .is_ok_and(|q| {
3032 q.run == state.id
3033 && q.resolution()
3034 .as_deref()
3035 .is_some_and(crate::merge_decision::stops)
3036 })
3037 })
3038 {
3039 return LandResume::Ready;
3040 }
3041 if !implementers_match(task, &state) {
3042 return LandResume::NotLanding;
3043 }
3044 let node = if state.status == RunStatus::Landing {
3048 land::APPROVAL_NODE
3049 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3050 crate::github_text::ASK_NODE
3051 } else {
3052 return LandResume::NotLanding;
3053 };
3054 let store = ask::Questions::open();
3055 let waiting = store
3056 .list()
3057 .into_iter()
3058 .filter(|q| &q.run == run_id && q.node == node)
3059 .max_by(|a, b| a.id.cmp(&b.id));
3060 let Some(mut q) = waiting else {
3061 return LandResume::Ready;
3062 };
3063 if !q.status.open() {
3064 if q.resolution().as_deref() == Some(land::REPAIR) {
3067 return if state.liveness(false) == Liveness::Live {
3068 LandResume::StillWaiting
3069 } else {
3070 LandResume::NotLanding
3071 };
3072 }
3073 return LandResume::Ready;
3074 }
3075 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3082 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3083 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3084 q.abandon(format!(
3085 "no answer within {}s of asking",
3086 timeout.as_secs().max(1)
3087 ));
3088 if store.put(&mut q).is_ok() {
3091 return LandResume::Ready;
3092 }
3093 }
3094 LandResume::StillWaiting
3095}
3096
3097const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3105
3106const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3118
3119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3132enum Interrupt {
3133 Idle,
3135 Parking {
3147 parked: Vec<String>,
3148 interrupt_task: String,
3149 },
3150 Running {
3158 parked: Vec<String>,
3159 interrupt_task: String,
3160 },
3161 Resuming { parked: Vec<String> },
3168}
3169
3170fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3191 match state {
3192 Interrupt::Idle => {
3193 if in_flight.len() != 1 {
3205 return Interrupt::Idle;
3206 }
3207 match runnable.iter().find(|t| t.interrupt) {
3208 Some(t) => Interrupt::Parking {
3209 parked: in_flight.to_vec(),
3210 interrupt_task: t.id.clone(),
3211 },
3212 None => Interrupt::Idle,
3213 }
3214 }
3215 Interrupt::Parking {
3216 parked,
3217 interrupt_task,
3218 } => {
3219 if in_flight.iter().any(|id| parked.contains(id)) {
3220 Interrupt::Parking {
3222 parked,
3223 interrupt_task,
3224 }
3225 } else if in_flight.contains(&interrupt_task) {
3226 Interrupt::Running {
3227 parked,
3228 interrupt_task,
3229 }
3230 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3231 Interrupt::Parking {
3235 parked,
3236 interrupt_task,
3237 }
3238 } else {
3239 Interrupt::Resuming { parked }
3244 }
3245 }
3246 Interrupt::Running {
3247 parked,
3248 interrupt_task,
3249 } => {
3250 if in_flight.contains(&interrupt_task) {
3251 Interrupt::Running {
3252 parked,
3253 interrupt_task,
3254 }
3255 } else {
3256 Interrupt::Resuming { parked }
3262 }
3263 }
3264 Interrupt::Resuming { parked } => {
3265 if in_flight.iter().any(|id| parked.contains(id)) {
3266 Interrupt::Idle
3272 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3273 Interrupt::Resuming { parked }
3274 } else {
3275 Interrupt::Idle
3278 }
3279 }
3280 }
3281}
3282
3283fn advance_interrupt_tick(
3289 enabled: bool,
3290 state: Interrupt,
3291 in_flight: &[String],
3292 runnable: &[Task],
3293) -> Interrupt {
3294 if !enabled {
3295 return Interrupt::Idle;
3296 }
3297 advance_interrupt(state, in_flight, runnable)
3298}
3299
3300fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3305 match state {
3306 Interrupt::Idle => candidates,
3307 Interrupt::Parking {
3308 parked,
3309 interrupt_task,
3310 } => {
3311 if in_flight.iter().any(|id| parked.contains(id)) {
3312 Vec::new()
3313 } else {
3314 candidates
3315 .into_iter()
3316 .filter(|t| &t.id == interrupt_task)
3317 .collect()
3318 }
3319 }
3320 Interrupt::Running { .. } => Vec::new(),
3321 Interrupt::Resuming { parked } => candidates
3329 .into_iter()
3330 .find(|t| parked.contains(&t.id))
3331 .into_iter()
3332 .collect(),
3333 }
3334}
3335
3336struct DispatchLimits {
3340 max_concurrent: usize,
3343 pause_for_interrupts: bool,
3345 recovery_cfg: Option<Config>,
3346}
3347
3348#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3357enum PermitKind {
3358 None,
3363 Urgent,
3370 #[default]
3373 Ordinary,
3374}
3375
3376fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3379 if priority {
3380 PermitKind::None
3381 } else if urgent {
3382 PermitKind::Urgent
3383 } else {
3384 PermitKind::Ordinary
3385 }
3386}
3387
3388fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3389 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3390 (0usize, 0usize),
3391 |(ordinary, urgent), request| match request.lane {
3392 PermitKind::Ordinary => (ordinary + 1, urgent),
3393 PermitKind::Urgent => (ordinary, urgent + 1),
3394 PermitKind::None => (ordinary, urgent),
3395 },
3396 );
3397 (
3398 limit.saturating_sub(ordinary),
3399 1usize.saturating_sub(urgent),
3400 )
3401}
3402
3403struct DispatchClaim {
3404 task: Task,
3405 claim: crate::queue::Claim,
3406 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3407}
3408
3409fn claim_dispatch(
3412 queue: &Queue,
3413 candidate: &Task,
3414 cooling_down: bool,
3415 ordinary: &Arc<tokio::sync::Semaphore>,
3416 urgent: &Arc<tokio::sync::Semaphore>,
3417) -> Option<DispatchClaim> {
3418 let Ok(claim) = queue.claim(&candidate.id) else {
3419 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3420 return None;
3421 };
3422 let task = match queue.get(&candidate.id) {
3423 Ok(t) if t.status.runnable() => t,
3424 Ok(_) => return None,
3425 Err(e) => {
3426 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3427 return None;
3428 }
3429 };
3430 let resume = land_resume_state(&task);
3431 if resume == LandResume::StillWaiting {
3432 return None;
3433 }
3434 let priority = resume == LandResume::Ready;
3435 if !priority && cooling_down {
3436 return None;
3437 }
3438 let permit = match permit_kind(priority, task.urgent) {
3441 PermitKind::None => None,
3442 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3443 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3444 };
3445 let stamp = Timestamp::now();
3448 let mut task = task;
3449 task.dispatched_at = Some(stamp);
3450 if let Err(e) = queue.modify(&task.id, |t| {
3451 t.dispatched_at = Some(stamp);
3452 true
3453 }) {
3454 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3455 }
3456 Some(DispatchClaim {
3457 task,
3458 claim,
3459 permit,
3460 })
3461}
3462
3463#[derive(Serialize, Deserialize)]
3482struct ServiceWorker {
3483 opts: Opts,
3484 queue: PathBuf,
3485 worktrees_root: PathBuf,
3486 operation: String,
3487}
3488
3489fn load_conductor(home: &Path) -> Result<Conductor> {
3490 match std::fs::read(home.join("conductor-state.json")) {
3491 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3492 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3493 Err(error) => Err(error.into()),
3494 }
3495}
3496
3497fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3498 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3499 .into_iter()
3500 .map(|c| c.task)
3501 .collect();
3502 let stalled = stalled_tasks(queue, home, Timestamp::now());
3503 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3504 let finished = finished_tasks(queue)
3505 .into_iter()
3506 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3507 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3508 .collect();
3509 let queued = queued_tasks(queue)
3510 .into_iter()
3511 .filter(|t| !live.contains(&t.id))
3512 .collect();
3513 (queued, stalled, finished)
3514}
3515
3516async fn start_service(
3517 home: &Path,
3518 opts: &Opts,
3519 queue: &Queue,
3520 worktrees_root: &Path,
3521 operation: &str,
3522 cfg: Option<&Config>,
3523 busy: bool,
3524) -> Result<()> {
3525 let fetch_cfg = if operation == "fetch" {
3528 match prepare(&opts.repo, opts) {
3529 Ok(cfg) => Some(cfg),
3530 Err(error) => {
3531 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3532 return Ok(());
3533 }
3534 }
3535 } else {
3536 None
3537 };
3538 let cfg = fetch_cfg.as_ref().or(cfg);
3539 let ticks = home.join("service-ticks");
3540 std::fs::create_dir_all(&ticks)?;
3541 let receipt = ticks.join(format!("daemon-{operation}"));
3542 let last = std::fs::read(&receipt)
3543 .ok()
3544 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3545 let interval = match operation {
3546 "disk-pressure" => 30,
3547 "cache" => CACHE_CHECK_INTERVAL_SECS,
3548 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3549 _ => opts.poll.as_secs().max(1),
3550 };
3551 let now = Timestamp::now();
3552 if !cache_check_due(last, now, interval) {
3553 return Ok(());
3554 }
3555 let key = format!("service:daemon-{operation}");
3556 if crate::worker::active(home)?
3557 .iter()
3558 .any(|job| job.key == key)
3559 {
3560 return Ok(());
3561 }
3562 let eligible = match operation {
3563 "conductor" => {
3564 let (queued, stalled, finished) = conductor_work(queue, home);
3565 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3566 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3567 }
3568 "maintenance" => Questions::at(home.join("questions"))
3569 .list()
3570 .iter()
3571 .any(|q| {
3572 q.chosen_action().is_some_and(|action| action.maintenance())
3573 && !home
3574 .join("choice-actions")
3575 .join(format!("{}.json", q.id))
3576 .exists()
3577 }),
3578 "housekeeping" => !busy && runnable(queue).is_empty(),
3579 "cache" => {
3580 !busy
3581 && !runnable(queue).is_empty()
3582 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3583 }
3584 "disk-pressure" => busy,
3585 "fetch" => {
3586 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3587 }
3588 _ => false,
3589 };
3590 if !eligible {
3591 return Ok(());
3592 }
3593 let request = ServiceWorker {
3594 opts: opts.absolute()?,
3595 queue: std::path::absolute(queue.root())?,
3596 worktrees_root: std::path::absolute(worktrees_root)?,
3597 operation: operation.to_owned(),
3598 };
3599 if let Err(error) =
3600 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3601 {
3602 tracing::warn!(operation, "could not launch daemon service: {error:#}");
3603 }
3604 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3605 Ok(())
3606}
3607
3608pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3611 let request: ServiceWorker = serde_json::from_value(payload)?;
3612 let opts = &request.opts;
3613 let queue = Queue::at(request.queue);
3614 let questions = Questions::at(home.join("questions"));
3615 match request.operation.as_str() {
3616 "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3617 "conductor" => {
3618 let path = home.join("conductor-state.json");
3619 let mut conductor = load_conductor(home)?;
3620 let (queued, stalled, finished) = conductor_work(&queue, home);
3621 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3622 && conductor.worth_a_look(&queue, &stalled, &finished)
3623 {
3624 let cfg = prepare(&opts.repo, opts)?;
3625 conductor
3626 .maybe_run(
3627 &cfg,
3628 &opts.repo,
3629 &queue,
3630 &questions,
3631 home,
3632 &queued,
3633 &stalled,
3634 &finished,
3635 opts.max_attempts,
3636 )
3637 .await;
3638 let temporary = path.with_extension("json.tmp");
3639 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3640 std::fs::rename(temporary, path)?;
3641 }
3642 }
3643 "fetch" => {
3644 let cfg = prepare(&opts.repo, opts)?;
3645 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3646 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3647 tracing::debug!("fetch origins: {outcome:?}");
3648 }
3649 }
3650 "cache" => {
3651 if task_jobs(home)?.is_empty() {
3652 let mut checked = None;
3653 maybe_prune_cache_between_runs(
3654 &opts.repo,
3655 opts,
3656 home,
3657 &Stop::new(),
3658 &mut checked,
3659 Timestamp::now(),
3660 )
3661 .await;
3662 }
3663 }
3664 "disk-pressure" => {
3665 if let Ok(cfg) = prepare(&opts.repo, opts) {
3666 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3667 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3668 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3669 }
3670 for current in current_work(home, Timestamp::now()) {
3671 if let Ok(state) = RunState::load_under(¤t.run, home)
3672 && let Some(reason) = disk_gate(&state.repo, &state.config)
3673 {
3674 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3675 job.key.strip_prefix("task:") == Some(current.task.as_str())
3676 }) {
3677 request_task_park(
3678 home,
3679 &job,
3680 crate::run::ParkCause::Interrupt {
3681 reason: reason.clone(),
3682 },
3683 )?;
3684 }
3685 notices::raise_in(
3686 home,
3687 Notice::warn(
3688 "disk:pressure",
3689 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3690 ),
3691 );
3692 }
3693 }
3694 }
3695 }
3696 "housekeeping" => {
3697 if task_jobs(home)?.is_empty() {
3698 if let Ok(cfg) = prepare(&opts.repo, opts) {
3699 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3700 }
3701 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3702 resweep_superseded_attempts(&queue, home);
3703 triage_held(&queue, home, opts).await;
3704 }
3705 }
3706 operation => bail!("unknown daemon service {operation}"),
3707 }
3708 Ok(())
3709}
3710
3711fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3715 let key = format!("task:{}", request.task);
3716 let payload = serde_json::to_value(request)?;
3717 if crate::worker::active(home)?
3718 .iter()
3719 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3720 {
3721 tracing::warn!(
3722 "task {} acquired a competing worker reservation: {error:#}",
3723 crate::run::short_of(&request.task)
3724 );
3725 return Ok(());
3726 }
3727 tracing::error!("task worker startup stopped dispatch: {error:#}");
3728 notices::raise_in(
3729 home,
3730 Notice::error(
3731 "loop:worker-startup",
3732 format!("Task {} worker could not be started or acknowledged. Scheduler dispatch stopped; already reserved workers may still complete. Inspect the local execution log and reservation worker.log for startup details.", request.task),
3735 ).link(Link::Task { id: request.task.clone() }),
3736 );
3737 Err(error).with_context(|| {
3738 format!(
3739 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3740 crate::run::short_of(&request.task)
3741 )
3742 })
3743}
3744
3745async fn poll(
3746 opts: &Opts,
3747 queue: &Queue,
3748 status: &Arc<Mutex<Status>>,
3749 home: &Path,
3750 worktrees_root: &Path,
3751 stop: &Stop,
3752 limits: DispatchLimits,
3753) -> Result<()> {
3754 let mut attempted = Vec::new();
3755 let mut settling_once_services = false;
3756 let interrupt_path = home.join("scheduler-interrupt.json");
3757 let mut interrupt = match std::fs::read(&interrupt_path) {
3758 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3759 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3760 Err(error) => return Err(error.into()),
3761 };
3762 let mut previous = std::collections::BTreeSet::<String>::new();
3763 while !stop.stopped() {
3764 let jobs: Vec<_> = crate::worker::active(home)?
3765 .into_iter()
3766 .filter(|job| job.kind == "task")
3767 .collect();
3768 let requests: Vec<_> = jobs
3769 .iter()
3770 .map(|job| {
3771 serde_json::from_value::<TaskWorker>(job.payload.clone())
3772 .with_context(|| format!("read live task worker {}", job.id))
3773 })
3774 .collect::<Result<_>>()?;
3775 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3776 let owned: std::collections::BTreeSet<_> = requests
3777 .iter()
3778 .filter(|r| !r.standalone)
3779 .map(|r| r.task.clone())
3780 .collect();
3781 let current: Vec<_> = requests
3782 .iter()
3783 .zip(&jobs)
3784 .filter(|(request, _)| !request.standalone)
3785 .map(|(request, job)| Current {
3786 worker: Some(job.id.clone()),
3787 task: request.task.clone(),
3788 run: queue
3789 .get(&request.task)
3790 .ok()
3791 .and_then(|task| task.runs.last().cloned())
3792 .unwrap_or_default(),
3793 })
3794 .collect();
3795 {
3796 let mut snapshot = lock(status);
3797 snapshot.polls += 1;
3798 snapshot.completed += previous.difference(&owned).count();
3799 snapshot.current = current;
3800 snapshot.idle = owned.is_empty();
3801 }
3802 previous = owned.clone();
3803 stop.busy.store(owned.len(), Ordering::SeqCst);
3804
3805 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3808 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3809 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3810 let mut permits = Vec::new();
3811 sweep_stale_claims(queue, STALE_CLAIM);
3812 reclaim_orphaned_running(queue, opts.max_attempts, &live);
3813 reclaim_abandoned_runs(home, Timestamp::now());
3814 let questions = Questions::at(home.join("questions"));
3815
3816 crate::task_chat::sweep(
3819 queue,
3820 &crate::talk::Talks::at(home.join("talks")),
3821 &questions,
3822 home,
3823 );
3824 repair_choice_offers(&questions);
3825 resolve_blockers(queue, &questions);
3826 apply_task_choice_actions(queue, &questions, home);
3827 triage::apply_answers(queue, &questions);
3828 reconcile_task_questions(queue, &questions);
3829 let talks = crate::talk::Talks::at(home.join("talks"));
3830 crate::chat_notify::sweep(queue, &talks, home);
3831 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3832 crate::chat_watch::sweep(home, &talks);
3833 let mut turns = tokio::task::JoinSet::new();
3834 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3835 while turns.join_next().await.is_some() {}
3837
3838 crate::consult::start_services(
3839 home,
3840 &opts.repo,
3841 limits.recovery_cfg.as_ref(),
3842 opts.config.as_deref(),
3843 )
3844 .await?;
3845 for operation in [
3846 "conductor",
3847 "maintenance",
3848 "housekeeping",
3849 "disk-pressure",
3850 "cache",
3851 "fetch",
3852 ] {
3853 if settling_once_services {
3857 break;
3858 }
3859 start_service(
3860 home,
3861 opts,
3862 queue,
3863 worktrees_root,
3864 operation,
3865 limits.recovery_cfg.as_ref(),
3866 !live.is_empty(),
3867 )
3868 .await?;
3869 }
3870 let latest = crate::worker::active(home)?;
3871 if latest.iter().any(|job| job.key == "service:daemon-cache")
3872 || latest
3873 .iter()
3874 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3875 {
3876 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3877 continue;
3878 }
3879 let candidates: Vec<Task> = runnable(queue)
3880 .into_iter()
3881 .filter(|task| !live.contains(&task.id))
3882 .filter(|task| !opts.once || !attempted.contains(&task.id))
3883 .collect();
3884 let in_flight: Vec<_> = owned.iter().cloned().collect();
3885 let prior_interrupt = std::mem::discriminant(&interrupt);
3886 interrupt = advance_interrupt_tick(
3887 limits.pause_for_interrupts,
3888 interrupt,
3889 &in_flight,
3890 &candidates,
3891 );
3892 if prior_interrupt != std::mem::discriminant(&interrupt) {
3895 let temporary = interrupt_path.with_extension("json.tmp");
3896 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3897 std::fs::rename(temporary, &interrupt_path)?;
3898 }
3899 if let Interrupt::Parking {
3900 parked,
3901 interrupt_task,
3902 } = &interrupt
3903 {
3904 for job in jobs.iter().filter(|job| {
3905 parked
3906 .iter()
3907 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3908 }) {
3909 if crate::worker::control(home, &job.key)?.is_none() {
3910 request_task_park(
3911 home,
3912 job,
3913 crate::run::ParkCause::Interrupt {
3914 reason: format!(
3915 "task {} asked to run first",
3916 crate::run::short_of(interrupt_task)
3917 ),
3918 },
3919 )?;
3920 }
3921 }
3922 }
3923 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3924 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3925 let mut started = false;
3926 let mut resync = false;
3927 for candidate in candidates {
3928 if stop.stopped() {
3929 break;
3930 }
3931 let Some(DispatchClaim {
3932 task,
3933 claim,
3934 permit,
3935 }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3936 else {
3937 continue;
3938 };
3939 if crate::worker::active(home)?
3940 .iter()
3941 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3942 {
3943 drop(claim);
3944 resync = true;
3945 break;
3946 }
3947 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3948 let request = TaskWorker {
3949 opts: opts.absolute()?,
3950 queue: std::path::absolute(queue.root())?,
3951 task: task.id.clone(),
3952 lane,
3953 standalone: false,
3954 };
3955 if let Err(error) = crate::worker::spawn(
3958 home,
3959 "task",
3960 &format!("task:{}", task.id),
3961 serde_json::to_value(&request)?,
3962 )
3963 .await
3964 {
3965 task_worker_spawn_error(home, &request, error)?;
3966 drop(claim);
3967 resync = true;
3968 break;
3969 }
3970 drop(claim);
3971 permits.extend(permit);
3972 attempted.push(task.id);
3973 started = true;
3974 }
3975 if started || resync {
3976 continue;
3977 }
3978 if owned.is_empty() && opts.once {
3979 settling_once_services = true;
3980 if crate::worker::active(home)?.iter().any(|job| {
3984 job.kind == "daemon-service"
3985 && matches!(
3986 job.key.as_str(),
3987 "service:daemon-housekeeping"
3988 | "service:daemon-conductor"
3989 | "service:daemon-maintenance"
3990 )
3991 }) {
3992 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3993 continue;
3994 }
3995 break;
3996 }
3997 stop.idle(if live.is_empty() {
3998 opts.poll
3999 } else {
4000 RECHECK_WHILE_BUSY.min(opts.poll)
4001 })
4002 .await;
4003 }
4004 stop.busy.store(0, Ordering::SeqCst);
4007 Ok(())
4008}
4009
4010async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4014 let busy = |error: &anyhow::Error| {
4015 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4016 error.kind() == std::io::ErrorKind::WouldBlock
4017 || cfg!(windows) && error.raw_os_error() == Some(33)
4018 })
4019 };
4020 match crate::pr_head::owner_lock(home, id) {
4021 Ok(lock) => return Ok(lock),
4022 Err(error) if busy(&error) => {}
4023 Err(error) => return Err(error),
4024 }
4025 let wait = RunState::load_under(id, home)?
4026 .config
4027 .graph
4028 .timeout_resource_wait;
4029 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4030}
4031
4032async fn public_resume_owner(
4036 home: &Path,
4037 runs: &[String],
4038 repo: &Path,
4039) -> Result<Option<RunState>> {
4040 let mut owner = None;
4041 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4042 let _lock = resume_owner_lock(home, id).await?;
4043 let state = RunState::load_under(id, home)?;
4044 if state.released()
4045 || state.retired_to.is_some()
4046 || state.pr_taken_over_by.is_some()
4047 || !crate::handover::landing_checkpoint(&state)
4048 {
4049 continue;
4050 }
4051 anyhow::ensure!(
4052 crate::git::toplevel(&state.repo).await?.canonicalize()?
4053 == crate::git::toplevel(repo).await?.canonicalize()?,
4054 "public owner repository differs; inspect run lineage"
4055 );
4056 anyhow::ensure!(
4057 owner.is_none(),
4058 "multiple retained public owners; inspect run lineage"
4059 );
4060 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4061 anyhow::bail!(reason.diagnostic(&state));
4062 }
4063 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4064 anyhow::ensure!(
4065 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4066 "public owner's driver is live or unknown; wait before retrying"
4067 );
4068 owner = Some(state);
4069 }
4070 Ok(owner)
4071}
4072
4073async fn attempt(
4079 opts: &Opts,
4080 queue: &Queue,
4081 status: &Arc<Mutex<Status>>,
4082 stop: &Stop,
4083 interrupt_pause: crate::graph::Pause,
4084 task: &mut Task,
4085) -> Vec<QuotaLoss> {
4086 let repo = repo_for(task, &opts.repo);
4087 tracing::info!(
4088 "task {} — {} (repo {})",
4089 task.short(),
4090 task.title,
4091 repo.display()
4092 );
4093
4094 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4095 Ok(owner) => owner,
4096 Err(e) => {
4097 task.hold_machine(Some(format!(
4098 "Cannot verify existing public owner: {e:#}; no attempt started."
4099 )));
4100 record(queue, task);
4101 return Vec::new();
4102 }
4103 };
4104 let resume_runs = public_owner
4105 .as_ref()
4106 .map(|s| vec![s.id.clone()])
4107 .unwrap_or_else(|| task.runs.clone());
4108
4109 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4113 && previous
4114 .merge_decision
4115 .as_ref()
4116 .is_some_and(|decision| !decision.closed)
4117 && previous.status != RunStatus::Landing
4118 && !crate::merge_decision::resumable_hold(&previous)
4119 {
4120 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)));
4121 record(queue, task);
4122 return Vec::new();
4123 }
4124 let stop_owner = resume_runs
4125 .last()
4126 .and_then(|id| RunState::load(id).ok())
4127 .filter(|state| {
4128 crate::merge_decision::resumable_hold(state)
4129 || state.status == RunStatus::Landing
4130 && state.land_approval.as_ref().is_some_and(|binding| {
4131 Questions::open().get(&binding.question).is_ok_and(|q| {
4132 q.run == state.id
4133 && q.resolution()
4134 .as_deref()
4135 .is_some_and(crate::merge_decision::stops)
4136 })
4137 })
4138 });
4139 if let Some(owner) = stop_owner {
4140 let mut runner = match Runner::resume(&owner.id) {
4141 Ok(runner) => runner,
4142 Err(e) => {
4143 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4144 record(queue, task);
4145 return Vec::new();
4146 }
4147 };
4148 runner.on_pause(stop.pause());
4149 runner.watch_interrupt(interrupt_pause);
4150 let quota_before = runner.state.quota.clone();
4151 task.start(owner.id.clone());
4152 record(queue, task);
4153 lock(status).current.push(Current {
4154 worker: None,
4155 task: task.id.clone(),
4156 run: owner.id,
4157 });
4158 runner.state.next_pass_task_entry = true;
4159 let result = runner.execute().await;
4160 return finish_attempt(
4161 opts.max_attempts,
4162 queue,
4163 task,
4164 &runner.state,
4165 "a_before,
4166 result,
4167 );
4168 }
4169
4170 if let Some(owner) = &public_owner
4171 && (task.fresh_start || !may_resume_run(owner, task))
4172 {
4173 task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. No attempt started.", owner.id)));
4174 record(queue, task);
4175 return Vec::new();
4176 }
4177
4178 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4179 && !task.fresh_start
4180 && task.review_branch.is_none()
4181 && task.pr_recovery.is_none()
4182 {
4183 let authorized = if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4186 let home = queue.root().parent().expect("queue has a home");
4187 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4188 Ok(()) => true,
4189 Err(error) => {
4190 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4191 false
4192 }
4193 }
4194 } else {
4195 false
4196 };
4197 if !authorized {
4198 task.hold_machine(Some("Base synchronization remains stopped. Inspect the retained run; for movement exhaustion, explicitly use `magi run --resume <run> --recover-base`. A release without a new owner approval grants no additional rebase and starts no replacement competition.".into()));
4199 task.base_sync_notice(&held);
4201 task.resume_override = None;
4202 record(queue, task);
4203 return Vec::new();
4204 }
4205 }
4206 let unfinished = (!task.fresh_start)
4207 .then(|| unfinished_run(&resume_runs, task.short()))
4208 .flatten()
4209 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4210 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4211 if !task.fresh_start
4212 && task.pr_recovery.is_none()
4213 && task.review_branch.is_none()
4214 && task.resume_override.is_none()
4215 && previous
4216 .as_ref()
4217 .is_some_and(|run| run.retired_to.is_some())
4218 && unfinished.is_none()
4219 {
4220 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()));
4221 record(queue, task);
4222 return Vec::new();
4223 }
4224
4225 let saved_recovery = previous.as_ref().filter(|run| {
4226 task.replacement.is_none()
4227 && task.pr_recovery.as_ref().is_some_and(|selected| {
4228 selected.check_task(&task.id, &task.instruction).is_ok()
4229 && selected_starter(selected, Some(run), unfinished.as_deref())
4230 == Starter::Resume(run.id.clone())
4231 })
4232 });
4233
4234 let explicit = match &task.overrides {
4238 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4239 Some(_) => opts.config.as_deref(),
4240 None => opts.config.as_deref(),
4241 };
4242 let (mut config, layers) = if let Some(run) = saved_recovery {
4243 let mut saved = run.clone();
4246 if let Err(e) = saved.configure_recovery_resume() {
4247 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4248 record(queue, task);
4249 return Vec::new();
4250 }
4251 (saved.config, Vec::new())
4252 } else {
4253 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4254 Ok(loaded) => loaded,
4255 Err(e) => {
4256 let reason = format!("[config] {e:#}");
4257 record_config_failure(task, &e);
4258 task.last_error = Some(reason.clone());
4259 task.hold_machine(Some(reason));
4260 record(queue, task);
4261 return Vec::new();
4262 }
4263 };
4264 if let Err(e) = apply_options(&mut config, opts, task) {
4265 task.hold_manual(Some(format!(
4266 "[config] {e:#}; correct the merge override before releasing the task"
4267 )));
4268 record(queue, task);
4269 return Vec::new();
4270 }
4271 if let Some(selected) = &task.pr_recovery
4272 && let Err(e) = selected.configure(&mut config)
4273 {
4274 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4275 record(queue, task);
4276 return Vec::new();
4277 }
4278 (config, layers)
4279 };
4280 let config_evidence = crate::pr_recovery::ConfigEvidence {
4281 layers,
4282 overrides: task.overrides.clone(),
4283 daemon_merge: task
4284 .overrides
4285 .as_ref()
4286 .is_none_or(|o| o.inherit_daemon_options)
4287 .then(|| opts.merge.clone())
4288 .flatten(),
4289 };
4290 apply_task_implementers(&mut config, task);
4291 if let Some(replacement) = &task.replacement {
4292 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4293 old.liveness(false) == Liveness::Dead
4294 && old.merge_decision.as_ref().is_some_and(|d| {
4295 d.closed
4296 && d.question == replacement.question
4297 && d.replacement_run.as_ref().is_none_or(|run| {
4298 task.runs.last() == Some(run)
4299 && RunState::load(run).is_ok_and(|current| {
4300 current.replaces.as_ref().is_some_and(|pin| {
4301 pin.question == replacement.question
4302 && pin.agent == replacement.agent
4303 })
4304 })
4305 })
4306 })
4307 });
4308 if !safe {
4309 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()));
4310 record(queue, task);
4311 return Vec::new();
4312 }
4313 match config.agent(&replacement.agent) {
4314 Ok(agent) if crate::agent::installed(agent) => {}
4315 _ => {
4316 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)));
4317 record(queue, task);
4318 return Vec::new();
4319 }
4320 }
4321 config.graph.implementers = 1;
4322 config.graph.land_approval = true;
4323 config.merge.mode = MergeMode::Pr;
4324 config.graph.selected_implementer = Some(replacement.agent.clone());
4325 }
4326 let p = phrases(&config.graph.language);
4327 let start_failed = p.could_not_start;
4328 if let Ok(base) =
4333 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4334 .await
4335 && let Ok(head) =
4336 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4337 {
4338 let mut inputs = crate::queue::recovery_inputs(&task.sources);
4339 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4340 let source = crate::git::rev_parse(&repo, branch)
4341 .await
4342 .unwrap_or_default();
4343 inputs.push_str(&format!(";review:{branch}:{source}"));
4344 }
4345 if let Some(reason) = task.recovery_exhausted(
4346 &head,
4347 &inputs,
4348 task.attempt_limit
4349 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4350 ) {
4351 task.hold_unrequested_retry(Some(reason));
4352 record(queue, task);
4353 return Vec::new();
4354 }
4355 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4356 }
4357
4358 if let Some(reason) = disk_gate(&repo, &config) {
4366 task.notice_cause("disk-space", None, None);
4367 task.last_error = Some(reason.clone());
4368 task.hold_machine(Some(reason.clone()));
4369 record(queue, task);
4370 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4371 notices::raise(
4374 Notice::warn(
4375 &format!("disk:{}", repo.display()),
4376 format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4377 )
4378 .link(Link::Task {
4379 id: task.id.clone(),
4380 }),
4381 );
4382 return Vec::new();
4383 }
4384
4385 let review_branch = take_review_branch(task, previous.as_ref());
4410 let branch_exists = match &review_branch {
4411 Some(branch) => crate::git::branch_exists(&repo, branch)
4412 .await
4413 .unwrap_or(false),
4414 None => false,
4415 };
4416 let proposed = review_retry_starter(
4420 task,
4421 previous.as_ref(),
4422 review_branch.as_deref(),
4423 branch_exists,
4424 unfinished.as_deref(),
4425 );
4426 let retry_selected = task.replacement.is_some()
4427 && task.resumption.is_some()
4428 && !task.fresh_start
4429 && previous.as_ref().is_some_and(|run| {
4430 run.replaces.is_some()
4431 && ((run.status == RunStatus::Failed && run.viable().is_empty())
4432 || (run.status == RunStatus::Blocked && run.tally.is_none()))
4433 });
4434 let stop_pin = task
4435 .resume_override
4436 .as_ref()
4437 .filter(|pin| {
4438 Questions::open().get(&pin.question_id).is_ok_and(|q| {
4439 q.node == land::APPROVAL_NODE
4440 && q.resolution()
4441 .as_deref()
4442 .is_some_and(crate::merge_decision::stops)
4443 })
4444 })
4445 .and_then(|pin| pin.pinned_run.clone());
4446 let starter = if let Some(owner) = &public_owner {
4447 Starter::Resume(owner.id.clone())
4448 } else if let Some(run) = stop_pin {
4449 Starter::Resume(run)
4452 } else if retry_selected {
4453 Starter::Resume(previous.as_ref().unwrap().id.clone())
4454 } else if let Some(selected) = &task.pr_recovery {
4455 if selected.check_task(&task.id, &task.instruction).is_ok() {
4456 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4457 } else {
4458 Starter::Review(selected.branch.clone())
4459 }
4460 } else {
4461 starter_with_implementers(task, previous.as_ref(), proposed)
4462 };
4463 if let Some(pin) = &task.resume_override
4466 && let Some(run) = &pin.pinned_run
4467 && starter != Starter::Resume(run.clone())
4468 {
4469 let run = run.clone();
4470 task.notice_cause("resume-owner", Some(&run), None);
4471 task.hold_machine(Some(format!(
4472 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4473 task.id
4474 )));
4475 record(queue, task);
4476 return Vec::new();
4477 }
4478 if task.replacement.is_some()
4479 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4480 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4481 {
4482 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()));
4483 record(queue, task);
4484 return Vec::new();
4485 }
4486 if let Some(reason) = retained_attempt_hold(
4487 task,
4488 &starter,
4489 config.disk.retained_attempt_limit,
4490 RunState::load,
4491 ) {
4492 if let Starter::Review(branch) = &starter {
4495 task.review_branch = Some(branch.clone());
4496 }
4497 task.hold_unrequested_retry(Some(reason));
4498 record(queue, task);
4499 return Vec::new();
4500 }
4501 let attachments = match task_attachments(queue, task) {
4506 Ok(a) => a,
4507 Err(e) => {
4508 task.attempts += 1;
4509 task.fail_startup_target(
4510 "startup-attachments",
4511 e.name.clone(),
4512 format!("{start_failed}{e:#}"),
4513 opts.max_attempts,
4514 );
4515 record(queue, task);
4516 return Vec::new();
4517 }
4518 };
4519 let startup_pause = stop.pause();
4520 let startup_interrupt = interrupt_pause.clone();
4521 let wait = crate::repo_lock::WaitPolicy::new(
4522 Duration::from_secs(config.graph.timeout_resource_wait),
4523 move || startup_pause.parked() || startup_interrupt.parked(),
4524 );
4525 let started = wait.scope(Box::pin(async { match &starter {
4528 Starter::Review(_) if task.pr_recovery.is_some() => {
4529 let selected = task.pr_recovery.clone().expect("selected recovery");
4530 match selected.check_task(&task.id, &task.instruction) {
4531 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4532 .await
4533 .map(|mut r| {
4534 r.state.attachments = attachments.clone();
4535 r
4536 }),
4537 Err(e) => Err(e),
4538 }
4539 }
4540 Starter::Review(branch) => {
4541 tracing::info!(
4542 "task {} reopens `{branch}` as a review-only pass",
4543 task.short()
4544 );
4545 let takeover = crate::handover::Takeover {
4548 earlier: task.earlier_attempts().to_vec(),
4549 home: crate::run::home(),
4550 choice: take_divergence_answer(branch, &config.merge.remote, task),
4551 task_instruction: Some(instruction_for(task)),
4552 };
4553 Runner::review_taking_over(
4554 &repo,
4555 branch,
4556 config,
4557 Some(takeover),
4558 crate::run::Origin::queue(&task.id),
4559 )
4560 .await
4561 }
4562 Starter::Resume(id) => {
4563 tracing::info!("resuming run {id} rather than competing again");
4564 Runner::resume(id).and_then(|mut r| {
4565 if retry_selected {
4566 for candidate in &mut r.state.candidates {
4569 candidate.failed = None;
4570 candidate.empty = false;
4571 candidate.commits = 0;
4572 }
4573 r.state.status = RunStatus::Implementing;
4574 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4575 }
4576 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4577 r.state.sources = task.sources.clone();
4578 }
4579 if r.state.prep_failure.is_some() {
4580 let approval = task
4581 .resumption
4582 .as_ref()
4583 .context("preparation retry requires an explicit task release")?;
4584 r.retry_preparation(approval.at)?;
4585 }
4586 if let Some(instruction) =
4587 prepare_instruction(&starter, Some(&r.state.instruction), task)
4588 {
4589 r.state.instruction = instruction;
4590 }
4591 r.state.attachments = attachments.clone();
4592 if task.replacement.is_some() {
4593 r.state.config.merge.mode = MergeMode::Pr;
4594 r.state.config.graph.land_approval = true;
4595 }
4596 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4600 .overrides
4601 .as_ref()
4602 .and_then(|o| o.merge.as_deref())
4603 .and_then(|m| merge_mode(m).ok())
4604 {
4605 r.state.config.merge.mode = mode;
4606 }
4607 Ok(r)
4608 })
4609 }
4610 Starter::Start => {
4611 if let Some(branch) = &review_branch {
4612 tracing::warn!(
4613 "conductor chose review for task {} but branch `{branch}` no longer \
4614 exists; requeuing as a fresh competition instead",
4615 task.short()
4616 );
4617 }
4618 let instruction = prepare_instruction(&starter, None, task)
4619 .unwrap_or_else(|| task.instruction.clone());
4620 Runner::start_naming(
4621 &repo,
4622 instruction,
4623 &task.title,
4624 config,
4625 crate::run::Origin::queue(&task.id),
4626 )
4627 .await
4628 .map(|mut r| {
4629 r.state.attachments = attachments.clone();
4630 r.state.sources = task.sources.clone();
4631 r
4632 })
4633 }
4634 }})).await;
4635 let mut runner = match started {
4636 Ok(r) => r,
4637 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4638 task.last_error = Some(e.to_string());
4639 if stop.parking() || interrupt_pause.parked() {
4640 let attempts = task.attempts;
4641 task.park(e.to_string());
4642 task.attempts = attempts;
4644 } else {
4645 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4646 }
4647 record(queue, task);
4648 return Vec::new();
4649 }
4650 Err(e) if task.pr_recovery.is_some() => {
4654 task.startup_notice_cause("startup-public-head");
4655 task.attempts += 1;
4656 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4657 task.link_run(&partial.run);
4658 task.record_pass(&partial.run, 0, task.attempts, None);
4659 }
4660 task.last_error = Some(format!("{start_failed}{e:#}"));
4661 task.hold_unrequested_retry(Some(format!(
4662 "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."
4663 )));
4664 record(queue, task);
4665 return Vec::new();
4666 }
4667 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4668 let detail = match e.downcast_ref::<crate::handover::Refused>() {
4669 Some(r) => (p.handover_refused)(r),
4670 None => format!("{e:#}"),
4671 };
4672 task.startup_notice_cause("startup-handover");
4673 let reason = format!("{start_failed}{detail}");
4674 task.last_error = Some(reason.clone());
4675 let branch = match &starter {
4678 Starter::Review(branch) => Some(branch.clone()),
4679 _ => None,
4680 };
4681 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4685 record(queue, task);
4686 tracing::warn!(
4687 "holding {} for a branch it cannot take over: {e:#}",
4688 task.short()
4689 );
4690 return Vec::new();
4691 }
4692 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4697 let d = e
4698 .downcast_ref::<crate::reconcile::Diverged>()
4699 .expect("checked by the guard");
4700 let mut q = ask::Question::new(
4701 task.id.clone(),
4702 crate::reconcile::NODE.to_owned(),
4703 crate::reconcile::SEAT.to_owned(),
4704 d.summary(),
4705 d.detail(),
4706 d.choices(),
4707 );
4708 match Questions::open().put(&mut q) {
4709 Ok(()) => {
4710 task.last_error = Some(format!("{e:#}"));
4711 task.review_branch = Some(d.branch.clone());
4714 task.review_instruction = Some(task.instruction.clone());
4715 task.block(vec![q.id.clone()], Some(d.summary()));
4716 }
4717 Err(put) => {
4718 tracing::warn!("could not file the divergence question: {put:#}");
4719 task.attempts += 1;
4720 task.fail_startup(
4721 "startup-question-store",
4722 format!("{start_failed}{e:#}"),
4723 opts.max_attempts,
4724 );
4725 }
4726 }
4727 record(queue, task);
4728 return Vec::new();
4729 }
4730 Err(e) => {
4731 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4737 && let Starter::Review(branch) = &starter
4738 {
4739 task.review_branch = Some(branch.clone());
4740 task.review_instruction = Some(task.instruction.clone());
4741 task.last_error = Some(format!("{start_failed}{e:#}"));
4742 task.status = crate::queue::TaskStatus::Failed;
4743 record(queue, task);
4744 return Vec::new();
4745 }
4746 task.attempts += 1;
4747 task.last_error = Some(format!("{start_failed}{e:#}"));
4748 task.startup_notice_cause("startup-source");
4749 task.hold_unrequested_retry(Some(format!(
4750 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4751 )));
4752 record(queue, task);
4753 return Vec::new();
4754 }
4755 };
4756 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4757 runner.state.recovery_config = Some(config_evidence);
4758 }
4759 if let Some(replacement) = &task.replacement {
4760 if matches!(starter, Starter::Start) {
4761 runner.state.instruction.push_str(&format!(
4762 "\n\n# Replacement review context\n{}",
4763 replacement.context
4764 ));
4765 }
4766 runner.state.replaces = Some(replacement.clone());
4767 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4768 if let Ok(mut old) = RunState::load(&replacement.run)
4769 && let Some(d) = &mut old.merge_decision
4770 {
4771 d.replacement_run = Some(runner.state.id.clone());
4772 old.event(
4773 "replacement",
4774 format!(
4775 "replacement run {} owns the next attempt; old PR remains closed",
4776 runner.state.id
4777 ),
4778 );
4779 if let Err(e) = old.save() {
4780 task.hold_manual(Some(format!(
4781 "Could not link replacement history: {e}; no agents dispatched"
4782 )));
4783 record(queue, task);
4784 return Vec::new();
4785 }
4786 }
4787 }
4788 runner.state.task_instruction = Some(task.instruction.clone());
4789 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4792 if runner.state.origin_chat.is_none() {
4793 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4794 }
4795 runner.on_pause(stop.pause());
4797 runner.watch_interrupt(interrupt_pause);
4801
4802 let run = runner.state.id.clone();
4805 task.start(run.clone());
4806 record(queue, task);
4807 lock(status).current.push(Current {
4808 worker: None,
4809 task: task.id.clone(),
4810 run,
4811 });
4812
4813 let quota_before = runner.state.quota.clone();
4816 runner.state.next_pass_task_entry = true;
4817 let result = runner.execute().await;
4818 finish_attempt(
4819 opts.max_attempts,
4820 queue,
4821 task,
4822 &runner.state,
4823 "a_before,
4824 result,
4825 )
4826}
4827
4828pub fn finish_attempt(
4833 max_attempts: usize,
4834 queue: &Queue,
4835 task: &mut Task,
4836 state: &RunState,
4837 quota_before: &[QuotaLoss],
4838 result: Result<()>,
4839) -> Vec<QuotaLoss> {
4840 let detail = match result {
4841 Ok(()) => describe(state),
4842 Err(e) => format!("{e:#}"),
4843 };
4844 let fresh = losses_this_attempt(quota_before, &state.quota);
4845 let verdict = Verdict {
4846 status: state.status,
4847 left_pr: state.pr.is_some(),
4850 quota_hit: !fresh.is_empty(),
4856 parked: state.parked,
4860 no_viable_candidates: state.viable().is_empty(),
4863 };
4864 if let Some(replacement) = &state.replaces
4865 && let Some(pr) = &state.pr
4866 && let Ok(mut old) = RunState::load(&replacement.run)
4867 && let Some(d) = &mut old.merge_decision
4868 {
4869 d.replacement_pr = Some(pr.url.clone());
4870 let _ = old.save();
4871 }
4872 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4873 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4874 task.hold_unrequested_retry(Some(format!(
4875 "Candidate setup failed: {detail}. Correct the explicit sources with `magi task sources {}` (README, \"Use\": implementation imports), or select a complete implementation with `magi task recover-pr`, then explicitly release the task.",
4876 task.short()
4877 )));
4878 }
4879 if task.status == TaskStatus::Done {
4880 supersede_prior_runs(task, &crate::run::home());
4881 }
4882 record(queue, task);
4883 tracing::info!(
4884 "task {} is {} after run {} ({})",
4885 task.short(),
4886 task.status.as_str(),
4887 state.short(),
4888 label(state.status)
4889 );
4890 fresh
4891}
4892
4893pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4897 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4900 && !awaiting_resume_with(task, RunState::load)
4901 && withheld_text_wait(task).is_none()
4905 && !(task.fresh_start && task.replacement.is_some())
4906 {
4907 let why = task.last_error.clone().map_or_else(
4908 || "the run did not finish".to_owned(),
4909 |e| format!("the run did not finish: {e}"),
4910 );
4911 task.hold_unrequested_retry(Some(format!(
4912 "{why}. It was started by hand, so it is not retried \
4913 automatically; `magi task release` retries it."
4914 )));
4915 record(queue, task);
4916 }
4917}
4918
4919#[must_use]
4923pub fn loop_would_resume(run: &str) -> bool {
4924 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4925}
4926
4927#[must_use]
4937pub fn foreign_loop(
4938 reading: Option<&Reading>,
4939 now: Timestamp,
4940 own_pid: u32,
4941) -> Option<Option<u32>> {
4942 let reading = reading.filter(|r| r.running(now))?;
4943 match reading.pid {
4944 Some(pid) if pid == own_pid => None,
4945 pid => Some(pid),
4946 }
4947}
4948
4949fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4950 reading.worker_protocol != Some(1)
4951 && (foreign_loop(Some(reading), now, own_pid).is_some()
4952 || reading
4953 .pid
4954 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4955}
4956
4957pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4968 run_claimed_until(opts, queue, task, &Stop::new()).await;
4969}
4970
4971async fn run_claimed_until(
4972 opts: &Opts,
4973 queue: &Queue,
4974 task: &mut Task,
4975 stop: &Stop,
4976) -> Vec<QuotaLoss> {
4977 let status = Arc::new(Mutex::new(Status::new()));
4978 let mut quota = Box::pin(attempt(
4981 opts,
4982 queue,
4983 &status,
4984 stop,
4985 crate::graph::Pause::new(),
4986 task,
4987 ))
4988 .await;
4989 let mut resumes = 0;
4998 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
4999 let Some(timeout) = withheld_text_wait(task) else {
5000 break;
5001 };
5002 eprintln!(
5003 "waiting for the owner's answer on a withheld pull request text \
5004 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5005 );
5006 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5009 let ready = loop {
5010 match land_resume_state(task) {
5011 LandResume::StillWaiting
5012 if !stop.parking() && std::time::Instant::now() < limit =>
5013 {
5014 tokio::time::sleep(WITHHELD_POLL).await;
5015 }
5016 LandResume::Ready => break true,
5017 _ => break false,
5018 }
5019 };
5020 if !ready || stop.parking() {
5021 break;
5022 }
5023 resumes += 1;
5024 quota.extend(
5025 Box::pin(attempt(
5026 opts,
5027 queue,
5028 &status,
5029 stop,
5030 crate::graph::Pause::new(),
5031 task,
5032 ))
5033 .await,
5034 );
5035 }
5036 hold_if_runnable(queue, task);
5037 quota
5038}
5039
5040const MAX_WITHHELD_RESUMES: u32 = 3;
5043
5044const WITHHELD_POLL: Duration = Duration::from_secs(15);
5046
5047fn withheld_text_wait(task: &Task) -> Option<u64> {
5050 let id = task.runs.last()?;
5051 let s = RunState::load(id).ok()?;
5052 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5053 .then_some(s.config.graph.answer_timeout)
5054}
5055
5056fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5066 after
5067 .iter()
5068 .filter(|q| !before.contains(q))
5069 .cloned()
5070 .collect()
5071}
5072
5073fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5076 let quota: Vec<_> = quota
5077 .iter()
5078 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5079 .collect();
5080 if quota.is_empty() {
5081 return None;
5082 }
5083 let with_hint = quota.iter().find(|q| q.reset.is_some());
5084 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5085 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5086 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5087 Some(
5088 now.checked_add(jiff::SignedDuration::from_secs(secs))
5089 .unwrap_or(Timestamp::MAX),
5090 )
5091}
5092
5093fn implementers_match(task: &Task, state: &RunState) -> bool {
5095 task.replacement.as_ref().map_or_else(
5096 || {
5097 task.implementers()
5098 .is_none_or(|n| n == state.config.graph.implementers)
5099 },
5100 |replacement| {
5101 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5102 && state.config.graph.implementers == 1
5103 },
5104 )
5105}
5106
5107fn starter_with_implementers(
5109 task: &Task,
5110 previous: Option<&RunState>,
5111 proposed: Starter,
5112) -> Starter {
5113 if previous.is_some_and(|s| !implementers_match(task, s)) {
5114 task.review_of
5115 .as_ref()
5116 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5117 } else {
5118 proposed
5119 }
5120}
5121
5122fn apply_task_implementers(config: &mut Config, task: &Task) {
5124 if let Some(n) = task.implementers() {
5125 config.graph.implementers = n;
5126 }
5127}
5128
5129#[cfg(test)]
5134fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5135 let explicit = match &task.overrides {
5136 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5137 _ => opts.config.as_deref(),
5138 };
5139 let (mut config, _) = Config::discover(repo, explicit)?;
5140 apply_options(&mut config, opts, task)?;
5141 Ok(config)
5142}
5143
5144fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5145 if task
5146 .overrides
5147 .as_ref()
5148 .is_none_or(|o| o.inherit_daemon_options)
5149 && let Some(mode) = opts.merge.as_deref()
5150 {
5151 config.merge.mode = merge_mode(mode)?;
5152 }
5153 if let Some(o) = &task.overrides {
5154 o.apply(config);
5155 }
5156 Ok(())
5157}
5158
5159fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5161 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5162 if let Some(mode) = &opts.merge {
5163 config.merge.mode = merge_mode(mode)?;
5164 }
5165 Ok(config)
5166}
5167
5168async fn maybe_prune_cache_between_runs(
5173 repo: &Path,
5174 opts: &Opts,
5175 home: &Path,
5176 stop: &Stop,
5177 last_checked: &mut Option<Timestamp>,
5178 now: Timestamp,
5179) {
5180 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5181 return;
5182 }
5183 *last_checked = Some(now);
5184 let cfg = match prepare(repo, opts) {
5185 Ok(cfg) => cfg,
5186 Err(e) => {
5187 tracing::warn!("cache check: no config: {e:#}");
5188 return;
5189 }
5190 };
5191 match clean::prune_cache_if_over_limit(&cfg, home) {
5192 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5193 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5194 pruned.files,
5195 pruned.freed
5196 ),
5197 Ok(_) => {}
5198 Err(e) => {
5199 tracing::warn!("housekeep: prune cache: {e:#}");
5200 notices::raise_in(
5201 home,
5202 Notice::warn(
5203 "housekeep:cache",
5204 format!(
5205 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5206 e.to_string()
5207 .lines()
5208 .next()
5209 .unwrap_or("unknown cleanup error")
5210 ),
5211 ),
5212 );
5213 }
5214 }
5215}
5216
5217fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5221 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5222}
5223
5224async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5243 let cfg = match prepare(repo, opts) {
5244 Ok(cfg) => cfg,
5245 Err(e) => {
5246 tracing::warn!("housekeep: no config: {e:#}");
5247 return;
5248 }
5249 };
5250 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5259 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5260 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5265 let mut extra = Vec::new();
5266 if out.unreadable > 0 {
5267 extra.push(format!("{} unreadable", out.unreadable));
5268 }
5269 if out.orphaned_worktrees > 0 {
5270 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5271 }
5272 let detail = if extra.is_empty() {
5273 String::new()
5274 } else {
5275 format!(" ({})", extra.join(", "))
5276 };
5277 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5278 }
5279 if out.external_merges_recorded > 0 {
5280 tracing::info!(
5281 "housekeep: recorded {} run(s) as merged externally",
5282 out.external_merges_recorded
5283 );
5284 }
5285 if out.stale_pr_states_repaired > 0 {
5286 tracing::info!(
5287 "housekeep: rewrote {} run record(s) whose pull request had already settled",
5288 out.stale_pr_states_repaired
5289 );
5290 }
5291 if out.cache_files > 0 {
5292 tracing::info!(
5293 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5294 out.cache_files,
5295 out.cache_freed
5296 );
5297 }
5298 if out.questions_abandoned > 0 {
5299 tracing::info!(
5300 "housekeep: abandoned {} question(s) left open by a finished run",
5301 out.questions_abandoned
5302 );
5303 }
5304}
5305
5306async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5315 let questions = Questions::at(home.join("questions"));
5316 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5317 if report.is_empty() {
5318 return;
5319 }
5320 if !report.quarantined.is_empty() {
5321 tracing::info!(
5322 "triage: held {} blocked task(s) whose blocked-on task or \
5323 question no longer exists: {}",
5324 report.quarantined.len(),
5325 report.quarantined.join(", ")
5326 );
5327 }
5328 if !report.resumed.is_empty() {
5329 tracing::info!(
5330 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5331 report.resumed.len(),
5332 report.resumed.join(", ")
5333 );
5334 }
5335 if !report.asked.is_empty() {
5336 tracing::info!(
5337 "triage: asked about {} held task(s): {}",
5338 report.asked.len(),
5339 report.asked.join(", ")
5340 );
5341 }
5342 if !report.answered.is_empty() {
5343 tracing::info!(
5344 "triage: applied {} operator answer(s): {}",
5345 report.answered.len(),
5346 report.answered.join(", ")
5347 );
5348 }
5349}
5350
5351pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5358 disk_gate_with(repo, config, crate::disk::free_bytes)
5359}
5360
5361fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5365 repo: &Path,
5366 config: &Config,
5367 free_bytes: F,
5368) -> Option<String> {
5369 let min = config.disk.min_free_bytes;
5370 if min == 0 {
5371 return None;
5372 }
5373 let mut paths = vec![repo.to_owned()];
5374 if let Some(cache) = config.cache_dir() {
5375 paths.push(cache);
5376 }
5377 if let Some(root) = &config.graph.worktree_root {
5378 paths.push(root.clone());
5379 }
5380 for path in paths {
5381 let probe = if path == repo {
5382 path.as_path()
5383 } else {
5384 path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5385 };
5386 let reason = match free_bytes(probe) {
5387 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5388 Err(e) => Some(crate::disk::unmeasured_in(
5389 probe,
5390 &e,
5391 &config.graph.language,
5392 )),
5393 };
5394 if reason.is_some() {
5395 return reason;
5396 }
5397 }
5398 None
5399}
5400
5401const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5408
5409const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5413
5414fn quota_wait(
5423 reset_at: Option<Timestamp>,
5424 now: Timestamp,
5425 fallback: Duration,
5426 cap: Duration,
5427) -> Duration {
5428 match reset_at {
5429 Some(at) if at > now => {
5430 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5431 Duration::from_secs(secs).min(cap)
5432 }
5433 _ => fallback,
5434 }
5435}
5436
5437fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5451 parse_reset_hint_zoned(text, now)
5452 .or_else(|| parse_reset_hint_dated(text))
5453 .or_else(|| parse_reset_hint_relative(text, recorded))
5454}
5455
5456fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5460 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5461 let mut rest = rest.trim();
5462 if rest.is_empty() {
5463 return None;
5464 }
5465 let mut total: i64 = 0;
5466 let mut matched = false;
5467 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5468 if let Some((digits, tail)) = rest.split_once(unit)
5469 && !digits.is_empty()
5470 && digits.bytes().all(|b| b.is_ascii_digit())
5471 {
5472 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5473 rest = tail;
5474 matched = true;
5475 }
5476 }
5477 if !rest.is_empty() || !matched {
5478 return None;
5479 }
5480 recorded
5481 .checked_add(jiff::SignedDuration::from_secs(total))
5482 .ok()
5483}
5484
5485fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5489 let clock = clock.trim().to_lowercase();
5490 let (digits, pm) = clock
5491 .strip_suffix("am")
5492 .map(|d| (d, false))
5493 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5494 let (h, m) = digits.trim().split_once(':')?;
5495 let mut hour: i8 = h.trim().parse().ok()?;
5496 let minute: i8 = m.trim().parse().ok()?;
5497 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5498 return None;
5499 }
5500 if pm && hour != 12 {
5501 hour += 12;
5502 } else if !pm && hour == 12 {
5503 hour = 0;
5504 }
5505 Some((hour, minute))
5506}
5507
5508fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5513 let open = text.find('(')?;
5514 let close = text.rfind(')')?;
5515 if close <= open {
5516 return None;
5517 }
5518 let zone = text[open + 1..close].trim();
5519 let (hour, minute) = parse_12h_clock(&text[..open])?;
5520 let tz = jiff::tz::TimeZone::get(zone).ok()?;
5521 let candidate = now
5522 .to_zoned(tz)
5523 .with()
5524 .hour(hour)
5525 .minute(minute)
5526 .second(0)
5527 .millisecond(0)
5528 .microsecond(0)
5529 .nanosecond(0)
5530 .build()
5531 .ok()?;
5532 let mut at = candidate.timestamp();
5533 if at <= now {
5534 at += jiff::SignedDuration::from_hours(24);
5535 }
5536 Some(at)
5537}
5538
5539fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5548 let words: Vec<&str> = text.split_whitespace().collect();
5549 if words.len() < 5 {
5550 return None;
5551 }
5552 (0..=words.len() - 5)
5553 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5554}
5555
5556fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5562 if trailing.is_some_and(|next| next.starts_with('(')) {
5563 return None;
5564 }
5565 let month = month_number(window[0])?;
5566 let day_token = window[1].strip_suffix(',')?.to_lowercase();
5567 let day_digits = ["st", "nd", "rd", "th"]
5568 .iter()
5569 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5570 let day: i8 = day_digits.parse().ok()?;
5571 let year_token = window[2];
5572 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5573 return None;
5574 }
5575 let year: i16 = year_token.parse().ok()?;
5576 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5580 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5581 let date = jiff::civil::Date::new(year, month, day).ok()?;
5582 let candidate = date
5583 .at(hour, minute, 0, 0)
5584 .to_zoned(jiff::tz::TimeZone::UTC)
5585 .ok()?;
5586 Some(candidate.timestamp())
5587}
5588
5589fn month_number(name: &str) -> Option<i8> {
5592 const NAMES: [&str; 12] = [
5593 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5594 ];
5595 let lower = name.to_lowercase();
5596 NAMES
5597 .iter()
5598 .position(|n| *n == lower.as_str())
5599 .map(|i| i as i8 + 1)
5600}
5601
5602#[cfg(test)]
5604fn exhausted_review_budget(state: &RunState) -> bool {
5605 !crate::handover::can_resume(state)
5608 && state.status == RunStatus::Blocked
5609 && !state.released()
5610 && state.retired_to.is_none()
5611}
5612
5613fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5650 unfinished_run_with(runs, short, RunState::load)
5651}
5652
5653pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5656where
5657 F: FnMut(&str) -> Result<RunState>,
5658{
5659 let mut id = runs.last()?.clone();
5660 let mut visited = std::collections::BTreeSet::new();
5661 let mut repo = None;
5662 loop {
5663 if !runs.contains(&id) || !visited.insert(id.clone()) {
5664 tracing::warn!("invalid or cyclic recovery authority for task {short}");
5665 return None;
5666 }
5667 let state = match load(&id) {
5668 Ok(state) if state.id == id => state,
5669 Ok(_) => return None,
5670 Err(e) => {
5671 tracing::warn!("could not read run {id} for task {short}: {e:#}");
5672 return None;
5673 }
5674 };
5675 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5676 return None;
5677 }
5678 repo = Some(state.repo.clone());
5679 if let Some(authority) = state.retired_to {
5680 id = authority;
5681 continue;
5682 }
5683 return (crate::handover::can_resume(&state)
5684 && state.liveness(false) != crate::run::Liveness::Live)
5685 .then_some(id);
5686 }
5687}
5688
5689fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5697where
5698 F: FnOnce(&str) -> Result<RunState>,
5699{
5700 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5702 || task.fresh_start
5703 || task.review_branch.is_some()
5704 {
5705 return false;
5706 }
5707 let Some(id) = task.runs.last() else {
5708 return false;
5709 };
5710 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5711}
5712
5713#[derive(Debug, Clone, PartialEq, Eq)]
5716enum Starter {
5717 Review(String),
5720 Resume(String),
5722 Start,
5724}
5725
5726fn retained_attempt_hold(
5730 task: &Task,
5731 starter: &Starter,
5732 limit: usize,
5733 mut load: impl FnMut(&str) -> Result<RunState>,
5734) -> Option<String> {
5735 if limit == 0 || matches!(starter, Starter::Resume(_)) {
5736 return None;
5737 }
5738 let mut retained = 0;
5739 for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5740 let state = match load(id) {
5741 Ok(state) if state.id == *id => state,
5742 _ => {
5743 return Some(format!(
5744 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5745 ));
5746 }
5747 };
5748 if state.retired_to.is_some() || state.released() {
5749 continue;
5750 }
5751 retained += 1;
5754 }
5755 (retained >= limit).then(|| format!(
5756 "[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."
5757 ))
5758}
5759
5760fn selected_starter(
5762 selected: &crate::pr_recovery::Selection,
5763 previous: Option<&RunState>,
5764 unfinished: Option<&str>,
5765) -> Starter {
5766 if let Some(id) = unfinished
5767 && previous.is_some_and(|r| {
5768 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5769 })
5770 {
5771 Starter::Resume(id.to_owned())
5772 } else {
5773 Starter::Review(selected.branch.clone())
5774 }
5775}
5776
5777fn take_divergence_answer(
5781 branch: &str,
5782 remote: &str,
5783 task: &mut Task,
5784) -> Option<crate::reconcile::Choice> {
5785 let summary = crate::reconcile::summary_for(branch, remote);
5786 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5787 (a.question == summary)
5788 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5789 .flatten()
5790 .map(|c| (i, c))
5791 })?;
5792 task.answers.remove(idx);
5793 Some(choice)
5794}
5795
5796fn choose_starter(
5808 review_branch: Option<&str>,
5809 branch_exists: bool,
5810 unfinished: Option<&str>,
5811) -> Starter {
5812 match review_branch {
5813 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5814 Some(_) => Starter::Start,
5815 None => match unfinished {
5816 Some(id) => Starter::Resume(id.to_owned()),
5817 None => Starter::Start,
5818 },
5819 }
5820}
5821
5822fn review_retry_starter(
5826 task: &Task,
5827 previous: Option<&RunState>,
5828 branch: Option<&str>,
5829 exists: bool,
5830 unfinished: Option<&str>,
5831) -> Starter {
5832 if let Some(run) = previous
5833 && unfinished == Some(run.id.as_str())
5834 && run.reviewed_commits.is_some()
5835 && branch.is_some_and(|branch| {
5836 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5837 })
5838 && may_resume_run(run, task)
5839 {
5840 return Starter::Resume(run.id.clone());
5841 }
5842 match (branch, unfinished, &task.review_of) {
5843 (None, None, Some(branch)) => Starter::Review(branch.clone()),
5844 _ => choose_starter(branch, exists, unfinished),
5845 }
5846}
5847
5848fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5850 let branch = task.review_branch.take();
5851 let instruction = task.review_instruction.take();
5852 branch.filter(|branch| match &instruction {
5853 Some(authored) => *authored == task.instruction,
5854 None => previous.map_or_else(
5857 || task.review_of.as_ref() == Some(branch),
5858 |run| compatible_run_instruction(run, task),
5859 ),
5860 })
5861}
5862
5863fn may_resume_run(run: &RunState, task: &Task) -> bool {
5866 task.resume_override
5867 .as_ref()
5868 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5869 || compatible_run_instruction(run, task)
5870}
5871
5872pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5874 if let Some(authored) = &run.task_instruction {
5875 return compatible_instruction(authored, task);
5876 }
5877 if compatible_instruction(&run.instruction, task) {
5878 return true;
5879 }
5880 if run.reviewed_commits.is_some() {
5883 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5884 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5885 }
5886 if let Some(branch) = &task.review_of {
5887 let canonical = format!(
5888 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5889 );
5890 let generated = format!(
5891 "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"
5892 );
5893 return task.instruction == canonical && run.instruction.starts_with(&generated);
5894 }
5895 }
5896 false
5897}
5898
5899pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5901 strip_answers_block(old, task) == task.instruction
5902}
5903
5904fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5907 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5908 return fallback.to_path_buf();
5909 }
5910 task.repo.clone()
5911}
5912
5913const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5917
5918fn answers_block(task: &Task, count: usize) -> String {
5920 let mut s = ANSWERS_HEADER.to_owned();
5921 for a in &task.answers[..count] {
5922 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5923 }
5924 s
5925}
5926
5927fn resumption_block(r: &crate::queue::Resumption) -> String {
5930 format!(
5931 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5932 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5933 r.generation, r.at, r.instruction, r.answers_through,
5934 )
5935}
5936
5937fn append_answers(base: &str, task: &Task) -> String {
5939 let mut s = base.to_owned();
5940 if !task.answers.is_empty() {
5941 s.push_str(&answers_block(task, task.answers.len()));
5942 }
5943 if let Some(r) = &task.resumption {
5944 s.push_str(&resumption_block(r));
5945 }
5946 s
5947}
5948
5949fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5953 let mut instruction = instruction;
5954 for approval in task
5955 .resumption
5956 .iter()
5957 .chain(task.resumption_history.iter().rev())
5958 {
5959 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5960 instruction = base;
5961 break;
5962 }
5963 }
5964 for count in (1..=task.answers.len()).rev() {
5965 let block = answers_block(task, count);
5966 if let Some(base) = instruction.strip_suffix(&block) {
5967 return base;
5968 }
5969 }
5970 instruction
5971}
5972
5973fn instruction_for(task: &Task) -> String {
5981 append_answers(&task.instruction, task)
5982}
5983
5984fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5996 append_answers(strip_answers_block(old_instruction, task), task)
5997}
5998
5999fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6001 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6002 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6003 if let Some(cause) = task.hold_notice_cause.as_mut() {
6004 cause.target = failure.map(|f| f.target.clone());
6005 }
6006}
6007
6008#[derive(Debug, thiserror::Error)]
6009#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6010struct MissingAttachment {
6011 name: String,
6012 path: PathBuf,
6013}
6014
6015fn task_attachments(
6017 queue: &Queue,
6018 task: &Task,
6019) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6020 let paths = queue.attachment_paths(task);
6021 for (name, path) in task.attachments.iter().zip(&paths) {
6022 if !path.is_file() {
6023 return Err(MissingAttachment {
6024 name: name.clone(),
6025 path: path.clone(),
6026 });
6027 }
6028 }
6029 Ok(paths)
6030}
6031
6032fn prepare_instruction(
6043 starter: &Starter,
6044 old_instruction: Option<&str>,
6045 task: &Task,
6046) -> Option<String> {
6047 match starter {
6048 Starter::Start => Some(instruction_for(task)),
6049 Starter::Resume(_) => Some(resumed_instruction(
6050 old_instruction.expect("a resumed run always has a prior instruction"),
6051 task,
6052 )),
6053 Starter::Review(_) => None,
6054 }
6055}
6056
6057fn record(queue: &Queue, task: &mut Task) {
6061 if let Err(e) = queue.put(task) {
6062 tracing::error!("could not record task {}: {e:#}", task.short());
6063 let notice = Notice::error(
6064 "loop:record",
6065 format!(
6066 "Task {} state could not be saved: {}. Check the disk.",
6067 task.id,
6068 e.to_string().lines().next().unwrap_or("unknown save error")
6069 ),
6070 )
6071 .link(Link::Task {
6072 id: task.id.clone(),
6073 });
6074 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6076 Some(home) => notices::raise_in(home, notice),
6077 None => notices::raise(notice),
6078 }
6079 }
6080}
6081
6082fn runnable(queue: &Queue) -> Vec<Task> {
6088 let mut tasks: Vec<Task> = queue
6089 .list()
6090 .into_iter()
6091 .filter(|t| t.status.runnable())
6092 .collect();
6093 tasks.sort_unstable_by(crate::queue::dispatch_order);
6094 tasks
6095}
6096
6097fn describe(state: &RunState) -> String {
6111 let p = phrases(&state.config.graph.language);
6112 let mut detail = if state.status == RunStatus::Stalled {
6113 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6114 seats.sort_unstable();
6115 seats.dedup();
6116 if seats.is_empty() {
6117 p.quorum_lost.to_owned()
6118 } else {
6119 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6120 }
6121 } else {
6122 format!("{}{}", p.run_ended, state.status.display_label())
6123 };
6124 if let Some(cause) = state.verification_blocking_cause() {
6125 detail.push_str(&format!(" ({cause})"));
6126 } else if let Some(last) = state.events.last() {
6127 let unanswered = state
6131 .reviews
6132 .last()
6133 .filter(|r| {
6134 state.status == RunStatus::Blocked
6135 && last.node == "review"
6136 && r.incomplete()
6137 && r.blocking == 0
6138 && r.round == state.config.graph.review_rounds
6139 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6140 })
6141 .map(|r| (r.expected - r.answered, r.round));
6142 match unanswered {
6143 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6144 detail.push_str(&format!(
6145 " ({}: {})",
6146 last.node,
6147 (p.reviewers_never_answered)(missing, rounds)
6148 ));
6149 }
6150 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6151 }
6152 }
6153 detail.push_str(&format!(" [run {}]", state.id));
6154 detail
6155}
6156
6157const DIAGNOSTIC_MAX: usize = 4_000;
6163
6164const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6169
6170fn diagnostic(state: &RunState) -> Option<String> {
6184 let mut parts: Vec<String> = Vec::new();
6185
6186 for o in state.gate.iter().filter(|o| !o.ok()) {
6188 parts.push(format!(
6189 "gate `{}` failed ({}):\n{}",
6190 o.command,
6191 notices::exit_status(o.code),
6192 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6193 ));
6194 }
6195
6196 if let Some(last) = state
6199 .events
6200 .iter()
6201 .rev()
6202 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6203 {
6204 parts.push(last.message.clone());
6205 }
6206
6207 if state.viable().is_empty() {
6214 for c in &state.candidates {
6215 if let Some(evidence) = &c.verified_noop {
6216 parts.push(format!(
6217 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6218 c.label
6219 ));
6220 } else if !c.summary.trim().is_empty() {
6221 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6222 } else if let Some(why) = &c.failed {
6223 parts.push(format!("candidate {}: {why}", c.label));
6224 }
6225 }
6226 }
6227
6228 if parts.is_empty() {
6229 return None;
6230 }
6231 Some(crate::run::tail(
6236 &parts.join("\n\n"),
6237 DIAGNOSTIC_MAX.saturating_sub(100),
6238 ))
6239}
6240
6241fn label(status: RunStatus) -> &'static str {
6249 status.as_str()
6250}
6251
6252pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6254 match mode {
6255 "none" => Ok(MergeMode::None),
6256 "local" => Ok(MergeMode::Local),
6257 "pr" => Ok(MergeMode::Pr),
6258 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6259 }
6260}
6261
6262fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6267 mutex
6268 .lock()
6269 .unwrap_or_else(std::sync::PoisonError::into_inner)
6270}
6271
6272#[cfg(test)]
6273mod tests {
6274 use super::*;
6275 use crate::queue::{Source, TaskStatus};
6276 use crate::run::{Candidate, CommandOutcome};
6277 use pretty_assertions::assert_eq;
6278
6279 fn task() -> Task {
6280 Task::new(
6281 "add retries".to_owned(),
6282 "add retries".to_owned(),
6283 PathBuf::from("/repo"),
6284 Source::Human,
6285 )
6286 }
6287
6288 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6289 let job = crate::worker::Job {
6290 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6291 sequence: 1,
6292 kind: "task".into(),
6293 key: format!("task:{}", request.task),
6294 payload: serde_json::to_value(request).unwrap(),
6295 generation: "a".repeat(64),
6296 version: None,
6297 status: crate::worker::Status::Starting,
6298 result: None,
6299 pid: None,
6300 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6301 finished_at: None,
6302 };
6303 let dir = home.join("workers/jobs").join(&job.id);
6304 std::fs::create_dir_all(&dir).unwrap();
6305 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6306 job
6307 }
6308
6309 #[test]
6310 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6311 let home = tempfile::tempdir().unwrap();
6312 let request = TaskWorker {
6313 opts: Opts::default(),
6314 queue: home.path().join("queue"),
6315 task: "startup".into(),
6316 lane: PermitKind::Ordinary,
6317 standalone: false,
6318 };
6319 let job = starting_task_reservation(home.path(), &request);
6320 let error = task_worker_spawn_error(
6321 home.path(),
6322 &request,
6323 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6324 )
6325 .expect_err("our own reservation must not turn a failed spawn into a resync");
6326 let active = crate::worker::active(home.path()).unwrap();
6327 assert_eq!(active.len(), 1);
6328 assert_eq!(active[0].id, job.id);
6329 assert_eq!(active[0].status, crate::worker::Status::Starting);
6330 assert!(
6331 crate::worker::control(home.path(), &job.key)
6332 .unwrap()
6333 .is_none()
6334 );
6335 let notices = notices::Notices::at(home.path().join("notifications")).list();
6336 assert_eq!(notices.len(), 1);
6337 assert_eq!(notices[0].key, "loop:worker-startup");
6338 assert!(!notices[0].message.contains("private-error-detail"));
6339 assert!(notices[0].message.contains(&request.task));
6340 assert!(
6341 notices[0]
6342 .message
6343 .contains("could not be started or acknowledged")
6344 );
6345 assert!(notices[0].message.contains("worker.log"));
6346 assert_eq!(
6347 notices[0].link,
6348 Some(Link::Task {
6349 id: request.task.clone()
6350 })
6351 );
6352 assert!(format!("{error:#}").contains("private-error-detail"));
6353 }
6354
6355 #[test]
6356 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6357 let home = tempfile::tempdir().unwrap();
6358 let mut request = TaskWorker {
6359 opts: Opts::default(),
6360 queue: home.path().join("queue"),
6361 task: "handoff".into(),
6362 lane: PermitKind::Ordinary,
6363 standalone: true,
6364 };
6365 let job = starting_task_reservation(home.path(), &request);
6366 request.standalone = false;
6367 task_worker_spawn_error(
6368 home.path(),
6369 &request,
6370 anyhow::anyhow!("operation key is already reserved for a different request"),
6371 )
6372 .expect("a different standalone request is the handoff race, not our startup failure");
6373 let active = crate::worker::active(home.path()).unwrap();
6374 assert_eq!(active.len(), 1);
6375 assert_eq!(active[0].id, job.id);
6376 assert_eq!(active[0].payload, job.payload);
6377 assert!(
6378 notices::Notices::at(home.path().join("notifications"))
6379 .list()
6380 .is_empty()
6381 );
6382 }
6383
6384 #[test]
6385 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6386 let home = tempfile::tempdir().unwrap();
6387 let queue = Queue::at(home.path().join("queue"));
6388 let mut task = task();
6389 task.runs = vec!["previous".into()];
6390 queue.put(&mut task).unwrap();
6391 let request = TaskWorker {
6392 opts: Opts::default(),
6393 queue: home.path().join("queue"),
6394 task: task.id.clone(),
6395 lane: PermitKind::Ordinary,
6396 standalone: false,
6397 };
6398 let job = starting_task_reservation(home.path(), &request);
6399 let claims = current_work(home.path(), Timestamp::now());
6400 assert_eq!(claims.len(), 1);
6401 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6402 assert_eq!(claims[0].run, "previous");
6403 assert!(other_claims_run(&claims, "previous", None));
6404 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6407 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6408 }
6409
6410 #[test]
6411 fn admission_excludes_only_the_callers_exact_reservation() {
6412 let own = Current {
6413 worker: Some("own".into()),
6414 task: "same-task".into(),
6415 run: "previous".into(),
6416 };
6417 assert!(!other_claims_run(
6418 std::slice::from_ref(&own),
6419 "previous",
6420 Some("own")
6421 ));
6422 assert!(other_claims_run(
6423 std::slice::from_ref(&own),
6424 "previous",
6425 None
6426 ));
6427 for worker in [None, Some("other".into())] {
6428 let other = Current {
6429 worker,
6430 ..own.clone()
6431 };
6432 assert!(other_claims_run(
6433 &[own.clone(), other],
6434 "previous",
6435 Some("own")
6436 ));
6437 }
6438 let legacy: Current =
6439 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6440 assert!(other_claims_run(&[legacy], "previous", Some("own")));
6441 }
6442
6443 #[test]
6444 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6445 let mut task = task();
6446 let mut run = run_state(RunStatus::Reviewing);
6447 run.task_instruction = Some(task.instruction.clone());
6448 run.reviewed_commits = Some(vec!["committed-fix".into()]);
6449 let branch = "magi/test/B";
6450 run.candidates.push(crate::run::Candidate {
6451 branch: branch.into(),
6452 ..candidate('B', "preserved work", false, None)
6453 });
6454 task.runs = vec![run.id.clone()];
6455 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6456 assert_eq!(
6457 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6458 Starter::Resume(run.id.clone())
6459 );
6460 assert!(matches!(
6461 review_retry_starter(
6462 &task,
6463 Some(&run),
6464 Some("different"),
6465 true,
6466 unfinished.as_deref()
6467 ),
6468 Starter::Review(_)
6469 ));
6470 assert_eq!(
6471 review_retry_starter(
6472 &task,
6473 Some(&run),
6474 Some(branch),
6475 false,
6476 unfinished.as_deref()
6477 ),
6478 Starter::Start
6479 );
6480 task.instruction.push_str(" changed criteria");
6481 assert!(matches!(
6482 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6483 Starter::Review(_)
6484 ));
6485 assert!(matches!(
6486 review_retry_starter(&task, Some(&run), Some(branch), true, None),
6487 Starter::Review(_)
6488 ));
6489 }
6490
6491 #[test]
6492 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6493 let dir = tempfile::tempdir().unwrap();
6494 let queue = Queue::at(dir.path().join("queue"));
6495 let mut task = task();
6496 task.status = TaskStatus::Running;
6497 task.attempts = 1;
6498 queue.put(&mut task).unwrap();
6499 let live = std::collections::BTreeSet::from([task.id.clone()]);
6500 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6501 drop(queue.claim(&task.id).unwrap());
6502 let saved = queue.get(&task.id).unwrap();
6503 assert_eq!(saved.status, TaskStatus::Running);
6504 assert_eq!(saved.attempts, 1);
6505 assert!(saved.last_error.is_none());
6506 }
6507
6508 #[test]
6509 fn standalone_workers_do_not_consume_scheduler_lanes() {
6510 let request = |task: &str, lane, standalone| TaskWorker {
6511 opts: Opts::default(),
6512 queue: PathBuf::from("/queue"),
6513 task: task.to_owned(),
6514 lane,
6515 standalone,
6516 };
6517 let mut jobs = vec![
6518 request("ordinary", PermitKind::Ordinary, false),
6519 request("standalone-urgent", PermitKind::Urgent, true),
6520 request("standalone-ordinary", PermitKind::Ordinary, true),
6521 request("decision", PermitKind::None, false),
6522 ];
6523 assert_eq!(available_slots(&jobs, 2), (1, 1));
6524 jobs.push(request("urgent", PermitKind::Urgent, false));
6525 assert_eq!(available_slots(&jobs, 2), (1, 0));
6526 assert_eq!(available_slots(&jobs, 0), (0, 0));
6527 }
6528
6529 #[test]
6530 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6531 let now = Timestamp::now();
6532 let mut reading = Reading {
6533 pid: Some(std::process::id()),
6534 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6535 ..Reading::default()
6536 };
6537 assert!(!reading.running(now));
6538 assert!(legacy_scheduler_running(&reading, now, 0));
6539 reading.worker_protocol = Some(1);
6540 assert!(!legacy_scheduler_running(&reading, now, 0));
6541 }
6542
6543 #[test]
6544 fn selected_public_head_overrides_historical_resume_and_pin() {
6545 let mut t = task();
6546 let mut old = run_state(RunStatus::Blocked);
6547 let selection = crate::pr_recovery::Selection {
6548 url: "url".into(),
6549 branch: format!("magi/task-{}", t.id),
6550 head: "a".repeat(40),
6551 source_head: None,
6552 source_run: None,
6553 source_proof: None,
6554 disposition: Some(crate::pr_recovery::Disposition::Review),
6555 instruction: t.instruction.clone(),
6556 approved_at: Timestamp::now(),
6557 };
6558 t.resume_override = Some(crate::queue::OperatorResume {
6559 pinned_run: Some(old.id.clone()),
6560 question_id: "choice".into(),
6561 at: Timestamp::now(),
6562 conductor_rehold: None,
6563 forced: false,
6564 });
6565 assert_eq!(
6566 selected_starter(&selection, Some(&old), Some(&old.id)),
6567 Starter::Review(selection.branch.clone())
6568 );
6569 old.pr_recovery = Some(selection.clone());
6570 assert_eq!(
6571 selected_starter(&selection, Some(&old), Some(&old.id)),
6572 Starter::Review(selection.branch.clone())
6573 );
6574 old.reviewed_commits = Some(vec!["implementation".into()]);
6575 assert_eq!(
6576 selected_starter(&selection, Some(&old), Some(&old.id)),
6577 Starter::Resume(old.id.clone())
6578 );
6579 let mut changed = selection.clone();
6580 changed.head = "b".repeat(40);
6581 assert_eq!(
6582 selected_starter(&changed, Some(&old), Some(&old.id)),
6583 Starter::Review(changed.branch)
6584 );
6585 }
6586
6587 #[test]
6588 fn candidate_transplant_failure_is_one_actionable_hold() {
6589 let dir = tempfile::tempdir().unwrap();
6590 let q = Queue::at(dir.path().join("queue"));
6591 let mut t = task();
6592 let mut state = run_state(RunStatus::Blocked);
6593 state.event("prep", "cannot apply referenced commit: conflict");
6594 state.prep_failure = Some("conflict".into());
6595 t.start(state.id.clone());
6596 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6597 assert_eq!(t.attempts, 1);
6598 assert_eq!(t.status, TaskStatus::Held);
6599 assert!(t.operator_held());
6600 assert!(!t.status.runnable());
6601 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6602 let first = t.chat_notice_key().unwrap();
6603 t.chat_notices.push(first.clone());
6604 t.release_operator("test", None);
6605 state.id = "another-unprepared-run".into();
6606 t.start(state.id.clone());
6607 finish_attempt(
6608 3,
6609 &q,
6610 &mut t,
6611 &state,
6612 &[],
6613 Err(anyhow::anyhow!("still conflicts")),
6614 );
6615 assert_eq!(
6616 t.chat_notice_key().as_ref(),
6617 Some(&first),
6618 "no work happened"
6619 );
6620 t.release_operator("test", None);
6621 state.prep_failure = None;
6622 state.status = RunStatus::Failed;
6623 state.begin_pass();
6624 t.start(state.id.clone());
6625 finish_attempt(
6626 1,
6627 &q,
6628 &mut t,
6629 &state,
6630 &[],
6631 Err(anyhow::anyhow!("new gate failure")),
6632 );
6633 let failure = t.chat_notice_key().unwrap();
6634 assert_ne!(failure, first, "approved recovery reached a real failure");
6635 t.release_operator("test", None);
6636 state.begin_pass();
6637 t.start(state.id.clone());
6638 finish_attempt(
6639 1,
6640 &q,
6641 &mut t,
6642 &state,
6643 &[],
6644 Err(anyhow::anyhow!("new failure on resume")),
6645 );
6646 assert_ne!(
6647 t.chat_notice_key().as_ref(),
6648 Some(&failure),
6649 "a new settled pass"
6650 );
6651 }
6652
6653 #[test]
6654 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6655 for source in ["cli", "web"] {
6656 let mut t = task();
6657 let mut run = run_state(RunStatus::Blocked);
6658 run.instruction = "Run A original criteria".into();
6659 run.task_instruction = Some(run.instruction.clone());
6660 t.start(run.id.clone());
6661 t.release_operator("choice", Some("resume-question"));
6662 t.resume_override = Some(crate::queue::OperatorResume {
6663 question_id: "resume-question".into(),
6664 at: Timestamp::now(),
6665 conductor_rehold: None,
6666 forced: true,
6667 pinned_run: Some(run.id.clone()),
6668 });
6669 t.hold_machine(Some("not enough free space to start a run".into()));
6670 let mut unchanged = t.clone();
6671 unchanged
6672 .edit("title changed".into(), unchanged.instruction.clone())
6673 .unwrap();
6674 unchanged.release_operator(source, None);
6675 assert_eq!(
6676 unchanged
6677 .resume_override
6678 .as_ref()
6679 .unwrap()
6680 .pinned_run
6681 .as_deref(),
6682 Some(run.id.as_str())
6683 );
6684 assert!(!compatible_run_instruction(&run, &unchanged));
6685 assert!(may_resume_run(&run, &unchanged));
6686
6687 t.edit(
6688 "approved recovery".into(),
6689 "Reuse measured PR head B; fix Clippy; review".into(),
6690 )
6691 .unwrap();
6692 assert!(t.resume_override.is_none());
6693 t.release_operator(source, None);
6694 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6695 assert!(reloaded.resume_override.is_none());
6696 assert!(!may_resume_run(&run, &reloaded));
6697 let unfinished =
6698 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6699 .filter(|_| may_resume_run(&run, &reloaded));
6700 assert_eq!(
6701 choose_starter(None, false, unfinished.as_deref()),
6702 Starter::Start
6703 );
6704 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6705 assert_eq!(
6706 reloaded.resumption_history[0].question_id.as_deref(),
6707 Some("resume-question")
6708 );
6709
6710 unchanged.instruction = "Reuse measured PR head B".into();
6713 unchanged.hold_machine(Some("disk hold".into()));
6714 unchanged.release_operator(source, None);
6715 assert!(unchanged.resume_override.is_none());
6716 assert!(!may_resume_run(&run, &unchanged));
6717 }
6718 }
6719
6720 #[test]
6721 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6722 let mut t = task();
6723 let mut run = run_state(RunStatus::Blocked);
6724 t.review_of = Some("approved-head".into());
6725 t.instruction =
6726 "Review the branch `approved-head` (review-only: no implementation, no judging)."
6727 .into();
6728 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();
6729 run.reviewed_commits = Some(vec!["Commit log".into()]);
6730 t.start(run.id.clone());
6731 t.hold_machine(Some("interrupted review".into()));
6732 t.release_operator("cli", None);
6733 assert!(
6734 compatible_run_instruction(&run, &t),
6735 "legacy explicit review remains resumable"
6736 );
6737 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6738 .filter(|_| compatible_run_instruction(&run, &t));
6739 assert_eq!(
6740 choose_starter(None, false, unfinished.as_deref()),
6741 Starter::Resume(run.id.clone())
6742 );
6743 run.task_instruction = Some(t.instruction.clone());
6744 assert!(compatible_run_instruction(&run, &t));
6745 let reloaded: RunState =
6746 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6747 assert!(compatible_run_instruction(&reloaded, &t));
6748 t.edit(
6749 "new approved head".into(),
6750 "Reuse measured PR head B".into(),
6751 )
6752 .unwrap();
6753 assert!(!compatible_run_instruction(&run, &t));
6754
6755 t.review_of = None;
6757 t.instruction = "Fix Clippy on approved head".into();
6758 run.task_instruction = None;
6759 run.instruction = format!(
6760 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6761 t.instruction
6762 );
6763 assert!(compatible_run_instruction(&run, &t));
6764 t.instruction.push('\n');
6765 assert!(
6766 compatible_run_instruction(&run, &t),
6767 "legacy generated review trimmed the original criteria"
6768 );
6769 t.hold_for_handover(Some("approved-head".into()), "refused".into());
6770 let mut unchanged = t.clone();
6771 assert_eq!(
6772 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6773 Some("approved-head")
6774 );
6775 t.edit("new plan".into(), "Reuse measured PR head B".into())
6776 .unwrap();
6777 assert!(take_review_branch(&mut t, Some(&run)).is_none());
6778 assert!(!compatible_run_instruction(&run, &t));
6779 t.review_branch = Some("approved-head".into());
6780 t.review_instruction = None;
6781 assert!(
6782 take_review_branch(&mut t, Some(&run)).is_none(),
6783 "legacy retained candidate cannot replace a revised approved head"
6784 );
6785 }
6786
6787 #[test]
6788 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6789 crate::run::pin_test_home();
6790 let dir = tempfile::tempdir().unwrap();
6791 let queue = Queue::at(dir.path().join("queue"));
6792 for resume in [true, false] {
6793 let state = run_state(RunStatus::Blocked);
6794 let mut t = task();
6795 t.start(state.id.clone());
6796 let action = if resume {
6797 ask::ChoiceAction::Resume {
6798 run: state.id.clone(),
6799 }
6800 } else {
6801 ask::ChoiceAction::Requeue
6802 };
6803 let mut q = action_question(&state.id, action);
6804 q.status = ask::QuestionStatus::Open;
6805 q.answer = None;
6806 q.answered_at = None;
6807 t.fail("run stopped with a question", 3);
6808 hold_if_runnable(&queue, &mut t);
6809 assert!(t.operator_decided_at.is_none());
6810 assert!(t.operator_held());
6811 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6812 let expected = if resume {
6813 ActionDecision::Resume(state.id.clone())
6814 } else {
6815 ActionDecision::Requeue
6816 };
6817 assert_eq!(
6818 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6819 expected
6820 );
6821 t.hold_manual(Some("later explicit hold".into()));
6822 assert_eq!(
6823 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6824 ActionDecision::Stale
6825 );
6826 }
6827 }
6828
6829 #[test]
6830 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6831 let mut t = task();
6832 t.answers.push(crate::queue::AnsweredQuestion {
6833 question: "Inspect the remote?".into(),
6834 answer: "Inspect then wait".into(),
6835 });
6836 let old = instruction_for(&t);
6837 assert!(compatible_instruction(&old, &t));
6838 t.instruction = "Reuse approved PR head and review".into();
6839 t.release_operator("cli", None);
6840 assert!(!compatible_instruction(&old, &t));
6841 let approved = instruction_for(&t);
6842 assert!(approved.contains("waiting premises are superseded"));
6843 assert!(compatible_instruction(&approved, &t));
6844 assert_eq!(resumed_instruction(&approved, &t), approved);
6845 t.release_operator("web", None);
6846 assert!(compatible_instruction(&approved, &t));
6847 assert_eq!(t.resumption_history.len(), 1);
6848 t.start("run".into());
6849 assert!(instruction_for(&t).contains("Explicit operator resumption"));
6850 }
6851
6852 #[test]
6856 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6857 let mut state = RunState::new(
6858 PathBuf::from("/repo"),
6859 "main".into(),
6860 "base".into(),
6861 "task".into(),
6862 Config::default(),
6863 );
6864 state.status = RunStatus::Landing;
6865 state.parked = true;
6866 state.pr_pushed_head = Some("head".into());
6867 state.land_unrelated = Some(
6868 serde_json::from_value(serde_json::json!({
6869 "head": "head", "question": "ci-question",
6870 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6871 }))
6872 .unwrap(),
6873 );
6874 let mut t = task();
6875 t.start(state.id.clone());
6876 let verdict = Verdict {
6877 status: RunStatus::Landing,
6878 left_pr: true,
6879 quota_hit: false,
6880 parked: true,
6881 no_viable_candidates: false,
6882 };
6883 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6884 assert_eq!(t.attempts, 0);
6885 assert_eq!(t.status, TaskStatus::Held);
6886 assert!(!t.operator_held());
6887 assert!(
6888 t.hold_reason
6889 .as_deref()
6890 .unwrap()
6891 .starts_with("[ci-unrelated]")
6892 );
6893 t.attempts = 1;
6895 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6896 assert_eq!(t.attempts, 1);
6897 assert_eq!(t.passes.len(), 1);
6898 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6899 state.pr_pushed_head = Some("new-head".into());
6900 state.parked = false;
6901 state.status = RunStatus::Blocked;
6902 let stale = Verdict {
6903 status: RunStatus::Blocked,
6904 parked: false,
6905 ..verdict
6906 };
6907 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6908 assert_eq!(t.attempts, 1);
6909 state.begin_pass();
6911 state.begin_pass();
6912 state.status = RunStatus::Landing;
6913 state.parked = true;
6914 state.pr_pushed_head = Some("head".into());
6915 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6916 assert_eq!(t.attempts, 0);
6917 assert_eq!(t.passes.len(), 2);
6918 }
6919
6920 #[test]
6921 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6922 let mut state = run_state(RunStatus::Failed);
6923 state
6924 .quota
6925 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6926 state.begin_pass();
6927 let mut t = task();
6928 t.start(state.id.clone());
6929 reclaim(&mut t, Some(state), 2, "en");
6930 assert_eq!(t.attempts, 1);
6931 }
6932
6933 #[test]
6934 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6935 let mut state = run_state(RunStatus::Blocked);
6936 let losses: Vec<_> = ["alpha", "beta"]
6937 .into_iter()
6938 .enumerate()
6939 .map(|(i, agent)| {
6940 QuotaLoss::from_report(
6941 format!("advisor-{i}"),
6942 "advise",
6943 Some(&crate::agent::Quota {
6944 cause: crate::agent::QuotaCause::Authentication,
6945 agent: agent.to_owned(),
6946 reset: None,
6947 }),
6948 )
6949 })
6950 .collect();
6951 crate::graph::block_machine_outage(&mut state, "advise", &losses);
6952 state.quota = losses;
6953 let mut t = task();
6954 t.start(state.id.clone());
6955 let verdict = Verdict {
6956 status: state.status,
6957 left_pr: false,
6958 quota_hit: true,
6959 parked: false,
6960 no_viable_candidates: true,
6961 };
6962 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
6963 assert_eq!(t.attempts, 0);
6964 assert_eq!(t.status, TaskStatus::Held);
6965 assert!(!t.operator_held());
6966 let reason = t.hold_reason.as_deref().unwrap();
6967 assert!(reason.starts_with("[authentication]"));
6968 assert!(
6969 reason.contains("alpha")
6970 && reason.contains("beta")
6971 && reason.contains("re-authenticate")
6972 );
6973 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
6974 let mut orphan = task();
6976 orphan.start(state.id.clone());
6977 reclaim(&mut orphan, Some(state), 2, "en");
6978 assert_eq!(orphan.attempts, 0);
6979 assert_eq!(orphan.status, TaskStatus::Held);
6980 }
6981
6982 #[test]
6983 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6984 let mut state = RunState::new(
6985 PathBuf::from("/repo"),
6986 "main".to_owned(),
6987 "abc1234".to_owned(),
6988 "task".to_owned(),
6989 Config::default(),
6990 );
6991 state.status = RunStatus::Blocked;
6992 state.resource_block = Some(crate::run::ResourceBlock {
6993 cause: crate::run::ResourceBlockCause::Other,
6994 node: "graft".to_owned(),
6995 kind: "shared build cache".to_owned(),
6996 detail: "timed out".to_owned(),
6997 at: jiff::Timestamp::now(),
6998 });
6999 let mut t = task();
7000 t.start("20260902-000000-aaaa".to_owned());
7001 assert_eq!(t.attempts, 1);
7002 let verdict = Verdict {
7003 status: RunStatus::Blocked,
7004 left_pr: false,
7005 quota_hit: false,
7006 parked: false,
7007 no_viable_candidates: false,
7008 };
7009 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7010 assert_eq!(t.status, TaskStatus::Held);
7011 assert_eq!(t.attempts, 0, "the attempt is refunded");
7012 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7013 assert!(
7014 !t.operator_held(),
7015 "a machine hold, released without a human"
7016 );
7017
7018 let mut selected = task();
7019 selected.start("20260902-000000-cccc".into());
7020 selected.replacement = Some(crate::merge_decision::Replacement {
7021 question: "fixture".into(),
7022 run: "earlier".into(),
7023 pr: "https://example.invalid/pr/1".into(),
7024 agent: "selected".into(),
7025 context: "fixture".into(),
7026 });
7027 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7028 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7029 assert_eq!(selected.attempts, 0);
7030 assert!(
7031 !selected.operator_held(),
7032 "a selected agent also retains a machine resource hold"
7033 );
7034 assert!(
7035 selected
7036 .hold_reason
7037 .as_deref()
7038 .unwrap()
7039 .starts_with("[resource] ")
7040 );
7041
7042 let mut p = task();
7044 p.start("20260902-000000-bbbb".to_owned());
7045 settle_and_diagnose(
7046 &mut p,
7047 Verdict {
7048 parked: true,
7049 ..verdict
7050 },
7051 "parked",
7052 2,
7053 &state,
7054 );
7055 assert_eq!(p.status, TaskStatus::Parked);
7056 assert_eq!(
7057 p.attempts, 0,
7058 "parking refunds once rather than also settling the resource hold"
7059 );
7060 }
7061
7062 #[test]
7063 fn record_failure_notice_links_the_task() {
7064 let dir = tempfile::tempdir().unwrap();
7065 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7068 let queue = Queue::at(dir.path().join("queue"));
7069 let mut t = interrupt_task("rec-fail-1");
7070 record(&queue, &mut t);
7071
7072 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7073 assert_eq!(found.len(), 1);
7074 assert_eq!(found[0].key, "loop:record");
7075 assert_eq!(
7076 found[0].link,
7077 Some(Link::Task {
7078 id: "rec-fail-1".to_owned()
7079 })
7080 );
7081 }
7082
7083 fn interrupt_task(id: &str) -> Task {
7086 let mut t = task();
7087 t.id = id.to_owned();
7088 t.interrupt = true;
7089 t
7090 }
7091
7092 fn task_with_id(id: &str) -> Task {
7094 let mut t = task();
7095 t.id = id.to_owned();
7096 t
7097 }
7098
7099 fn urgent_task(id: &str) -> Task {
7101 let mut t = task();
7102 t.id = id.to_owned();
7103 t.urgent = true;
7104 t
7105 }
7106
7107 #[test]
7108 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7109 let dir = tempfile::tempdir().unwrap();
7110 let queue = Queue::at(dir.path().join("queue"));
7111 let mut parked = task_with_id("parked");
7112 parked.start("run".into());
7113 parked.park("upgrade");
7114 parked.record_pass_at(
7115 "run",
7116 0,
7117 Some(Timestamp::now()),
7118 1,
7119 Some(crate::run::ParkCause::Upgrade {
7120 from: "old".into(),
7121 to: None,
7122 }),
7123 );
7124 let mut fresh = task_with_id("fresh");
7125 fresh.priority = 100;
7126 let mut urgent_task = urgent_task("urgent");
7127 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7128 queue.put(t).unwrap();
7129 }
7130 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7131 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7132 let candidates = runnable(&queue);
7133 assert_eq!(candidates[0].id, parked.id);
7134 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7135 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7136 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7137 drop(first);
7138 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7139 let next = runnable(&queue)
7140 .into_iter()
7141 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7142 .unwrap();
7143 assert_eq!(next.task.id, fresh.id);
7144 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7145 drop(claimed_elsewhere);
7146 drop(next);
7147 assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7148 }
7149
7150 #[test]
7151 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7152 let dir = tempfile::tempdir().unwrap();
7153 let queue = Queue::at(dir.path().join("queue"));
7154 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7155 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7156 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7157 let mut first = task();
7158 queue.put(&mut first).unwrap();
7159 let stale_plain = queue.get(&first.id).unwrap();
7160 first.set_urgent(true).unwrap();
7161 queue.put(&mut first).unwrap();
7162 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7163 let mut second = urgent_task("second");
7164 queue.put(&mut second).unwrap();
7165 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7166 drop(queue.claim(&second.id).unwrap());
7167 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7168 drop(dispatched);
7169 let stale_urgent = queue.get(&first.id).unwrap();
7170 first.set_urgent(false).unwrap();
7171 queue.put(&mut first).unwrap();
7172 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7173 assert_eq!(urgent.available_permits(), 1);
7174 drop(queue.claim(&first.id).unwrap());
7175 drop(occupied);
7176 }
7177
7178 #[test]
7179 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7180 let dir = tempfile::tempdir().unwrap();
7181 let queue = Queue::at(dir.path().join("queue"));
7182 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7183 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7184 let mut t = task();
7185 queue.put(&mut t).unwrap();
7186 for enabled in [true, false] {
7187 let stale = queue.get(&t.id).unwrap();
7188 t.set_urgent(enabled).unwrap();
7189 queue.put(&mut t).unwrap();
7190 assert_ne!(stale.urgent, enabled);
7191 let DispatchClaim {
7192 task: fresh,
7193 claim,
7194 permit,
7195 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7196 assert_eq!(fresh.urgent, enabled);
7197 assert_eq!(ordinary.available_permits(), usize::from(enabled));
7198 assert_eq!(urgent.available_permits(), usize::from(!enabled));
7199 assert!(queue.claim(&t.id).is_err());
7200 assert_eq!(fresh.attempts, stale.attempts);
7201 drop((claim, permit));
7202 assert_eq!(ordinary.available_permits(), 1);
7203 assert_eq!(urgent.available_permits(), 1);
7204 }
7205 t.set_urgent(true).unwrap();
7206 queue.put(&mut t).unwrap();
7207 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7208 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7209 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7210 drop(queue.claim(&t.id).unwrap());
7211 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7212 drop(occupied);
7213 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7214 drop(queue.claim(&t.id).unwrap());
7215 let held = queue.claim(&t.id).unwrap();
7216 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7217 drop(held);
7218 t.status = TaskStatus::Held;
7219 queue.put(&mut t).unwrap();
7220 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7221 drop(queue.claim(&t.id).unwrap());
7222 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7223 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7224 drop(queue.claim(&t.id).unwrap());
7225 assert_eq!(urgent.available_permits(), 1);
7226 }
7227
7228 #[test]
7233 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7234 assert_eq!(permit_kind(true, false), PermitKind::None);
7235 assert_eq!(permit_kind(true, true), PermitKind::None);
7236 }
7237
7238 #[test]
7243 fn permit_kind_separates_urgent_from_ordinary() {
7244 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7245 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7246 }
7247
7248 #[test]
7255 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7256 let cfg = Config::default();
7257 let repo = Path::new("/any/repo/path");
7258
7259 let reason =
7260 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7261 assert!(reason.contains("1024"), "{reason}");
7262 assert!(
7263 reason.contains(&cfg.disk.min_free_bytes.to_string()),
7264 "{reason}"
7265 );
7266
7267 assert_eq!(
7268 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7269 None,
7270 "exactly at the floor is open"
7271 );
7272 assert_eq!(
7273 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7274 None,
7275 "comfortably above the floor is open"
7276 );
7277 }
7278
7279 #[test]
7280 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7281 let mut cfg = Config::default();
7282 cfg.disk.min_free_bytes = 0;
7283 let repo = Path::new("/any/repo/path");
7284 assert_eq!(
7285 disk_gate_with(repo, &cfg, |_| Ok(0)),
7286 None,
7287 "a zero floor never measures at all"
7288 );
7289 }
7290
7291 #[test]
7292 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7293 let cfg = Config::default();
7294 let repo = Path::new("/any/repo/path");
7295 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7296 .expect("a measurement failure must close the gate, not open it");
7297 assert!(reason.contains("could not measure"), "{reason}");
7298 }
7299
7300 #[test]
7301 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7302 let ordinary = task();
7303 let next = advance_interrupt(
7304 Interrupt::Idle,
7305 std::slice::from_ref(&ordinary.id),
7306 std::slice::from_ref(&ordinary),
7307 );
7308 assert_eq!(next, Interrupt::Idle);
7309 }
7310
7311 #[test]
7312 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7313 let marked = interrupt_task("marked");
7316 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7317 assert_eq!(next, Interrupt::Idle);
7318 }
7319
7320 #[test]
7321 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7322 let marked = interrupt_task("marked");
7323 let next = advance_interrupt(
7324 Interrupt::Idle,
7325 &["running".to_owned()],
7326 std::slice::from_ref(&marked),
7327 );
7328 assert_eq!(
7329 next,
7330 Interrupt::Parking {
7331 parked: vec!["running".to_owned()],
7332 interrupt_task: "marked".to_owned(),
7333 }
7334 );
7335 }
7336
7337 #[test]
7346 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7347 let marked = interrupt_task("marked");
7348
7349 let two = advance_interrupt(
7350 Interrupt::Idle,
7351 &["a".to_owned(), "b".to_owned()],
7352 std::slice::from_ref(&marked),
7353 );
7354 assert_eq!(two, Interrupt::Idle);
7355
7356 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7357 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7358 }
7359
7360 #[test]
7361 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7362 let state = Interrupt::Parking {
7363 parked: vec!["running".to_owned()],
7364 interrupt_task: "marked".to_owned(),
7365 };
7366 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7368 assert_eq!(still_going, state);
7369
7370 let stopped_but_not_yet_dispatched =
7374 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7375 assert_eq!(stopped_but_not_yet_dispatched, state);
7376
7377 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7379 assert_eq!(
7380 dispatched,
7381 Interrupt::Running {
7382 parked: vec!["running".to_owned()],
7383 interrupt_task: "marked".to_owned(),
7384 }
7385 );
7386 }
7387
7388 #[test]
7389 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7390 let state = Interrupt::Running {
7391 parked: vec!["running".to_owned()],
7392 interrupt_task: "marked".to_owned(),
7393 };
7394 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7395 assert_eq!(still_running, state);
7396
7397 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7404 assert_eq!(
7405 ended,
7406 Interrupt::Resuming {
7407 parked: vec!["running".to_owned()]
7408 }
7409 );
7410 }
7411
7412 #[test]
7413 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7414 let state = Interrupt::Resuming {
7415 parked: vec!["running".to_owned()],
7416 };
7417 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7418 assert_eq!(still_waiting, state);
7419
7420 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7421 assert_eq!(dispatched, Interrupt::Idle);
7422 }
7423
7424 #[test]
7430 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7431 {
7432 let state = Interrupt::Parking {
7433 parked: vec!["running".to_owned()],
7434 interrupt_task: "marked".to_owned(),
7435 };
7436 let next = advance_interrupt(state, &[], &[]);
7439 assert_eq!(
7440 next,
7441 Interrupt::Resuming {
7442 parked: vec!["running".to_owned()]
7443 },
7444 "abandoning the interrupt must not abandon the resume it owes"
7445 );
7446 }
7447
7448 #[test]
7451 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7452 let state = Interrupt::Resuming {
7453 parked: vec!["running".to_owned()],
7454 };
7455 let next = advance_interrupt(state, &[], &[]);
7456 assert_eq!(
7457 next,
7458 Interrupt::Idle,
7459 "nothing is left to wait for; the loop must not stay wedged"
7460 );
7461 }
7462
7463 #[test]
7464 fn disabled_by_config_the_sequence_can_never_leave_idle() {
7465 let marked = interrupt_task("marked");
7466 let next = advance_interrupt_tick(
7467 false,
7468 Interrupt::Idle,
7469 &["running".to_owned()],
7470 std::slice::from_ref(&marked),
7471 );
7472 assert_eq!(
7473 next,
7474 Interrupt::Idle,
7475 "an unmarked, unconfigured daemon must behave exactly as before"
7476 );
7477 }
7478
7479 #[test]
7480 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7481 let state = Interrupt::Parking {
7482 parked: vec!["running".to_owned()],
7483 interrupt_task: "marked".to_owned(),
7484 };
7485 let candidates = vec![interrupt_task("marked"), task()];
7486 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7487 assert!(
7488 allowed.is_empty(),
7489 "nothing may dispatch - not even the interrupt task itself - \
7490 until the parked run has actually stopped"
7491 );
7492 }
7493
7494 #[test]
7508 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7509 for state in [
7510 Interrupt::Parking {
7511 parked: vec!["running".to_owned()],
7512 interrupt_task: "marked".to_owned(),
7513 },
7514 Interrupt::Running {
7515 parked: vec!["running".to_owned()],
7516 interrupt_task: "marked".to_owned(),
7517 },
7518 Interrupt::Resuming {
7519 parked: vec!["running".to_owned()],
7520 },
7521 ] {
7522 let candidates = vec![
7523 interrupt_task("marked"),
7524 urgent_task("hot"),
7525 task_with_id("ordinary"),
7526 ];
7527 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7528 assert!(
7529 !allowed.iter().any(|t| t.id == "hot"),
7530 "an urgent candidate must wait out the same gate as anything \
7531 else while the run it would run alongside has not actually \
7532 left flight, for state {state:?}: {allowed:?}"
7533 );
7534 }
7535 }
7536
7537 #[test]
7543 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7544 let state = Interrupt::Resuming {
7545 parked: vec!["hot".to_owned()],
7546 };
7547 let candidates = vec![urgent_task("hot"), task()];
7548 let allowed = interrupt_gate(&state, &[], candidates);
7549 assert_eq!(
7550 allowed.iter().filter(|t| t.id == "hot").count(),
7551 1,
7552 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7553 );
7554 }
7555
7556 #[test]
7557 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7558 let state = Interrupt::Parking {
7559 parked: vec!["running".to_owned()],
7560 interrupt_task: "marked".to_owned(),
7561 };
7562 let other = task();
7563 let candidates = vec![interrupt_task("marked"), other.clone()];
7564 let allowed = interrupt_gate(&state, &[], candidates);
7565 assert_eq!(allowed.len(), 1);
7566 assert_eq!(allowed[0].id, "marked");
7567 }
7568
7569 #[test]
7570 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7571 let state = Interrupt::Running {
7572 parked: vec!["running".to_owned()],
7573 interrupt_task: "marked".to_owned(),
7574 };
7575 let candidates = vec![task(), task()];
7576 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7577 assert!(allowed.is_empty());
7578 }
7579
7580 #[test]
7587 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7588 let state = Interrupt::Resuming {
7589 parked: vec!["a".to_owned(), "c".to_owned()],
7590 };
7591 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7592 let allowed = interrupt_gate(&state, &[], candidates);
7593 assert_eq!(
7594 allowed.len(),
7595 1,
7596 "at most one candidate may be offered while resuming: {allowed:?}"
7597 );
7598 assert_eq!(allowed[0].id, "a");
7599 }
7600
7601 #[test]
7602 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7603 let state = Interrupt::Resuming {
7604 parked: vec!["a".to_owned()],
7605 };
7606 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7607 assert!(allowed.is_empty());
7608 }
7609
7610 #[test]
7616 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7617 let running = task(); let marked = interrupt_task("marked");
7619
7620 let mut state = Interrupt::Idle;
7621 let in_flight = vec![running.id.clone()];
7623 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7624 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7625 assert!(gated.is_empty(), "still waiting on `running` to park");
7626
7627 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7629 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7630 assert_eq!(
7631 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7632 vec!["marked"],
7633 "only the interrupt task may be offered to the dispatcher now"
7634 );
7635
7636 state = advance_interrupt_tick(
7638 true,
7639 state,
7640 &["marked".to_owned()],
7641 std::slice::from_ref(&running),
7642 );
7643 let gated = interrupt_gate(
7644 &state,
7645 &["marked".to_owned()],
7646 vec![marked.clone(), running.clone()],
7647 );
7648 assert!(
7649 gated.is_empty(),
7650 "the parked run must not be offered back while the interrupt \
7651 task is still running"
7652 );
7653
7654 let other = task_with_id("other");
7658 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7659 assert_eq!(
7660 state,
7661 Interrupt::Resuming {
7662 parked: vec![running.id.clone()]
7663 }
7664 );
7665 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7666 assert_eq!(
7667 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7668 vec![running.id.as_str()],
7669 "exactly the parked run resumes - not the unrelated task, even \
7670 though it was offered first"
7671 );
7672
7673 state = advance_interrupt_tick(
7677 true,
7678 state,
7679 std::slice::from_ref(&running.id),
7680 std::slice::from_ref(&other),
7681 );
7682 assert_eq!(state, Interrupt::Idle);
7683 let gated = interrupt_gate(
7684 &state,
7685 std::slice::from_ref(&running.id),
7686 vec![other.clone()],
7687 );
7688 assert_eq!(
7689 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7690 vec![other.id.as_str()],
7691 "ordinary dispatch is unrestricted again"
7692 );
7693 }
7694
7695 #[test]
7696 fn every_run_status_settles_the_task_it_came_from() {
7697 let table = [
7699 (RunStatus::Merged, TaskStatus::Done, 1),
7700 (RunStatus::Ready, TaskStatus::Done, 1),
7701 (RunStatus::Stalled, TaskStatus::Failed, 0),
7702 (RunStatus::Blocked, TaskStatus::Failed, 1),
7703 (RunStatus::Failed, TaskStatus::Failed, 1),
7704 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7705 (RunStatus::Prep, TaskStatus::Failed, 1),
7706 (RunStatus::Implementing, TaskStatus::Failed, 1),
7707 (RunStatus::Judging, TaskStatus::Failed, 1),
7708 (RunStatus::Deliberating, TaskStatus::Failed, 1),
7709 (RunStatus::Voting, TaskStatus::Failed, 1),
7710 (RunStatus::Reviewing, TaskStatus::Failed, 1),
7711 (RunStatus::Gating, TaskStatus::Failed, 1),
7712 ];
7713 for (run, want, attempts) in table {
7714 let mut t = task();
7715 t.start("20260902-000000-aaaa".to_owned());
7716 settle(
7717 &mut t,
7718 Verdict {
7719 status: run,
7720 left_pr: false,
7721 parked: false,
7722 quota_hit: matches!(run, RunStatus::Stalled),
7723 no_viable_candidates: false,
7724 },
7725 "why",
7726 2,
7727 );
7728 assert_eq!(t.status, want, "task status after {}", label(run));
7729 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7730 }
7731 }
7732
7733 #[test]
7734 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7735 let mut stalled = task();
7736 stalled.start("20260902-000000-aaaa".to_owned());
7737 settle(
7738 &mut stalled,
7739 Verdict {
7740 status: RunStatus::Stalled,
7741 left_pr: false,
7742 parked: false,
7743 quota_hit: true,
7744 no_viable_candidates: false,
7745 },
7746 "quota",
7747 1,
7748 );
7749 assert_eq!(stalled.attempts, 0);
7750 assert!(
7751 stalled.status.runnable(),
7752 "a machine problem must leave the task in line"
7753 );
7754
7755 let mut blocked = task();
7756 blocked.start("20260902-000000-aaaa".to_owned());
7757 settle(
7758 &mut blocked,
7759 Verdict {
7760 status: RunStatus::Blocked,
7761 left_pr: false,
7762 parked: false,
7763 quota_hit: false,
7764 no_viable_candidates: false,
7765 },
7766 "findings open",
7767 1,
7768 );
7769 assert_eq!(blocked.attempts, 1);
7770 assert_eq!(
7771 blocked.status,
7772 TaskStatus::Held,
7773 "the last attempt hands the task to a human"
7774 );
7775 }
7776
7777 #[test]
7778 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7779 let mut delivered = task();
7782 delivered.start("20260903-080619-01c2".to_owned());
7783 settle(
7784 &mut delivered,
7785 Verdict {
7786 status: RunStatus::Blocked,
7787 left_pr: true,
7788 parked: false,
7789 quota_hit: false,
7790 no_viable_candidates: false,
7791 },
7792 "no check status",
7793 4,
7794 );
7795 assert_eq!(
7796 delivered.status,
7797 TaskStatus::Held,
7798 "a pull request waiting on CI or a person is not a retryable failure"
7799 );
7800 assert!(
7801 !delivered.status.runnable(),
7802 "the loop must not pick this task up again"
7803 );
7804 assert_eq!(
7805 delivered.last_error.as_deref(),
7806 Some("no check status"),
7807 "the operator needs to be told what the gate was waiting for"
7808 );
7809
7810 let mut empty_handed = task();
7813 empty_handed.start("20260903-080619-01c2".to_owned());
7814 settle(
7815 &mut empty_handed,
7816 Verdict {
7817 status: RunStatus::Blocked,
7818 left_pr: false,
7819 parked: false,
7820 quota_hit: false,
7821 no_viable_candidates: false,
7822 },
7823 "findings open",
7824 4,
7825 );
7826 assert_eq!(empty_handed.status, TaskStatus::Failed);
7827 assert!(empty_handed.status.runnable());
7828 }
7829
7830 #[test]
7831 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7832 let mut noop = task();
7838 noop.start("20260912-131304-391f".to_owned());
7839 settle(
7840 &mut noop,
7841 Verdict {
7842 status: RunStatus::VerifiedNoop,
7843 left_pr: false,
7844 parked: false,
7845 quota_hit: false,
7846 no_viable_candidates: true,
7847 },
7848 "candidate A: already fixed by b32cfc4, on main",
7849 4,
7850 );
7851 assert_eq!(
7852 noop.status,
7853 TaskStatus::Held,
7854 "an unverified claim is a request for a human, not a failure"
7855 );
7856 assert!(
7857 !noop.status.runnable(),
7858 "the loop must not requeue this on the same unverified claim"
7859 );
7860 assert_eq!(noop.attempts, 1);
7865 }
7866
7867 #[test]
7868 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7869 let mut parked = task();
7874 parked.start("20260903-183634-2d98".to_owned());
7875 settle(
7876 &mut parked,
7877 Verdict {
7878 status: RunStatus::Implementing,
7879 left_pr: false,
7880 quota_hit: false,
7881 parked: true,
7882 no_viable_candidates: false,
7883 },
7884 "parked after `implementing`",
7885 2,
7886 );
7887 assert_eq!(parked.attempts, 0, "a park is refunded");
7888 assert!(
7889 parked.status.runnable(),
7890 "and the task stays in line so the next loop resumes its run"
7891 );
7892 assert_eq!(parked.status, TaskStatus::Parked);
7893 assert_eq!(
7894 parked.park_reason.as_deref(),
7895 Some("parked after `implementing`"),
7896 "the card says where it stopped"
7897 );
7898 assert_eq!(parked.last_error, None, "nothing failed");
7899
7900 let mut broken = task();
7904 broken.start("20260903-183634-2d98".to_owned());
7905 settle(
7906 &mut broken,
7907 Verdict {
7908 status: RunStatus::Implementing,
7909 left_pr: false,
7910 quota_hit: false,
7911 parked: false,
7912 no_viable_candidates: false,
7913 },
7914 "returned mid-flight",
7915 2,
7916 );
7917 assert_eq!(broken.attempts, 1);
7918 }
7919
7920 #[test]
7921 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7922 let mut flaky = task();
7927 flaky.start("20260903-123023-e633".to_owned());
7928 settle(
7929 &mut flaky,
7930 Verdict {
7931 status: RunStatus::Stalled,
7932 left_pr: false,
7933 parked: false,
7934 quota_hit: false,
7935 no_viable_candidates: false,
7936 },
7937 "verdict rests on 1 of 3 judges",
7938 2,
7939 );
7940 assert_eq!(
7941 flaky.attempts, 1,
7942 "flakiness spends an attempt, so `max_attempts` still bounds it"
7943 );
7944 assert!(flaky.status.runnable(), "and it is still worth retrying");
7945
7946 let mut limited = task();
7948 limited.start("20260903-123023-e633".to_owned());
7949 settle(
7950 &mut limited,
7951 Verdict {
7952 status: RunStatus::Stalled,
7953 left_pr: false,
7954 parked: false,
7955 quota_hit: true,
7956 no_viable_candidates: false,
7957 },
7958 "judge-2, judge-3 out of quota",
7959 2,
7960 );
7961 assert_eq!(limited.attempts, 0, "a quota window is refunded");
7962 assert!(limited.status.runnable());
7963
7964 let mut worn = task();
7967 for _ in 0..2 {
7968 worn.release();
7969 }
7970 worn.start("20260903-123023-e633".to_owned());
7971 worn.attempts = 2;
7972 settle(
7973 &mut worn,
7974 Verdict {
7975 status: RunStatus::Stalled,
7976 left_pr: false,
7977 parked: false,
7978 quota_hit: false,
7979 no_viable_candidates: false,
7980 },
7981 "no quorum again",
7982 2,
7983 );
7984 assert_eq!(worn.status, TaskStatus::Held);
7985 assert!(!worn.status.runnable());
7986 }
7987
7988 #[test]
7989 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7990 let mut wiped_out = task();
7997 wiped_out.start("20260907-025000-a1b2".to_owned());
7998 settle(
7999 &mut wiped_out,
8000 Verdict {
8001 status: RunStatus::Failed,
8002 left_pr: false,
8003 parked: false,
8004 quota_hit: true,
8005 no_viable_candidates: true,
8006 },
8007 "no candidate produced a change; nothing to judge",
8008 2,
8009 );
8010 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8011 assert!(
8012 wiped_out.status.runnable(),
8013 "a machine problem must leave the task in line"
8014 );
8015
8016 let mut partial_progress = task();
8022 partial_progress.start("20260907-025500-c3d4".to_owned());
8023 settle(
8024 &mut partial_progress,
8025 Verdict {
8026 status: RunStatus::Failed,
8027 left_pr: false,
8028 parked: false,
8029 quota_hit: true,
8030 no_viable_candidates: false,
8031 },
8032 "gate failed on the winning candidate",
8033 2,
8034 );
8035 assert_eq!(
8036 partial_progress.attempts, 1,
8037 "a candidate that actually produced a change spends the attempt \
8038 even though some other seat hit its quota"
8039 );
8040 assert!(partial_progress.status.runnable());
8041 }
8042
8043 #[test]
8044 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8045 let mut t = task();
8051 t.start("20260907-025000-a1b2".to_owned());
8052 let mut state = run_state(RunStatus::Failed);
8053 state.quota.push(QuotaLoss {
8054 cause: crate::agent::QuotaCause::UsageLimit,
8055 agent: String::new(),
8056 seat: "cand-a".to_owned(),
8057 node: "implement".to_owned(),
8058 at: Timestamp::now(),
8059 reset: None,
8060 });
8061 assert!(
8062 state.viable().is_empty(),
8063 "no candidate was added, so nothing is viable"
8064 );
8065 reclaim(&mut t, Some(state), 2, "en");
8066 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8067 assert!(t.status.runnable());
8068 }
8069
8070 #[test]
8071 fn a_held_task_is_never_offered_to_the_loop() {
8072 let dir = tempfile::tempdir().unwrap();
8073 let queue = Queue::at(dir.path().to_path_buf());
8074 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8075 let mut t = task();
8076 t.id = format!("2026090{n}-000000-000{n}");
8077 t.priority = priority;
8078 queue.put(&mut t).unwrap();
8079 }
8080 let mut held = task();
8081 held.id = "20260909-000000-9999".to_owned();
8082 held.priority = 99;
8083 held.hold_machine(None);
8084 queue.put(&mut held).unwrap();
8085
8086 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8087 assert_eq!(order.len(), 3);
8088 assert!(!order.contains(&held.id));
8089 assert_eq!(
8090 order.first().cloned(),
8091 queue.next_runnable().map(|t| t.id),
8092 "the loop's first candidate is exactly what the queue offers"
8093 );
8094 assert_eq!(
8095 order,
8096 vec![
8097 "20260902-000000-0002".to_owned(),
8098 "20260903-000000-0003".to_owned(),
8099 "20260901-000000-0001".to_owned(),
8100 ],
8101 "priority first, then oldest, so nothing starves"
8102 );
8103 }
8104
8105 #[test]
8106 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8107 let dir = tempfile::tempdir().unwrap();
8108 let queue = Queue::at(dir.path().to_path_buf());
8109 let mut old = task();
8110 old.id = "20260101-000000-old0".to_owned();
8111 queue.put(&mut old).unwrap();
8112 let mut fresh = task();
8113 fresh.id = "20260101-000000-new0".to_owned();
8114 queue.put(&mut fresh).unwrap();
8115
8116 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8120 std::thread::sleep(Duration::from_millis(60));
8121 let live = queue.claim(&fresh.id).unwrap();
8122
8123 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8124 assert_eq!(swept, vec![old.id.clone()]);
8125 assert!(
8126 queue.claim(&old.id).is_ok(),
8127 "an unparseable lock older than the threshold is swept"
8128 );
8129 assert!(
8130 queue.claim(&fresh.id).is_err(),
8131 "a live pid protects its lock regardless of age"
8132 );
8133 drop(live);
8134 }
8135
8136 #[test]
8137 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8138 let dir = tempfile::tempdir().unwrap();
8141 let queue = Queue::at(dir.path().to_path_buf());
8142 let mut t = task();
8143 t.id = "20260101-000000-live".to_owned();
8144 queue.put(&mut t).unwrap();
8145
8146 let claim = queue.claim(&t.id).unwrap();
8147 std::thread::sleep(Duration::from_millis(60));
8148
8149 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8150 assert!(
8151 swept.is_empty(),
8152 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8153 );
8154 assert!(
8155 queue.claim(&t.id).is_err(),
8156 "the lock still protects its task"
8157 );
8158 drop(claim);
8159 }
8160
8161 fn injected_dead_pid() -> u32 {
8164 std::process::id().checked_add(1).unwrap_or(1)
8165 }
8166
8167 #[test]
8168 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8169 let dir = tempfile::tempdir().unwrap();
8170 let queue = Queue::at(dir.path().to_path_buf());
8171 let mut t = task();
8172 t.id = "20260101-000000-dead".to_owned();
8173 queue.put(&mut t).unwrap();
8174 let dead_pid = injected_dead_pid();
8175
8176 std::fs::write(
8181 dir.path().join(format!("{}.lock", t.id)),
8182 dead_pid.to_string(),
8183 )
8184 .unwrap();
8185
8186 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8187 pid != dead_pid
8188 });
8189 assert_eq!(
8190 swept,
8191 vec![t.id.clone()],
8192 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8193 );
8194 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8195 }
8196
8197 #[test]
8198 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8199 let dir = tempfile::tempdir().unwrap();
8200 let queue = Queue::at(dir.path().to_path_buf());
8201 let mut t = task();
8202 t.id = "20260101-000000-late".to_owned();
8203 queue.put(&mut t).unwrap();
8204 let dead_pid = injected_dead_pid();
8205
8206 assert!(
8209 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8210 "nothing has claimed the task yet"
8211 );
8212
8213 std::fs::write(
8216 dir.path().join(format!("{}.lock", t.id)),
8217 dead_pid.to_string(),
8218 )
8219 .unwrap();
8220
8221 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8225 pid != dead_pid
8226 });
8227 assert_eq!(swept, vec![t.id.clone()]);
8228 }
8229
8230 #[test]
8231 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8232 crate::run::pin_test_home();
8237 let dir = tempfile::tempdir().unwrap();
8238 let queue = Queue::at(dir.path().to_path_buf());
8239 let mut t = task();
8240 t.id = "20260101-000000-crsh".to_owned();
8241 t.status = TaskStatus::Running;
8242 t.attempts = 1;
8243 t.runs.push("20260904-000000-4043".to_owned());
8247 queue.put(&mut t).unwrap();
8248 let dead_pid = injected_dead_pid();
8249
8250 std::fs::write(
8253 dir.path().join(format!("{}.lock", t.id)),
8254 dead_pid.to_string(),
8255 )
8256 .unwrap();
8257
8258 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8264 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8265
8266 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8267 pid != dead_pid
8268 });
8269 assert_eq!(swept, vec![t.id.clone()]);
8270
8271 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8272 assert_eq!(reclaimed, vec![t.id.clone()]);
8273 let after = queue.get(&t.id).unwrap();
8274 assert_eq!(
8275 after.status,
8276 TaskStatus::Held,
8277 "no run.json to recover from, so a human is asked"
8278 );
8279 assert_eq!(
8280 after.runs,
8281 vec!["20260904-000000-4043".to_owned()],
8282 "the crashed run's id is kept as evidence, not discarded"
8283 );
8284 }
8285
8286 #[test]
8287 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8288 let dir = tempfile::tempdir().unwrap();
8289 let queue = Queue::at(dir.path().to_path_buf());
8290 let mut t = task();
8291 t.id = "20260101-000000-unknown".to_owned();
8292 queue.put(&mut t).unwrap();
8293 let dead_pid = injected_dead_pid();
8294 std::fs::write(
8295 dir.path().join(format!("{}.lock", t.id)),
8296 dead_pid.to_string(),
8297 )
8298 .unwrap();
8299
8300 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8301 assert!(swept.is_empty(), "an unknown pid must keep its lock");
8302 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8303 }
8304
8305 fn run_state_in(status: RunStatus, language: &str) -> RunState {
8306 let mut s = run_state(status);
8307 s.config.graph.language = language.to_owned();
8308 s
8309 }
8310
8311 fn unstarted_verdict(status: RunStatus) -> Verdict {
8312 Verdict {
8313 status,
8314 left_pr: false,
8315 quota_hit: false,
8316 parked: false,
8317 no_viable_candidates: false,
8318 }
8319 }
8320
8321 #[test]
8322 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8323 let mut t = task();
8324 t.attempts = 1;
8325 settle_in(
8326 &mut t,
8327 unstarted_verdict(RunStatus::AlreadyInBase),
8328 "already in main",
8329 1,
8330 phrases("en"),
8331 );
8332 assert_eq!(t.status, TaskStatus::Done);
8333 assert_eq!(t.attempts, 0);
8334 }
8335
8336 #[test]
8337 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8338 let reason = |language: &str| {
8339 let mut t = task();
8340 settle_in(
8341 &mut t,
8342 unstarted_verdict(RunStatus::Judging),
8343 "boom",
8344 1,
8345 phrases(language),
8346 );
8347 t.last_error.or(t.hold_reason).unwrap_or_default()
8348 };
8349 assert!(
8350 reason("en").starts_with("the graph stopped at `"),
8351 "{}",
8352 reason("en")
8353 );
8354 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8355 assert!(reason("日本語").contains("boom"));
8356 assert_eq!(reason("fr"), reason("en"));
8357 }
8358
8359 #[test]
8360 fn describe_follows_the_run_language_and_keeps_the_run_id() {
8361 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8362 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8363 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8364 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8365 assert!(ja.contains("[run "), "{ja}");
8366 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8367 assert!(ended.starts_with("run 終了: "), "{ended}");
8368 let mut de = run_state_in(RunStatus::Failed, "de");
8369 let mut en = run_state_in(RunStatus::Failed, "en");
8370 de.id = "same".to_owned();
8371 en.id = "same".to_owned();
8372 assert_eq!(describe(&de), describe(&en));
8373 }
8374
8375 #[test]
8376 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8377 use crate::handover::Refused;
8378 let cases = [
8379 Refused::Foreign {
8380 branch: "b".into(),
8381 path: "/w/x".into(),
8382 why: "made by hand".into(),
8383 },
8384 Refused::Unsafe {
8385 branch: "b".into(),
8386 path: "/w/x".into(),
8387 why: "its worktree has uncommitted changes (a.rs)".into(),
8388 },
8389 Refused::ReleaseFailed {
8390 branch: "b".into(),
8391 path: "/w/x".into(),
8392 run: "ab12".into(),
8393 },
8394 ];
8395 for r in &cases {
8396 let en = (phrases("en").handover_refused)(r);
8397 assert_eq!(en, r.to_string());
8398 let ja = (phrases("ja").handover_refused)(r);
8399 assert!(
8400 !ja.contains("is checked out") && !ja.contains("try again"),
8401 "{ja}"
8402 );
8403 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8404 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8405 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8406 }
8407 }
8408 assert!(phrases("en").handover_hint.contains("release the task"));
8409 assert!(phrases("ja").handover_hint.contains("解放"));
8410 }
8411
8412 #[test]
8413 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8414 let build = |lang: &str| {
8415 let mut s = run_state_in(RunStatus::Blocked, lang);
8416 s.id = "same".to_owned();
8417 s.config.graph.review_rounds = 3;
8418 let mut r = review_round(3);
8419 r.expected = 3;
8420 r.answered = 1;
8421 s.reviews.push(r);
8422 s.event(
8423 "review",
8424 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8425 );
8426 s
8427 };
8428 let en = describe(&build("en"));
8429 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8430 let ja = describe(&build("ja"));
8431 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8432 assert!(!ja.contains("never answered"), "{ja}");
8433 assert!(ja.contains("[run "), "{ja}");
8434
8435 let mut failed = build("ja");
8438 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8439 command: "cargo test".to_owned(),
8440 code: Some(1),
8441 output_tail: String::new(),
8442 duration_ms: 0,
8443 resource_blocked: false,
8444 });
8445 failed.event("review", "stopped; e2e failed: cargo test");
8446 let ja = describe(&failed);
8447 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8448 assert!(!ja.contains("席のレビュアー"), "{ja}");
8449 }
8450
8451 #[test]
8452 fn refusals_and_recovery_prose_follow_the_language() {
8453 let t = held_task_with("r1");
8454 let q = action_question(
8455 "r1",
8456 ask::ChoiceAction::Resume {
8457 run: "r1".to_owned(),
8458 },
8459 );
8460 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8461 ActionDecision::Refuse(s) => s,
8462 other => panic!("{other:?}"),
8463 };
8464 assert!(refuse(phrases("en")).contains("could not be read: gone"));
8465 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8466 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8467
8468 let mut held = task();
8469 reclaim(&mut held, None, 2, "ja");
8470 assert!(held.hold_reason.unwrap().contains("保留にしました"));
8471 let mut held = task();
8472 reclaim(&mut held, None, 2, "xx");
8473 assert!(held.hold_reason.unwrap().contains("held for a human"));
8474 }
8475
8476 fn run_state(status: RunStatus) -> RunState {
8477 let mut state = RunState::new(
8478 PathBuf::from("/repo"),
8479 "main".to_owned(),
8480 "abc1234def".to_owned(),
8481 "add retries".to_owned(),
8482 Config::default(),
8483 );
8484 state.status = status;
8485 state
8486 }
8487
8488 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8489 Candidate {
8490 index: 0,
8491 label,
8492 agent: "claude".to_owned(),
8493 branch: format!("magi/x/{label}"),
8494 worktree: PathBuf::from("/repo"),
8495 summary: summary.to_owned(),
8496 stat: String::new(),
8497 files: 0,
8498 commits: usize::from(!empty),
8499 empty,
8500 failed: failed.map(str::to_owned),
8501 verified_noop: None,
8502 duration_ms: 0,
8503 folded: false,
8504 }
8505 }
8506
8507 #[test]
8508 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8509 let mut state = run_state(RunStatus::Blocked);
8510 state.gate = vec![
8511 CommandOutcome {
8512 command: "cargo make check".to_owned(),
8513 code: Some(0),
8514 output_tail: "ok".to_owned(),
8515 duration_ms: 0,
8516 resource_blocked: false,
8517 },
8518 CommandOutcome {
8519 command: "cargo test".to_owned(),
8520 code: Some(101),
8521 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8522 duration_ms: 0,
8523 resource_blocked: false,
8524 },
8525 ];
8526 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8527 assert!(d.contains("cargo test"), "{d}");
8528 assert!(
8529 !d.contains("cargo make check"),
8530 "a passing check is not a diagnostic: {d}"
8531 );
8532 assert!(d.contains("assertion failed"), "{d}");
8533 }
8534
8535 #[test]
8536 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8537 let mut state = run_state(RunStatus::Blocked);
8538 state.event(
8539 "land",
8540 "stopped: the fixer produced no commit while 2 check(s) were failing \
8541 (build, lint); stopping instead of looping on an unchanged tree",
8542 );
8543 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8544 assert!(d.contains("build"), "{d}");
8545 assert!(d.contains("lint"), "{d}");
8546 assert!(d.contains("fixer produced no commit"), "{d}");
8547 }
8548
8549 #[test]
8550 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8551 let state = run_state(RunStatus::VerifiedNoop);
8556 let d = describe(&state);
8557 assert!(
8558 d.contains("agent-verified no-op"),
8559 "expected the display label, not the wire spelling: {d}"
8560 );
8561 assert!(!d.contains("verified_noop"), "{d}");
8562 }
8563
8564 #[test]
8565 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8566 let mut state = run_state(RunStatus::Failed);
8567 state.gate.push(crate::run::CommandOutcome {
8568 command: "cargo test".into(),
8569 code: Some(101),
8570 output_tail: format!(
8571 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8572 " 41: 0x1234 - backtrace frame\n".repeat(10000)
8573 ),
8574 duration_ms: 1,
8575 resource_blocked: false,
8576 });
8577 let d = diagnostic(&state).unwrap();
8578 assert!(d.contains("panicked at widget.rs:12"), "{d}");
8579 assert!(d.contains("assertion failed: widget missing"));
8580 assert!(d.contains("widget log"));
8581 }
8582
8583 #[test]
8584 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8585 let mut state = run_state(RunStatus::Failed);
8591 state.candidates = vec![candidate(
8592 'A',
8593 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8594 true,
8595 None,
8596 )];
8597 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8598 assert!(d.contains("candidate A"), "{d}");
8599 assert!(d.contains("tagged v1.2.3"), "{d}");
8600 }
8601
8602 #[test]
8603 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8604 let mut state = run_state(RunStatus::Failed);
8605 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8606 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8607 assert!(d.contains("candidate A"), "{d}");
8608 assert!(d.contains("agent timed out"), "{d}");
8609 }
8610
8611 #[test]
8612 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8613 let mut state = run_state(RunStatus::Failed);
8616 state.candidates = vec![candidate('A', "did the work", false, None)];
8617 assert!(diagnostic(&state).is_none());
8618 }
8619
8620 #[test]
8621 fn diagnostic_is_bounded_however_much_a_run_printed() {
8622 let mut state = run_state(RunStatus::Blocked);
8623 state.gate = vec![
8624 CommandOutcome {
8625 command: "cargo test".to_owned(),
8626 code: Some(101),
8627 output_tail: "x".repeat(50_000),
8628 duration_ms: 0,
8629 resource_blocked: false,
8630 },
8631 CommandOutcome {
8632 command: "cargo clippy".to_owned(),
8633 code: Some(1),
8634 output_tail: "y".repeat(50_000),
8635 duration_ms: 0,
8636 resource_blocked: false,
8637 },
8638 ];
8639 state.candidates = vec![
8640 candidate('A', &"z".repeat(50_000), true, None),
8641 candidate('B', &"w".repeat(50_000), true, None),
8642 ];
8643 let d = diagnostic(&state).expect("plenty here to diagnose");
8644 assert!(
8645 d.len() <= DIAGNOSTIC_MAX,
8646 "diagnostic grew to {} bytes, unbounded",
8647 d.len()
8648 );
8649 }
8650
8651 #[test]
8652 fn selected_delivery_guards_survive_recovery_failure_accounting() {
8653 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8654 let mut t = task();
8655 let mut state = run_state(status);
8656 t.pr_recovery = Some(crate::pr_recovery::Selection {
8657 url: "url".into(),
8658 branch: format!("magi/task-{}", t.id),
8659 head: "a".repeat(40),
8660 source_head: None,
8661 source_run: None,
8662 source_proof: None,
8663 disposition: Some(crate::pr_recovery::Disposition::Land),
8664 instruction: t.instruction.clone(),
8665 approved_at: Timestamp::now(),
8666 });
8667 state.pr_recovery = t.pr_recovery.clone();
8668 t.start(state.id.clone());
8669 settle_and_diagnose(
8670 &mut t,
8671 Verdict {
8672 status,
8673 left_pr: false,
8674 quota_hit: false,
8675 parked: false,
8676 no_viable_candidates: false,
8677 },
8678 "delivery stopped",
8679 5,
8680 &state,
8681 );
8682 assert_eq!(t.status, TaskStatus::Held);
8683 let reason = t.hold_reason.as_deref().unwrap();
8684 if status == RunStatus::Ready {
8685 assert!(reason.contains("Selected PR delivery is incomplete"));
8686 assert!(t.recovery_budget.is_none());
8687 } else {
8688 assert!(reason.contains("Selected recovery stopped"));
8689 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8690 }
8691 assert!(t.pr_recovery.is_some());
8692 }
8693 }
8694
8695 #[test]
8696 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8697 let mut state = run_state(RunStatus::Voting);
8698 state.base_sync = Some(crate::run::BaseSync {
8699 tip: "base-tip".into(),
8700 behind: 3,
8701 attempts: 4,
8702 conflict: Some("base stopped".into()),
8703 already_in: None,
8704 });
8705 state.record_base_sync_stop("candidate-head");
8706 let mut t = task();
8707 t.start(state.id.clone());
8708 let verdict = Verdict {
8709 status: RunStatus::Blocked,
8710 left_pr: false,
8711 quota_hit: false,
8712 parked: false,
8713 no_viable_candidates: false,
8714 };
8715 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8716 assert_eq!(
8717 t.status,
8718 TaskStatus::Held,
8719 "unspent task attempts cannot start another competition"
8720 );
8721 let at = t.held_at;
8722 let cause = t.hold_notice_cause.clone();
8723 state.begin_pass();
8724 t.release_operator("test-resume", None);
8725 t.start(state.id.clone());
8726 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8727 assert_eq!(t.status, TaskStatus::Held);
8728 assert_eq!(t.held_at, at);
8729 assert_eq!(t.hold_notice_cause, cause);
8730 }
8731
8732 #[test]
8733 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8734 let mut state = run_state(RunStatus::Blocked);
8735 state.gate = vec![CommandOutcome {
8736 command: "cargo test".to_owned(),
8737 code: Some(101),
8738 output_tail: "assertion failed".to_owned(),
8739 duration_ms: 0,
8740 resource_blocked: false,
8741 }];
8742 let verdict = Verdict {
8743 status: RunStatus::Blocked,
8744 left_pr: false,
8745 quota_hit: false,
8746 parked: false,
8747 no_viable_candidates: false,
8748 };
8749
8750 let mut t = task();
8753 t.start("run-1".to_owned());
8754 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8755 assert_eq!(t.status, TaskStatus::Failed);
8756 assert!(t.diagnostic.is_none());
8757
8758 t.start("run-2".to_owned());
8761 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8762 assert_eq!(t.status, TaskStatus::Held);
8763 let d = t.diagnostic.expect("a held task must carry its diagnostic");
8764 assert!(d.contains("cargo test"), "{d}");
8765 }
8766
8767 #[test]
8768 fn a_held_task_names_the_open_question_it_is_waiting_on() {
8769 crate::run::pin_test_home();
8774 let home = crate::run::home();
8775 let state = run_state(RunStatus::VerifiedNoop);
8776 let mut q = ask::Question::new(
8777 state.id.clone(),
8778 "implement".to_owned(),
8779 "impl-A".to_owned(),
8780 "is this really a no-op?".to_owned(),
8781 String::new(),
8782 Vec::new(),
8783 );
8784 Questions::at(home.join("questions")).put(&mut q).unwrap();
8785
8786 let verdict = Verdict {
8787 status: RunStatus::VerifiedNoop,
8788 left_pr: false,
8789 quota_hit: false,
8790 parked: false,
8791 no_viable_candidates: false,
8792 };
8793 let mut t = task();
8794 t.start(state.id.clone());
8795 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8796
8797 assert_eq!(t.status, TaskStatus::Held);
8798 let reason = t.hold_reason.expect("a held task must record why");
8799 assert!(
8800 reason.starts_with("run ended agent-verified no-op"),
8801 "the original settle reason must survive unchanged: {reason}"
8802 );
8803 assert!(
8804 reason.contains(q.short()),
8805 "the open question's id must be named so the notice is actionable: {reason}"
8806 );
8807 }
8808
8809 #[test]
8810 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8811 crate::run::pin_test_home();
8812 let state = run_state(RunStatus::VerifiedNoop);
8813
8814 let verdict = Verdict {
8815 status: RunStatus::VerifiedNoop,
8816 left_pr: false,
8817 quota_hit: false,
8818 parked: false,
8819 no_viable_candidates: false,
8820 };
8821 let mut t = task();
8822 t.start(state.id.clone());
8823 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8824
8825 assert_eq!(t.status, TaskStatus::Held);
8826 assert_eq!(
8827 t.hold_reason.as_deref(),
8828 Some("run ended agent-verified no-op"),
8829 "nothing to append when the question was already answered or never asked"
8830 );
8831 }
8832
8833 #[test]
8834 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8835 crate::run::pin_test_home();
8836 let mut first = run_state(RunStatus::Blocked);
8837 first.id = "20260101-000000-sup1".to_owned();
8838 first.save().unwrap();
8839 let mut second = run_state(RunStatus::Merged);
8840 second.id = "20260101-000000-sup2".to_owned();
8841 second.save().unwrap();
8842
8843 let mut t = task();
8844 t.runs = vec![first.id.clone(), second.id.clone()];
8845 t.status = TaskStatus::Done;
8846
8847 supersede_prior_runs(&t, &crate::run::home());
8848
8849 assert_eq!(
8850 RunState::load(&first.id).unwrap().status,
8851 RunStatus::Superseded,
8852 "the first attempt's Blocked no longer needs anyone's attention"
8853 );
8854 assert_eq!(
8855 RunState::load(&second.id).unwrap().status,
8856 RunStatus::Merged,
8857 "the run that actually succeeded is left exactly as it was"
8858 );
8859 }
8860
8861 #[test]
8862 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8863 crate::run::pin_test_home();
8869 let mut first = run_state(RunStatus::Blocked);
8870 first.id = "20260101-000000-sup9".to_owned();
8871 first.driver_pid = Some(std::process::id());
8874 first.driver_started_at = Some(
8875 crate::proc::process_started_at(std::process::id())
8876 .expect("this test process's own start time must be queryable"),
8877 );
8878 first.save().unwrap();
8879 let mut second = run_state(RunStatus::Merged);
8880 second.id = "20260101-000000-supa".to_owned();
8881 second.save().unwrap();
8882
8883 let mut t = task();
8884 t.runs = vec![first.id.clone(), second.id.clone()];
8885 t.status = TaskStatus::Done;
8886
8887 supersede_prior_runs(&t, &crate::run::home());
8888
8889 assert_eq!(
8890 RunState::load(&first.id).unwrap().status,
8891 RunStatus::Blocked,
8892 "a live driver_pid means something is still actually working this run, \
8893 even though no daemon claims it - rewriting under it would just be \
8894 undone the next time that process saves"
8895 );
8896 }
8897
8898 #[test]
8899 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8900 let dir = tempfile::tempdir().unwrap();
8906 let home = dir.path().to_path_buf();
8907 let queue = Queue::at(dir.path().join("queue"));
8908
8909 let mut first = run_state(RunStatus::Blocked);
8910 first.id = "20260101-000000-supd".to_owned();
8911 first.driver_pid = Some(std::process::id());
8912 first.driver_started_at = Some(
8913 crate::proc::process_started_at(std::process::id())
8914 .expect("this test process's own start time must be queryable"),
8915 );
8916 first.save_under(&home).unwrap();
8917 let mut second = run_state(RunStatus::Merged);
8918 second.id = "20260101-000000-supe".to_owned();
8919 second.save_under(&home).unwrap();
8920
8921 let mut t = task();
8922 t.runs = vec![first.id.clone(), second.id.clone()];
8923 t.status = TaskStatus::Done;
8924 queue.put(&mut t).unwrap();
8925
8926 resweep_superseded_attempts(&queue, &home);
8927 assert_eq!(
8928 RunState::load_under(&first.id, &home).unwrap().status,
8929 RunStatus::Blocked,
8930 "still live on the first pass, so still untouched"
8931 );
8932
8933 let mut stale = RunState::load_under(&first.id, &home).unwrap();
8939 stale.driver_started_at = Some("1".to_owned());
8940 stale.save_under(&home).unwrap();
8941
8942 resweep_superseded_attempts(&queue, &home);
8943 assert_eq!(
8944 RunState::load_under(&first.id, &home).unwrap().status,
8945 RunStatus::Superseded,
8946 "the second pass catches up what the first one correctly skipped"
8947 );
8948 }
8949
8950 #[test]
8951 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8952 crate::run::pin_test_home();
8953 let mut first = run_state(RunStatus::Blocked);
8954 first.id = "20260101-000000-sup3".to_owned();
8955 first.save().unwrap();
8956 let mut second = run_state(RunStatus::Blocked);
8957 second.id = "20260101-000000-sup4".to_owned();
8958 second.save().unwrap();
8959
8960 let mut t = task();
8961 t.runs = vec![first.id.clone(), second.id.clone()];
8962 t.status = TaskStatus::Failed;
8966
8967 supersede_prior_runs(&t, &crate::run::home());
8968
8969 assert_eq!(
8970 RunState::load(&first.id).unwrap().status,
8971 RunStatus::Blocked
8972 );
8973 assert_eq!(
8974 RunState::load(&second.id).unwrap().status,
8975 RunStatus::Blocked
8976 );
8977 }
8978
8979 #[test]
8980 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8981 crate::run::pin_test_home();
8985 let mut first = run_state(RunStatus::Blocked);
8986 first.id = "20260101-000000-sup5".to_owned();
8987 first.save().unwrap();
8988
8989 let mut t = task();
8990 t.runs = vec![first.id.clone()];
8991 t.status = TaskStatus::Done;
8992
8993 supersede_prior_runs(&t, &crate::run::home());
8994
8995 assert_eq!(
8996 RunState::load(&first.id).unwrap().status,
8997 RunStatus::Blocked,
8998 "a single-attempt task has no earlier run to supersede"
8999 );
9000 }
9001
9002 #[test]
9003 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9004 crate::run::pin_test_home();
9011 let mut first = run_state(RunStatus::Blocked);
9012 first.id = "20260101-000000-supb".to_owned();
9013 first.save().unwrap();
9014 let mut second = run_state(RunStatus::Failed);
9015 second.id = "20260101-000000-supc".to_owned();
9016 second.save().unwrap();
9017
9018 let mut t = task();
9019 t.runs = vec![first.id.clone(), second.id.clone()];
9020 t.status = TaskStatus::Done;
9021
9022 supersede_prior_runs(&t, &crate::run::home());
9023
9024 assert_eq!(
9025 RunState::load(&first.id).unwrap().status,
9026 RunStatus::Blocked,
9027 "the task's last attempt never landed, so there is nothing here \
9028 actually superseding it"
9029 );
9030 }
9031
9032 #[test]
9033 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9034 crate::run::pin_test_home();
9038 let mut failed = run_state(RunStatus::Failed);
9039 failed.id = "20260101-000000-sup6".to_owned();
9040 failed.save().unwrap();
9041 let mut noop = run_state(RunStatus::VerifiedNoop);
9042 noop.id = "20260101-000000-sup7".to_owned();
9043 noop.save().unwrap();
9044 let mut winner = run_state(RunStatus::Ready);
9045 winner.id = "20260101-000000-sup8".to_owned();
9046 winner.save().unwrap();
9047
9048 let mut t = task();
9049 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9050 t.status = TaskStatus::Done;
9051
9052 supersede_prior_runs(&t, &crate::run::home());
9053
9054 assert_eq!(
9055 RunState::load(&failed.id).unwrap().status,
9056 RunStatus::Failed
9057 );
9058 assert_eq!(
9059 RunState::load(&noop.id).unwrap().status,
9060 RunStatus::VerifiedNoop
9061 );
9062 }
9063
9064 fn approval_question(run: &str) -> ask::Question {
9065 ask::Question::new(
9066 run.to_owned(),
9067 land::APPROVAL_NODE.to_owned(),
9068 "land".to_owned(),
9069 "merge?".to_owned(),
9070 String::new(),
9071 vec!["merge".to_owned(), "hold".to_owned()],
9072 )
9073 }
9074
9075 #[test]
9076 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9077 crate::run::pin_test_home();
9078 let mut state = run_state(RunStatus::Landing);
9079 state.id = "20260101-000000-fre1".to_owned();
9080 state.parked = true;
9081 state.save().unwrap();
9082 ask::Questions::open()
9083 .put(&mut approval_question(&state.id))
9084 .unwrap();
9085
9086 let mut t = task();
9087 t.runs.push(state.id.clone());
9088 assert_eq!(
9089 land_resume_state(&t),
9090 LandResume::StillWaiting,
9091 "nobody has answered and the timeout has not passed"
9092 );
9093 }
9094
9095 #[test]
9096 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9097 crate::run::pin_test_home();
9098 let mut state = run_state(RunStatus::Gating);
9099 state.id = "20260101-000000-gt01".to_owned();
9100 state.parked = true;
9101 state.config.graph.answer_timeout = 60;
9102 state.github_text = Some(crate::run::GithubTextAsk {
9103 rewrite: None,
9104 fingerprint: "f".into(),
9105 title: true,
9106 body: false,
9107 categories: vec!["title-language".into()],
9108 question: None,
9109 asks: 1,
9110 resolved: false,
9111 chosen_title: None,
9112 choice: None,
9113 });
9114 state.save().unwrap();
9115 let store = ask::Questions::open();
9116 let mut q = ask::Question::new(
9117 state.id.clone(),
9118 crate::github_text::ASK_NODE.to_owned(),
9119 crate::github_text::ASK_SEAT.to_owned(),
9120 "s".into(),
9121 String::new(),
9122 vec!["use fallback".into()],
9123 );
9124 store.put(&mut q).unwrap();
9125 let mut t = task();
9126 t.runs.push(state.id.clone());
9127 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9128 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9129 store.put(&mut q).unwrap();
9130 assert_eq!(land_resume_state(&t), LandResume::Ready);
9131 assert!(!store.get(&q.id).unwrap().status.open());
9132 state.github_text.as_mut().unwrap().resolved = true;
9134 state.save().unwrap();
9135 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9136 }
9137
9138 #[test]
9139 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9140 crate::run::pin_test_home();
9145 let mut state = run_state(RunStatus::Landing);
9146 state.id = "20260101-000000-exp1".to_owned();
9147 state.parked = true;
9148 state.config.graph.answer_timeout = 60;
9149 state.save().unwrap();
9150
9151 let store = ask::Questions::open();
9152 let mut q = approval_question(&state.id);
9153 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9154 store.put(&mut q).unwrap();
9155
9156 let mut t = task();
9157 t.runs.push(state.id.clone());
9158 assert_eq!(
9159 land_resume_state(&t),
9160 LandResume::Ready,
9161 "an expired question must not be waited on forever"
9162 );
9163
9164 let after = store.get(&q.id).unwrap();
9165 assert!(
9166 !after.status.open(),
9167 "the question is abandoned, not silently ignored"
9168 );
9169 assert!(
9170 after.resolution().is_none(),
9171 "an abandoned question is not read as a decision"
9172 );
9173 }
9174
9175 #[test]
9176 fn reclaim_settles_a_running_task_against_its_last_run() {
9177 let mut t = task();
9178 t.start("20260904-000000-4043".to_owned());
9179 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9180 assert_eq!(
9181 t.status,
9182 TaskStatus::Done,
9183 "a run that actually finished must not stay `running` forever"
9184 );
9185 }
9186
9187 #[test]
9188 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9189 let mut t = task();
9190 t.start("20260904-000000-4043".to_owned());
9191 t.last_error = Some("earlier trouble".to_owned());
9192 let mut state = run_state(RunStatus::Judging);
9193 state.parked = true;
9194 reclaim(&mut t, Some(state), 1, "en");
9195 assert_eq!(t.status, TaskStatus::Parked);
9196 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9197 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9198 assert!(t.park_reason.is_some());
9199 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9200 assert!(!t.fresh_start);
9201 assert!(t.status.runnable());
9202 }
9203
9204 #[test]
9205 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9206 let mut t = task();
9207 t.start("20260904-000000-4043".to_owned());
9208 t.last_error = Some("earlier trouble".to_owned());
9209 settle(
9210 &mut t,
9211 Verdict {
9212 status: RunStatus::Judging,
9213 left_pr: false,
9214 quota_hit: false,
9215 parked: true,
9216 no_viable_candidates: false,
9217 },
9218 "parked after `judging`",
9219 1,
9220 );
9221 assert_eq!(t.status, TaskStatus::Parked);
9222 assert_eq!(t.attempts, 0);
9223 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9224 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9225 assert_eq!(t.schema, crate::queue::SCHEMA);
9226 assert!(
9227 crate::notices::task_held(&t).is_none(),
9228 "a park is not news"
9229 );
9230 t.start("20260904-000000-4043".to_owned());
9231 assert_eq!(t.park_reason, None);
9232 }
9233
9234 #[test]
9235 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9236 let mut t = task();
9240 t.start("20260904-000000-4043".to_owned());
9241 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9242 assert_eq!(t.status, TaskStatus::Failed);
9243 assert!(t.status.runnable());
9244 }
9245
9246 #[test]
9247 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9248 let mut t = task();
9249 t.start("20260904-000000-4043".to_owned());
9250 assert_eq!(t.attempts, 1);
9251 let mut run = run_state(RunStatus::Implementing);
9252 run.id = "20260904-000000-4043".to_owned();
9253 run.begin_pass();
9254 let cause = crate::run::ParkCause::Upgrade {
9255 from: "0.121.0".to_owned(),
9256 to: Some("0.121.1".to_owned()),
9257 };
9258 run.end_pass_parked(cause.clone());
9259 run.parked = true;
9260 let verdict = Verdict {
9261 status: run.status,
9262 left_pr: false,
9263 quota_hit: false,
9264 parked: true,
9265 no_viable_candidates: false,
9266 };
9267 let mut orphan = t.clone();
9270 reclaim(&mut orphan, Some(run.clone()), 2, "en");
9271 assert_eq!(orphan.status, TaskStatus::Parked);
9272 assert_eq!(orphan.attempts, 0);
9273 assert_eq!(
9274 orphan.upgrade_resume_key(),
9275 Some((run.passes[0].started_at, orphan.id.as_str()))
9276 );
9277 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9278 assert_eq!(t.attempts, 0);
9279 assert_eq!(t.passes.len(), 1);
9280 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9281 assert_eq!(t.passes[0].parked, Some(cause));
9282 assert_eq!(t.passes[0].pass_index, 0);
9283 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9284 assert!(t.upgrade_resume_key().is_some());
9285
9286 t.start("20260904-000000-4043".to_owned());
9289 run.begin_pass();
9290 run.status = RunStatus::Failed;
9291 let verdict = Verdict {
9292 status: RunStatus::Failed,
9293 left_pr: false,
9294 quota_hit: false,
9295 parked: false,
9296 no_viable_candidates: false,
9297 };
9298 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9299 assert_eq!(t.passes.len(), 2);
9300 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9301 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9302 assert_eq!(t.passes[1].pass_index, 1);
9303 assert_eq!(t.attempts, 1);
9304 }
9305
9306 #[test]
9307 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9308 let mut t = task();
9309 t.start("20260904-000000-4043".to_owned());
9310 reclaim(&mut t, None, 2, "en");
9311 assert_eq!(t.status, TaskStatus::Held);
9312 assert!(
9313 t.last_error
9314 .as_deref()
9315 .is_some_and(|e| e.contains("running")),
9316 "the operator needs to know why this task was held"
9317 );
9318 }
9319
9320 #[test]
9321 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9322 let dir = tempfile::tempdir().unwrap();
9323 let queue = Queue::at(dir.path().to_path_buf());
9324
9325 let mut orphaned = task();
9327 orphaned.id = "20260904-000000-orph".to_owned();
9328 orphaned.status = TaskStatus::Running;
9329 orphaned.attempts = 1;
9330 queue.put(&mut orphaned).unwrap();
9331
9332 let mut alive = task();
9333 alive.id = "20260904-000000-live".to_owned();
9334 alive.status = TaskStatus::Running;
9335 alive.attempts = 1;
9336 queue.put(&mut alive).unwrap();
9337 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9338
9339 let mut queued = task();
9340 queued.id = "20260904-000000-wait".to_owned();
9341 queue.put(&mut queued).unwrap();
9342
9343 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9344 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9345
9346 assert_eq!(
9347 queue.get(&orphaned.id).unwrap().status,
9348 TaskStatus::Held,
9349 "nothing was driving it and there was no run to recover"
9350 );
9351 assert_eq!(
9352 queue.get(&alive.id).unwrap().status,
9353 TaskStatus::Running,
9354 "a live claim must protect the task it belongs to"
9355 );
9356 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9357 }
9358
9359 fn read_run_under(home: &Path, id: &str) -> RunState {
9365 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9366 serde_json::from_str(&body).unwrap()
9367 }
9368
9369 #[test]
9370 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9371 let dir = tempfile::tempdir().unwrap();
9372 let home = dir.path().to_path_buf();
9373 let now = Timestamp::now();
9374 let overrun_seat = || crate::run::ActiveSeat {
9375 node: "implement".to_owned(),
9376 started_at: now - jiff::SignedDuration::new(21_000, 0),
9377 timeout_secs: 3_600,
9378 attempt: 0,
9379 task: None,
9380 command: None,
9381 index: None,
9382 total: None,
9383 };
9384
9385 let mut dead = run_state(RunStatus::Implementing);
9386 dead.id = "20260101-000000-dead".to_owned();
9387 dead.active.insert("impl-A".to_owned(), overrun_seat());
9388 dead.driver_pid = Some(4242);
9391 dead.save_under(&home).unwrap();
9392
9393 let mut alive = run_state(RunStatus::Implementing);
9396 alive.id = "20260101-000000-aliv".to_owned();
9397 alive.active.insert("impl-A".to_owned(), overrun_seat());
9398 alive.save_under(&home).unwrap();
9399 let mut status = Status::new();
9400 status.current = vec![Current {
9401 worker: None,
9402 task: "20260101-000000-task".to_owned(),
9403 run: alive.id.clone(),
9404 }];
9405 write_status_to(&home.join("daemon.json"), &status).unwrap();
9406
9407 let questions = Questions::at(home.join("questions"));
9411 let mut q = ask::Question::new(
9412 dead.id.clone(),
9413 "implement".to_owned(),
9414 "impl-A".to_owned(),
9415 "Which storage backend?".to_owned(),
9416 String::new(),
9417 vec!["SQLite".to_owned(), "Redis".to_owned()],
9418 );
9419 questions.put(&mut q).unwrap();
9420
9421 let abandoned = reclaim_abandoned_runs_with(
9422 &home,
9423 now,
9424 |pid| if pid == 4242 { Some(false) } else { None },
9425 |_| panic!("a query answering Dead outright needs no identity corroboration"),
9426 );
9427 assert_eq!(abandoned, vec![dead.id.clone()]);
9428
9429 let reloaded = read_run_under(&home, &dead.id);
9430 assert_eq!(reloaded.status, RunStatus::Failed);
9431 assert!(reloaded.active.is_empty());
9432 assert!(
9433 !questions.get(&q.id).unwrap().status.open(),
9434 "the failed run's own open question must be settled in the same pass"
9435 );
9436
9437 let still_alive = read_run_under(&home, &alive.id);
9438 assert_eq!(
9439 still_alive.status,
9440 RunStatus::Implementing,
9441 "a live daemon's claim protects it"
9442 );
9443 assert!(!still_alive.active.is_empty());
9444 }
9445
9446 #[test]
9456 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9457 let dir = tempfile::tempdir().unwrap();
9458 let home = dir.path().to_path_buf();
9459 let now = Timestamp::now();
9460
9461 let mut manual = run_state(RunStatus::Reviewing);
9462 manual.id = "20260101-000000-manl".to_owned();
9463 manual.active.insert(
9464 "review-1".to_owned(),
9465 crate::run::ActiveSeat {
9466 node: "review".to_owned(),
9467 started_at: now - jiff::SignedDuration::new(21_000, 0),
9468 timeout_secs: 3_600,
9469 attempt: 0,
9470 task: None,
9471 command: None,
9472 index: None,
9473 total: None,
9474 },
9475 );
9476 manual.driver_pid = Some(4242);
9480 manual.driver_started_at = Some("1790000000".to_owned());
9481 manual.save_under(&home).unwrap();
9482
9483 let abandoned = reclaim_abandoned_runs_with(
9484 &home,
9485 now,
9486 |pid| if pid == 4242 { Some(true) } else { None },
9487 |pid| {
9488 if pid == 4242 {
9489 Some("1790000000".to_owned())
9490 } else {
9491 None
9492 }
9493 },
9494 );
9495 assert!(
9496 abandoned.is_empty(),
9497 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9498 );
9499
9500 let reloaded = read_run_under(&home, &manual.id);
9501 assert_eq!(reloaded.status, RunStatus::Reviewing);
9502 assert!(!reloaded.active.is_empty());
9503 }
9504
9505 #[test]
9506 fn an_already_claimed_task_is_skipped_rather_than_failed() {
9507 let dir = tempfile::tempdir().unwrap();
9508 let queue = Queue::at(dir.path().to_path_buf());
9509 let mut only = task();
9510 queue.put(&mut only).unwrap();
9511
9512 let _elsewhere = queue.claim(&only.id).unwrap();
9513 let candidates = runnable(&queue);
9514 assert_eq!(candidates.len(), 1, "the task is still runnable");
9515 assert!(
9516 queue.claim(&candidates[0].id).is_err(),
9517 "the loop cannot take a claim somebody else holds"
9518 );
9519
9520 let after = queue.get(&only.id).unwrap();
9521 assert_eq!(after.status, TaskStatus::Queued);
9522 assert_eq!(
9523 after.attempts, 0,
9524 "losing the race is not an attempt at the task"
9525 );
9526 assert_eq!(after.last_error, None);
9527 }
9528
9529 #[test]
9530 fn the_status_file_round_trips_and_its_heartbeat_advances() {
9531 let dir = tempfile::tempdir().unwrap();
9532 let path = dir.path().join("daemon.json");
9533
9534 let mut status = Status::new();
9535 status.idle = false;
9536 status.completed = 7;
9537 status.current = vec![Current {
9538 worker: None,
9539 task: "20260902-000000-t111".to_owned(),
9540 run: "20260902-000001-r111".to_owned(),
9541 }];
9542 write_status_to(&path, &status).unwrap();
9543 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9544 assert_eq!(first.schema, SCHEMA);
9545 assert_eq!(first.pid, std::process::id());
9546 assert!(!first.idle);
9547 assert_eq!(first.completed, 7);
9548 assert_eq!(first.current, status.current);
9549 assert!(
9550 !path.with_extension("json.tmp").exists(),
9551 "the temp file is renamed, not left behind"
9552 );
9553
9554 std::thread::sleep(Duration::from_millis(5));
9555 status.updated_at = Timestamp::now();
9556 status.polls = 3;
9557 write_status_to(&path, &status).unwrap();
9558 let second: Status =
9559 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9560 assert!(
9561 second.updated_at > first.updated_at,
9562 "a reader can only detect staleness if the heartbeat moves"
9563 );
9564 assert_eq!(
9565 second.started_at, first.started_at,
9566 "the start time is not a heartbeat"
9567 );
9568 assert_eq!(second.polls, 3);
9569 }
9570
9571 #[test]
9572 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9573 let dir = tempfile::tempdir().unwrap();
9574
9575 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9576
9577 let mut status = Status::new();
9578 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9579 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9580 let stale = read_status(dir.path()).unwrap();
9581 assert!(
9582 !stale.running(Timestamp::now()),
9583 "a minute without a heartbeat is a dead daemon, not a busy one"
9584 );
9585 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9586
9587 status.updated_at = Timestamp::now();
9588 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9589 let fresh = read_status(dir.path()).unwrap();
9590 assert!(fresh.running(Timestamp::now()));
9591 }
9592
9593 #[test]
9594 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9595 let dir = tempfile::tempdir().unwrap();
9596 let now = Timestamp::now();
9597 let mine = "20260903-080619-01c2";
9598
9599 assert!(
9600 !is_working_on(dir.path(), mine, now),
9601 "no status file means nobody is working on anything"
9602 );
9603
9604 let mut status = Status::new();
9605 status.current = vec![Current {
9606 worker: None,
9607 task: "20260903-080340-0167".to_owned(),
9608 run: mine.to_owned(),
9609 }];
9610 status.updated_at = now;
9611 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9612 assert!(is_working_on(dir.path(), mine, now));
9613 assert!(
9614 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9615 "a daemon busy with one run is not working on another"
9616 );
9617
9618 status.updated_at = now - jiff::SignedDuration::from_secs(600);
9621 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9622 assert!(
9623 !is_working_on(dir.path(), mine, now),
9624 "a stale heartbeat is a dead daemon, so its run is a leftover"
9625 );
9626 }
9627
9628 #[test]
9629 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9630 let dir = tempfile::tempdir().unwrap();
9631 let now = Timestamp::now();
9632
9633 assert!(
9634 !is_working_on_short(dir.path(), "01c2", now),
9635 "no status file means nobody is working on anything"
9636 );
9637
9638 let mut status = Status::new();
9639 status.current = vec![Current {
9640 worker: None,
9641 task: "20260903-080340-0167".to_owned(),
9642 run: "20260903-080619-01c2".to_owned(),
9643 }];
9644 status.updated_at = now;
9645 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9646 assert!(
9647 is_working_on_short(dir.path(), "01c2", now),
9648 "the run's short id is the last block of its full id"
9649 );
9650 assert!(
9651 !is_working_on_short(dir.path(), "3cbf", now),
9652 "a daemon busy with one worktree bay is not working on another"
9653 );
9654 }
9655
9656 #[test]
9657 fn a_newer_status_file_still_yields_a_reading() {
9658 let dir = tempfile::tempdir().unwrap();
9659 std::fs::write(
9662 dir.path().join("daemon.json"),
9663 serde_json::json!({
9664 "schema": 2,
9665 "updated_at": Timestamp::now().to_string(),
9666 "idle": true,
9667 "surprise": { "nested": [1, 2, 3] },
9668 })
9669 .to_string(),
9670 )
9671 .unwrap();
9672
9673 let reading = read_status(dir.path()).expect("a forward-compatible read");
9674 assert!(reading.running(Timestamp::now()));
9675 assert!(reading.idle);
9676 assert!(reading.current.is_empty());
9677 }
9678
9679 #[test]
9680 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9681 let dir = tempfile::tempdir().unwrap();
9687 std::fs::write(
9688 dir.path().join("daemon.json"),
9689 serde_json::json!({
9690 "schema": 1,
9691 "pid": 4242,
9692 "updated_at": Timestamp::now().to_string(),
9693 "idle": false,
9694 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9695 "completed": 3,
9696 "polls": 9,
9697 })
9698 .to_string(),
9699 )
9700 .unwrap();
9701
9702 let reading = read_status(dir.path()).expect("an older shape must still parse");
9703 assert!(reading.running(Timestamp::now()));
9704 assert_eq!(
9705 reading.current,
9706 vec![Current {
9707 worker: None,
9708 task: "20260902-140501-aaaa".to_owned(),
9709 run: "20260902-140502-bbbb".to_owned(),
9710 }]
9711 );
9712 }
9713
9714 #[test]
9715 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9716 let dir = tempfile::tempdir().unwrap();
9717 std::fs::write(
9718 dir.path().join("daemon.json"),
9719 serde_json::json!({
9720 "schema": 1,
9721 "updated_at": Timestamp::now().to_string(),
9722 "idle": true,
9723 "current": null,
9724 })
9725 .to_string(),
9726 )
9727 .unwrap();
9728 let with_null = read_status(dir.path()).expect("null must still parse");
9729 assert!(with_null.current.is_empty());
9730
9731 std::fs::write(
9732 dir.path().join("daemon.json"),
9733 serde_json::json!({
9734 "schema": 1,
9735 "updated_at": Timestamp::now().to_string(),
9736 "idle": true,
9737 })
9738 .to_string(),
9739 )
9740 .unwrap();
9741 let absent = read_status(dir.path()).expect("a missing field must still parse");
9742 assert!(absent.current.is_empty());
9743 }
9744
9745 #[test]
9746 fn a_task_without_a_repository_runs_in_the_daemons_default() {
9747 let fallback = Path::new("/default");
9748 let mut blank = task();
9749 blank.repo = PathBuf::new();
9750 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9751 let mut dot = task();
9752 dot.repo = PathBuf::from(".");
9753 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9754 assert_eq!(
9755 repo_for(&task(), fallback),
9756 PathBuf::from("/repo"),
9757 "a task that names a repository keeps it"
9758 );
9759 }
9760
9761 #[test]
9762 fn task_implementers_edit_inherits_daemon_config_and_merge() {
9763 let dir = tempfile::tempdir().unwrap();
9764 let path = dir.path().join("explicit.toml");
9765 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9766 let opts = Opts {
9767 config: Some(path),
9768 merge: Some("none".into()),
9769 ..Default::default()
9770 };
9771 let mut t = task();
9772 t.set_implementers(
9773 2,
9774 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9775 .unwrap(),
9776 )
9777 .unwrap();
9778 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9779 assert_eq!(cfg.graph.implementers, 2);
9780 assert_eq!(cfg.graph.judges, 1);
9781 assert_eq!(cfg.merge.mode, MergeMode::None);
9782 t.set_implementers(1, &cfg).unwrap();
9783 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9784 apply_task_implementers(&mut cfg, &t);
9785 assert_eq!(cfg.graph.implementers, 1);
9786 assert_eq!(cfg.graph.judges, 1);
9787 assert_eq!(cfg.merge.mode, MergeMode::None);
9788 }
9789
9790 #[test]
9791 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9792 let dir = tempfile::tempdir().unwrap();
9793 let repo = dir.path().join("repo");
9794 std::fs::create_dir(&repo).unwrap();
9795 std::fs::write(
9796 repo.join("magi.toml"),
9797 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9798 )
9799 .unwrap();
9800 let daemon_config = dir.path().join("daemon.toml");
9801 std::fs::write(
9802 &daemon_config,
9803 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9804 )
9805 .unwrap();
9806 let opts = Opts {
9807 config: Some(daemon_config),
9808 merge: Some("pr".into()),
9809 ..Default::default()
9810 };
9811 let q = Queue::at(dir.path().join("queue"));
9812 let validation: Config =
9813 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9814 .unwrap();
9815 for record in ["{}", r#"{"candidates":2}"#] {
9817 let overrides = serde_json::from_str(record).unwrap();
9818 let filing = crate::direct::Filing {
9819 instruction: "work".into(),
9820 title: "direct".into(),
9821 repo: repo.clone(),
9822 source: crate::queue::Source::Human,
9823 solo: false,
9824 overrides,
9825 review_of: None,
9826 sources: Default::default(),
9827 };
9828 let filed =
9829 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9830 let crate::direct::Filed::Standalone {
9831 mut task,
9832 claim: _claim,
9833 } = filed
9834 else {
9835 panic!("local filing")
9836 };
9837 let before = prepare_for(&repo, &opts, &task).unwrap();
9838 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9839 assert_eq!(
9840 before.merge.mode,
9841 MergeMode::None,
9842 "daemon --merge must not leak"
9843 );
9844 for n in [2, 1, 2] {
9845 task.set_implementers(n, &validation).unwrap();
9846 q.put(&mut task).unwrap();
9847 task = q.get(&task.id).unwrap();
9848 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9849 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9850 apply_task_implementers(&mut cfg, &task);
9851 assert_eq!(cfg.graph.implementers, usize::from(n));
9852 assert_eq!(cfg.graph.judges, 2);
9853 assert_eq!(cfg.merge.mode, MergeMode::None);
9854 }
9855 }
9856 }
9857
9858 #[test]
9859 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9860 let cfg: Config =
9861 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9862 .unwrap();
9863 let mut t = task();
9864 t.review_of = Some("review-target".into());
9865 t.hold_manual(Some("retry".into()));
9866 let mut previous = RunState::new(
9867 PathBuf::from("/repo"),
9868 "main".into(),
9869 "abc1234".into(),
9870 "review".into(),
9871 cfg.clone(),
9872 );
9873 previous.config.graph.implementers = 2;
9874 for count in [1, 3] {
9875 t.set_implementers(count, &cfg).unwrap();
9876 t.release();
9877 assert_eq!(t.review_of.as_deref(), Some("review-target"));
9878 for proposed in [
9879 Starter::Resume(previous.id.clone()),
9880 Starter::Review("recovery-target".into()),
9881 ] {
9882 assert_eq!(
9883 starter_with_implementers(&t, Some(&previous), proposed),
9884 Starter::Review("review-target".into())
9885 );
9886 }
9887 let mut configured = cfg.clone();
9888 apply_task_implementers(&mut configured, &t);
9889 assert_eq!(configured.graph.implementers, usize::from(count));
9890 assert_eq!(previous.config.graph.implementers, 2);
9891 }
9892 }
9893
9894 #[test]
9895 fn task_implementers_dispatch_and_resume_agree() {
9896 let mut t = task();
9897 let cfg: crate::config::Config =
9898 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9899 .unwrap();
9900 let mut run = RunState::new(
9901 PathBuf::from("/repo"),
9902 "main".into(),
9903 "abc1234".into(),
9904 "work".into(),
9905 cfg.clone(),
9906 );
9907 run.config.graph.implementers = 2;
9908 for n in [2, 1, 3, 2] {
9909 t.set_implementers(n, &cfg).unwrap();
9910 let mut dispatched = cfg.clone();
9911 apply_task_implementers(&mut dispatched, &t);
9912 assert_eq!(dispatched.graph.implementers, usize::from(n));
9913 assert_eq!(implementers_match(&t, &run), n == 2);
9914 for proposed in [
9915 Starter::Resume(run.id.clone()),
9916 Starter::Review("old-branch".into()),
9917 ] {
9918 let expected = if n == 2 {
9919 proposed.clone()
9920 } else {
9921 Starter::Start
9922 };
9923 assert_eq!(
9924 starter_with_implementers(&t, Some(&run), proposed),
9925 expected
9926 );
9927 }
9928 assert_eq!(
9929 run.config.graph.implementers, 2,
9930 "history must not be rewritten"
9931 );
9932 }
9933 t.solo = false;
9934 t.overrides = None;
9935 assert!(implementers_match(&t, &run));
9936 }
9937
9938 #[test]
9939 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9940 let mut solo_cfg = Config::default();
9946 solo_cfg.graph.implementers = 3;
9947 let mut solo_task = task();
9948 solo_task.solo = true;
9949 apply_task_implementers(&mut solo_cfg, &solo_task);
9950 assert_eq!(solo_cfg.graph.implementers, 1);
9951
9952 let mut plain_cfg = Config::default();
9953 plain_cfg.graph.implementers = 3;
9954 let plain_task = task();
9955 assert!(!plain_task.solo);
9956 apply_task_implementers(&mut plain_cfg, &plain_task);
9957 assert_eq!(
9958 plain_cfg.graph.implementers, 3,
9959 "a task that did not ask to run alone keeps the config's candidates"
9960 );
9961 }
9962
9963 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9964 QuotaLoss {
9965 cause: crate::agent::QuotaCause::UsageLimit,
9966 agent: String::new(),
9967 seat: seat.into(),
9968 node: "judge".into(),
9969 at: at.parse().unwrap(),
9970 reset: reset.map(str::to_string),
9971 }
9972 }
9973
9974 #[test]
9975 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
9976 let now = Timestamp::now();
9977 for reset in [None, Some("in 1h")] {
9978 let auth = crate::agent::Quota {
9979 cause: crate::agent::QuotaCause::Authentication,
9980 agent: "alpha".into(),
9981 reset: reset.map(str::to_owned),
9982 };
9983 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
9984 assert_eq!(cooldown_until(&[loss], now), None);
9985 }
9986 }
9987
9988 #[test]
9989 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9990 let old: Vec<QuotaLoss> = (1..=4)
9991 .map(|i| {
9992 loss(
9993 &format!("judge-{i}"),
9994 "2026-09-23T05:23:00Z",
9995 Some("2:40pm (Asia/Tokyo)"),
9996 )
9997 })
9998 .collect();
9999 let fresh = losses_this_attempt(&old, &old);
10000 assert!(fresh.is_empty());
10001 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10002 }
10004
10005 #[test]
10006 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10007 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10008 let now = Timestamp::now();
10009 let mut after = old.clone();
10010 after.push(loss("judge-2", &now.to_string(), None));
10011 let fresh = losses_this_attempt(&old, &after);
10012 assert_eq!(fresh, vec![after[1].clone()]);
10013 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10014 assert_eq!(
10015 until,
10016 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10017 );
10018 }
10019
10020 #[test]
10021 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10022 let before = vec![
10025 loss("judge-1", "2026-09-23T05:23:00Z", None),
10026 loss("judge-2", "2026-09-23T05:24:00Z", None),
10027 ];
10028 let after = vec![
10029 loss("judge-2", "2026-09-23T05:24:00Z", None),
10030 loss("judge-1", "2026-09-24T01:00:00Z", None),
10031 ];
10032 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10033 }
10034
10035 #[test]
10036 fn merge_overrides_are_parsed_or_refused() {
10037 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10038 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10039 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10040 assert!(merge_mode("squash").is_err());
10041 }
10042
10043 #[test]
10044 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10045 let now = Timestamp::now();
10046 let fallback = Duration::from_secs(300);
10047 let cap = Duration::from_secs(1800);
10048
10049 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10051
10052 let soon = now + jiff::SignedDuration::from_secs(600);
10054 assert_eq!(
10055 quota_wait(Some(soon), now, fallback, cap),
10056 Duration::from_secs(600)
10057 );
10058
10059 let past = now - jiff::SignedDuration::from_secs(60);
10062 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10063
10064 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10067 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10068 }
10069
10070 #[test]
10071 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10072 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10073
10074 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10075 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10076
10077 let already_past =
10081 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10082 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10083
10084 assert!(
10085 parse_reset_hint("session limit reached", now, now).is_none(),
10086 "free text with no recognised shape is not guessed at"
10087 );
10088 assert!(
10089 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10090 "an unresolvable zone name is not guessed at either"
10091 );
10092 }
10093
10094 #[test]
10095 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10096 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10097
10098 let at = parse_reset_hint(
10099 "You've hit your usage limit. Visit \
10100 https://chatgpt.com/codex/settings/usage to purchase more \
10101 credits or try again at Sep 19th, 2026 5:10 PM.",
10102 now,
10103 now,
10104 )
10105 .expect("the codex reset wording is a recognised shape");
10106 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10107
10108 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10113 .expect("an explicit year needs no rollover");
10114 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10115
10116 assert!(
10117 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10118 "a two-digit year is not the documented shape and is not guessed at"
10119 );
10120 assert!(
10121 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10122 "a four-letter month name is not the documented three-letter abbreviation"
10123 );
10124 assert!(
10125 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10126 "an explicit zone on the dated shape is a format nobody has \
10127 documented, and is refused rather than guessed at as UTC"
10128 );
10129 }
10130
10131 #[test]
10132 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10133 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10134 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10135
10136 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10137 assert_eq!(at.as_second() - recorded.as_second(), 3769);
10138
10139 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10140 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10141
10142 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10143 assert!(
10144 parse_reset_hint(bad, now, recorded).is_none(),
10145 "{bad:?} must not be guessed at"
10146 );
10147 }
10148 }
10149
10150 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10154 let config = dir.join("magi.toml");
10155 std::fs::write(
10156 &config,
10157 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10158 )
10159 .unwrap();
10160 let opts = Opts {
10161 poll: Duration::from_secs(30),
10162 config: Some(config),
10163 repo: dir.join("repo"),
10167 ..Opts::default()
10168 };
10169 let home = dir.join("home");
10178 let stamps = home.join("service-ticks");
10181 std::fs::create_dir_all(&stamps).unwrap();
10182 for service in ["waiter", "deputies", "release-watch"] {
10183 std::fs::write(
10184 stamps.join(service),
10185 Timestamp::now().as_second().to_string(),
10186 )
10187 .unwrap();
10188 }
10189 for operation in [
10190 "conductor",
10191 "maintenance",
10192 "housekeeping",
10193 "disk-pressure",
10194 "cache",
10195 "fetch",
10196 ] {
10197 std::fs::write(
10198 stamps.join(format!("daemon-{operation}")),
10199 serde_json::to_vec(&Timestamp::now()).unwrap(),
10200 )
10201 .unwrap();
10202 }
10203 let worktrees = dir.join("wt");
10204 (
10205 opts,
10206 Queue::at(dir.join("queue")),
10207 home.join("daemon.json"),
10208 home,
10209 worktrees,
10210 )
10211 }
10212
10213 #[test]
10214 fn a_stop_is_idempotent_and_once_set_stays_set() {
10215 let stop = Stop::new();
10216 assert!(!stop.stopped());
10217
10218 stop.stop();
10219 assert!(stop.stopped());
10220 stop.stop();
10221 assert!(stop.stopped(), "a second stop is not a toggle");
10222
10223 let shared = stop.clone();
10224 assert!(
10225 shared.stopped(),
10226 "a clone is the same stop; that is how the loop and its caller share one"
10227 );
10228 }
10229
10230 #[tokio::test]
10231 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10232 for operation in ["conductor", "maintenance", "housekeeping"] {
10233 let dir = tempfile::tempdir().unwrap();
10234 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10235 opts.once = true;
10236 opts.poll = Duration::from_millis(1);
10237 let mut task = task();
10238 task.runs.push("fixture-run".into());
10239 queue.put(&mut task).unwrap();
10240 let claim = queue.claim(&task.id).unwrap();
10241
10242 let directory = home.join("workers/jobs/abcdef");
10245 std::fs::create_dir_all(&directory).unwrap();
10246 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10247 crate::pr_head::try_lock_file(&lease).unwrap();
10248 let mut job = crate::worker::Job {
10249 id: "abcdef".into(),
10250 sequence: 1,
10251 kind: "daemon-service".into(),
10252 key: format!("service:daemon-{operation}"),
10253 payload: serde_json::Value::Null,
10254 generation: "fixture".into(),
10255 version: None,
10256 status: crate::worker::Status::Running,
10257 result: None,
10258 pid: Some(std::process::id()),
10259 created_at: Timestamp::now().as_second() as u64,
10260 finished_at: None,
10261 };
10262 let record = directory.join("job.json");
10263 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10264
10265 let status = Arc::new(Mutex::new(Status::new()));
10266 let stop = Stop::new();
10267 let mut drain = Box::pin(poll(
10268 &opts,
10269 &queue,
10270 &status,
10271 &home,
10272 &worktrees,
10273 &stop,
10274 DispatchLimits {
10275 max_concurrent: 1,
10276 pause_for_interrupts: false,
10277 recovery_cfg: None,
10278 },
10279 ));
10280 std::future::poll_fn(|cx| {
10281 use std::future::Future;
10282 assert!(
10283 drain.as_mut().poll(cx).is_pending(),
10284 "--once must wait for {operation} to release its queue claim"
10285 );
10286 std::task::Poll::Ready(())
10287 })
10288 .await;
10289 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10290
10291 let questions = Questions::at(home.join("questions"));
10294 let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10295 questions.put(&mut q).unwrap();
10296 drop(claim);
10297 let expired =
10301 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10302 for service in [operation, "housekeeping"] {
10303 std::fs::write(
10304 home.join("service-ticks").join(format!("daemon-{service}")),
10305 &expired,
10306 )
10307 .unwrap();
10308 }
10309 job.status = crate::worker::Status::Finished;
10310 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10311 drop(lease);
10312 tokio::time::timeout(Duration::from_secs(2), drain)
10313 .await
10314 .expect("the settled service must allow the drain to finish")
10315 .unwrap();
10316 let after = queue.get(&task.id).unwrap();
10317 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10318 assert!(after.action_applied(&q.id));
10319 for service in [operation, "housekeeping"] {
10320 assert_eq!(
10321 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10322 .unwrap(),
10323 expired,
10324 "the final once rescan must not restart {service}"
10325 );
10326 }
10327 }
10328 }
10329
10330 #[test]
10331 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10332 let stop = Stop::new();
10333 stop.busy.store(1, Ordering::SeqCst);
10334 assert!(
10335 !stop.finishing(),
10336 "a busy loop nobody has asked to stop is just running"
10337 );
10338
10339 stop.stop();
10340 assert!(
10341 stop.finishing(),
10342 "a stop asked for mid-run has not landed until the run is settled"
10343 );
10344
10345 stop.busy.store(0, Ordering::SeqCst);
10346 assert!(
10347 !stop.finishing(),
10348 "once the run is settled the stop has landed and there is nothing to finish"
10349 );
10350 }
10351
10352 #[test]
10353 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10354 let stop = Stop::new();
10355 stop.busy.store(2, Ordering::SeqCst);
10356 stop.stop();
10357 assert!(stop.finishing(), "two runs still in flight");
10358
10359 stop.busy.store(1, Ordering::SeqCst);
10360 assert!(
10361 stop.finishing(),
10362 "one run finished, but a sibling is still working"
10363 );
10364
10365 stop.busy.store(0, Ordering::SeqCst);
10366 assert!(
10367 !stop.finishing(),
10368 "the last run out is what actually lands the stop"
10369 );
10370 }
10371
10372 #[tokio::test]
10373 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10374 let dir = tempfile::tempdir().unwrap();
10375 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10376 let stop = Stop::new();
10377 stop.stop();
10378
10379 let began = std::time::Instant::now();
10380 tokio::time::timeout(
10381 Duration::from_secs(2),
10382 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10383 )
10384 .await
10385 .expect("a stopped loop must return, not sit out its poll interval")
10386 .expect("the loop's own setup and teardown must not fail");
10387 assert!(
10388 began.elapsed() < opts.poll,
10389 "returned only after {:?}, which is a poll interval, not a stop",
10390 began.elapsed()
10391 );
10392 }
10393
10394 #[tokio::test]
10395 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10396 let dir = tempfile::tempdir().unwrap();
10397 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10398 let stop = Stop::new();
10399
10400 let asker = {
10403 let stop = stop.clone();
10404 tokio::spawn(async move {
10405 tokio::time::sleep(Duration::from_millis(20)).await;
10406 stop.stop();
10407 })
10408 };
10409
10410 let began = std::time::Instant::now();
10411 tokio::time::timeout(
10412 Duration::from_secs(2),
10413 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10414 )
10415 .await
10416 .expect("a stop asked for while idle must wake the wait")
10417 .expect("the loop's own setup and teardown must not fail");
10418 asker.await.unwrap();
10419 assert!(
10420 began.elapsed() < opts.poll,
10421 "returned only after {:?}, so the stop waited on the sleep",
10422 began.elapsed()
10423 );
10424 }
10425
10426 #[tokio::test]
10427 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10428 let dir = tempfile::tempdir().unwrap();
10429 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10430 let stop = Stop::new();
10431 stop.stop();
10432
10433 tokio::time::timeout(
10434 Duration::from_secs(2),
10435 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10436 )
10437 .await
10438 .expect("a stopped loop must return")
10439 .expect("the loop's own setup and teardown must not fail");
10440
10441 assert!(
10442 home.is_dir(),
10443 "the loop did publish a status file, so its removal is the teardown and not an absence"
10444 );
10445 assert!(
10446 !status_file.exists(),
10447 "a stopped loop clears its status file"
10448 );
10449 assert!(
10450 read_status(&home).is_none(),
10451 "a reader must see no daemon at all, not a heartbeat that merely stopped"
10452 );
10453 }
10454
10455 #[tokio::test]
10456 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10457 let dir = tempfile::tempdir().unwrap();
10458 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10459
10460 let mut settled = RunState::new(
10461 dir.path().join("repo"),
10462 "main".to_owned(),
10463 "abc1234".to_owned(),
10464 "fixture".to_owned(),
10465 Config::default(),
10466 );
10467 settled.status = RunStatus::Ready;
10468 let run_dir = home.join("runs").join(&settled.id);
10469 std::fs::create_dir_all(&run_dir).unwrap();
10470 std::fs::write(
10471 run_dir.join("run.json"),
10472 serde_json::to_string_pretty(&settled).unwrap(),
10473 )
10474 .unwrap();
10475 let questions = Questions::at(home.join("questions"));
10476 let mut question = ask::Question::new(
10477 settled.id.clone(),
10478 "review".to_owned(),
10479 "reviewer-1".to_owned(),
10480 "Continue?".to_owned(),
10481 String::new(),
10482 Vec::new(),
10483 );
10484 questions.put(&mut question).unwrap();
10485
10486 run_service_worker(
10487 &home,
10488 serde_json::to_value(ServiceWorker {
10489 opts,
10490 queue: queue.root().to_path_buf(),
10491 worktrees_root: worktrees,
10492 operation: "housekeeping".to_owned(),
10493 })
10494 .unwrap(),
10495 )
10496 .await
10497 .unwrap();
10498
10499 assert_eq!(
10500 questions.get(&question.id).unwrap().status,
10501 ask::QuestionStatus::Abandoned,
10502 "the independent housekeeping worker settles ended-run questions"
10503 );
10504 }
10505
10506 #[test]
10507 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10508 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10509
10510 assert!(
10511 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10512 "never checked before: due at once"
10513 );
10514
10515 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10516 assert!(
10517 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10518 "well inside the interval: not due yet"
10519 );
10520
10521 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10522 assert!(
10523 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10524 "exactly at the edge: not yet due, same convention as `clean::due`"
10525 );
10526
10527 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10528 assert!(
10529 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10530 "past the interval: due again"
10531 );
10532 }
10533
10534 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10539 let config = dir.join("magi.toml");
10540 std::fs::write(
10546 &config,
10547 format!(
10548 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10549 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10550 cache_dir.display()
10551 ),
10552 )
10553 .unwrap();
10554 Opts {
10555 config: Some(config),
10556 repo: dir.join("repo"),
10557 ..Opts::default()
10558 }
10559 }
10560
10561 #[tokio::test]
10562 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10563 let dir = tempfile::tempdir().unwrap();
10564 let home = dir.path().join("home");
10565 let cache_dir = dir.path().join("cache");
10566 std::fs::create_dir_all(&cache_dir).unwrap();
10567 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10568 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10569
10570 let running = Stop::new();
10573 let mut last_checked = None;
10574 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10575 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10576 .await;
10577 assert_eq!(
10578 crate::disk::dir_size(&cache_dir),
10579 0,
10580 "over the cap on the first check ever: pruned at once, no idle queue required"
10581 );
10582 assert_eq!(last_checked, Some(t0));
10583
10584 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10586 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10587 maybe_prune_cache_between_runs(
10588 &opts.repo,
10589 &opts,
10590 &home,
10591 &running,
10592 &mut last_checked,
10593 too_soon,
10594 )
10595 .await;
10596 assert_eq!(
10597 crate::disk::dir_size(&cache_dir),
10598 10,
10599 "too soon since the last check: left alone rather than rescanned every call"
10600 );
10601 assert_eq!(
10602 last_checked,
10603 Some(t0),
10604 "an idle check does not reset the clock"
10605 );
10606
10607 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10609 maybe_prune_cache_between_runs(
10610 &opts.repo,
10611 &opts,
10612 &home,
10613 &running,
10614 &mut last_checked,
10615 due_again,
10616 )
10617 .await;
10618 assert_eq!(
10619 crate::disk::dir_size(&cache_dir),
10620 0,
10621 "due again: pruned back under the cap"
10622 );
10623 }
10624
10625 #[tokio::test]
10633 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10634 let dir = tempfile::tempdir().unwrap();
10635 let home = dir.path().join("home");
10636 let cache_dir = dir.path().join("cache");
10637 std::fs::create_dir_all(&cache_dir).unwrap();
10638 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10639 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10640
10641 let stop = Stop::new();
10642 stop.stop();
10643 assert!(
10644 !stop.finishing(),
10645 "no run is in flight at a between-runs boundary, so nothing else \
10646 would tell the operator this stop had not taken effect yet"
10647 );
10648
10649 let mut last_checked = None;
10650 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10651 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10652 .await;
10653 assert_eq!(
10654 crate::disk::dir_size(&cache_dir),
10655 10,
10656 "over its cap, and due for the first check ever, but a stop outranks \
10657 it: the cap is a standing policy the next start measures again"
10658 );
10659 assert_eq!(
10660 last_checked, None,
10661 "a check that never happened must not claim the interval"
10662 );
10663 }
10664
10665 #[tokio::test]
10668 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10669 let dir = tempfile::tempdir().unwrap();
10670 let cache_dir = dir.path().join("cache");
10671 std::fs::create_dir_all(&cache_dir).unwrap();
10672 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10673
10674 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10675 opts.poll = Duration::from_millis(20);
10676 opts.max_attempts = 1_000;
10677
10678 let queue = Queue::at(dir.path().join("queue"));
10679 for i in 0..128 {
10680 let mut task = Task::new(
10681 format!("queued work {i}"),
10682 format!("queued work {i}"),
10683 opts.repo.clone(),
10684 Source::Human,
10685 );
10686 queue.put(&mut task).unwrap();
10687 }
10688
10689 let home = dir.path().join("home");
10690 let worktrees = dir.path().join("wt");
10691 run_service_worker(
10692 &home,
10693 serde_json::to_value(ServiceWorker {
10694 opts,
10695 queue: queue.root().to_path_buf(),
10696 worktrees_root: worktrees,
10697 operation: "cache".to_owned(),
10698 })
10699 .unwrap(),
10700 )
10701 .await
10702 .unwrap();
10703 let after = queue.list();
10704 assert_eq!(after.len(), 128);
10705 assert!(
10706 after
10707 .iter()
10708 .all(|task| task.status.runnable() && task.attempts == 0)
10709 );
10710
10711 assert_eq!(
10712 crate::disk::dir_size(&cache_dir),
10713 0,
10714 "an oversized cache must not be left to grow unboundedly just because the \
10715 queue kept the loop busy the whole time"
10716 );
10717 }
10718
10719 #[test]
10720 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10721 let dir = tempfile::tempdir().unwrap();
10722 let queue = Queue::at(dir.path().join("queue"));
10723 let questions = Questions::at(dir.path().join("questions"));
10724 let mut task = task();
10725 queue.put(&mut task).unwrap();
10726
10727 let mut task_question = ask::Question::new(
10728 task.id.clone(),
10729 crate::conduct::NODE.to_owned(),
10730 "conduct".to_owned(),
10731 "Which backend?".to_owned(),
10732 String::new(),
10733 Vec::new(),
10734 );
10735 questions.put(&mut task_question).unwrap();
10736 task.block(vec![task_question.id.clone()], None);
10737 queue.put(&mut task).unwrap();
10738
10739 let mut run_question = ask::Question::new(
10740 "20260101-000000-run1".to_owned(),
10741 "review".to_owned(),
10742 "reviewer-1".to_owned(),
10743 "Run question".to_owned(),
10744 String::new(),
10745 Vec::new(),
10746 );
10747 questions.put(&mut run_question).unwrap();
10748
10749 let mut coincidental = ask::Question::new(
10754 task.id.clone(),
10755 "review".to_owned(),
10756 "reviewer-1".to_owned(),
10757 "Unrelated review question".to_owned(),
10758 String::new(),
10759 Vec::new(),
10760 );
10761 questions.put(&mut coincidental).unwrap();
10762
10763 reconcile_task_questions(&queue, &questions);
10764 assert!(questions.get(&task_question.id).unwrap().status.open());
10765 assert!(questions.get(&run_question.id).unwrap().status.open());
10766 assert!(questions.get(&coincidental.id).unwrap().status.open());
10767
10768 task.release();
10769 queue.put(&mut task).unwrap();
10770 reconcile_task_questions(&queue, &questions);
10771 assert_eq!(
10772 questions.get(&task_question.id).unwrap().status,
10773 ask::QuestionStatus::Abandoned
10774 );
10775 assert!(
10776 questions.get(&run_question.id).unwrap().status.open(),
10777 "run questions remain the run janitor's responsibility"
10778 );
10779 assert!(
10780 questions.get(&coincidental.id).unwrap().status.open(),
10781 "a non-conductor question must not be abandoned just because its \
10782 run id coincides with a task id"
10783 );
10784 }
10785
10786 #[test]
10787 fn a_freshly_started_running_task_is_never_stalled() {
10788 let dir = tempfile::tempdir().unwrap();
10789 let mut t = task();
10790 t.start("run-1".to_owned());
10791 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10794 }
10795
10796 #[test]
10797 fn a_long_running_task_with_no_live_daemon_is_stalled() {
10798 let dir = tempfile::tempdir().unwrap();
10799 let mut t = task();
10800 t.start("run-1".to_owned());
10801 t.updated_at = Timestamp::now()
10802 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10803 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10804 assert_eq!(
10805 stalled_tasks(
10806 &Queue::at(dir.path().join("q")),
10807 dir.path(),
10808 Timestamp::now()
10809 )
10810 .len(),
10811 0,
10812 "the task was never written to this queue"
10813 );
10814 }
10815
10816 #[test]
10817 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10818 let dir = tempfile::tempdir().unwrap();
10819 let mut t = task();
10820 t.id = "20260903-080340-0167".to_owned();
10821 t.start("20260903-080619-01c2".to_owned());
10822 t.updated_at = Timestamp::now()
10823 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10824
10825 let mut status = Status::new();
10826 status.current = vec![Current {
10827 worker: None,
10828 task: t.id.clone(),
10829 run: "20260903-080619-01c2".to_owned(),
10830 }];
10831 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10832
10833 assert!(
10834 !is_stalled(&t, dir.path(), Timestamp::now()),
10835 "a live daemon's own heartbeat rules out stalled, however long the task has run"
10836 );
10837 }
10838
10839 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10843 let path = queue.path_of(id);
10844 let body = std::fs::read_to_string(&path).unwrap();
10845 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10846 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10847 v["updated_at"] = serde_json::Value::String(old.to_string());
10848 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10849 }
10850
10851 #[test]
10852 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10853 let dir = tempfile::tempdir().unwrap();
10866 let queue = Queue::at(dir.path().join("queue"));
10867 let home = dir.path().join("home");
10868
10869 let mut t = task();
10870 t.id = "20260101-000001-lock".to_owned();
10871 t.start("run-1".to_owned());
10872 queue.put(&mut t).unwrap();
10873 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10874 std::fs::write(
10875 dir.path().join("queue").join(format!("{}.lock", t.id)),
10876 "not a pid",
10877 )
10878 .unwrap();
10879
10880 let now = Timestamp::now();
10881 assert!(
10882 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10883 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10884 and reclaim must leave the task alone"
10885 );
10886 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10887
10888 let stalled = stalled_tasks(&queue, &home, now);
10889 assert_eq!(
10890 stalled.len(),
10891 1,
10892 "reclaim's inability to claim it yet must not hide it from the conductor"
10893 );
10894 assert_eq!(stalled[0].id, t.id);
10895 }
10896
10897 #[test]
10898 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10899 let dir = tempfile::tempdir().unwrap();
10900 crate::run::set_home(dir.path().join("run-home"));
10901 let queue = Queue::at(dir.path().join("queue"));
10902 let home = dir.path().join("home");
10903 let questions = Questions::at(dir.path().join("questions"));
10904
10905 let mut t = task();
10906 t.id = "20260101-000003-dead".to_owned();
10907 t.start("missing-run".to_owned());
10908 queue.put(&mut t).unwrap();
10909 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10910
10911 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10914 assert_eq!(
10915 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10916 [&t.id]
10917 );
10918 assert_eq!(
10919 reclaim_orphaned_running(&queue, 2, &Default::default()),
10920 [t.id.clone()]
10921 );
10922 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10923
10924 crate::conduct::apply(
10927 &queue,
10928 &questions,
10929 &crate::conduct::Verdict {
10930 decisions: vec![crate::conduct::Decision {
10931 id: t.id.clone(),
10932 recovery: Some(crate::conduct::Recovery::Requeue),
10933 ..crate::conduct::Decision::default()
10934 }],
10935 },
10936 )
10937 .unwrap();
10938 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10939 }
10940
10941 #[test]
10942 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10943 let dir = tempfile::tempdir().unwrap();
10944 let queue = Queue::at(dir.path().join("queue"));
10945 let home = dir.path().join("home");
10946
10947 let mut fresh = task();
10948 fresh.id = "20260101-000001-aaaa".to_owned();
10949 fresh.start("run-1".to_owned());
10950 queue.put(&mut fresh).unwrap();
10951
10952 let mut old = task();
10953 old.id = "20260101-000002-bbbb".to_owned();
10954 old.start("run-2".to_owned());
10955 queue.put(&mut old).unwrap();
10956 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10957
10958 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10959 assert_eq!(stalled.len(), 1);
10960 assert_eq!(stalled[0].id, old.id);
10961 }
10962
10963 #[test]
10964 fn queued_and_finished_task_views_partition_by_status() {
10965 let dir = tempfile::tempdir().unwrap();
10966 let queue = Queue::at(dir.path().join("queue"));
10967
10968 let mut queued = task();
10969 queued.id = "20260101-000001-aaaa".to_owned();
10970 queue.put(&mut queued).unwrap();
10971
10972 let mut failed = task();
10973 failed.id = "20260101-000002-bbbb".to_owned();
10974 failed.start("run-1".to_owned());
10975 failed.fail("gate red", 5);
10976 queue.put(&mut failed).unwrap();
10977
10978 let mut held = task();
10979 held.id = "20260101-000003-cccc".to_owned();
10980 held.hold_machine(None);
10981 queue.put(&mut held).unwrap();
10982
10983 let mut running = task();
10984 running.id = "20260101-000004-dddd".to_owned();
10985 running.start("run-2".to_owned());
10986 queue.put(&mut running).unwrap();
10987
10988 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10989 assert_eq!(queued_ids, [queued.id.clone()]);
10990
10991 let mut finished_ids: Vec<String> =
10992 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10993 finished_ids.sort_unstable();
10994 let mut want = vec![failed.id.clone(), held.id.clone()];
10995 want.sort_unstable();
10996 assert_eq!(finished_ids, want);
10997 }
10998
10999 #[test]
11000 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11001 for short in [false, true] {
11002 let dir = tempfile::tempdir().unwrap();
11003 let queue = Queue::at(dir.path().join("queue"));
11004 let questions = ask::Questions::at(dir.path().join("questions"));
11005 let mut running = task();
11006 running.id = "20261013-192213-feb2".into();
11007 running.start("existing-run".into());
11008 queue.put(&mut running).unwrap();
11009 let mut middle = task();
11010 middle.id = "20261013-193611-ca5b".into();
11011 middle.block(
11012 vec![if short {
11013 "feb2".into()
11014 } else {
11015 running.id.clone()
11016 }],
11017 None,
11018 );
11019 queue.put(&mut middle).unwrap();
11020 let mut waiting = task();
11021 waiting.id = "20261013-202849-ee37".into();
11022 waiting.block(
11023 vec![if short {
11024 "ca5b".into()
11025 } else {
11026 middle.id.clone()
11027 }],
11028 Some("wait for implementation".into()),
11029 );
11030 queue.put(&mut waiting).unwrap();
11031 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11032 let inv = crate::blockers::Inventory::load(&queue, &questions);
11033 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11034 assert!(inv.stuck().is_empty());
11035 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11036 assert!(report.quarantined.is_empty());
11037 assert!(report.asked.is_empty());
11038 resolve_blockers(&queue, &questions);
11039 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11040 assert!(questions.list().is_empty());
11041 running.succeed();
11044 queue.put(&mut running).unwrap();
11045 resolve_blockers(&queue, &questions);
11046 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11047 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11048 middle = queue.get(&middle.id).unwrap();
11049 middle.succeed();
11050 queue.put(&mut middle).unwrap();
11051 resolve_blockers(&queue, &questions);
11052 let after = queue.get(&waiting.id).unwrap();
11053 assert_eq!(after.status, TaskStatus::Queued);
11054 assert!(after.blocked_by.is_empty());
11055 assert_eq!(after.instruction, waiting.instruction);
11056 }
11057 }
11058
11059 #[test]
11060 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11061 for future_schema in [false, true] {
11062 let name = "20261013-193611-ca5b";
11063 let mut future = task();
11064 future.id = name.into();
11065 future.schema = crate::queue::SCHEMA + 1;
11066 let contents = if future_schema {
11067 serde_json::to_string(&future).unwrap()
11068 } else {
11069 "corrupt".into()
11070 };
11071 let dir = tempfile::tempdir().unwrap();
11072 let queue = Queue::at(dir.path().join("queue"));
11073 let questions = ask::Questions::at(dir.path().join("questions"));
11074 let mut waiting = task();
11075 waiting.id = "20261013-202849-ee37".into();
11076 waiting.block(vec!["ca5b".into()], None);
11077 queue.put(&mut waiting).unwrap();
11078 std::fs::write(queue.path_of(name), contents).unwrap();
11079 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11080 assert!(
11081 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11082 );
11083 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11084 assert!(report.asked.is_empty());
11085 resolve_blockers(&queue, &questions);
11086 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11087 assert!(questions.list().is_empty());
11088 }
11089 let dir = tempfile::tempdir().unwrap();
11090 let queue = Queue::at(dir.path().join("queue"));
11091 let questions = ask::Questions::at(dir.path().join("questions"));
11092 let mut waiting = task();
11093 waiting.id = "20261013-202849-ee37".into();
11094 waiting.block(vec!["ca5b".into()], None);
11095 queue.put(&mut waiting).unwrap();
11096 let mut done = task();
11097 done.id = "20261013-193611-ca5b".into();
11098 done.succeed();
11099 queue.put(&mut done).unwrap();
11100 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11103 assert!(queue.get("ca5b").is_err());
11104 assert_eq!(
11105 crate::queue::dependency(&queue, &questions, "ca5b"),
11106 crate::queue::Dependency::Ambiguous
11107 );
11108 resolve_blockers(&queue, &questions);
11109 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11110 assert!(report.asked.is_empty());
11111 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11112 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11113 }
11114
11115 #[test]
11116 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11117 for held in [false, true] {
11118 for question in [false, true] {
11119 for reference in ["ca5b", "20261013-193611-ca5b"] {
11120 let dir = tempfile::tempdir().unwrap();
11121 let queue = Queue::at(dir.path().join("queue"));
11122 let questions = ask::Questions::at(dir.path().join("questions"));
11123 let mut prerequisite = task();
11124 prerequisite.id = "20261013-193611-ca5b".into();
11125 prerequisite.start("existing-run".into());
11126 queue.put(&mut prerequisite).unwrap();
11127 let mut waiting = task();
11128 waiting.id = "20261013-202849-ee37".into();
11129 if held {
11130 waiting.hold_machine(Some("waiting for separate consent".into()));
11131 }
11132 queue.put(&mut waiting).unwrap();
11133 let reason = "Deleting saved data requires separate owner consent";
11134 crate::conduct::apply(
11135 &queue,
11136 &questions,
11137 &crate::conduct::Verdict {
11138 decisions: vec![crate::conduct::Decision {
11139 id: waiting.id.clone(),
11140 blocked_by: vec![reference.into()],
11141 question: question.then(|| "May the saved data be deleted?".into()),
11142 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11143 reason: Some(reason.into()),
11144 ..crate::conduct::Decision::default()
11145 }],
11146 },
11147 )
11148 .unwrap();
11149 let before = queue.get(&waiting.id).unwrap();
11150 if question {
11151 assert_eq!(before.status, TaskStatus::Blocked);
11152 let q = questions.get(&before.blocked_by[0]).unwrap();
11153 assert_eq!(q.summary, "May the saved data be deleted?");
11154 assert!(q.status.open());
11155 } else {
11156 assert_eq!(before.status, TaskStatus::Held);
11157 let recorded_reason = before.hold_reason.as_deref().unwrap();
11158 assert!(recorded_reason.starts_with(reason));
11159 if held {
11160 assert!(recorded_reason.contains("waiting for separate consent"));
11161 }
11162 }
11163 prerequisite.succeed();
11164 queue.put(&mut prerequisite).unwrap();
11165 resolve_blockers(&queue, &questions);
11166 let after = queue.get(&waiting.id).unwrap();
11167 assert_eq!(after.status, before.status);
11168 assert_eq!(after.blocked_by, before.blocked_by);
11169 assert_eq!(after.hold_reason, before.hold_reason);
11170 assert_eq!(after.instruction, waiting.instruction);
11171 if question {
11172 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11173 }
11174 assert!(
11175 queue.next_runnable().is_none(),
11176 "dependency completion is not consent"
11177 );
11178 }
11179 }
11180 }
11181 }
11182
11183 #[test]
11184 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11185 let dir = tempfile::tempdir().unwrap();
11186 let queue = Queue::at(dir.path().join("queue"));
11187 let questions = ask::Questions::at(dir.path().join("questions"));
11188
11189 let mut dep = task();
11190 dep.id = "20260101-000001-dep0".to_owned();
11191 dep.succeed();
11192 queue.put(&mut dep).unwrap();
11193
11194 let mut still_going = task();
11195 still_going.id = "20260101-000002-dep1".to_owned();
11196 queue.put(&mut still_going).unwrap();
11197
11198 let mut blocked = task();
11199 blocked.id = "20260101-000003-main".to_owned();
11200 blocked.block(
11201 vec![dep.id.clone(), still_going.id.clone()],
11202 Some("waits on both".to_owned()),
11203 );
11204 queue.put(&mut blocked).unwrap();
11205
11206 resolve_blockers(&queue, &questions);
11207
11208 let after = queue.get(&blocked.id).unwrap();
11209 assert_eq!(
11210 after.status,
11211 TaskStatus::Blocked,
11212 "one dependency is still outstanding"
11213 );
11214 assert_eq!(after.blocked_by, [still_going.id.clone()]);
11215 }
11216
11217 #[test]
11218 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11219 let dir = tempfile::tempdir().unwrap();
11220 let queue = Queue::at(dir.path().join("queue"));
11221 let questions = ask::Questions::at(dir.path().join("questions"));
11222
11223 let mut q = crate::ask::Question::new(
11224 "20260101-000001-main".to_owned(),
11225 crate::conduct::NODE.to_owned(),
11226 "conduct".to_owned(),
11227 "Which backend?".to_owned(),
11228 String::new(),
11229 Vec::new(),
11230 );
11231 questions.put(&mut q).unwrap();
11232 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11233 .unwrap();
11234 questions.put(&mut q).unwrap();
11235
11236 let mut blocked = task();
11237 blocked.id = "20260101-000001-main".to_owned();
11238 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11239 queue.put(&mut blocked).unwrap();
11240
11241 resolve_blockers(&queue, &questions);
11242
11243 let after = queue.get(&blocked.id).unwrap();
11244 assert_eq!(
11245 after.status,
11246 TaskStatus::Queued,
11247 "the only blocker resolved"
11248 );
11249 assert_eq!(after.answers.len(), 1);
11250 assert_eq!(after.answers[0].question, "Which backend?");
11251 assert_eq!(after.answers[0].answer, "SQLite");
11252
11253 let instruction = instruction_for(&after);
11255 assert!(instruction.contains("Which backend?"));
11256 assert!(instruction.contains("SQLite"));
11257 }
11258
11259 #[test]
11260 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11261 let dir = tempfile::tempdir().unwrap();
11262 let queue = Queue::at(dir.path().join("queue"));
11263 let questions = ask::Questions::at(dir.path().join("questions"));
11264
11265 let mut q = crate::ask::Question::new(
11266 "20260101-000001-main".to_owned(),
11267 crate::conduct::NODE.to_owned(),
11268 "conduct".to_owned(),
11269 "Is the setup done?".to_owned(),
11270 String::new(),
11271 Vec::new(),
11272 );
11273 q.abandon("no answer within 60s of asking");
11274 questions.put(&mut q).unwrap();
11275
11276 let mut blocked = task();
11277 blocked.id = "20260101-000001-main".to_owned();
11278 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11279 queue.put(&mut blocked).unwrap();
11280
11281 resolve_blockers(&queue, &questions);
11282
11283 let after = queue.get(&blocked.id).unwrap();
11284 assert_eq!(
11285 after.status,
11286 TaskStatus::Held,
11287 "never left blocked on nothing"
11288 );
11289 assert!(!after.operator_held(), "a machine hold, for triage");
11290 assert!(
11291 after
11292 .hold_reason
11293 .as_deref()
11294 .unwrap_or_default()
11295 .contains("went unanswered")
11296 );
11297 }
11298
11299 #[test]
11300 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11301 let dir = tempfile::tempdir().unwrap();
11307 let queue = Queue::at(dir.path().join("queue"));
11308 let questions = ask::Questions::at(dir.path().join("questions"));
11309
11310 let mut q = crate::ask::Question::new(
11311 "20260101-000001-main".to_owned(),
11312 crate::conduct::NODE.to_owned(),
11313 "conduct".to_owned(),
11314 "How should this be handled?".to_owned(),
11315 String::new(),
11316 Vec::new(),
11317 );
11318 questions.put(&mut q).unwrap();
11319 q.answer(crate::ask::Answer::Text(
11320 "leave it held, a human will look at it later".to_owned(),
11321 ))
11322 .unwrap();
11323 questions.put(&mut q).unwrap();
11324
11325 let mut held = task();
11326 held.id = "20260101-000001-main".to_owned();
11327 held.hold_machine(Some("out of attempts".to_owned()));
11328 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11329 queue.put(&mut held).unwrap();
11330
11331 resolve_blockers(&queue, &questions);
11332
11333 let after = queue.get(&held.id).unwrap();
11334 assert_eq!(after.status, TaskStatus::Held);
11335 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11336 assert_eq!(
11337 after.answers[0].answer,
11338 "leave it held, a human will look at it later"
11339 );
11340 }
11341
11342 #[test]
11343 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11344 let dir = tempfile::tempdir().unwrap();
11345 let queue = Queue::at(dir.path().join("queue"));
11346 let questions = ask::Questions::at(dir.path().join("questions"));
11347 let mut dep = task();
11348 dep.id = "20260101-000001-gone".to_owned();
11349 queue.put(&mut dep).unwrap();
11350 let mut blocked = task();
11351 blocked.id = "20260101-000003-main".to_owned();
11352 blocked.block(vec![dep.id.clone()], None);
11353 queue.put(&mut blocked).unwrap();
11354
11355 let claim = queue.claim(&blocked.id).unwrap();
11357 queue.remove(&dep.id, false, &questions).unwrap();
11358 drop(claim);
11359 resolve_blockers(&queue, &questions);
11360
11361 let after = queue.get(&blocked.id).unwrap();
11362 assert_eq!(after.status, TaskStatus::Queued);
11363 assert!(after.blocked_by.is_empty());
11364 }
11365
11366 #[test]
11367 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11368 let dir = tempfile::tempdir().unwrap();
11374 let queue = Queue::at(dir.path().join("queue"));
11375 let questions = ask::Questions::at(dir.path().join("questions"));
11376
11377 let mut still_going = task();
11378 still_going.id = "20260101-000002-dep1".to_owned();
11379 queue.put(&mut still_going).unwrap();
11380
11381 let mut blocked = task();
11382 blocked.id = "20260101-000003-main".to_owned();
11383 blocked.block(
11384 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11385 Some("waits on both".to_owned()),
11386 );
11387 queue.put(&mut blocked).unwrap();
11388
11389 resolve_blockers(&queue, &questions);
11390
11391 let after = queue.get(&blocked.id).unwrap();
11392 assert_eq!(
11393 after.status,
11394 TaskStatus::Held,
11395 "a missing dependency must not leave the task blocked forever"
11396 );
11397 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11398 assert!(after.blocked_by.is_empty());
11399 let reason = after.hold_reason.as_deref().unwrap_or_default();
11400 assert!(
11401 reason.contains("20260101-000001-gone"),
11402 "the missing id must be named so an operator can tell what happened: {reason}"
11403 );
11404 assert!(
11405 reason.contains(&still_going.id),
11406 "the still-valid dependency must not silently vanish from the record: {reason}"
11407 );
11408 }
11409
11410 #[test]
11411 fn instruction_for_is_unchanged_without_any_answers() {
11412 let t = task();
11413 assert_eq!(instruction_for(&t), t.instruction);
11414 }
11415
11416 #[test]
11417 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11418 let dir = tempfile::tempdir().unwrap();
11419 let q = Queue::at(dir.path().join("queue"));
11420 let src = dir.path().join("shot.png");
11421 std::fs::write(&src, "x").unwrap();
11422 let mut t = task();
11423 q.attach(&mut t, &[src]).unwrap();
11424 let paths = task_attachments(&q, &t).unwrap();
11425 assert_eq!(paths.len(), 1);
11426 assert!(paths[0].is_absolute() && paths[0].is_file());
11427 std::fs::remove_file(&paths[0]).unwrap();
11428 let err = task_attachments(&q, &t).unwrap_err().to_string();
11429 assert!(err.contains("shot.png"), "{err}");
11430 }
11431
11432 #[tokio::test]
11433 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11434 let dir = tempfile::tempdir().unwrap();
11435 let queue_path = dir.path().join("queue");
11436 let queue = Queue::at(queue_path.clone());
11437 let mut t = task();
11438 t.source = Source::Agent {
11439 run: "originating-chat".into(),
11440 node: crate::queue::CHAT_NODE.into(),
11441 };
11442 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11443 stage: "config-fetch",
11444 target: "origin/main".into(),
11445 });
11446 record_config_failure(&mut t, &fetch);
11447 t.hold_machine(Some(format!("{fetch:#}")));
11448 let fetch_key = t.chat_notice_due().unwrap();
11449 t.chat_notices.push(fetch_key.clone());
11450 queue.put(&mut t).unwrap();
11451
11452 let queue = Queue::at(queue_path);
11453 let mut t = queue.get(&t.id).unwrap();
11454 let a = dir.path().join("a.toml");
11455 let b = dir.path().join("b.toml");
11456 for (path, text, new_cause) in [
11457 (&a, "[graph", true),
11458 (&a, "[verify", false),
11459 (&a, "[graph]\nimplementers = 'invalid-type'", true),
11460 (&b, "[graph]\nimplementers = 'invalid-type'", true),
11461 ] {
11462 t.release_operator("test", None);
11463 std::fs::write(path, text).unwrap();
11464 let error = Config::discover_fetched(dir.path(), Some(path))
11465 .await
11466 .unwrap_err();
11467 record_config_failure(&mut t, &error);
11468 t.hold_machine(Some(format!("{error:#}")));
11469 let due = t.chat_notice_due();
11470 assert_eq!(due.is_some(), new_cause, "{error:#}");
11471 if let Some(key) = due {
11472 assert_ne!(key, fetch_key);
11473 t.chat_notices.push(key);
11474 }
11475 }
11476 t.succeed();
11477 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11478 }
11479
11480 #[test]
11481 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11482 let dir = tempfile::tempdir().unwrap();
11483 let queue_path = dir.path().join("queue");
11484 let queue = Queue::at(queue_path.clone());
11485 let mut t = task();
11486 t.source = crate::queue::Source::Agent {
11487 run: "originating-chat".into(),
11488 node: crate::queue::CHAT_NODE.into(),
11489 };
11490 let a = dir.path().join("a.png");
11491 let b = dir.path().join("b.png");
11492 std::fs::write(&a, "a").unwrap();
11493 std::fs::write(&b, "b").unwrap();
11494 queue.attach(&mut t, &[a, b]).unwrap();
11495 let paths = task_attachments(&queue, &t).unwrap();
11496 for path in &paths {
11497 std::fs::remove_file(path).unwrap();
11498 }
11499 let missing = task_attachments(&queue, &t).unwrap_err();
11500 t.attempts += 1;
11501 let reason = missing.to_string();
11502 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11503 let first = t.chat_notice_due().expect("first attachment notice");
11504 t.chat_notices.push(first.clone());
11505 queue.put(&mut t).unwrap();
11506
11507 let queue = Queue::at(queue_path.clone());
11508 let mut t = queue.get(&t.id).unwrap();
11509 assert!(t.chat_notice_due().is_none(), "restart does not replay");
11510 t.release_operator("test", None);
11511 t.attempts += 1;
11512 let missing = task_attachments(&queue, &t).unwrap_err();
11513 t.fail_startup_target(
11514 "startup-attachments",
11515 missing.name,
11516 "same missing attachment with regenerated wording",
11517 1,
11518 );
11519 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11520
11521 std::fs::write(&paths[0], "restored").unwrap();
11522 t.release_operator("test", None);
11523 t.attempts += 1;
11524 let missing = task_attachments(&queue, &t).unwrap_err();
11525 let reason = missing.to_string();
11526 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11527 let second = t
11528 .chat_notice_due()
11529 .expect("different attachment must notify");
11530 assert_ne!(first, second);
11531 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11532 }
11533
11534 #[test]
11535 fn resumed_instruction_is_unchanged_without_any_answers() {
11536 let t = task();
11537 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11538 }
11539
11540 #[test]
11541 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11542 let mut t = task();
11543 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11544 let old = t.instruction.clone();
11548
11549 let refreshed = resumed_instruction(&old, &t);
11550 assert!(refreshed.starts_with(&old), "the original text is kept");
11551 assert!(refreshed.contains("Which backend?"));
11552 assert!(refreshed.contains("SQLite"));
11553 }
11554
11555 #[test]
11556 fn resumed_instruction_keeps_an_original_answers_heading() {
11557 let mut t = task();
11558 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11559 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11560
11561 let refreshed = resumed_instruction(&t.instruction, &t);
11562
11563 assert!(
11564 refreshed.starts_with(&t.instruction),
11565 "an answers heading in the original instruction is not the appended block"
11566 );
11567 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11568 assert!(refreshed.contains("Which backend?"));
11569 assert!(refreshed.contains("SQLite"));
11570
11571 let repeated = resumed_instruction(&refreshed, &t);
11572 assert_eq!(
11573 repeated, refreshed,
11574 "only the final appended block is refreshed"
11575 );
11576 }
11577
11578 #[test]
11579 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11580 let mut t = task();
11581 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11582
11583 let once = resumed_instruction(&t.instruction, &t);
11587 let twice = resumed_instruction(&once, &t);
11588 assert_eq!(once, twice);
11589 assert_eq!(once.matches("Which backend?").count(), 1);
11590
11591 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11593 let refreshed = resumed_instruction(&once, &t);
11594 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11595 assert!(refreshed.contains("Which backend?"));
11596 assert!(refreshed.contains("Which cache?"));
11597 }
11598
11599 #[test]
11600 fn prepare_instruction_covers_all_three_starters() {
11601 let mut t = task();
11602 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11603
11604 assert_eq!(
11607 prepare_instruction(&Starter::Start, None, &t),
11608 Some(instruction_for(&t))
11609 );
11610
11611 let old = t.instruction.clone();
11614 assert_eq!(
11615 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11616 Some(resumed_instruction(&old, &t))
11617 );
11618
11619 assert_eq!(
11623 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11624 None
11625 );
11626 }
11627
11628 #[test]
11629 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11630 assert_eq!(
11631 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11632 Starter::Review("magi/eba2/A".to_owned())
11633 );
11634 }
11635
11636 #[test]
11637 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11638 assert_eq!(
11639 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11640 Starter::Start,
11641 "a vanished review branch must not fall back to resuming the old run either"
11642 );
11643 }
11644
11645 #[test]
11646 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11647 let mut t = task();
11648 t.start("old-run".to_owned());
11649 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11650 t.release();
11651 let branch = t.review_branch.take();
11652 assert_eq!(
11653 choose_starter(branch.as_deref(), true, Some("old-run")),
11654 Starter::Review("magi/eba2/A".to_owned()),
11655 "a review wins over resuming the old run"
11656 );
11657 }
11658
11659 #[test]
11660 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11661 assert_eq!(
11662 choose_starter(None, false, Some("some-run")),
11663 Starter::Resume("some-run".to_owned())
11664 );
11665 assert_eq!(choose_starter(None, false, None), Starter::Start);
11666 }
11667
11668 #[test]
11669 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11670 let mut released = task();
11671 released.start("stalled-run".to_owned());
11672 released.requeue();
11673 let unfinished = (!released.fresh_start)
11674 .then(|| Some("stalled-run".to_owned()))
11675 .flatten();
11676 assert_eq!(
11677 choose_starter(None, false, unfinished.as_deref()),
11678 Starter::Start,
11679 "release keeps run history but must not resume it"
11680 );
11681 assert_eq!(released.runs, ["stalled-run"]);
11682 }
11683
11684 fn stopped_public_run(status: RunStatus) -> RunState {
11685 let mut state = run_state(status);
11686 state.driver_exited = true;
11687 state.config.graph.land = true;
11688 state.config.graph.review_rounds = 1;
11689 state.reviews = vec![review_round(1)];
11690 state.merge = Some(crate::run::MergeOutcome {
11691 mode: MergeMode::Pr,
11692 ok: false,
11693 detail: "landing stopped".into(),
11694 empty: false,
11695 });
11696 state.pr = Some(crate::run::PrRecord {
11697 url: "https://example.test/pull/1".into(),
11698 number: 1,
11699 state: "open".into(),
11700 checks: "red".into(),
11701 round: 1,
11702 rounds: 1,
11703 red_at_merge: Vec::new(),
11704 });
11705 state
11706 }
11707
11708 #[test]
11709 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11710 for status in [RunStatus::Blocked, RunStatus::Gating] {
11711 let home = tempfile::tempdir().unwrap();
11712 let mut state = stopped_public_run(status);
11713 state.save_under(home.path()).unwrap();
11714 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11715 assert!(!exhausted_review_budget(&state));
11716 let mut task = held_task_with(&state.id);
11717 task.release();
11718 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11719 assert_eq!(
11720 choose_starter(None, false, unfinished.as_deref()),
11721 Starter::Resume(state.id.clone())
11722 );
11723 let question = action_question(&state.id, resume_action(&state.id));
11724 assert_eq!(
11725 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11726 ActionDecision::Resume(state.id.clone())
11727 );
11728 assert_eq!(
11730 crate::resume::validate(home.path(), &state.id).unwrap().id,
11731 state.id
11732 );
11733 let queue = Queue::at(home.path().join("queue"));
11734 let mut controlled = Task::new(
11735 "resume land".into(),
11736 state.instruction.clone(),
11737 state.repo.clone(),
11738 Source::Agent {
11739 run: "talk".into(),
11740 node: crate::queue::CHAT_NODE.into(),
11741 },
11742 );
11743 controlled.runs.push(state.id.clone());
11744 controlled.hold_machine(Some("land stopped".into()));
11745 queue.put(&mut controlled).unwrap();
11746 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11747 assert_eq!(resumed.status, TaskStatus::Queued);
11748 assert_eq!(
11749 resumed.resume_override.unwrap().pinned_run,
11750 Some(state.id.clone())
11751 );
11752 assert_eq!(resumed.attempts, 0);
11753 }
11754 }
11755
11756 #[test]
11757 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11758 for review_rounds in [0, 1] {
11759 let home = tempfile::tempdir().unwrap();
11760 let mut state = run_state(RunStatus::Blocked);
11761 state.config.graph.review_rounds = review_rounds;
11762 if review_rounds > 0 {
11763 let mut review = review_round(1);
11764 review.clean = true;
11765 state.reviews = vec![review];
11766 }
11767 state.gate_ran = true;
11768 state.gate = vec![crate::run::CommandOutcome {
11769 command: "verify".into(),
11770 code: Some(1),
11771 output_tail: "gate failed after repair budget exhausted".into(),
11772 duration_ms: 0,
11773 resource_blocked: false,
11774 }];
11775 state.save_under(home.path()).unwrap();
11776 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11777 assert!(exhausted_review_budget(&state));
11778 let mut task = held_task_with(&state.id);
11779 task.release();
11780 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11781 let question = action_question(&state.id, resume_action(&state.id));
11782 assert_ne!(
11783 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11784 ActionDecision::Resume(state.id.clone())
11785 );
11786 let error = crate::resume::validate(home.path(), &state.id)
11787 .unwrap_err()
11788 .to_string();
11789 assert!(!error.contains("review budget exhausted"), "{error}");
11790 assert!(
11791 error.contains(if review_rounds == 0 {
11792 "review is disabled"
11793 } else {
11794 "gate already ran"
11795 }),
11796 "{error}"
11797 );
11798
11799 state.gate_ran = false;
11801 state.gate.clear();
11802 assert!(!exhausted_review_budget(&state));
11803 assert_eq!(
11804 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11805 Some(state.id)
11806 );
11807 }
11808 }
11809
11810 #[test]
11811 fn resource_blocked_verification_resumes_the_same_run() {
11812 for (kind, stage) in [
11813 ("cache", "clean"),
11814 ("coordination", "clean"),
11815 ("cache", "review-e2e"),
11816 ("coordination", "no-reviews"),
11817 ("coordination", "handoff"),
11818 ] {
11819 let home = tempfile::tempdir().unwrap();
11820 let mut state = run_state(RunStatus::Blocked);
11821 state.config.graph.review_rounds = 1;
11822 let mut review = review_round(1);
11823 review.clean = true;
11824 state.reviews = vec![review];
11825 if stage == "review-e2e" {
11826 let review = &mut state.reviews[0];
11827 review.clean = false;
11828 review.blocking = 1;
11829 review.e2e = vec![crate::run::CommandOutcome {
11830 command: "verify".into(),
11831 code: None,
11832 output_tail: "resource wait expired".into(),
11833 duration_ms: 0,
11834 resource_blocked: true,
11835 }];
11836 } else if stage == "no-reviews" {
11837 state.config.graph.review_rounds = 0;
11838 state.reviews.clear();
11839 } else if stage == "handoff" {
11840 let review = &mut state.reviews[0];
11843 review.clean = false;
11844 review.blocking = 1;
11845 review.e2e = vec![crate::run::CommandOutcome {
11846 command: "verify".into(),
11847 code: Some(0),
11848 output_tail: String::new(),
11849 duration_ms: 0,
11850 resource_blocked: false,
11851 }];
11852 }
11853 state.gate_ran = false;
11854 state.resource_block = Some(crate::run::ResourceBlock {
11855 cause: crate::run::ResourceBlockCause::Other,
11856 node: if stage == "review-e2e" {
11857 "review"
11858 } else {
11859 "gate"
11860 }
11861 .into(),
11862 kind: kind.into(),
11863 detail: "resource wait expired".into(),
11864 at: jiff::Timestamp::now(),
11865 });
11866 state.save_under(home.path()).unwrap();
11867 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11868 assert!(!exhausted_review_budget(&state));
11869 let mut task = held_task_with(&state.id);
11870 task.release();
11871 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11872 assert_eq!(
11873 choose_starter(None, false, unfinished.as_deref()),
11874 Starter::Resume(state.id.clone())
11875 );
11876 let question = action_question(&state.id, resume_action(&state.id));
11877 assert_eq!(
11878 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11879 ActionDecision::Resume(state.id.clone())
11880 );
11881 assert_eq!(
11882 crate::resume::validate(home.path(), &state.id).unwrap().id,
11883 state.id
11884 );
11885 let queue = Queue::at(home.path().join("queue"));
11886 let mut controlled = Task::new(
11887 "resume verification".into(),
11888 state.instruction.clone(),
11889 state.repo.clone(),
11890 Source::Agent {
11891 run: "talk".into(),
11892 node: crate::queue::CHAT_NODE.into(),
11893 },
11894 );
11895 controlled.runs.push(state.id.clone());
11896 controlled.hold_machine(Some("verification resource unavailable".into()));
11897 queue.put(&mut controlled).unwrap();
11898 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11899 assert_eq!(resumed.status, TaskStatus::Queued);
11900 assert_eq!(
11901 resumed.resume_override.unwrap().pinned_run,
11902 Some(state.id.clone())
11903 );
11904 assert_eq!(resumed.attempts, 0);
11905
11906 state.config.graph.review_rounds = 1;
11908 let mut unresolved = review_round(1);
11909 unresolved.blocking = 1;
11910 state.reviews = vec![unresolved];
11911 state.resource_block = None;
11912 state.save_under(home.path()).unwrap();
11913 assert!(exhausted_review_budget(&state));
11914 assert!(crate::resume::validate(home.path(), &state.id).is_err());
11915 }
11916 }
11917
11918 #[tokio::test]
11919 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11920 if !crate::standalone_test(
11921 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11922 ) {
11923 return;
11924 }
11925 let home = tempfile::tempdir().unwrap();
11926 let mut owner = stopped_public_run(RunStatus::Blocked);
11927 owner.save_under(home.path()).unwrap();
11928 let history = vec![owner.id.clone()];
11929 let repo = owner.repo.clone();
11930 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11931 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11932 let initial =
11933 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11934 assert!(
11935 initial.is_pending(),
11936 "a busy record must not hold or resume the task"
11937 );
11938 owner.retired_to = Some("20260101-000001-bbbb".into());
11939 owner.save_under(home.path()).unwrap();
11940 drop(lock);
11941 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11942 .await
11943 .expect("ownership lock released")
11944 .expect("read settled owner");
11945 assert!(
11946 result.is_none(),
11947 "the retired owner must not be resumed from a stale read"
11948 );
11949 }
11950
11951 #[tokio::test]
11952 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11953 if !crate::standalone_test(
11954 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11955 ) {
11956 return;
11957 }
11958 let home = tempfile::tempdir().unwrap();
11959 let mut owner = stopped_public_run(RunStatus::Blocked);
11960 let repo = tempfile::tempdir().unwrap();
11961 crate::git::git(repo.path(), &["init"]).await.unwrap();
11962 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11963 owner.id = "20260101-000000-aaaa".into();
11964 owner.save_under(home.path()).unwrap();
11965 let mut successor = run_state(RunStatus::Blocked);
11966 successor.id = "20260101-000001-bbbb".into();
11967 successor.save_under(home.path()).unwrap();
11968 let runs = vec![owner.id.clone(), successor.id.clone()];
11969 assert_eq!(
11970 public_resume_owner(home.path(), &runs, &owner.repo)
11971 .await
11972 .unwrap()
11973 .unwrap()
11974 .id,
11975 owner.id
11976 );
11977 let subdir = owner.repo.join("nested");
11978 std::fs::create_dir(&subdir).unwrap();
11979 assert_eq!(
11980 public_resume_owner(home.path(), &runs, &subdir)
11981 .await
11982 .unwrap()
11983 .unwrap()
11984 .id,
11985 owner.id
11986 );
11987 #[cfg(unix)]
11988 {
11989 let alias = home.path().join("repo-alias");
11990 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11991 assert_eq!(
11992 public_resume_owner(home.path(), &runs, &alias.join("nested"))
11993 .await
11994 .unwrap()
11995 .unwrap()
11996 .id,
11997 owner.id
11998 );
11999 }
12000 let different = tempfile::tempdir().unwrap();
12001 crate::git::git(different.path(), &["init"]).await.unwrap();
12002 assert!(
12003 public_resume_owner(home.path(), &runs, different.path())
12004 .await
12005 .is_err()
12006 );
12007 std::fs::remove_file(
12008 home.path()
12009 .join("runs")
12010 .join(&successor.id)
12011 .join("run.json"),
12012 )
12013 .unwrap();
12014 assert!(
12015 public_resume_owner(home.path(), &runs, &owner.repo)
12016 .await
12017 .is_err()
12018 );
12019 }
12020
12021 #[test]
12022 fn an_ordinary_release_keeps_a_resumable_run_available() {
12023 let mut released = task();
12024 released.start("stalled-run".to_owned());
12025 released.release();
12026 let unfinished = (!released.fresh_start)
12027 .then(|| Some("stalled-run".to_owned()))
12028 .flatten();
12029 assert_eq!(
12030 choose_starter(None, false, unfinished.as_deref()),
12031 Starter::Resume("stalled-run".to_owned()),
12032 "manual release must preserve the normal resume path"
12033 );
12034 }
12035
12036 #[test]
12037 fn resume_refusals_explain_admission_without_changing_task_or_run() {
12038 crate::run::pin_test_home();
12039 use crate::handover::{ResumeRefusal, resume_refusal_under};
12040 let home = tempfile::tempdir().unwrap();
12041 let mut exhausted = run_state(RunStatus::Blocked);
12042 exhausted.driver_exited = true;
12043 exhausted.config.graph.review_rounds = 3;
12044 exhausted.reviews = (1..=3).map(review_round).collect();
12045 for refusal in [
12046 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12047 ResumeRefusal::Status(RunStatus::Ready),
12048 ResumeRefusal::Released("20261022-000000-aaaa".into()),
12049 ResumeRefusal::Retired("retirement-successor".into()),
12050 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12051 ] {
12052 let mut state = exhausted.clone();
12053 let expected = match refusal {
12054 ResumeRefusal::Status(_) => {
12055 state.status = RunStatus::Ready;
12056 "status `ready`"
12057 }
12058 ResumeRefusal::Released(ref target) => {
12059 state.released_to = Some(target.clone());
12060 "execution was released"
12061 }
12062 ResumeRefusal::Retired(ref target) => {
12063 state.retired_to = Some(target.clone());
12064 "execution was retired"
12065 }
12066 ResumeRefusal::OwnershipTransferred(ref target) => {
12067 state.pr_taken_over_by = Some(target.clone());
12068 "PR ownership was transferred"
12069 }
12070 _ => "review budget exhausted (3/3 rounds used)",
12071 };
12072 assert_eq!(
12073 resume_refusal_under(&state, Some(home.path())),
12074 Some(refusal.clone())
12075 );
12076 assert_eq!(
12077 refusal.successor(),
12078 state
12079 .released_to
12080 .as_deref()
12081 .or(state.retired_to.as_deref())
12082 .or(state.pr_taken_over_by.as_deref())
12083 );
12084 state.save_under(home.path()).unwrap();
12085 let queue = Queue::at(home.path().join("queue"));
12086 let mut task = Task::new(
12087 "retained implementation".into(),
12088 state.instruction.clone(),
12089 state.repo.clone(),
12090 Source::Agent {
12091 run: "talk".into(),
12092 node: crate::queue::CHAT_NODE.into(),
12093 },
12094 );
12095 task.runs.push(state.id.clone());
12096 task.hold_machine(Some("stopped".into()));
12097 queue.put(&mut task).unwrap();
12098 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12099 let before_run = serde_json::to_value(&state).unwrap();
12100 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12101 .unwrap_err()
12102 .to_string();
12103 assert!(error.contains(expected), "{error}");
12104 assert!(!error.contains("only a stalled or blocked"), "{error}");
12105 if matches!(refusal, ResumeRefusal::Status(_)) {
12106 assert!(
12107 error.contains("is final; there is nothing left to resume"),
12108 "{error}"
12109 );
12110 }
12111 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12112 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12113 assert!(error.contains("review-only successor with a new review budget"));
12114 assert!(error.contains("does not resume this run"));
12115 }
12116 for target in [
12117 &state.released_to,
12118 &state.retired_to,
12119 &state.pr_taken_over_by,
12120 ]
12121 .into_iter()
12122 .flatten()
12123 {
12124 let short = if state.retired_to.as_ref() == Some(target) {
12125 target.as_str()
12126 } else {
12127 crate::run::short_of(target)
12128 };
12129 assert!(
12130 error.contains(&format!("run {short}; inspect `magi show {short}`")),
12131 "{error}"
12132 );
12133 if short != target {
12134 assert!(!error.contains(target), "full successor id leaked: {error}");
12135 }
12136 }
12137 assert_eq!(
12138 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12139 before_task
12140 );
12141 assert_eq!(
12142 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12143 .unwrap(),
12144 before_run
12145 );
12146 let question = action_question(&state.id, resume_action(&state.id));
12147 for phrases in [&PHRASES_EN, &PHRASES_JA] {
12148 let ActionDecision::Refuse(detail) =
12149 decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12150 else {
12151 panic!("refusal expected");
12152 };
12153 assert!(detail.contains(expected), "{detail}");
12154 }
12155 }
12156 exhausted.status = RunStatus::Ready;
12158 exhausted.released_to = Some("released".into());
12159 exhausted.retired_to = Some("retired".into());
12160 exhausted.pr_taken_over_by = Some("owner".into());
12161 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12162 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12163 let detail = reason.diagnostic(&exhausted);
12164 for target in ["released", "retired", "owner"] {
12165 assert!(detail.contains(&format!("magi show {target}")));
12166 }
12167 }
12168
12169 #[test]
12170 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12171 let home = tempfile::tempdir().unwrap();
12172 let mut state = run_state(RunStatus::Blocked);
12173 state.driver_exited = true;
12174 state.config.graph.review_rounds = 1;
12175 state.reviews = vec![review_round(1)];
12176 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12177 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12178 let mut saved = state.clone();
12179 match checkpoint {
12180 "publication" => saved.pr_publication_pending = true,
12181 "approval" => {
12182 saved.land_approval = Some(crate::run::LandApproval {
12183 question: "approval".into(),
12184 head: "head".into(),
12185 })
12186 }
12187 "armed" => saved.land_armed_head = Some("head".into()),
12188 "landing" => saved.status = RunStatus::Landing,
12189 _ => {
12190 let mut question = ask::Question::new(
12191 saved.id.clone(),
12192 "review".into(),
12193 "review-1".into(),
12194 "continue?".into(),
12195 String::new(),
12196 vec!["continue".into()],
12197 );
12198 ask::Questions::at(home.path().join("questions"))
12199 .put(&mut question)
12200 .unwrap();
12201 }
12202 }
12203 saved.save_under(home.path()).unwrap();
12204 assert!(
12205 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12206 "{checkpoint}"
12207 );
12208 assert!(
12209 crate::resume::validate(home.path(), &saved.id).is_ok(),
12210 "{checkpoint}"
12211 );
12212 }
12213 }
12214
12215 #[test]
12216 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12217 let mut state = run_state(RunStatus::Blocked);
12218 state.config.graph.review_rounds = 3;
12219 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12220 assert!(exhausted_review_budget(&state));
12221
12222 state.reviews.pop();
12224 assert!(!exhausted_review_budget(&state));
12225
12226 let mut stalled = run_state(RunStatus::Stalled);
12229 stalled.config.graph.review_rounds = 1;
12230 stalled.reviews = vec![review_round(1)];
12231 assert!(!exhausted_review_budget(&stalled));
12232 }
12233
12234 fn review_round(round: usize) -> crate::run::ReviewRound {
12235 crate::run::ReviewRound {
12236 round,
12237 head: "deadbeef".to_owned(),
12238 verified_head: None,
12239 verified_at: None,
12240 reviews: Vec::new(),
12241 e2e: Vec::new(),
12242 verify_retried: false,
12243 e2e_deferred: false,
12244 e2e_defer_reason: None,
12245 fix: None,
12246 blocking: 0,
12247 answered: 1,
12248 expected: 1,
12249 clean: false,
12250 progressed: true,
12251 vote_split: false,
12252 reconsideration: Vec::new(),
12253 verdict: None,
12254 }
12255 }
12256
12257 #[test]
12258 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12259 let mut run = RunState::new(
12260 PathBuf::from("/repo"),
12261 "main".to_owned(),
12262 "abc1234def".to_owned(),
12263 "add retries".to_owned(),
12264 Config::default(),
12265 );
12266 run.status = RunStatus::Judging;
12267 run.parked = true;
12268 let mut task = Task::new(
12269 "add retries".to_owned(),
12270 "add retries".to_owned(),
12271 PathBuf::from("/repo"),
12272 crate::queue::Source::Human,
12273 );
12274 task.status = TaskStatus::Failed;
12275 task.runs = vec![run.id.clone()];
12276 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12277 assert!(with(&task, &run), "parked after judging is the case");
12278 let mut parked_task = task.clone();
12279 parked_task.status = TaskStatus::Parked;
12280 assert!(with(&parked_task, &run), "the Parked status is the case");
12281
12282 let mut not_parked = run.clone();
12283 not_parked.parked = false;
12284 not_parked.status = RunStatus::Stalled;
12285 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
12286
12287 let mut fresh = task.clone();
12288 fresh.fresh_start = true;
12289 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12290
12291 let mut review = task.clone();
12292 review.review_branch = Some("magi/x/A".to_owned());
12293 assert!(!with(&review, &run), "review is ranked before resume");
12294
12295 let mut held = task.clone();
12296 held.status = TaskStatus::Held;
12297 assert!(!with(&held, &run), "a hold stays visible to the conductor");
12298
12299 let mut released = run.clone();
12300 released.released_to = Some("20260901-000000-new1".to_owned());
12301 assert!(!with(&task, &released), "nothing left to resume into");
12302
12303 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12304 "unreadable"
12305 )));
12306 }
12307
12308 #[test]
12309 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12310 let mut released = RunState::new(
12311 PathBuf::from("/repo"),
12312 "main".to_owned(),
12313 "abc1234def".to_owned(),
12314 "add retries".to_owned(),
12315 Config::default(),
12316 );
12317 released.status = RunStatus::Blocked;
12318 assert_eq!(
12319 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12320 Some(released.id.clone())
12321 );
12322 released.released_to = Some("20260901-000000-new1".to_owned());
12323 assert_eq!(
12324 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12325 None,
12326 "there is nothing left to resume it into"
12327 );
12328 }
12329
12330 #[test]
12331 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12332 let mut exhausted = RunState::new(
12341 PathBuf::from("/repo"),
12342 "main".to_owned(),
12343 "abc1234def".to_owned(),
12344 "add retries".to_owned(),
12345 Config::default(),
12346 );
12347 exhausted.status = RunStatus::Blocked;
12348 exhausted.config.graph.review_rounds = 1;
12349 exhausted.reviews = vec![review_round(1)];
12350
12351 assert_eq!(
12352 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12353 None,
12354 "an exhausted `Blocked` run must not be offered as resumable"
12355 );
12356
12357 let mut has_budget_left = RunState::new(
12360 PathBuf::from("/repo"),
12361 "main".to_owned(),
12362 "abc1234def".to_owned(),
12363 "add retries".to_owned(),
12364 Config::default(),
12365 );
12366 has_budget_left.status = RunStatus::Blocked;
12367 has_budget_left.config.graph.review_rounds = 3;
12368 has_budget_left.reviews = vec![review_round(1)];
12369
12370 assert_eq!(
12371 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12372 Ok(has_budget_left.clone())
12373 }),
12374 Some(has_budget_left.id.clone())
12375 );
12376 }
12377
12378 #[test]
12379 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12380 let mut run = RunState::new(
12381 PathBuf::from("/repo"),
12382 "main".to_owned(),
12383 "abc1234def".to_owned(),
12384 "add retries".to_owned(),
12385 Config::default(),
12386 );
12387 run.status = RunStatus::Blocked;
12388 run.config.graph.review_rounds = 1;
12389 run.reviews = vec![review_round(1)];
12390 run.pr_publication_pending = true;
12391 assert_eq!(
12392 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12393 Some(run.id.clone()),
12394 "a spent review budget must not turn a failed publication into a re-competition"
12395 );
12396 }
12397
12398 #[test]
12399 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12400 let mut task = Task::new(
12401 "recover work".into(),
12402 "recover work".into(),
12403 PathBuf::from("/repo"),
12404 crate::queue::Source::Human,
12405 );
12406 let mut history = std::collections::BTreeMap::new();
12407 for index in 0..8 {
12408 let mut run = run_state(RunStatus::Blocked);
12409 run.id = format!("20260101-000000-{index:04}");
12410 run.base_commit = format!("upstream-{index}");
12411 if index > 0 {
12413 run.candidates.clear();
12414 }
12415 task.runs.extend([run.id.clone(), run.id.clone()]);
12416 history.insert(run.id.clone(), run);
12417 task.requeue();
12418 }
12419 let check = |task: &Task, starter: &Starter, limit| {
12420 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12421 };
12422 assert!(
12423 check(&task, &Starter::Start, 8)
12424 .unwrap()
12425 .contains("8 unretired")
12426 );
12427 assert!(check(&task, &Starter::Start, 9).is_none());
12428 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12429 task.release_operator("owner", None);
12430 assert_eq!(task.attempts, 0);
12431 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12432 assert!(check(&restored, &Starter::Start, 8).is_some());
12433 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12434 assert!(check(&restored, &Starter::Start, 0).is_none());
12435 }
12436
12437 #[test]
12438 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12439 let mut task = Task::new(
12440 "recover work".into(),
12441 "recover work".into(),
12442 PathBuf::from("/repo"),
12443 crate::queue::Source::Human,
12444 );
12445 let mut run = run_state(RunStatus::Superseded);
12446 run.candidates.clear();
12447 task.runs.push(run.id.clone());
12448 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12449 run.retired_to = Some("authority".into());
12450 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12451 run.retired_to = None;
12452 run.released_to = Some("authority".into());
12453 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12454 assert!(
12455 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12456 .unwrap()
12457 .contains("Cannot verify")
12458 );
12459 assert!(
12461 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12462 panic!("resume must not load historical attempts")
12463 })
12464 .is_none()
12465 );
12466 }
12467
12468 #[test]
12469 fn retired_resume_requires_a_valid_same_repository_authority() {
12470 let mut source = run_state(RunStatus::Blocked);
12471 let mut empty = run_state(RunStatus::Blocked);
12472 empty.retired_to = Some(source.id.clone());
12473 let runs = vec![source.id.clone(), empty.id.clone()];
12474 let resolve = |source: &RunState, empty: &RunState| {
12475 unfinished_run_with(&runs, "fixture", |id| {
12476 if id == source.id {
12477 Ok(source.clone())
12478 } else if id == empty.id {
12479 Ok(empty.clone())
12480 } else {
12481 bail!("unreadable authority")
12482 }
12483 })
12484 };
12485 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12486 assert_eq!(
12487 choose_starter(None, false, resolve(&source, &empty).as_deref()),
12488 Starter::Resume(source.id.clone())
12489 );
12490 source.retired_to = Some(empty.id.clone());
12491 assert!(
12492 resolve(&source, &empty).is_none(),
12493 "cycles do not revive obsolete runs"
12494 );
12495 source.retired_to = None;
12496 source.repo = PathBuf::from("/another-repository");
12497 assert!(resolve(&source, &empty).is_none());
12498 source.repo = empty.repo.clone();
12499 source.released_to = Some("later".into());
12500 assert!(resolve(&source, &empty).is_none());
12501 empty.retired_to = Some("unlisted-run".into());
12502 assert!(resolve(&source, &empty).is_none());
12503 }
12504
12505 #[test]
12506 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12507 let mut older_stalled = RunState::new(
12515 PathBuf::from("/repo"),
12516 "main".to_owned(),
12517 "abc1234def".to_owned(),
12518 "add retries".to_owned(),
12519 Config::default(),
12520 );
12521 older_stalled.status = RunStatus::Stalled;
12522
12523 let mut newest_exhausted = RunState::new(
12524 PathBuf::from("/repo"),
12525 "main".to_owned(),
12526 "abc1234def".to_owned(),
12527 "add retries".to_owned(),
12528 Config::default(),
12529 );
12530 newest_exhausted.status = RunStatus::Blocked;
12531 newest_exhausted.config.graph.review_rounds = 1;
12532 newest_exhausted.reviews = vec![review_round(1)];
12533
12534 assert_eq!(
12535 unfinished_run_with(
12536 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12537 "t",
12538 |_| Ok(newest_exhausted.clone())
12539 ),
12540 None,
12541 "the newest run is exhausted, so nothing here is worth resuming - \
12542 least of all the older, already-superseded run"
12543 );
12544 }
12545
12546 #[test]
12547 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12548 assert_eq!(
12549 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12550 Err(anyhow::anyhow!("fixture is absent"))
12551 }),
12552 None
12553 );
12554 }
12555
12556 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12557 let mut q = ask::Question::new(
12558 run.to_owned(),
12559 "implement".to_owned(),
12560 "impl-A".to_owned(),
12561 "continue?".to_owned(),
12562 String::new(),
12563 vec!["resume で続行する".to_owned(), "other".to_owned()],
12564 );
12565 q.actions.insert("resume で続行する".to_owned(), action);
12566 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12567 .unwrap();
12568 q
12569 }
12570
12571 fn held_task_with(run: &str) -> Task {
12572 let mut t = task();
12573 t.runs = vec![run.to_owned()];
12574 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12575 t
12576 }
12577
12578 fn resume_action(run: &str) -> ask::ChoiceAction {
12579 ask::ChoiceAction::Resume { run: run.into() }
12580 }
12581
12582 #[test]
12583 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12584 for parked in [false, true] {
12585 let mut t = task();
12586 t.start("A".into());
12587 t.start("B".into());
12588 assert_eq!(t.runs, vec!["A", "B"]);
12589 t.start("A".into());
12590 let mut resumed = run_state(RunStatus::Blocked);
12591 resumed.id = "A".into();
12592 resumed.parked = parked;
12593 resumed.driver_exited = true;
12594 t.hold_machine(Some("resumed run stopped".into()));
12595 let q = action_question("A", resume_action("A"));
12596 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12597 assert_eq!(
12598 decide_action(&t, &q, &PHRASES_EN, |id| {
12599 assert_eq!(id, "A");
12600 Ok(resumed.clone())
12601 }),
12602 ActionDecision::Resume("A".into())
12603 );
12604 assert_eq!(
12605 action_standing(&t, &action_question("B", resume_action("B"))),
12606 ActionStanding::Stale
12607 );
12608 t.release_operator("cli", None);
12609 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12610 assert_eq!(id, "A");
12611 Ok(resumed.clone())
12612 });
12613 assert_eq!(
12614 choose_starter(None, false, unfinished.as_deref()),
12615 Starter::Resume("A".into())
12616 );
12617 assert_eq!(t.runs, vec!["B", "A"]);
12618 }
12619 }
12620
12621 #[test]
12622 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12623 let mut state = crate::land::tests::repair_state(true, true);
12624 state.status = RunStatus::Landing;
12625 state.parked = true;
12626 state.driver_exited = true;
12627 let mut q = ask::Question::new(
12628 state.id.clone(),
12629 land::APPROVAL_NODE.into(),
12630 "land".into(),
12631 "Merge?".into(),
12632 String::new(),
12633 vec![land::APPROVE.into(), land::HOLD.into()],
12634 );
12635 q.id = state.id.clone();
12636 state.land_approval = Some(crate::run::LandApproval {
12637 question: q.id.clone(),
12638 head: "current-head".into(),
12639 });
12640 assert!(land::upgrade_repair_choice(&mut q, &state));
12641 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12642 let mut task = held_task_with(&state.id);
12643 task.status = TaskStatus::Parked;
12644 assert_eq!(
12645 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12646 ActionDecision::Resume(state.id.clone())
12647 );
12648 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12649 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12650 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12651 assert_eq!(
12652 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12653 ActionDecision::Resume(state.id.clone()),
12654 "a repair answer newer than the manual hold resumes the existing owner"
12655 );
12656 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12657 for answered_at in [q.answered_at, None] {
12658 let mut older = q.clone();
12659 older.answered_at = answered_at;
12660 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12661 panic!("a later manual hold must prevent dispatch")
12662 });
12663 let ActionDecision::Refuse(reason) = refused else {
12664 panic!("expected an actionable refusal, got {refused:?}");
12665 };
12666 assert!(reason.contains("later operator decision"));
12667 assert!(reason.contains(&format!("magi task release {}", task.id)));
12668 }
12669 task.operator_decided_at = None;
12670 let mut superseded = state.clone();
12671 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12672 assert_eq!(
12673 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12674 ActionDecision::Stale
12675 );
12676 for case in 1..4 {
12677 let mut changed = state.clone();
12678 match case {
12679 1 => changed.status = RunStatus::Blocked,
12680 2 => changed.released_to = Some("new-owner".into()),
12681 _ => changed.land_approval.as_mut().unwrap().head.clear(),
12682 }
12683 assert!(matches!(
12684 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12685 ActionDecision::Refuse(_)
12686 ));
12687 }
12688 assert!(matches!(
12689 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12690 ActionDecision::Refuse(_)
12691 ));
12692 task.runs.push("replacement".into());
12693 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12694 assert_eq!(
12695 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12696 "old owner must not load"
12697 )),
12698 ActionDecision::Stale
12699 );
12700 }
12701
12702 #[test]
12703 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12704 let mut state = crate::land::tests::repair_state(true, true);
12705 state.status = RunStatus::Landing;
12706 state.parked = true;
12707 state.driver_exited = true;
12708 let mut q = ask::Question::new(
12709 state.id.clone(),
12710 land::APPROVAL_NODE.into(),
12711 "land".into(),
12712 "Merge?".into(),
12713 String::new(),
12714 vec![land::APPROVE.into(), land::HOLD.into()],
12715 );
12716 q.id = state.id.clone();
12717 state.land_approval = Some(crate::run::LandApproval {
12718 question: q.id.clone(),
12719 head: "current-head".into(),
12720 });
12721 state.save().unwrap();
12722 land::upgrade_repair_choice(&mut q, &state);
12723 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12724 Questions::open().put(&mut q).unwrap();
12725 let tmp = tempfile::tempdir().unwrap();
12726 let queue = Queue::at(tmp.path().join("queue"));
12727 let mut task = held_task_with(&state.id);
12728 task.status = TaskStatus::Parked;
12729 queue.put(&mut task).unwrap();
12730 let empty = Arc::new(tokio::sync::Semaphore::new(0));
12731 let free = Arc::new(tokio::sync::Semaphore::new(1));
12732 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12733 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12734 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12735 assert!(claim.permit.is_some());
12736 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12737 drop(claim);
12738 Questions::open()
12739 .update(&q.id, |q| {
12740 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12741 Ok(())
12742 })
12743 .unwrap();
12744 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12745 assert!(claim.permit.is_none());
12746 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12747 }
12748
12749 #[test]
12750 fn decide_action_resumes_only_the_latest_resumable_run() {
12751 let t = held_task_with("r1");
12752 let q = action_question("r1", resume_action("r1"));
12753 let load = |s: RunState| move |_: &str| Ok(s);
12754 assert_eq!(
12755 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12756 ActionDecision::Resume("r1".into())
12757 );
12758 let q_other = action_question("r1", resume_action("r0"));
12760 assert!(matches!(
12761 decide_action(
12762 &t,
12763 &q_other,
12764 &PHRASES_EN,
12765 load(run_state(RunStatus::Blocked))
12766 ),
12767 ActionDecision::Refuse(_)
12768 ));
12769 assert!(matches!(
12771 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12772 ActionDecision::Refuse(_)
12773 ));
12774 let mut released = run_state(RunStatus::Blocked);
12776 released.released_to = Some("elsewhere".into());
12777 assert!(matches!(
12778 decide_action(&t, &q, &PHRASES_EN, load(released)),
12779 ActionDecision::Refuse(_)
12780 ));
12781 assert!(matches!(
12783 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12784 ActionDecision::Refuse(_)
12785 ));
12786 }
12787
12788 #[test]
12789 fn decide_action_ignores_a_question_about_an_earlier_run() {
12790 let mut t = held_task_with("r1");
12791 t.runs.push("r2".to_owned());
12792 let never = |_: &str| -> Result<RunState> { bail!("not read") };
12793 assert_eq!(
12794 decide_action(
12795 &t,
12796 &action_question("r1", ask::ChoiceAction::Done),
12797 &PHRASES_EN,
12798 never
12799 ),
12800 ActionDecision::Stale
12801 );
12802 }
12803
12804 #[test]
12805 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12806 let mut t = held_task_with("r1");
12807 let never = |_: &str| -> Result<RunState> { bail!("not read") };
12808 assert_eq!(
12809 decide_action(
12810 &t,
12811 &action_question("r1", ask::ChoiceAction::Requeue),
12812 &PHRASES_EN,
12813 never
12814 ),
12815 ActionDecision::Requeue
12816 );
12817 let done_q = action_question("r1", ask::ChoiceAction::Done);
12818 assert_eq!(
12819 decide_action(&t, &done_q, &PHRASES_EN, never),
12820 ActionDecision::Done
12821 );
12822 t.mark_action_applied(&done_q.id);
12823 assert_eq!(
12824 decide_action(&t, &done_q, &PHRASES_EN, never),
12825 ActionDecision::Skip
12826 );
12827
12828 let mut plain = action_question("r1", ask::ChoiceAction::Done);
12830 plain.actions.clear();
12831 assert_eq!(
12832 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12833 ActionDecision::Skip
12834 );
12835 let mut running = held_task_with("r1");
12837 running.status = TaskStatus::Running;
12838 assert_eq!(
12839 decide_action(
12840 &running,
12841 &action_question("r1", ask::ChoiceAction::Done),
12842 &PHRASES_EN,
12843 never
12844 ),
12845 ActionDecision::Skip
12846 );
12847 }
12848
12849 #[test]
12850 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12851 crate::run::pin_test_home();
12852 for legacy in [false, true] {
12853 let dir = tempfile::tempdir().unwrap();
12854 let queue = Queue::at(dir.path().join("queue"));
12855 let questions = Questions::at(dir.path().join("questions"));
12856 let run = "20260101-000000-hold";
12857 let mut task = held_task_with(run);
12858 task.status = TaskStatus::Parked;
12859 let mut q = ask::Question::new(
12860 run.into(),
12861 land::APPROVAL_NODE.into(),
12862 "land".into(),
12863 "Repair?".into(),
12864 String::new(),
12865 vec![land::REPAIR.into()],
12866 );
12867 q.actions.insert(land::REPAIR.into(), resume_action(run));
12868 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12869 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12871 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12872 questions.put(&mut q).unwrap();
12873 task.hold_manual(Some("Keep this PR paused".into()));
12874 if legacy {
12875 task.hold_source = None;
12876 }
12877 queue.put(&mut task).unwrap();
12878
12879 apply_task_choice_actions(&queue, &questions, dir.path());
12880 let after = queue.get(&task.id).unwrap();
12881 assert!(after.operator_held());
12882 assert_eq!(after.hold_source, task.hold_source);
12883 assert_eq!(after.operator_decided_at, task.operator_decided_at);
12884 assert_eq!(after.runs, task.runs);
12885 assert_eq!(after.instruction, task.instruction);
12886 assert!(after.resume_override.is_none());
12887 assert!(after.action_applied(&q.id));
12888 let reason = after.hold_reason.as_deref().unwrap();
12889 assert!(reason.starts_with("Keep this PR paused"));
12890 assert!(reason.contains("later operator decision"));
12891 assert!(reason.contains(&format!("magi task release {}", task.id)));
12892
12893 for recovery in [
12894 crate::conduct::Recovery::Review,
12895 crate::conduct::Recovery::Requeue,
12896 ] {
12897 crate::conduct::apply(
12898 &queue,
12899 &questions,
12900 &crate::conduct::Verdict {
12901 decisions: vec![crate::conduct::Decision {
12902 id: task.id.clone(),
12903 recovery: Some(recovery),
12904 ..Default::default()
12905 }],
12906 },
12907 )
12908 .unwrap();
12909 }
12910 apply_task_choice_actions(&queue, &questions, dir.path());
12913 let still_held = queue.get(&task.id).unwrap();
12914 assert!(still_held.operator_held());
12915 assert_eq!(still_held.hold_reason, after.hold_reason);
12916 assert_eq!(still_held.runs, task.runs);
12917 assert!(still_held.review_branch.is_none());
12918 assert!(!still_held.fresh_start);
12919 assert!(queue.next_runnable().is_none());
12920 }
12921 }
12922
12923 #[test]
12924 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12925 for held in [false, true] {
12926 for retry in [false, true] {
12927 let dir = tempfile::tempdir().unwrap();
12928 let queue = Queue::at(dir.path().join("queue"));
12929 let questions = Questions::at(dir.path().join("questions"));
12930 let home = dir.path().join("home");
12931 let mut t = task();
12932 if held {
12933 t.hold_machine(Some("driver state unknown".into()));
12934 }
12935 queue.put(&mut t).unwrap();
12936 let verdict = serde_json::from_value(serde_json::json!({
12937 "decisions": [{
12938 "id": t.id,
12939 "question": "Driver state unknown; retry the checks or hold?",
12940 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12941 "actions": {
12942 "daemon: recheck and retry": {"do": "requeue"},
12943 "daemon: hold the task": {"do": "hold"}
12944 }
12945 }]
12946 }))
12947 .unwrap();
12948 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12949 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12950 let mut q = questions.list().pop().unwrap();
12951 let choice = if retry {
12952 "daemon: recheck and retry"
12953 } else {
12954 "daemon: hold the task"
12955 };
12956 assert_eq!(q.actions.len(), 2);
12957 q.answer(ask::Answer::Choice(choice.into())).unwrap();
12958 questions.put(&mut q).unwrap();
12959
12960 questions.beat(&q.id, ask::WaiterKind::Deputy);
12962 for _ in 0..2 {
12963 resolve_blockers(&queue, &questions);
12964 apply_task_choice_actions(&queue, &questions, &home);
12965 let waiting = queue.get(&t.id).unwrap();
12966 assert_eq!(waiting.status, TaskStatus::Blocked);
12967 assert_eq!(waiting.blocked_by, [q.id.clone()]);
12968 assert!(waiting.answers.is_empty());
12969 assert!(!waiting.action_applied(&q.id));
12970 assert!(runnable(&queue).is_empty());
12971 let free = Arc::new(tokio::sync::Semaphore::new(1));
12972 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12973 }
12974 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12975
12976 resolve_blockers(&queue, &questions);
12978 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12979 apply_task_choice_actions(&queue, &questions, &home);
12980 let after = queue.get(&t.id).unwrap();
12981 assert_eq!(
12982 after.status,
12983 if retry {
12984 TaskStatus::Queued
12985 } else {
12986 TaskStatus::Held
12987 }
12988 );
12989 assert!(after.action_applied(&q.id));
12990 assert_eq!(after.operator_held(), !retry);
12991 assert_eq!(after.answers.len(), 1);
12992
12993 let mut changed = after;
12995 if retry {
12996 changed.hold_manual(Some("later hold".into()));
12997 } else {
12998 changed.release_operator("test", None);
12999 }
13000 let expected = changed.status;
13001 queue.put(&mut changed).unwrap();
13002 apply_task_choice_actions(&queue, &questions, &home);
13003 assert_eq!(queue.get(&t.id).unwrap().status, expected);
13004 }
13005 }
13006 }
13007
13008 #[test]
13009 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13010 let dir = tempfile::tempdir().unwrap();
13011 let queue = Queue::at(dir.path().join("queue"));
13012 let questions = Questions::at(dir.path().join("questions"));
13013 let home = dir.path().join("home");
13014 let mut state = run_state(RunStatus::Blocked);
13015 state.id = "20260101-000000-act1".to_owned();
13016 state.save_under(&home).unwrap();
13017
13018 let mut t = held_task_with(&state.id);
13019 queue.put(&mut t).unwrap();
13020 let mut q = action_question(&state.id, resume_action(&state.id));
13021 questions.put(&mut q).unwrap();
13022
13023 apply_task_choice_actions(&queue, &questions, &home);
13024 let after = queue.get(&t.id).unwrap();
13025 assert_eq!(after.status, TaskStatus::Queued);
13026 assert!(!after.fresh_start);
13027 assert!(after.action_applied(&q.id));
13028 let pin = after.resume_override.clone().unwrap();
13029 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13030 assert!(pin.forced);
13031
13032 let mut again = queue.get(&t.id).unwrap();
13034 again.hold_machine(Some("later".into()));
13035 queue.put(&mut again).unwrap();
13036 apply_task_choice_actions(&queue, &questions, &home);
13037 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13038 }
13039
13040 #[test]
13041 fn a_delivered_answer_is_still_acted_on_exactly_once() {
13042 let dir = tempfile::tempdir().unwrap();
13043 let queue = Queue::at(dir.path().join("queue"));
13044 let questions = Questions::at(dir.path().join("questions"));
13045 let home = dir.path().join("home");
13046 let mut state = run_state(RunStatus::Blocked);
13047 state.id = "20260101-000000-act2".to_owned();
13048 state.save_under(&home).unwrap();
13049
13050 let mut t = held_task_with(&state.id);
13051 queue.put(&mut t).unwrap();
13052 let mut q = action_question(&state.id, resume_action(&state.id));
13053 q.answer_delivered = true;
13054 questions.put(&mut q).unwrap();
13055
13056 apply_task_choice_actions(&queue, &questions, &home);
13059 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13060 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13061
13062 let mut again = queue.get(&t.id).unwrap();
13064 again.hold_machine(Some("later".into()));
13065 queue.put(&mut again).unwrap();
13066 apply_task_choice_actions(&queue, &questions, &home);
13067 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13068 }
13069
13070 #[test]
13071 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13072 let dir = tempfile::tempdir().unwrap();
13073 let queue = Queue::at(dir.path().join("queue"));
13074 let questions = Questions::at(dir.path().join("questions"));
13075 let home = dir.path().join("home");
13076 let mut state = run_state(RunStatus::Blocked);
13077 state.id = "20260101-000000-act3".to_owned();
13078 state.save_under(&home).unwrap();
13079 let mut t = held_task_with(&state.id);
13080 queue.put(&mut t).unwrap();
13081 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13082 questions.put(&mut q).unwrap();
13083
13084 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13085 apply_task_choice_actions(&queue, &questions, &home);
13086 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13087
13088 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13089 apply_task_choice_actions(&queue, &questions, &home);
13090 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13091 }
13092
13093 #[test]
13094 fn action_standing_tells_the_reasons_apart() {
13095 let mut t = held_task_with("r1");
13096 let q = action_question("r1", ask::ChoiceAction::Requeue);
13097 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13098 let mut plain = q.clone();
13099 plain.actions.clear();
13100 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13101
13102 t.mark_action_applied(&q.id);
13104 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13105
13106 let mut t = held_task_with("r1");
13108 t.start("r2".to_owned());
13109 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13110 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13112 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13113 t.status = TaskStatus::Blocked;
13114 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13115
13116 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13118 c.node = crate::conduct::NODE.to_owned();
13119 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13120 assert!(!ActionStanding::Busy.daemon_owns());
13121 }
13122
13123 #[test]
13124 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13125 let dir = tempfile::tempdir().unwrap();
13126 let queue = Queue::at(dir.path().join("queue"));
13127 let questions = Questions::at(dir.path().join("questions"));
13128 let home = dir.path().join("home");
13129 let mut state = run_state(RunStatus::Blocked);
13130 state.id = "20260101-000000-act4".to_owned();
13131 state.save_under(&home).unwrap();
13132 let mut t = held_task_with(&state.id);
13133 t.status = TaskStatus::Running;
13134 queue.put(&mut t).unwrap();
13135 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13136 q.cwd = Some(dir.path().display().to_string());
13137 questions.put(&mut q).unwrap();
13138
13139 let running = queue.get(&t.id).unwrap();
13142 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13143 assert!(matches!(
13144 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13145 crate::waiter::Action::Deliver(_)
13146 ));
13147 apply_task_choice_actions(&queue, &questions, &home);
13149 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13150 let mut back = queue.get(&t.id).unwrap();
13151 back.hold_machine(Some("later".into()));
13152 queue.put(&mut back).unwrap();
13153 apply_task_choice_actions(&queue, &questions, &home);
13154 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13155 let mut again = queue.get(&t.id).unwrap();
13156 again.hold_machine(Some("again".into()));
13157 queue.put(&mut again).unwrap();
13158 apply_task_choice_actions(&queue, &questions, &home);
13159 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13160 }
13161}